1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * Network block device - make block devices work over TCP
5 * Note that you can not swap over this thing, yet. Seems to work but
6 * deadlocks sometimes - you can not swap over TCP in general.
8 * Copyright 1997-2000, 2008 Pavel Machek <pavel@ucw.cz>
9 * Parts copyright 2001 Steven Whitehouse <steve@chygwyn.com>
11 * (part of code stolen from loop.c)
14 #define pr_fmt(fmt) "nbd: " fmt
16 #include <linux/major.h>
18 #include <linux/blkdev.h>
19 #include <linux/module.h>
20 #include <linux/init.h>
21 #include <linux/sched.h>
22 #include <linux/sched/mm.h>
24 #include <linux/bio.h>
25 #include <linux/stat.h>
26 #include <linux/errno.h>
27 #include <linux/file.h>
28 #include <linux/ioctl.h>
29 #include <linux/mutex.h>
30 #include <linux/compiler.h>
31 #include <linux/completion.h>
32 #include <linux/err.h>
33 #include <linux/kernel.h>
34 #include <linux/slab.h>
36 #include <linux/net.h>
37 #include <linux/kthread.h>
38 #include <linux/types.h>
39 #include <linux/debugfs.h>
40 #include <linux/blk-mq.h>
42 #include <linux/uaccess.h>
43 #include <asm/types.h>
45 #include <linux/nbd.h>
46 #include <linux/nbd-netlink.h>
47 #include <net/genetlink.h>
49 #define CREATE_TRACE_POINTS
50 #include <trace/events/nbd.h>
52 static DEFINE_IDR(nbd_index_idr);
53 static DEFINE_MUTEX(nbd_index_mutex);
54 static struct workqueue_struct *nbd_del_wq;
55 static int nbd_total_devices = 0;
60 struct request *pending;
67 struct recv_thread_args {
68 struct work_struct work;
69 struct nbd_device *nbd;
70 struct nbd_sock *nsock;
74 struct link_dead_args {
75 struct work_struct work;
79 #define NBD_RT_TIMEDOUT 0
80 #define NBD_RT_DISCONNECT_REQUESTED 1
81 #define NBD_RT_DISCONNECTED 2
82 #define NBD_RT_HAS_PID_FILE 3
83 #define NBD_RT_HAS_CONFIG_REF 4
84 #define NBD_RT_BOUND 5
85 #define NBD_RT_DISCONNECT_ON_CLOSE 6
86 #define NBD_RT_HAS_BACKEND_FILE 7
88 #define NBD_DESTROY_ON_DISCONNECT 0
89 #define NBD_DISCONNECT_REQUESTED 1
93 unsigned long runtime_flags;
94 u64 dead_conn_timeout;
96 struct nbd_sock **socks;
98 atomic_t live_connections;
99 wait_queue_head_t conn_wait;
101 atomic_t recv_threads;
102 wait_queue_head_t recv_wq;
103 unsigned int blksize_bits;
105 #if IS_ENABLED(CONFIG_DEBUG_FS)
106 struct dentry *dbg_dir;
110 static inline unsigned int nbd_blksize(struct nbd_config *config)
112 return 1u << config->blksize_bits;
116 struct blk_mq_tag_set tag_set;
119 refcount_t config_refs;
121 struct nbd_config *config;
122 struct mutex config_lock;
123 struct gendisk *disk;
124 struct workqueue_struct *recv_workq;
125 struct work_struct remove_work;
127 struct list_head list;
128 struct task_struct *task_setup;
131 pid_t pid; /* pid of nbd-client, if attached */
136 #define NBD_CMD_REQUEUED 1
138 * This flag will be set if nbd_queue_rq() succeed, and will be checked and
139 * cleared in completion. Both setting and clearing of the flag are protected
142 #define NBD_CMD_INFLIGHT 2
145 struct nbd_device *nbd;
155 #if IS_ENABLED(CONFIG_DEBUG_FS)
156 static struct dentry *nbd_dbg_dir;
159 #define nbd_name(nbd) ((nbd)->disk->disk_name)
161 #define NBD_DEF_BLKSIZE_BITS 10
163 static unsigned int nbds_max = 16;
164 static int max_part = 16;
165 static int part_shift;
167 static int nbd_dev_dbg_init(struct nbd_device *nbd);
168 static void nbd_dev_dbg_close(struct nbd_device *nbd);
169 static void nbd_config_put(struct nbd_device *nbd);
170 static void nbd_connect_reply(struct genl_info *info, int index);
171 static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info);
172 static void nbd_dead_link_work(struct work_struct *work);
173 static void nbd_disconnect_and_put(struct nbd_device *nbd);
175 static inline struct device *nbd_to_dev(struct nbd_device *nbd)
177 return disk_to_dev(nbd->disk);
180 static void nbd_requeue_cmd(struct nbd_cmd *cmd)
182 struct request *req = blk_mq_rq_from_pdu(cmd);
184 if (!test_and_set_bit(NBD_CMD_REQUEUED, &cmd->flags))
185 blk_mq_requeue_request(req, true);
188 #define NBD_COOKIE_BITS 32
190 static u64 nbd_cmd_handle(struct nbd_cmd *cmd)
192 struct request *req = blk_mq_rq_from_pdu(cmd);
193 u32 tag = blk_mq_unique_tag(req);
194 u64 cookie = cmd->cmd_cookie;
196 return (cookie << NBD_COOKIE_BITS) | tag;
199 static u32 nbd_handle_to_tag(u64 handle)
204 static u32 nbd_handle_to_cookie(u64 handle)
206 return (u32)(handle >> NBD_COOKIE_BITS);
209 static const char *nbdcmd_to_ascii(int cmd)
212 case NBD_CMD_READ: return "read";
213 case NBD_CMD_WRITE: return "write";
214 case NBD_CMD_DISC: return "disconnect";
215 case NBD_CMD_FLUSH: return "flush";
216 case NBD_CMD_TRIM: return "trim/discard";
221 static ssize_t pid_show(struct device *dev,
222 struct device_attribute *attr, char *buf)
224 struct gendisk *disk = dev_to_disk(dev);
225 struct nbd_device *nbd = (struct nbd_device *)disk->private_data;
227 return sprintf(buf, "%d\n", nbd->pid);
230 static const struct device_attribute pid_attr = {
231 .attr = { .name = "pid", .mode = 0444},
235 static ssize_t backend_show(struct device *dev,
236 struct device_attribute *attr, char *buf)
238 struct gendisk *disk = dev_to_disk(dev);
239 struct nbd_device *nbd = (struct nbd_device *)disk->private_data;
241 return sprintf(buf, "%s\n", nbd->backend ?: "");
244 static const struct device_attribute backend_attr = {
245 .attr = { .name = "backend", .mode = 0444},
246 .show = backend_show,
249 static void nbd_dev_remove(struct nbd_device *nbd)
251 struct gendisk *disk = nbd->disk;
254 blk_mq_free_tag_set(&nbd->tag_set);
257 * Remove from idr after del_gendisk() completes, so if the same ID is
258 * reused, the following add_disk() will succeed.
260 mutex_lock(&nbd_index_mutex);
261 idr_remove(&nbd_index_idr, nbd->index);
262 mutex_unlock(&nbd_index_mutex);
263 destroy_workqueue(nbd->recv_workq);
267 static void nbd_dev_remove_work(struct work_struct *work)
269 nbd_dev_remove(container_of(work, struct nbd_device, remove_work));
272 static void nbd_put(struct nbd_device *nbd)
274 if (!refcount_dec_and_test(&nbd->refs))
277 /* Call del_gendisk() asynchrounously to prevent deadlock */
278 if (test_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags))
279 queue_work(nbd_del_wq, &nbd->remove_work);
284 static int nbd_disconnected(struct nbd_config *config)
286 return test_bit(NBD_RT_DISCONNECTED, &config->runtime_flags) ||
287 test_bit(NBD_RT_DISCONNECT_REQUESTED, &config->runtime_flags);
290 static void nbd_mark_nsock_dead(struct nbd_device *nbd, struct nbd_sock *nsock,
293 if (!nsock->dead && notify && !nbd_disconnected(nbd->config)) {
294 struct link_dead_args *args;
295 args = kmalloc(sizeof(struct link_dead_args), GFP_NOIO);
297 INIT_WORK(&args->work, nbd_dead_link_work);
298 args->index = nbd->index;
299 queue_work(system_wq, &args->work);
303 kernel_sock_shutdown(nsock->sock, SHUT_RDWR);
304 if (atomic_dec_return(&nbd->config->live_connections) == 0) {
305 if (test_and_clear_bit(NBD_RT_DISCONNECT_REQUESTED,
306 &nbd->config->runtime_flags)) {
307 set_bit(NBD_RT_DISCONNECTED,
308 &nbd->config->runtime_flags);
309 dev_info(nbd_to_dev(nbd),
310 "Disconnected due to user request.\n");
315 nsock->pending = NULL;
319 static int nbd_set_size(struct nbd_device *nbd, loff_t bytesize,
323 blksize = 1u << NBD_DEF_BLKSIZE_BITS;
325 if (blk_validate_block_size(blksize))
331 nbd->config->bytesize = bytesize;
332 nbd->config->blksize_bits = __ffs(blksize);
337 if (nbd->config->flags & NBD_FLAG_SEND_TRIM) {
338 nbd->disk->queue->limits.discard_granularity = blksize;
339 blk_queue_max_discard_sectors(nbd->disk->queue, UINT_MAX);
341 blk_queue_logical_block_size(nbd->disk->queue, blksize);
342 blk_queue_physical_block_size(nbd->disk->queue, blksize);
345 set_bit(GD_NEED_PART_SCAN, &nbd->disk->state);
346 if (!set_capacity_and_notify(nbd->disk, bytesize >> 9))
347 kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
351 static void nbd_complete_rq(struct request *req)
353 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
355 dev_dbg(nbd_to_dev(cmd->nbd), "request %p: %s\n", req,
356 cmd->status ? "failed" : "done");
358 blk_mq_end_request(req, cmd->status);
362 * Forcibly shutdown the socket causing all listeners to error
364 static void sock_shutdown(struct nbd_device *nbd)
366 struct nbd_config *config = nbd->config;
369 if (config->num_connections == 0)
371 if (test_and_set_bit(NBD_RT_DISCONNECTED, &config->runtime_flags))
374 for (i = 0; i < config->num_connections; i++) {
375 struct nbd_sock *nsock = config->socks[i];
376 mutex_lock(&nsock->tx_lock);
377 nbd_mark_nsock_dead(nbd, nsock, 0);
378 mutex_unlock(&nsock->tx_lock);
380 dev_warn(disk_to_dev(nbd->disk), "shutting down sockets\n");
383 static u32 req_to_nbd_cmd_type(struct request *req)
385 switch (req_op(req)) {
389 return NBD_CMD_FLUSH;
391 return NBD_CMD_WRITE;
399 static struct nbd_config *nbd_get_config_unlocked(struct nbd_device *nbd)
401 if (refcount_inc_not_zero(&nbd->config_refs)) {
403 * Add smp_mb__after_atomic to ensure that reading nbd->config_refs
404 * and reading nbd->config is ordered. The pair is the barrier in
405 * nbd_alloc_and_init_config(), avoid nbd->config_refs is set
406 * before nbd->config.
408 smp_mb__after_atomic();
415 static enum blk_eh_timer_return nbd_xmit_timeout(struct request *req)
417 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
418 struct nbd_device *nbd = cmd->nbd;
419 struct nbd_config *config;
421 if (!mutex_trylock(&cmd->lock))
422 return BLK_EH_RESET_TIMER;
424 if (!test_bit(NBD_CMD_INFLIGHT, &cmd->flags)) {
425 mutex_unlock(&cmd->lock);
429 config = nbd_get_config_unlocked(nbd);
431 cmd->status = BLK_STS_TIMEOUT;
432 __clear_bit(NBD_CMD_INFLIGHT, &cmd->flags);
433 mutex_unlock(&cmd->lock);
437 if (config->num_connections > 1 ||
438 (config->num_connections == 1 && nbd->tag_set.timeout)) {
439 dev_err_ratelimited(nbd_to_dev(nbd),
440 "Connection timed out, retrying (%d/%d alive)\n",
441 atomic_read(&config->live_connections),
442 config->num_connections);
444 * Hooray we have more connections, requeue this IO, the submit
445 * path will put it on a real connection. Or if only one
446 * connection is configured, the submit path will wait util
447 * a new connection is reconfigured or util dead timeout.
450 if (cmd->index < config->num_connections) {
451 struct nbd_sock *nsock =
452 config->socks[cmd->index];
453 mutex_lock(&nsock->tx_lock);
454 /* We can have multiple outstanding requests, so
455 * we don't want to mark the nsock dead if we've
456 * already reconnected with a new socket, so
457 * only mark it dead if its the same socket we
460 if (cmd->cookie == nsock->cookie)
461 nbd_mark_nsock_dead(nbd, nsock, 1);
462 mutex_unlock(&nsock->tx_lock);
464 mutex_unlock(&cmd->lock);
465 nbd_requeue_cmd(cmd);
471 if (!nbd->tag_set.timeout) {
473 * Userspace sets timeout=0 to disable socket disconnection,
474 * so just warn and reset the timer.
476 struct nbd_sock *nsock = config->socks[cmd->index];
478 dev_info(nbd_to_dev(nbd), "Possible stuck request %p: control (%s@%llu,%uB). Runtime %u seconds\n",
479 req, nbdcmd_to_ascii(req_to_nbd_cmd_type(req)),
480 (unsigned long long)blk_rq_pos(req) << 9,
481 blk_rq_bytes(req), (req->timeout / HZ) * cmd->retries);
483 mutex_lock(&nsock->tx_lock);
484 if (cmd->cookie != nsock->cookie) {
485 nbd_requeue_cmd(cmd);
486 mutex_unlock(&nsock->tx_lock);
487 mutex_unlock(&cmd->lock);
491 mutex_unlock(&nsock->tx_lock);
492 mutex_unlock(&cmd->lock);
494 return BLK_EH_RESET_TIMER;
497 dev_err_ratelimited(nbd_to_dev(nbd), "Connection timed out\n");
498 set_bit(NBD_RT_TIMEDOUT, &config->runtime_flags);
499 cmd->status = BLK_STS_IOERR;
500 __clear_bit(NBD_CMD_INFLIGHT, &cmd->flags);
501 mutex_unlock(&cmd->lock);
505 blk_mq_complete_request(req);
509 static int __sock_xmit(struct nbd_device *nbd, struct socket *sock, int send,
510 struct iov_iter *iter, int msg_flags, int *sent)
514 unsigned int noreclaim_flag;
516 if (unlikely(!sock)) {
517 dev_err_ratelimited(disk_to_dev(nbd->disk),
518 "Attempted %s on closed socket in sock_xmit\n",
519 (send ? "send" : "recv"));
523 msg.msg_iter = *iter;
525 noreclaim_flag = memalloc_noreclaim_save();
527 sock->sk->sk_allocation = GFP_NOIO | __GFP_MEMALLOC;
528 sock->sk->sk_use_task_frag = false;
531 msg.msg_control = NULL;
532 msg.msg_controllen = 0;
533 msg.msg_flags = msg_flags | MSG_NOSIGNAL;
536 result = sock_sendmsg(sock, &msg);
538 result = sock_recvmsg(sock, &msg, msg.msg_flags);
542 result = -EPIPE; /* short read */
547 } while (msg_data_left(&msg));
549 memalloc_noreclaim_restore(noreclaim_flag);
555 * Send or receive packet. Return a positive value on success and
556 * negtive value on failure, and never return 0.
558 static int sock_xmit(struct nbd_device *nbd, int index, int send,
559 struct iov_iter *iter, int msg_flags, int *sent)
561 struct nbd_config *config = nbd->config;
562 struct socket *sock = config->socks[index]->sock;
564 return __sock_xmit(nbd, sock, send, iter, msg_flags, sent);
568 * Different settings for sk->sk_sndtimeo can result in different return values
569 * if there is a signal pending when we enter sendmsg, because reasons?
571 static inline int was_interrupted(int result)
573 return result == -ERESTARTSYS || result == -EINTR;
576 /* always call with the tx_lock held */
577 static int nbd_send_cmd(struct nbd_device *nbd, struct nbd_cmd *cmd, int index)
579 struct request *req = blk_mq_rq_from_pdu(cmd);
580 struct nbd_config *config = nbd->config;
581 struct nbd_sock *nsock = config->socks[index];
583 struct nbd_request request = {.magic = htonl(NBD_REQUEST_MAGIC)};
584 struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
585 struct iov_iter from;
586 unsigned long size = blk_rq_bytes(req);
590 u32 nbd_cmd_flags = 0;
591 int sent = nsock->sent, skip = 0;
593 iov_iter_kvec(&from, ITER_SOURCE, &iov, 1, sizeof(request));
595 type = req_to_nbd_cmd_type(req);
599 if (rq_data_dir(req) == WRITE &&
600 (config->flags & NBD_FLAG_READ_ONLY)) {
601 dev_err_ratelimited(disk_to_dev(nbd->disk),
602 "Write on read-only\n");
606 if (req->cmd_flags & REQ_FUA)
607 nbd_cmd_flags |= NBD_CMD_FLAG_FUA;
609 /* We did a partial send previously, and we at least sent the whole
610 * request struct, so just go and send the rest of the pages in the
614 if (sent >= sizeof(request)) {
615 skip = sent - sizeof(request);
617 /* initialize handle for tracing purposes */
618 handle = nbd_cmd_handle(cmd);
622 iov_iter_advance(&from, sent);
627 cmd->cookie = nsock->cookie;
629 request.type = htonl(type | nbd_cmd_flags);
630 if (type != NBD_CMD_FLUSH) {
631 request.from = cpu_to_be64((u64)blk_rq_pos(req) << 9);
632 request.len = htonl(size);
634 handle = nbd_cmd_handle(cmd);
635 request.cookie = cpu_to_be64(handle);
637 trace_nbd_send_request(&request, nbd->index, blk_mq_rq_from_pdu(cmd));
639 dev_dbg(nbd_to_dev(nbd), "request %p: sending control (%s@%llu,%uB)\n",
640 req, nbdcmd_to_ascii(type),
641 (unsigned long long)blk_rq_pos(req) << 9, blk_rq_bytes(req));
642 result = sock_xmit(nbd, index, 1, &from,
643 (type == NBD_CMD_WRITE) ? MSG_MORE : 0, &sent);
644 trace_nbd_header_sent(req, handle);
646 if (was_interrupted(result)) {
647 /* If we haven't sent anything we can just return BUSY,
648 * however if we have sent something we need to make
649 * sure we only allow this req to be sent until we are
653 nsock->pending = req;
656 set_bit(NBD_CMD_REQUEUED, &cmd->flags);
657 return BLK_STS_RESOURCE;
659 dev_err_ratelimited(disk_to_dev(nbd->disk),
660 "Send control failed (result %d)\n", result);
664 if (type != NBD_CMD_WRITE)
669 struct bio *next = bio->bi_next;
670 struct bvec_iter iter;
673 bio_for_each_segment(bvec, bio, iter) {
674 bool is_last = !next && bio_iter_last(bvec, iter);
675 int flags = is_last ? 0 : MSG_MORE;
677 dev_dbg(nbd_to_dev(nbd), "request %p: sending %d bytes data\n",
679 iov_iter_bvec(&from, ITER_SOURCE, &bvec, 1, bvec.bv_len);
681 if (skip >= iov_iter_count(&from)) {
682 skip -= iov_iter_count(&from);
685 iov_iter_advance(&from, skip);
688 result = sock_xmit(nbd, index, 1, &from, flags, &sent);
690 if (was_interrupted(result)) {
691 /* We've already sent the header, we
692 * have no choice but to set pending and
695 nsock->pending = req;
697 set_bit(NBD_CMD_REQUEUED, &cmd->flags);
698 return BLK_STS_RESOURCE;
700 dev_err(disk_to_dev(nbd->disk),
701 "Send data failed (result %d)\n",
706 * The completion might already have come in,
707 * so break for the last one instead of letting
708 * the iterator do it. This prevents use-after-free
717 trace_nbd_payload_sent(req, handle);
718 nsock->pending = NULL;
723 static int nbd_read_reply(struct nbd_device *nbd, struct socket *sock,
724 struct nbd_reply *reply)
726 struct kvec iov = {.iov_base = reply, .iov_len = sizeof(*reply)};
731 iov_iter_kvec(&to, ITER_DEST, &iov, 1, sizeof(*reply));
732 result = __sock_xmit(nbd, sock, 0, &to, MSG_WAITALL, NULL);
734 if (!nbd_disconnected(nbd->config))
735 dev_err(disk_to_dev(nbd->disk),
736 "Receive control failed (result %d)\n", result);
740 if (ntohl(reply->magic) != NBD_REPLY_MAGIC) {
741 dev_err(disk_to_dev(nbd->disk), "Wrong magic (0x%lx)\n",
742 (unsigned long)ntohl(reply->magic));
749 /* NULL returned = something went wrong, inform userspace */
750 static struct nbd_cmd *nbd_handle_reply(struct nbd_device *nbd, int index,
751 struct nbd_reply *reply)
755 struct request *req = NULL;
761 handle = be64_to_cpu(reply->cookie);
762 tag = nbd_handle_to_tag(handle);
763 hwq = blk_mq_unique_tag_to_hwq(tag);
764 if (hwq < nbd->tag_set.nr_hw_queues)
765 req = blk_mq_tag_to_rq(nbd->tag_set.tags[hwq],
766 blk_mq_unique_tag_to_tag(tag));
767 if (!req || !blk_mq_request_started(req)) {
768 dev_err(disk_to_dev(nbd->disk), "Unexpected reply (%d) %p\n",
770 return ERR_PTR(-ENOENT);
772 trace_nbd_header_received(req, handle);
773 cmd = blk_mq_rq_to_pdu(req);
775 mutex_lock(&cmd->lock);
776 if (!test_bit(NBD_CMD_INFLIGHT, &cmd->flags)) {
777 dev_err(disk_to_dev(nbd->disk), "Suspicious reply %d (status %u flags %lu)",
778 tag, cmd->status, cmd->flags);
782 if (cmd->index != index) {
783 dev_err(disk_to_dev(nbd->disk), "Unexpected reply %d from different sock %d (expected %d)",
784 tag, index, cmd->index);
788 if (cmd->cmd_cookie != nbd_handle_to_cookie(handle)) {
789 dev_err(disk_to_dev(nbd->disk), "Double reply on req %p, cmd_cookie %u, handle cookie %u\n",
790 req, cmd->cmd_cookie, nbd_handle_to_cookie(handle));
794 if (cmd->status != BLK_STS_OK) {
795 dev_err(disk_to_dev(nbd->disk), "Command already handled %p\n",
800 if (test_bit(NBD_CMD_REQUEUED, &cmd->flags)) {
801 dev_err(disk_to_dev(nbd->disk), "Raced with timeout on req %p\n",
806 if (ntohl(reply->error)) {
807 dev_err(disk_to_dev(nbd->disk), "Other side returned error (%d)\n",
808 ntohl(reply->error));
809 cmd->status = BLK_STS_IOERR;
813 dev_dbg(nbd_to_dev(nbd), "request %p: got reply\n", req);
814 if (rq_data_dir(req) != WRITE) {
815 struct req_iterator iter;
819 rq_for_each_segment(bvec, req, iter) {
820 iov_iter_bvec(&to, ITER_DEST, &bvec, 1, bvec.bv_len);
821 result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
823 dev_err(disk_to_dev(nbd->disk), "Receive data failed (result %d)\n",
826 * If we've disconnected, we need to make sure we
827 * complete this request, otherwise error out
828 * and let the timeout stuff handle resubmitting
829 * this request onto another connection.
831 if (nbd_disconnected(nbd->config)) {
832 cmd->status = BLK_STS_IOERR;
838 dev_dbg(nbd_to_dev(nbd), "request %p: got %d bytes data\n",
843 trace_nbd_payload_received(req, handle);
844 mutex_unlock(&cmd->lock);
845 return ret ? ERR_PTR(ret) : cmd;
848 static void recv_work(struct work_struct *work)
850 struct recv_thread_args *args = container_of(work,
851 struct recv_thread_args,
853 struct nbd_device *nbd = args->nbd;
854 struct nbd_config *config = nbd->config;
855 struct request_queue *q = nbd->disk->queue;
856 struct nbd_sock *nsock = args->nsock;
861 struct nbd_reply reply;
863 if (nbd_read_reply(nbd, nsock->sock, &reply))
867 * Grab .q_usage_counter so request pool won't go away, then no
868 * request use-after-free is possible during nbd_handle_reply().
869 * If queue is frozen, there won't be any inflight requests, we
870 * needn't to handle the incoming garbage message.
872 if (!percpu_ref_tryget(&q->q_usage_counter)) {
873 dev_err(disk_to_dev(nbd->disk), "%s: no io inflight\n",
878 cmd = nbd_handle_reply(nbd, args->index, &reply);
880 percpu_ref_put(&q->q_usage_counter);
884 rq = blk_mq_rq_from_pdu(cmd);
885 if (likely(!blk_should_fake_timeout(rq->q))) {
888 mutex_lock(&cmd->lock);
889 complete = __test_and_clear_bit(NBD_CMD_INFLIGHT,
891 mutex_unlock(&cmd->lock);
893 blk_mq_complete_request(rq);
895 percpu_ref_put(&q->q_usage_counter);
898 mutex_lock(&nsock->tx_lock);
899 nbd_mark_nsock_dead(nbd, nsock, 1);
900 mutex_unlock(&nsock->tx_lock);
903 atomic_dec(&config->recv_threads);
904 wake_up(&config->recv_wq);
908 static bool nbd_clear_req(struct request *req, void *data)
910 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
912 /* don't abort one completed request */
913 if (blk_mq_request_completed(req))
916 mutex_lock(&cmd->lock);
917 if (!__test_and_clear_bit(NBD_CMD_INFLIGHT, &cmd->flags)) {
918 mutex_unlock(&cmd->lock);
921 cmd->status = BLK_STS_IOERR;
922 mutex_unlock(&cmd->lock);
924 blk_mq_complete_request(req);
928 static void nbd_clear_que(struct nbd_device *nbd)
930 blk_mq_quiesce_queue(nbd->disk->queue);
931 blk_mq_tagset_busy_iter(&nbd->tag_set, nbd_clear_req, NULL);
932 blk_mq_unquiesce_queue(nbd->disk->queue);
933 dev_dbg(disk_to_dev(nbd->disk), "queue cleared\n");
936 static int find_fallback(struct nbd_device *nbd, int index)
938 struct nbd_config *config = nbd->config;
940 struct nbd_sock *nsock = config->socks[index];
941 int fallback = nsock->fallback_index;
943 if (test_bit(NBD_RT_DISCONNECTED, &config->runtime_flags))
946 if (config->num_connections <= 1) {
947 dev_err_ratelimited(disk_to_dev(nbd->disk),
948 "Dead connection, failed to find a fallback\n");
952 if (fallback >= 0 && fallback < config->num_connections &&
953 !config->socks[fallback]->dead)
956 if (nsock->fallback_index < 0 ||
957 nsock->fallback_index >= config->num_connections ||
958 config->socks[nsock->fallback_index]->dead) {
960 for (i = 0; i < config->num_connections; i++) {
963 if (!config->socks[i]->dead) {
968 nsock->fallback_index = new_index;
970 dev_err_ratelimited(disk_to_dev(nbd->disk),
971 "Dead connection, failed to find a fallback\n");
975 new_index = nsock->fallback_index;
979 static int wait_for_reconnect(struct nbd_device *nbd)
981 struct nbd_config *config = nbd->config;
982 if (!config->dead_conn_timeout)
985 if (!wait_event_timeout(config->conn_wait,
986 test_bit(NBD_RT_DISCONNECTED,
987 &config->runtime_flags) ||
988 atomic_read(&config->live_connections) > 0,
989 config->dead_conn_timeout))
992 return !test_bit(NBD_RT_DISCONNECTED, &config->runtime_flags);
995 static int nbd_handle_cmd(struct nbd_cmd *cmd, int index)
997 struct request *req = blk_mq_rq_from_pdu(cmd);
998 struct nbd_device *nbd = cmd->nbd;
999 struct nbd_config *config;
1000 struct nbd_sock *nsock;
1003 config = nbd_get_config_unlocked(nbd);
1005 dev_err_ratelimited(disk_to_dev(nbd->disk),
1006 "Socks array is empty\n");
1010 if (index >= config->num_connections) {
1011 dev_err_ratelimited(disk_to_dev(nbd->disk),
1012 "Attempted send on invalid socket\n");
1013 nbd_config_put(nbd);
1016 cmd->status = BLK_STS_OK;
1018 nsock = config->socks[index];
1019 mutex_lock(&nsock->tx_lock);
1021 int old_index = index;
1022 index = find_fallback(nbd, index);
1023 mutex_unlock(&nsock->tx_lock);
1025 if (wait_for_reconnect(nbd)) {
1029 /* All the sockets should already be down at this point,
1030 * we just want to make sure that DISCONNECTED is set so
1031 * any requests that come in that were queue'ed waiting
1032 * for the reconnect timer don't trigger the timer again
1033 * and instead just error out.
1036 nbd_config_put(nbd);
1042 /* Handle the case that we have a pending request that was partially
1043 * transmitted that _has_ to be serviced first. We need to call requeue
1044 * here so that it gets put _after_ the request that is already on the
1047 blk_mq_start_request(req);
1048 if (unlikely(nsock->pending && nsock->pending != req)) {
1049 nbd_requeue_cmd(cmd);
1054 * Some failures are related to the link going down, so anything that
1055 * returns EAGAIN can be retried on a different socket.
1057 ret = nbd_send_cmd(nbd, cmd, index);
1059 * Access to this flag is protected by cmd->lock, thus it's safe to set
1060 * the flag after nbd_send_cmd() succeed to send request to server.
1063 __set_bit(NBD_CMD_INFLIGHT, &cmd->flags);
1064 else if (ret == -EAGAIN) {
1065 dev_err_ratelimited(disk_to_dev(nbd->disk),
1066 "Request send failed, requeueing\n");
1067 nbd_mark_nsock_dead(nbd, nsock, 1);
1068 nbd_requeue_cmd(cmd);
1072 mutex_unlock(&nsock->tx_lock);
1073 nbd_config_put(nbd);
1077 static blk_status_t nbd_queue_rq(struct blk_mq_hw_ctx *hctx,
1078 const struct blk_mq_queue_data *bd)
1080 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(bd->rq);
1084 * Since we look at the bio's to send the request over the network we
1085 * need to make sure the completion work doesn't mark this request done
1086 * before we are done doing our send. This keeps us from dereferencing
1087 * freed data if we have particularly fast completions (ie we get the
1088 * completion before we exit sock_xmit on the last bvec) or in the case
1089 * that the server is misbehaving (or there was an error) before we're
1090 * done sending everything over the wire.
1092 mutex_lock(&cmd->lock);
1093 clear_bit(NBD_CMD_REQUEUED, &cmd->flags);
1095 /* We can be called directly from the user space process, which means we
1096 * could possibly have signals pending so our sendmsg will fail. In
1097 * this case we need to return that we are busy, otherwise error out as
1100 ret = nbd_handle_cmd(cmd, hctx->queue_num);
1102 ret = BLK_STS_IOERR;
1105 mutex_unlock(&cmd->lock);
1110 static struct socket *nbd_get_socket(struct nbd_device *nbd, unsigned long fd,
1113 struct socket *sock;
1116 sock = sockfd_lookup(fd, err);
1120 if (sock->ops->shutdown == sock_no_shutdown) {
1121 dev_err(disk_to_dev(nbd->disk), "Unsupported socket: shutdown callout must be supported.\n");
1130 static int nbd_add_socket(struct nbd_device *nbd, unsigned long arg,
1133 struct nbd_config *config = nbd->config;
1134 struct socket *sock;
1135 struct nbd_sock **socks;
1136 struct nbd_sock *nsock;
1139 /* Arg will be cast to int, check it to avoid overflow */
1142 sock = nbd_get_socket(nbd, arg, &err);
1147 * We need to make sure we don't get any errant requests while we're
1148 * reallocating the ->socks array.
1150 blk_mq_freeze_queue(nbd->disk->queue);
1152 if (!netlink && !nbd->task_setup &&
1153 !test_bit(NBD_RT_BOUND, &config->runtime_flags))
1154 nbd->task_setup = current;
1157 (nbd->task_setup != current ||
1158 test_bit(NBD_RT_BOUND, &config->runtime_flags))) {
1159 dev_err(disk_to_dev(nbd->disk),
1160 "Device being setup by another task");
1165 nsock = kzalloc(sizeof(*nsock), GFP_KERNEL);
1171 socks = krealloc(config->socks, (config->num_connections + 1) *
1172 sizeof(struct nbd_sock *), GFP_KERNEL);
1179 config->socks = socks;
1181 nsock->fallback_index = -1;
1182 nsock->dead = false;
1183 mutex_init(&nsock->tx_lock);
1185 nsock->pending = NULL;
1188 socks[config->num_connections++] = nsock;
1189 atomic_inc(&config->live_connections);
1190 blk_mq_unfreeze_queue(nbd->disk->queue);
1195 blk_mq_unfreeze_queue(nbd->disk->queue);
1200 static int nbd_reconnect_socket(struct nbd_device *nbd, unsigned long arg)
1202 struct nbd_config *config = nbd->config;
1203 struct socket *sock, *old;
1204 struct recv_thread_args *args;
1208 sock = nbd_get_socket(nbd, arg, &err);
1212 args = kzalloc(sizeof(*args), GFP_KERNEL);
1218 for (i = 0; i < config->num_connections; i++) {
1219 struct nbd_sock *nsock = config->socks[i];
1224 mutex_lock(&nsock->tx_lock);
1226 mutex_unlock(&nsock->tx_lock);
1229 sk_set_memalloc(sock->sk);
1230 if (nbd->tag_set.timeout)
1231 sock->sk->sk_sndtimeo = nbd->tag_set.timeout;
1232 atomic_inc(&config->recv_threads);
1233 refcount_inc(&nbd->config_refs);
1235 nsock->fallback_index = -1;
1237 nsock->dead = false;
1238 INIT_WORK(&args->work, recv_work);
1241 args->nsock = nsock;
1243 mutex_unlock(&nsock->tx_lock);
1246 clear_bit(NBD_RT_DISCONNECTED, &config->runtime_flags);
1248 /* We take the tx_mutex in an error path in the recv_work, so we
1249 * need to queue_work outside of the tx_mutex.
1251 queue_work(nbd->recv_workq, &args->work);
1253 atomic_inc(&config->live_connections);
1254 wake_up(&config->conn_wait);
1262 static void nbd_bdev_reset(struct nbd_device *nbd)
1264 if (disk_openers(nbd->disk) > 1)
1266 set_capacity(nbd->disk, 0);
1269 static void nbd_parse_flags(struct nbd_device *nbd)
1271 struct nbd_config *config = nbd->config;
1272 if (config->flags & NBD_FLAG_READ_ONLY)
1273 set_disk_ro(nbd->disk, true);
1275 set_disk_ro(nbd->disk, false);
1276 if (config->flags & NBD_FLAG_SEND_FLUSH) {
1277 if (config->flags & NBD_FLAG_SEND_FUA)
1278 blk_queue_write_cache(nbd->disk->queue, true, true);
1280 blk_queue_write_cache(nbd->disk->queue, true, false);
1283 blk_queue_write_cache(nbd->disk->queue, false, false);
1286 static void send_disconnects(struct nbd_device *nbd)
1288 struct nbd_config *config = nbd->config;
1289 struct nbd_request request = {
1290 .magic = htonl(NBD_REQUEST_MAGIC),
1291 .type = htonl(NBD_CMD_DISC),
1293 struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
1294 struct iov_iter from;
1297 for (i = 0; i < config->num_connections; i++) {
1298 struct nbd_sock *nsock = config->socks[i];
1300 iov_iter_kvec(&from, ITER_SOURCE, &iov, 1, sizeof(request));
1301 mutex_lock(&nsock->tx_lock);
1302 ret = sock_xmit(nbd, i, 1, &from, 0, NULL);
1304 dev_err(disk_to_dev(nbd->disk),
1305 "Send disconnect failed %d\n", ret);
1306 mutex_unlock(&nsock->tx_lock);
1310 static int nbd_disconnect(struct nbd_device *nbd)
1312 struct nbd_config *config = nbd->config;
1314 dev_info(disk_to_dev(nbd->disk), "NBD_DISCONNECT\n");
1315 set_bit(NBD_RT_DISCONNECT_REQUESTED, &config->runtime_flags);
1316 set_bit(NBD_DISCONNECT_REQUESTED, &nbd->flags);
1317 send_disconnects(nbd);
1321 static void nbd_clear_sock(struct nbd_device *nbd)
1325 nbd->task_setup = NULL;
1328 static void nbd_config_put(struct nbd_device *nbd)
1330 if (refcount_dec_and_mutex_lock(&nbd->config_refs,
1331 &nbd->config_lock)) {
1332 struct nbd_config *config = nbd->config;
1333 nbd_dev_dbg_close(nbd);
1334 invalidate_disk(nbd->disk);
1335 if (nbd->config->bytesize)
1336 kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
1337 if (test_and_clear_bit(NBD_RT_HAS_PID_FILE,
1338 &config->runtime_flags))
1339 device_remove_file(disk_to_dev(nbd->disk), &pid_attr);
1341 if (test_and_clear_bit(NBD_RT_HAS_BACKEND_FILE,
1342 &config->runtime_flags)) {
1343 device_remove_file(disk_to_dev(nbd->disk), &backend_attr);
1344 kfree(nbd->backend);
1345 nbd->backend = NULL;
1347 nbd_clear_sock(nbd);
1348 if (config->num_connections) {
1350 for (i = 0; i < config->num_connections; i++) {
1351 sockfd_put(config->socks[i]->sock);
1352 kfree(config->socks[i]);
1354 kfree(config->socks);
1359 nbd->tag_set.timeout = 0;
1360 nbd->disk->queue->limits.discard_granularity = 0;
1361 blk_queue_max_discard_sectors(nbd->disk->queue, 0);
1363 mutex_unlock(&nbd->config_lock);
1365 module_put(THIS_MODULE);
1369 static int nbd_start_device(struct nbd_device *nbd)
1371 struct nbd_config *config = nbd->config;
1372 int num_connections = config->num_connections;
1379 if (num_connections > 1 &&
1380 !(config->flags & NBD_FLAG_CAN_MULTI_CONN)) {
1381 dev_err(disk_to_dev(nbd->disk), "server does not support multiple connections per device.\n");
1385 blk_mq_update_nr_hw_queues(&nbd->tag_set, config->num_connections);
1386 nbd->pid = task_pid_nr(current);
1388 nbd_parse_flags(nbd);
1390 error = device_create_file(disk_to_dev(nbd->disk), &pid_attr);
1392 dev_err(disk_to_dev(nbd->disk), "device_create_file failed for pid!\n");
1395 set_bit(NBD_RT_HAS_PID_FILE, &config->runtime_flags);
1397 nbd_dev_dbg_init(nbd);
1398 for (i = 0; i < num_connections; i++) {
1399 struct recv_thread_args *args;
1401 args = kzalloc(sizeof(*args), GFP_KERNEL);
1405 * If num_connections is m (2 < m),
1406 * and NO.1 ~ NO.n(1 < n < m) kzallocs are successful.
1407 * But NO.(n + 1) failed. We still have n recv threads.
1408 * So, add flush_workqueue here to prevent recv threads
1409 * dropping the last config_refs and trying to destroy
1410 * the workqueue from inside the workqueue.
1413 flush_workqueue(nbd->recv_workq);
1416 sk_set_memalloc(config->socks[i]->sock->sk);
1417 if (nbd->tag_set.timeout)
1418 config->socks[i]->sock->sk->sk_sndtimeo =
1419 nbd->tag_set.timeout;
1420 atomic_inc(&config->recv_threads);
1421 refcount_inc(&nbd->config_refs);
1422 INIT_WORK(&args->work, recv_work);
1424 args->nsock = config->socks[i];
1426 queue_work(nbd->recv_workq, &args->work);
1428 return nbd_set_size(nbd, config->bytesize, nbd_blksize(config));
1431 static int nbd_start_device_ioctl(struct nbd_device *nbd)
1433 struct nbd_config *config = nbd->config;
1436 ret = nbd_start_device(nbd);
1441 set_bit(GD_NEED_PART_SCAN, &nbd->disk->state);
1442 mutex_unlock(&nbd->config_lock);
1443 ret = wait_event_interruptible(config->recv_wq,
1444 atomic_read(&config->recv_threads) == 0);
1450 flush_workqueue(nbd->recv_workq);
1451 mutex_lock(&nbd->config_lock);
1452 nbd_bdev_reset(nbd);
1453 /* user requested, ignore socket errors */
1454 if (test_bit(NBD_RT_DISCONNECT_REQUESTED, &config->runtime_flags))
1456 if (test_bit(NBD_RT_TIMEDOUT, &config->runtime_flags))
1461 static void nbd_clear_sock_ioctl(struct nbd_device *nbd)
1463 nbd_clear_sock(nbd);
1464 disk_force_media_change(nbd->disk);
1465 nbd_bdev_reset(nbd);
1466 if (test_and_clear_bit(NBD_RT_HAS_CONFIG_REF,
1467 &nbd->config->runtime_flags))
1468 nbd_config_put(nbd);
1471 static void nbd_set_cmd_timeout(struct nbd_device *nbd, u64 timeout)
1473 nbd->tag_set.timeout = timeout * HZ;
1475 blk_queue_rq_timeout(nbd->disk->queue, timeout * HZ);
1477 blk_queue_rq_timeout(nbd->disk->queue, 30 * HZ);
1480 /* Must be called with config_lock held */
1481 static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
1482 unsigned int cmd, unsigned long arg)
1484 struct nbd_config *config = nbd->config;
1488 case NBD_DISCONNECT:
1489 return nbd_disconnect(nbd);
1490 case NBD_CLEAR_SOCK:
1491 nbd_clear_sock_ioctl(nbd);
1494 return nbd_add_socket(nbd, arg, false);
1495 case NBD_SET_BLKSIZE:
1496 return nbd_set_size(nbd, config->bytesize, arg);
1498 return nbd_set_size(nbd, arg, nbd_blksize(config));
1499 case NBD_SET_SIZE_BLOCKS:
1500 if (check_shl_overflow(arg, config->blksize_bits, &bytesize))
1502 return nbd_set_size(nbd, bytesize, nbd_blksize(config));
1503 case NBD_SET_TIMEOUT:
1504 nbd_set_cmd_timeout(nbd, arg);
1508 config->flags = arg;
1511 return nbd_start_device_ioctl(nbd);
1514 * This is for compatibility only. The queue is always cleared
1515 * by NBD_DO_IT or NBD_CLEAR_SOCK.
1518 case NBD_PRINT_DEBUG:
1520 * For compatibility only, we no longer keep a list of
1521 * outstanding requests.
1528 static int nbd_ioctl(struct block_device *bdev, blk_mode_t mode,
1529 unsigned int cmd, unsigned long arg)
1531 struct nbd_device *nbd = bdev->bd_disk->private_data;
1532 struct nbd_config *config = nbd->config;
1533 int error = -EINVAL;
1535 if (!capable(CAP_SYS_ADMIN))
1538 /* The block layer will pass back some non-nbd ioctls in case we have
1539 * special handling for them, but we don't so just return an error.
1541 if (_IOC_TYPE(cmd) != 0xab)
1544 mutex_lock(&nbd->config_lock);
1546 /* Don't allow ioctl operations on a nbd device that was created with
1547 * netlink, unless it's DISCONNECT or CLEAR_SOCK, which are fine.
1549 if (!test_bit(NBD_RT_BOUND, &config->runtime_flags) ||
1550 (cmd == NBD_DISCONNECT || cmd == NBD_CLEAR_SOCK))
1551 error = __nbd_ioctl(bdev, nbd, cmd, arg);
1553 dev_err(nbd_to_dev(nbd), "Cannot use ioctl interface on a netlink controlled device.\n");
1554 mutex_unlock(&nbd->config_lock);
1558 static int nbd_alloc_and_init_config(struct nbd_device *nbd)
1560 struct nbd_config *config;
1562 if (WARN_ON(nbd->config))
1565 if (!try_module_get(THIS_MODULE))
1568 config = kzalloc(sizeof(struct nbd_config), GFP_NOFS);
1570 module_put(THIS_MODULE);
1574 atomic_set(&config->recv_threads, 0);
1575 init_waitqueue_head(&config->recv_wq);
1576 init_waitqueue_head(&config->conn_wait);
1577 config->blksize_bits = NBD_DEF_BLKSIZE_BITS;
1578 atomic_set(&config->live_connections, 0);
1580 nbd->config = config;
1582 * Order refcount_set(&nbd->config_refs, 1) and nbd->config assignment,
1583 * its pair is the barrier in nbd_get_config_unlocked().
1584 * So nbd_get_config_unlocked() won't see nbd->config as null after
1585 * refcount_inc_not_zero() succeed.
1587 smp_mb__before_atomic();
1588 refcount_set(&nbd->config_refs, 1);
1593 static int nbd_open(struct gendisk *disk, blk_mode_t mode)
1595 struct nbd_device *nbd;
1596 struct nbd_config *config;
1599 mutex_lock(&nbd_index_mutex);
1600 nbd = disk->private_data;
1605 if (!refcount_inc_not_zero(&nbd->refs)) {
1610 config = nbd_get_config_unlocked(nbd);
1612 mutex_lock(&nbd->config_lock);
1613 if (refcount_inc_not_zero(&nbd->config_refs)) {
1614 mutex_unlock(&nbd->config_lock);
1617 ret = nbd_alloc_and_init_config(nbd);
1619 mutex_unlock(&nbd->config_lock);
1623 refcount_inc(&nbd->refs);
1624 mutex_unlock(&nbd->config_lock);
1626 set_bit(GD_NEED_PART_SCAN, &disk->state);
1627 } else if (nbd_disconnected(config)) {
1629 set_bit(GD_NEED_PART_SCAN, &disk->state);
1632 mutex_unlock(&nbd_index_mutex);
1636 static void nbd_release(struct gendisk *disk)
1638 struct nbd_device *nbd = disk->private_data;
1640 if (test_bit(NBD_RT_DISCONNECT_ON_CLOSE, &nbd->config->runtime_flags) &&
1641 disk_openers(disk) == 0)
1642 nbd_disconnect_and_put(nbd);
1644 nbd_config_put(nbd);
1648 static void nbd_free_disk(struct gendisk *disk)
1650 struct nbd_device *nbd = disk->private_data;
1655 static const struct block_device_operations nbd_fops =
1657 .owner = THIS_MODULE,
1659 .release = nbd_release,
1661 .compat_ioctl = nbd_ioctl,
1662 .free_disk = nbd_free_disk,
1665 #if IS_ENABLED(CONFIG_DEBUG_FS)
1667 static int nbd_dbg_tasks_show(struct seq_file *s, void *unused)
1669 struct nbd_device *nbd = s->private;
1672 seq_printf(s, "recv: %d\n", nbd->pid);
1677 DEFINE_SHOW_ATTRIBUTE(nbd_dbg_tasks);
1679 static int nbd_dbg_flags_show(struct seq_file *s, void *unused)
1681 struct nbd_device *nbd = s->private;
1682 u32 flags = nbd->config->flags;
1684 seq_printf(s, "Hex: 0x%08x\n\n", flags);
1686 seq_puts(s, "Known flags:\n");
1688 if (flags & NBD_FLAG_HAS_FLAGS)
1689 seq_puts(s, "NBD_FLAG_HAS_FLAGS\n");
1690 if (flags & NBD_FLAG_READ_ONLY)
1691 seq_puts(s, "NBD_FLAG_READ_ONLY\n");
1692 if (flags & NBD_FLAG_SEND_FLUSH)
1693 seq_puts(s, "NBD_FLAG_SEND_FLUSH\n");
1694 if (flags & NBD_FLAG_SEND_FUA)
1695 seq_puts(s, "NBD_FLAG_SEND_FUA\n");
1696 if (flags & NBD_FLAG_SEND_TRIM)
1697 seq_puts(s, "NBD_FLAG_SEND_TRIM\n");
1702 DEFINE_SHOW_ATTRIBUTE(nbd_dbg_flags);
1704 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1707 struct nbd_config *config = nbd->config;
1712 dir = debugfs_create_dir(nbd_name(nbd), nbd_dbg_dir);
1714 dev_err(nbd_to_dev(nbd), "Failed to create debugfs dir for '%s'\n",
1718 config->dbg_dir = dir;
1720 debugfs_create_file("tasks", 0444, dir, nbd, &nbd_dbg_tasks_fops);
1721 debugfs_create_u64("size_bytes", 0444, dir, &config->bytesize);
1722 debugfs_create_u32("timeout", 0444, dir, &nbd->tag_set.timeout);
1723 debugfs_create_u32("blocksize_bits", 0444, dir, &config->blksize_bits);
1724 debugfs_create_file("flags", 0444, dir, nbd, &nbd_dbg_flags_fops);
1729 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1731 debugfs_remove_recursive(nbd->config->dbg_dir);
1734 static int nbd_dbg_init(void)
1736 struct dentry *dbg_dir;
1738 dbg_dir = debugfs_create_dir("nbd", NULL);
1739 if (IS_ERR(dbg_dir))
1742 nbd_dbg_dir = dbg_dir;
1747 static void nbd_dbg_close(void)
1749 debugfs_remove_recursive(nbd_dbg_dir);
1752 #else /* IS_ENABLED(CONFIG_DEBUG_FS) */
1754 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1759 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1763 static int nbd_dbg_init(void)
1768 static void nbd_dbg_close(void)
1774 static int nbd_init_request(struct blk_mq_tag_set *set, struct request *rq,
1775 unsigned int hctx_idx, unsigned int numa_node)
1777 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(rq);
1778 cmd->nbd = set->driver_data;
1780 mutex_init(&cmd->lock);
1784 static const struct blk_mq_ops nbd_mq_ops = {
1785 .queue_rq = nbd_queue_rq,
1786 .complete = nbd_complete_rq,
1787 .init_request = nbd_init_request,
1788 .timeout = nbd_xmit_timeout,
1791 static struct nbd_device *nbd_dev_add(int index, unsigned int refs)
1793 struct nbd_device *nbd;
1794 struct gendisk *disk;
1797 nbd = kzalloc(sizeof(struct nbd_device), GFP_KERNEL);
1801 nbd->tag_set.ops = &nbd_mq_ops;
1802 nbd->tag_set.nr_hw_queues = 1;
1803 nbd->tag_set.queue_depth = 128;
1804 nbd->tag_set.numa_node = NUMA_NO_NODE;
1805 nbd->tag_set.cmd_size = sizeof(struct nbd_cmd);
1806 nbd->tag_set.flags = BLK_MQ_F_SHOULD_MERGE |
1808 nbd->tag_set.driver_data = nbd;
1809 INIT_WORK(&nbd->remove_work, nbd_dev_remove_work);
1810 nbd->backend = NULL;
1812 err = blk_mq_alloc_tag_set(&nbd->tag_set);
1816 mutex_lock(&nbd_index_mutex);
1818 err = idr_alloc(&nbd_index_idr, nbd, index, index + 1,
1823 err = idr_alloc(&nbd_index_idr, nbd, 0,
1824 (MINORMASK >> part_shift) + 1, GFP_KERNEL);
1829 mutex_unlock(&nbd_index_mutex);
1833 disk = blk_mq_alloc_disk(&nbd->tag_set, NULL);
1835 err = PTR_ERR(disk);
1840 nbd->recv_workq = alloc_workqueue("nbd%d-recv",
1841 WQ_MEM_RECLAIM | WQ_HIGHPRI |
1842 WQ_UNBOUND, 0, nbd->index);
1843 if (!nbd->recv_workq) {
1844 dev_err(disk_to_dev(nbd->disk), "Could not allocate knbd recv work queue.\n");
1850 * Tell the block layer that we are not a rotational device
1852 blk_queue_flag_set(QUEUE_FLAG_NONROT, disk->queue);
1853 disk->queue->limits.discard_granularity = 0;
1854 blk_queue_max_discard_sectors(disk->queue, 0);
1855 blk_queue_max_segment_size(disk->queue, UINT_MAX);
1856 blk_queue_max_segments(disk->queue, USHRT_MAX);
1857 blk_queue_max_hw_sectors(disk->queue, 65536);
1858 disk->queue->limits.max_sectors = 256;
1860 mutex_init(&nbd->config_lock);
1861 refcount_set(&nbd->config_refs, 0);
1863 * Start out with a zero references to keep other threads from using
1864 * this device until it is fully initialized.
1866 refcount_set(&nbd->refs, 0);
1867 INIT_LIST_HEAD(&nbd->list);
1868 disk->major = NBD_MAJOR;
1869 disk->first_minor = index << part_shift;
1870 disk->minors = 1 << part_shift;
1871 disk->fops = &nbd_fops;
1872 disk->private_data = nbd;
1873 sprintf(disk->disk_name, "nbd%d", index);
1874 err = add_disk(disk);
1879 * Now publish the device.
1881 refcount_set(&nbd->refs, refs);
1882 nbd_total_devices++;
1886 destroy_workqueue(nbd->recv_workq);
1890 mutex_lock(&nbd_index_mutex);
1891 idr_remove(&nbd_index_idr, index);
1892 mutex_unlock(&nbd_index_mutex);
1894 blk_mq_free_tag_set(&nbd->tag_set);
1898 return ERR_PTR(err);
1901 static struct nbd_device *nbd_find_get_unused(void)
1903 struct nbd_device *nbd;
1906 lockdep_assert_held(&nbd_index_mutex);
1908 idr_for_each_entry(&nbd_index_idr, nbd, id) {
1909 if (refcount_read(&nbd->config_refs) ||
1910 test_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags))
1912 if (refcount_inc_not_zero(&nbd->refs))
1919 /* Netlink interface. */
1920 static const struct nla_policy nbd_attr_policy[NBD_ATTR_MAX + 1] = {
1921 [NBD_ATTR_INDEX] = { .type = NLA_U32 },
1922 [NBD_ATTR_SIZE_BYTES] = { .type = NLA_U64 },
1923 [NBD_ATTR_BLOCK_SIZE_BYTES] = { .type = NLA_U64 },
1924 [NBD_ATTR_TIMEOUT] = { .type = NLA_U64 },
1925 [NBD_ATTR_SERVER_FLAGS] = { .type = NLA_U64 },
1926 [NBD_ATTR_CLIENT_FLAGS] = { .type = NLA_U64 },
1927 [NBD_ATTR_SOCKETS] = { .type = NLA_NESTED},
1928 [NBD_ATTR_DEAD_CONN_TIMEOUT] = { .type = NLA_U64 },
1929 [NBD_ATTR_DEVICE_LIST] = { .type = NLA_NESTED},
1930 [NBD_ATTR_BACKEND_IDENTIFIER] = { .type = NLA_STRING},
1933 static const struct nla_policy nbd_sock_policy[NBD_SOCK_MAX + 1] = {
1934 [NBD_SOCK_FD] = { .type = NLA_U32 },
1937 /* We don't use this right now since we don't parse the incoming list, but we
1938 * still want it here so userspace knows what to expect.
1940 static const struct nla_policy __attribute__((unused))
1941 nbd_device_policy[NBD_DEVICE_ATTR_MAX + 1] = {
1942 [NBD_DEVICE_INDEX] = { .type = NLA_U32 },
1943 [NBD_DEVICE_CONNECTED] = { .type = NLA_U8 },
1946 static int nbd_genl_size_set(struct genl_info *info, struct nbd_device *nbd)
1948 struct nbd_config *config = nbd->config;
1949 u64 bsize = nbd_blksize(config);
1950 u64 bytes = config->bytesize;
1952 if (info->attrs[NBD_ATTR_SIZE_BYTES])
1953 bytes = nla_get_u64(info->attrs[NBD_ATTR_SIZE_BYTES]);
1955 if (info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES])
1956 bsize = nla_get_u64(info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]);
1958 if (bytes != config->bytesize || bsize != nbd_blksize(config))
1959 return nbd_set_size(nbd, bytes, bsize);
1963 static int nbd_genl_connect(struct sk_buff *skb, struct genl_info *info)
1965 struct nbd_device *nbd;
1966 struct nbd_config *config;
1969 bool put_dev = false;
1971 if (!netlink_capable(skb, CAP_SYS_ADMIN))
1974 if (info->attrs[NBD_ATTR_INDEX]) {
1975 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1978 * Too big first_minor can cause duplicate creation of
1979 * sysfs files/links, since index << part_shift might overflow, or
1980 * MKDEV() expect that the max bits of first_minor is 20.
1982 if (index < 0 || index > MINORMASK >> part_shift) {
1983 pr_err("illegal input index %d\n", index);
1987 if (GENL_REQ_ATTR_CHECK(info, NBD_ATTR_SOCKETS)) {
1988 pr_err("must specify at least one socket\n");
1991 if (GENL_REQ_ATTR_CHECK(info, NBD_ATTR_SIZE_BYTES)) {
1992 pr_err("must specify a size in bytes for the device\n");
1996 mutex_lock(&nbd_index_mutex);
1998 nbd = nbd_find_get_unused();
2000 nbd = idr_find(&nbd_index_idr, index);
2002 if ((test_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags) &&
2003 test_bit(NBD_DISCONNECT_REQUESTED, &nbd->flags)) ||
2004 !refcount_inc_not_zero(&nbd->refs)) {
2005 mutex_unlock(&nbd_index_mutex);
2006 pr_err("device at index %d is going down\n",
2012 mutex_unlock(&nbd_index_mutex);
2015 nbd = nbd_dev_add(index, 2);
2017 pr_err("failed to add new device\n");
2018 return PTR_ERR(nbd);
2022 mutex_lock(&nbd->config_lock);
2023 if (refcount_read(&nbd->config_refs)) {
2024 mutex_unlock(&nbd->config_lock);
2028 pr_err("nbd%d already in use\n", index);
2032 ret = nbd_alloc_and_init_config(nbd);
2034 mutex_unlock(&nbd->config_lock);
2036 pr_err("couldn't allocate config\n");
2040 config = nbd->config;
2041 set_bit(NBD_RT_BOUND, &config->runtime_flags);
2042 ret = nbd_genl_size_set(info, nbd);
2046 if (info->attrs[NBD_ATTR_TIMEOUT])
2047 nbd_set_cmd_timeout(nbd,
2048 nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]));
2049 if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
2050 config->dead_conn_timeout =
2051 nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
2052 config->dead_conn_timeout *= HZ;
2054 if (info->attrs[NBD_ATTR_SERVER_FLAGS])
2056 nla_get_u64(info->attrs[NBD_ATTR_SERVER_FLAGS]);
2057 if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
2058 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
2059 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
2061 * We have 1 ref to keep the device around, and then 1
2062 * ref for our current operation here, which will be
2063 * inherited by the config. If we already have
2064 * DESTROY_ON_DISCONNECT set then we know we don't have
2065 * that extra ref already held so we don't need the
2068 if (!test_and_set_bit(NBD_DESTROY_ON_DISCONNECT,
2072 if (test_and_clear_bit(NBD_DESTROY_ON_DISCONNECT,
2074 refcount_inc(&nbd->refs);
2076 if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
2077 set_bit(NBD_RT_DISCONNECT_ON_CLOSE,
2078 &config->runtime_flags);
2082 if (info->attrs[NBD_ATTR_SOCKETS]) {
2083 struct nlattr *attr;
2086 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
2088 struct nlattr *socks[NBD_SOCK_MAX+1];
2090 if (nla_type(attr) != NBD_SOCK_ITEM) {
2091 pr_err("socks must be embedded in a SOCK_ITEM attr\n");
2095 ret = nla_parse_nested_deprecated(socks, NBD_SOCK_MAX,
2100 pr_err("error processing sock list\n");
2104 if (!socks[NBD_SOCK_FD])
2106 fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
2107 ret = nbd_add_socket(nbd, fd, true);
2112 ret = nbd_start_device(nbd);
2115 if (info->attrs[NBD_ATTR_BACKEND_IDENTIFIER]) {
2116 nbd->backend = nla_strdup(info->attrs[NBD_ATTR_BACKEND_IDENTIFIER],
2118 if (!nbd->backend) {
2123 ret = device_create_file(disk_to_dev(nbd->disk), &backend_attr);
2125 dev_err(disk_to_dev(nbd->disk),
2126 "device_create_file failed for backend!\n");
2129 set_bit(NBD_RT_HAS_BACKEND_FILE, &config->runtime_flags);
2131 mutex_unlock(&nbd->config_lock);
2133 set_bit(NBD_RT_HAS_CONFIG_REF, &config->runtime_flags);
2134 refcount_inc(&nbd->config_refs);
2135 nbd_connect_reply(info, nbd->index);
2137 nbd_config_put(nbd);
2143 static void nbd_disconnect_and_put(struct nbd_device *nbd)
2145 mutex_lock(&nbd->config_lock);
2146 nbd_disconnect(nbd);
2148 wake_up(&nbd->config->conn_wait);
2150 * Make sure recv thread has finished, we can safely call nbd_clear_que()
2151 * to cancel the inflight I/Os.
2153 flush_workqueue(nbd->recv_workq);
2155 nbd->task_setup = NULL;
2156 mutex_unlock(&nbd->config_lock);
2158 if (test_and_clear_bit(NBD_RT_HAS_CONFIG_REF,
2159 &nbd->config->runtime_flags))
2160 nbd_config_put(nbd);
2163 static int nbd_genl_disconnect(struct sk_buff *skb, struct genl_info *info)
2165 struct nbd_device *nbd;
2168 if (!netlink_capable(skb, CAP_SYS_ADMIN))
2171 if (GENL_REQ_ATTR_CHECK(info, NBD_ATTR_INDEX)) {
2172 pr_err("must specify an index to disconnect\n");
2175 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2176 mutex_lock(&nbd_index_mutex);
2177 nbd = idr_find(&nbd_index_idr, index);
2179 mutex_unlock(&nbd_index_mutex);
2180 pr_err("couldn't find device at index %d\n", index);
2183 if (!refcount_inc_not_zero(&nbd->refs)) {
2184 mutex_unlock(&nbd_index_mutex);
2185 pr_err("device at index %d is going down\n", index);
2188 mutex_unlock(&nbd_index_mutex);
2189 if (!refcount_inc_not_zero(&nbd->config_refs))
2191 nbd_disconnect_and_put(nbd);
2192 nbd_config_put(nbd);
2198 static int nbd_genl_reconfigure(struct sk_buff *skb, struct genl_info *info)
2200 struct nbd_device *nbd = NULL;
2201 struct nbd_config *config;
2204 bool put_dev = false;
2206 if (!netlink_capable(skb, CAP_SYS_ADMIN))
2209 if (GENL_REQ_ATTR_CHECK(info, NBD_ATTR_INDEX)) {
2210 pr_err("must specify a device to reconfigure\n");
2213 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2214 mutex_lock(&nbd_index_mutex);
2215 nbd = idr_find(&nbd_index_idr, index);
2217 mutex_unlock(&nbd_index_mutex);
2218 pr_err("couldn't find a device at index %d\n", index);
2222 if (info->attrs[NBD_ATTR_BACKEND_IDENTIFIER]) {
2223 if (nla_strcmp(info->attrs[NBD_ATTR_BACKEND_IDENTIFIER],
2225 mutex_unlock(&nbd_index_mutex);
2226 dev_err(nbd_to_dev(nbd),
2227 "backend image doesn't match with %s\n",
2232 mutex_unlock(&nbd_index_mutex);
2233 dev_err(nbd_to_dev(nbd), "must specify backend\n");
2237 if (!refcount_inc_not_zero(&nbd->refs)) {
2238 mutex_unlock(&nbd_index_mutex);
2239 pr_err("device at index %d is going down\n", index);
2242 mutex_unlock(&nbd_index_mutex);
2244 config = nbd_get_config_unlocked(nbd);
2246 dev_err(nbd_to_dev(nbd),
2247 "not configured, cannot reconfigure\n");
2252 mutex_lock(&nbd->config_lock);
2253 if (!test_bit(NBD_RT_BOUND, &config->runtime_flags) ||
2255 dev_err(nbd_to_dev(nbd),
2256 "not configured, cannot reconfigure\n");
2261 ret = nbd_genl_size_set(info, nbd);
2265 if (info->attrs[NBD_ATTR_TIMEOUT])
2266 nbd_set_cmd_timeout(nbd,
2267 nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]));
2268 if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
2269 config->dead_conn_timeout =
2270 nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
2271 config->dead_conn_timeout *= HZ;
2273 if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
2274 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
2275 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
2276 if (!test_and_set_bit(NBD_DESTROY_ON_DISCONNECT,
2280 if (test_and_clear_bit(NBD_DESTROY_ON_DISCONNECT,
2282 refcount_inc(&nbd->refs);
2285 if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
2286 set_bit(NBD_RT_DISCONNECT_ON_CLOSE,
2287 &config->runtime_flags);
2289 clear_bit(NBD_RT_DISCONNECT_ON_CLOSE,
2290 &config->runtime_flags);
2294 if (info->attrs[NBD_ATTR_SOCKETS]) {
2295 struct nlattr *attr;
2298 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
2300 struct nlattr *socks[NBD_SOCK_MAX+1];
2302 if (nla_type(attr) != NBD_SOCK_ITEM) {
2303 pr_err("socks must be embedded in a SOCK_ITEM attr\n");
2307 ret = nla_parse_nested_deprecated(socks, NBD_SOCK_MAX,
2312 pr_err("error processing sock list\n");
2316 if (!socks[NBD_SOCK_FD])
2318 fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
2319 ret = nbd_reconnect_socket(nbd, fd);
2325 dev_info(nbd_to_dev(nbd), "reconnected socket\n");
2329 mutex_unlock(&nbd->config_lock);
2330 nbd_config_put(nbd);
2337 static const struct genl_small_ops nbd_connect_genl_ops[] = {
2339 .cmd = NBD_CMD_CONNECT,
2340 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2341 .doit = nbd_genl_connect,
2344 .cmd = NBD_CMD_DISCONNECT,
2345 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2346 .doit = nbd_genl_disconnect,
2349 .cmd = NBD_CMD_RECONFIGURE,
2350 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2351 .doit = nbd_genl_reconfigure,
2354 .cmd = NBD_CMD_STATUS,
2355 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2356 .doit = nbd_genl_status,
2360 static const struct genl_multicast_group nbd_mcast_grps[] = {
2361 { .name = NBD_GENL_MCAST_GROUP_NAME, },
2364 static struct genl_family nbd_genl_family __ro_after_init = {
2366 .name = NBD_GENL_FAMILY_NAME,
2367 .version = NBD_GENL_VERSION,
2368 .module = THIS_MODULE,
2369 .small_ops = nbd_connect_genl_ops,
2370 .n_small_ops = ARRAY_SIZE(nbd_connect_genl_ops),
2371 .resv_start_op = NBD_CMD_STATUS + 1,
2372 .maxattr = NBD_ATTR_MAX,
2374 .policy = nbd_attr_policy,
2375 .mcgrps = nbd_mcast_grps,
2376 .n_mcgrps = ARRAY_SIZE(nbd_mcast_grps),
2378 MODULE_ALIAS_GENL_FAMILY(NBD_GENL_FAMILY_NAME);
2380 static int populate_nbd_status(struct nbd_device *nbd, struct sk_buff *reply)
2382 struct nlattr *dev_opt;
2386 /* This is a little racey, but for status it's ok. The
2387 * reason we don't take a ref here is because we can't
2388 * take a ref in the index == -1 case as we would need
2389 * to put under the nbd_index_mutex, which could
2390 * deadlock if we are configured to remove ourselves
2391 * once we're disconnected.
2393 if (refcount_read(&nbd->config_refs))
2395 dev_opt = nla_nest_start_noflag(reply, NBD_DEVICE_ITEM);
2398 ret = nla_put_u32(reply, NBD_DEVICE_INDEX, nbd->index);
2401 ret = nla_put_u8(reply, NBD_DEVICE_CONNECTED,
2405 nla_nest_end(reply, dev_opt);
2409 static int status_cb(int id, void *ptr, void *data)
2411 struct nbd_device *nbd = ptr;
2412 return populate_nbd_status(nbd, (struct sk_buff *)data);
2415 static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info)
2417 struct nlattr *dev_list;
2418 struct sk_buff *reply;
2424 if (info->attrs[NBD_ATTR_INDEX])
2425 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2427 mutex_lock(&nbd_index_mutex);
2429 msg_size = nla_total_size(nla_attr_size(sizeof(u32)) +
2430 nla_attr_size(sizeof(u8)));
2431 msg_size *= (index == -1) ? nbd_total_devices : 1;
2433 reply = genlmsg_new(msg_size, GFP_KERNEL);
2436 reply_head = genlmsg_put_reply(reply, info, &nbd_genl_family, 0,
2443 dev_list = nla_nest_start_noflag(reply, NBD_ATTR_DEVICE_LIST);
2445 ret = idr_for_each(&nbd_index_idr, &status_cb, reply);
2451 struct nbd_device *nbd;
2452 nbd = idr_find(&nbd_index_idr, index);
2454 ret = populate_nbd_status(nbd, reply);
2461 nla_nest_end(reply, dev_list);
2462 genlmsg_end(reply, reply_head);
2463 ret = genlmsg_reply(reply, info);
2465 mutex_unlock(&nbd_index_mutex);
2469 static void nbd_connect_reply(struct genl_info *info, int index)
2471 struct sk_buff *skb;
2475 skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2478 msg_head = genlmsg_put_reply(skb, info, &nbd_genl_family, 0,
2484 ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2489 genlmsg_end(skb, msg_head);
2490 genlmsg_reply(skb, info);
2493 static void nbd_mcast_index(int index)
2495 struct sk_buff *skb;
2499 skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2502 msg_head = genlmsg_put(skb, 0, 0, &nbd_genl_family, 0,
2508 ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2513 genlmsg_end(skb, msg_head);
2514 genlmsg_multicast(&nbd_genl_family, skb, 0, 0, GFP_KERNEL);
2517 static void nbd_dead_link_work(struct work_struct *work)
2519 struct link_dead_args *args = container_of(work, struct link_dead_args,
2521 nbd_mcast_index(args->index);
2525 static int __init nbd_init(void)
2529 BUILD_BUG_ON(sizeof(struct nbd_request) != 28);
2532 pr_err("max_part must be >= 0\n");
2538 part_shift = fls(max_part);
2541 * Adjust max_part according to part_shift as it is exported
2542 * to user space so that user can know the max number of
2543 * partition kernel should be able to manage.
2545 * Note that -1 is required because partition 0 is reserved
2546 * for the whole disk.
2548 max_part = (1UL << part_shift) - 1;
2551 if ((1UL << part_shift) > DISK_MAX_PARTS)
2554 if (nbds_max > 1UL << (MINORBITS - part_shift))
2557 if (register_blkdev(NBD_MAJOR, "nbd"))
2560 nbd_del_wq = alloc_workqueue("nbd-del", WQ_UNBOUND, 0);
2562 unregister_blkdev(NBD_MAJOR, "nbd");
2566 if (genl_register_family(&nbd_genl_family)) {
2567 destroy_workqueue(nbd_del_wq);
2568 unregister_blkdev(NBD_MAJOR, "nbd");
2573 for (i = 0; i < nbds_max; i++)
2578 static int nbd_exit_cb(int id, void *ptr, void *data)
2580 struct list_head *list = (struct list_head *)data;
2581 struct nbd_device *nbd = ptr;
2583 /* Skip nbd that is being removed asynchronously */
2584 if (refcount_read(&nbd->refs))
2585 list_add_tail(&nbd->list, list);
2590 static void __exit nbd_cleanup(void)
2592 struct nbd_device *nbd;
2593 LIST_HEAD(del_list);
2596 * Unregister netlink interface prior to waiting
2597 * for the completion of netlink commands.
2599 genl_unregister_family(&nbd_genl_family);
2603 mutex_lock(&nbd_index_mutex);
2604 idr_for_each(&nbd_index_idr, &nbd_exit_cb, &del_list);
2605 mutex_unlock(&nbd_index_mutex);
2607 while (!list_empty(&del_list)) {
2608 nbd = list_first_entry(&del_list, struct nbd_device, list);
2609 list_del_init(&nbd->list);
2610 if (refcount_read(&nbd->config_refs))
2611 pr_err("possibly leaking nbd_config (ref %d)\n",
2612 refcount_read(&nbd->config_refs));
2613 if (refcount_read(&nbd->refs) != 1)
2614 pr_err("possibly leaking a device\n");
2618 /* Also wait for nbd_dev_remove_work() completes */
2619 destroy_workqueue(nbd_del_wq);
2621 idr_destroy(&nbd_index_idr);
2622 unregister_blkdev(NBD_MAJOR, "nbd");
2625 module_init(nbd_init);
2626 module_exit(nbd_cleanup);
2628 MODULE_DESCRIPTION("Network Block Device");
2629 MODULE_LICENSE("GPL");
2631 module_param(nbds_max, int, 0444);
2632 MODULE_PARM_DESC(nbds_max, "number of network block devices to initialize (default: 16)");
2633 module_param(max_part, int, 0444);
2634 MODULE_PARM_DESC(max_part, "number of partitions per device (default: 16)");