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;
73 struct link_dead_args {
74 struct work_struct work;
78 #define NBD_RT_TIMEDOUT 0
79 #define NBD_RT_DISCONNECT_REQUESTED 1
80 #define NBD_RT_DISCONNECTED 2
81 #define NBD_RT_HAS_PID_FILE 3
82 #define NBD_RT_HAS_CONFIG_REF 4
83 #define NBD_RT_BOUND 5
84 #define NBD_RT_DISCONNECT_ON_CLOSE 6
85 #define NBD_RT_HAS_BACKEND_FILE 7
87 #define NBD_DESTROY_ON_DISCONNECT 0
88 #define NBD_DISCONNECT_REQUESTED 1
92 unsigned long runtime_flags;
93 u64 dead_conn_timeout;
95 struct nbd_sock **socks;
97 atomic_t live_connections;
98 wait_queue_head_t conn_wait;
100 atomic_t recv_threads;
101 wait_queue_head_t recv_wq;
102 unsigned int blksize_bits;
104 #if IS_ENABLED(CONFIG_DEBUG_FS)
105 struct dentry *dbg_dir;
109 static inline unsigned int nbd_blksize(struct nbd_config *config)
111 return 1u << config->blksize_bits;
115 struct blk_mq_tag_set tag_set;
118 refcount_t config_refs;
120 struct nbd_config *config;
121 struct mutex config_lock;
122 struct gendisk *disk;
123 struct workqueue_struct *recv_workq;
124 struct work_struct remove_work;
126 struct list_head list;
127 struct task_struct *task_setup;
130 pid_t pid; /* pid of nbd-client, if attached */
135 #define NBD_CMD_REQUEUED 1
137 * This flag will be set if nbd_queue_rq() succeed, and will be checked and
138 * cleared in completion. Both setting and clearing of the flag are protected
141 #define NBD_CMD_INFLIGHT 2
144 struct nbd_device *nbd;
154 #if IS_ENABLED(CONFIG_DEBUG_FS)
155 static struct dentry *nbd_dbg_dir;
158 #define nbd_name(nbd) ((nbd)->disk->disk_name)
160 #define NBD_DEF_BLKSIZE_BITS 10
162 static unsigned int nbds_max = 16;
163 static int max_part = 16;
164 static int part_shift;
166 static int nbd_dev_dbg_init(struct nbd_device *nbd);
167 static void nbd_dev_dbg_close(struct nbd_device *nbd);
168 static void nbd_config_put(struct nbd_device *nbd);
169 static void nbd_connect_reply(struct genl_info *info, int index);
170 static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info);
171 static void nbd_dead_link_work(struct work_struct *work);
172 static void nbd_disconnect_and_put(struct nbd_device *nbd);
174 static inline struct device *nbd_to_dev(struct nbd_device *nbd)
176 return disk_to_dev(nbd->disk);
179 static void nbd_requeue_cmd(struct nbd_cmd *cmd)
181 struct request *req = blk_mq_rq_from_pdu(cmd);
183 if (!test_and_set_bit(NBD_CMD_REQUEUED, &cmd->flags))
184 blk_mq_requeue_request(req, true);
187 #define NBD_COOKIE_BITS 32
189 static u64 nbd_cmd_handle(struct nbd_cmd *cmd)
191 struct request *req = blk_mq_rq_from_pdu(cmd);
192 u32 tag = blk_mq_unique_tag(req);
193 u64 cookie = cmd->cmd_cookie;
195 return (cookie << NBD_COOKIE_BITS) | tag;
198 static u32 nbd_handle_to_tag(u64 handle)
203 static u32 nbd_handle_to_cookie(u64 handle)
205 return (u32)(handle >> NBD_COOKIE_BITS);
208 static const char *nbdcmd_to_ascii(int cmd)
211 case NBD_CMD_READ: return "read";
212 case NBD_CMD_WRITE: return "write";
213 case NBD_CMD_DISC: return "disconnect";
214 case NBD_CMD_FLUSH: return "flush";
215 case NBD_CMD_TRIM: return "trim/discard";
220 static ssize_t pid_show(struct device *dev,
221 struct device_attribute *attr, char *buf)
223 struct gendisk *disk = dev_to_disk(dev);
224 struct nbd_device *nbd = (struct nbd_device *)disk->private_data;
226 return sprintf(buf, "%d\n", nbd->pid);
229 static const struct device_attribute pid_attr = {
230 .attr = { .name = "pid", .mode = 0444},
234 static ssize_t backend_show(struct device *dev,
235 struct device_attribute *attr, char *buf)
237 struct gendisk *disk = dev_to_disk(dev);
238 struct nbd_device *nbd = (struct nbd_device *)disk->private_data;
240 return sprintf(buf, "%s\n", nbd->backend ?: "");
243 static const struct device_attribute backend_attr = {
244 .attr = { .name = "backend", .mode = 0444},
245 .show = backend_show,
248 static void nbd_dev_remove(struct nbd_device *nbd)
250 struct gendisk *disk = nbd->disk;
253 blk_mq_free_tag_set(&nbd->tag_set);
256 * Remove from idr after del_gendisk() completes, so if the same ID is
257 * reused, the following add_disk() will succeed.
259 mutex_lock(&nbd_index_mutex);
260 idr_remove(&nbd_index_idr, nbd->index);
261 mutex_unlock(&nbd_index_mutex);
262 destroy_workqueue(nbd->recv_workq);
266 static void nbd_dev_remove_work(struct work_struct *work)
268 nbd_dev_remove(container_of(work, struct nbd_device, remove_work));
271 static void nbd_put(struct nbd_device *nbd)
273 if (!refcount_dec_and_test(&nbd->refs))
276 /* Call del_gendisk() asynchrounously to prevent deadlock */
277 if (test_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags))
278 queue_work(nbd_del_wq, &nbd->remove_work);
283 static int nbd_disconnected(struct nbd_config *config)
285 return test_bit(NBD_RT_DISCONNECTED, &config->runtime_flags) ||
286 test_bit(NBD_RT_DISCONNECT_REQUESTED, &config->runtime_flags);
289 static void nbd_mark_nsock_dead(struct nbd_device *nbd, struct nbd_sock *nsock,
292 if (!nsock->dead && notify && !nbd_disconnected(nbd->config)) {
293 struct link_dead_args *args;
294 args = kmalloc(sizeof(struct link_dead_args), GFP_NOIO);
296 INIT_WORK(&args->work, nbd_dead_link_work);
297 args->index = nbd->index;
298 queue_work(system_wq, &args->work);
302 kernel_sock_shutdown(nsock->sock, SHUT_RDWR);
303 if (atomic_dec_return(&nbd->config->live_connections) == 0) {
304 if (test_and_clear_bit(NBD_RT_DISCONNECT_REQUESTED,
305 &nbd->config->runtime_flags)) {
306 set_bit(NBD_RT_DISCONNECTED,
307 &nbd->config->runtime_flags);
308 dev_info(nbd_to_dev(nbd),
309 "Disconnected due to user request.\n");
314 nsock->pending = NULL;
318 static int nbd_set_size(struct nbd_device *nbd, loff_t bytesize,
322 blksize = 1u << NBD_DEF_BLKSIZE_BITS;
324 if (blk_validate_block_size(blksize))
330 nbd->config->bytesize = bytesize;
331 nbd->config->blksize_bits = __ffs(blksize);
336 if (nbd->config->flags & NBD_FLAG_SEND_TRIM) {
337 nbd->disk->queue->limits.discard_granularity = blksize;
338 blk_queue_max_discard_sectors(nbd->disk->queue, UINT_MAX);
340 blk_queue_logical_block_size(nbd->disk->queue, blksize);
341 blk_queue_physical_block_size(nbd->disk->queue, blksize);
344 set_bit(GD_NEED_PART_SCAN, &nbd->disk->state);
345 if (!set_capacity_and_notify(nbd->disk, bytesize >> 9))
346 kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
350 static void nbd_complete_rq(struct request *req)
352 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
354 dev_dbg(nbd_to_dev(cmd->nbd), "request %p: %s\n", req,
355 cmd->status ? "failed" : "done");
357 blk_mq_end_request(req, cmd->status);
361 * Forcibly shutdown the socket causing all listeners to error
363 static void sock_shutdown(struct nbd_device *nbd)
365 struct nbd_config *config = nbd->config;
368 if (config->num_connections == 0)
370 if (test_and_set_bit(NBD_RT_DISCONNECTED, &config->runtime_flags))
373 for (i = 0; i < config->num_connections; i++) {
374 struct nbd_sock *nsock = config->socks[i];
375 mutex_lock(&nsock->tx_lock);
376 nbd_mark_nsock_dead(nbd, nsock, 0);
377 mutex_unlock(&nsock->tx_lock);
379 dev_warn(disk_to_dev(nbd->disk), "shutting down sockets\n");
382 static u32 req_to_nbd_cmd_type(struct request *req)
384 switch (req_op(req)) {
388 return NBD_CMD_FLUSH;
390 return NBD_CMD_WRITE;
398 static struct nbd_config *nbd_get_config_unlocked(struct nbd_device *nbd)
400 if (refcount_inc_not_zero(&nbd->config_refs))
406 static enum blk_eh_timer_return nbd_xmit_timeout(struct request *req)
408 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
409 struct nbd_device *nbd = cmd->nbd;
410 struct nbd_config *config;
412 if (!mutex_trylock(&cmd->lock))
413 return BLK_EH_RESET_TIMER;
415 if (!test_bit(NBD_CMD_INFLIGHT, &cmd->flags)) {
416 mutex_unlock(&cmd->lock);
420 config = nbd_get_config_unlocked(nbd);
422 cmd->status = BLK_STS_TIMEOUT;
423 __clear_bit(NBD_CMD_INFLIGHT, &cmd->flags);
424 mutex_unlock(&cmd->lock);
428 if (config->num_connections > 1 ||
429 (config->num_connections == 1 && nbd->tag_set.timeout)) {
430 dev_err_ratelimited(nbd_to_dev(nbd),
431 "Connection timed out, retrying (%d/%d alive)\n",
432 atomic_read(&config->live_connections),
433 config->num_connections);
435 * Hooray we have more connections, requeue this IO, the submit
436 * path will put it on a real connection. Or if only one
437 * connection is configured, the submit path will wait util
438 * a new connection is reconfigured or util dead timeout.
441 if (cmd->index < config->num_connections) {
442 struct nbd_sock *nsock =
443 config->socks[cmd->index];
444 mutex_lock(&nsock->tx_lock);
445 /* We can have multiple outstanding requests, so
446 * we don't want to mark the nsock dead if we've
447 * already reconnected with a new socket, so
448 * only mark it dead if its the same socket we
451 if (cmd->cookie == nsock->cookie)
452 nbd_mark_nsock_dead(nbd, nsock, 1);
453 mutex_unlock(&nsock->tx_lock);
455 mutex_unlock(&cmd->lock);
456 nbd_requeue_cmd(cmd);
462 if (!nbd->tag_set.timeout) {
464 * Userspace sets timeout=0 to disable socket disconnection,
465 * so just warn and reset the timer.
467 struct nbd_sock *nsock = config->socks[cmd->index];
469 dev_info(nbd_to_dev(nbd), "Possible stuck request %p: control (%s@%llu,%uB). Runtime %u seconds\n",
470 req, nbdcmd_to_ascii(req_to_nbd_cmd_type(req)),
471 (unsigned long long)blk_rq_pos(req) << 9,
472 blk_rq_bytes(req), (req->timeout / HZ) * cmd->retries);
474 mutex_lock(&nsock->tx_lock);
475 if (cmd->cookie != nsock->cookie) {
476 nbd_requeue_cmd(cmd);
477 mutex_unlock(&nsock->tx_lock);
478 mutex_unlock(&cmd->lock);
482 mutex_unlock(&nsock->tx_lock);
483 mutex_unlock(&cmd->lock);
485 return BLK_EH_RESET_TIMER;
488 dev_err_ratelimited(nbd_to_dev(nbd), "Connection timed out\n");
489 set_bit(NBD_RT_TIMEDOUT, &config->runtime_flags);
490 cmd->status = BLK_STS_IOERR;
491 __clear_bit(NBD_CMD_INFLIGHT, &cmd->flags);
492 mutex_unlock(&cmd->lock);
496 blk_mq_complete_request(req);
501 * Send or receive packet. Return a positive value on success and
502 * negtive value on failue, and never return 0.
504 static int sock_xmit(struct nbd_device *nbd, int index, int send,
505 struct iov_iter *iter, int msg_flags, int *sent)
507 struct nbd_config *config = nbd->config;
508 struct socket *sock = config->socks[index]->sock;
511 unsigned int noreclaim_flag;
513 if (unlikely(!sock)) {
514 dev_err_ratelimited(disk_to_dev(nbd->disk),
515 "Attempted %s on closed socket in sock_xmit\n",
516 (send ? "send" : "recv"));
520 msg.msg_iter = *iter;
522 noreclaim_flag = memalloc_noreclaim_save();
524 sock->sk->sk_allocation = GFP_NOIO | __GFP_MEMALLOC;
525 sock->sk->sk_use_task_frag = false;
528 msg.msg_control = NULL;
529 msg.msg_controllen = 0;
530 msg.msg_flags = msg_flags | MSG_NOSIGNAL;
533 result = sock_sendmsg(sock, &msg);
535 result = sock_recvmsg(sock, &msg, msg.msg_flags);
539 result = -EPIPE; /* short read */
544 } while (msg_data_left(&msg));
546 memalloc_noreclaim_restore(noreclaim_flag);
552 * Different settings for sk->sk_sndtimeo can result in different return values
553 * if there is a signal pending when we enter sendmsg, because reasons?
555 static inline int was_interrupted(int result)
557 return result == -ERESTARTSYS || result == -EINTR;
560 /* always call with the tx_lock held */
561 static int nbd_send_cmd(struct nbd_device *nbd, struct nbd_cmd *cmd, int index)
563 struct request *req = blk_mq_rq_from_pdu(cmd);
564 struct nbd_config *config = nbd->config;
565 struct nbd_sock *nsock = config->socks[index];
567 struct nbd_request request = {.magic = htonl(NBD_REQUEST_MAGIC)};
568 struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
569 struct iov_iter from;
570 unsigned long size = blk_rq_bytes(req);
574 u32 nbd_cmd_flags = 0;
575 int sent = nsock->sent, skip = 0;
577 iov_iter_kvec(&from, ITER_SOURCE, &iov, 1, sizeof(request));
579 type = req_to_nbd_cmd_type(req);
583 if (rq_data_dir(req) == WRITE &&
584 (config->flags & NBD_FLAG_READ_ONLY)) {
585 dev_err_ratelimited(disk_to_dev(nbd->disk),
586 "Write on read-only\n");
590 if (req->cmd_flags & REQ_FUA)
591 nbd_cmd_flags |= NBD_CMD_FLAG_FUA;
593 /* We did a partial send previously, and we at least sent the whole
594 * request struct, so just go and send the rest of the pages in the
598 if (sent >= sizeof(request)) {
599 skip = sent - sizeof(request);
601 /* initialize handle for tracing purposes */
602 handle = nbd_cmd_handle(cmd);
606 iov_iter_advance(&from, sent);
611 cmd->cookie = nsock->cookie;
613 request.type = htonl(type | nbd_cmd_flags);
614 if (type != NBD_CMD_FLUSH) {
615 request.from = cpu_to_be64((u64)blk_rq_pos(req) << 9);
616 request.len = htonl(size);
618 handle = nbd_cmd_handle(cmd);
619 request.cookie = cpu_to_be64(handle);
621 trace_nbd_send_request(&request, nbd->index, blk_mq_rq_from_pdu(cmd));
623 dev_dbg(nbd_to_dev(nbd), "request %p: sending control (%s@%llu,%uB)\n",
624 req, nbdcmd_to_ascii(type),
625 (unsigned long long)blk_rq_pos(req) << 9, blk_rq_bytes(req));
626 result = sock_xmit(nbd, index, 1, &from,
627 (type == NBD_CMD_WRITE) ? MSG_MORE : 0, &sent);
628 trace_nbd_header_sent(req, handle);
630 if (was_interrupted(result)) {
631 /* If we haven't sent anything we can just return BUSY,
632 * however if we have sent something we need to make
633 * sure we only allow this req to be sent until we are
637 nsock->pending = req;
640 set_bit(NBD_CMD_REQUEUED, &cmd->flags);
641 return BLK_STS_RESOURCE;
643 dev_err_ratelimited(disk_to_dev(nbd->disk),
644 "Send control failed (result %d)\n", result);
648 if (type != NBD_CMD_WRITE)
653 struct bio *next = bio->bi_next;
654 struct bvec_iter iter;
657 bio_for_each_segment(bvec, bio, iter) {
658 bool is_last = !next && bio_iter_last(bvec, iter);
659 int flags = is_last ? 0 : MSG_MORE;
661 dev_dbg(nbd_to_dev(nbd), "request %p: sending %d bytes data\n",
663 iov_iter_bvec(&from, ITER_SOURCE, &bvec, 1, bvec.bv_len);
665 if (skip >= iov_iter_count(&from)) {
666 skip -= iov_iter_count(&from);
669 iov_iter_advance(&from, skip);
672 result = sock_xmit(nbd, index, 1, &from, flags, &sent);
674 if (was_interrupted(result)) {
675 /* We've already sent the header, we
676 * have no choice but to set pending and
679 nsock->pending = req;
681 set_bit(NBD_CMD_REQUEUED, &cmd->flags);
682 return BLK_STS_RESOURCE;
684 dev_err(disk_to_dev(nbd->disk),
685 "Send data failed (result %d)\n",
690 * The completion might already have come in,
691 * so break for the last one instead of letting
692 * the iterator do it. This prevents use-after-free
701 trace_nbd_payload_sent(req, handle);
702 nsock->pending = NULL;
707 static int nbd_read_reply(struct nbd_device *nbd, int index,
708 struct nbd_reply *reply)
710 struct kvec iov = {.iov_base = reply, .iov_len = sizeof(*reply)};
715 iov_iter_kvec(&to, ITER_DEST, &iov, 1, sizeof(*reply));
716 result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
718 if (!nbd_disconnected(nbd->config))
719 dev_err(disk_to_dev(nbd->disk),
720 "Receive control failed (result %d)\n", result);
724 if (ntohl(reply->magic) != NBD_REPLY_MAGIC) {
725 dev_err(disk_to_dev(nbd->disk), "Wrong magic (0x%lx)\n",
726 (unsigned long)ntohl(reply->magic));
733 /* NULL returned = something went wrong, inform userspace */
734 static struct nbd_cmd *nbd_handle_reply(struct nbd_device *nbd, int index,
735 struct nbd_reply *reply)
739 struct request *req = NULL;
745 handle = be64_to_cpu(reply->cookie);
746 tag = nbd_handle_to_tag(handle);
747 hwq = blk_mq_unique_tag_to_hwq(tag);
748 if (hwq < nbd->tag_set.nr_hw_queues)
749 req = blk_mq_tag_to_rq(nbd->tag_set.tags[hwq],
750 blk_mq_unique_tag_to_tag(tag));
751 if (!req || !blk_mq_request_started(req)) {
752 dev_err(disk_to_dev(nbd->disk), "Unexpected reply (%d) %p\n",
754 return ERR_PTR(-ENOENT);
756 trace_nbd_header_received(req, handle);
757 cmd = blk_mq_rq_to_pdu(req);
759 mutex_lock(&cmd->lock);
760 if (!test_bit(NBD_CMD_INFLIGHT, &cmd->flags)) {
761 dev_err(disk_to_dev(nbd->disk), "Suspicious reply %d (status %u flags %lu)",
762 tag, cmd->status, cmd->flags);
766 if (cmd->index != index) {
767 dev_err(disk_to_dev(nbd->disk), "Unexpected reply %d from different sock %d (expected %d)",
768 tag, index, cmd->index);
772 if (cmd->cmd_cookie != nbd_handle_to_cookie(handle)) {
773 dev_err(disk_to_dev(nbd->disk), "Double reply on req %p, cmd_cookie %u, handle cookie %u\n",
774 req, cmd->cmd_cookie, nbd_handle_to_cookie(handle));
778 if (cmd->status != BLK_STS_OK) {
779 dev_err(disk_to_dev(nbd->disk), "Command already handled %p\n",
784 if (test_bit(NBD_CMD_REQUEUED, &cmd->flags)) {
785 dev_err(disk_to_dev(nbd->disk), "Raced with timeout on req %p\n",
790 if (ntohl(reply->error)) {
791 dev_err(disk_to_dev(nbd->disk), "Other side returned error (%d)\n",
792 ntohl(reply->error));
793 cmd->status = BLK_STS_IOERR;
797 dev_dbg(nbd_to_dev(nbd), "request %p: got reply\n", req);
798 if (rq_data_dir(req) != WRITE) {
799 struct req_iterator iter;
803 rq_for_each_segment(bvec, req, iter) {
804 iov_iter_bvec(&to, ITER_DEST, &bvec, 1, bvec.bv_len);
805 result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
807 dev_err(disk_to_dev(nbd->disk), "Receive data failed (result %d)\n",
810 * If we've disconnected, we need to make sure we
811 * complete this request, otherwise error out
812 * and let the timeout stuff handle resubmitting
813 * this request onto another connection.
815 if (nbd_disconnected(nbd->config)) {
816 cmd->status = BLK_STS_IOERR;
822 dev_dbg(nbd_to_dev(nbd), "request %p: got %d bytes data\n",
827 trace_nbd_payload_received(req, handle);
828 mutex_unlock(&cmd->lock);
829 return ret ? ERR_PTR(ret) : cmd;
832 static void recv_work(struct work_struct *work)
834 struct recv_thread_args *args = container_of(work,
835 struct recv_thread_args,
837 struct nbd_device *nbd = args->nbd;
838 struct nbd_config *config = nbd->config;
839 struct request_queue *q = nbd->disk->queue;
840 struct nbd_sock *nsock;
845 struct nbd_reply reply;
847 if (nbd_read_reply(nbd, args->index, &reply))
851 * Grab .q_usage_counter so request pool won't go away, then no
852 * request use-after-free is possible during nbd_handle_reply().
853 * If queue is frozen, there won't be any inflight requests, we
854 * needn't to handle the incoming garbage message.
856 if (!percpu_ref_tryget(&q->q_usage_counter)) {
857 dev_err(disk_to_dev(nbd->disk), "%s: no io inflight\n",
862 cmd = nbd_handle_reply(nbd, args->index, &reply);
864 percpu_ref_put(&q->q_usage_counter);
868 rq = blk_mq_rq_from_pdu(cmd);
869 if (likely(!blk_should_fake_timeout(rq->q))) {
872 mutex_lock(&cmd->lock);
873 complete = __test_and_clear_bit(NBD_CMD_INFLIGHT,
875 mutex_unlock(&cmd->lock);
877 blk_mq_complete_request(rq);
879 percpu_ref_put(&q->q_usage_counter);
882 nsock = config->socks[args->index];
883 mutex_lock(&nsock->tx_lock);
884 nbd_mark_nsock_dead(nbd, nsock, 1);
885 mutex_unlock(&nsock->tx_lock);
888 atomic_dec(&config->recv_threads);
889 wake_up(&config->recv_wq);
893 static bool nbd_clear_req(struct request *req, void *data)
895 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
897 /* don't abort one completed request */
898 if (blk_mq_request_completed(req))
901 mutex_lock(&cmd->lock);
902 if (!__test_and_clear_bit(NBD_CMD_INFLIGHT, &cmd->flags)) {
903 mutex_unlock(&cmd->lock);
906 cmd->status = BLK_STS_IOERR;
907 mutex_unlock(&cmd->lock);
909 blk_mq_complete_request(req);
913 static void nbd_clear_que(struct nbd_device *nbd)
915 blk_mq_quiesce_queue(nbd->disk->queue);
916 blk_mq_tagset_busy_iter(&nbd->tag_set, nbd_clear_req, NULL);
917 blk_mq_unquiesce_queue(nbd->disk->queue);
918 dev_dbg(disk_to_dev(nbd->disk), "queue cleared\n");
921 static int find_fallback(struct nbd_device *nbd, int index)
923 struct nbd_config *config = nbd->config;
925 struct nbd_sock *nsock = config->socks[index];
926 int fallback = nsock->fallback_index;
928 if (test_bit(NBD_RT_DISCONNECTED, &config->runtime_flags))
931 if (config->num_connections <= 1) {
932 dev_err_ratelimited(disk_to_dev(nbd->disk),
933 "Dead connection, failed to find a fallback\n");
937 if (fallback >= 0 && fallback < config->num_connections &&
938 !config->socks[fallback]->dead)
941 if (nsock->fallback_index < 0 ||
942 nsock->fallback_index >= config->num_connections ||
943 config->socks[nsock->fallback_index]->dead) {
945 for (i = 0; i < config->num_connections; i++) {
948 if (!config->socks[i]->dead) {
953 nsock->fallback_index = new_index;
955 dev_err_ratelimited(disk_to_dev(nbd->disk),
956 "Dead connection, failed to find a fallback\n");
960 new_index = nsock->fallback_index;
964 static int wait_for_reconnect(struct nbd_device *nbd)
966 struct nbd_config *config = nbd->config;
967 if (!config->dead_conn_timeout)
970 if (!wait_event_timeout(config->conn_wait,
971 test_bit(NBD_RT_DISCONNECTED,
972 &config->runtime_flags) ||
973 atomic_read(&config->live_connections) > 0,
974 config->dead_conn_timeout))
977 return !test_bit(NBD_RT_DISCONNECTED, &config->runtime_flags);
980 static int nbd_handle_cmd(struct nbd_cmd *cmd, int index)
982 struct request *req = blk_mq_rq_from_pdu(cmd);
983 struct nbd_device *nbd = cmd->nbd;
984 struct nbd_config *config;
985 struct nbd_sock *nsock;
988 config = nbd_get_config_unlocked(nbd);
990 dev_err_ratelimited(disk_to_dev(nbd->disk),
991 "Socks array is empty\n");
995 if (index >= config->num_connections) {
996 dev_err_ratelimited(disk_to_dev(nbd->disk),
997 "Attempted send on invalid socket\n");
1001 cmd->status = BLK_STS_OK;
1003 nsock = config->socks[index];
1004 mutex_lock(&nsock->tx_lock);
1006 int old_index = index;
1007 index = find_fallback(nbd, index);
1008 mutex_unlock(&nsock->tx_lock);
1010 if (wait_for_reconnect(nbd)) {
1014 /* All the sockets should already be down at this point,
1015 * we just want to make sure that DISCONNECTED is set so
1016 * any requests that come in that were queue'ed waiting
1017 * for the reconnect timer don't trigger the timer again
1018 * and instead just error out.
1021 nbd_config_put(nbd);
1027 /* Handle the case that we have a pending request that was partially
1028 * transmitted that _has_ to be serviced first. We need to call requeue
1029 * here so that it gets put _after_ the request that is already on the
1032 blk_mq_start_request(req);
1033 if (unlikely(nsock->pending && nsock->pending != req)) {
1034 nbd_requeue_cmd(cmd);
1039 * Some failures are related to the link going down, so anything that
1040 * returns EAGAIN can be retried on a different socket.
1042 ret = nbd_send_cmd(nbd, cmd, index);
1044 * Access to this flag is protected by cmd->lock, thus it's safe to set
1045 * the flag after nbd_send_cmd() succeed to send request to server.
1048 __set_bit(NBD_CMD_INFLIGHT, &cmd->flags);
1049 else if (ret == -EAGAIN) {
1050 dev_err_ratelimited(disk_to_dev(nbd->disk),
1051 "Request send failed, requeueing\n");
1052 nbd_mark_nsock_dead(nbd, nsock, 1);
1053 nbd_requeue_cmd(cmd);
1057 mutex_unlock(&nsock->tx_lock);
1058 nbd_config_put(nbd);
1062 static blk_status_t nbd_queue_rq(struct blk_mq_hw_ctx *hctx,
1063 const struct blk_mq_queue_data *bd)
1065 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(bd->rq);
1069 * Since we look at the bio's to send the request over the network we
1070 * need to make sure the completion work doesn't mark this request done
1071 * before we are done doing our send. This keeps us from dereferencing
1072 * freed data if we have particularly fast completions (ie we get the
1073 * completion before we exit sock_xmit on the last bvec) or in the case
1074 * that the server is misbehaving (or there was an error) before we're
1075 * done sending everything over the wire.
1077 mutex_lock(&cmd->lock);
1078 clear_bit(NBD_CMD_REQUEUED, &cmd->flags);
1080 /* We can be called directly from the user space process, which means we
1081 * could possibly have signals pending so our sendmsg will fail. In
1082 * this case we need to return that we are busy, otherwise error out as
1085 ret = nbd_handle_cmd(cmd, hctx->queue_num);
1087 ret = BLK_STS_IOERR;
1090 mutex_unlock(&cmd->lock);
1095 static struct socket *nbd_get_socket(struct nbd_device *nbd, unsigned long fd,
1098 struct socket *sock;
1101 sock = sockfd_lookup(fd, err);
1105 if (sock->ops->shutdown == sock_no_shutdown) {
1106 dev_err(disk_to_dev(nbd->disk), "Unsupported socket: shutdown callout must be supported.\n");
1115 static int nbd_add_socket(struct nbd_device *nbd, unsigned long arg,
1118 struct nbd_config *config = nbd->config;
1119 struct socket *sock;
1120 struct nbd_sock **socks;
1121 struct nbd_sock *nsock;
1124 /* Arg will be cast to int, check it to avoid overflow */
1127 sock = nbd_get_socket(nbd, arg, &err);
1132 * We need to make sure we don't get any errant requests while we're
1133 * reallocating the ->socks array.
1135 blk_mq_freeze_queue(nbd->disk->queue);
1137 if (!netlink && !nbd->task_setup &&
1138 !test_bit(NBD_RT_BOUND, &config->runtime_flags))
1139 nbd->task_setup = current;
1142 (nbd->task_setup != current ||
1143 test_bit(NBD_RT_BOUND, &config->runtime_flags))) {
1144 dev_err(disk_to_dev(nbd->disk),
1145 "Device being setup by another task");
1150 nsock = kzalloc(sizeof(*nsock), GFP_KERNEL);
1156 socks = krealloc(config->socks, (config->num_connections + 1) *
1157 sizeof(struct nbd_sock *), GFP_KERNEL);
1164 config->socks = socks;
1166 nsock->fallback_index = -1;
1167 nsock->dead = false;
1168 mutex_init(&nsock->tx_lock);
1170 nsock->pending = NULL;
1173 socks[config->num_connections++] = nsock;
1174 atomic_inc(&config->live_connections);
1175 blk_mq_unfreeze_queue(nbd->disk->queue);
1180 blk_mq_unfreeze_queue(nbd->disk->queue);
1185 static int nbd_reconnect_socket(struct nbd_device *nbd, unsigned long arg)
1187 struct nbd_config *config = nbd->config;
1188 struct socket *sock, *old;
1189 struct recv_thread_args *args;
1193 sock = nbd_get_socket(nbd, arg, &err);
1197 args = kzalloc(sizeof(*args), GFP_KERNEL);
1203 for (i = 0; i < config->num_connections; i++) {
1204 struct nbd_sock *nsock = config->socks[i];
1209 mutex_lock(&nsock->tx_lock);
1211 mutex_unlock(&nsock->tx_lock);
1214 sk_set_memalloc(sock->sk);
1215 if (nbd->tag_set.timeout)
1216 sock->sk->sk_sndtimeo = nbd->tag_set.timeout;
1217 atomic_inc(&config->recv_threads);
1218 refcount_inc(&nbd->config_refs);
1220 nsock->fallback_index = -1;
1222 nsock->dead = false;
1223 INIT_WORK(&args->work, recv_work);
1227 mutex_unlock(&nsock->tx_lock);
1230 clear_bit(NBD_RT_DISCONNECTED, &config->runtime_flags);
1232 /* We take the tx_mutex in an error path in the recv_work, so we
1233 * need to queue_work outside of the tx_mutex.
1235 queue_work(nbd->recv_workq, &args->work);
1237 atomic_inc(&config->live_connections);
1238 wake_up(&config->conn_wait);
1246 static void nbd_bdev_reset(struct nbd_device *nbd)
1248 if (disk_openers(nbd->disk) > 1)
1250 set_capacity(nbd->disk, 0);
1253 static void nbd_parse_flags(struct nbd_device *nbd)
1255 struct nbd_config *config = nbd->config;
1256 if (config->flags & NBD_FLAG_READ_ONLY)
1257 set_disk_ro(nbd->disk, true);
1259 set_disk_ro(nbd->disk, false);
1260 if (config->flags & NBD_FLAG_SEND_FLUSH) {
1261 if (config->flags & NBD_FLAG_SEND_FUA)
1262 blk_queue_write_cache(nbd->disk->queue, true, true);
1264 blk_queue_write_cache(nbd->disk->queue, true, false);
1267 blk_queue_write_cache(nbd->disk->queue, false, false);
1270 static void send_disconnects(struct nbd_device *nbd)
1272 struct nbd_config *config = nbd->config;
1273 struct nbd_request request = {
1274 .magic = htonl(NBD_REQUEST_MAGIC),
1275 .type = htonl(NBD_CMD_DISC),
1277 struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
1278 struct iov_iter from;
1281 for (i = 0; i < config->num_connections; i++) {
1282 struct nbd_sock *nsock = config->socks[i];
1284 iov_iter_kvec(&from, ITER_SOURCE, &iov, 1, sizeof(request));
1285 mutex_lock(&nsock->tx_lock);
1286 ret = sock_xmit(nbd, i, 1, &from, 0, NULL);
1288 dev_err(disk_to_dev(nbd->disk),
1289 "Send disconnect failed %d\n", ret);
1290 mutex_unlock(&nsock->tx_lock);
1294 static int nbd_disconnect(struct nbd_device *nbd)
1296 struct nbd_config *config = nbd->config;
1298 dev_info(disk_to_dev(nbd->disk), "NBD_DISCONNECT\n");
1299 set_bit(NBD_RT_DISCONNECT_REQUESTED, &config->runtime_flags);
1300 set_bit(NBD_DISCONNECT_REQUESTED, &nbd->flags);
1301 send_disconnects(nbd);
1305 static void nbd_clear_sock(struct nbd_device *nbd)
1309 nbd->task_setup = NULL;
1312 static void nbd_config_put(struct nbd_device *nbd)
1314 if (refcount_dec_and_mutex_lock(&nbd->config_refs,
1315 &nbd->config_lock)) {
1316 struct nbd_config *config = nbd->config;
1317 nbd_dev_dbg_close(nbd);
1318 invalidate_disk(nbd->disk);
1319 if (nbd->config->bytesize)
1320 kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
1321 if (test_and_clear_bit(NBD_RT_HAS_PID_FILE,
1322 &config->runtime_flags))
1323 device_remove_file(disk_to_dev(nbd->disk), &pid_attr);
1325 if (test_and_clear_bit(NBD_RT_HAS_BACKEND_FILE,
1326 &config->runtime_flags)) {
1327 device_remove_file(disk_to_dev(nbd->disk), &backend_attr);
1328 kfree(nbd->backend);
1329 nbd->backend = NULL;
1331 nbd_clear_sock(nbd);
1332 if (config->num_connections) {
1334 for (i = 0; i < config->num_connections; i++) {
1335 sockfd_put(config->socks[i]->sock);
1336 kfree(config->socks[i]);
1338 kfree(config->socks);
1343 nbd->tag_set.timeout = 0;
1344 nbd->disk->queue->limits.discard_granularity = 0;
1345 blk_queue_max_discard_sectors(nbd->disk->queue, 0);
1347 mutex_unlock(&nbd->config_lock);
1349 module_put(THIS_MODULE);
1353 static int nbd_start_device(struct nbd_device *nbd)
1355 struct nbd_config *config = nbd->config;
1356 int num_connections = config->num_connections;
1363 if (num_connections > 1 &&
1364 !(config->flags & NBD_FLAG_CAN_MULTI_CONN)) {
1365 dev_err(disk_to_dev(nbd->disk), "server does not support multiple connections per device.\n");
1369 blk_mq_update_nr_hw_queues(&nbd->tag_set, config->num_connections);
1370 nbd->pid = task_pid_nr(current);
1372 nbd_parse_flags(nbd);
1374 error = device_create_file(disk_to_dev(nbd->disk), &pid_attr);
1376 dev_err(disk_to_dev(nbd->disk), "device_create_file failed for pid!\n");
1379 set_bit(NBD_RT_HAS_PID_FILE, &config->runtime_flags);
1381 nbd_dev_dbg_init(nbd);
1382 for (i = 0; i < num_connections; i++) {
1383 struct recv_thread_args *args;
1385 args = kzalloc(sizeof(*args), GFP_KERNEL);
1389 * If num_connections is m (2 < m),
1390 * and NO.1 ~ NO.n(1 < n < m) kzallocs are successful.
1391 * But NO.(n + 1) failed. We still have n recv threads.
1392 * So, add flush_workqueue here to prevent recv threads
1393 * dropping the last config_refs and trying to destroy
1394 * the workqueue from inside the workqueue.
1397 flush_workqueue(nbd->recv_workq);
1400 sk_set_memalloc(config->socks[i]->sock->sk);
1401 if (nbd->tag_set.timeout)
1402 config->socks[i]->sock->sk->sk_sndtimeo =
1403 nbd->tag_set.timeout;
1404 atomic_inc(&config->recv_threads);
1405 refcount_inc(&nbd->config_refs);
1406 INIT_WORK(&args->work, recv_work);
1409 queue_work(nbd->recv_workq, &args->work);
1411 return nbd_set_size(nbd, config->bytesize, nbd_blksize(config));
1414 static int nbd_start_device_ioctl(struct nbd_device *nbd)
1416 struct nbd_config *config = nbd->config;
1419 ret = nbd_start_device(nbd);
1424 set_bit(GD_NEED_PART_SCAN, &nbd->disk->state);
1425 mutex_unlock(&nbd->config_lock);
1426 ret = wait_event_interruptible(config->recv_wq,
1427 atomic_read(&config->recv_threads) == 0);
1433 flush_workqueue(nbd->recv_workq);
1434 mutex_lock(&nbd->config_lock);
1435 nbd_bdev_reset(nbd);
1436 /* user requested, ignore socket errors */
1437 if (test_bit(NBD_RT_DISCONNECT_REQUESTED, &config->runtime_flags))
1439 if (test_bit(NBD_RT_TIMEDOUT, &config->runtime_flags))
1444 static void nbd_clear_sock_ioctl(struct nbd_device *nbd)
1446 nbd_clear_sock(nbd);
1447 disk_force_media_change(nbd->disk);
1448 nbd_bdev_reset(nbd);
1449 if (test_and_clear_bit(NBD_RT_HAS_CONFIG_REF,
1450 &nbd->config->runtime_flags))
1451 nbd_config_put(nbd);
1454 static void nbd_set_cmd_timeout(struct nbd_device *nbd, u64 timeout)
1456 nbd->tag_set.timeout = timeout * HZ;
1458 blk_queue_rq_timeout(nbd->disk->queue, timeout * HZ);
1460 blk_queue_rq_timeout(nbd->disk->queue, 30 * HZ);
1463 /* Must be called with config_lock held */
1464 static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
1465 unsigned int cmd, unsigned long arg)
1467 struct nbd_config *config = nbd->config;
1471 case NBD_DISCONNECT:
1472 return nbd_disconnect(nbd);
1473 case NBD_CLEAR_SOCK:
1474 nbd_clear_sock_ioctl(nbd);
1477 return nbd_add_socket(nbd, arg, false);
1478 case NBD_SET_BLKSIZE:
1479 return nbd_set_size(nbd, config->bytesize, arg);
1481 return nbd_set_size(nbd, arg, nbd_blksize(config));
1482 case NBD_SET_SIZE_BLOCKS:
1483 if (check_shl_overflow(arg, config->blksize_bits, &bytesize))
1485 return nbd_set_size(nbd, bytesize, nbd_blksize(config));
1486 case NBD_SET_TIMEOUT:
1487 nbd_set_cmd_timeout(nbd, arg);
1491 config->flags = arg;
1494 return nbd_start_device_ioctl(nbd);
1497 * This is for compatibility only. The queue is always cleared
1498 * by NBD_DO_IT or NBD_CLEAR_SOCK.
1501 case NBD_PRINT_DEBUG:
1503 * For compatibility only, we no longer keep a list of
1504 * outstanding requests.
1511 static int nbd_ioctl(struct block_device *bdev, blk_mode_t mode,
1512 unsigned int cmd, unsigned long arg)
1514 struct nbd_device *nbd = bdev->bd_disk->private_data;
1515 struct nbd_config *config = nbd->config;
1516 int error = -EINVAL;
1518 if (!capable(CAP_SYS_ADMIN))
1521 /* The block layer will pass back some non-nbd ioctls in case we have
1522 * special handling for them, but we don't so just return an error.
1524 if (_IOC_TYPE(cmd) != 0xab)
1527 mutex_lock(&nbd->config_lock);
1529 /* Don't allow ioctl operations on a nbd device that was created with
1530 * netlink, unless it's DISCONNECT or CLEAR_SOCK, which are fine.
1532 if (!test_bit(NBD_RT_BOUND, &config->runtime_flags) ||
1533 (cmd == NBD_DISCONNECT || cmd == NBD_CLEAR_SOCK))
1534 error = __nbd_ioctl(bdev, nbd, cmd, arg);
1536 dev_err(nbd_to_dev(nbd), "Cannot use ioctl interface on a netlink controlled device.\n");
1537 mutex_unlock(&nbd->config_lock);
1541 static int nbd_alloc_and_init_config(struct nbd_device *nbd)
1543 struct nbd_config *config;
1545 if (WARN_ON(nbd->config))
1548 if (!try_module_get(THIS_MODULE))
1551 config = kzalloc(sizeof(struct nbd_config), GFP_NOFS);
1553 module_put(THIS_MODULE);
1557 atomic_set(&config->recv_threads, 0);
1558 init_waitqueue_head(&config->recv_wq);
1559 init_waitqueue_head(&config->conn_wait);
1560 config->blksize_bits = NBD_DEF_BLKSIZE_BITS;
1561 atomic_set(&config->live_connections, 0);
1562 nbd->config = config;
1563 refcount_set(&nbd->config_refs, 1);
1568 static int nbd_open(struct gendisk *disk, blk_mode_t mode)
1570 struct nbd_device *nbd;
1571 struct nbd_config *config;
1574 mutex_lock(&nbd_index_mutex);
1575 nbd = disk->private_data;
1580 if (!refcount_inc_not_zero(&nbd->refs)) {
1585 config = nbd_get_config_unlocked(nbd);
1587 mutex_lock(&nbd->config_lock);
1588 if (refcount_inc_not_zero(&nbd->config_refs)) {
1589 mutex_unlock(&nbd->config_lock);
1592 ret = nbd_alloc_and_init_config(nbd);
1594 mutex_unlock(&nbd->config_lock);
1598 refcount_inc(&nbd->refs);
1599 mutex_unlock(&nbd->config_lock);
1601 set_bit(GD_NEED_PART_SCAN, &disk->state);
1602 } else if (nbd_disconnected(config)) {
1604 set_bit(GD_NEED_PART_SCAN, &disk->state);
1607 mutex_unlock(&nbd_index_mutex);
1611 static void nbd_release(struct gendisk *disk)
1613 struct nbd_device *nbd = disk->private_data;
1615 if (test_bit(NBD_RT_DISCONNECT_ON_CLOSE, &nbd->config->runtime_flags) &&
1616 disk_openers(disk) == 0)
1617 nbd_disconnect_and_put(nbd);
1619 nbd_config_put(nbd);
1623 static void nbd_free_disk(struct gendisk *disk)
1625 struct nbd_device *nbd = disk->private_data;
1630 static const struct block_device_operations nbd_fops =
1632 .owner = THIS_MODULE,
1634 .release = nbd_release,
1636 .compat_ioctl = nbd_ioctl,
1637 .free_disk = nbd_free_disk,
1640 #if IS_ENABLED(CONFIG_DEBUG_FS)
1642 static int nbd_dbg_tasks_show(struct seq_file *s, void *unused)
1644 struct nbd_device *nbd = s->private;
1647 seq_printf(s, "recv: %d\n", nbd->pid);
1652 DEFINE_SHOW_ATTRIBUTE(nbd_dbg_tasks);
1654 static int nbd_dbg_flags_show(struct seq_file *s, void *unused)
1656 struct nbd_device *nbd = s->private;
1657 u32 flags = nbd->config->flags;
1659 seq_printf(s, "Hex: 0x%08x\n\n", flags);
1661 seq_puts(s, "Known flags:\n");
1663 if (flags & NBD_FLAG_HAS_FLAGS)
1664 seq_puts(s, "NBD_FLAG_HAS_FLAGS\n");
1665 if (flags & NBD_FLAG_READ_ONLY)
1666 seq_puts(s, "NBD_FLAG_READ_ONLY\n");
1667 if (flags & NBD_FLAG_SEND_FLUSH)
1668 seq_puts(s, "NBD_FLAG_SEND_FLUSH\n");
1669 if (flags & NBD_FLAG_SEND_FUA)
1670 seq_puts(s, "NBD_FLAG_SEND_FUA\n");
1671 if (flags & NBD_FLAG_SEND_TRIM)
1672 seq_puts(s, "NBD_FLAG_SEND_TRIM\n");
1677 DEFINE_SHOW_ATTRIBUTE(nbd_dbg_flags);
1679 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1682 struct nbd_config *config = nbd->config;
1687 dir = debugfs_create_dir(nbd_name(nbd), nbd_dbg_dir);
1689 dev_err(nbd_to_dev(nbd), "Failed to create debugfs dir for '%s'\n",
1693 config->dbg_dir = dir;
1695 debugfs_create_file("tasks", 0444, dir, nbd, &nbd_dbg_tasks_fops);
1696 debugfs_create_u64("size_bytes", 0444, dir, &config->bytesize);
1697 debugfs_create_u32("timeout", 0444, dir, &nbd->tag_set.timeout);
1698 debugfs_create_u32("blocksize_bits", 0444, dir, &config->blksize_bits);
1699 debugfs_create_file("flags", 0444, dir, nbd, &nbd_dbg_flags_fops);
1704 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1706 debugfs_remove_recursive(nbd->config->dbg_dir);
1709 static int nbd_dbg_init(void)
1711 struct dentry *dbg_dir;
1713 dbg_dir = debugfs_create_dir("nbd", NULL);
1714 if (IS_ERR(dbg_dir))
1717 nbd_dbg_dir = dbg_dir;
1722 static void nbd_dbg_close(void)
1724 debugfs_remove_recursive(nbd_dbg_dir);
1727 #else /* IS_ENABLED(CONFIG_DEBUG_FS) */
1729 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1734 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1738 static int nbd_dbg_init(void)
1743 static void nbd_dbg_close(void)
1749 static int nbd_init_request(struct blk_mq_tag_set *set, struct request *rq,
1750 unsigned int hctx_idx, unsigned int numa_node)
1752 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(rq);
1753 cmd->nbd = set->driver_data;
1755 mutex_init(&cmd->lock);
1759 static const struct blk_mq_ops nbd_mq_ops = {
1760 .queue_rq = nbd_queue_rq,
1761 .complete = nbd_complete_rq,
1762 .init_request = nbd_init_request,
1763 .timeout = nbd_xmit_timeout,
1766 static struct nbd_device *nbd_dev_add(int index, unsigned int refs)
1768 struct nbd_device *nbd;
1769 struct gendisk *disk;
1772 nbd = kzalloc(sizeof(struct nbd_device), GFP_KERNEL);
1776 nbd->tag_set.ops = &nbd_mq_ops;
1777 nbd->tag_set.nr_hw_queues = 1;
1778 nbd->tag_set.queue_depth = 128;
1779 nbd->tag_set.numa_node = NUMA_NO_NODE;
1780 nbd->tag_set.cmd_size = sizeof(struct nbd_cmd);
1781 nbd->tag_set.flags = BLK_MQ_F_SHOULD_MERGE |
1783 nbd->tag_set.driver_data = nbd;
1784 INIT_WORK(&nbd->remove_work, nbd_dev_remove_work);
1785 nbd->backend = NULL;
1787 err = blk_mq_alloc_tag_set(&nbd->tag_set);
1791 mutex_lock(&nbd_index_mutex);
1793 err = idr_alloc(&nbd_index_idr, nbd, index, index + 1,
1798 err = idr_alloc(&nbd_index_idr, nbd, 0,
1799 (MINORMASK >> part_shift) + 1, GFP_KERNEL);
1804 mutex_unlock(&nbd_index_mutex);
1808 disk = blk_mq_alloc_disk(&nbd->tag_set, NULL);
1810 err = PTR_ERR(disk);
1815 nbd->recv_workq = alloc_workqueue("nbd%d-recv",
1816 WQ_MEM_RECLAIM | WQ_HIGHPRI |
1817 WQ_UNBOUND, 0, nbd->index);
1818 if (!nbd->recv_workq) {
1819 dev_err(disk_to_dev(nbd->disk), "Could not allocate knbd recv work queue.\n");
1825 * Tell the block layer that we are not a rotational device
1827 blk_queue_flag_set(QUEUE_FLAG_NONROT, disk->queue);
1828 disk->queue->limits.discard_granularity = 0;
1829 blk_queue_max_discard_sectors(disk->queue, 0);
1830 blk_queue_max_segment_size(disk->queue, UINT_MAX);
1831 blk_queue_max_segments(disk->queue, USHRT_MAX);
1832 blk_queue_max_hw_sectors(disk->queue, 65536);
1833 disk->queue->limits.max_sectors = 256;
1835 mutex_init(&nbd->config_lock);
1836 refcount_set(&nbd->config_refs, 0);
1838 * Start out with a zero references to keep other threads from using
1839 * this device until it is fully initialized.
1841 refcount_set(&nbd->refs, 0);
1842 INIT_LIST_HEAD(&nbd->list);
1843 disk->major = NBD_MAJOR;
1844 disk->first_minor = index << part_shift;
1845 disk->minors = 1 << part_shift;
1846 disk->fops = &nbd_fops;
1847 disk->private_data = nbd;
1848 sprintf(disk->disk_name, "nbd%d", index);
1849 err = add_disk(disk);
1854 * Now publish the device.
1856 refcount_set(&nbd->refs, refs);
1857 nbd_total_devices++;
1861 destroy_workqueue(nbd->recv_workq);
1865 mutex_lock(&nbd_index_mutex);
1866 idr_remove(&nbd_index_idr, index);
1867 mutex_unlock(&nbd_index_mutex);
1869 blk_mq_free_tag_set(&nbd->tag_set);
1873 return ERR_PTR(err);
1876 static struct nbd_device *nbd_find_get_unused(void)
1878 struct nbd_device *nbd;
1881 lockdep_assert_held(&nbd_index_mutex);
1883 idr_for_each_entry(&nbd_index_idr, nbd, id) {
1884 if (refcount_read(&nbd->config_refs) ||
1885 test_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags))
1887 if (refcount_inc_not_zero(&nbd->refs))
1894 /* Netlink interface. */
1895 static const struct nla_policy nbd_attr_policy[NBD_ATTR_MAX + 1] = {
1896 [NBD_ATTR_INDEX] = { .type = NLA_U32 },
1897 [NBD_ATTR_SIZE_BYTES] = { .type = NLA_U64 },
1898 [NBD_ATTR_BLOCK_SIZE_BYTES] = { .type = NLA_U64 },
1899 [NBD_ATTR_TIMEOUT] = { .type = NLA_U64 },
1900 [NBD_ATTR_SERVER_FLAGS] = { .type = NLA_U64 },
1901 [NBD_ATTR_CLIENT_FLAGS] = { .type = NLA_U64 },
1902 [NBD_ATTR_SOCKETS] = { .type = NLA_NESTED},
1903 [NBD_ATTR_DEAD_CONN_TIMEOUT] = { .type = NLA_U64 },
1904 [NBD_ATTR_DEVICE_LIST] = { .type = NLA_NESTED},
1905 [NBD_ATTR_BACKEND_IDENTIFIER] = { .type = NLA_STRING},
1908 static const struct nla_policy nbd_sock_policy[NBD_SOCK_MAX + 1] = {
1909 [NBD_SOCK_FD] = { .type = NLA_U32 },
1912 /* We don't use this right now since we don't parse the incoming list, but we
1913 * still want it here so userspace knows what to expect.
1915 static const struct nla_policy __attribute__((unused))
1916 nbd_device_policy[NBD_DEVICE_ATTR_MAX + 1] = {
1917 [NBD_DEVICE_INDEX] = { .type = NLA_U32 },
1918 [NBD_DEVICE_CONNECTED] = { .type = NLA_U8 },
1921 static int nbd_genl_size_set(struct genl_info *info, struct nbd_device *nbd)
1923 struct nbd_config *config = nbd->config;
1924 u64 bsize = nbd_blksize(config);
1925 u64 bytes = config->bytesize;
1927 if (info->attrs[NBD_ATTR_SIZE_BYTES])
1928 bytes = nla_get_u64(info->attrs[NBD_ATTR_SIZE_BYTES]);
1930 if (info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES])
1931 bsize = nla_get_u64(info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]);
1933 if (bytes != config->bytesize || bsize != nbd_blksize(config))
1934 return nbd_set_size(nbd, bytes, bsize);
1938 static int nbd_genl_connect(struct sk_buff *skb, struct genl_info *info)
1940 struct nbd_device *nbd;
1941 struct nbd_config *config;
1944 bool put_dev = false;
1946 if (!netlink_capable(skb, CAP_SYS_ADMIN))
1949 if (info->attrs[NBD_ATTR_INDEX]) {
1950 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1953 * Too big first_minor can cause duplicate creation of
1954 * sysfs files/links, since index << part_shift might overflow, or
1955 * MKDEV() expect that the max bits of first_minor is 20.
1957 if (index < 0 || index > MINORMASK >> part_shift) {
1958 pr_err("illegal input index %d\n", index);
1962 if (GENL_REQ_ATTR_CHECK(info, NBD_ATTR_SOCKETS)) {
1963 pr_err("must specify at least one socket\n");
1966 if (GENL_REQ_ATTR_CHECK(info, NBD_ATTR_SIZE_BYTES)) {
1967 pr_err("must specify a size in bytes for the device\n");
1971 mutex_lock(&nbd_index_mutex);
1973 nbd = nbd_find_get_unused();
1975 nbd = idr_find(&nbd_index_idr, index);
1977 if ((test_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags) &&
1978 test_bit(NBD_DISCONNECT_REQUESTED, &nbd->flags)) ||
1979 !refcount_inc_not_zero(&nbd->refs)) {
1980 mutex_unlock(&nbd_index_mutex);
1981 pr_err("device at index %d is going down\n",
1987 mutex_unlock(&nbd_index_mutex);
1990 nbd = nbd_dev_add(index, 2);
1992 pr_err("failed to add new device\n");
1993 return PTR_ERR(nbd);
1997 mutex_lock(&nbd->config_lock);
1998 if (refcount_read(&nbd->config_refs)) {
1999 mutex_unlock(&nbd->config_lock);
2003 pr_err("nbd%d already in use\n", index);
2007 ret = nbd_alloc_and_init_config(nbd);
2009 mutex_unlock(&nbd->config_lock);
2011 pr_err("couldn't allocate config\n");
2015 config = nbd->config;
2016 set_bit(NBD_RT_BOUND, &config->runtime_flags);
2017 ret = nbd_genl_size_set(info, nbd);
2021 if (info->attrs[NBD_ATTR_TIMEOUT])
2022 nbd_set_cmd_timeout(nbd,
2023 nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]));
2024 if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
2025 config->dead_conn_timeout =
2026 nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
2027 config->dead_conn_timeout *= HZ;
2029 if (info->attrs[NBD_ATTR_SERVER_FLAGS])
2031 nla_get_u64(info->attrs[NBD_ATTR_SERVER_FLAGS]);
2032 if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
2033 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
2034 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
2036 * We have 1 ref to keep the device around, and then 1
2037 * ref for our current operation here, which will be
2038 * inherited by the config. If we already have
2039 * DESTROY_ON_DISCONNECT set then we know we don't have
2040 * that extra ref already held so we don't need the
2043 if (!test_and_set_bit(NBD_DESTROY_ON_DISCONNECT,
2047 if (test_and_clear_bit(NBD_DESTROY_ON_DISCONNECT,
2049 refcount_inc(&nbd->refs);
2051 if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
2052 set_bit(NBD_RT_DISCONNECT_ON_CLOSE,
2053 &config->runtime_flags);
2057 if (info->attrs[NBD_ATTR_SOCKETS]) {
2058 struct nlattr *attr;
2061 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
2063 struct nlattr *socks[NBD_SOCK_MAX+1];
2065 if (nla_type(attr) != NBD_SOCK_ITEM) {
2066 pr_err("socks must be embedded in a SOCK_ITEM attr\n");
2070 ret = nla_parse_nested_deprecated(socks, NBD_SOCK_MAX,
2075 pr_err("error processing sock list\n");
2079 if (!socks[NBD_SOCK_FD])
2081 fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
2082 ret = nbd_add_socket(nbd, fd, true);
2087 ret = nbd_start_device(nbd);
2090 if (info->attrs[NBD_ATTR_BACKEND_IDENTIFIER]) {
2091 nbd->backend = nla_strdup(info->attrs[NBD_ATTR_BACKEND_IDENTIFIER],
2093 if (!nbd->backend) {
2098 ret = device_create_file(disk_to_dev(nbd->disk), &backend_attr);
2100 dev_err(disk_to_dev(nbd->disk),
2101 "device_create_file failed for backend!\n");
2104 set_bit(NBD_RT_HAS_BACKEND_FILE, &config->runtime_flags);
2106 mutex_unlock(&nbd->config_lock);
2108 set_bit(NBD_RT_HAS_CONFIG_REF, &config->runtime_flags);
2109 refcount_inc(&nbd->config_refs);
2110 nbd_connect_reply(info, nbd->index);
2112 nbd_config_put(nbd);
2118 static void nbd_disconnect_and_put(struct nbd_device *nbd)
2120 mutex_lock(&nbd->config_lock);
2121 nbd_disconnect(nbd);
2123 wake_up(&nbd->config->conn_wait);
2125 * Make sure recv thread has finished, we can safely call nbd_clear_que()
2126 * to cancel the inflight I/Os.
2128 flush_workqueue(nbd->recv_workq);
2130 nbd->task_setup = NULL;
2131 mutex_unlock(&nbd->config_lock);
2133 if (test_and_clear_bit(NBD_RT_HAS_CONFIG_REF,
2134 &nbd->config->runtime_flags))
2135 nbd_config_put(nbd);
2138 static int nbd_genl_disconnect(struct sk_buff *skb, struct genl_info *info)
2140 struct nbd_device *nbd;
2143 if (!netlink_capable(skb, CAP_SYS_ADMIN))
2146 if (GENL_REQ_ATTR_CHECK(info, NBD_ATTR_INDEX)) {
2147 pr_err("must specify an index to disconnect\n");
2150 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2151 mutex_lock(&nbd_index_mutex);
2152 nbd = idr_find(&nbd_index_idr, index);
2154 mutex_unlock(&nbd_index_mutex);
2155 pr_err("couldn't find device at index %d\n", index);
2158 if (!refcount_inc_not_zero(&nbd->refs)) {
2159 mutex_unlock(&nbd_index_mutex);
2160 pr_err("device at index %d is going down\n", index);
2163 mutex_unlock(&nbd_index_mutex);
2164 if (!refcount_inc_not_zero(&nbd->config_refs))
2166 nbd_disconnect_and_put(nbd);
2167 nbd_config_put(nbd);
2173 static int nbd_genl_reconfigure(struct sk_buff *skb, struct genl_info *info)
2175 struct nbd_device *nbd = NULL;
2176 struct nbd_config *config;
2179 bool put_dev = false;
2181 if (!netlink_capable(skb, CAP_SYS_ADMIN))
2184 if (GENL_REQ_ATTR_CHECK(info, NBD_ATTR_INDEX)) {
2185 pr_err("must specify a device to reconfigure\n");
2188 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2189 mutex_lock(&nbd_index_mutex);
2190 nbd = idr_find(&nbd_index_idr, index);
2192 mutex_unlock(&nbd_index_mutex);
2193 pr_err("couldn't find a device at index %d\n", index);
2197 if (info->attrs[NBD_ATTR_BACKEND_IDENTIFIER]) {
2198 if (nla_strcmp(info->attrs[NBD_ATTR_BACKEND_IDENTIFIER],
2200 mutex_unlock(&nbd_index_mutex);
2201 dev_err(nbd_to_dev(nbd),
2202 "backend image doesn't match with %s\n",
2207 mutex_unlock(&nbd_index_mutex);
2208 dev_err(nbd_to_dev(nbd), "must specify backend\n");
2212 if (!refcount_inc_not_zero(&nbd->refs)) {
2213 mutex_unlock(&nbd_index_mutex);
2214 pr_err("device at index %d is going down\n", index);
2217 mutex_unlock(&nbd_index_mutex);
2219 config = nbd_get_config_unlocked(nbd);
2221 dev_err(nbd_to_dev(nbd),
2222 "not configured, cannot reconfigure\n");
2227 mutex_lock(&nbd->config_lock);
2228 if (!test_bit(NBD_RT_BOUND, &config->runtime_flags) ||
2230 dev_err(nbd_to_dev(nbd),
2231 "not configured, cannot reconfigure\n");
2236 ret = nbd_genl_size_set(info, nbd);
2240 if (info->attrs[NBD_ATTR_TIMEOUT])
2241 nbd_set_cmd_timeout(nbd,
2242 nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]));
2243 if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
2244 config->dead_conn_timeout =
2245 nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
2246 config->dead_conn_timeout *= HZ;
2248 if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
2249 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
2250 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
2251 if (!test_and_set_bit(NBD_DESTROY_ON_DISCONNECT,
2255 if (test_and_clear_bit(NBD_DESTROY_ON_DISCONNECT,
2257 refcount_inc(&nbd->refs);
2260 if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
2261 set_bit(NBD_RT_DISCONNECT_ON_CLOSE,
2262 &config->runtime_flags);
2264 clear_bit(NBD_RT_DISCONNECT_ON_CLOSE,
2265 &config->runtime_flags);
2269 if (info->attrs[NBD_ATTR_SOCKETS]) {
2270 struct nlattr *attr;
2273 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
2275 struct nlattr *socks[NBD_SOCK_MAX+1];
2277 if (nla_type(attr) != NBD_SOCK_ITEM) {
2278 pr_err("socks must be embedded in a SOCK_ITEM attr\n");
2282 ret = nla_parse_nested_deprecated(socks, NBD_SOCK_MAX,
2287 pr_err("error processing sock list\n");
2291 if (!socks[NBD_SOCK_FD])
2293 fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
2294 ret = nbd_reconnect_socket(nbd, fd);
2300 dev_info(nbd_to_dev(nbd), "reconnected socket\n");
2304 mutex_unlock(&nbd->config_lock);
2305 nbd_config_put(nbd);
2312 static const struct genl_small_ops nbd_connect_genl_ops[] = {
2314 .cmd = NBD_CMD_CONNECT,
2315 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2316 .doit = nbd_genl_connect,
2319 .cmd = NBD_CMD_DISCONNECT,
2320 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2321 .doit = nbd_genl_disconnect,
2324 .cmd = NBD_CMD_RECONFIGURE,
2325 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2326 .doit = nbd_genl_reconfigure,
2329 .cmd = NBD_CMD_STATUS,
2330 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2331 .doit = nbd_genl_status,
2335 static const struct genl_multicast_group nbd_mcast_grps[] = {
2336 { .name = NBD_GENL_MCAST_GROUP_NAME, },
2339 static struct genl_family nbd_genl_family __ro_after_init = {
2341 .name = NBD_GENL_FAMILY_NAME,
2342 .version = NBD_GENL_VERSION,
2343 .module = THIS_MODULE,
2344 .small_ops = nbd_connect_genl_ops,
2345 .n_small_ops = ARRAY_SIZE(nbd_connect_genl_ops),
2346 .resv_start_op = NBD_CMD_STATUS + 1,
2347 .maxattr = NBD_ATTR_MAX,
2349 .policy = nbd_attr_policy,
2350 .mcgrps = nbd_mcast_grps,
2351 .n_mcgrps = ARRAY_SIZE(nbd_mcast_grps),
2353 MODULE_ALIAS_GENL_FAMILY(NBD_GENL_FAMILY_NAME);
2355 static int populate_nbd_status(struct nbd_device *nbd, struct sk_buff *reply)
2357 struct nlattr *dev_opt;
2361 /* This is a little racey, but for status it's ok. The
2362 * reason we don't take a ref here is because we can't
2363 * take a ref in the index == -1 case as we would need
2364 * to put under the nbd_index_mutex, which could
2365 * deadlock if we are configured to remove ourselves
2366 * once we're disconnected.
2368 if (refcount_read(&nbd->config_refs))
2370 dev_opt = nla_nest_start_noflag(reply, NBD_DEVICE_ITEM);
2373 ret = nla_put_u32(reply, NBD_DEVICE_INDEX, nbd->index);
2376 ret = nla_put_u8(reply, NBD_DEVICE_CONNECTED,
2380 nla_nest_end(reply, dev_opt);
2384 static int status_cb(int id, void *ptr, void *data)
2386 struct nbd_device *nbd = ptr;
2387 return populate_nbd_status(nbd, (struct sk_buff *)data);
2390 static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info)
2392 struct nlattr *dev_list;
2393 struct sk_buff *reply;
2399 if (info->attrs[NBD_ATTR_INDEX])
2400 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2402 mutex_lock(&nbd_index_mutex);
2404 msg_size = nla_total_size(nla_attr_size(sizeof(u32)) +
2405 nla_attr_size(sizeof(u8)));
2406 msg_size *= (index == -1) ? nbd_total_devices : 1;
2408 reply = genlmsg_new(msg_size, GFP_KERNEL);
2411 reply_head = genlmsg_put_reply(reply, info, &nbd_genl_family, 0,
2418 dev_list = nla_nest_start_noflag(reply, NBD_ATTR_DEVICE_LIST);
2420 ret = idr_for_each(&nbd_index_idr, &status_cb, reply);
2426 struct nbd_device *nbd;
2427 nbd = idr_find(&nbd_index_idr, index);
2429 ret = populate_nbd_status(nbd, reply);
2436 nla_nest_end(reply, dev_list);
2437 genlmsg_end(reply, reply_head);
2438 ret = genlmsg_reply(reply, info);
2440 mutex_unlock(&nbd_index_mutex);
2444 static void nbd_connect_reply(struct genl_info *info, int index)
2446 struct sk_buff *skb;
2450 skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2453 msg_head = genlmsg_put_reply(skb, info, &nbd_genl_family, 0,
2459 ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2464 genlmsg_end(skb, msg_head);
2465 genlmsg_reply(skb, info);
2468 static void nbd_mcast_index(int index)
2470 struct sk_buff *skb;
2474 skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2477 msg_head = genlmsg_put(skb, 0, 0, &nbd_genl_family, 0,
2483 ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2488 genlmsg_end(skb, msg_head);
2489 genlmsg_multicast(&nbd_genl_family, skb, 0, 0, GFP_KERNEL);
2492 static void nbd_dead_link_work(struct work_struct *work)
2494 struct link_dead_args *args = container_of(work, struct link_dead_args,
2496 nbd_mcast_index(args->index);
2500 static int __init nbd_init(void)
2504 BUILD_BUG_ON(sizeof(struct nbd_request) != 28);
2507 pr_err("max_part must be >= 0\n");
2513 part_shift = fls(max_part);
2516 * Adjust max_part according to part_shift as it is exported
2517 * to user space so that user can know the max number of
2518 * partition kernel should be able to manage.
2520 * Note that -1 is required because partition 0 is reserved
2521 * for the whole disk.
2523 max_part = (1UL << part_shift) - 1;
2526 if ((1UL << part_shift) > DISK_MAX_PARTS)
2529 if (nbds_max > 1UL << (MINORBITS - part_shift))
2532 if (register_blkdev(NBD_MAJOR, "nbd"))
2535 nbd_del_wq = alloc_workqueue("nbd-del", WQ_UNBOUND, 0);
2537 unregister_blkdev(NBD_MAJOR, "nbd");
2541 if (genl_register_family(&nbd_genl_family)) {
2542 destroy_workqueue(nbd_del_wq);
2543 unregister_blkdev(NBD_MAJOR, "nbd");
2548 for (i = 0; i < nbds_max; i++)
2553 static int nbd_exit_cb(int id, void *ptr, void *data)
2555 struct list_head *list = (struct list_head *)data;
2556 struct nbd_device *nbd = ptr;
2558 /* Skip nbd that is being removed asynchronously */
2559 if (refcount_read(&nbd->refs))
2560 list_add_tail(&nbd->list, list);
2565 static void __exit nbd_cleanup(void)
2567 struct nbd_device *nbd;
2568 LIST_HEAD(del_list);
2571 * Unregister netlink interface prior to waiting
2572 * for the completion of netlink commands.
2574 genl_unregister_family(&nbd_genl_family);
2578 mutex_lock(&nbd_index_mutex);
2579 idr_for_each(&nbd_index_idr, &nbd_exit_cb, &del_list);
2580 mutex_unlock(&nbd_index_mutex);
2582 while (!list_empty(&del_list)) {
2583 nbd = list_first_entry(&del_list, struct nbd_device, list);
2584 list_del_init(&nbd->list);
2585 if (refcount_read(&nbd->config_refs))
2586 pr_err("possibly leaking nbd_config (ref %d)\n",
2587 refcount_read(&nbd->config_refs));
2588 if (refcount_read(&nbd->refs) != 1)
2589 pr_err("possibly leaking a device\n");
2593 /* Also wait for nbd_dev_remove_work() completes */
2594 destroy_workqueue(nbd_del_wq);
2596 idr_destroy(&nbd_index_idr);
2597 unregister_blkdev(NBD_MAJOR, "nbd");
2600 module_init(nbd_init);
2601 module_exit(nbd_cleanup);
2603 MODULE_DESCRIPTION("Network Block Device");
2604 MODULE_LICENSE("GPL");
2606 module_param(nbds_max, int, 0444);
2607 MODULE_PARM_DESC(nbds_max, "number of network block devices to initialize (default: 16)");
2608 module_param(max_part, int, 0444);
2609 MODULE_PARM_DESC(max_part, "number of partitions per device (default: 16)");