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 enum blk_eh_timer_return nbd_xmit_timeout(struct request *req)
400 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
401 struct nbd_device *nbd = cmd->nbd;
402 struct nbd_config *config;
404 if (!mutex_trylock(&cmd->lock))
405 return BLK_EH_RESET_TIMER;
407 if (!test_bit(NBD_CMD_INFLIGHT, &cmd->flags)) {
408 mutex_unlock(&cmd->lock);
412 if (!refcount_inc_not_zero(&nbd->config_refs)) {
413 cmd->status = BLK_STS_TIMEOUT;
414 __clear_bit(NBD_CMD_INFLIGHT, &cmd->flags);
415 mutex_unlock(&cmd->lock);
418 config = nbd->config;
420 if (config->num_connections > 1 ||
421 (config->num_connections == 1 && nbd->tag_set.timeout)) {
422 dev_err_ratelimited(nbd_to_dev(nbd),
423 "Connection timed out, retrying (%d/%d alive)\n",
424 atomic_read(&config->live_connections),
425 config->num_connections);
427 * Hooray we have more connections, requeue this IO, the submit
428 * path will put it on a real connection. Or if only one
429 * connection is configured, the submit path will wait util
430 * a new connection is reconfigured or util dead timeout.
433 if (cmd->index < config->num_connections) {
434 struct nbd_sock *nsock =
435 config->socks[cmd->index];
436 mutex_lock(&nsock->tx_lock);
437 /* We can have multiple outstanding requests, so
438 * we don't want to mark the nsock dead if we've
439 * already reconnected with a new socket, so
440 * only mark it dead if its the same socket we
443 if (cmd->cookie == nsock->cookie)
444 nbd_mark_nsock_dead(nbd, nsock, 1);
445 mutex_unlock(&nsock->tx_lock);
447 mutex_unlock(&cmd->lock);
448 nbd_requeue_cmd(cmd);
454 if (!nbd->tag_set.timeout) {
456 * Userspace sets timeout=0 to disable socket disconnection,
457 * so just warn and reset the timer.
459 struct nbd_sock *nsock = config->socks[cmd->index];
461 dev_info(nbd_to_dev(nbd), "Possible stuck request %p: control (%s@%llu,%uB). Runtime %u seconds\n",
462 req, nbdcmd_to_ascii(req_to_nbd_cmd_type(req)),
463 (unsigned long long)blk_rq_pos(req) << 9,
464 blk_rq_bytes(req), (req->timeout / HZ) * cmd->retries);
466 mutex_lock(&nsock->tx_lock);
467 if (cmd->cookie != nsock->cookie) {
468 nbd_requeue_cmd(cmd);
469 mutex_unlock(&nsock->tx_lock);
470 mutex_unlock(&cmd->lock);
474 mutex_unlock(&nsock->tx_lock);
475 mutex_unlock(&cmd->lock);
477 return BLK_EH_RESET_TIMER;
480 dev_err_ratelimited(nbd_to_dev(nbd), "Connection timed out\n");
481 set_bit(NBD_RT_TIMEDOUT, &config->runtime_flags);
482 cmd->status = BLK_STS_IOERR;
483 __clear_bit(NBD_CMD_INFLIGHT, &cmd->flags);
484 mutex_unlock(&cmd->lock);
488 blk_mq_complete_request(req);
493 * Send or receive packet. Return a positive value on success and
494 * negtive value on failue, and never return 0.
496 static int sock_xmit(struct nbd_device *nbd, int index, int send,
497 struct iov_iter *iter, int msg_flags, int *sent)
499 struct nbd_config *config = nbd->config;
500 struct socket *sock = config->socks[index]->sock;
503 unsigned int noreclaim_flag;
505 if (unlikely(!sock)) {
506 dev_err_ratelimited(disk_to_dev(nbd->disk),
507 "Attempted %s on closed socket in sock_xmit\n",
508 (send ? "send" : "recv"));
512 msg.msg_iter = *iter;
514 noreclaim_flag = memalloc_noreclaim_save();
516 sock->sk->sk_allocation = GFP_NOIO | __GFP_MEMALLOC;
517 sock->sk->sk_use_task_frag = false;
520 msg.msg_control = NULL;
521 msg.msg_controllen = 0;
522 msg.msg_flags = msg_flags | MSG_NOSIGNAL;
525 result = sock_sendmsg(sock, &msg);
527 result = sock_recvmsg(sock, &msg, msg.msg_flags);
531 result = -EPIPE; /* short read */
536 } while (msg_data_left(&msg));
538 memalloc_noreclaim_restore(noreclaim_flag);
544 * Different settings for sk->sk_sndtimeo can result in different return values
545 * if there is a signal pending when we enter sendmsg, because reasons?
547 static inline int was_interrupted(int result)
549 return result == -ERESTARTSYS || result == -EINTR;
552 /* always call with the tx_lock held */
553 static int nbd_send_cmd(struct nbd_device *nbd, struct nbd_cmd *cmd, int index)
555 struct request *req = blk_mq_rq_from_pdu(cmd);
556 struct nbd_config *config = nbd->config;
557 struct nbd_sock *nsock = config->socks[index];
559 struct nbd_request request = {.magic = htonl(NBD_REQUEST_MAGIC)};
560 struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
561 struct iov_iter from;
562 unsigned long size = blk_rq_bytes(req);
566 u32 nbd_cmd_flags = 0;
567 int sent = nsock->sent, skip = 0;
569 iov_iter_kvec(&from, ITER_SOURCE, &iov, 1, sizeof(request));
571 type = req_to_nbd_cmd_type(req);
575 if (rq_data_dir(req) == WRITE &&
576 (config->flags & NBD_FLAG_READ_ONLY)) {
577 dev_err_ratelimited(disk_to_dev(nbd->disk),
578 "Write on read-only\n");
582 if (req->cmd_flags & REQ_FUA)
583 nbd_cmd_flags |= NBD_CMD_FLAG_FUA;
585 /* We did a partial send previously, and we at least sent the whole
586 * request struct, so just go and send the rest of the pages in the
590 if (sent >= sizeof(request)) {
591 skip = sent - sizeof(request);
593 /* initialize handle for tracing purposes */
594 handle = nbd_cmd_handle(cmd);
598 iov_iter_advance(&from, sent);
603 cmd->cookie = nsock->cookie;
605 request.type = htonl(type | nbd_cmd_flags);
606 if (type != NBD_CMD_FLUSH) {
607 request.from = cpu_to_be64((u64)blk_rq_pos(req) << 9);
608 request.len = htonl(size);
610 handle = nbd_cmd_handle(cmd);
611 request.cookie = cpu_to_be64(handle);
613 trace_nbd_send_request(&request, nbd->index, blk_mq_rq_from_pdu(cmd));
615 dev_dbg(nbd_to_dev(nbd), "request %p: sending control (%s@%llu,%uB)\n",
616 req, nbdcmd_to_ascii(type),
617 (unsigned long long)blk_rq_pos(req) << 9, blk_rq_bytes(req));
618 result = sock_xmit(nbd, index, 1, &from,
619 (type == NBD_CMD_WRITE) ? MSG_MORE : 0, &sent);
620 trace_nbd_header_sent(req, handle);
622 if (was_interrupted(result)) {
623 /* If we haven't sent anything we can just return BUSY,
624 * however if we have sent something we need to make
625 * sure we only allow this req to be sent until we are
629 nsock->pending = req;
632 set_bit(NBD_CMD_REQUEUED, &cmd->flags);
633 return BLK_STS_RESOURCE;
635 dev_err_ratelimited(disk_to_dev(nbd->disk),
636 "Send control failed (result %d)\n", result);
640 if (type != NBD_CMD_WRITE)
645 struct bio *next = bio->bi_next;
646 struct bvec_iter iter;
649 bio_for_each_segment(bvec, bio, iter) {
650 bool is_last = !next && bio_iter_last(bvec, iter);
651 int flags = is_last ? 0 : MSG_MORE;
653 dev_dbg(nbd_to_dev(nbd), "request %p: sending %d bytes data\n",
655 iov_iter_bvec(&from, ITER_SOURCE, &bvec, 1, bvec.bv_len);
657 if (skip >= iov_iter_count(&from)) {
658 skip -= iov_iter_count(&from);
661 iov_iter_advance(&from, skip);
664 result = sock_xmit(nbd, index, 1, &from, flags, &sent);
666 if (was_interrupted(result)) {
667 /* We've already sent the header, we
668 * have no choice but to set pending and
671 nsock->pending = req;
673 set_bit(NBD_CMD_REQUEUED, &cmd->flags);
674 return BLK_STS_RESOURCE;
676 dev_err(disk_to_dev(nbd->disk),
677 "Send data failed (result %d)\n",
682 * The completion might already have come in,
683 * so break for the last one instead of letting
684 * the iterator do it. This prevents use-after-free
693 trace_nbd_payload_sent(req, handle);
694 nsock->pending = NULL;
699 static int nbd_read_reply(struct nbd_device *nbd, int index,
700 struct nbd_reply *reply)
702 struct kvec iov = {.iov_base = reply, .iov_len = sizeof(*reply)};
707 iov_iter_kvec(&to, ITER_DEST, &iov, 1, sizeof(*reply));
708 result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
710 if (!nbd_disconnected(nbd->config))
711 dev_err(disk_to_dev(nbd->disk),
712 "Receive control failed (result %d)\n", result);
716 if (ntohl(reply->magic) != NBD_REPLY_MAGIC) {
717 dev_err(disk_to_dev(nbd->disk), "Wrong magic (0x%lx)\n",
718 (unsigned long)ntohl(reply->magic));
725 /* NULL returned = something went wrong, inform userspace */
726 static struct nbd_cmd *nbd_handle_reply(struct nbd_device *nbd, int index,
727 struct nbd_reply *reply)
731 struct request *req = NULL;
737 handle = be64_to_cpu(reply->cookie);
738 tag = nbd_handle_to_tag(handle);
739 hwq = blk_mq_unique_tag_to_hwq(tag);
740 if (hwq < nbd->tag_set.nr_hw_queues)
741 req = blk_mq_tag_to_rq(nbd->tag_set.tags[hwq],
742 blk_mq_unique_tag_to_tag(tag));
743 if (!req || !blk_mq_request_started(req)) {
744 dev_err(disk_to_dev(nbd->disk), "Unexpected reply (%d) %p\n",
746 return ERR_PTR(-ENOENT);
748 trace_nbd_header_received(req, handle);
749 cmd = blk_mq_rq_to_pdu(req);
751 mutex_lock(&cmd->lock);
752 if (!test_bit(NBD_CMD_INFLIGHT, &cmd->flags)) {
753 dev_err(disk_to_dev(nbd->disk), "Suspicious reply %d (status %u flags %lu)",
754 tag, cmd->status, cmd->flags);
758 if (cmd->index != index) {
759 dev_err(disk_to_dev(nbd->disk), "Unexpected reply %d from different sock %d (expected %d)",
760 tag, index, cmd->index);
764 if (cmd->cmd_cookie != nbd_handle_to_cookie(handle)) {
765 dev_err(disk_to_dev(nbd->disk), "Double reply on req %p, cmd_cookie %u, handle cookie %u\n",
766 req, cmd->cmd_cookie, nbd_handle_to_cookie(handle));
770 if (cmd->status != BLK_STS_OK) {
771 dev_err(disk_to_dev(nbd->disk), "Command already handled %p\n",
776 if (test_bit(NBD_CMD_REQUEUED, &cmd->flags)) {
777 dev_err(disk_to_dev(nbd->disk), "Raced with timeout on req %p\n",
782 if (ntohl(reply->error)) {
783 dev_err(disk_to_dev(nbd->disk), "Other side returned error (%d)\n",
784 ntohl(reply->error));
785 cmd->status = BLK_STS_IOERR;
789 dev_dbg(nbd_to_dev(nbd), "request %p: got reply\n", req);
790 if (rq_data_dir(req) != WRITE) {
791 struct req_iterator iter;
795 rq_for_each_segment(bvec, req, iter) {
796 iov_iter_bvec(&to, ITER_DEST, &bvec, 1, bvec.bv_len);
797 result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
799 dev_err(disk_to_dev(nbd->disk), "Receive data failed (result %d)\n",
802 * If we've disconnected, we need to make sure we
803 * complete this request, otherwise error out
804 * and let the timeout stuff handle resubmitting
805 * this request onto another connection.
807 if (nbd_disconnected(nbd->config)) {
808 cmd->status = BLK_STS_IOERR;
814 dev_dbg(nbd_to_dev(nbd), "request %p: got %d bytes data\n",
819 trace_nbd_payload_received(req, handle);
820 mutex_unlock(&cmd->lock);
821 return ret ? ERR_PTR(ret) : cmd;
824 static void recv_work(struct work_struct *work)
826 struct recv_thread_args *args = container_of(work,
827 struct recv_thread_args,
829 struct nbd_device *nbd = args->nbd;
830 struct nbd_config *config = nbd->config;
831 struct request_queue *q = nbd->disk->queue;
832 struct nbd_sock *nsock;
837 struct nbd_reply reply;
839 if (nbd_read_reply(nbd, args->index, &reply))
843 * Grab .q_usage_counter so request pool won't go away, then no
844 * request use-after-free is possible during nbd_handle_reply().
845 * If queue is frozen, there won't be any inflight requests, we
846 * needn't to handle the incoming garbage message.
848 if (!percpu_ref_tryget(&q->q_usage_counter)) {
849 dev_err(disk_to_dev(nbd->disk), "%s: no io inflight\n",
854 cmd = nbd_handle_reply(nbd, args->index, &reply);
856 percpu_ref_put(&q->q_usage_counter);
860 rq = blk_mq_rq_from_pdu(cmd);
861 if (likely(!blk_should_fake_timeout(rq->q))) {
864 mutex_lock(&cmd->lock);
865 complete = __test_and_clear_bit(NBD_CMD_INFLIGHT,
867 mutex_unlock(&cmd->lock);
869 blk_mq_complete_request(rq);
871 percpu_ref_put(&q->q_usage_counter);
874 nsock = config->socks[args->index];
875 mutex_lock(&nsock->tx_lock);
876 nbd_mark_nsock_dead(nbd, nsock, 1);
877 mutex_unlock(&nsock->tx_lock);
880 atomic_dec(&config->recv_threads);
881 wake_up(&config->recv_wq);
885 static bool nbd_clear_req(struct request *req, void *data)
887 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
889 /* don't abort one completed request */
890 if (blk_mq_request_completed(req))
893 mutex_lock(&cmd->lock);
894 if (!__test_and_clear_bit(NBD_CMD_INFLIGHT, &cmd->flags)) {
895 mutex_unlock(&cmd->lock);
898 cmd->status = BLK_STS_IOERR;
899 mutex_unlock(&cmd->lock);
901 blk_mq_complete_request(req);
905 static void nbd_clear_que(struct nbd_device *nbd)
907 blk_mq_quiesce_queue(nbd->disk->queue);
908 blk_mq_tagset_busy_iter(&nbd->tag_set, nbd_clear_req, NULL);
909 blk_mq_unquiesce_queue(nbd->disk->queue);
910 dev_dbg(disk_to_dev(nbd->disk), "queue cleared\n");
913 static int find_fallback(struct nbd_device *nbd, int index)
915 struct nbd_config *config = nbd->config;
917 struct nbd_sock *nsock = config->socks[index];
918 int fallback = nsock->fallback_index;
920 if (test_bit(NBD_RT_DISCONNECTED, &config->runtime_flags))
923 if (config->num_connections <= 1) {
924 dev_err_ratelimited(disk_to_dev(nbd->disk),
925 "Dead connection, failed to find a fallback\n");
929 if (fallback >= 0 && fallback < config->num_connections &&
930 !config->socks[fallback]->dead)
933 if (nsock->fallback_index < 0 ||
934 nsock->fallback_index >= config->num_connections ||
935 config->socks[nsock->fallback_index]->dead) {
937 for (i = 0; i < config->num_connections; i++) {
940 if (!config->socks[i]->dead) {
945 nsock->fallback_index = new_index;
947 dev_err_ratelimited(disk_to_dev(nbd->disk),
948 "Dead connection, failed to find a fallback\n");
952 new_index = nsock->fallback_index;
956 static int wait_for_reconnect(struct nbd_device *nbd)
958 struct nbd_config *config = nbd->config;
959 if (!config->dead_conn_timeout)
962 if (!wait_event_timeout(config->conn_wait,
963 test_bit(NBD_RT_DISCONNECTED,
964 &config->runtime_flags) ||
965 atomic_read(&config->live_connections) > 0,
966 config->dead_conn_timeout))
969 return !test_bit(NBD_RT_DISCONNECTED, &config->runtime_flags);
972 static int nbd_handle_cmd(struct nbd_cmd *cmd, int index)
974 struct request *req = blk_mq_rq_from_pdu(cmd);
975 struct nbd_device *nbd = cmd->nbd;
976 struct nbd_config *config;
977 struct nbd_sock *nsock;
980 if (!refcount_inc_not_zero(&nbd->config_refs)) {
981 dev_err_ratelimited(disk_to_dev(nbd->disk),
982 "Socks array is empty\n");
985 config = nbd->config;
987 if (index >= config->num_connections) {
988 dev_err_ratelimited(disk_to_dev(nbd->disk),
989 "Attempted send on invalid socket\n");
993 cmd->status = BLK_STS_OK;
995 nsock = config->socks[index];
996 mutex_lock(&nsock->tx_lock);
998 int old_index = index;
999 index = find_fallback(nbd, index);
1000 mutex_unlock(&nsock->tx_lock);
1002 if (wait_for_reconnect(nbd)) {
1006 /* All the sockets should already be down at this point,
1007 * we just want to make sure that DISCONNECTED is set so
1008 * any requests that come in that were queue'ed waiting
1009 * for the reconnect timer don't trigger the timer again
1010 * and instead just error out.
1013 nbd_config_put(nbd);
1019 /* Handle the case that we have a pending request that was partially
1020 * transmitted that _has_ to be serviced first. We need to call requeue
1021 * here so that it gets put _after_ the request that is already on the
1024 blk_mq_start_request(req);
1025 if (unlikely(nsock->pending && nsock->pending != req)) {
1026 nbd_requeue_cmd(cmd);
1031 * Some failures are related to the link going down, so anything that
1032 * returns EAGAIN can be retried on a different socket.
1034 ret = nbd_send_cmd(nbd, cmd, index);
1036 * Access to this flag is protected by cmd->lock, thus it's safe to set
1037 * the flag after nbd_send_cmd() succeed to send request to server.
1040 __set_bit(NBD_CMD_INFLIGHT, &cmd->flags);
1041 else if (ret == -EAGAIN) {
1042 dev_err_ratelimited(disk_to_dev(nbd->disk),
1043 "Request send failed, requeueing\n");
1044 nbd_mark_nsock_dead(nbd, nsock, 1);
1045 nbd_requeue_cmd(cmd);
1049 mutex_unlock(&nsock->tx_lock);
1050 nbd_config_put(nbd);
1054 static blk_status_t nbd_queue_rq(struct blk_mq_hw_ctx *hctx,
1055 const struct blk_mq_queue_data *bd)
1057 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(bd->rq);
1061 * Since we look at the bio's to send the request over the network we
1062 * need to make sure the completion work doesn't mark this request done
1063 * before we are done doing our send. This keeps us from dereferencing
1064 * freed data if we have particularly fast completions (ie we get the
1065 * completion before we exit sock_xmit on the last bvec) or in the case
1066 * that the server is misbehaving (or there was an error) before we're
1067 * done sending everything over the wire.
1069 mutex_lock(&cmd->lock);
1070 clear_bit(NBD_CMD_REQUEUED, &cmd->flags);
1072 /* We can be called directly from the user space process, which means we
1073 * could possibly have signals pending so our sendmsg will fail. In
1074 * this case we need to return that we are busy, otherwise error out as
1077 ret = nbd_handle_cmd(cmd, hctx->queue_num);
1079 ret = BLK_STS_IOERR;
1082 mutex_unlock(&cmd->lock);
1087 static struct socket *nbd_get_socket(struct nbd_device *nbd, unsigned long fd,
1090 struct socket *sock;
1093 sock = sockfd_lookup(fd, err);
1097 if (sock->ops->shutdown == sock_no_shutdown) {
1098 dev_err(disk_to_dev(nbd->disk), "Unsupported socket: shutdown callout must be supported.\n");
1107 static int nbd_add_socket(struct nbd_device *nbd, unsigned long arg,
1110 struct nbd_config *config = nbd->config;
1111 struct socket *sock;
1112 struct nbd_sock **socks;
1113 struct nbd_sock *nsock;
1116 /* Arg will be cast to int, check it to avoid overflow */
1119 sock = nbd_get_socket(nbd, arg, &err);
1124 * We need to make sure we don't get any errant requests while we're
1125 * reallocating the ->socks array.
1127 blk_mq_freeze_queue(nbd->disk->queue);
1129 if (!netlink && !nbd->task_setup &&
1130 !test_bit(NBD_RT_BOUND, &config->runtime_flags))
1131 nbd->task_setup = current;
1134 (nbd->task_setup != current ||
1135 test_bit(NBD_RT_BOUND, &config->runtime_flags))) {
1136 dev_err(disk_to_dev(nbd->disk),
1137 "Device being setup by another task");
1142 nsock = kzalloc(sizeof(*nsock), GFP_KERNEL);
1148 socks = krealloc(config->socks, (config->num_connections + 1) *
1149 sizeof(struct nbd_sock *), GFP_KERNEL);
1156 config->socks = socks;
1158 nsock->fallback_index = -1;
1159 nsock->dead = false;
1160 mutex_init(&nsock->tx_lock);
1162 nsock->pending = NULL;
1165 socks[config->num_connections++] = nsock;
1166 atomic_inc(&config->live_connections);
1167 blk_mq_unfreeze_queue(nbd->disk->queue);
1172 blk_mq_unfreeze_queue(nbd->disk->queue);
1177 static int nbd_reconnect_socket(struct nbd_device *nbd, unsigned long arg)
1179 struct nbd_config *config = nbd->config;
1180 struct socket *sock, *old;
1181 struct recv_thread_args *args;
1185 sock = nbd_get_socket(nbd, arg, &err);
1189 args = kzalloc(sizeof(*args), GFP_KERNEL);
1195 for (i = 0; i < config->num_connections; i++) {
1196 struct nbd_sock *nsock = config->socks[i];
1201 mutex_lock(&nsock->tx_lock);
1203 mutex_unlock(&nsock->tx_lock);
1206 sk_set_memalloc(sock->sk);
1207 if (nbd->tag_set.timeout)
1208 sock->sk->sk_sndtimeo = nbd->tag_set.timeout;
1209 atomic_inc(&config->recv_threads);
1210 refcount_inc(&nbd->config_refs);
1212 nsock->fallback_index = -1;
1214 nsock->dead = false;
1215 INIT_WORK(&args->work, recv_work);
1219 mutex_unlock(&nsock->tx_lock);
1222 clear_bit(NBD_RT_DISCONNECTED, &config->runtime_flags);
1224 /* We take the tx_mutex in an error path in the recv_work, so we
1225 * need to queue_work outside of the tx_mutex.
1227 queue_work(nbd->recv_workq, &args->work);
1229 atomic_inc(&config->live_connections);
1230 wake_up(&config->conn_wait);
1238 static void nbd_bdev_reset(struct nbd_device *nbd)
1240 if (disk_openers(nbd->disk) > 1)
1242 set_capacity(nbd->disk, 0);
1245 static void nbd_parse_flags(struct nbd_device *nbd)
1247 struct nbd_config *config = nbd->config;
1248 if (config->flags & NBD_FLAG_READ_ONLY)
1249 set_disk_ro(nbd->disk, true);
1251 set_disk_ro(nbd->disk, false);
1252 if (config->flags & NBD_FLAG_SEND_FLUSH) {
1253 if (config->flags & NBD_FLAG_SEND_FUA)
1254 blk_queue_write_cache(nbd->disk->queue, true, true);
1256 blk_queue_write_cache(nbd->disk->queue, true, false);
1259 blk_queue_write_cache(nbd->disk->queue, false, false);
1262 static void send_disconnects(struct nbd_device *nbd)
1264 struct nbd_config *config = nbd->config;
1265 struct nbd_request request = {
1266 .magic = htonl(NBD_REQUEST_MAGIC),
1267 .type = htonl(NBD_CMD_DISC),
1269 struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
1270 struct iov_iter from;
1273 for (i = 0; i < config->num_connections; i++) {
1274 struct nbd_sock *nsock = config->socks[i];
1276 iov_iter_kvec(&from, ITER_SOURCE, &iov, 1, sizeof(request));
1277 mutex_lock(&nsock->tx_lock);
1278 ret = sock_xmit(nbd, i, 1, &from, 0, NULL);
1280 dev_err(disk_to_dev(nbd->disk),
1281 "Send disconnect failed %d\n", ret);
1282 mutex_unlock(&nsock->tx_lock);
1286 static int nbd_disconnect(struct nbd_device *nbd)
1288 struct nbd_config *config = nbd->config;
1290 dev_info(disk_to_dev(nbd->disk), "NBD_DISCONNECT\n");
1291 set_bit(NBD_RT_DISCONNECT_REQUESTED, &config->runtime_flags);
1292 set_bit(NBD_DISCONNECT_REQUESTED, &nbd->flags);
1293 send_disconnects(nbd);
1297 static void nbd_clear_sock(struct nbd_device *nbd)
1301 nbd->task_setup = NULL;
1304 static void nbd_config_put(struct nbd_device *nbd)
1306 if (refcount_dec_and_mutex_lock(&nbd->config_refs,
1307 &nbd->config_lock)) {
1308 struct nbd_config *config = nbd->config;
1309 nbd_dev_dbg_close(nbd);
1310 invalidate_disk(nbd->disk);
1311 if (nbd->config->bytesize)
1312 kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
1313 if (test_and_clear_bit(NBD_RT_HAS_PID_FILE,
1314 &config->runtime_flags))
1315 device_remove_file(disk_to_dev(nbd->disk), &pid_attr);
1317 if (test_and_clear_bit(NBD_RT_HAS_BACKEND_FILE,
1318 &config->runtime_flags)) {
1319 device_remove_file(disk_to_dev(nbd->disk), &backend_attr);
1320 kfree(nbd->backend);
1321 nbd->backend = NULL;
1323 nbd_clear_sock(nbd);
1324 if (config->num_connections) {
1326 for (i = 0; i < config->num_connections; i++) {
1327 sockfd_put(config->socks[i]->sock);
1328 kfree(config->socks[i]);
1330 kfree(config->socks);
1335 nbd->tag_set.timeout = 0;
1336 nbd->disk->queue->limits.discard_granularity = 0;
1337 blk_queue_max_discard_sectors(nbd->disk->queue, 0);
1339 mutex_unlock(&nbd->config_lock);
1341 module_put(THIS_MODULE);
1345 static int nbd_start_device(struct nbd_device *nbd)
1347 struct nbd_config *config = nbd->config;
1348 int num_connections = config->num_connections;
1355 if (num_connections > 1 &&
1356 !(config->flags & NBD_FLAG_CAN_MULTI_CONN)) {
1357 dev_err(disk_to_dev(nbd->disk), "server does not support multiple connections per device.\n");
1361 blk_mq_update_nr_hw_queues(&nbd->tag_set, config->num_connections);
1362 nbd->pid = task_pid_nr(current);
1364 nbd_parse_flags(nbd);
1366 error = device_create_file(disk_to_dev(nbd->disk), &pid_attr);
1368 dev_err(disk_to_dev(nbd->disk), "device_create_file failed for pid!\n");
1371 set_bit(NBD_RT_HAS_PID_FILE, &config->runtime_flags);
1373 nbd_dev_dbg_init(nbd);
1374 for (i = 0; i < num_connections; i++) {
1375 struct recv_thread_args *args;
1377 args = kzalloc(sizeof(*args), GFP_KERNEL);
1381 * If num_connections is m (2 < m),
1382 * and NO.1 ~ NO.n(1 < n < m) kzallocs are successful.
1383 * But NO.(n + 1) failed. We still have n recv threads.
1384 * So, add flush_workqueue here to prevent recv threads
1385 * dropping the last config_refs and trying to destroy
1386 * the workqueue from inside the workqueue.
1389 flush_workqueue(nbd->recv_workq);
1392 sk_set_memalloc(config->socks[i]->sock->sk);
1393 if (nbd->tag_set.timeout)
1394 config->socks[i]->sock->sk->sk_sndtimeo =
1395 nbd->tag_set.timeout;
1396 atomic_inc(&config->recv_threads);
1397 refcount_inc(&nbd->config_refs);
1398 INIT_WORK(&args->work, recv_work);
1401 queue_work(nbd->recv_workq, &args->work);
1403 return nbd_set_size(nbd, config->bytesize, nbd_blksize(config));
1406 static int nbd_start_device_ioctl(struct nbd_device *nbd)
1408 struct nbd_config *config = nbd->config;
1411 ret = nbd_start_device(nbd);
1416 set_bit(GD_NEED_PART_SCAN, &nbd->disk->state);
1417 mutex_unlock(&nbd->config_lock);
1418 ret = wait_event_interruptible(config->recv_wq,
1419 atomic_read(&config->recv_threads) == 0);
1425 flush_workqueue(nbd->recv_workq);
1426 mutex_lock(&nbd->config_lock);
1427 nbd_bdev_reset(nbd);
1428 /* user requested, ignore socket errors */
1429 if (test_bit(NBD_RT_DISCONNECT_REQUESTED, &config->runtime_flags))
1431 if (test_bit(NBD_RT_TIMEDOUT, &config->runtime_flags))
1436 static void nbd_clear_sock_ioctl(struct nbd_device *nbd)
1438 nbd_clear_sock(nbd);
1439 disk_force_media_change(nbd->disk);
1440 nbd_bdev_reset(nbd);
1441 if (test_and_clear_bit(NBD_RT_HAS_CONFIG_REF,
1442 &nbd->config->runtime_flags))
1443 nbd_config_put(nbd);
1446 static void nbd_set_cmd_timeout(struct nbd_device *nbd, u64 timeout)
1448 nbd->tag_set.timeout = timeout * HZ;
1450 blk_queue_rq_timeout(nbd->disk->queue, timeout * HZ);
1452 blk_queue_rq_timeout(nbd->disk->queue, 30 * HZ);
1455 /* Must be called with config_lock held */
1456 static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
1457 unsigned int cmd, unsigned long arg)
1459 struct nbd_config *config = nbd->config;
1463 case NBD_DISCONNECT:
1464 return nbd_disconnect(nbd);
1465 case NBD_CLEAR_SOCK:
1466 nbd_clear_sock_ioctl(nbd);
1469 return nbd_add_socket(nbd, arg, false);
1470 case NBD_SET_BLKSIZE:
1471 return nbd_set_size(nbd, config->bytesize, arg);
1473 return nbd_set_size(nbd, arg, nbd_blksize(config));
1474 case NBD_SET_SIZE_BLOCKS:
1475 if (check_shl_overflow(arg, config->blksize_bits, &bytesize))
1477 return nbd_set_size(nbd, bytesize, nbd_blksize(config));
1478 case NBD_SET_TIMEOUT:
1479 nbd_set_cmd_timeout(nbd, arg);
1483 config->flags = arg;
1486 return nbd_start_device_ioctl(nbd);
1489 * This is for compatibility only. The queue is always cleared
1490 * by NBD_DO_IT or NBD_CLEAR_SOCK.
1493 case NBD_PRINT_DEBUG:
1495 * For compatibility only, we no longer keep a list of
1496 * outstanding requests.
1503 static int nbd_ioctl(struct block_device *bdev, blk_mode_t mode,
1504 unsigned int cmd, unsigned long arg)
1506 struct nbd_device *nbd = bdev->bd_disk->private_data;
1507 struct nbd_config *config = nbd->config;
1508 int error = -EINVAL;
1510 if (!capable(CAP_SYS_ADMIN))
1513 /* The block layer will pass back some non-nbd ioctls in case we have
1514 * special handling for them, but we don't so just return an error.
1516 if (_IOC_TYPE(cmd) != 0xab)
1519 mutex_lock(&nbd->config_lock);
1521 /* Don't allow ioctl operations on a nbd device that was created with
1522 * netlink, unless it's DISCONNECT or CLEAR_SOCK, which are fine.
1524 if (!test_bit(NBD_RT_BOUND, &config->runtime_flags) ||
1525 (cmd == NBD_DISCONNECT || cmd == NBD_CLEAR_SOCK))
1526 error = __nbd_ioctl(bdev, nbd, cmd, arg);
1528 dev_err(nbd_to_dev(nbd), "Cannot use ioctl interface on a netlink controlled device.\n");
1529 mutex_unlock(&nbd->config_lock);
1533 static int nbd_alloc_and_init_config(struct nbd_device *nbd)
1535 struct nbd_config *config;
1537 if (WARN_ON(nbd->config))
1540 if (!try_module_get(THIS_MODULE))
1543 config = kzalloc(sizeof(struct nbd_config), GFP_NOFS);
1545 module_put(THIS_MODULE);
1549 atomic_set(&config->recv_threads, 0);
1550 init_waitqueue_head(&config->recv_wq);
1551 init_waitqueue_head(&config->conn_wait);
1552 config->blksize_bits = NBD_DEF_BLKSIZE_BITS;
1553 atomic_set(&config->live_connections, 0);
1554 nbd->config = config;
1555 refcount_set(&nbd->config_refs, 1);
1560 static int nbd_open(struct gendisk *disk, blk_mode_t mode)
1562 struct nbd_device *nbd;
1565 mutex_lock(&nbd_index_mutex);
1566 nbd = disk->private_data;
1571 if (!refcount_inc_not_zero(&nbd->refs)) {
1575 if (!refcount_inc_not_zero(&nbd->config_refs)) {
1576 mutex_lock(&nbd->config_lock);
1577 if (refcount_inc_not_zero(&nbd->config_refs)) {
1578 mutex_unlock(&nbd->config_lock);
1581 ret = nbd_alloc_and_init_config(nbd);
1583 mutex_unlock(&nbd->config_lock);
1587 refcount_inc(&nbd->refs);
1588 mutex_unlock(&nbd->config_lock);
1590 set_bit(GD_NEED_PART_SCAN, &disk->state);
1591 } else if (nbd_disconnected(nbd->config)) {
1593 set_bit(GD_NEED_PART_SCAN, &disk->state);
1596 mutex_unlock(&nbd_index_mutex);
1600 static void nbd_release(struct gendisk *disk)
1602 struct nbd_device *nbd = disk->private_data;
1604 if (test_bit(NBD_RT_DISCONNECT_ON_CLOSE, &nbd->config->runtime_flags) &&
1605 disk_openers(disk) == 0)
1606 nbd_disconnect_and_put(nbd);
1608 nbd_config_put(nbd);
1612 static void nbd_free_disk(struct gendisk *disk)
1614 struct nbd_device *nbd = disk->private_data;
1619 static const struct block_device_operations nbd_fops =
1621 .owner = THIS_MODULE,
1623 .release = nbd_release,
1625 .compat_ioctl = nbd_ioctl,
1626 .free_disk = nbd_free_disk,
1629 #if IS_ENABLED(CONFIG_DEBUG_FS)
1631 static int nbd_dbg_tasks_show(struct seq_file *s, void *unused)
1633 struct nbd_device *nbd = s->private;
1636 seq_printf(s, "recv: %d\n", nbd->pid);
1641 DEFINE_SHOW_ATTRIBUTE(nbd_dbg_tasks);
1643 static int nbd_dbg_flags_show(struct seq_file *s, void *unused)
1645 struct nbd_device *nbd = s->private;
1646 u32 flags = nbd->config->flags;
1648 seq_printf(s, "Hex: 0x%08x\n\n", flags);
1650 seq_puts(s, "Known flags:\n");
1652 if (flags & NBD_FLAG_HAS_FLAGS)
1653 seq_puts(s, "NBD_FLAG_HAS_FLAGS\n");
1654 if (flags & NBD_FLAG_READ_ONLY)
1655 seq_puts(s, "NBD_FLAG_READ_ONLY\n");
1656 if (flags & NBD_FLAG_SEND_FLUSH)
1657 seq_puts(s, "NBD_FLAG_SEND_FLUSH\n");
1658 if (flags & NBD_FLAG_SEND_FUA)
1659 seq_puts(s, "NBD_FLAG_SEND_FUA\n");
1660 if (flags & NBD_FLAG_SEND_TRIM)
1661 seq_puts(s, "NBD_FLAG_SEND_TRIM\n");
1666 DEFINE_SHOW_ATTRIBUTE(nbd_dbg_flags);
1668 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1671 struct nbd_config *config = nbd->config;
1676 dir = debugfs_create_dir(nbd_name(nbd), nbd_dbg_dir);
1678 dev_err(nbd_to_dev(nbd), "Failed to create debugfs dir for '%s'\n",
1682 config->dbg_dir = dir;
1684 debugfs_create_file("tasks", 0444, dir, nbd, &nbd_dbg_tasks_fops);
1685 debugfs_create_u64("size_bytes", 0444, dir, &config->bytesize);
1686 debugfs_create_u32("timeout", 0444, dir, &nbd->tag_set.timeout);
1687 debugfs_create_u32("blocksize_bits", 0444, dir, &config->blksize_bits);
1688 debugfs_create_file("flags", 0444, dir, nbd, &nbd_dbg_flags_fops);
1693 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1695 debugfs_remove_recursive(nbd->config->dbg_dir);
1698 static int nbd_dbg_init(void)
1700 struct dentry *dbg_dir;
1702 dbg_dir = debugfs_create_dir("nbd", NULL);
1703 if (IS_ERR(dbg_dir))
1706 nbd_dbg_dir = dbg_dir;
1711 static void nbd_dbg_close(void)
1713 debugfs_remove_recursive(nbd_dbg_dir);
1716 #else /* IS_ENABLED(CONFIG_DEBUG_FS) */
1718 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1723 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1727 static int nbd_dbg_init(void)
1732 static void nbd_dbg_close(void)
1738 static int nbd_init_request(struct blk_mq_tag_set *set, struct request *rq,
1739 unsigned int hctx_idx, unsigned int numa_node)
1741 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(rq);
1742 cmd->nbd = set->driver_data;
1744 mutex_init(&cmd->lock);
1748 static const struct blk_mq_ops nbd_mq_ops = {
1749 .queue_rq = nbd_queue_rq,
1750 .complete = nbd_complete_rq,
1751 .init_request = nbd_init_request,
1752 .timeout = nbd_xmit_timeout,
1755 static struct nbd_device *nbd_dev_add(int index, unsigned int refs)
1757 struct nbd_device *nbd;
1758 struct gendisk *disk;
1761 nbd = kzalloc(sizeof(struct nbd_device), GFP_KERNEL);
1765 nbd->tag_set.ops = &nbd_mq_ops;
1766 nbd->tag_set.nr_hw_queues = 1;
1767 nbd->tag_set.queue_depth = 128;
1768 nbd->tag_set.numa_node = NUMA_NO_NODE;
1769 nbd->tag_set.cmd_size = sizeof(struct nbd_cmd);
1770 nbd->tag_set.flags = BLK_MQ_F_SHOULD_MERGE |
1772 nbd->tag_set.driver_data = nbd;
1773 INIT_WORK(&nbd->remove_work, nbd_dev_remove_work);
1774 nbd->backend = NULL;
1776 err = blk_mq_alloc_tag_set(&nbd->tag_set);
1780 mutex_lock(&nbd_index_mutex);
1782 err = idr_alloc(&nbd_index_idr, nbd, index, index + 1,
1787 err = idr_alloc(&nbd_index_idr, nbd, 0,
1788 (MINORMASK >> part_shift) + 1, GFP_KERNEL);
1793 mutex_unlock(&nbd_index_mutex);
1797 disk = blk_mq_alloc_disk(&nbd->tag_set, NULL);
1799 err = PTR_ERR(disk);
1804 nbd->recv_workq = alloc_workqueue("nbd%d-recv",
1805 WQ_MEM_RECLAIM | WQ_HIGHPRI |
1806 WQ_UNBOUND, 0, nbd->index);
1807 if (!nbd->recv_workq) {
1808 dev_err(disk_to_dev(nbd->disk), "Could not allocate knbd recv work queue.\n");
1814 * Tell the block layer that we are not a rotational device
1816 blk_queue_flag_set(QUEUE_FLAG_NONROT, disk->queue);
1817 disk->queue->limits.discard_granularity = 0;
1818 blk_queue_max_discard_sectors(disk->queue, 0);
1819 blk_queue_max_segment_size(disk->queue, UINT_MAX);
1820 blk_queue_max_segments(disk->queue, USHRT_MAX);
1821 blk_queue_max_hw_sectors(disk->queue, 65536);
1822 disk->queue->limits.max_sectors = 256;
1824 mutex_init(&nbd->config_lock);
1825 refcount_set(&nbd->config_refs, 0);
1827 * Start out with a zero references to keep other threads from using
1828 * this device until it is fully initialized.
1830 refcount_set(&nbd->refs, 0);
1831 INIT_LIST_HEAD(&nbd->list);
1832 disk->major = NBD_MAJOR;
1833 disk->first_minor = index << part_shift;
1834 disk->minors = 1 << part_shift;
1835 disk->fops = &nbd_fops;
1836 disk->private_data = nbd;
1837 sprintf(disk->disk_name, "nbd%d", index);
1838 err = add_disk(disk);
1843 * Now publish the device.
1845 refcount_set(&nbd->refs, refs);
1846 nbd_total_devices++;
1850 destroy_workqueue(nbd->recv_workq);
1854 mutex_lock(&nbd_index_mutex);
1855 idr_remove(&nbd_index_idr, index);
1856 mutex_unlock(&nbd_index_mutex);
1858 blk_mq_free_tag_set(&nbd->tag_set);
1862 return ERR_PTR(err);
1865 static struct nbd_device *nbd_find_get_unused(void)
1867 struct nbd_device *nbd;
1870 lockdep_assert_held(&nbd_index_mutex);
1872 idr_for_each_entry(&nbd_index_idr, nbd, id) {
1873 if (refcount_read(&nbd->config_refs) ||
1874 test_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags))
1876 if (refcount_inc_not_zero(&nbd->refs))
1883 /* Netlink interface. */
1884 static const struct nla_policy nbd_attr_policy[NBD_ATTR_MAX + 1] = {
1885 [NBD_ATTR_INDEX] = { .type = NLA_U32 },
1886 [NBD_ATTR_SIZE_BYTES] = { .type = NLA_U64 },
1887 [NBD_ATTR_BLOCK_SIZE_BYTES] = { .type = NLA_U64 },
1888 [NBD_ATTR_TIMEOUT] = { .type = NLA_U64 },
1889 [NBD_ATTR_SERVER_FLAGS] = { .type = NLA_U64 },
1890 [NBD_ATTR_CLIENT_FLAGS] = { .type = NLA_U64 },
1891 [NBD_ATTR_SOCKETS] = { .type = NLA_NESTED},
1892 [NBD_ATTR_DEAD_CONN_TIMEOUT] = { .type = NLA_U64 },
1893 [NBD_ATTR_DEVICE_LIST] = { .type = NLA_NESTED},
1894 [NBD_ATTR_BACKEND_IDENTIFIER] = { .type = NLA_STRING},
1897 static const struct nla_policy nbd_sock_policy[NBD_SOCK_MAX + 1] = {
1898 [NBD_SOCK_FD] = { .type = NLA_U32 },
1901 /* We don't use this right now since we don't parse the incoming list, but we
1902 * still want it here so userspace knows what to expect.
1904 static const struct nla_policy __attribute__((unused))
1905 nbd_device_policy[NBD_DEVICE_ATTR_MAX + 1] = {
1906 [NBD_DEVICE_INDEX] = { .type = NLA_U32 },
1907 [NBD_DEVICE_CONNECTED] = { .type = NLA_U8 },
1910 static int nbd_genl_size_set(struct genl_info *info, struct nbd_device *nbd)
1912 struct nbd_config *config = nbd->config;
1913 u64 bsize = nbd_blksize(config);
1914 u64 bytes = config->bytesize;
1916 if (info->attrs[NBD_ATTR_SIZE_BYTES])
1917 bytes = nla_get_u64(info->attrs[NBD_ATTR_SIZE_BYTES]);
1919 if (info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES])
1920 bsize = nla_get_u64(info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]);
1922 if (bytes != config->bytesize || bsize != nbd_blksize(config))
1923 return nbd_set_size(nbd, bytes, bsize);
1927 static int nbd_genl_connect(struct sk_buff *skb, struct genl_info *info)
1929 struct nbd_device *nbd;
1930 struct nbd_config *config;
1933 bool put_dev = false;
1935 if (!netlink_capable(skb, CAP_SYS_ADMIN))
1938 if (info->attrs[NBD_ATTR_INDEX]) {
1939 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1942 * Too big first_minor can cause duplicate creation of
1943 * sysfs files/links, since index << part_shift might overflow, or
1944 * MKDEV() expect that the max bits of first_minor is 20.
1946 if (index < 0 || index > MINORMASK >> part_shift) {
1947 pr_err("illegal input index %d\n", index);
1951 if (GENL_REQ_ATTR_CHECK(info, NBD_ATTR_SOCKETS)) {
1952 pr_err("must specify at least one socket\n");
1955 if (GENL_REQ_ATTR_CHECK(info, NBD_ATTR_SIZE_BYTES)) {
1956 pr_err("must specify a size in bytes for the device\n");
1960 mutex_lock(&nbd_index_mutex);
1962 nbd = nbd_find_get_unused();
1964 nbd = idr_find(&nbd_index_idr, index);
1966 if ((test_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags) &&
1967 test_bit(NBD_DISCONNECT_REQUESTED, &nbd->flags)) ||
1968 !refcount_inc_not_zero(&nbd->refs)) {
1969 mutex_unlock(&nbd_index_mutex);
1970 pr_err("device at index %d is going down\n",
1976 mutex_unlock(&nbd_index_mutex);
1979 nbd = nbd_dev_add(index, 2);
1981 pr_err("failed to add new device\n");
1982 return PTR_ERR(nbd);
1986 mutex_lock(&nbd->config_lock);
1987 if (refcount_read(&nbd->config_refs)) {
1988 mutex_unlock(&nbd->config_lock);
1992 pr_err("nbd%d already in use\n", index);
1996 ret = nbd_alloc_and_init_config(nbd);
1998 mutex_unlock(&nbd->config_lock);
2000 pr_err("couldn't allocate config\n");
2004 config = nbd->config;
2005 set_bit(NBD_RT_BOUND, &config->runtime_flags);
2006 ret = nbd_genl_size_set(info, nbd);
2010 if (info->attrs[NBD_ATTR_TIMEOUT])
2011 nbd_set_cmd_timeout(nbd,
2012 nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]));
2013 if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
2014 config->dead_conn_timeout =
2015 nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
2016 config->dead_conn_timeout *= HZ;
2018 if (info->attrs[NBD_ATTR_SERVER_FLAGS])
2020 nla_get_u64(info->attrs[NBD_ATTR_SERVER_FLAGS]);
2021 if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
2022 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
2023 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
2025 * We have 1 ref to keep the device around, and then 1
2026 * ref for our current operation here, which will be
2027 * inherited by the config. If we already have
2028 * DESTROY_ON_DISCONNECT set then we know we don't have
2029 * that extra ref already held so we don't need the
2032 if (!test_and_set_bit(NBD_DESTROY_ON_DISCONNECT,
2036 if (test_and_clear_bit(NBD_DESTROY_ON_DISCONNECT,
2038 refcount_inc(&nbd->refs);
2040 if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
2041 set_bit(NBD_RT_DISCONNECT_ON_CLOSE,
2042 &config->runtime_flags);
2046 if (info->attrs[NBD_ATTR_SOCKETS]) {
2047 struct nlattr *attr;
2050 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
2052 struct nlattr *socks[NBD_SOCK_MAX+1];
2054 if (nla_type(attr) != NBD_SOCK_ITEM) {
2055 pr_err("socks must be embedded in a SOCK_ITEM attr\n");
2059 ret = nla_parse_nested_deprecated(socks, NBD_SOCK_MAX,
2064 pr_err("error processing sock list\n");
2068 if (!socks[NBD_SOCK_FD])
2070 fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
2071 ret = nbd_add_socket(nbd, fd, true);
2076 ret = nbd_start_device(nbd);
2079 if (info->attrs[NBD_ATTR_BACKEND_IDENTIFIER]) {
2080 nbd->backend = nla_strdup(info->attrs[NBD_ATTR_BACKEND_IDENTIFIER],
2082 if (!nbd->backend) {
2087 ret = device_create_file(disk_to_dev(nbd->disk), &backend_attr);
2089 dev_err(disk_to_dev(nbd->disk),
2090 "device_create_file failed for backend!\n");
2093 set_bit(NBD_RT_HAS_BACKEND_FILE, &config->runtime_flags);
2095 mutex_unlock(&nbd->config_lock);
2097 set_bit(NBD_RT_HAS_CONFIG_REF, &config->runtime_flags);
2098 refcount_inc(&nbd->config_refs);
2099 nbd_connect_reply(info, nbd->index);
2101 nbd_config_put(nbd);
2107 static void nbd_disconnect_and_put(struct nbd_device *nbd)
2109 mutex_lock(&nbd->config_lock);
2110 nbd_disconnect(nbd);
2112 wake_up(&nbd->config->conn_wait);
2114 * Make sure recv thread has finished, we can safely call nbd_clear_que()
2115 * to cancel the inflight I/Os.
2117 flush_workqueue(nbd->recv_workq);
2119 nbd->task_setup = NULL;
2120 mutex_unlock(&nbd->config_lock);
2122 if (test_and_clear_bit(NBD_RT_HAS_CONFIG_REF,
2123 &nbd->config->runtime_flags))
2124 nbd_config_put(nbd);
2127 static int nbd_genl_disconnect(struct sk_buff *skb, struct genl_info *info)
2129 struct nbd_device *nbd;
2132 if (!netlink_capable(skb, CAP_SYS_ADMIN))
2135 if (GENL_REQ_ATTR_CHECK(info, NBD_ATTR_INDEX)) {
2136 pr_err("must specify an index to disconnect\n");
2139 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2140 mutex_lock(&nbd_index_mutex);
2141 nbd = idr_find(&nbd_index_idr, index);
2143 mutex_unlock(&nbd_index_mutex);
2144 pr_err("couldn't find device at index %d\n", index);
2147 if (!refcount_inc_not_zero(&nbd->refs)) {
2148 mutex_unlock(&nbd_index_mutex);
2149 pr_err("device at index %d is going down\n", index);
2152 mutex_unlock(&nbd_index_mutex);
2153 if (!refcount_inc_not_zero(&nbd->config_refs))
2155 nbd_disconnect_and_put(nbd);
2156 nbd_config_put(nbd);
2162 static int nbd_genl_reconfigure(struct sk_buff *skb, struct genl_info *info)
2164 struct nbd_device *nbd = NULL;
2165 struct nbd_config *config;
2168 bool put_dev = false;
2170 if (!netlink_capable(skb, CAP_SYS_ADMIN))
2173 if (GENL_REQ_ATTR_CHECK(info, NBD_ATTR_INDEX)) {
2174 pr_err("must specify a device to reconfigure\n");
2177 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2178 mutex_lock(&nbd_index_mutex);
2179 nbd = idr_find(&nbd_index_idr, index);
2181 mutex_unlock(&nbd_index_mutex);
2182 pr_err("couldn't find a device at index %d\n", index);
2186 if (info->attrs[NBD_ATTR_BACKEND_IDENTIFIER]) {
2187 if (nla_strcmp(info->attrs[NBD_ATTR_BACKEND_IDENTIFIER],
2189 mutex_unlock(&nbd_index_mutex);
2190 dev_err(nbd_to_dev(nbd),
2191 "backend image doesn't match with %s\n",
2196 mutex_unlock(&nbd_index_mutex);
2197 dev_err(nbd_to_dev(nbd), "must specify backend\n");
2201 if (!refcount_inc_not_zero(&nbd->refs)) {
2202 mutex_unlock(&nbd_index_mutex);
2203 pr_err("device at index %d is going down\n", index);
2206 mutex_unlock(&nbd_index_mutex);
2208 if (!refcount_inc_not_zero(&nbd->config_refs)) {
2209 dev_err(nbd_to_dev(nbd),
2210 "not configured, cannot reconfigure\n");
2215 mutex_lock(&nbd->config_lock);
2216 config = nbd->config;
2217 if (!test_bit(NBD_RT_BOUND, &config->runtime_flags) ||
2219 dev_err(nbd_to_dev(nbd),
2220 "not configured, cannot reconfigure\n");
2225 ret = nbd_genl_size_set(info, nbd);
2229 if (info->attrs[NBD_ATTR_TIMEOUT])
2230 nbd_set_cmd_timeout(nbd,
2231 nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]));
2232 if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
2233 config->dead_conn_timeout =
2234 nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
2235 config->dead_conn_timeout *= HZ;
2237 if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
2238 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
2239 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
2240 if (!test_and_set_bit(NBD_DESTROY_ON_DISCONNECT,
2244 if (test_and_clear_bit(NBD_DESTROY_ON_DISCONNECT,
2246 refcount_inc(&nbd->refs);
2249 if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
2250 set_bit(NBD_RT_DISCONNECT_ON_CLOSE,
2251 &config->runtime_flags);
2253 clear_bit(NBD_RT_DISCONNECT_ON_CLOSE,
2254 &config->runtime_flags);
2258 if (info->attrs[NBD_ATTR_SOCKETS]) {
2259 struct nlattr *attr;
2262 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
2264 struct nlattr *socks[NBD_SOCK_MAX+1];
2266 if (nla_type(attr) != NBD_SOCK_ITEM) {
2267 pr_err("socks must be embedded in a SOCK_ITEM attr\n");
2271 ret = nla_parse_nested_deprecated(socks, NBD_SOCK_MAX,
2276 pr_err("error processing sock list\n");
2280 if (!socks[NBD_SOCK_FD])
2282 fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
2283 ret = nbd_reconnect_socket(nbd, fd);
2289 dev_info(nbd_to_dev(nbd), "reconnected socket\n");
2293 mutex_unlock(&nbd->config_lock);
2294 nbd_config_put(nbd);
2301 static const struct genl_small_ops nbd_connect_genl_ops[] = {
2303 .cmd = NBD_CMD_CONNECT,
2304 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2305 .doit = nbd_genl_connect,
2308 .cmd = NBD_CMD_DISCONNECT,
2309 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2310 .doit = nbd_genl_disconnect,
2313 .cmd = NBD_CMD_RECONFIGURE,
2314 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2315 .doit = nbd_genl_reconfigure,
2318 .cmd = NBD_CMD_STATUS,
2319 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2320 .doit = nbd_genl_status,
2324 static const struct genl_multicast_group nbd_mcast_grps[] = {
2325 { .name = NBD_GENL_MCAST_GROUP_NAME, },
2328 static struct genl_family nbd_genl_family __ro_after_init = {
2330 .name = NBD_GENL_FAMILY_NAME,
2331 .version = NBD_GENL_VERSION,
2332 .module = THIS_MODULE,
2333 .small_ops = nbd_connect_genl_ops,
2334 .n_small_ops = ARRAY_SIZE(nbd_connect_genl_ops),
2335 .resv_start_op = NBD_CMD_STATUS + 1,
2336 .maxattr = NBD_ATTR_MAX,
2338 .policy = nbd_attr_policy,
2339 .mcgrps = nbd_mcast_grps,
2340 .n_mcgrps = ARRAY_SIZE(nbd_mcast_grps),
2342 MODULE_ALIAS_GENL_FAMILY(NBD_GENL_FAMILY_NAME);
2344 static int populate_nbd_status(struct nbd_device *nbd, struct sk_buff *reply)
2346 struct nlattr *dev_opt;
2350 /* This is a little racey, but for status it's ok. The
2351 * reason we don't take a ref here is because we can't
2352 * take a ref in the index == -1 case as we would need
2353 * to put under the nbd_index_mutex, which could
2354 * deadlock if we are configured to remove ourselves
2355 * once we're disconnected.
2357 if (refcount_read(&nbd->config_refs))
2359 dev_opt = nla_nest_start_noflag(reply, NBD_DEVICE_ITEM);
2362 ret = nla_put_u32(reply, NBD_DEVICE_INDEX, nbd->index);
2365 ret = nla_put_u8(reply, NBD_DEVICE_CONNECTED,
2369 nla_nest_end(reply, dev_opt);
2373 static int status_cb(int id, void *ptr, void *data)
2375 struct nbd_device *nbd = ptr;
2376 return populate_nbd_status(nbd, (struct sk_buff *)data);
2379 static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info)
2381 struct nlattr *dev_list;
2382 struct sk_buff *reply;
2388 if (info->attrs[NBD_ATTR_INDEX])
2389 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2391 mutex_lock(&nbd_index_mutex);
2393 msg_size = nla_total_size(nla_attr_size(sizeof(u32)) +
2394 nla_attr_size(sizeof(u8)));
2395 msg_size *= (index == -1) ? nbd_total_devices : 1;
2397 reply = genlmsg_new(msg_size, GFP_KERNEL);
2400 reply_head = genlmsg_put_reply(reply, info, &nbd_genl_family, 0,
2407 dev_list = nla_nest_start_noflag(reply, NBD_ATTR_DEVICE_LIST);
2409 ret = idr_for_each(&nbd_index_idr, &status_cb, reply);
2415 struct nbd_device *nbd;
2416 nbd = idr_find(&nbd_index_idr, index);
2418 ret = populate_nbd_status(nbd, reply);
2425 nla_nest_end(reply, dev_list);
2426 genlmsg_end(reply, reply_head);
2427 ret = genlmsg_reply(reply, info);
2429 mutex_unlock(&nbd_index_mutex);
2433 static void nbd_connect_reply(struct genl_info *info, int index)
2435 struct sk_buff *skb;
2439 skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2442 msg_head = genlmsg_put_reply(skb, info, &nbd_genl_family, 0,
2448 ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2453 genlmsg_end(skb, msg_head);
2454 genlmsg_reply(skb, info);
2457 static void nbd_mcast_index(int index)
2459 struct sk_buff *skb;
2463 skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2466 msg_head = genlmsg_put(skb, 0, 0, &nbd_genl_family, 0,
2472 ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2477 genlmsg_end(skb, msg_head);
2478 genlmsg_multicast(&nbd_genl_family, skb, 0, 0, GFP_KERNEL);
2481 static void nbd_dead_link_work(struct work_struct *work)
2483 struct link_dead_args *args = container_of(work, struct link_dead_args,
2485 nbd_mcast_index(args->index);
2489 static int __init nbd_init(void)
2493 BUILD_BUG_ON(sizeof(struct nbd_request) != 28);
2496 pr_err("max_part must be >= 0\n");
2502 part_shift = fls(max_part);
2505 * Adjust max_part according to part_shift as it is exported
2506 * to user space so that user can know the max number of
2507 * partition kernel should be able to manage.
2509 * Note that -1 is required because partition 0 is reserved
2510 * for the whole disk.
2512 max_part = (1UL << part_shift) - 1;
2515 if ((1UL << part_shift) > DISK_MAX_PARTS)
2518 if (nbds_max > 1UL << (MINORBITS - part_shift))
2521 if (register_blkdev(NBD_MAJOR, "nbd"))
2524 nbd_del_wq = alloc_workqueue("nbd-del", WQ_UNBOUND, 0);
2526 unregister_blkdev(NBD_MAJOR, "nbd");
2530 if (genl_register_family(&nbd_genl_family)) {
2531 destroy_workqueue(nbd_del_wq);
2532 unregister_blkdev(NBD_MAJOR, "nbd");
2537 for (i = 0; i < nbds_max; i++)
2542 static int nbd_exit_cb(int id, void *ptr, void *data)
2544 struct list_head *list = (struct list_head *)data;
2545 struct nbd_device *nbd = ptr;
2547 /* Skip nbd that is being removed asynchronously */
2548 if (refcount_read(&nbd->refs))
2549 list_add_tail(&nbd->list, list);
2554 static void __exit nbd_cleanup(void)
2556 struct nbd_device *nbd;
2557 LIST_HEAD(del_list);
2560 * Unregister netlink interface prior to waiting
2561 * for the completion of netlink commands.
2563 genl_unregister_family(&nbd_genl_family);
2567 mutex_lock(&nbd_index_mutex);
2568 idr_for_each(&nbd_index_idr, &nbd_exit_cb, &del_list);
2569 mutex_unlock(&nbd_index_mutex);
2571 while (!list_empty(&del_list)) {
2572 nbd = list_first_entry(&del_list, struct nbd_device, list);
2573 list_del_init(&nbd->list);
2574 if (refcount_read(&nbd->config_refs))
2575 pr_err("possibly leaking nbd_config (ref %d)\n",
2576 refcount_read(&nbd->config_refs));
2577 if (refcount_read(&nbd->refs) != 1)
2578 pr_err("possibly leaking a device\n");
2582 /* Also wait for nbd_dev_remove_work() completes */
2583 destroy_workqueue(nbd_del_wq);
2585 idr_destroy(&nbd_index_idr);
2586 unregister_blkdev(NBD_MAJOR, "nbd");
2589 module_init(nbd_init);
2590 module_exit(nbd_cleanup);
2592 MODULE_DESCRIPTION("Network Block Device");
2593 MODULE_LICENSE("GPL");
2595 module_param(nbds_max, int, 0444);
2596 MODULE_PARM_DESC(nbds_max, "number of network block devices to initialize (default: 16)");
2597 module_param(max_part, int, 0444);
2598 MODULE_PARM_DESC(max_part, "number of partitions per device (default: 16)");