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.
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);
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 nbd->disk->queue->limits.discard_alignment = blksize;
337 blk_queue_max_discard_sectors(nbd->disk->queue, UINT_MAX);
339 blk_queue_logical_block_size(nbd->disk->queue, blksize);
340 blk_queue_physical_block_size(nbd->disk->queue, blksize);
343 set_bit(GD_NEED_PART_SCAN, &nbd->disk->state);
344 if (!set_capacity_and_notify(nbd->disk, bytesize >> 9))
345 kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
349 static void nbd_complete_rq(struct request *req)
351 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
353 dev_dbg(nbd_to_dev(cmd->nbd), "request %p: %s\n", req,
354 cmd->status ? "failed" : "done");
356 blk_mq_end_request(req, cmd->status);
360 * Forcibly shutdown the socket causing all listeners to error
362 static void sock_shutdown(struct nbd_device *nbd)
364 struct nbd_config *config = nbd->config;
367 if (config->num_connections == 0)
369 if (test_and_set_bit(NBD_RT_DISCONNECTED, &config->runtime_flags))
372 for (i = 0; i < config->num_connections; i++) {
373 struct nbd_sock *nsock = config->socks[i];
374 mutex_lock(&nsock->tx_lock);
375 nbd_mark_nsock_dead(nbd, nsock, 0);
376 mutex_unlock(&nsock->tx_lock);
378 dev_warn(disk_to_dev(nbd->disk), "shutting down sockets\n");
381 static u32 req_to_nbd_cmd_type(struct request *req)
383 switch (req_op(req)) {
387 return NBD_CMD_FLUSH;
389 return NBD_CMD_WRITE;
397 static enum blk_eh_timer_return nbd_xmit_timeout(struct request *req,
400 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
401 struct nbd_device *nbd = cmd->nbd;
402 struct nbd_config *config;
404 if (!mutex_trylock(&cmd->lock))
405 return BLK_EH_RESET_TIMER;
407 if (!__test_and_clear_bit(NBD_CMD_INFLIGHT, &cmd->flags)) {
408 mutex_unlock(&cmd->lock);
412 if (!refcount_inc_not_zero(&nbd->config_refs)) {
413 cmd->status = BLK_STS_TIMEOUT;
414 mutex_unlock(&cmd->lock);
417 config = nbd->config;
419 if (config->num_connections > 1 ||
420 (config->num_connections == 1 && nbd->tag_set.timeout)) {
421 dev_err_ratelimited(nbd_to_dev(nbd),
422 "Connection timed out, retrying (%d/%d alive)\n",
423 atomic_read(&config->live_connections),
424 config->num_connections);
426 * Hooray we have more connections, requeue this IO, the submit
427 * path will put it on a real connection. Or if only one
428 * connection is configured, the submit path will wait util
429 * a new connection is reconfigured or util dead timeout.
432 if (cmd->index < config->num_connections) {
433 struct nbd_sock *nsock =
434 config->socks[cmd->index];
435 mutex_lock(&nsock->tx_lock);
436 /* We can have multiple outstanding requests, so
437 * we don't want to mark the nsock dead if we've
438 * already reconnected with a new socket, so
439 * only mark it dead if its the same socket we
442 if (cmd->cookie == nsock->cookie)
443 nbd_mark_nsock_dead(nbd, nsock, 1);
444 mutex_unlock(&nsock->tx_lock);
446 mutex_unlock(&cmd->lock);
447 nbd_requeue_cmd(cmd);
453 if (!nbd->tag_set.timeout) {
455 * Userspace sets timeout=0 to disable socket disconnection,
456 * so just warn and reset the timer.
458 struct nbd_sock *nsock = config->socks[cmd->index];
460 dev_info(nbd_to_dev(nbd), "Possible stuck request %p: control (%s@%llu,%uB). Runtime %u seconds\n",
461 req, nbdcmd_to_ascii(req_to_nbd_cmd_type(req)),
462 (unsigned long long)blk_rq_pos(req) << 9,
463 blk_rq_bytes(req), (req->timeout / HZ) * cmd->retries);
465 mutex_lock(&nsock->tx_lock);
466 if (cmd->cookie != nsock->cookie) {
467 nbd_requeue_cmd(cmd);
468 mutex_unlock(&nsock->tx_lock);
469 mutex_unlock(&cmd->lock);
473 mutex_unlock(&nsock->tx_lock);
474 mutex_unlock(&cmd->lock);
476 return BLK_EH_RESET_TIMER;
479 dev_err_ratelimited(nbd_to_dev(nbd), "Connection timed out\n");
480 set_bit(NBD_RT_TIMEDOUT, &config->runtime_flags);
481 cmd->status = BLK_STS_IOERR;
482 mutex_unlock(&cmd->lock);
486 blk_mq_complete_request(req);
491 * Send or receive packet. Return a positive value on success and
492 * negtive value on failue, and never return 0.
494 static int sock_xmit(struct nbd_device *nbd, int index, int send,
495 struct iov_iter *iter, int msg_flags, int *sent)
497 struct nbd_config *config = nbd->config;
498 struct socket *sock = config->socks[index]->sock;
501 unsigned int noreclaim_flag;
503 if (unlikely(!sock)) {
504 dev_err_ratelimited(disk_to_dev(nbd->disk),
505 "Attempted %s on closed socket in sock_xmit\n",
506 (send ? "send" : "recv"));
510 msg.msg_iter = *iter;
512 noreclaim_flag = memalloc_noreclaim_save();
514 sock->sk->sk_allocation = GFP_NOIO | __GFP_MEMALLOC;
517 msg.msg_control = NULL;
518 msg.msg_controllen = 0;
519 msg.msg_flags = msg_flags | MSG_NOSIGNAL;
522 result = sock_sendmsg(sock, &msg);
524 result = sock_recvmsg(sock, &msg, msg.msg_flags);
528 result = -EPIPE; /* short read */
533 } while (msg_data_left(&msg));
535 memalloc_noreclaim_restore(noreclaim_flag);
541 * Different settings for sk->sk_sndtimeo can result in different return values
542 * if there is a signal pending when we enter sendmsg, because reasons?
544 static inline int was_interrupted(int result)
546 return result == -ERESTARTSYS || result == -EINTR;
549 /* always call with the tx_lock held */
550 static int nbd_send_cmd(struct nbd_device *nbd, struct nbd_cmd *cmd, int index)
552 struct request *req = blk_mq_rq_from_pdu(cmd);
553 struct nbd_config *config = nbd->config;
554 struct nbd_sock *nsock = config->socks[index];
556 struct nbd_request request = {.magic = htonl(NBD_REQUEST_MAGIC)};
557 struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
558 struct iov_iter from;
559 unsigned long size = blk_rq_bytes(req);
563 u32 nbd_cmd_flags = 0;
564 int sent = nsock->sent, skip = 0;
566 iov_iter_kvec(&from, WRITE, &iov, 1, sizeof(request));
568 type = req_to_nbd_cmd_type(req);
572 if (rq_data_dir(req) == WRITE &&
573 (config->flags & NBD_FLAG_READ_ONLY)) {
574 dev_err_ratelimited(disk_to_dev(nbd->disk),
575 "Write on read-only\n");
579 if (req->cmd_flags & REQ_FUA)
580 nbd_cmd_flags |= NBD_CMD_FLAG_FUA;
582 /* We did a partial send previously, and we at least sent the whole
583 * request struct, so just go and send the rest of the pages in the
587 if (sent >= sizeof(request)) {
588 skip = sent - sizeof(request);
590 /* initialize handle for tracing purposes */
591 handle = nbd_cmd_handle(cmd);
595 iov_iter_advance(&from, sent);
600 cmd->cookie = nsock->cookie;
602 request.type = htonl(type | nbd_cmd_flags);
603 if (type != NBD_CMD_FLUSH) {
604 request.from = cpu_to_be64((u64)blk_rq_pos(req) << 9);
605 request.len = htonl(size);
607 handle = nbd_cmd_handle(cmd);
608 memcpy(request.handle, &handle, sizeof(handle));
610 trace_nbd_send_request(&request, nbd->index, blk_mq_rq_from_pdu(cmd));
612 dev_dbg(nbd_to_dev(nbd), "request %p: sending control (%s@%llu,%uB)\n",
613 req, nbdcmd_to_ascii(type),
614 (unsigned long long)blk_rq_pos(req) << 9, blk_rq_bytes(req));
615 result = sock_xmit(nbd, index, 1, &from,
616 (type == NBD_CMD_WRITE) ? MSG_MORE : 0, &sent);
617 trace_nbd_header_sent(req, handle);
619 if (was_interrupted(result)) {
620 /* If we havne't sent anything we can just return BUSY,
621 * however if we have sent something we need to make
622 * sure we only allow this req to be sent until we are
626 nsock->pending = req;
629 set_bit(NBD_CMD_REQUEUED, &cmd->flags);
630 return BLK_STS_RESOURCE;
632 dev_err_ratelimited(disk_to_dev(nbd->disk),
633 "Send control failed (result %d)\n", result);
637 if (type != NBD_CMD_WRITE)
642 struct bio *next = bio->bi_next;
643 struct bvec_iter iter;
646 bio_for_each_segment(bvec, bio, iter) {
647 bool is_last = !next && bio_iter_last(bvec, iter);
648 int flags = is_last ? 0 : MSG_MORE;
650 dev_dbg(nbd_to_dev(nbd), "request %p: sending %d bytes data\n",
652 iov_iter_bvec(&from, WRITE, &bvec, 1, bvec.bv_len);
654 if (skip >= iov_iter_count(&from)) {
655 skip -= iov_iter_count(&from);
658 iov_iter_advance(&from, skip);
661 result = sock_xmit(nbd, index, 1, &from, flags, &sent);
663 if (was_interrupted(result)) {
664 /* We've already sent the header, we
665 * have no choice but to set pending and
668 nsock->pending = req;
670 set_bit(NBD_CMD_REQUEUED, &cmd->flags);
671 return BLK_STS_RESOURCE;
673 dev_err(disk_to_dev(nbd->disk),
674 "Send data failed (result %d)\n",
679 * The completion might already have come in,
680 * so break for the last one instead of letting
681 * the iterator do it. This prevents use-after-free
690 trace_nbd_payload_sent(req, handle);
691 nsock->pending = NULL;
696 static int nbd_read_reply(struct nbd_device *nbd, int index,
697 struct nbd_reply *reply)
699 struct kvec iov = {.iov_base = reply, .iov_len = sizeof(*reply)};
704 iov_iter_kvec(&to, READ, &iov, 1, sizeof(*reply));
705 result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
707 if (!nbd_disconnected(nbd->config))
708 dev_err(disk_to_dev(nbd->disk),
709 "Receive control failed (result %d)\n", result);
713 if (ntohl(reply->magic) != NBD_REPLY_MAGIC) {
714 dev_err(disk_to_dev(nbd->disk), "Wrong magic (0x%lx)\n",
715 (unsigned long)ntohl(reply->magic));
722 /* NULL returned = something went wrong, inform userspace */
723 static struct nbd_cmd *nbd_handle_reply(struct nbd_device *nbd, int index,
724 struct nbd_reply *reply)
728 struct request *req = NULL;
734 memcpy(&handle, reply->handle, sizeof(handle));
735 tag = nbd_handle_to_tag(handle);
736 hwq = blk_mq_unique_tag_to_hwq(tag);
737 if (hwq < nbd->tag_set.nr_hw_queues)
738 req = blk_mq_tag_to_rq(nbd->tag_set.tags[hwq],
739 blk_mq_unique_tag_to_tag(tag));
740 if (!req || !blk_mq_request_started(req)) {
741 dev_err(disk_to_dev(nbd->disk), "Unexpected reply (%d) %p\n",
743 return ERR_PTR(-ENOENT);
745 trace_nbd_header_received(req, handle);
746 cmd = blk_mq_rq_to_pdu(req);
748 mutex_lock(&cmd->lock);
749 if (!__test_and_clear_bit(NBD_CMD_INFLIGHT, &cmd->flags)) {
750 dev_err(disk_to_dev(nbd->disk), "Suspicious reply %d (status %u flags %lu)",
751 tag, cmd->status, cmd->flags);
755 if (cmd->index != index) {
756 dev_err(disk_to_dev(nbd->disk), "Unexpected reply %d from different sock %d (expected %d)",
757 tag, index, cmd->index);
759 if (cmd->cmd_cookie != nbd_handle_to_cookie(handle)) {
760 dev_err(disk_to_dev(nbd->disk), "Double reply on req %p, cmd_cookie %u, handle cookie %u\n",
761 req, cmd->cmd_cookie, nbd_handle_to_cookie(handle));
765 if (cmd->status != BLK_STS_OK) {
766 dev_err(disk_to_dev(nbd->disk), "Command already handled %p\n",
771 if (test_bit(NBD_CMD_REQUEUED, &cmd->flags)) {
772 dev_err(disk_to_dev(nbd->disk), "Raced with timeout on req %p\n",
777 if (ntohl(reply->error)) {
778 dev_err(disk_to_dev(nbd->disk), "Other side returned error (%d)\n",
779 ntohl(reply->error));
780 cmd->status = BLK_STS_IOERR;
784 dev_dbg(nbd_to_dev(nbd), "request %p: got reply\n", req);
785 if (rq_data_dir(req) != WRITE) {
786 struct req_iterator iter;
790 rq_for_each_segment(bvec, req, iter) {
791 iov_iter_bvec(&to, READ, &bvec, 1, bvec.bv_len);
792 result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
794 dev_err(disk_to_dev(nbd->disk), "Receive data failed (result %d)\n",
797 * If we've disconnected, we need to make sure we
798 * complete this request, otherwise error out
799 * and let the timeout stuff handle resubmitting
800 * this request onto another connection.
802 if (nbd_disconnected(nbd->config)) {
803 cmd->status = BLK_STS_IOERR;
809 dev_dbg(nbd_to_dev(nbd), "request %p: got %d bytes data\n",
814 trace_nbd_payload_received(req, handle);
815 mutex_unlock(&cmd->lock);
816 return ret ? ERR_PTR(ret) : cmd;
819 static void recv_work(struct work_struct *work)
821 struct recv_thread_args *args = container_of(work,
822 struct recv_thread_args,
824 struct nbd_device *nbd = args->nbd;
825 struct nbd_config *config = nbd->config;
826 struct request_queue *q = nbd->disk->queue;
827 struct nbd_sock *nsock;
832 struct nbd_reply reply;
834 if (nbd_read_reply(nbd, args->index, &reply))
838 * Grab .q_usage_counter so request pool won't go away, then no
839 * request use-after-free is possible during nbd_handle_reply().
840 * If queue is frozen, there won't be any inflight requests, we
841 * needn't to handle the incoming garbage message.
843 if (!percpu_ref_tryget(&q->q_usage_counter)) {
844 dev_err(disk_to_dev(nbd->disk), "%s: no io inflight\n",
849 cmd = nbd_handle_reply(nbd, args->index, &reply);
851 percpu_ref_put(&q->q_usage_counter);
855 rq = blk_mq_rq_from_pdu(cmd);
856 if (likely(!blk_should_fake_timeout(rq->q)))
857 blk_mq_complete_request(rq);
858 percpu_ref_put(&q->q_usage_counter);
861 nsock = config->socks[args->index];
862 mutex_lock(&nsock->tx_lock);
863 nbd_mark_nsock_dead(nbd, nsock, 1);
864 mutex_unlock(&nsock->tx_lock);
867 atomic_dec(&config->recv_threads);
868 wake_up(&config->recv_wq);
872 static bool nbd_clear_req(struct request *req, void *data, bool reserved)
874 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
876 /* don't abort one completed request */
877 if (blk_mq_request_completed(req))
880 mutex_lock(&cmd->lock);
881 if (!__test_and_clear_bit(NBD_CMD_INFLIGHT, &cmd->flags)) {
882 mutex_unlock(&cmd->lock);
885 cmd->status = BLK_STS_IOERR;
886 mutex_unlock(&cmd->lock);
888 blk_mq_complete_request(req);
892 static void nbd_clear_que(struct nbd_device *nbd)
894 blk_mq_quiesce_queue(nbd->disk->queue);
895 blk_mq_tagset_busy_iter(&nbd->tag_set, nbd_clear_req, NULL);
896 blk_mq_unquiesce_queue(nbd->disk->queue);
897 dev_dbg(disk_to_dev(nbd->disk), "queue cleared\n");
900 static int find_fallback(struct nbd_device *nbd, int index)
902 struct nbd_config *config = nbd->config;
904 struct nbd_sock *nsock = config->socks[index];
905 int fallback = nsock->fallback_index;
907 if (test_bit(NBD_RT_DISCONNECTED, &config->runtime_flags))
910 if (config->num_connections <= 1) {
911 dev_err_ratelimited(disk_to_dev(nbd->disk),
912 "Dead connection, failed to find a fallback\n");
916 if (fallback >= 0 && fallback < config->num_connections &&
917 !config->socks[fallback]->dead)
920 if (nsock->fallback_index < 0 ||
921 nsock->fallback_index >= config->num_connections ||
922 config->socks[nsock->fallback_index]->dead) {
924 for (i = 0; i < config->num_connections; i++) {
927 if (!config->socks[i]->dead) {
932 nsock->fallback_index = new_index;
934 dev_err_ratelimited(disk_to_dev(nbd->disk),
935 "Dead connection, failed to find a fallback\n");
939 new_index = nsock->fallback_index;
943 static int wait_for_reconnect(struct nbd_device *nbd)
945 struct nbd_config *config = nbd->config;
946 if (!config->dead_conn_timeout)
948 if (test_bit(NBD_RT_DISCONNECTED, &config->runtime_flags))
950 return wait_event_timeout(config->conn_wait,
951 atomic_read(&config->live_connections) > 0,
952 config->dead_conn_timeout) > 0;
955 static int nbd_handle_cmd(struct nbd_cmd *cmd, int index)
957 struct request *req = blk_mq_rq_from_pdu(cmd);
958 struct nbd_device *nbd = cmd->nbd;
959 struct nbd_config *config;
960 struct nbd_sock *nsock;
963 if (!refcount_inc_not_zero(&nbd->config_refs)) {
964 dev_err_ratelimited(disk_to_dev(nbd->disk),
965 "Socks array is empty\n");
968 config = nbd->config;
970 if (index >= config->num_connections) {
971 dev_err_ratelimited(disk_to_dev(nbd->disk),
972 "Attempted send on invalid socket\n");
976 cmd->status = BLK_STS_OK;
978 nsock = config->socks[index];
979 mutex_lock(&nsock->tx_lock);
981 int old_index = index;
982 index = find_fallback(nbd, index);
983 mutex_unlock(&nsock->tx_lock);
985 if (wait_for_reconnect(nbd)) {
989 /* All the sockets should already be down at this point,
990 * we just want to make sure that DISCONNECTED is set so
991 * any requests that come in that were queue'ed waiting
992 * for the reconnect timer don't trigger the timer again
993 * and instead just error out.
1002 /* Handle the case that we have a pending request that was partially
1003 * transmitted that _has_ to be serviced first. We need to call requeue
1004 * here so that it gets put _after_ the request that is already on the
1007 blk_mq_start_request(req);
1008 if (unlikely(nsock->pending && nsock->pending != req)) {
1009 nbd_requeue_cmd(cmd);
1014 * Some failures are related to the link going down, so anything that
1015 * returns EAGAIN can be retried on a different socket.
1017 ret = nbd_send_cmd(nbd, cmd, index);
1019 * Access to this flag is protected by cmd->lock, thus it's safe to set
1020 * the flag after nbd_send_cmd() succeed to send request to server.
1023 __set_bit(NBD_CMD_INFLIGHT, &cmd->flags);
1024 else if (ret == -EAGAIN) {
1025 dev_err_ratelimited(disk_to_dev(nbd->disk),
1026 "Request send failed, requeueing\n");
1027 nbd_mark_nsock_dead(nbd, nsock, 1);
1028 nbd_requeue_cmd(cmd);
1032 mutex_unlock(&nsock->tx_lock);
1033 nbd_config_put(nbd);
1037 static blk_status_t nbd_queue_rq(struct blk_mq_hw_ctx *hctx,
1038 const struct blk_mq_queue_data *bd)
1040 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(bd->rq);
1044 * Since we look at the bio's to send the request over the network we
1045 * need to make sure the completion work doesn't mark this request done
1046 * before we are done doing our send. This keeps us from dereferencing
1047 * freed data if we have particularly fast completions (ie we get the
1048 * completion before we exit sock_xmit on the last bvec) or in the case
1049 * that the server is misbehaving (or there was an error) before we're
1050 * done sending everything over the wire.
1052 mutex_lock(&cmd->lock);
1053 clear_bit(NBD_CMD_REQUEUED, &cmd->flags);
1055 /* We can be called directly from the user space process, which means we
1056 * could possibly have signals pending so our sendmsg will fail. In
1057 * this case we need to return that we are busy, otherwise error out as
1060 ret = nbd_handle_cmd(cmd, hctx->queue_num);
1062 ret = BLK_STS_IOERR;
1065 mutex_unlock(&cmd->lock);
1070 static struct socket *nbd_get_socket(struct nbd_device *nbd, unsigned long fd,
1073 struct socket *sock;
1076 sock = sockfd_lookup(fd, err);
1080 if (sock->ops->shutdown == sock_no_shutdown) {
1081 dev_err(disk_to_dev(nbd->disk), "Unsupported socket: shutdown callout must be supported.\n");
1090 static int nbd_add_socket(struct nbd_device *nbd, unsigned long arg,
1093 struct nbd_config *config = nbd->config;
1094 struct socket *sock;
1095 struct nbd_sock **socks;
1096 struct nbd_sock *nsock;
1099 sock = nbd_get_socket(nbd, arg, &err);
1104 * We need to make sure we don't get any errant requests while we're
1105 * reallocating the ->socks array.
1107 blk_mq_freeze_queue(nbd->disk->queue);
1109 if (!netlink && !nbd->task_setup &&
1110 !test_bit(NBD_RT_BOUND, &config->runtime_flags))
1111 nbd->task_setup = current;
1114 (nbd->task_setup != current ||
1115 test_bit(NBD_RT_BOUND, &config->runtime_flags))) {
1116 dev_err(disk_to_dev(nbd->disk),
1117 "Device being setup by another task");
1122 nsock = kzalloc(sizeof(*nsock), GFP_KERNEL);
1128 socks = krealloc(config->socks, (config->num_connections + 1) *
1129 sizeof(struct nbd_sock *), GFP_KERNEL);
1136 config->socks = socks;
1138 nsock->fallback_index = -1;
1139 nsock->dead = false;
1140 mutex_init(&nsock->tx_lock);
1142 nsock->pending = NULL;
1145 socks[config->num_connections++] = nsock;
1146 atomic_inc(&config->live_connections);
1147 blk_mq_unfreeze_queue(nbd->disk->queue);
1152 blk_mq_unfreeze_queue(nbd->disk->queue);
1157 static int nbd_reconnect_socket(struct nbd_device *nbd, unsigned long arg)
1159 struct nbd_config *config = nbd->config;
1160 struct socket *sock, *old;
1161 struct recv_thread_args *args;
1165 sock = nbd_get_socket(nbd, arg, &err);
1169 args = kzalloc(sizeof(*args), GFP_KERNEL);
1175 for (i = 0; i < config->num_connections; i++) {
1176 struct nbd_sock *nsock = config->socks[i];
1181 mutex_lock(&nsock->tx_lock);
1183 mutex_unlock(&nsock->tx_lock);
1186 sk_set_memalloc(sock->sk);
1187 if (nbd->tag_set.timeout)
1188 sock->sk->sk_sndtimeo = nbd->tag_set.timeout;
1189 atomic_inc(&config->recv_threads);
1190 refcount_inc(&nbd->config_refs);
1192 nsock->fallback_index = -1;
1194 nsock->dead = false;
1195 INIT_WORK(&args->work, recv_work);
1199 mutex_unlock(&nsock->tx_lock);
1202 clear_bit(NBD_RT_DISCONNECTED, &config->runtime_flags);
1204 /* We take the tx_mutex in an error path in the recv_work, so we
1205 * need to queue_work outside of the tx_mutex.
1207 queue_work(nbd->recv_workq, &args->work);
1209 atomic_inc(&config->live_connections);
1210 wake_up(&config->conn_wait);
1218 static void nbd_bdev_reset(struct block_device *bdev)
1220 if (bdev->bd_openers > 1)
1222 set_capacity(bdev->bd_disk, 0);
1225 static void nbd_parse_flags(struct nbd_device *nbd)
1227 struct nbd_config *config = nbd->config;
1228 if (config->flags & NBD_FLAG_READ_ONLY)
1229 set_disk_ro(nbd->disk, true);
1231 set_disk_ro(nbd->disk, false);
1232 if (config->flags & NBD_FLAG_SEND_TRIM)
1233 blk_queue_flag_set(QUEUE_FLAG_DISCARD, nbd->disk->queue);
1234 if (config->flags & NBD_FLAG_SEND_FLUSH) {
1235 if (config->flags & NBD_FLAG_SEND_FUA)
1236 blk_queue_write_cache(nbd->disk->queue, true, true);
1238 blk_queue_write_cache(nbd->disk->queue, true, false);
1241 blk_queue_write_cache(nbd->disk->queue, false, false);
1244 static void send_disconnects(struct nbd_device *nbd)
1246 struct nbd_config *config = nbd->config;
1247 struct nbd_request request = {
1248 .magic = htonl(NBD_REQUEST_MAGIC),
1249 .type = htonl(NBD_CMD_DISC),
1251 struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
1252 struct iov_iter from;
1255 for (i = 0; i < config->num_connections; i++) {
1256 struct nbd_sock *nsock = config->socks[i];
1258 iov_iter_kvec(&from, WRITE, &iov, 1, sizeof(request));
1259 mutex_lock(&nsock->tx_lock);
1260 ret = sock_xmit(nbd, i, 1, &from, 0, NULL);
1262 dev_err(disk_to_dev(nbd->disk),
1263 "Send disconnect failed %d\n", ret);
1264 mutex_unlock(&nsock->tx_lock);
1268 static int nbd_disconnect(struct nbd_device *nbd)
1270 struct nbd_config *config = nbd->config;
1272 dev_info(disk_to_dev(nbd->disk), "NBD_DISCONNECT\n");
1273 set_bit(NBD_RT_DISCONNECT_REQUESTED, &config->runtime_flags);
1274 set_bit(NBD_DISCONNECT_REQUESTED, &nbd->flags);
1275 send_disconnects(nbd);
1279 static void nbd_clear_sock(struct nbd_device *nbd)
1283 nbd->task_setup = NULL;
1286 static void nbd_config_put(struct nbd_device *nbd)
1288 if (refcount_dec_and_mutex_lock(&nbd->config_refs,
1289 &nbd->config_lock)) {
1290 struct nbd_config *config = nbd->config;
1291 nbd_dev_dbg_close(nbd);
1292 invalidate_disk(nbd->disk);
1293 if (nbd->config->bytesize)
1294 kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
1295 if (test_and_clear_bit(NBD_RT_HAS_PID_FILE,
1296 &config->runtime_flags))
1297 device_remove_file(disk_to_dev(nbd->disk), &pid_attr);
1299 if (test_and_clear_bit(NBD_RT_HAS_BACKEND_FILE,
1300 &config->runtime_flags)) {
1301 device_remove_file(disk_to_dev(nbd->disk), &backend_attr);
1302 kfree(nbd->backend);
1303 nbd->backend = NULL;
1305 nbd_clear_sock(nbd);
1306 if (config->num_connections) {
1308 for (i = 0; i < config->num_connections; i++) {
1309 sockfd_put(config->socks[i]->sock);
1310 kfree(config->socks[i]);
1312 kfree(config->socks);
1317 if (nbd->recv_workq)
1318 destroy_workqueue(nbd->recv_workq);
1319 nbd->recv_workq = NULL;
1321 nbd->tag_set.timeout = 0;
1322 nbd->disk->queue->limits.discard_granularity = 0;
1323 nbd->disk->queue->limits.discard_alignment = 0;
1324 blk_queue_max_discard_sectors(nbd->disk->queue, UINT_MAX);
1325 blk_queue_flag_clear(QUEUE_FLAG_DISCARD, nbd->disk->queue);
1327 mutex_unlock(&nbd->config_lock);
1329 module_put(THIS_MODULE);
1333 static int nbd_start_device(struct nbd_device *nbd)
1335 struct nbd_config *config = nbd->config;
1336 int num_connections = config->num_connections;
1343 if (num_connections > 1 &&
1344 !(config->flags & NBD_FLAG_CAN_MULTI_CONN)) {
1345 dev_err(disk_to_dev(nbd->disk), "server does not support multiple connections per device.\n");
1349 nbd->recv_workq = alloc_workqueue("knbd%d-recv",
1350 WQ_MEM_RECLAIM | WQ_HIGHPRI |
1351 WQ_UNBOUND, 0, nbd->index);
1352 if (!nbd->recv_workq) {
1353 dev_err(disk_to_dev(nbd->disk), "Could not allocate knbd recv work queue.\n");
1357 blk_mq_update_nr_hw_queues(&nbd->tag_set, config->num_connections);
1358 nbd->pid = task_pid_nr(current);
1360 nbd_parse_flags(nbd);
1362 error = device_create_file(disk_to_dev(nbd->disk), &pid_attr);
1364 dev_err(disk_to_dev(nbd->disk), "device_create_file failed for pid!\n");
1367 set_bit(NBD_RT_HAS_PID_FILE, &config->runtime_flags);
1369 nbd_dev_dbg_init(nbd);
1370 for (i = 0; i < num_connections; i++) {
1371 struct recv_thread_args *args;
1373 args = kzalloc(sizeof(*args), GFP_KERNEL);
1377 * If num_connections is m (2 < m),
1378 * and NO.1 ~ NO.n(1 < n < m) kzallocs are successful.
1379 * But NO.(n + 1) failed. We still have n recv threads.
1380 * So, add flush_workqueue here to prevent recv threads
1381 * dropping the last config_refs and trying to destroy
1382 * the workqueue from inside the workqueue.
1385 flush_workqueue(nbd->recv_workq);
1388 sk_set_memalloc(config->socks[i]->sock->sk);
1389 if (nbd->tag_set.timeout)
1390 config->socks[i]->sock->sk->sk_sndtimeo =
1391 nbd->tag_set.timeout;
1392 atomic_inc(&config->recv_threads);
1393 refcount_inc(&nbd->config_refs);
1394 INIT_WORK(&args->work, recv_work);
1397 queue_work(nbd->recv_workq, &args->work);
1399 return nbd_set_size(nbd, config->bytesize, nbd_blksize(config));
1402 static int nbd_start_device_ioctl(struct nbd_device *nbd, struct block_device *bdev)
1404 struct nbd_config *config = nbd->config;
1407 ret = nbd_start_device(nbd);
1412 set_bit(GD_NEED_PART_SCAN, &nbd->disk->state);
1413 mutex_unlock(&nbd->config_lock);
1414 ret = wait_event_interruptible(config->recv_wq,
1415 atomic_read(&config->recv_threads) == 0);
1418 flush_workqueue(nbd->recv_workq);
1420 mutex_lock(&nbd->config_lock);
1421 nbd_bdev_reset(bdev);
1422 /* user requested, ignore socket errors */
1423 if (test_bit(NBD_RT_DISCONNECT_REQUESTED, &config->runtime_flags))
1425 if (test_bit(NBD_RT_TIMEDOUT, &config->runtime_flags))
1430 static void nbd_clear_sock_ioctl(struct nbd_device *nbd,
1431 struct block_device *bdev)
1434 __invalidate_device(bdev, true);
1435 nbd_bdev_reset(bdev);
1436 if (test_and_clear_bit(NBD_RT_HAS_CONFIG_REF,
1437 &nbd->config->runtime_flags))
1438 nbd_config_put(nbd);
1441 static void nbd_set_cmd_timeout(struct nbd_device *nbd, u64 timeout)
1443 nbd->tag_set.timeout = timeout * HZ;
1445 blk_queue_rq_timeout(nbd->disk->queue, timeout * HZ);
1447 blk_queue_rq_timeout(nbd->disk->queue, 30 * HZ);
1450 /* Must be called with config_lock held */
1451 static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
1452 unsigned int cmd, unsigned long arg)
1454 struct nbd_config *config = nbd->config;
1458 case NBD_DISCONNECT:
1459 return nbd_disconnect(nbd);
1460 case NBD_CLEAR_SOCK:
1461 nbd_clear_sock_ioctl(nbd, bdev);
1464 return nbd_add_socket(nbd, arg, false);
1465 case NBD_SET_BLKSIZE:
1466 return nbd_set_size(nbd, config->bytesize, arg);
1468 return nbd_set_size(nbd, arg, nbd_blksize(config));
1469 case NBD_SET_SIZE_BLOCKS:
1470 if (check_shl_overflow(arg, config->blksize_bits, &bytesize))
1472 return nbd_set_size(nbd, bytesize, nbd_blksize(config));
1473 case NBD_SET_TIMEOUT:
1474 nbd_set_cmd_timeout(nbd, arg);
1478 config->flags = arg;
1481 return nbd_start_device_ioctl(nbd, bdev);
1484 * This is for compatibility only. The queue is always cleared
1485 * by NBD_DO_IT or NBD_CLEAR_SOCK.
1488 case NBD_PRINT_DEBUG:
1490 * For compatibility only, we no longer keep a list of
1491 * outstanding requests.
1498 static int nbd_ioctl(struct block_device *bdev, fmode_t mode,
1499 unsigned int cmd, unsigned long arg)
1501 struct nbd_device *nbd = bdev->bd_disk->private_data;
1502 struct nbd_config *config = nbd->config;
1503 int error = -EINVAL;
1505 if (!capable(CAP_SYS_ADMIN))
1508 /* The block layer will pass back some non-nbd ioctls in case we have
1509 * special handling for them, but we don't so just return an error.
1511 if (_IOC_TYPE(cmd) != 0xab)
1514 mutex_lock(&nbd->config_lock);
1516 /* Don't allow ioctl operations on a nbd device that was created with
1517 * netlink, unless it's DISCONNECT or CLEAR_SOCK, which are fine.
1519 if (!test_bit(NBD_RT_BOUND, &config->runtime_flags) ||
1520 (cmd == NBD_DISCONNECT || cmd == NBD_CLEAR_SOCK))
1521 error = __nbd_ioctl(bdev, nbd, cmd, arg);
1523 dev_err(nbd_to_dev(nbd), "Cannot use ioctl interface on a netlink controlled device.\n");
1524 mutex_unlock(&nbd->config_lock);
1528 static struct nbd_config *nbd_alloc_config(void)
1530 struct nbd_config *config;
1532 config = kzalloc(sizeof(struct nbd_config), GFP_NOFS);
1535 atomic_set(&config->recv_threads, 0);
1536 init_waitqueue_head(&config->recv_wq);
1537 init_waitqueue_head(&config->conn_wait);
1538 config->blksize_bits = NBD_DEF_BLKSIZE_BITS;
1539 atomic_set(&config->live_connections, 0);
1540 try_module_get(THIS_MODULE);
1544 static int nbd_open(struct block_device *bdev, fmode_t mode)
1546 struct nbd_device *nbd;
1549 mutex_lock(&nbd_index_mutex);
1550 nbd = bdev->bd_disk->private_data;
1555 if (!refcount_inc_not_zero(&nbd->refs)) {
1559 if (!refcount_inc_not_zero(&nbd->config_refs)) {
1560 struct nbd_config *config;
1562 mutex_lock(&nbd->config_lock);
1563 if (refcount_inc_not_zero(&nbd->config_refs)) {
1564 mutex_unlock(&nbd->config_lock);
1567 config = nbd->config = nbd_alloc_config();
1570 mutex_unlock(&nbd->config_lock);
1573 refcount_set(&nbd->config_refs, 1);
1574 refcount_inc(&nbd->refs);
1575 mutex_unlock(&nbd->config_lock);
1577 set_bit(GD_NEED_PART_SCAN, &bdev->bd_disk->state);
1578 } else if (nbd_disconnected(nbd->config)) {
1580 set_bit(GD_NEED_PART_SCAN, &bdev->bd_disk->state);
1583 mutex_unlock(&nbd_index_mutex);
1587 static void nbd_release(struct gendisk *disk, fmode_t mode)
1589 struct nbd_device *nbd = disk->private_data;
1591 if (test_bit(NBD_RT_DISCONNECT_ON_CLOSE, &nbd->config->runtime_flags) &&
1592 disk->part0->bd_openers == 0)
1593 nbd_disconnect_and_put(nbd);
1595 nbd_config_put(nbd);
1599 static const struct block_device_operations nbd_fops =
1601 .owner = THIS_MODULE,
1603 .release = nbd_release,
1605 .compat_ioctl = nbd_ioctl,
1608 #if IS_ENABLED(CONFIG_DEBUG_FS)
1610 static int nbd_dbg_tasks_show(struct seq_file *s, void *unused)
1612 struct nbd_device *nbd = s->private;
1615 seq_printf(s, "recv: %d\n", nbd->pid);
1620 DEFINE_SHOW_ATTRIBUTE(nbd_dbg_tasks);
1622 static int nbd_dbg_flags_show(struct seq_file *s, void *unused)
1624 struct nbd_device *nbd = s->private;
1625 u32 flags = nbd->config->flags;
1627 seq_printf(s, "Hex: 0x%08x\n\n", flags);
1629 seq_puts(s, "Known flags:\n");
1631 if (flags & NBD_FLAG_HAS_FLAGS)
1632 seq_puts(s, "NBD_FLAG_HAS_FLAGS\n");
1633 if (flags & NBD_FLAG_READ_ONLY)
1634 seq_puts(s, "NBD_FLAG_READ_ONLY\n");
1635 if (flags & NBD_FLAG_SEND_FLUSH)
1636 seq_puts(s, "NBD_FLAG_SEND_FLUSH\n");
1637 if (flags & NBD_FLAG_SEND_FUA)
1638 seq_puts(s, "NBD_FLAG_SEND_FUA\n");
1639 if (flags & NBD_FLAG_SEND_TRIM)
1640 seq_puts(s, "NBD_FLAG_SEND_TRIM\n");
1645 DEFINE_SHOW_ATTRIBUTE(nbd_dbg_flags);
1647 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1650 struct nbd_config *config = nbd->config;
1655 dir = debugfs_create_dir(nbd_name(nbd), nbd_dbg_dir);
1657 dev_err(nbd_to_dev(nbd), "Failed to create debugfs dir for '%s'\n",
1661 config->dbg_dir = dir;
1663 debugfs_create_file("tasks", 0444, dir, nbd, &nbd_dbg_tasks_fops);
1664 debugfs_create_u64("size_bytes", 0444, dir, &config->bytesize);
1665 debugfs_create_u32("timeout", 0444, dir, &nbd->tag_set.timeout);
1666 debugfs_create_u32("blocksize_bits", 0444, dir, &config->blksize_bits);
1667 debugfs_create_file("flags", 0444, dir, nbd, &nbd_dbg_flags_fops);
1672 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1674 debugfs_remove_recursive(nbd->config->dbg_dir);
1677 static int nbd_dbg_init(void)
1679 struct dentry *dbg_dir;
1681 dbg_dir = debugfs_create_dir("nbd", NULL);
1685 nbd_dbg_dir = dbg_dir;
1690 static void nbd_dbg_close(void)
1692 debugfs_remove_recursive(nbd_dbg_dir);
1695 #else /* IS_ENABLED(CONFIG_DEBUG_FS) */
1697 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1702 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1706 static int nbd_dbg_init(void)
1711 static void nbd_dbg_close(void)
1717 static int nbd_init_request(struct blk_mq_tag_set *set, struct request *rq,
1718 unsigned int hctx_idx, unsigned int numa_node)
1720 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(rq);
1721 cmd->nbd = set->driver_data;
1723 mutex_init(&cmd->lock);
1727 static const struct blk_mq_ops nbd_mq_ops = {
1728 .queue_rq = nbd_queue_rq,
1729 .complete = nbd_complete_rq,
1730 .init_request = nbd_init_request,
1731 .timeout = nbd_xmit_timeout,
1734 static struct nbd_device *nbd_dev_add(int index, unsigned int refs)
1736 struct nbd_device *nbd;
1737 struct gendisk *disk;
1740 nbd = kzalloc(sizeof(struct nbd_device), GFP_KERNEL);
1744 nbd->tag_set.ops = &nbd_mq_ops;
1745 nbd->tag_set.nr_hw_queues = 1;
1746 nbd->tag_set.queue_depth = 128;
1747 nbd->tag_set.numa_node = NUMA_NO_NODE;
1748 nbd->tag_set.cmd_size = sizeof(struct nbd_cmd);
1749 nbd->tag_set.flags = BLK_MQ_F_SHOULD_MERGE |
1751 nbd->tag_set.driver_data = nbd;
1752 INIT_WORK(&nbd->remove_work, nbd_dev_remove_work);
1753 nbd->backend = NULL;
1755 err = blk_mq_alloc_tag_set(&nbd->tag_set);
1759 mutex_lock(&nbd_index_mutex);
1761 err = idr_alloc(&nbd_index_idr, nbd, index, index + 1,
1766 err = idr_alloc(&nbd_index_idr, nbd, 0, 0, GFP_KERNEL);
1771 mutex_unlock(&nbd_index_mutex);
1775 disk = blk_mq_alloc_disk(&nbd->tag_set, NULL);
1777 err = PTR_ERR(disk);
1783 * Tell the block layer that we are not a rotational device
1785 blk_queue_flag_set(QUEUE_FLAG_NONROT, disk->queue);
1786 blk_queue_flag_clear(QUEUE_FLAG_ADD_RANDOM, disk->queue);
1787 disk->queue->limits.discard_granularity = 0;
1788 disk->queue->limits.discard_alignment = 0;
1789 blk_queue_max_discard_sectors(disk->queue, 0);
1790 blk_queue_max_segment_size(disk->queue, UINT_MAX);
1791 blk_queue_max_segments(disk->queue, USHRT_MAX);
1792 blk_queue_max_hw_sectors(disk->queue, 65536);
1793 disk->queue->limits.max_sectors = 256;
1795 mutex_init(&nbd->config_lock);
1796 refcount_set(&nbd->config_refs, 0);
1798 * Start out with a zero references to keep other threads from using
1799 * this device until it is fully initialized.
1801 refcount_set(&nbd->refs, 0);
1802 INIT_LIST_HEAD(&nbd->list);
1803 disk->major = NBD_MAJOR;
1805 /* Too big first_minor can cause duplicate creation of
1806 * sysfs files/links, since first_minor will be truncated to
1807 * byte in __device_add_disk().
1809 disk->first_minor = index << part_shift;
1810 if (disk->first_minor > 0xff) {
1815 disk->minors = 1 << part_shift;
1816 disk->fops = &nbd_fops;
1817 disk->private_data = nbd;
1818 sprintf(disk->disk_name, "nbd%d", index);
1819 err = add_disk(disk);
1824 * Now publish the device.
1826 refcount_set(&nbd->refs, refs);
1827 nbd_total_devices++;
1831 blk_cleanup_disk(disk);
1833 mutex_lock(&nbd_index_mutex);
1834 idr_remove(&nbd_index_idr, index);
1835 mutex_unlock(&nbd_index_mutex);
1837 blk_mq_free_tag_set(&nbd->tag_set);
1841 return ERR_PTR(err);
1844 static struct nbd_device *nbd_find_get_unused(void)
1846 struct nbd_device *nbd;
1849 lockdep_assert_held(&nbd_index_mutex);
1851 idr_for_each_entry(&nbd_index_idr, nbd, id) {
1852 if (refcount_read(&nbd->config_refs) ||
1853 test_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags))
1855 if (refcount_inc_not_zero(&nbd->refs))
1862 /* Netlink interface. */
1863 static const struct nla_policy nbd_attr_policy[NBD_ATTR_MAX + 1] = {
1864 [NBD_ATTR_INDEX] = { .type = NLA_U32 },
1865 [NBD_ATTR_SIZE_BYTES] = { .type = NLA_U64 },
1866 [NBD_ATTR_BLOCK_SIZE_BYTES] = { .type = NLA_U64 },
1867 [NBD_ATTR_TIMEOUT] = { .type = NLA_U64 },
1868 [NBD_ATTR_SERVER_FLAGS] = { .type = NLA_U64 },
1869 [NBD_ATTR_CLIENT_FLAGS] = { .type = NLA_U64 },
1870 [NBD_ATTR_SOCKETS] = { .type = NLA_NESTED},
1871 [NBD_ATTR_DEAD_CONN_TIMEOUT] = { .type = NLA_U64 },
1872 [NBD_ATTR_DEVICE_LIST] = { .type = NLA_NESTED},
1873 [NBD_ATTR_BACKEND_IDENTIFIER] = { .type = NLA_STRING},
1876 static const struct nla_policy nbd_sock_policy[NBD_SOCK_MAX + 1] = {
1877 [NBD_SOCK_FD] = { .type = NLA_U32 },
1880 /* We don't use this right now since we don't parse the incoming list, but we
1881 * still want it here so userspace knows what to expect.
1883 static const struct nla_policy __attribute__((unused))
1884 nbd_device_policy[NBD_DEVICE_ATTR_MAX + 1] = {
1885 [NBD_DEVICE_INDEX] = { .type = NLA_U32 },
1886 [NBD_DEVICE_CONNECTED] = { .type = NLA_U8 },
1889 static int nbd_genl_size_set(struct genl_info *info, struct nbd_device *nbd)
1891 struct nbd_config *config = nbd->config;
1892 u64 bsize = nbd_blksize(config);
1893 u64 bytes = config->bytesize;
1895 if (info->attrs[NBD_ATTR_SIZE_BYTES])
1896 bytes = nla_get_u64(info->attrs[NBD_ATTR_SIZE_BYTES]);
1898 if (info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES])
1899 bsize = nla_get_u64(info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]);
1901 if (bytes != config->bytesize || bsize != nbd_blksize(config))
1902 return nbd_set_size(nbd, bytes, bsize);
1906 static int nbd_genl_connect(struct sk_buff *skb, struct genl_info *info)
1908 struct nbd_device *nbd;
1909 struct nbd_config *config;
1912 bool put_dev = false;
1914 if (!netlink_capable(skb, CAP_SYS_ADMIN))
1917 if (info->attrs[NBD_ATTR_INDEX])
1918 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1919 if (!info->attrs[NBD_ATTR_SOCKETS]) {
1920 printk(KERN_ERR "nbd: must specify at least one socket\n");
1923 if (!info->attrs[NBD_ATTR_SIZE_BYTES]) {
1924 printk(KERN_ERR "nbd: must specify a size in bytes for the device\n");
1928 mutex_lock(&nbd_index_mutex);
1930 nbd = nbd_find_get_unused();
1932 nbd = idr_find(&nbd_index_idr, index);
1934 if ((test_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags) &&
1935 test_bit(NBD_DISCONNECT_REQUESTED, &nbd->flags)) ||
1936 !refcount_inc_not_zero(&nbd->refs)) {
1937 mutex_unlock(&nbd_index_mutex);
1938 pr_err("nbd: device at index %d is going down\n",
1944 mutex_unlock(&nbd_index_mutex);
1947 nbd = nbd_dev_add(index, 2);
1949 pr_err("nbd: failed to add new device\n");
1950 return PTR_ERR(nbd);
1954 mutex_lock(&nbd->config_lock);
1955 if (refcount_read(&nbd->config_refs)) {
1956 mutex_unlock(&nbd->config_lock);
1960 printk(KERN_ERR "nbd: nbd%d already in use\n", index);
1963 if (WARN_ON(nbd->config)) {
1964 mutex_unlock(&nbd->config_lock);
1968 config = nbd->config = nbd_alloc_config();
1970 mutex_unlock(&nbd->config_lock);
1972 printk(KERN_ERR "nbd: couldn't allocate config\n");
1975 refcount_set(&nbd->config_refs, 1);
1976 set_bit(NBD_RT_BOUND, &config->runtime_flags);
1978 ret = nbd_genl_size_set(info, nbd);
1982 if (info->attrs[NBD_ATTR_TIMEOUT])
1983 nbd_set_cmd_timeout(nbd,
1984 nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]));
1985 if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
1986 config->dead_conn_timeout =
1987 nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
1988 config->dead_conn_timeout *= HZ;
1990 if (info->attrs[NBD_ATTR_SERVER_FLAGS])
1992 nla_get_u64(info->attrs[NBD_ATTR_SERVER_FLAGS]);
1993 if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
1994 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
1995 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
1997 * We have 1 ref to keep the device around, and then 1
1998 * ref for our current operation here, which will be
1999 * inherited by the config. If we already have
2000 * DESTROY_ON_DISCONNECT set then we know we don't have
2001 * that extra ref already held so we don't need the
2004 if (!test_and_set_bit(NBD_DESTROY_ON_DISCONNECT,
2008 if (test_and_clear_bit(NBD_DESTROY_ON_DISCONNECT,
2010 refcount_inc(&nbd->refs);
2012 if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
2013 set_bit(NBD_RT_DISCONNECT_ON_CLOSE,
2014 &config->runtime_flags);
2018 if (info->attrs[NBD_ATTR_SOCKETS]) {
2019 struct nlattr *attr;
2022 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
2024 struct nlattr *socks[NBD_SOCK_MAX+1];
2026 if (nla_type(attr) != NBD_SOCK_ITEM) {
2027 printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
2031 ret = nla_parse_nested_deprecated(socks, NBD_SOCK_MAX,
2036 printk(KERN_ERR "nbd: error processing sock list\n");
2040 if (!socks[NBD_SOCK_FD])
2042 fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
2043 ret = nbd_add_socket(nbd, fd, true);
2048 ret = nbd_start_device(nbd);
2051 if (info->attrs[NBD_ATTR_BACKEND_IDENTIFIER]) {
2052 nbd->backend = nla_strdup(info->attrs[NBD_ATTR_BACKEND_IDENTIFIER],
2054 if (!nbd->backend) {
2059 ret = device_create_file(disk_to_dev(nbd->disk), &backend_attr);
2061 dev_err(disk_to_dev(nbd->disk),
2062 "device_create_file failed for backend!\n");
2065 set_bit(NBD_RT_HAS_BACKEND_FILE, &config->runtime_flags);
2067 mutex_unlock(&nbd->config_lock);
2069 set_bit(NBD_RT_HAS_CONFIG_REF, &config->runtime_flags);
2070 refcount_inc(&nbd->config_refs);
2071 nbd_connect_reply(info, nbd->index);
2073 nbd_config_put(nbd);
2079 static void nbd_disconnect_and_put(struct nbd_device *nbd)
2081 mutex_lock(&nbd->config_lock);
2082 nbd_disconnect(nbd);
2085 * Make sure recv thread has finished, so it does not drop the last
2086 * config ref and try to destroy the workqueue from inside the work
2087 * queue. And this also ensure that we can safely call nbd_clear_que()
2088 * to cancel the inflight I/Os.
2090 if (nbd->recv_workq)
2091 flush_workqueue(nbd->recv_workq);
2093 nbd->task_setup = NULL;
2094 mutex_unlock(&nbd->config_lock);
2096 if (test_and_clear_bit(NBD_RT_HAS_CONFIG_REF,
2097 &nbd->config->runtime_flags))
2098 nbd_config_put(nbd);
2101 static int nbd_genl_disconnect(struct sk_buff *skb, struct genl_info *info)
2103 struct nbd_device *nbd;
2106 if (!netlink_capable(skb, CAP_SYS_ADMIN))
2109 if (!info->attrs[NBD_ATTR_INDEX]) {
2110 printk(KERN_ERR "nbd: must specify an index to disconnect\n");
2113 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2114 mutex_lock(&nbd_index_mutex);
2115 nbd = idr_find(&nbd_index_idr, index);
2117 mutex_unlock(&nbd_index_mutex);
2118 printk(KERN_ERR "nbd: couldn't find device at index %d\n",
2122 if (!refcount_inc_not_zero(&nbd->refs)) {
2123 mutex_unlock(&nbd_index_mutex);
2124 printk(KERN_ERR "nbd: device at index %d is going down\n",
2128 mutex_unlock(&nbd_index_mutex);
2129 if (!refcount_inc_not_zero(&nbd->config_refs))
2131 nbd_disconnect_and_put(nbd);
2132 nbd_config_put(nbd);
2138 static int nbd_genl_reconfigure(struct sk_buff *skb, struct genl_info *info)
2140 struct nbd_device *nbd = NULL;
2141 struct nbd_config *config;
2144 bool put_dev = false;
2146 if (!netlink_capable(skb, CAP_SYS_ADMIN))
2149 if (!info->attrs[NBD_ATTR_INDEX]) {
2150 printk(KERN_ERR "nbd: must specify a device to reconfigure\n");
2153 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2154 mutex_lock(&nbd_index_mutex);
2155 nbd = idr_find(&nbd_index_idr, index);
2157 mutex_unlock(&nbd_index_mutex);
2158 printk(KERN_ERR "nbd: couldn't find a device at index %d\n",
2163 if (info->attrs[NBD_ATTR_BACKEND_IDENTIFIER]) {
2164 if (nla_strcmp(info->attrs[NBD_ATTR_BACKEND_IDENTIFIER],
2166 mutex_unlock(&nbd_index_mutex);
2167 dev_err(nbd_to_dev(nbd),
2168 "backend image doesn't match with %s\n",
2173 mutex_unlock(&nbd_index_mutex);
2174 dev_err(nbd_to_dev(nbd), "must specify backend\n");
2178 if (!refcount_inc_not_zero(&nbd->refs)) {
2179 mutex_unlock(&nbd_index_mutex);
2180 printk(KERN_ERR "nbd: device at index %d is going down\n",
2184 mutex_unlock(&nbd_index_mutex);
2186 if (!refcount_inc_not_zero(&nbd->config_refs)) {
2187 dev_err(nbd_to_dev(nbd),
2188 "not configured, cannot reconfigure\n");
2193 mutex_lock(&nbd->config_lock);
2194 config = nbd->config;
2195 if (!test_bit(NBD_RT_BOUND, &config->runtime_flags) ||
2197 dev_err(nbd_to_dev(nbd),
2198 "not configured, cannot reconfigure\n");
2203 ret = nbd_genl_size_set(info, nbd);
2207 if (info->attrs[NBD_ATTR_TIMEOUT])
2208 nbd_set_cmd_timeout(nbd,
2209 nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]));
2210 if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
2211 config->dead_conn_timeout =
2212 nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
2213 config->dead_conn_timeout *= HZ;
2215 if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
2216 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
2217 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
2218 if (!test_and_set_bit(NBD_DESTROY_ON_DISCONNECT,
2222 if (test_and_clear_bit(NBD_DESTROY_ON_DISCONNECT,
2224 refcount_inc(&nbd->refs);
2227 if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
2228 set_bit(NBD_RT_DISCONNECT_ON_CLOSE,
2229 &config->runtime_flags);
2231 clear_bit(NBD_RT_DISCONNECT_ON_CLOSE,
2232 &config->runtime_flags);
2236 if (info->attrs[NBD_ATTR_SOCKETS]) {
2237 struct nlattr *attr;
2240 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
2242 struct nlattr *socks[NBD_SOCK_MAX+1];
2244 if (nla_type(attr) != NBD_SOCK_ITEM) {
2245 printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
2249 ret = nla_parse_nested_deprecated(socks, NBD_SOCK_MAX,
2254 printk(KERN_ERR "nbd: error processing sock list\n");
2258 if (!socks[NBD_SOCK_FD])
2260 fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
2261 ret = nbd_reconnect_socket(nbd, fd);
2267 dev_info(nbd_to_dev(nbd), "reconnected socket\n");
2271 mutex_unlock(&nbd->config_lock);
2272 nbd_config_put(nbd);
2279 static const struct genl_small_ops nbd_connect_genl_ops[] = {
2281 .cmd = NBD_CMD_CONNECT,
2282 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2283 .doit = nbd_genl_connect,
2286 .cmd = NBD_CMD_DISCONNECT,
2287 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2288 .doit = nbd_genl_disconnect,
2291 .cmd = NBD_CMD_RECONFIGURE,
2292 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2293 .doit = nbd_genl_reconfigure,
2296 .cmd = NBD_CMD_STATUS,
2297 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2298 .doit = nbd_genl_status,
2302 static const struct genl_multicast_group nbd_mcast_grps[] = {
2303 { .name = NBD_GENL_MCAST_GROUP_NAME, },
2306 static struct genl_family nbd_genl_family __ro_after_init = {
2308 .name = NBD_GENL_FAMILY_NAME,
2309 .version = NBD_GENL_VERSION,
2310 .module = THIS_MODULE,
2311 .small_ops = nbd_connect_genl_ops,
2312 .n_small_ops = ARRAY_SIZE(nbd_connect_genl_ops),
2313 .maxattr = NBD_ATTR_MAX,
2314 .policy = nbd_attr_policy,
2315 .mcgrps = nbd_mcast_grps,
2316 .n_mcgrps = ARRAY_SIZE(nbd_mcast_grps),
2319 static int populate_nbd_status(struct nbd_device *nbd, struct sk_buff *reply)
2321 struct nlattr *dev_opt;
2325 /* This is a little racey, but for status it's ok. The
2326 * reason we don't take a ref here is because we can't
2327 * take a ref in the index == -1 case as we would need
2328 * to put under the nbd_index_mutex, which could
2329 * deadlock if we are configured to remove ourselves
2330 * once we're disconnected.
2332 if (refcount_read(&nbd->config_refs))
2334 dev_opt = nla_nest_start_noflag(reply, NBD_DEVICE_ITEM);
2337 ret = nla_put_u32(reply, NBD_DEVICE_INDEX, nbd->index);
2340 ret = nla_put_u8(reply, NBD_DEVICE_CONNECTED,
2344 nla_nest_end(reply, dev_opt);
2348 static int status_cb(int id, void *ptr, void *data)
2350 struct nbd_device *nbd = ptr;
2351 return populate_nbd_status(nbd, (struct sk_buff *)data);
2354 static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info)
2356 struct nlattr *dev_list;
2357 struct sk_buff *reply;
2363 if (info->attrs[NBD_ATTR_INDEX])
2364 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2366 mutex_lock(&nbd_index_mutex);
2368 msg_size = nla_total_size(nla_attr_size(sizeof(u32)) +
2369 nla_attr_size(sizeof(u8)));
2370 msg_size *= (index == -1) ? nbd_total_devices : 1;
2372 reply = genlmsg_new(msg_size, GFP_KERNEL);
2375 reply_head = genlmsg_put_reply(reply, info, &nbd_genl_family, 0,
2382 dev_list = nla_nest_start_noflag(reply, NBD_ATTR_DEVICE_LIST);
2384 ret = idr_for_each(&nbd_index_idr, &status_cb, reply);
2390 struct nbd_device *nbd;
2391 nbd = idr_find(&nbd_index_idr, index);
2393 ret = populate_nbd_status(nbd, reply);
2400 nla_nest_end(reply, dev_list);
2401 genlmsg_end(reply, reply_head);
2402 ret = genlmsg_reply(reply, info);
2404 mutex_unlock(&nbd_index_mutex);
2408 static void nbd_connect_reply(struct genl_info *info, int index)
2410 struct sk_buff *skb;
2414 skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2417 msg_head = genlmsg_put_reply(skb, info, &nbd_genl_family, 0,
2423 ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2428 genlmsg_end(skb, msg_head);
2429 genlmsg_reply(skb, info);
2432 static void nbd_mcast_index(int index)
2434 struct sk_buff *skb;
2438 skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2441 msg_head = genlmsg_put(skb, 0, 0, &nbd_genl_family, 0,
2447 ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2452 genlmsg_end(skb, msg_head);
2453 genlmsg_multicast(&nbd_genl_family, skb, 0, 0, GFP_KERNEL);
2456 static void nbd_dead_link_work(struct work_struct *work)
2458 struct link_dead_args *args = container_of(work, struct link_dead_args,
2460 nbd_mcast_index(args->index);
2464 static int __init nbd_init(void)
2468 BUILD_BUG_ON(sizeof(struct nbd_request) != 28);
2471 printk(KERN_ERR "nbd: max_part must be >= 0\n");
2477 part_shift = fls(max_part);
2480 * Adjust max_part according to part_shift as it is exported
2481 * to user space so that user can know the max number of
2482 * partition kernel should be able to manage.
2484 * Note that -1 is required because partition 0 is reserved
2485 * for the whole disk.
2487 max_part = (1UL << part_shift) - 1;
2490 if ((1UL << part_shift) > DISK_MAX_PARTS)
2493 if (nbds_max > 1UL << (MINORBITS - part_shift))
2496 if (register_blkdev(NBD_MAJOR, "nbd"))
2499 nbd_del_wq = alloc_workqueue("nbd-del", WQ_UNBOUND, 0);
2501 unregister_blkdev(NBD_MAJOR, "nbd");
2505 if (genl_register_family(&nbd_genl_family)) {
2506 destroy_workqueue(nbd_del_wq);
2507 unregister_blkdev(NBD_MAJOR, "nbd");
2512 for (i = 0; i < nbds_max; i++)
2517 static int nbd_exit_cb(int id, void *ptr, void *data)
2519 struct list_head *list = (struct list_head *)data;
2520 struct nbd_device *nbd = ptr;
2522 /* Skip nbd that is being removed asynchronously */
2523 if (refcount_read(&nbd->refs))
2524 list_add_tail(&nbd->list, list);
2529 static void __exit nbd_cleanup(void)
2531 struct nbd_device *nbd;
2532 LIST_HEAD(del_list);
2536 mutex_lock(&nbd_index_mutex);
2537 idr_for_each(&nbd_index_idr, &nbd_exit_cb, &del_list);
2538 mutex_unlock(&nbd_index_mutex);
2540 while (!list_empty(&del_list)) {
2541 nbd = list_first_entry(&del_list, struct nbd_device, list);
2542 list_del_init(&nbd->list);
2543 if (refcount_read(&nbd->refs) != 1)
2544 printk(KERN_ERR "nbd: possibly leaking a device\n");
2548 /* Also wait for nbd_dev_remove_work() completes */
2549 destroy_workqueue(nbd_del_wq);
2551 idr_destroy(&nbd_index_idr);
2552 genl_unregister_family(&nbd_genl_family);
2553 unregister_blkdev(NBD_MAJOR, "nbd");
2556 module_init(nbd_init);
2557 module_exit(nbd_cleanup);
2559 MODULE_DESCRIPTION("Network Block Device");
2560 MODULE_LICENSE("GPL");
2562 module_param(nbds_max, int, 0444);
2563 MODULE_PARM_DESC(nbds_max, "number of network block devices to initialize (default: 16)");
2564 module_param(max_part, int, 0444);
2565 MODULE_PARM_DESC(max_part, "number of partitions per device (default: 16)");