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 #include <linux/major.h>
16 #include <linux/blkdev.h>
17 #include <linux/module.h>
18 #include <linux/init.h>
19 #include <linux/sched.h>
20 #include <linux/sched/mm.h>
22 #include <linux/bio.h>
23 #include <linux/stat.h>
24 #include <linux/errno.h>
25 #include <linux/file.h>
26 #include <linux/ioctl.h>
27 #include <linux/mutex.h>
28 #include <linux/compiler.h>
29 #include <linux/completion.h>
30 #include <linux/err.h>
31 #include <linux/kernel.h>
32 #include <linux/slab.h>
34 #include <linux/net.h>
35 #include <linux/kthread.h>
36 #include <linux/types.h>
37 #include <linux/debugfs.h>
38 #include <linux/blk-mq.h>
40 #include <linux/uaccess.h>
41 #include <asm/types.h>
43 #include <linux/nbd.h>
44 #include <linux/nbd-netlink.h>
45 #include <net/genetlink.h>
47 #define CREATE_TRACE_POINTS
48 #include <trace/events/nbd.h>
50 static DEFINE_IDR(nbd_index_idr);
51 static DEFINE_MUTEX(nbd_index_mutex);
52 static struct workqueue_struct *nbd_del_wq;
53 static int nbd_total_devices = 0;
58 struct request *pending;
65 struct recv_thread_args {
66 struct work_struct work;
67 struct nbd_device *nbd;
71 struct link_dead_args {
72 struct work_struct work;
76 #define NBD_RT_TIMEDOUT 0
77 #define NBD_RT_DISCONNECT_REQUESTED 1
78 #define NBD_RT_DISCONNECTED 2
79 #define NBD_RT_HAS_PID_FILE 3
80 #define NBD_RT_HAS_CONFIG_REF 4
81 #define NBD_RT_BOUND 5
82 #define NBD_RT_DISCONNECT_ON_CLOSE 6
83 #define NBD_RT_HAS_BACKEND_FILE 7
85 #define NBD_DESTROY_ON_DISCONNECT 0
86 #define NBD_DISCONNECT_REQUESTED 1
90 unsigned long runtime_flags;
91 u64 dead_conn_timeout;
93 struct nbd_sock **socks;
95 atomic_t live_connections;
96 wait_queue_head_t conn_wait;
98 atomic_t recv_threads;
99 wait_queue_head_t recv_wq;
100 unsigned int blksize_bits;
102 #if IS_ENABLED(CONFIG_DEBUG_FS)
103 struct dentry *dbg_dir;
107 static inline unsigned int nbd_blksize(struct nbd_config *config)
109 return 1u << config->blksize_bits;
113 struct blk_mq_tag_set tag_set;
116 refcount_t config_refs;
118 struct nbd_config *config;
119 struct mutex config_lock;
120 struct gendisk *disk;
121 struct workqueue_struct *recv_workq;
122 struct work_struct remove_work;
124 struct list_head list;
125 struct task_struct *task_setup;
128 pid_t pid; /* pid of nbd-client, if attached */
133 #define NBD_CMD_REQUEUED 1
135 * This flag will be set if nbd_queue_rq() succeed, and will be checked and
136 * cleared in completion. Both setting and clearing of the flag are protected
139 #define NBD_CMD_INFLIGHT 2
142 struct nbd_device *nbd;
152 #if IS_ENABLED(CONFIG_DEBUG_FS)
153 static struct dentry *nbd_dbg_dir;
156 #define nbd_name(nbd) ((nbd)->disk->disk_name)
158 #define NBD_MAGIC 0x68797548
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_cleanup_disk(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))
328 nbd->config->bytesize = bytesize;
329 nbd->config->blksize_bits = __ffs(blksize);
334 if (nbd->config->flags & NBD_FLAG_SEND_TRIM) {
335 nbd->disk->queue->limits.discard_granularity = blksize;
336 blk_queue_max_discard_sectors(nbd->disk->queue, UINT_MAX);
338 blk_queue_logical_block_size(nbd->disk->queue, blksize);
339 blk_queue_physical_block_size(nbd->disk->queue, blksize);
342 set_bit(GD_NEED_PART_SCAN, &nbd->disk->state);
343 if (!set_capacity_and_notify(nbd->disk, bytesize >> 9))
344 kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
348 static void nbd_complete_rq(struct request *req)
350 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
352 dev_dbg(nbd_to_dev(cmd->nbd), "request %p: %s\n", req,
353 cmd->status ? "failed" : "done");
355 blk_mq_end_request(req, cmd->status);
359 * Forcibly shutdown the socket causing all listeners to error
361 static void sock_shutdown(struct nbd_device *nbd)
363 struct nbd_config *config = nbd->config;
366 if (config->num_connections == 0)
368 if (test_and_set_bit(NBD_RT_DISCONNECTED, &config->runtime_flags))
371 for (i = 0; i < config->num_connections; i++) {
372 struct nbd_sock *nsock = config->socks[i];
373 mutex_lock(&nsock->tx_lock);
374 nbd_mark_nsock_dead(nbd, nsock, 0);
375 mutex_unlock(&nsock->tx_lock);
377 dev_warn(disk_to_dev(nbd->disk), "shutting down sockets\n");
380 static u32 req_to_nbd_cmd_type(struct request *req)
382 switch (req_op(req)) {
386 return NBD_CMD_FLUSH;
388 return NBD_CMD_WRITE;
396 static enum blk_eh_timer_return nbd_xmit_timeout(struct request *req,
399 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
400 struct nbd_device *nbd = cmd->nbd;
401 struct nbd_config *config;
403 if (!mutex_trylock(&cmd->lock))
404 return BLK_EH_RESET_TIMER;
406 if (!__test_and_clear_bit(NBD_CMD_INFLIGHT, &cmd->flags)) {
407 mutex_unlock(&cmd->lock);
411 if (!refcount_inc_not_zero(&nbd->config_refs)) {
412 cmd->status = BLK_STS_TIMEOUT;
413 mutex_unlock(&cmd->lock);
416 config = nbd->config;
418 if (config->num_connections > 1 ||
419 (config->num_connections == 1 && nbd->tag_set.timeout)) {
420 dev_err_ratelimited(nbd_to_dev(nbd),
421 "Connection timed out, retrying (%d/%d alive)\n",
422 atomic_read(&config->live_connections),
423 config->num_connections);
425 * Hooray we have more connections, requeue this IO, the submit
426 * path will put it on a real connection. Or if only one
427 * connection is configured, the submit path will wait util
428 * a new connection is reconfigured or util dead timeout.
431 if (cmd->index < config->num_connections) {
432 struct nbd_sock *nsock =
433 config->socks[cmd->index];
434 mutex_lock(&nsock->tx_lock);
435 /* We can have multiple outstanding requests, so
436 * we don't want to mark the nsock dead if we've
437 * already reconnected with a new socket, so
438 * only mark it dead if its the same socket we
441 if (cmd->cookie == nsock->cookie)
442 nbd_mark_nsock_dead(nbd, nsock, 1);
443 mutex_unlock(&nsock->tx_lock);
445 mutex_unlock(&cmd->lock);
446 nbd_requeue_cmd(cmd);
452 if (!nbd->tag_set.timeout) {
454 * Userspace sets timeout=0 to disable socket disconnection,
455 * so just warn and reset the timer.
457 struct nbd_sock *nsock = config->socks[cmd->index];
459 dev_info(nbd_to_dev(nbd), "Possible stuck request %p: control (%s@%llu,%uB). Runtime %u seconds\n",
460 req, nbdcmd_to_ascii(req_to_nbd_cmd_type(req)),
461 (unsigned long long)blk_rq_pos(req) << 9,
462 blk_rq_bytes(req), (req->timeout / HZ) * cmd->retries);
464 mutex_lock(&nsock->tx_lock);
465 if (cmd->cookie != nsock->cookie) {
466 nbd_requeue_cmd(cmd);
467 mutex_unlock(&nsock->tx_lock);
468 mutex_unlock(&cmd->lock);
472 mutex_unlock(&nsock->tx_lock);
473 mutex_unlock(&cmd->lock);
475 return BLK_EH_RESET_TIMER;
478 dev_err_ratelimited(nbd_to_dev(nbd), "Connection timed out\n");
479 set_bit(NBD_RT_TIMEDOUT, &config->runtime_flags);
480 cmd->status = BLK_STS_IOERR;
481 mutex_unlock(&cmd->lock);
485 blk_mq_complete_request(req);
490 * Send or receive packet. Return a positive value on success and
491 * negtive value on failue, and never return 0.
493 static int sock_xmit(struct nbd_device *nbd, int index, int send,
494 struct iov_iter *iter, int msg_flags, int *sent)
496 struct nbd_config *config = nbd->config;
497 struct socket *sock = config->socks[index]->sock;
500 unsigned int noreclaim_flag;
502 if (unlikely(!sock)) {
503 dev_err_ratelimited(disk_to_dev(nbd->disk),
504 "Attempted %s on closed socket in sock_xmit\n",
505 (send ? "send" : "recv"));
509 msg.msg_iter = *iter;
511 noreclaim_flag = memalloc_noreclaim_save();
513 sock->sk->sk_allocation = GFP_NOIO | __GFP_MEMALLOC;
516 msg.msg_control = NULL;
517 msg.msg_controllen = 0;
518 msg.msg_flags = msg_flags | MSG_NOSIGNAL;
521 result = sock_sendmsg(sock, &msg);
523 result = sock_recvmsg(sock, &msg, msg.msg_flags);
527 result = -EPIPE; /* short read */
532 } while (msg_data_left(&msg));
534 memalloc_noreclaim_restore(noreclaim_flag);
540 * Different settings for sk->sk_sndtimeo can result in different return values
541 * if there is a signal pending when we enter sendmsg, because reasons?
543 static inline int was_interrupted(int result)
545 return result == -ERESTARTSYS || result == -EINTR;
548 /* always call with the tx_lock held */
549 static int nbd_send_cmd(struct nbd_device *nbd, struct nbd_cmd *cmd, int index)
551 struct request *req = blk_mq_rq_from_pdu(cmd);
552 struct nbd_config *config = nbd->config;
553 struct nbd_sock *nsock = config->socks[index];
555 struct nbd_request request = {.magic = htonl(NBD_REQUEST_MAGIC)};
556 struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
557 struct iov_iter from;
558 unsigned long size = blk_rq_bytes(req);
562 u32 nbd_cmd_flags = 0;
563 int sent = nsock->sent, skip = 0;
565 iov_iter_kvec(&from, WRITE, &iov, 1, sizeof(request));
567 type = req_to_nbd_cmd_type(req);
571 if (rq_data_dir(req) == WRITE &&
572 (config->flags & NBD_FLAG_READ_ONLY)) {
573 dev_err_ratelimited(disk_to_dev(nbd->disk),
574 "Write on read-only\n");
578 if (req->cmd_flags & REQ_FUA)
579 nbd_cmd_flags |= NBD_CMD_FLAG_FUA;
581 /* We did a partial send previously, and we at least sent the whole
582 * request struct, so just go and send the rest of the pages in the
586 if (sent >= sizeof(request)) {
587 skip = sent - sizeof(request);
589 /* initialize handle for tracing purposes */
590 handle = nbd_cmd_handle(cmd);
594 iov_iter_advance(&from, sent);
599 cmd->cookie = nsock->cookie;
601 request.type = htonl(type | nbd_cmd_flags);
602 if (type != NBD_CMD_FLUSH) {
603 request.from = cpu_to_be64((u64)blk_rq_pos(req) << 9);
604 request.len = htonl(size);
606 handle = nbd_cmd_handle(cmd);
607 memcpy(request.handle, &handle, sizeof(handle));
609 trace_nbd_send_request(&request, nbd->index, blk_mq_rq_from_pdu(cmd));
611 dev_dbg(nbd_to_dev(nbd), "request %p: sending control (%s@%llu,%uB)\n",
612 req, nbdcmd_to_ascii(type),
613 (unsigned long long)blk_rq_pos(req) << 9, blk_rq_bytes(req));
614 result = sock_xmit(nbd, index, 1, &from,
615 (type == NBD_CMD_WRITE) ? MSG_MORE : 0, &sent);
616 trace_nbd_header_sent(req, handle);
618 if (was_interrupted(result)) {
619 /* If we havne't sent anything we can just return BUSY,
620 * however if we have sent something we need to make
621 * sure we only allow this req to be sent until we are
625 nsock->pending = req;
628 set_bit(NBD_CMD_REQUEUED, &cmd->flags);
629 return BLK_STS_RESOURCE;
631 dev_err_ratelimited(disk_to_dev(nbd->disk),
632 "Send control failed (result %d)\n", result);
636 if (type != NBD_CMD_WRITE)
641 struct bio *next = bio->bi_next;
642 struct bvec_iter iter;
645 bio_for_each_segment(bvec, bio, iter) {
646 bool is_last = !next && bio_iter_last(bvec, iter);
647 int flags = is_last ? 0 : MSG_MORE;
649 dev_dbg(nbd_to_dev(nbd), "request %p: sending %d bytes data\n",
651 iov_iter_bvec(&from, WRITE, &bvec, 1, bvec.bv_len);
653 if (skip >= iov_iter_count(&from)) {
654 skip -= iov_iter_count(&from);
657 iov_iter_advance(&from, skip);
660 result = sock_xmit(nbd, index, 1, &from, flags, &sent);
662 if (was_interrupted(result)) {
663 /* We've already sent the header, we
664 * have no choice but to set pending and
667 nsock->pending = req;
669 set_bit(NBD_CMD_REQUEUED, &cmd->flags);
670 return BLK_STS_RESOURCE;
672 dev_err(disk_to_dev(nbd->disk),
673 "Send data failed (result %d)\n",
678 * The completion might already have come in,
679 * so break for the last one instead of letting
680 * the iterator do it. This prevents use-after-free
689 trace_nbd_payload_sent(req, handle);
690 nsock->pending = NULL;
695 static int nbd_read_reply(struct nbd_device *nbd, int index,
696 struct nbd_reply *reply)
698 struct kvec iov = {.iov_base = reply, .iov_len = sizeof(*reply)};
703 iov_iter_kvec(&to, READ, &iov, 1, sizeof(*reply));
704 result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
706 if (!nbd_disconnected(nbd->config))
707 dev_err(disk_to_dev(nbd->disk),
708 "Receive control failed (result %d)\n", result);
712 if (ntohl(reply->magic) != NBD_REPLY_MAGIC) {
713 dev_err(disk_to_dev(nbd->disk), "Wrong magic (0x%lx)\n",
714 (unsigned long)ntohl(reply->magic));
721 /* NULL returned = something went wrong, inform userspace */
722 static struct nbd_cmd *nbd_handle_reply(struct nbd_device *nbd, int index,
723 struct nbd_reply *reply)
727 struct request *req = NULL;
733 memcpy(&handle, reply->handle, sizeof(handle));
734 tag = nbd_handle_to_tag(handle);
735 hwq = blk_mq_unique_tag_to_hwq(tag);
736 if (hwq < nbd->tag_set.nr_hw_queues)
737 req = blk_mq_tag_to_rq(nbd->tag_set.tags[hwq],
738 blk_mq_unique_tag_to_tag(tag));
739 if (!req || !blk_mq_request_started(req)) {
740 dev_err(disk_to_dev(nbd->disk), "Unexpected reply (%d) %p\n",
742 return ERR_PTR(-ENOENT);
744 trace_nbd_header_received(req, handle);
745 cmd = blk_mq_rq_to_pdu(req);
747 mutex_lock(&cmd->lock);
748 if (!__test_and_clear_bit(NBD_CMD_INFLIGHT, &cmd->flags)) {
749 dev_err(disk_to_dev(nbd->disk), "Suspicious reply %d (status %u flags %lu)",
750 tag, cmd->status, cmd->flags);
754 if (cmd->index != index) {
755 dev_err(disk_to_dev(nbd->disk), "Unexpected reply %d from different sock %d (expected %d)",
756 tag, index, cmd->index);
760 if (cmd->cmd_cookie != nbd_handle_to_cookie(handle)) {
761 dev_err(disk_to_dev(nbd->disk), "Double reply on req %p, cmd_cookie %u, handle cookie %u\n",
762 req, cmd->cmd_cookie, nbd_handle_to_cookie(handle));
766 if (cmd->status != BLK_STS_OK) {
767 dev_err(disk_to_dev(nbd->disk), "Command already handled %p\n",
772 if (test_bit(NBD_CMD_REQUEUED, &cmd->flags)) {
773 dev_err(disk_to_dev(nbd->disk), "Raced with timeout on req %p\n",
778 if (ntohl(reply->error)) {
779 dev_err(disk_to_dev(nbd->disk), "Other side returned error (%d)\n",
780 ntohl(reply->error));
781 cmd->status = BLK_STS_IOERR;
785 dev_dbg(nbd_to_dev(nbd), "request %p: got reply\n", req);
786 if (rq_data_dir(req) != WRITE) {
787 struct req_iterator iter;
791 rq_for_each_segment(bvec, req, iter) {
792 iov_iter_bvec(&to, READ, &bvec, 1, bvec.bv_len);
793 result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
795 dev_err(disk_to_dev(nbd->disk), "Receive data failed (result %d)\n",
798 * If we've disconnected, we need to make sure we
799 * complete this request, otherwise error out
800 * and let the timeout stuff handle resubmitting
801 * this request onto another connection.
803 if (nbd_disconnected(nbd->config)) {
804 cmd->status = BLK_STS_IOERR;
810 dev_dbg(nbd_to_dev(nbd), "request %p: got %d bytes data\n",
815 trace_nbd_payload_received(req, handle);
816 mutex_unlock(&cmd->lock);
817 return ret ? ERR_PTR(ret) : cmd;
820 static void recv_work(struct work_struct *work)
822 struct recv_thread_args *args = container_of(work,
823 struct recv_thread_args,
825 struct nbd_device *nbd = args->nbd;
826 struct nbd_config *config = nbd->config;
827 struct request_queue *q = nbd->disk->queue;
828 struct nbd_sock *nsock;
833 struct nbd_reply reply;
835 if (nbd_read_reply(nbd, args->index, &reply))
839 * Grab .q_usage_counter so request pool won't go away, then no
840 * request use-after-free is possible during nbd_handle_reply().
841 * If queue is frozen, there won't be any inflight requests, we
842 * needn't to handle the incoming garbage message.
844 if (!percpu_ref_tryget(&q->q_usage_counter)) {
845 dev_err(disk_to_dev(nbd->disk), "%s: no io inflight\n",
850 cmd = nbd_handle_reply(nbd, args->index, &reply);
852 percpu_ref_put(&q->q_usage_counter);
856 rq = blk_mq_rq_from_pdu(cmd);
857 if (likely(!blk_should_fake_timeout(rq->q)))
858 blk_mq_complete_request(rq);
859 percpu_ref_put(&q->q_usage_counter);
862 nsock = config->socks[args->index];
863 mutex_lock(&nsock->tx_lock);
864 nbd_mark_nsock_dead(nbd, nsock, 1);
865 mutex_unlock(&nsock->tx_lock);
868 atomic_dec(&config->recv_threads);
869 wake_up(&config->recv_wq);
873 static bool nbd_clear_req(struct request *req, void *data, bool reserved)
875 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
877 /* don't abort one completed request */
878 if (blk_mq_request_completed(req))
881 mutex_lock(&cmd->lock);
882 if (!__test_and_clear_bit(NBD_CMD_INFLIGHT, &cmd->flags)) {
883 mutex_unlock(&cmd->lock);
886 cmd->status = BLK_STS_IOERR;
887 mutex_unlock(&cmd->lock);
889 blk_mq_complete_request(req);
893 static void nbd_clear_que(struct nbd_device *nbd)
895 blk_mq_quiesce_queue(nbd->disk->queue);
896 blk_mq_tagset_busy_iter(&nbd->tag_set, nbd_clear_req, NULL);
897 blk_mq_unquiesce_queue(nbd->disk->queue);
898 dev_dbg(disk_to_dev(nbd->disk), "queue cleared\n");
901 static int find_fallback(struct nbd_device *nbd, int index)
903 struct nbd_config *config = nbd->config;
905 struct nbd_sock *nsock = config->socks[index];
906 int fallback = nsock->fallback_index;
908 if (test_bit(NBD_RT_DISCONNECTED, &config->runtime_flags))
911 if (config->num_connections <= 1) {
912 dev_err_ratelimited(disk_to_dev(nbd->disk),
913 "Dead connection, failed to find a fallback\n");
917 if (fallback >= 0 && fallback < config->num_connections &&
918 !config->socks[fallback]->dead)
921 if (nsock->fallback_index < 0 ||
922 nsock->fallback_index >= config->num_connections ||
923 config->socks[nsock->fallback_index]->dead) {
925 for (i = 0; i < config->num_connections; i++) {
928 if (!config->socks[i]->dead) {
933 nsock->fallback_index = new_index;
935 dev_err_ratelimited(disk_to_dev(nbd->disk),
936 "Dead connection, failed to find a fallback\n");
940 new_index = nsock->fallback_index;
944 static int wait_for_reconnect(struct nbd_device *nbd)
946 struct nbd_config *config = nbd->config;
947 if (!config->dead_conn_timeout)
950 if (!wait_event_timeout(config->conn_wait,
951 test_bit(NBD_RT_DISCONNECTED,
952 &config->runtime_flags) ||
953 atomic_read(&config->live_connections) > 0,
954 config->dead_conn_timeout))
957 return !test_bit(NBD_RT_DISCONNECTED, &config->runtime_flags);
960 static int nbd_handle_cmd(struct nbd_cmd *cmd, int index)
962 struct request *req = blk_mq_rq_from_pdu(cmd);
963 struct nbd_device *nbd = cmd->nbd;
964 struct nbd_config *config;
965 struct nbd_sock *nsock;
968 if (!refcount_inc_not_zero(&nbd->config_refs)) {
969 dev_err_ratelimited(disk_to_dev(nbd->disk),
970 "Socks array is empty\n");
973 config = nbd->config;
975 if (index >= config->num_connections) {
976 dev_err_ratelimited(disk_to_dev(nbd->disk),
977 "Attempted send on invalid socket\n");
981 cmd->status = BLK_STS_OK;
983 nsock = config->socks[index];
984 mutex_lock(&nsock->tx_lock);
986 int old_index = index;
987 index = find_fallback(nbd, index);
988 mutex_unlock(&nsock->tx_lock);
990 if (wait_for_reconnect(nbd)) {
994 /* All the sockets should already be down at this point,
995 * we just want to make sure that DISCONNECTED is set so
996 * any requests that come in that were queue'ed waiting
997 * for the reconnect timer don't trigger the timer again
998 * and instead just error out.
1001 nbd_config_put(nbd);
1007 /* Handle the case that we have a pending request that was partially
1008 * transmitted that _has_ to be serviced first. We need to call requeue
1009 * here so that it gets put _after_ the request that is already on the
1012 blk_mq_start_request(req);
1013 if (unlikely(nsock->pending && nsock->pending != req)) {
1014 nbd_requeue_cmd(cmd);
1019 * Some failures are related to the link going down, so anything that
1020 * returns EAGAIN can be retried on a different socket.
1022 ret = nbd_send_cmd(nbd, cmd, index);
1024 * Access to this flag is protected by cmd->lock, thus it's safe to set
1025 * the flag after nbd_send_cmd() succeed to send request to server.
1028 __set_bit(NBD_CMD_INFLIGHT, &cmd->flags);
1029 else if (ret == -EAGAIN) {
1030 dev_err_ratelimited(disk_to_dev(nbd->disk),
1031 "Request send failed, requeueing\n");
1032 nbd_mark_nsock_dead(nbd, nsock, 1);
1033 nbd_requeue_cmd(cmd);
1037 mutex_unlock(&nsock->tx_lock);
1038 nbd_config_put(nbd);
1042 static blk_status_t nbd_queue_rq(struct blk_mq_hw_ctx *hctx,
1043 const struct blk_mq_queue_data *bd)
1045 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(bd->rq);
1049 * Since we look at the bio's to send the request over the network we
1050 * need to make sure the completion work doesn't mark this request done
1051 * before we are done doing our send. This keeps us from dereferencing
1052 * freed data if we have particularly fast completions (ie we get the
1053 * completion before we exit sock_xmit on the last bvec) or in the case
1054 * that the server is misbehaving (or there was an error) before we're
1055 * done sending everything over the wire.
1057 mutex_lock(&cmd->lock);
1058 clear_bit(NBD_CMD_REQUEUED, &cmd->flags);
1060 /* We can be called directly from the user space process, which means we
1061 * could possibly have signals pending so our sendmsg will fail. In
1062 * this case we need to return that we are busy, otherwise error out as
1065 ret = nbd_handle_cmd(cmd, hctx->queue_num);
1067 ret = BLK_STS_IOERR;
1070 mutex_unlock(&cmd->lock);
1075 static struct socket *nbd_get_socket(struct nbd_device *nbd, unsigned long fd,
1078 struct socket *sock;
1081 sock = sockfd_lookup(fd, err);
1085 if (sock->ops->shutdown == sock_no_shutdown) {
1086 dev_err(disk_to_dev(nbd->disk), "Unsupported socket: shutdown callout must be supported.\n");
1095 static int nbd_add_socket(struct nbd_device *nbd, unsigned long arg,
1098 struct nbd_config *config = nbd->config;
1099 struct socket *sock;
1100 struct nbd_sock **socks;
1101 struct nbd_sock *nsock;
1104 sock = nbd_get_socket(nbd, arg, &err);
1109 * We need to make sure we don't get any errant requests while we're
1110 * reallocating the ->socks array.
1112 blk_mq_freeze_queue(nbd->disk->queue);
1114 if (!netlink && !nbd->task_setup &&
1115 !test_bit(NBD_RT_BOUND, &config->runtime_flags))
1116 nbd->task_setup = current;
1119 (nbd->task_setup != current ||
1120 test_bit(NBD_RT_BOUND, &config->runtime_flags))) {
1121 dev_err(disk_to_dev(nbd->disk),
1122 "Device being setup by another task");
1127 nsock = kzalloc(sizeof(*nsock), GFP_KERNEL);
1133 socks = krealloc(config->socks, (config->num_connections + 1) *
1134 sizeof(struct nbd_sock *), GFP_KERNEL);
1141 config->socks = socks;
1143 nsock->fallback_index = -1;
1144 nsock->dead = false;
1145 mutex_init(&nsock->tx_lock);
1147 nsock->pending = NULL;
1150 socks[config->num_connections++] = nsock;
1151 atomic_inc(&config->live_connections);
1152 blk_mq_unfreeze_queue(nbd->disk->queue);
1157 blk_mq_unfreeze_queue(nbd->disk->queue);
1162 static int nbd_reconnect_socket(struct nbd_device *nbd, unsigned long arg)
1164 struct nbd_config *config = nbd->config;
1165 struct socket *sock, *old;
1166 struct recv_thread_args *args;
1170 sock = nbd_get_socket(nbd, arg, &err);
1174 args = kzalloc(sizeof(*args), GFP_KERNEL);
1180 for (i = 0; i < config->num_connections; i++) {
1181 struct nbd_sock *nsock = config->socks[i];
1186 mutex_lock(&nsock->tx_lock);
1188 mutex_unlock(&nsock->tx_lock);
1191 sk_set_memalloc(sock->sk);
1192 if (nbd->tag_set.timeout)
1193 sock->sk->sk_sndtimeo = nbd->tag_set.timeout;
1194 atomic_inc(&config->recv_threads);
1195 refcount_inc(&nbd->config_refs);
1197 nsock->fallback_index = -1;
1199 nsock->dead = false;
1200 INIT_WORK(&args->work, recv_work);
1204 mutex_unlock(&nsock->tx_lock);
1207 clear_bit(NBD_RT_DISCONNECTED, &config->runtime_flags);
1209 /* We take the tx_mutex in an error path in the recv_work, so we
1210 * need to queue_work outside of the tx_mutex.
1212 queue_work(nbd->recv_workq, &args->work);
1214 atomic_inc(&config->live_connections);
1215 wake_up(&config->conn_wait);
1223 static void nbd_bdev_reset(struct nbd_device *nbd)
1225 if (disk_openers(nbd->disk) > 1)
1227 set_capacity(nbd->disk, 0);
1230 static void nbd_parse_flags(struct nbd_device *nbd)
1232 struct nbd_config *config = nbd->config;
1233 if (config->flags & NBD_FLAG_READ_ONLY)
1234 set_disk_ro(nbd->disk, true);
1236 set_disk_ro(nbd->disk, false);
1237 if (config->flags & NBD_FLAG_SEND_FLUSH) {
1238 if (config->flags & NBD_FLAG_SEND_FUA)
1239 blk_queue_write_cache(nbd->disk->queue, true, true);
1241 blk_queue_write_cache(nbd->disk->queue, true, false);
1244 blk_queue_write_cache(nbd->disk->queue, false, false);
1247 static void send_disconnects(struct nbd_device *nbd)
1249 struct nbd_config *config = nbd->config;
1250 struct nbd_request request = {
1251 .magic = htonl(NBD_REQUEST_MAGIC),
1252 .type = htonl(NBD_CMD_DISC),
1254 struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
1255 struct iov_iter from;
1258 for (i = 0; i < config->num_connections; i++) {
1259 struct nbd_sock *nsock = config->socks[i];
1261 iov_iter_kvec(&from, WRITE, &iov, 1, sizeof(request));
1262 mutex_lock(&nsock->tx_lock);
1263 ret = sock_xmit(nbd, i, 1, &from, 0, NULL);
1265 dev_err(disk_to_dev(nbd->disk),
1266 "Send disconnect failed %d\n", ret);
1267 mutex_unlock(&nsock->tx_lock);
1271 static int nbd_disconnect(struct nbd_device *nbd)
1273 struct nbd_config *config = nbd->config;
1275 dev_info(disk_to_dev(nbd->disk), "NBD_DISCONNECT\n");
1276 set_bit(NBD_RT_DISCONNECT_REQUESTED, &config->runtime_flags);
1277 set_bit(NBD_DISCONNECT_REQUESTED, &nbd->flags);
1278 send_disconnects(nbd);
1282 static void nbd_clear_sock(struct nbd_device *nbd)
1286 nbd->task_setup = NULL;
1289 static void nbd_config_put(struct nbd_device *nbd)
1291 if (refcount_dec_and_mutex_lock(&nbd->config_refs,
1292 &nbd->config_lock)) {
1293 struct nbd_config *config = nbd->config;
1294 nbd_dev_dbg_close(nbd);
1295 invalidate_disk(nbd->disk);
1296 if (nbd->config->bytesize)
1297 kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
1298 if (test_and_clear_bit(NBD_RT_HAS_PID_FILE,
1299 &config->runtime_flags))
1300 device_remove_file(disk_to_dev(nbd->disk), &pid_attr);
1302 if (test_and_clear_bit(NBD_RT_HAS_BACKEND_FILE,
1303 &config->runtime_flags)) {
1304 device_remove_file(disk_to_dev(nbd->disk), &backend_attr);
1305 kfree(nbd->backend);
1306 nbd->backend = NULL;
1308 nbd_clear_sock(nbd);
1309 if (config->num_connections) {
1311 for (i = 0; i < config->num_connections; i++) {
1312 sockfd_put(config->socks[i]->sock);
1313 kfree(config->socks[i]);
1315 kfree(config->socks);
1320 nbd->tag_set.timeout = 0;
1321 nbd->disk->queue->limits.discard_granularity = 0;
1322 blk_queue_max_discard_sectors(nbd->disk->queue, 0);
1324 mutex_unlock(&nbd->config_lock);
1326 module_put(THIS_MODULE);
1330 static int nbd_start_device(struct nbd_device *nbd)
1332 struct nbd_config *config = nbd->config;
1333 int num_connections = config->num_connections;
1340 if (num_connections > 1 &&
1341 !(config->flags & NBD_FLAG_CAN_MULTI_CONN)) {
1342 dev_err(disk_to_dev(nbd->disk), "server does not support multiple connections per device.\n");
1346 blk_mq_update_nr_hw_queues(&nbd->tag_set, config->num_connections);
1347 nbd->pid = task_pid_nr(current);
1349 nbd_parse_flags(nbd);
1351 error = device_create_file(disk_to_dev(nbd->disk), &pid_attr);
1353 dev_err(disk_to_dev(nbd->disk), "device_create_file failed for pid!\n");
1356 set_bit(NBD_RT_HAS_PID_FILE, &config->runtime_flags);
1358 nbd_dev_dbg_init(nbd);
1359 for (i = 0; i < num_connections; i++) {
1360 struct recv_thread_args *args;
1362 args = kzalloc(sizeof(*args), GFP_KERNEL);
1366 * If num_connections is m (2 < m),
1367 * and NO.1 ~ NO.n(1 < n < m) kzallocs are successful.
1368 * But NO.(n + 1) failed. We still have n recv threads.
1369 * So, add flush_workqueue here to prevent recv threads
1370 * dropping the last config_refs and trying to destroy
1371 * the workqueue from inside the workqueue.
1374 flush_workqueue(nbd->recv_workq);
1377 sk_set_memalloc(config->socks[i]->sock->sk);
1378 if (nbd->tag_set.timeout)
1379 config->socks[i]->sock->sk->sk_sndtimeo =
1380 nbd->tag_set.timeout;
1381 atomic_inc(&config->recv_threads);
1382 refcount_inc(&nbd->config_refs);
1383 INIT_WORK(&args->work, recv_work);
1386 queue_work(nbd->recv_workq, &args->work);
1388 return nbd_set_size(nbd, config->bytesize, nbd_blksize(config));
1391 static int nbd_start_device_ioctl(struct nbd_device *nbd)
1393 struct nbd_config *config = nbd->config;
1396 ret = nbd_start_device(nbd);
1401 set_bit(GD_NEED_PART_SCAN, &nbd->disk->state);
1402 mutex_unlock(&nbd->config_lock);
1403 ret = wait_event_interruptible(config->recv_wq,
1404 atomic_read(&config->recv_threads) == 0);
1407 flush_workqueue(nbd->recv_workq);
1409 mutex_lock(&nbd->config_lock);
1410 nbd_bdev_reset(nbd);
1411 /* user requested, ignore socket errors */
1412 if (test_bit(NBD_RT_DISCONNECT_REQUESTED, &config->runtime_flags))
1414 if (test_bit(NBD_RT_TIMEDOUT, &config->runtime_flags))
1419 static void nbd_clear_sock_ioctl(struct nbd_device *nbd,
1420 struct block_device *bdev)
1423 __invalidate_device(bdev, true);
1424 nbd_bdev_reset(nbd);
1425 if (test_and_clear_bit(NBD_RT_HAS_CONFIG_REF,
1426 &nbd->config->runtime_flags))
1427 nbd_config_put(nbd);
1430 static void nbd_set_cmd_timeout(struct nbd_device *nbd, u64 timeout)
1432 nbd->tag_set.timeout = timeout * HZ;
1434 blk_queue_rq_timeout(nbd->disk->queue, timeout * HZ);
1436 blk_queue_rq_timeout(nbd->disk->queue, 30 * HZ);
1439 /* Must be called with config_lock held */
1440 static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
1441 unsigned int cmd, unsigned long arg)
1443 struct nbd_config *config = nbd->config;
1447 case NBD_DISCONNECT:
1448 return nbd_disconnect(nbd);
1449 case NBD_CLEAR_SOCK:
1450 nbd_clear_sock_ioctl(nbd, bdev);
1453 return nbd_add_socket(nbd, arg, false);
1454 case NBD_SET_BLKSIZE:
1455 return nbd_set_size(nbd, config->bytesize, arg);
1457 return nbd_set_size(nbd, arg, nbd_blksize(config));
1458 case NBD_SET_SIZE_BLOCKS:
1459 if (check_shl_overflow(arg, config->blksize_bits, &bytesize))
1461 return nbd_set_size(nbd, bytesize, nbd_blksize(config));
1462 case NBD_SET_TIMEOUT:
1463 nbd_set_cmd_timeout(nbd, arg);
1467 config->flags = arg;
1470 return nbd_start_device_ioctl(nbd);
1473 * This is for compatibility only. The queue is always cleared
1474 * by NBD_DO_IT or NBD_CLEAR_SOCK.
1477 case NBD_PRINT_DEBUG:
1479 * For compatibility only, we no longer keep a list of
1480 * outstanding requests.
1487 static int nbd_ioctl(struct block_device *bdev, fmode_t mode,
1488 unsigned int cmd, unsigned long arg)
1490 struct nbd_device *nbd = bdev->bd_disk->private_data;
1491 struct nbd_config *config = nbd->config;
1492 int error = -EINVAL;
1494 if (!capable(CAP_SYS_ADMIN))
1497 /* The block layer will pass back some non-nbd ioctls in case we have
1498 * special handling for them, but we don't so just return an error.
1500 if (_IOC_TYPE(cmd) != 0xab)
1503 mutex_lock(&nbd->config_lock);
1505 /* Don't allow ioctl operations on a nbd device that was created with
1506 * netlink, unless it's DISCONNECT or CLEAR_SOCK, which are fine.
1508 if (!test_bit(NBD_RT_BOUND, &config->runtime_flags) ||
1509 (cmd == NBD_DISCONNECT || cmd == NBD_CLEAR_SOCK))
1510 error = __nbd_ioctl(bdev, nbd, cmd, arg);
1512 dev_err(nbd_to_dev(nbd), "Cannot use ioctl interface on a netlink controlled device.\n");
1513 mutex_unlock(&nbd->config_lock);
1517 static struct nbd_config *nbd_alloc_config(void)
1519 struct nbd_config *config;
1521 config = kzalloc(sizeof(struct nbd_config), GFP_NOFS);
1524 atomic_set(&config->recv_threads, 0);
1525 init_waitqueue_head(&config->recv_wq);
1526 init_waitqueue_head(&config->conn_wait);
1527 config->blksize_bits = NBD_DEF_BLKSIZE_BITS;
1528 atomic_set(&config->live_connections, 0);
1529 try_module_get(THIS_MODULE);
1533 static int nbd_open(struct block_device *bdev, fmode_t mode)
1535 struct nbd_device *nbd;
1538 mutex_lock(&nbd_index_mutex);
1539 nbd = bdev->bd_disk->private_data;
1544 if (!refcount_inc_not_zero(&nbd->refs)) {
1548 if (!refcount_inc_not_zero(&nbd->config_refs)) {
1549 struct nbd_config *config;
1551 mutex_lock(&nbd->config_lock);
1552 if (refcount_inc_not_zero(&nbd->config_refs)) {
1553 mutex_unlock(&nbd->config_lock);
1556 config = nbd->config = nbd_alloc_config();
1559 mutex_unlock(&nbd->config_lock);
1562 refcount_set(&nbd->config_refs, 1);
1563 refcount_inc(&nbd->refs);
1564 mutex_unlock(&nbd->config_lock);
1566 set_bit(GD_NEED_PART_SCAN, &bdev->bd_disk->state);
1567 } else if (nbd_disconnected(nbd->config)) {
1569 set_bit(GD_NEED_PART_SCAN, &bdev->bd_disk->state);
1572 mutex_unlock(&nbd_index_mutex);
1576 static void nbd_release(struct gendisk *disk, fmode_t mode)
1578 struct nbd_device *nbd = disk->private_data;
1580 if (test_bit(NBD_RT_DISCONNECT_ON_CLOSE, &nbd->config->runtime_flags) &&
1581 disk_openers(disk) == 0)
1582 nbd_disconnect_and_put(nbd);
1584 nbd_config_put(nbd);
1588 static const struct block_device_operations nbd_fops =
1590 .owner = THIS_MODULE,
1592 .release = nbd_release,
1594 .compat_ioctl = nbd_ioctl,
1597 #if IS_ENABLED(CONFIG_DEBUG_FS)
1599 static int nbd_dbg_tasks_show(struct seq_file *s, void *unused)
1601 struct nbd_device *nbd = s->private;
1604 seq_printf(s, "recv: %d\n", nbd->pid);
1609 DEFINE_SHOW_ATTRIBUTE(nbd_dbg_tasks);
1611 static int nbd_dbg_flags_show(struct seq_file *s, void *unused)
1613 struct nbd_device *nbd = s->private;
1614 u32 flags = nbd->config->flags;
1616 seq_printf(s, "Hex: 0x%08x\n\n", flags);
1618 seq_puts(s, "Known flags:\n");
1620 if (flags & NBD_FLAG_HAS_FLAGS)
1621 seq_puts(s, "NBD_FLAG_HAS_FLAGS\n");
1622 if (flags & NBD_FLAG_READ_ONLY)
1623 seq_puts(s, "NBD_FLAG_READ_ONLY\n");
1624 if (flags & NBD_FLAG_SEND_FLUSH)
1625 seq_puts(s, "NBD_FLAG_SEND_FLUSH\n");
1626 if (flags & NBD_FLAG_SEND_FUA)
1627 seq_puts(s, "NBD_FLAG_SEND_FUA\n");
1628 if (flags & NBD_FLAG_SEND_TRIM)
1629 seq_puts(s, "NBD_FLAG_SEND_TRIM\n");
1634 DEFINE_SHOW_ATTRIBUTE(nbd_dbg_flags);
1636 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1639 struct nbd_config *config = nbd->config;
1644 dir = debugfs_create_dir(nbd_name(nbd), nbd_dbg_dir);
1646 dev_err(nbd_to_dev(nbd), "Failed to create debugfs dir for '%s'\n",
1650 config->dbg_dir = dir;
1652 debugfs_create_file("tasks", 0444, dir, nbd, &nbd_dbg_tasks_fops);
1653 debugfs_create_u64("size_bytes", 0444, dir, &config->bytesize);
1654 debugfs_create_u32("timeout", 0444, dir, &nbd->tag_set.timeout);
1655 debugfs_create_u32("blocksize_bits", 0444, dir, &config->blksize_bits);
1656 debugfs_create_file("flags", 0444, dir, nbd, &nbd_dbg_flags_fops);
1661 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1663 debugfs_remove_recursive(nbd->config->dbg_dir);
1666 static int nbd_dbg_init(void)
1668 struct dentry *dbg_dir;
1670 dbg_dir = debugfs_create_dir("nbd", NULL);
1674 nbd_dbg_dir = dbg_dir;
1679 static void nbd_dbg_close(void)
1681 debugfs_remove_recursive(nbd_dbg_dir);
1684 #else /* IS_ENABLED(CONFIG_DEBUG_FS) */
1686 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1691 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1695 static int nbd_dbg_init(void)
1700 static void nbd_dbg_close(void)
1706 static int nbd_init_request(struct blk_mq_tag_set *set, struct request *rq,
1707 unsigned int hctx_idx, unsigned int numa_node)
1709 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(rq);
1710 cmd->nbd = set->driver_data;
1712 mutex_init(&cmd->lock);
1716 static const struct blk_mq_ops nbd_mq_ops = {
1717 .queue_rq = nbd_queue_rq,
1718 .complete = nbd_complete_rq,
1719 .init_request = nbd_init_request,
1720 .timeout = nbd_xmit_timeout,
1723 static struct nbd_device *nbd_dev_add(int index, unsigned int refs)
1725 struct nbd_device *nbd;
1726 struct gendisk *disk;
1729 nbd = kzalloc(sizeof(struct nbd_device), GFP_KERNEL);
1733 nbd->tag_set.ops = &nbd_mq_ops;
1734 nbd->tag_set.nr_hw_queues = 1;
1735 nbd->tag_set.queue_depth = 128;
1736 nbd->tag_set.numa_node = NUMA_NO_NODE;
1737 nbd->tag_set.cmd_size = sizeof(struct nbd_cmd);
1738 nbd->tag_set.flags = BLK_MQ_F_SHOULD_MERGE |
1740 nbd->tag_set.driver_data = nbd;
1741 INIT_WORK(&nbd->remove_work, nbd_dev_remove_work);
1742 nbd->backend = NULL;
1744 err = blk_mq_alloc_tag_set(&nbd->tag_set);
1748 mutex_lock(&nbd_index_mutex);
1750 err = idr_alloc(&nbd_index_idr, nbd, index, index + 1,
1755 err = idr_alloc(&nbd_index_idr, nbd, 0, 0, GFP_KERNEL);
1760 mutex_unlock(&nbd_index_mutex);
1764 disk = blk_mq_alloc_disk(&nbd->tag_set, NULL);
1766 err = PTR_ERR(disk);
1771 nbd->recv_workq = alloc_workqueue("nbd%d-recv",
1772 WQ_MEM_RECLAIM | WQ_HIGHPRI |
1773 WQ_UNBOUND, 0, nbd->index);
1774 if (!nbd->recv_workq) {
1775 dev_err(disk_to_dev(nbd->disk), "Could not allocate knbd recv work queue.\n");
1781 * Tell the block layer that we are not a rotational device
1783 blk_queue_flag_set(QUEUE_FLAG_NONROT, disk->queue);
1784 blk_queue_flag_clear(QUEUE_FLAG_ADD_RANDOM, disk->queue);
1785 disk->queue->limits.discard_granularity = 0;
1786 blk_queue_max_discard_sectors(disk->queue, 0);
1787 blk_queue_max_segment_size(disk->queue, UINT_MAX);
1788 blk_queue_max_segments(disk->queue, USHRT_MAX);
1789 blk_queue_max_hw_sectors(disk->queue, 65536);
1790 disk->queue->limits.max_sectors = 256;
1792 mutex_init(&nbd->config_lock);
1793 refcount_set(&nbd->config_refs, 0);
1795 * Start out with a zero references to keep other threads from using
1796 * this device until it is fully initialized.
1798 refcount_set(&nbd->refs, 0);
1799 INIT_LIST_HEAD(&nbd->list);
1800 disk->major = NBD_MAJOR;
1802 /* Too big first_minor can cause duplicate creation of
1803 * sysfs files/links, since index << part_shift might overflow, or
1804 * MKDEV() expect that the max bits of first_minor is 20.
1806 disk->first_minor = index << part_shift;
1807 if (disk->first_minor < index || disk->first_minor > MINORMASK) {
1812 disk->minors = 1 << part_shift;
1813 disk->fops = &nbd_fops;
1814 disk->private_data = nbd;
1815 sprintf(disk->disk_name, "nbd%d", index);
1816 err = add_disk(disk);
1821 * Now publish the device.
1823 refcount_set(&nbd->refs, refs);
1824 nbd_total_devices++;
1828 destroy_workqueue(nbd->recv_workq);
1830 blk_cleanup_disk(disk);
1832 mutex_lock(&nbd_index_mutex);
1833 idr_remove(&nbd_index_idr, index);
1834 mutex_unlock(&nbd_index_mutex);
1836 blk_mq_free_tag_set(&nbd->tag_set);
1840 return ERR_PTR(err);
1843 static struct nbd_device *nbd_find_get_unused(void)
1845 struct nbd_device *nbd;
1848 lockdep_assert_held(&nbd_index_mutex);
1850 idr_for_each_entry(&nbd_index_idr, nbd, id) {
1851 if (refcount_read(&nbd->config_refs) ||
1852 test_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags))
1854 if (refcount_inc_not_zero(&nbd->refs))
1861 /* Netlink interface. */
1862 static const struct nla_policy nbd_attr_policy[NBD_ATTR_MAX + 1] = {
1863 [NBD_ATTR_INDEX] = { .type = NLA_U32 },
1864 [NBD_ATTR_SIZE_BYTES] = { .type = NLA_U64 },
1865 [NBD_ATTR_BLOCK_SIZE_BYTES] = { .type = NLA_U64 },
1866 [NBD_ATTR_TIMEOUT] = { .type = NLA_U64 },
1867 [NBD_ATTR_SERVER_FLAGS] = { .type = NLA_U64 },
1868 [NBD_ATTR_CLIENT_FLAGS] = { .type = NLA_U64 },
1869 [NBD_ATTR_SOCKETS] = { .type = NLA_NESTED},
1870 [NBD_ATTR_DEAD_CONN_TIMEOUT] = { .type = NLA_U64 },
1871 [NBD_ATTR_DEVICE_LIST] = { .type = NLA_NESTED},
1872 [NBD_ATTR_BACKEND_IDENTIFIER] = { .type = NLA_STRING},
1875 static const struct nla_policy nbd_sock_policy[NBD_SOCK_MAX + 1] = {
1876 [NBD_SOCK_FD] = { .type = NLA_U32 },
1879 /* We don't use this right now since we don't parse the incoming list, but we
1880 * still want it here so userspace knows what to expect.
1882 static const struct nla_policy __attribute__((unused))
1883 nbd_device_policy[NBD_DEVICE_ATTR_MAX + 1] = {
1884 [NBD_DEVICE_INDEX] = { .type = NLA_U32 },
1885 [NBD_DEVICE_CONNECTED] = { .type = NLA_U8 },
1888 static int nbd_genl_size_set(struct genl_info *info, struct nbd_device *nbd)
1890 struct nbd_config *config = nbd->config;
1891 u64 bsize = nbd_blksize(config);
1892 u64 bytes = config->bytesize;
1894 if (info->attrs[NBD_ATTR_SIZE_BYTES])
1895 bytes = nla_get_u64(info->attrs[NBD_ATTR_SIZE_BYTES]);
1897 if (info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES])
1898 bsize = nla_get_u64(info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]);
1900 if (bytes != config->bytesize || bsize != nbd_blksize(config))
1901 return nbd_set_size(nbd, bytes, bsize);
1905 static int nbd_genl_connect(struct sk_buff *skb, struct genl_info *info)
1907 struct nbd_device *nbd;
1908 struct nbd_config *config;
1911 bool put_dev = false;
1913 if (!netlink_capable(skb, CAP_SYS_ADMIN))
1916 if (info->attrs[NBD_ATTR_INDEX])
1917 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1918 if (!info->attrs[NBD_ATTR_SOCKETS]) {
1919 printk(KERN_ERR "nbd: must specify at least one socket\n");
1922 if (!info->attrs[NBD_ATTR_SIZE_BYTES]) {
1923 printk(KERN_ERR "nbd: must specify a size in bytes for the device\n");
1927 mutex_lock(&nbd_index_mutex);
1929 nbd = nbd_find_get_unused();
1931 nbd = idr_find(&nbd_index_idr, index);
1933 if ((test_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags) &&
1934 test_bit(NBD_DISCONNECT_REQUESTED, &nbd->flags)) ||
1935 !refcount_inc_not_zero(&nbd->refs)) {
1936 mutex_unlock(&nbd_index_mutex);
1937 pr_err("nbd: device at index %d is going down\n",
1943 mutex_unlock(&nbd_index_mutex);
1946 nbd = nbd_dev_add(index, 2);
1948 pr_err("nbd: failed to add new device\n");
1949 return PTR_ERR(nbd);
1953 mutex_lock(&nbd->config_lock);
1954 if (refcount_read(&nbd->config_refs)) {
1955 mutex_unlock(&nbd->config_lock);
1959 printk(KERN_ERR "nbd: nbd%d already in use\n", index);
1962 if (WARN_ON(nbd->config)) {
1963 mutex_unlock(&nbd->config_lock);
1967 config = nbd->config = nbd_alloc_config();
1969 mutex_unlock(&nbd->config_lock);
1971 printk(KERN_ERR "nbd: couldn't allocate config\n");
1974 refcount_set(&nbd->config_refs, 1);
1975 set_bit(NBD_RT_BOUND, &config->runtime_flags);
1977 ret = nbd_genl_size_set(info, nbd);
1981 if (info->attrs[NBD_ATTR_TIMEOUT])
1982 nbd_set_cmd_timeout(nbd,
1983 nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]));
1984 if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
1985 config->dead_conn_timeout =
1986 nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
1987 config->dead_conn_timeout *= HZ;
1989 if (info->attrs[NBD_ATTR_SERVER_FLAGS])
1991 nla_get_u64(info->attrs[NBD_ATTR_SERVER_FLAGS]);
1992 if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
1993 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
1994 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
1996 * We have 1 ref to keep the device around, and then 1
1997 * ref for our current operation here, which will be
1998 * inherited by the config. If we already have
1999 * DESTROY_ON_DISCONNECT set then we know we don't have
2000 * that extra ref already held so we don't need the
2003 if (!test_and_set_bit(NBD_DESTROY_ON_DISCONNECT,
2007 if (test_and_clear_bit(NBD_DESTROY_ON_DISCONNECT,
2009 refcount_inc(&nbd->refs);
2011 if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
2012 set_bit(NBD_RT_DISCONNECT_ON_CLOSE,
2013 &config->runtime_flags);
2017 if (info->attrs[NBD_ATTR_SOCKETS]) {
2018 struct nlattr *attr;
2021 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
2023 struct nlattr *socks[NBD_SOCK_MAX+1];
2025 if (nla_type(attr) != NBD_SOCK_ITEM) {
2026 printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
2030 ret = nla_parse_nested_deprecated(socks, NBD_SOCK_MAX,
2035 printk(KERN_ERR "nbd: error processing sock list\n");
2039 if (!socks[NBD_SOCK_FD])
2041 fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
2042 ret = nbd_add_socket(nbd, fd, true);
2047 ret = nbd_start_device(nbd);
2050 if (info->attrs[NBD_ATTR_BACKEND_IDENTIFIER]) {
2051 nbd->backend = nla_strdup(info->attrs[NBD_ATTR_BACKEND_IDENTIFIER],
2053 if (!nbd->backend) {
2058 ret = device_create_file(disk_to_dev(nbd->disk), &backend_attr);
2060 dev_err(disk_to_dev(nbd->disk),
2061 "device_create_file failed for backend!\n");
2064 set_bit(NBD_RT_HAS_BACKEND_FILE, &config->runtime_flags);
2066 mutex_unlock(&nbd->config_lock);
2068 set_bit(NBD_RT_HAS_CONFIG_REF, &config->runtime_flags);
2069 refcount_inc(&nbd->config_refs);
2070 nbd_connect_reply(info, nbd->index);
2072 nbd_config_put(nbd);
2078 static void nbd_disconnect_and_put(struct nbd_device *nbd)
2080 mutex_lock(&nbd->config_lock);
2081 nbd_disconnect(nbd);
2083 wake_up(&nbd->config->conn_wait);
2085 * Make sure recv thread has finished, we can safely call nbd_clear_que()
2086 * to cancel the inflight I/Os.
2088 flush_workqueue(nbd->recv_workq);
2090 nbd->task_setup = NULL;
2091 mutex_unlock(&nbd->config_lock);
2093 if (test_and_clear_bit(NBD_RT_HAS_CONFIG_REF,
2094 &nbd->config->runtime_flags))
2095 nbd_config_put(nbd);
2098 static int nbd_genl_disconnect(struct sk_buff *skb, struct genl_info *info)
2100 struct nbd_device *nbd;
2103 if (!netlink_capable(skb, CAP_SYS_ADMIN))
2106 if (!info->attrs[NBD_ATTR_INDEX]) {
2107 printk(KERN_ERR "nbd: must specify an index to disconnect\n");
2110 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2111 mutex_lock(&nbd_index_mutex);
2112 nbd = idr_find(&nbd_index_idr, index);
2114 mutex_unlock(&nbd_index_mutex);
2115 printk(KERN_ERR "nbd: couldn't find device at index %d\n",
2119 if (!refcount_inc_not_zero(&nbd->refs)) {
2120 mutex_unlock(&nbd_index_mutex);
2121 printk(KERN_ERR "nbd: device at index %d is going down\n",
2125 mutex_unlock(&nbd_index_mutex);
2126 if (!refcount_inc_not_zero(&nbd->config_refs))
2128 nbd_disconnect_and_put(nbd);
2129 nbd_config_put(nbd);
2135 static int nbd_genl_reconfigure(struct sk_buff *skb, struct genl_info *info)
2137 struct nbd_device *nbd = NULL;
2138 struct nbd_config *config;
2141 bool put_dev = false;
2143 if (!netlink_capable(skb, CAP_SYS_ADMIN))
2146 if (!info->attrs[NBD_ATTR_INDEX]) {
2147 printk(KERN_ERR "nbd: must specify a device to reconfigure\n");
2150 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2151 mutex_lock(&nbd_index_mutex);
2152 nbd = idr_find(&nbd_index_idr, index);
2154 mutex_unlock(&nbd_index_mutex);
2155 printk(KERN_ERR "nbd: couldn't find a device at index %d\n",
2160 if (info->attrs[NBD_ATTR_BACKEND_IDENTIFIER]) {
2161 if (nla_strcmp(info->attrs[NBD_ATTR_BACKEND_IDENTIFIER],
2163 mutex_unlock(&nbd_index_mutex);
2164 dev_err(nbd_to_dev(nbd),
2165 "backend image doesn't match with %s\n",
2170 mutex_unlock(&nbd_index_mutex);
2171 dev_err(nbd_to_dev(nbd), "must specify backend\n");
2175 if (!refcount_inc_not_zero(&nbd->refs)) {
2176 mutex_unlock(&nbd_index_mutex);
2177 printk(KERN_ERR "nbd: device at index %d is going down\n",
2181 mutex_unlock(&nbd_index_mutex);
2183 if (!refcount_inc_not_zero(&nbd->config_refs)) {
2184 dev_err(nbd_to_dev(nbd),
2185 "not configured, cannot reconfigure\n");
2190 mutex_lock(&nbd->config_lock);
2191 config = nbd->config;
2192 if (!test_bit(NBD_RT_BOUND, &config->runtime_flags) ||
2194 dev_err(nbd_to_dev(nbd),
2195 "not configured, cannot reconfigure\n");
2200 ret = nbd_genl_size_set(info, nbd);
2204 if (info->attrs[NBD_ATTR_TIMEOUT])
2205 nbd_set_cmd_timeout(nbd,
2206 nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]));
2207 if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
2208 config->dead_conn_timeout =
2209 nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
2210 config->dead_conn_timeout *= HZ;
2212 if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
2213 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
2214 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
2215 if (!test_and_set_bit(NBD_DESTROY_ON_DISCONNECT,
2219 if (test_and_clear_bit(NBD_DESTROY_ON_DISCONNECT,
2221 refcount_inc(&nbd->refs);
2224 if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
2225 set_bit(NBD_RT_DISCONNECT_ON_CLOSE,
2226 &config->runtime_flags);
2228 clear_bit(NBD_RT_DISCONNECT_ON_CLOSE,
2229 &config->runtime_flags);
2233 if (info->attrs[NBD_ATTR_SOCKETS]) {
2234 struct nlattr *attr;
2237 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
2239 struct nlattr *socks[NBD_SOCK_MAX+1];
2241 if (nla_type(attr) != NBD_SOCK_ITEM) {
2242 printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
2246 ret = nla_parse_nested_deprecated(socks, NBD_SOCK_MAX,
2251 printk(KERN_ERR "nbd: error processing sock list\n");
2255 if (!socks[NBD_SOCK_FD])
2257 fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
2258 ret = nbd_reconnect_socket(nbd, fd);
2264 dev_info(nbd_to_dev(nbd), "reconnected socket\n");
2268 mutex_unlock(&nbd->config_lock);
2269 nbd_config_put(nbd);
2276 static const struct genl_small_ops nbd_connect_genl_ops[] = {
2278 .cmd = NBD_CMD_CONNECT,
2279 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2280 .doit = nbd_genl_connect,
2283 .cmd = NBD_CMD_DISCONNECT,
2284 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2285 .doit = nbd_genl_disconnect,
2288 .cmd = NBD_CMD_RECONFIGURE,
2289 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2290 .doit = nbd_genl_reconfigure,
2293 .cmd = NBD_CMD_STATUS,
2294 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2295 .doit = nbd_genl_status,
2299 static const struct genl_multicast_group nbd_mcast_grps[] = {
2300 { .name = NBD_GENL_MCAST_GROUP_NAME, },
2303 static struct genl_family nbd_genl_family __ro_after_init = {
2305 .name = NBD_GENL_FAMILY_NAME,
2306 .version = NBD_GENL_VERSION,
2307 .module = THIS_MODULE,
2308 .small_ops = nbd_connect_genl_ops,
2309 .n_small_ops = ARRAY_SIZE(nbd_connect_genl_ops),
2310 .maxattr = NBD_ATTR_MAX,
2311 .policy = nbd_attr_policy,
2312 .mcgrps = nbd_mcast_grps,
2313 .n_mcgrps = ARRAY_SIZE(nbd_mcast_grps),
2316 static int populate_nbd_status(struct nbd_device *nbd, struct sk_buff *reply)
2318 struct nlattr *dev_opt;
2322 /* This is a little racey, but for status it's ok. The
2323 * reason we don't take a ref here is because we can't
2324 * take a ref in the index == -1 case as we would need
2325 * to put under the nbd_index_mutex, which could
2326 * deadlock if we are configured to remove ourselves
2327 * once we're disconnected.
2329 if (refcount_read(&nbd->config_refs))
2331 dev_opt = nla_nest_start_noflag(reply, NBD_DEVICE_ITEM);
2334 ret = nla_put_u32(reply, NBD_DEVICE_INDEX, nbd->index);
2337 ret = nla_put_u8(reply, NBD_DEVICE_CONNECTED,
2341 nla_nest_end(reply, dev_opt);
2345 static int status_cb(int id, void *ptr, void *data)
2347 struct nbd_device *nbd = ptr;
2348 return populate_nbd_status(nbd, (struct sk_buff *)data);
2351 static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info)
2353 struct nlattr *dev_list;
2354 struct sk_buff *reply;
2360 if (info->attrs[NBD_ATTR_INDEX])
2361 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2363 mutex_lock(&nbd_index_mutex);
2365 msg_size = nla_total_size(nla_attr_size(sizeof(u32)) +
2366 nla_attr_size(sizeof(u8)));
2367 msg_size *= (index == -1) ? nbd_total_devices : 1;
2369 reply = genlmsg_new(msg_size, GFP_KERNEL);
2372 reply_head = genlmsg_put_reply(reply, info, &nbd_genl_family, 0,
2379 dev_list = nla_nest_start_noflag(reply, NBD_ATTR_DEVICE_LIST);
2381 ret = idr_for_each(&nbd_index_idr, &status_cb, reply);
2387 struct nbd_device *nbd;
2388 nbd = idr_find(&nbd_index_idr, index);
2390 ret = populate_nbd_status(nbd, reply);
2397 nla_nest_end(reply, dev_list);
2398 genlmsg_end(reply, reply_head);
2399 ret = genlmsg_reply(reply, info);
2401 mutex_unlock(&nbd_index_mutex);
2405 static void nbd_connect_reply(struct genl_info *info, int index)
2407 struct sk_buff *skb;
2411 skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2414 msg_head = genlmsg_put_reply(skb, info, &nbd_genl_family, 0,
2420 ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2425 genlmsg_end(skb, msg_head);
2426 genlmsg_reply(skb, info);
2429 static void nbd_mcast_index(int index)
2431 struct sk_buff *skb;
2435 skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2438 msg_head = genlmsg_put(skb, 0, 0, &nbd_genl_family, 0,
2444 ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2449 genlmsg_end(skb, msg_head);
2450 genlmsg_multicast(&nbd_genl_family, skb, 0, 0, GFP_KERNEL);
2453 static void nbd_dead_link_work(struct work_struct *work)
2455 struct link_dead_args *args = container_of(work, struct link_dead_args,
2457 nbd_mcast_index(args->index);
2461 static int __init nbd_init(void)
2465 BUILD_BUG_ON(sizeof(struct nbd_request) != 28);
2468 printk(KERN_ERR "nbd: max_part must be >= 0\n");
2474 part_shift = fls(max_part);
2477 * Adjust max_part according to part_shift as it is exported
2478 * to user space so that user can know the max number of
2479 * partition kernel should be able to manage.
2481 * Note that -1 is required because partition 0 is reserved
2482 * for the whole disk.
2484 max_part = (1UL << part_shift) - 1;
2487 if ((1UL << part_shift) > DISK_MAX_PARTS)
2490 if (nbds_max > 1UL << (MINORBITS - part_shift))
2493 if (register_blkdev(NBD_MAJOR, "nbd"))
2496 nbd_del_wq = alloc_workqueue("nbd-del", WQ_UNBOUND, 0);
2498 unregister_blkdev(NBD_MAJOR, "nbd");
2502 if (genl_register_family(&nbd_genl_family)) {
2503 destroy_workqueue(nbd_del_wq);
2504 unregister_blkdev(NBD_MAJOR, "nbd");
2509 for (i = 0; i < nbds_max; i++)
2514 static int nbd_exit_cb(int id, void *ptr, void *data)
2516 struct list_head *list = (struct list_head *)data;
2517 struct nbd_device *nbd = ptr;
2519 /* Skip nbd that is being removed asynchronously */
2520 if (refcount_read(&nbd->refs))
2521 list_add_tail(&nbd->list, list);
2526 static void __exit nbd_cleanup(void)
2528 struct nbd_device *nbd;
2529 LIST_HEAD(del_list);
2533 mutex_lock(&nbd_index_mutex);
2534 idr_for_each(&nbd_index_idr, &nbd_exit_cb, &del_list);
2535 mutex_unlock(&nbd_index_mutex);
2537 while (!list_empty(&del_list)) {
2538 nbd = list_first_entry(&del_list, struct nbd_device, list);
2539 list_del_init(&nbd->list);
2540 if (refcount_read(&nbd->refs) != 1)
2541 printk(KERN_ERR "nbd: possibly leaking a device\n");
2545 /* Also wait for nbd_dev_remove_work() completes */
2546 destroy_workqueue(nbd_del_wq);
2548 idr_destroy(&nbd_index_idr);
2549 genl_unregister_family(&nbd_genl_family);
2550 unregister_blkdev(NBD_MAJOR, "nbd");
2553 module_init(nbd_init);
2554 module_exit(nbd_cleanup);
2556 MODULE_DESCRIPTION("Network Block Device");
2557 MODULE_LICENSE("GPL");
2559 module_param(nbds_max, int, 0444);
2560 MODULE_PARM_DESC(nbds_max, "number of network block devices to initialize (default: 16)");
2561 module_param(max_part, int, 0444);
2562 MODULE_PARM_DESC(max_part, "number of partitions per device (default: 16)");