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;
254 blk_mq_free_tag_set(&nbd->tag_set);
257 * Remove from idr after del_gendisk() completes, so if the same ID is
258 * reused, the following add_disk() will succeed.
260 mutex_lock(&nbd_index_mutex);
261 idr_remove(&nbd_index_idr, nbd->index);
262 mutex_unlock(&nbd_index_mutex);
263 destroy_workqueue(nbd->recv_workq);
267 static void nbd_dev_remove_work(struct work_struct *work)
269 nbd_dev_remove(container_of(work, struct nbd_device, remove_work));
272 static void nbd_put(struct nbd_device *nbd)
274 if (!refcount_dec_and_test(&nbd->refs))
277 /* Call del_gendisk() asynchrounously to prevent deadlock */
278 if (test_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags))
279 queue_work(nbd_del_wq, &nbd->remove_work);
284 static int nbd_disconnected(struct nbd_config *config)
286 return test_bit(NBD_RT_DISCONNECTED, &config->runtime_flags) ||
287 test_bit(NBD_RT_DISCONNECT_REQUESTED, &config->runtime_flags);
290 static void nbd_mark_nsock_dead(struct nbd_device *nbd, struct nbd_sock *nsock,
293 if (!nsock->dead && notify && !nbd_disconnected(nbd->config)) {
294 struct link_dead_args *args;
295 args = kmalloc(sizeof(struct link_dead_args), GFP_NOIO);
297 INIT_WORK(&args->work, nbd_dead_link_work);
298 args->index = nbd->index;
299 queue_work(system_wq, &args->work);
303 kernel_sock_shutdown(nsock->sock, SHUT_RDWR);
304 if (atomic_dec_return(&nbd->config->live_connections) == 0) {
305 if (test_and_clear_bit(NBD_RT_DISCONNECT_REQUESTED,
306 &nbd->config->runtime_flags)) {
307 set_bit(NBD_RT_DISCONNECTED,
308 &nbd->config->runtime_flags);
309 dev_info(nbd_to_dev(nbd),
310 "Disconnected due to user request.\n");
315 nsock->pending = NULL;
319 static int nbd_set_size(struct nbd_device *nbd, loff_t bytesize,
323 blksize = 1u << NBD_DEF_BLKSIZE_BITS;
325 if (blk_validate_block_size(blksize))
331 nbd->config->bytesize = bytesize;
332 nbd->config->blksize_bits = __ffs(blksize);
337 if (nbd->config->flags & NBD_FLAG_SEND_TRIM) {
338 nbd->disk->queue->limits.discard_granularity = blksize;
339 blk_queue_max_discard_sectors(nbd->disk->queue, UINT_MAX);
341 blk_queue_logical_block_size(nbd->disk->queue, blksize);
342 blk_queue_physical_block_size(nbd->disk->queue, blksize);
345 set_bit(GD_NEED_PART_SCAN, &nbd->disk->state);
346 if (!set_capacity_and_notify(nbd->disk, bytesize >> 9))
347 kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
351 static void nbd_complete_rq(struct request *req)
353 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
355 dev_dbg(nbd_to_dev(cmd->nbd), "request %p: %s\n", req,
356 cmd->status ? "failed" : "done");
358 blk_mq_end_request(req, cmd->status);
362 * Forcibly shutdown the socket causing all listeners to error
364 static void sock_shutdown(struct nbd_device *nbd)
366 struct nbd_config *config = nbd->config;
369 if (config->num_connections == 0)
371 if (test_and_set_bit(NBD_RT_DISCONNECTED, &config->runtime_flags))
374 for (i = 0; i < config->num_connections; i++) {
375 struct nbd_sock *nsock = config->socks[i];
376 mutex_lock(&nsock->tx_lock);
377 nbd_mark_nsock_dead(nbd, nsock, 0);
378 mutex_unlock(&nsock->tx_lock);
380 dev_warn(disk_to_dev(nbd->disk), "shutting down sockets\n");
383 static u32 req_to_nbd_cmd_type(struct request *req)
385 switch (req_op(req)) {
389 return NBD_CMD_FLUSH;
391 return NBD_CMD_WRITE;
399 static enum blk_eh_timer_return nbd_xmit_timeout(struct request *req)
401 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
402 struct nbd_device *nbd = cmd->nbd;
403 struct nbd_config *config;
405 if (!mutex_trylock(&cmd->lock))
406 return BLK_EH_RESET_TIMER;
408 if (!test_bit(NBD_CMD_INFLIGHT, &cmd->flags)) {
409 mutex_unlock(&cmd->lock);
413 if (!refcount_inc_not_zero(&nbd->config_refs)) {
414 cmd->status = BLK_STS_TIMEOUT;
415 __clear_bit(NBD_CMD_INFLIGHT, &cmd->flags);
416 mutex_unlock(&cmd->lock);
419 config = nbd->config;
421 if (config->num_connections > 1 ||
422 (config->num_connections == 1 && nbd->tag_set.timeout)) {
423 dev_err_ratelimited(nbd_to_dev(nbd),
424 "Connection timed out, retrying (%d/%d alive)\n",
425 atomic_read(&config->live_connections),
426 config->num_connections);
428 * Hooray we have more connections, requeue this IO, the submit
429 * path will put it on a real connection. Or if only one
430 * connection is configured, the submit path will wait util
431 * a new connection is reconfigured or util dead timeout.
434 if (cmd->index < config->num_connections) {
435 struct nbd_sock *nsock =
436 config->socks[cmd->index];
437 mutex_lock(&nsock->tx_lock);
438 /* We can have multiple outstanding requests, so
439 * we don't want to mark the nsock dead if we've
440 * already reconnected with a new socket, so
441 * only mark it dead if its the same socket we
444 if (cmd->cookie == nsock->cookie)
445 nbd_mark_nsock_dead(nbd, nsock, 1);
446 mutex_unlock(&nsock->tx_lock);
448 mutex_unlock(&cmd->lock);
449 nbd_requeue_cmd(cmd);
455 if (!nbd->tag_set.timeout) {
457 * Userspace sets timeout=0 to disable socket disconnection,
458 * so just warn and reset the timer.
460 struct nbd_sock *nsock = config->socks[cmd->index];
462 dev_info(nbd_to_dev(nbd), "Possible stuck request %p: control (%s@%llu,%uB). Runtime %u seconds\n",
463 req, nbdcmd_to_ascii(req_to_nbd_cmd_type(req)),
464 (unsigned long long)blk_rq_pos(req) << 9,
465 blk_rq_bytes(req), (req->timeout / HZ) * cmd->retries);
467 mutex_lock(&nsock->tx_lock);
468 if (cmd->cookie != nsock->cookie) {
469 nbd_requeue_cmd(cmd);
470 mutex_unlock(&nsock->tx_lock);
471 mutex_unlock(&cmd->lock);
475 mutex_unlock(&nsock->tx_lock);
476 mutex_unlock(&cmd->lock);
478 return BLK_EH_RESET_TIMER;
481 dev_err_ratelimited(nbd_to_dev(nbd), "Connection timed out\n");
482 set_bit(NBD_RT_TIMEDOUT, &config->runtime_flags);
483 cmd->status = BLK_STS_IOERR;
484 __clear_bit(NBD_CMD_INFLIGHT, &cmd->flags);
485 mutex_unlock(&cmd->lock);
489 blk_mq_complete_request(req);
494 * Send or receive packet. Return a positive value on success and
495 * negtive value on failue, and never return 0.
497 static int sock_xmit(struct nbd_device *nbd, int index, int send,
498 struct iov_iter *iter, int msg_flags, int *sent)
500 struct nbd_config *config = nbd->config;
501 struct socket *sock = config->socks[index]->sock;
504 unsigned int noreclaim_flag;
506 if (unlikely(!sock)) {
507 dev_err_ratelimited(disk_to_dev(nbd->disk),
508 "Attempted %s on closed socket in sock_xmit\n",
509 (send ? "send" : "recv"));
513 msg.msg_iter = *iter;
515 noreclaim_flag = memalloc_noreclaim_save();
517 sock->sk->sk_allocation = GFP_NOIO | __GFP_MEMALLOC;
518 sock->sk->sk_use_task_frag = false;
521 msg.msg_control = NULL;
522 msg.msg_controllen = 0;
523 msg.msg_flags = msg_flags | MSG_NOSIGNAL;
526 result = sock_sendmsg(sock, &msg);
528 result = sock_recvmsg(sock, &msg, msg.msg_flags);
532 result = -EPIPE; /* short read */
537 } while (msg_data_left(&msg));
539 memalloc_noreclaim_restore(noreclaim_flag);
545 * Different settings for sk->sk_sndtimeo can result in different return values
546 * if there is a signal pending when we enter sendmsg, because reasons?
548 static inline int was_interrupted(int result)
550 return result == -ERESTARTSYS || result == -EINTR;
553 /* always call with the tx_lock held */
554 static int nbd_send_cmd(struct nbd_device *nbd, struct nbd_cmd *cmd, int index)
556 struct request *req = blk_mq_rq_from_pdu(cmd);
557 struct nbd_config *config = nbd->config;
558 struct nbd_sock *nsock = config->socks[index];
560 struct nbd_request request = {.magic = htonl(NBD_REQUEST_MAGIC)};
561 struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
562 struct iov_iter from;
563 unsigned long size = blk_rq_bytes(req);
567 u32 nbd_cmd_flags = 0;
568 int sent = nsock->sent, skip = 0;
570 iov_iter_kvec(&from, ITER_SOURCE, &iov, 1, sizeof(request));
572 type = req_to_nbd_cmd_type(req);
576 if (rq_data_dir(req) == WRITE &&
577 (config->flags & NBD_FLAG_READ_ONLY)) {
578 dev_err_ratelimited(disk_to_dev(nbd->disk),
579 "Write on read-only\n");
583 if (req->cmd_flags & REQ_FUA)
584 nbd_cmd_flags |= NBD_CMD_FLAG_FUA;
586 /* We did a partial send previously, and we at least sent the whole
587 * request struct, so just go and send the rest of the pages in the
591 if (sent >= sizeof(request)) {
592 skip = sent - sizeof(request);
594 /* initialize handle for tracing purposes */
595 handle = nbd_cmd_handle(cmd);
599 iov_iter_advance(&from, sent);
604 cmd->cookie = nsock->cookie;
606 request.type = htonl(type | nbd_cmd_flags);
607 if (type != NBD_CMD_FLUSH) {
608 request.from = cpu_to_be64((u64)blk_rq_pos(req) << 9);
609 request.len = htonl(size);
611 handle = nbd_cmd_handle(cmd);
612 request.cookie = cpu_to_be64(handle);
614 trace_nbd_send_request(&request, nbd->index, blk_mq_rq_from_pdu(cmd));
616 dev_dbg(nbd_to_dev(nbd), "request %p: sending control (%s@%llu,%uB)\n",
617 req, nbdcmd_to_ascii(type),
618 (unsigned long long)blk_rq_pos(req) << 9, blk_rq_bytes(req));
619 result = sock_xmit(nbd, index, 1, &from,
620 (type == NBD_CMD_WRITE) ? MSG_MORE : 0, &sent);
621 trace_nbd_header_sent(req, handle);
623 if (was_interrupted(result)) {
624 /* If we haven't sent anything we can just return BUSY,
625 * however if we have sent something we need to make
626 * sure we only allow this req to be sent until we are
630 nsock->pending = req;
633 set_bit(NBD_CMD_REQUEUED, &cmd->flags);
634 return BLK_STS_RESOURCE;
636 dev_err_ratelimited(disk_to_dev(nbd->disk),
637 "Send control failed (result %d)\n", result);
641 if (type != NBD_CMD_WRITE)
646 struct bio *next = bio->bi_next;
647 struct bvec_iter iter;
650 bio_for_each_segment(bvec, bio, iter) {
651 bool is_last = !next && bio_iter_last(bvec, iter);
652 int flags = is_last ? 0 : MSG_MORE;
654 dev_dbg(nbd_to_dev(nbd), "request %p: sending %d bytes data\n",
656 iov_iter_bvec(&from, ITER_SOURCE, &bvec, 1, bvec.bv_len);
658 if (skip >= iov_iter_count(&from)) {
659 skip -= iov_iter_count(&from);
662 iov_iter_advance(&from, skip);
665 result = sock_xmit(nbd, index, 1, &from, flags, &sent);
667 if (was_interrupted(result)) {
668 /* We've already sent the header, we
669 * have no choice but to set pending and
672 nsock->pending = req;
674 set_bit(NBD_CMD_REQUEUED, &cmd->flags);
675 return BLK_STS_RESOURCE;
677 dev_err(disk_to_dev(nbd->disk),
678 "Send data failed (result %d)\n",
683 * The completion might already have come in,
684 * so break for the last one instead of letting
685 * the iterator do it. This prevents use-after-free
694 trace_nbd_payload_sent(req, handle);
695 nsock->pending = NULL;
700 static int nbd_read_reply(struct nbd_device *nbd, int index,
701 struct nbd_reply *reply)
703 struct kvec iov = {.iov_base = reply, .iov_len = sizeof(*reply)};
708 iov_iter_kvec(&to, ITER_DEST, &iov, 1, sizeof(*reply));
709 result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
711 if (!nbd_disconnected(nbd->config))
712 dev_err(disk_to_dev(nbd->disk),
713 "Receive control failed (result %d)\n", result);
717 if (ntohl(reply->magic) != NBD_REPLY_MAGIC) {
718 dev_err(disk_to_dev(nbd->disk), "Wrong magic (0x%lx)\n",
719 (unsigned long)ntohl(reply->magic));
726 /* NULL returned = something went wrong, inform userspace */
727 static struct nbd_cmd *nbd_handle_reply(struct nbd_device *nbd, int index,
728 struct nbd_reply *reply)
732 struct request *req = NULL;
738 handle = be64_to_cpu(reply->cookie);
739 tag = nbd_handle_to_tag(handle);
740 hwq = blk_mq_unique_tag_to_hwq(tag);
741 if (hwq < nbd->tag_set.nr_hw_queues)
742 req = blk_mq_tag_to_rq(nbd->tag_set.tags[hwq],
743 blk_mq_unique_tag_to_tag(tag));
744 if (!req || !blk_mq_request_started(req)) {
745 dev_err(disk_to_dev(nbd->disk), "Unexpected reply (%d) %p\n",
747 return ERR_PTR(-ENOENT);
749 trace_nbd_header_received(req, handle);
750 cmd = blk_mq_rq_to_pdu(req);
752 mutex_lock(&cmd->lock);
753 if (!test_bit(NBD_CMD_INFLIGHT, &cmd->flags)) {
754 dev_err(disk_to_dev(nbd->disk), "Suspicious reply %d (status %u flags %lu)",
755 tag, cmd->status, cmd->flags);
759 if (cmd->index != index) {
760 dev_err(disk_to_dev(nbd->disk), "Unexpected reply %d from different sock %d (expected %d)",
761 tag, index, cmd->index);
765 if (cmd->cmd_cookie != nbd_handle_to_cookie(handle)) {
766 dev_err(disk_to_dev(nbd->disk), "Double reply on req %p, cmd_cookie %u, handle cookie %u\n",
767 req, cmd->cmd_cookie, nbd_handle_to_cookie(handle));
771 if (cmd->status != BLK_STS_OK) {
772 dev_err(disk_to_dev(nbd->disk), "Command already handled %p\n",
777 if (test_bit(NBD_CMD_REQUEUED, &cmd->flags)) {
778 dev_err(disk_to_dev(nbd->disk), "Raced with timeout on req %p\n",
783 if (ntohl(reply->error)) {
784 dev_err(disk_to_dev(nbd->disk), "Other side returned error (%d)\n",
785 ntohl(reply->error));
786 cmd->status = BLK_STS_IOERR;
790 dev_dbg(nbd_to_dev(nbd), "request %p: got reply\n", req);
791 if (rq_data_dir(req) != WRITE) {
792 struct req_iterator iter;
796 rq_for_each_segment(bvec, req, iter) {
797 iov_iter_bvec(&to, ITER_DEST, &bvec, 1, bvec.bv_len);
798 result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
800 dev_err(disk_to_dev(nbd->disk), "Receive data failed (result %d)\n",
803 * If we've disconnected, we need to make sure we
804 * complete this request, otherwise error out
805 * and let the timeout stuff handle resubmitting
806 * this request onto another connection.
808 if (nbd_disconnected(nbd->config)) {
809 cmd->status = BLK_STS_IOERR;
815 dev_dbg(nbd_to_dev(nbd), "request %p: got %d bytes data\n",
820 trace_nbd_payload_received(req, handle);
821 mutex_unlock(&cmd->lock);
822 return ret ? ERR_PTR(ret) : cmd;
825 static void recv_work(struct work_struct *work)
827 struct recv_thread_args *args = container_of(work,
828 struct recv_thread_args,
830 struct nbd_device *nbd = args->nbd;
831 struct nbd_config *config = nbd->config;
832 struct request_queue *q = nbd->disk->queue;
833 struct nbd_sock *nsock;
838 struct nbd_reply reply;
840 if (nbd_read_reply(nbd, args->index, &reply))
844 * Grab .q_usage_counter so request pool won't go away, then no
845 * request use-after-free is possible during nbd_handle_reply().
846 * If queue is frozen, there won't be any inflight requests, we
847 * needn't to handle the incoming garbage message.
849 if (!percpu_ref_tryget(&q->q_usage_counter)) {
850 dev_err(disk_to_dev(nbd->disk), "%s: no io inflight\n",
855 cmd = nbd_handle_reply(nbd, args->index, &reply);
857 percpu_ref_put(&q->q_usage_counter);
861 rq = blk_mq_rq_from_pdu(cmd);
862 if (likely(!blk_should_fake_timeout(rq->q))) {
865 mutex_lock(&cmd->lock);
866 complete = __test_and_clear_bit(NBD_CMD_INFLIGHT,
868 mutex_unlock(&cmd->lock);
870 blk_mq_complete_request(rq);
872 percpu_ref_put(&q->q_usage_counter);
875 nsock = config->socks[args->index];
876 mutex_lock(&nsock->tx_lock);
877 nbd_mark_nsock_dead(nbd, nsock, 1);
878 mutex_unlock(&nsock->tx_lock);
881 atomic_dec(&config->recv_threads);
882 wake_up(&config->recv_wq);
886 static bool nbd_clear_req(struct request *req, void *data)
888 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
890 /* don't abort one completed request */
891 if (blk_mq_request_completed(req))
894 mutex_lock(&cmd->lock);
895 if (!__test_and_clear_bit(NBD_CMD_INFLIGHT, &cmd->flags)) {
896 mutex_unlock(&cmd->lock);
899 cmd->status = BLK_STS_IOERR;
900 mutex_unlock(&cmd->lock);
902 blk_mq_complete_request(req);
906 static void nbd_clear_que(struct nbd_device *nbd)
908 blk_mq_quiesce_queue(nbd->disk->queue);
909 blk_mq_tagset_busy_iter(&nbd->tag_set, nbd_clear_req, NULL);
910 blk_mq_unquiesce_queue(nbd->disk->queue);
911 dev_dbg(disk_to_dev(nbd->disk), "queue cleared\n");
914 static int find_fallback(struct nbd_device *nbd, int index)
916 struct nbd_config *config = nbd->config;
918 struct nbd_sock *nsock = config->socks[index];
919 int fallback = nsock->fallback_index;
921 if (test_bit(NBD_RT_DISCONNECTED, &config->runtime_flags))
924 if (config->num_connections <= 1) {
925 dev_err_ratelimited(disk_to_dev(nbd->disk),
926 "Dead connection, failed to find a fallback\n");
930 if (fallback >= 0 && fallback < config->num_connections &&
931 !config->socks[fallback]->dead)
934 if (nsock->fallback_index < 0 ||
935 nsock->fallback_index >= config->num_connections ||
936 config->socks[nsock->fallback_index]->dead) {
938 for (i = 0; i < config->num_connections; i++) {
941 if (!config->socks[i]->dead) {
946 nsock->fallback_index = new_index;
948 dev_err_ratelimited(disk_to_dev(nbd->disk),
949 "Dead connection, failed to find a fallback\n");
953 new_index = nsock->fallback_index;
957 static int wait_for_reconnect(struct nbd_device *nbd)
959 struct nbd_config *config = nbd->config;
960 if (!config->dead_conn_timeout)
963 if (!wait_event_timeout(config->conn_wait,
964 test_bit(NBD_RT_DISCONNECTED,
965 &config->runtime_flags) ||
966 atomic_read(&config->live_connections) > 0,
967 config->dead_conn_timeout))
970 return !test_bit(NBD_RT_DISCONNECTED, &config->runtime_flags);
973 static int nbd_handle_cmd(struct nbd_cmd *cmd, int index)
975 struct request *req = blk_mq_rq_from_pdu(cmd);
976 struct nbd_device *nbd = cmd->nbd;
977 struct nbd_config *config;
978 struct nbd_sock *nsock;
981 if (!refcount_inc_not_zero(&nbd->config_refs)) {
982 dev_err_ratelimited(disk_to_dev(nbd->disk),
983 "Socks array is empty\n");
986 config = nbd->config;
988 if (index >= config->num_connections) {
989 dev_err_ratelimited(disk_to_dev(nbd->disk),
990 "Attempted send on invalid socket\n");
994 cmd->status = BLK_STS_OK;
996 nsock = config->socks[index];
997 mutex_lock(&nsock->tx_lock);
999 int old_index = index;
1000 index = find_fallback(nbd, index);
1001 mutex_unlock(&nsock->tx_lock);
1003 if (wait_for_reconnect(nbd)) {
1007 /* All the sockets should already be down at this point,
1008 * we just want to make sure that DISCONNECTED is set so
1009 * any requests that come in that were queue'ed waiting
1010 * for the reconnect timer don't trigger the timer again
1011 * and instead just error out.
1014 nbd_config_put(nbd);
1020 /* Handle the case that we have a pending request that was partially
1021 * transmitted that _has_ to be serviced first. We need to call requeue
1022 * here so that it gets put _after_ the request that is already on the
1025 blk_mq_start_request(req);
1026 if (unlikely(nsock->pending && nsock->pending != req)) {
1027 nbd_requeue_cmd(cmd);
1032 * Some failures are related to the link going down, so anything that
1033 * returns EAGAIN can be retried on a different socket.
1035 ret = nbd_send_cmd(nbd, cmd, index);
1037 * Access to this flag is protected by cmd->lock, thus it's safe to set
1038 * the flag after nbd_send_cmd() succeed to send request to server.
1041 __set_bit(NBD_CMD_INFLIGHT, &cmd->flags);
1042 else if (ret == -EAGAIN) {
1043 dev_err_ratelimited(disk_to_dev(nbd->disk),
1044 "Request send failed, requeueing\n");
1045 nbd_mark_nsock_dead(nbd, nsock, 1);
1046 nbd_requeue_cmd(cmd);
1050 mutex_unlock(&nsock->tx_lock);
1051 nbd_config_put(nbd);
1055 static blk_status_t nbd_queue_rq(struct blk_mq_hw_ctx *hctx,
1056 const struct blk_mq_queue_data *bd)
1058 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(bd->rq);
1062 * Since we look at the bio's to send the request over the network we
1063 * need to make sure the completion work doesn't mark this request done
1064 * before we are done doing our send. This keeps us from dereferencing
1065 * freed data if we have particularly fast completions (ie we get the
1066 * completion before we exit sock_xmit on the last bvec) or in the case
1067 * that the server is misbehaving (or there was an error) before we're
1068 * done sending everything over the wire.
1070 mutex_lock(&cmd->lock);
1071 clear_bit(NBD_CMD_REQUEUED, &cmd->flags);
1073 /* We can be called directly from the user space process, which means we
1074 * could possibly have signals pending so our sendmsg will fail. In
1075 * this case we need to return that we are busy, otherwise error out as
1078 ret = nbd_handle_cmd(cmd, hctx->queue_num);
1080 ret = BLK_STS_IOERR;
1083 mutex_unlock(&cmd->lock);
1088 static struct socket *nbd_get_socket(struct nbd_device *nbd, unsigned long fd,
1091 struct socket *sock;
1094 sock = sockfd_lookup(fd, err);
1098 if (sock->ops->shutdown == sock_no_shutdown) {
1099 dev_err(disk_to_dev(nbd->disk), "Unsupported socket: shutdown callout must be supported.\n");
1108 static int nbd_add_socket(struct nbd_device *nbd, unsigned long arg,
1111 struct nbd_config *config = nbd->config;
1112 struct socket *sock;
1113 struct nbd_sock **socks;
1114 struct nbd_sock *nsock;
1117 /* Arg will be cast to int, check it to avoid overflow */
1120 sock = nbd_get_socket(nbd, arg, &err);
1125 * We need to make sure we don't get any errant requests while we're
1126 * reallocating the ->socks array.
1128 blk_mq_freeze_queue(nbd->disk->queue);
1130 if (!netlink && !nbd->task_setup &&
1131 !test_bit(NBD_RT_BOUND, &config->runtime_flags))
1132 nbd->task_setup = current;
1135 (nbd->task_setup != current ||
1136 test_bit(NBD_RT_BOUND, &config->runtime_flags))) {
1137 dev_err(disk_to_dev(nbd->disk),
1138 "Device being setup by another task");
1143 nsock = kzalloc(sizeof(*nsock), GFP_KERNEL);
1149 socks = krealloc(config->socks, (config->num_connections + 1) *
1150 sizeof(struct nbd_sock *), GFP_KERNEL);
1157 config->socks = socks;
1159 nsock->fallback_index = -1;
1160 nsock->dead = false;
1161 mutex_init(&nsock->tx_lock);
1163 nsock->pending = NULL;
1166 socks[config->num_connections++] = nsock;
1167 atomic_inc(&config->live_connections);
1168 blk_mq_unfreeze_queue(nbd->disk->queue);
1173 blk_mq_unfreeze_queue(nbd->disk->queue);
1178 static int nbd_reconnect_socket(struct nbd_device *nbd, unsigned long arg)
1180 struct nbd_config *config = nbd->config;
1181 struct socket *sock, *old;
1182 struct recv_thread_args *args;
1186 sock = nbd_get_socket(nbd, arg, &err);
1190 args = kzalloc(sizeof(*args), GFP_KERNEL);
1196 for (i = 0; i < config->num_connections; i++) {
1197 struct nbd_sock *nsock = config->socks[i];
1202 mutex_lock(&nsock->tx_lock);
1204 mutex_unlock(&nsock->tx_lock);
1207 sk_set_memalloc(sock->sk);
1208 if (nbd->tag_set.timeout)
1209 sock->sk->sk_sndtimeo = nbd->tag_set.timeout;
1210 atomic_inc(&config->recv_threads);
1211 refcount_inc(&nbd->config_refs);
1213 nsock->fallback_index = -1;
1215 nsock->dead = false;
1216 INIT_WORK(&args->work, recv_work);
1220 mutex_unlock(&nsock->tx_lock);
1223 clear_bit(NBD_RT_DISCONNECTED, &config->runtime_flags);
1225 /* We take the tx_mutex in an error path in the recv_work, so we
1226 * need to queue_work outside of the tx_mutex.
1228 queue_work(nbd->recv_workq, &args->work);
1230 atomic_inc(&config->live_connections);
1231 wake_up(&config->conn_wait);
1239 static void nbd_bdev_reset(struct nbd_device *nbd)
1241 if (disk_openers(nbd->disk) > 1)
1243 set_capacity(nbd->disk, 0);
1246 static void nbd_parse_flags(struct nbd_device *nbd)
1248 struct nbd_config *config = nbd->config;
1249 if (config->flags & NBD_FLAG_READ_ONLY)
1250 set_disk_ro(nbd->disk, true);
1252 set_disk_ro(nbd->disk, false);
1253 if (config->flags & NBD_FLAG_SEND_FLUSH) {
1254 if (config->flags & NBD_FLAG_SEND_FUA)
1255 blk_queue_write_cache(nbd->disk->queue, true, true);
1257 blk_queue_write_cache(nbd->disk->queue, true, false);
1260 blk_queue_write_cache(nbd->disk->queue, false, false);
1263 static void send_disconnects(struct nbd_device *nbd)
1265 struct nbd_config *config = nbd->config;
1266 struct nbd_request request = {
1267 .magic = htonl(NBD_REQUEST_MAGIC),
1268 .type = htonl(NBD_CMD_DISC),
1270 struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
1271 struct iov_iter from;
1274 for (i = 0; i < config->num_connections; i++) {
1275 struct nbd_sock *nsock = config->socks[i];
1277 iov_iter_kvec(&from, ITER_SOURCE, &iov, 1, sizeof(request));
1278 mutex_lock(&nsock->tx_lock);
1279 ret = sock_xmit(nbd, i, 1, &from, 0, NULL);
1281 dev_err(disk_to_dev(nbd->disk),
1282 "Send disconnect failed %d\n", ret);
1283 mutex_unlock(&nsock->tx_lock);
1287 static int nbd_disconnect(struct nbd_device *nbd)
1289 struct nbd_config *config = nbd->config;
1291 dev_info(disk_to_dev(nbd->disk), "NBD_DISCONNECT\n");
1292 set_bit(NBD_RT_DISCONNECT_REQUESTED, &config->runtime_flags);
1293 set_bit(NBD_DISCONNECT_REQUESTED, &nbd->flags);
1294 send_disconnects(nbd);
1298 static void nbd_clear_sock(struct nbd_device *nbd)
1302 nbd->task_setup = NULL;
1305 static void nbd_config_put(struct nbd_device *nbd)
1307 if (refcount_dec_and_mutex_lock(&nbd->config_refs,
1308 &nbd->config_lock)) {
1309 struct nbd_config *config = nbd->config;
1310 nbd_dev_dbg_close(nbd);
1311 invalidate_disk(nbd->disk);
1312 if (nbd->config->bytesize)
1313 kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
1314 if (test_and_clear_bit(NBD_RT_HAS_PID_FILE,
1315 &config->runtime_flags))
1316 device_remove_file(disk_to_dev(nbd->disk), &pid_attr);
1318 if (test_and_clear_bit(NBD_RT_HAS_BACKEND_FILE,
1319 &config->runtime_flags)) {
1320 device_remove_file(disk_to_dev(nbd->disk), &backend_attr);
1321 kfree(nbd->backend);
1322 nbd->backend = NULL;
1324 nbd_clear_sock(nbd);
1325 if (config->num_connections) {
1327 for (i = 0; i < config->num_connections; i++) {
1328 sockfd_put(config->socks[i]->sock);
1329 kfree(config->socks[i]);
1331 kfree(config->socks);
1336 nbd->tag_set.timeout = 0;
1337 nbd->disk->queue->limits.discard_granularity = 0;
1338 blk_queue_max_discard_sectors(nbd->disk->queue, 0);
1340 mutex_unlock(&nbd->config_lock);
1342 module_put(THIS_MODULE);
1346 static int nbd_start_device(struct nbd_device *nbd)
1348 struct nbd_config *config = nbd->config;
1349 int num_connections = config->num_connections;
1356 if (num_connections > 1 &&
1357 !(config->flags & NBD_FLAG_CAN_MULTI_CONN)) {
1358 dev_err(disk_to_dev(nbd->disk), "server does not support multiple connections per device.\n");
1362 blk_mq_update_nr_hw_queues(&nbd->tag_set, config->num_connections);
1363 nbd->pid = task_pid_nr(current);
1365 nbd_parse_flags(nbd);
1367 error = device_create_file(disk_to_dev(nbd->disk), &pid_attr);
1369 dev_err(disk_to_dev(nbd->disk), "device_create_file failed for pid!\n");
1372 set_bit(NBD_RT_HAS_PID_FILE, &config->runtime_flags);
1374 nbd_dev_dbg_init(nbd);
1375 for (i = 0; i < num_connections; i++) {
1376 struct recv_thread_args *args;
1378 args = kzalloc(sizeof(*args), GFP_KERNEL);
1382 * If num_connections is m (2 < m),
1383 * and NO.1 ~ NO.n(1 < n < m) kzallocs are successful.
1384 * But NO.(n + 1) failed. We still have n recv threads.
1385 * So, add flush_workqueue here to prevent recv threads
1386 * dropping the last config_refs and trying to destroy
1387 * the workqueue from inside the workqueue.
1390 flush_workqueue(nbd->recv_workq);
1393 sk_set_memalloc(config->socks[i]->sock->sk);
1394 if (nbd->tag_set.timeout)
1395 config->socks[i]->sock->sk->sk_sndtimeo =
1396 nbd->tag_set.timeout;
1397 atomic_inc(&config->recv_threads);
1398 refcount_inc(&nbd->config_refs);
1399 INIT_WORK(&args->work, recv_work);
1402 queue_work(nbd->recv_workq, &args->work);
1404 return nbd_set_size(nbd, config->bytesize, nbd_blksize(config));
1407 static int nbd_start_device_ioctl(struct nbd_device *nbd)
1409 struct nbd_config *config = nbd->config;
1412 ret = nbd_start_device(nbd);
1417 set_bit(GD_NEED_PART_SCAN, &nbd->disk->state);
1418 mutex_unlock(&nbd->config_lock);
1419 ret = wait_event_interruptible(config->recv_wq,
1420 atomic_read(&config->recv_threads) == 0);
1426 flush_workqueue(nbd->recv_workq);
1427 mutex_lock(&nbd->config_lock);
1428 nbd_bdev_reset(nbd);
1429 /* user requested, ignore socket errors */
1430 if (test_bit(NBD_RT_DISCONNECT_REQUESTED, &config->runtime_flags))
1432 if (test_bit(NBD_RT_TIMEDOUT, &config->runtime_flags))
1437 static void nbd_clear_sock_ioctl(struct nbd_device *nbd)
1439 nbd_clear_sock(nbd);
1440 disk_force_media_change(nbd->disk);
1441 nbd_bdev_reset(nbd);
1442 if (test_and_clear_bit(NBD_RT_HAS_CONFIG_REF,
1443 &nbd->config->runtime_flags))
1444 nbd_config_put(nbd);
1447 static void nbd_set_cmd_timeout(struct nbd_device *nbd, u64 timeout)
1449 nbd->tag_set.timeout = timeout * HZ;
1451 blk_queue_rq_timeout(nbd->disk->queue, timeout * HZ);
1453 blk_queue_rq_timeout(nbd->disk->queue, 30 * HZ);
1456 /* Must be called with config_lock held */
1457 static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
1458 unsigned int cmd, unsigned long arg)
1460 struct nbd_config *config = nbd->config;
1464 case NBD_DISCONNECT:
1465 return nbd_disconnect(nbd);
1466 case NBD_CLEAR_SOCK:
1467 nbd_clear_sock_ioctl(nbd);
1470 return nbd_add_socket(nbd, arg, false);
1471 case NBD_SET_BLKSIZE:
1472 return nbd_set_size(nbd, config->bytesize, arg);
1474 return nbd_set_size(nbd, arg, nbd_blksize(config));
1475 case NBD_SET_SIZE_BLOCKS:
1476 if (check_shl_overflow(arg, config->blksize_bits, &bytesize))
1478 return nbd_set_size(nbd, bytesize, nbd_blksize(config));
1479 case NBD_SET_TIMEOUT:
1480 nbd_set_cmd_timeout(nbd, arg);
1484 config->flags = arg;
1487 return nbd_start_device_ioctl(nbd);
1490 * This is for compatibility only. The queue is always cleared
1491 * by NBD_DO_IT or NBD_CLEAR_SOCK.
1494 case NBD_PRINT_DEBUG:
1496 * For compatibility only, we no longer keep a list of
1497 * outstanding requests.
1504 static int nbd_ioctl(struct block_device *bdev, blk_mode_t mode,
1505 unsigned int cmd, unsigned long arg)
1507 struct nbd_device *nbd = bdev->bd_disk->private_data;
1508 struct nbd_config *config = nbd->config;
1509 int error = -EINVAL;
1511 if (!capable(CAP_SYS_ADMIN))
1514 /* The block layer will pass back some non-nbd ioctls in case we have
1515 * special handling for them, but we don't so just return an error.
1517 if (_IOC_TYPE(cmd) != 0xab)
1520 mutex_lock(&nbd->config_lock);
1522 /* Don't allow ioctl operations on a nbd device that was created with
1523 * netlink, unless it's DISCONNECT or CLEAR_SOCK, which are fine.
1525 if (!test_bit(NBD_RT_BOUND, &config->runtime_flags) ||
1526 (cmd == NBD_DISCONNECT || cmd == NBD_CLEAR_SOCK))
1527 error = __nbd_ioctl(bdev, nbd, cmd, arg);
1529 dev_err(nbd_to_dev(nbd), "Cannot use ioctl interface on a netlink controlled device.\n");
1530 mutex_unlock(&nbd->config_lock);
1534 static struct nbd_config *nbd_alloc_config(void)
1536 struct nbd_config *config;
1538 if (!try_module_get(THIS_MODULE))
1539 return ERR_PTR(-ENODEV);
1541 config = kzalloc(sizeof(struct nbd_config), GFP_NOFS);
1543 module_put(THIS_MODULE);
1544 return ERR_PTR(-ENOMEM);
1547 atomic_set(&config->recv_threads, 0);
1548 init_waitqueue_head(&config->recv_wq);
1549 init_waitqueue_head(&config->conn_wait);
1550 config->blksize_bits = NBD_DEF_BLKSIZE_BITS;
1551 atomic_set(&config->live_connections, 0);
1555 static int nbd_open(struct gendisk *disk, blk_mode_t mode)
1557 struct nbd_device *nbd;
1560 mutex_lock(&nbd_index_mutex);
1561 nbd = disk->private_data;
1566 if (!refcount_inc_not_zero(&nbd->refs)) {
1570 if (!refcount_inc_not_zero(&nbd->config_refs)) {
1571 struct nbd_config *config;
1573 mutex_lock(&nbd->config_lock);
1574 if (refcount_inc_not_zero(&nbd->config_refs)) {
1575 mutex_unlock(&nbd->config_lock);
1578 config = nbd_alloc_config();
1579 if (IS_ERR(config)) {
1580 ret = PTR_ERR(config);
1581 mutex_unlock(&nbd->config_lock);
1584 nbd->config = config;
1585 refcount_set(&nbd->config_refs, 1);
1586 refcount_inc(&nbd->refs);
1587 mutex_unlock(&nbd->config_lock);
1589 set_bit(GD_NEED_PART_SCAN, &disk->state);
1590 } else if (nbd_disconnected(nbd->config)) {
1592 set_bit(GD_NEED_PART_SCAN, &disk->state);
1595 mutex_unlock(&nbd_index_mutex);
1599 static void nbd_release(struct gendisk *disk)
1601 struct nbd_device *nbd = disk->private_data;
1603 if (test_bit(NBD_RT_DISCONNECT_ON_CLOSE, &nbd->config->runtime_flags) &&
1604 disk_openers(disk) == 0)
1605 nbd_disconnect_and_put(nbd);
1607 nbd_config_put(nbd);
1611 static const struct block_device_operations nbd_fops =
1613 .owner = THIS_MODULE,
1615 .release = nbd_release,
1617 .compat_ioctl = nbd_ioctl,
1620 #if IS_ENABLED(CONFIG_DEBUG_FS)
1622 static int nbd_dbg_tasks_show(struct seq_file *s, void *unused)
1624 struct nbd_device *nbd = s->private;
1627 seq_printf(s, "recv: %d\n", nbd->pid);
1632 DEFINE_SHOW_ATTRIBUTE(nbd_dbg_tasks);
1634 static int nbd_dbg_flags_show(struct seq_file *s, void *unused)
1636 struct nbd_device *nbd = s->private;
1637 u32 flags = nbd->config->flags;
1639 seq_printf(s, "Hex: 0x%08x\n\n", flags);
1641 seq_puts(s, "Known flags:\n");
1643 if (flags & NBD_FLAG_HAS_FLAGS)
1644 seq_puts(s, "NBD_FLAG_HAS_FLAGS\n");
1645 if (flags & NBD_FLAG_READ_ONLY)
1646 seq_puts(s, "NBD_FLAG_READ_ONLY\n");
1647 if (flags & NBD_FLAG_SEND_FLUSH)
1648 seq_puts(s, "NBD_FLAG_SEND_FLUSH\n");
1649 if (flags & NBD_FLAG_SEND_FUA)
1650 seq_puts(s, "NBD_FLAG_SEND_FUA\n");
1651 if (flags & NBD_FLAG_SEND_TRIM)
1652 seq_puts(s, "NBD_FLAG_SEND_TRIM\n");
1657 DEFINE_SHOW_ATTRIBUTE(nbd_dbg_flags);
1659 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1662 struct nbd_config *config = nbd->config;
1667 dir = debugfs_create_dir(nbd_name(nbd), nbd_dbg_dir);
1669 dev_err(nbd_to_dev(nbd), "Failed to create debugfs dir for '%s'\n",
1673 config->dbg_dir = dir;
1675 debugfs_create_file("tasks", 0444, dir, nbd, &nbd_dbg_tasks_fops);
1676 debugfs_create_u64("size_bytes", 0444, dir, &config->bytesize);
1677 debugfs_create_u32("timeout", 0444, dir, &nbd->tag_set.timeout);
1678 debugfs_create_u32("blocksize_bits", 0444, dir, &config->blksize_bits);
1679 debugfs_create_file("flags", 0444, dir, nbd, &nbd_dbg_flags_fops);
1684 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1686 debugfs_remove_recursive(nbd->config->dbg_dir);
1689 static int nbd_dbg_init(void)
1691 struct dentry *dbg_dir;
1693 dbg_dir = debugfs_create_dir("nbd", NULL);
1694 if (IS_ERR(dbg_dir))
1697 nbd_dbg_dir = dbg_dir;
1702 static void nbd_dbg_close(void)
1704 debugfs_remove_recursive(nbd_dbg_dir);
1707 #else /* IS_ENABLED(CONFIG_DEBUG_FS) */
1709 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1714 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1718 static int nbd_dbg_init(void)
1723 static void nbd_dbg_close(void)
1729 static int nbd_init_request(struct blk_mq_tag_set *set, struct request *rq,
1730 unsigned int hctx_idx, unsigned int numa_node)
1732 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(rq);
1733 cmd->nbd = set->driver_data;
1735 mutex_init(&cmd->lock);
1739 static const struct blk_mq_ops nbd_mq_ops = {
1740 .queue_rq = nbd_queue_rq,
1741 .complete = nbd_complete_rq,
1742 .init_request = nbd_init_request,
1743 .timeout = nbd_xmit_timeout,
1746 static struct nbd_device *nbd_dev_add(int index, unsigned int refs)
1748 struct nbd_device *nbd;
1749 struct gendisk *disk;
1752 nbd = kzalloc(sizeof(struct nbd_device), GFP_KERNEL);
1756 nbd->tag_set.ops = &nbd_mq_ops;
1757 nbd->tag_set.nr_hw_queues = 1;
1758 nbd->tag_set.queue_depth = 128;
1759 nbd->tag_set.numa_node = NUMA_NO_NODE;
1760 nbd->tag_set.cmd_size = sizeof(struct nbd_cmd);
1761 nbd->tag_set.flags = BLK_MQ_F_SHOULD_MERGE |
1763 nbd->tag_set.driver_data = nbd;
1764 INIT_WORK(&nbd->remove_work, nbd_dev_remove_work);
1765 nbd->backend = NULL;
1767 err = blk_mq_alloc_tag_set(&nbd->tag_set);
1771 mutex_lock(&nbd_index_mutex);
1773 err = idr_alloc(&nbd_index_idr, nbd, index, index + 1,
1778 err = idr_alloc(&nbd_index_idr, nbd, 0,
1779 (MINORMASK >> part_shift) + 1, GFP_KERNEL);
1784 mutex_unlock(&nbd_index_mutex);
1788 disk = blk_mq_alloc_disk(&nbd->tag_set, NULL);
1790 err = PTR_ERR(disk);
1795 nbd->recv_workq = alloc_workqueue("nbd%d-recv",
1796 WQ_MEM_RECLAIM | WQ_HIGHPRI |
1797 WQ_UNBOUND, 0, nbd->index);
1798 if (!nbd->recv_workq) {
1799 dev_err(disk_to_dev(nbd->disk), "Could not allocate knbd recv work queue.\n");
1805 * Tell the block layer that we are not a rotational device
1807 blk_queue_flag_set(QUEUE_FLAG_NONROT, disk->queue);
1808 disk->queue->limits.discard_granularity = 0;
1809 blk_queue_max_discard_sectors(disk->queue, 0);
1810 blk_queue_max_segment_size(disk->queue, UINT_MAX);
1811 blk_queue_max_segments(disk->queue, USHRT_MAX);
1812 blk_queue_max_hw_sectors(disk->queue, 65536);
1813 disk->queue->limits.max_sectors = 256;
1815 mutex_init(&nbd->config_lock);
1816 refcount_set(&nbd->config_refs, 0);
1818 * Start out with a zero references to keep other threads from using
1819 * this device until it is fully initialized.
1821 refcount_set(&nbd->refs, 0);
1822 INIT_LIST_HEAD(&nbd->list);
1823 disk->major = NBD_MAJOR;
1824 disk->first_minor = index << part_shift;
1825 disk->minors = 1 << part_shift;
1826 disk->fops = &nbd_fops;
1827 disk->private_data = nbd;
1828 sprintf(disk->disk_name, "nbd%d", index);
1829 err = add_disk(disk);
1834 * Now publish the device.
1836 refcount_set(&nbd->refs, refs);
1837 nbd_total_devices++;
1841 destroy_workqueue(nbd->recv_workq);
1845 mutex_lock(&nbd_index_mutex);
1846 idr_remove(&nbd_index_idr, index);
1847 mutex_unlock(&nbd_index_mutex);
1849 blk_mq_free_tag_set(&nbd->tag_set);
1853 return ERR_PTR(err);
1856 static struct nbd_device *nbd_find_get_unused(void)
1858 struct nbd_device *nbd;
1861 lockdep_assert_held(&nbd_index_mutex);
1863 idr_for_each_entry(&nbd_index_idr, nbd, id) {
1864 if (refcount_read(&nbd->config_refs) ||
1865 test_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags))
1867 if (refcount_inc_not_zero(&nbd->refs))
1874 /* Netlink interface. */
1875 static const struct nla_policy nbd_attr_policy[NBD_ATTR_MAX + 1] = {
1876 [NBD_ATTR_INDEX] = { .type = NLA_U32 },
1877 [NBD_ATTR_SIZE_BYTES] = { .type = NLA_U64 },
1878 [NBD_ATTR_BLOCK_SIZE_BYTES] = { .type = NLA_U64 },
1879 [NBD_ATTR_TIMEOUT] = { .type = NLA_U64 },
1880 [NBD_ATTR_SERVER_FLAGS] = { .type = NLA_U64 },
1881 [NBD_ATTR_CLIENT_FLAGS] = { .type = NLA_U64 },
1882 [NBD_ATTR_SOCKETS] = { .type = NLA_NESTED},
1883 [NBD_ATTR_DEAD_CONN_TIMEOUT] = { .type = NLA_U64 },
1884 [NBD_ATTR_DEVICE_LIST] = { .type = NLA_NESTED},
1885 [NBD_ATTR_BACKEND_IDENTIFIER] = { .type = NLA_STRING},
1888 static const struct nla_policy nbd_sock_policy[NBD_SOCK_MAX + 1] = {
1889 [NBD_SOCK_FD] = { .type = NLA_U32 },
1892 /* We don't use this right now since we don't parse the incoming list, but we
1893 * still want it here so userspace knows what to expect.
1895 static const struct nla_policy __attribute__((unused))
1896 nbd_device_policy[NBD_DEVICE_ATTR_MAX + 1] = {
1897 [NBD_DEVICE_INDEX] = { .type = NLA_U32 },
1898 [NBD_DEVICE_CONNECTED] = { .type = NLA_U8 },
1901 static int nbd_genl_size_set(struct genl_info *info, struct nbd_device *nbd)
1903 struct nbd_config *config = nbd->config;
1904 u64 bsize = nbd_blksize(config);
1905 u64 bytes = config->bytesize;
1907 if (info->attrs[NBD_ATTR_SIZE_BYTES])
1908 bytes = nla_get_u64(info->attrs[NBD_ATTR_SIZE_BYTES]);
1910 if (info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES])
1911 bsize = nla_get_u64(info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]);
1913 if (bytes != config->bytesize || bsize != nbd_blksize(config))
1914 return nbd_set_size(nbd, bytes, bsize);
1918 static int nbd_genl_connect(struct sk_buff *skb, struct genl_info *info)
1920 struct nbd_device *nbd;
1921 struct nbd_config *config;
1924 bool put_dev = false;
1926 if (!netlink_capable(skb, CAP_SYS_ADMIN))
1929 if (info->attrs[NBD_ATTR_INDEX]) {
1930 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1933 * Too big first_minor can cause duplicate creation of
1934 * sysfs files/links, since index << part_shift might overflow, or
1935 * MKDEV() expect that the max bits of first_minor is 20.
1937 if (index < 0 || index > MINORMASK >> part_shift) {
1938 pr_err("illegal input index %d\n", index);
1942 if (GENL_REQ_ATTR_CHECK(info, NBD_ATTR_SOCKETS)) {
1943 pr_err("must specify at least one socket\n");
1946 if (GENL_REQ_ATTR_CHECK(info, NBD_ATTR_SIZE_BYTES)) {
1947 pr_err("must specify a size in bytes for the device\n");
1951 mutex_lock(&nbd_index_mutex);
1953 nbd = nbd_find_get_unused();
1955 nbd = idr_find(&nbd_index_idr, index);
1957 if ((test_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags) &&
1958 test_bit(NBD_DISCONNECT_REQUESTED, &nbd->flags)) ||
1959 !refcount_inc_not_zero(&nbd->refs)) {
1960 mutex_unlock(&nbd_index_mutex);
1961 pr_err("device at index %d is going down\n",
1967 mutex_unlock(&nbd_index_mutex);
1970 nbd = nbd_dev_add(index, 2);
1972 pr_err("failed to add new device\n");
1973 return PTR_ERR(nbd);
1977 mutex_lock(&nbd->config_lock);
1978 if (refcount_read(&nbd->config_refs)) {
1979 mutex_unlock(&nbd->config_lock);
1983 pr_err("nbd%d already in use\n", index);
1986 if (WARN_ON(nbd->config)) {
1987 mutex_unlock(&nbd->config_lock);
1991 config = nbd_alloc_config();
1992 if (IS_ERR(config)) {
1993 mutex_unlock(&nbd->config_lock);
1995 pr_err("couldn't allocate config\n");
1996 return PTR_ERR(config);
1998 nbd->config = config;
1999 refcount_set(&nbd->config_refs, 1);
2000 set_bit(NBD_RT_BOUND, &config->runtime_flags);
2002 ret = nbd_genl_size_set(info, nbd);
2006 if (info->attrs[NBD_ATTR_TIMEOUT])
2007 nbd_set_cmd_timeout(nbd,
2008 nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]));
2009 if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
2010 config->dead_conn_timeout =
2011 nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
2012 config->dead_conn_timeout *= HZ;
2014 if (info->attrs[NBD_ATTR_SERVER_FLAGS])
2016 nla_get_u64(info->attrs[NBD_ATTR_SERVER_FLAGS]);
2017 if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
2018 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
2019 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
2021 * We have 1 ref to keep the device around, and then 1
2022 * ref for our current operation here, which will be
2023 * inherited by the config. If we already have
2024 * DESTROY_ON_DISCONNECT set then we know we don't have
2025 * that extra ref already held so we don't need the
2028 if (!test_and_set_bit(NBD_DESTROY_ON_DISCONNECT,
2032 if (test_and_clear_bit(NBD_DESTROY_ON_DISCONNECT,
2034 refcount_inc(&nbd->refs);
2036 if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
2037 set_bit(NBD_RT_DISCONNECT_ON_CLOSE,
2038 &config->runtime_flags);
2042 if (info->attrs[NBD_ATTR_SOCKETS]) {
2043 struct nlattr *attr;
2046 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
2048 struct nlattr *socks[NBD_SOCK_MAX+1];
2050 if (nla_type(attr) != NBD_SOCK_ITEM) {
2051 pr_err("socks must be embedded in a SOCK_ITEM attr\n");
2055 ret = nla_parse_nested_deprecated(socks, NBD_SOCK_MAX,
2060 pr_err("error processing sock list\n");
2064 if (!socks[NBD_SOCK_FD])
2066 fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
2067 ret = nbd_add_socket(nbd, fd, true);
2072 ret = nbd_start_device(nbd);
2075 if (info->attrs[NBD_ATTR_BACKEND_IDENTIFIER]) {
2076 nbd->backend = nla_strdup(info->attrs[NBD_ATTR_BACKEND_IDENTIFIER],
2078 if (!nbd->backend) {
2083 ret = device_create_file(disk_to_dev(nbd->disk), &backend_attr);
2085 dev_err(disk_to_dev(nbd->disk),
2086 "device_create_file failed for backend!\n");
2089 set_bit(NBD_RT_HAS_BACKEND_FILE, &config->runtime_flags);
2091 mutex_unlock(&nbd->config_lock);
2093 set_bit(NBD_RT_HAS_CONFIG_REF, &config->runtime_flags);
2094 refcount_inc(&nbd->config_refs);
2095 nbd_connect_reply(info, nbd->index);
2097 nbd_config_put(nbd);
2103 static void nbd_disconnect_and_put(struct nbd_device *nbd)
2105 mutex_lock(&nbd->config_lock);
2106 nbd_disconnect(nbd);
2108 wake_up(&nbd->config->conn_wait);
2110 * Make sure recv thread has finished, we can safely call nbd_clear_que()
2111 * to cancel the inflight I/Os.
2113 flush_workqueue(nbd->recv_workq);
2115 nbd->task_setup = NULL;
2116 mutex_unlock(&nbd->config_lock);
2118 if (test_and_clear_bit(NBD_RT_HAS_CONFIG_REF,
2119 &nbd->config->runtime_flags))
2120 nbd_config_put(nbd);
2123 static int nbd_genl_disconnect(struct sk_buff *skb, struct genl_info *info)
2125 struct nbd_device *nbd;
2128 if (!netlink_capable(skb, CAP_SYS_ADMIN))
2131 if (GENL_REQ_ATTR_CHECK(info, NBD_ATTR_INDEX)) {
2132 pr_err("must specify an index to disconnect\n");
2135 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2136 mutex_lock(&nbd_index_mutex);
2137 nbd = idr_find(&nbd_index_idr, index);
2139 mutex_unlock(&nbd_index_mutex);
2140 pr_err("couldn't find device at index %d\n", index);
2143 if (!refcount_inc_not_zero(&nbd->refs)) {
2144 mutex_unlock(&nbd_index_mutex);
2145 pr_err("device at index %d is going down\n", index);
2148 mutex_unlock(&nbd_index_mutex);
2149 if (!refcount_inc_not_zero(&nbd->config_refs))
2151 nbd_disconnect_and_put(nbd);
2152 nbd_config_put(nbd);
2158 static int nbd_genl_reconfigure(struct sk_buff *skb, struct genl_info *info)
2160 struct nbd_device *nbd = NULL;
2161 struct nbd_config *config;
2164 bool put_dev = false;
2166 if (!netlink_capable(skb, CAP_SYS_ADMIN))
2169 if (GENL_REQ_ATTR_CHECK(info, NBD_ATTR_INDEX)) {
2170 pr_err("must specify a device to reconfigure\n");
2173 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2174 mutex_lock(&nbd_index_mutex);
2175 nbd = idr_find(&nbd_index_idr, index);
2177 mutex_unlock(&nbd_index_mutex);
2178 pr_err("couldn't find a device at index %d\n", index);
2182 if (info->attrs[NBD_ATTR_BACKEND_IDENTIFIER]) {
2183 if (nla_strcmp(info->attrs[NBD_ATTR_BACKEND_IDENTIFIER],
2185 mutex_unlock(&nbd_index_mutex);
2186 dev_err(nbd_to_dev(nbd),
2187 "backend image doesn't match with %s\n",
2192 mutex_unlock(&nbd_index_mutex);
2193 dev_err(nbd_to_dev(nbd), "must specify backend\n");
2197 if (!refcount_inc_not_zero(&nbd->refs)) {
2198 mutex_unlock(&nbd_index_mutex);
2199 pr_err("device at index %d is going down\n", index);
2202 mutex_unlock(&nbd_index_mutex);
2204 if (!refcount_inc_not_zero(&nbd->config_refs)) {
2205 dev_err(nbd_to_dev(nbd),
2206 "not configured, cannot reconfigure\n");
2211 mutex_lock(&nbd->config_lock);
2212 config = nbd->config;
2213 if (!test_bit(NBD_RT_BOUND, &config->runtime_flags) ||
2215 dev_err(nbd_to_dev(nbd),
2216 "not configured, cannot reconfigure\n");
2221 ret = nbd_genl_size_set(info, nbd);
2225 if (info->attrs[NBD_ATTR_TIMEOUT])
2226 nbd_set_cmd_timeout(nbd,
2227 nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]));
2228 if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
2229 config->dead_conn_timeout =
2230 nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
2231 config->dead_conn_timeout *= HZ;
2233 if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
2234 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
2235 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
2236 if (!test_and_set_bit(NBD_DESTROY_ON_DISCONNECT,
2240 if (test_and_clear_bit(NBD_DESTROY_ON_DISCONNECT,
2242 refcount_inc(&nbd->refs);
2245 if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
2246 set_bit(NBD_RT_DISCONNECT_ON_CLOSE,
2247 &config->runtime_flags);
2249 clear_bit(NBD_RT_DISCONNECT_ON_CLOSE,
2250 &config->runtime_flags);
2254 if (info->attrs[NBD_ATTR_SOCKETS]) {
2255 struct nlattr *attr;
2258 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
2260 struct nlattr *socks[NBD_SOCK_MAX+1];
2262 if (nla_type(attr) != NBD_SOCK_ITEM) {
2263 pr_err("socks must be embedded in a SOCK_ITEM attr\n");
2267 ret = nla_parse_nested_deprecated(socks, NBD_SOCK_MAX,
2272 pr_err("error processing sock list\n");
2276 if (!socks[NBD_SOCK_FD])
2278 fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
2279 ret = nbd_reconnect_socket(nbd, fd);
2285 dev_info(nbd_to_dev(nbd), "reconnected socket\n");
2289 mutex_unlock(&nbd->config_lock);
2290 nbd_config_put(nbd);
2297 static const struct genl_small_ops nbd_connect_genl_ops[] = {
2299 .cmd = NBD_CMD_CONNECT,
2300 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2301 .doit = nbd_genl_connect,
2304 .cmd = NBD_CMD_DISCONNECT,
2305 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2306 .doit = nbd_genl_disconnect,
2309 .cmd = NBD_CMD_RECONFIGURE,
2310 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2311 .doit = nbd_genl_reconfigure,
2314 .cmd = NBD_CMD_STATUS,
2315 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2316 .doit = nbd_genl_status,
2320 static const struct genl_multicast_group nbd_mcast_grps[] = {
2321 { .name = NBD_GENL_MCAST_GROUP_NAME, },
2324 static struct genl_family nbd_genl_family __ro_after_init = {
2326 .name = NBD_GENL_FAMILY_NAME,
2327 .version = NBD_GENL_VERSION,
2328 .module = THIS_MODULE,
2329 .small_ops = nbd_connect_genl_ops,
2330 .n_small_ops = ARRAY_SIZE(nbd_connect_genl_ops),
2331 .resv_start_op = NBD_CMD_STATUS + 1,
2332 .maxattr = NBD_ATTR_MAX,
2334 .policy = nbd_attr_policy,
2335 .mcgrps = nbd_mcast_grps,
2336 .n_mcgrps = ARRAY_SIZE(nbd_mcast_grps),
2338 MODULE_ALIAS_GENL_FAMILY(NBD_GENL_FAMILY_NAME);
2340 static int populate_nbd_status(struct nbd_device *nbd, struct sk_buff *reply)
2342 struct nlattr *dev_opt;
2346 /* This is a little racey, but for status it's ok. The
2347 * reason we don't take a ref here is because we can't
2348 * take a ref in the index == -1 case as we would need
2349 * to put under the nbd_index_mutex, which could
2350 * deadlock if we are configured to remove ourselves
2351 * once we're disconnected.
2353 if (refcount_read(&nbd->config_refs))
2355 dev_opt = nla_nest_start_noflag(reply, NBD_DEVICE_ITEM);
2358 ret = nla_put_u32(reply, NBD_DEVICE_INDEX, nbd->index);
2361 ret = nla_put_u8(reply, NBD_DEVICE_CONNECTED,
2365 nla_nest_end(reply, dev_opt);
2369 static int status_cb(int id, void *ptr, void *data)
2371 struct nbd_device *nbd = ptr;
2372 return populate_nbd_status(nbd, (struct sk_buff *)data);
2375 static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info)
2377 struct nlattr *dev_list;
2378 struct sk_buff *reply;
2384 if (info->attrs[NBD_ATTR_INDEX])
2385 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2387 mutex_lock(&nbd_index_mutex);
2389 msg_size = nla_total_size(nla_attr_size(sizeof(u32)) +
2390 nla_attr_size(sizeof(u8)));
2391 msg_size *= (index == -1) ? nbd_total_devices : 1;
2393 reply = genlmsg_new(msg_size, GFP_KERNEL);
2396 reply_head = genlmsg_put_reply(reply, info, &nbd_genl_family, 0,
2403 dev_list = nla_nest_start_noflag(reply, NBD_ATTR_DEVICE_LIST);
2405 ret = idr_for_each(&nbd_index_idr, &status_cb, reply);
2411 struct nbd_device *nbd;
2412 nbd = idr_find(&nbd_index_idr, index);
2414 ret = populate_nbd_status(nbd, reply);
2421 nla_nest_end(reply, dev_list);
2422 genlmsg_end(reply, reply_head);
2423 ret = genlmsg_reply(reply, info);
2425 mutex_unlock(&nbd_index_mutex);
2429 static void nbd_connect_reply(struct genl_info *info, int index)
2431 struct sk_buff *skb;
2435 skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2438 msg_head = genlmsg_put_reply(skb, info, &nbd_genl_family, 0,
2444 ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2449 genlmsg_end(skb, msg_head);
2450 genlmsg_reply(skb, info);
2453 static void nbd_mcast_index(int index)
2455 struct sk_buff *skb;
2459 skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2462 msg_head = genlmsg_put(skb, 0, 0, &nbd_genl_family, 0,
2468 ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2473 genlmsg_end(skb, msg_head);
2474 genlmsg_multicast(&nbd_genl_family, skb, 0, 0, GFP_KERNEL);
2477 static void nbd_dead_link_work(struct work_struct *work)
2479 struct link_dead_args *args = container_of(work, struct link_dead_args,
2481 nbd_mcast_index(args->index);
2485 static int __init nbd_init(void)
2489 BUILD_BUG_ON(sizeof(struct nbd_request) != 28);
2492 pr_err("max_part must be >= 0\n");
2498 part_shift = fls(max_part);
2501 * Adjust max_part according to part_shift as it is exported
2502 * to user space so that user can know the max number of
2503 * partition kernel should be able to manage.
2505 * Note that -1 is required because partition 0 is reserved
2506 * for the whole disk.
2508 max_part = (1UL << part_shift) - 1;
2511 if ((1UL << part_shift) > DISK_MAX_PARTS)
2514 if (nbds_max > 1UL << (MINORBITS - part_shift))
2517 if (register_blkdev(NBD_MAJOR, "nbd"))
2520 nbd_del_wq = alloc_workqueue("nbd-del", WQ_UNBOUND, 0);
2522 unregister_blkdev(NBD_MAJOR, "nbd");
2526 if (genl_register_family(&nbd_genl_family)) {
2527 destroy_workqueue(nbd_del_wq);
2528 unregister_blkdev(NBD_MAJOR, "nbd");
2533 for (i = 0; i < nbds_max; i++)
2538 static int nbd_exit_cb(int id, void *ptr, void *data)
2540 struct list_head *list = (struct list_head *)data;
2541 struct nbd_device *nbd = ptr;
2543 /* Skip nbd that is being removed asynchronously */
2544 if (refcount_read(&nbd->refs))
2545 list_add_tail(&nbd->list, list);
2550 static void __exit nbd_cleanup(void)
2552 struct nbd_device *nbd;
2553 LIST_HEAD(del_list);
2556 * Unregister netlink interface prior to waiting
2557 * for the completion of netlink commands.
2559 genl_unregister_family(&nbd_genl_family);
2563 mutex_lock(&nbd_index_mutex);
2564 idr_for_each(&nbd_index_idr, &nbd_exit_cb, &del_list);
2565 mutex_unlock(&nbd_index_mutex);
2567 while (!list_empty(&del_list)) {
2568 nbd = list_first_entry(&del_list, struct nbd_device, list);
2569 list_del_init(&nbd->list);
2570 if (refcount_read(&nbd->config_refs))
2571 pr_err("possibly leaking nbd_config (ref %d)\n",
2572 refcount_read(&nbd->config_refs));
2573 if (refcount_read(&nbd->refs) != 1)
2574 pr_err("possibly leaking a device\n");
2578 /* Also wait for nbd_dev_remove_work() completes */
2579 destroy_workqueue(nbd_del_wq);
2581 idr_destroy(&nbd_index_idr);
2582 unregister_blkdev(NBD_MAJOR, "nbd");
2585 module_init(nbd_init);
2586 module_exit(nbd_cleanup);
2588 MODULE_DESCRIPTION("Network Block Device");
2589 MODULE_LICENSE("GPL");
2591 module_param(nbds_max, int, 0444);
2592 MODULE_PARM_DESC(nbds_max, "number of network block devices to initialize (default: 16)");
2593 module_param(max_part, int, 0444);
2594 MODULE_PARM_DESC(max_part, "number of partitions per device (default: 16)");