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 int nbd_total_devices = 0;
57 struct request *pending;
64 struct recv_thread_args {
65 struct work_struct work;
66 struct nbd_device *nbd;
70 struct link_dead_args {
71 struct work_struct work;
75 #define NBD_RT_TIMEDOUT 0
76 #define NBD_RT_DISCONNECT_REQUESTED 1
77 #define NBD_RT_DISCONNECTED 2
78 #define NBD_RT_HAS_PID_FILE 3
79 #define NBD_RT_HAS_CONFIG_REF 4
80 #define NBD_RT_BOUND 5
81 #define NBD_RT_DISCONNECT_ON_CLOSE 6
83 #define NBD_DESTROY_ON_DISCONNECT 0
84 #define NBD_DISCONNECT_REQUESTED 1
88 unsigned long runtime_flags;
89 u64 dead_conn_timeout;
91 struct nbd_sock **socks;
93 atomic_t live_connections;
94 wait_queue_head_t conn_wait;
96 atomic_t recv_threads;
97 wait_queue_head_t recv_wq;
100 #if IS_ENABLED(CONFIG_DEBUG_FS)
101 struct dentry *dbg_dir;
106 struct blk_mq_tag_set tag_set;
109 refcount_t config_refs;
111 struct nbd_config *config;
112 struct mutex config_lock;
113 struct gendisk *disk;
114 struct workqueue_struct *recv_workq;
116 struct list_head list;
117 struct task_struct *task_recv;
118 struct task_struct *task_setup;
120 struct completion *destroy_complete;
124 #define NBD_CMD_REQUEUED 1
127 struct nbd_device *nbd;
137 #if IS_ENABLED(CONFIG_DEBUG_FS)
138 static struct dentry *nbd_dbg_dir;
141 #define nbd_name(nbd) ((nbd)->disk->disk_name)
143 #define NBD_MAGIC 0x68797548
145 #define NBD_DEF_BLKSIZE 1024
147 static unsigned int nbds_max = 16;
148 static int max_part = 16;
149 static int part_shift;
151 static int nbd_dev_dbg_init(struct nbd_device *nbd);
152 static void nbd_dev_dbg_close(struct nbd_device *nbd);
153 static void nbd_config_put(struct nbd_device *nbd);
154 static void nbd_connect_reply(struct genl_info *info, int index);
155 static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info);
156 static void nbd_dead_link_work(struct work_struct *work);
157 static void nbd_disconnect_and_put(struct nbd_device *nbd);
159 static inline struct device *nbd_to_dev(struct nbd_device *nbd)
161 return disk_to_dev(nbd->disk);
164 static void nbd_requeue_cmd(struct nbd_cmd *cmd)
166 struct request *req = blk_mq_rq_from_pdu(cmd);
168 if (!test_and_set_bit(NBD_CMD_REQUEUED, &cmd->flags))
169 blk_mq_requeue_request(req, true);
172 #define NBD_COOKIE_BITS 32
174 static u64 nbd_cmd_handle(struct nbd_cmd *cmd)
176 struct request *req = blk_mq_rq_from_pdu(cmd);
177 u32 tag = blk_mq_unique_tag(req);
178 u64 cookie = cmd->cmd_cookie;
180 return (cookie << NBD_COOKIE_BITS) | tag;
183 static u32 nbd_handle_to_tag(u64 handle)
188 static u32 nbd_handle_to_cookie(u64 handle)
190 return (u32)(handle >> NBD_COOKIE_BITS);
193 static const char *nbdcmd_to_ascii(int cmd)
196 case NBD_CMD_READ: return "read";
197 case NBD_CMD_WRITE: return "write";
198 case NBD_CMD_DISC: return "disconnect";
199 case NBD_CMD_FLUSH: return "flush";
200 case NBD_CMD_TRIM: return "trim/discard";
205 static ssize_t pid_show(struct device *dev,
206 struct device_attribute *attr, char *buf)
208 struct gendisk *disk = dev_to_disk(dev);
209 struct nbd_device *nbd = (struct nbd_device *)disk->private_data;
211 return sprintf(buf, "%d\n", task_pid_nr(nbd->task_recv));
214 static const struct device_attribute pid_attr = {
215 .attr = { .name = "pid", .mode = 0444},
219 static void nbd_dev_remove(struct nbd_device *nbd)
221 struct gendisk *disk = nbd->disk;
225 blk_mq_free_tag_set(&nbd->tag_set);
226 blk_cleanup_disk(disk);
230 * Place this in the last just before the nbd is freed to
231 * make sure that the disk and the related kobject are also
232 * totally removed to avoid duplicate creation of the same
235 if (test_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags) && nbd->destroy_complete)
236 complete(nbd->destroy_complete);
241 static void nbd_put(struct nbd_device *nbd)
243 if (refcount_dec_and_mutex_lock(&nbd->refs,
245 idr_remove(&nbd_index_idr, nbd->index);
247 mutex_unlock(&nbd_index_mutex);
251 static int nbd_disconnected(struct nbd_config *config)
253 return test_bit(NBD_RT_DISCONNECTED, &config->runtime_flags) ||
254 test_bit(NBD_RT_DISCONNECT_REQUESTED, &config->runtime_flags);
257 static void nbd_mark_nsock_dead(struct nbd_device *nbd, struct nbd_sock *nsock,
260 if (!nsock->dead && notify && !nbd_disconnected(nbd->config)) {
261 struct link_dead_args *args;
262 args = kmalloc(sizeof(struct link_dead_args), GFP_NOIO);
264 INIT_WORK(&args->work, nbd_dead_link_work);
265 args->index = nbd->index;
266 queue_work(system_wq, &args->work);
270 kernel_sock_shutdown(nsock->sock, SHUT_RDWR);
271 if (atomic_dec_return(&nbd->config->live_connections) == 0) {
272 if (test_and_clear_bit(NBD_RT_DISCONNECT_REQUESTED,
273 &nbd->config->runtime_flags)) {
274 set_bit(NBD_RT_DISCONNECTED,
275 &nbd->config->runtime_flags);
276 dev_info(nbd_to_dev(nbd),
277 "Disconnected due to user request.\n");
282 nsock->pending = NULL;
286 static void nbd_size_clear(struct nbd_device *nbd)
288 if (nbd->config->bytesize) {
289 set_capacity(nbd->disk, 0);
290 kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
294 static int nbd_set_size(struct nbd_device *nbd, loff_t bytesize,
298 blksize = NBD_DEF_BLKSIZE;
299 if (blksize < 512 || blksize > PAGE_SIZE || !is_power_of_2(blksize))
302 nbd->config->bytesize = bytesize;
303 nbd->config->blksize = blksize;
308 if (nbd->config->flags & NBD_FLAG_SEND_TRIM) {
309 nbd->disk->queue->limits.discard_granularity = blksize;
310 nbd->disk->queue->limits.discard_alignment = blksize;
311 blk_queue_max_discard_sectors(nbd->disk->queue, UINT_MAX);
313 blk_queue_logical_block_size(nbd->disk->queue, blksize);
314 blk_queue_physical_block_size(nbd->disk->queue, blksize);
317 set_bit(GD_NEED_PART_SCAN, &nbd->disk->state);
318 if (!set_capacity_and_notify(nbd->disk, bytesize >> 9))
319 kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
323 static void nbd_complete_rq(struct request *req)
325 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
327 dev_dbg(nbd_to_dev(cmd->nbd), "request %p: %s\n", req,
328 cmd->status ? "failed" : "done");
330 blk_mq_end_request(req, cmd->status);
334 * Forcibly shutdown the socket causing all listeners to error
336 static void sock_shutdown(struct nbd_device *nbd)
338 struct nbd_config *config = nbd->config;
341 if (config->num_connections == 0)
343 if (test_and_set_bit(NBD_RT_DISCONNECTED, &config->runtime_flags))
346 for (i = 0; i < config->num_connections; i++) {
347 struct nbd_sock *nsock = config->socks[i];
348 mutex_lock(&nsock->tx_lock);
349 nbd_mark_nsock_dead(nbd, nsock, 0);
350 mutex_unlock(&nsock->tx_lock);
352 dev_warn(disk_to_dev(nbd->disk), "shutting down sockets\n");
355 static u32 req_to_nbd_cmd_type(struct request *req)
357 switch (req_op(req)) {
361 return NBD_CMD_FLUSH;
363 return NBD_CMD_WRITE;
371 static enum blk_eh_timer_return nbd_xmit_timeout(struct request *req,
374 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
375 struct nbd_device *nbd = cmd->nbd;
376 struct nbd_config *config;
378 if (!mutex_trylock(&cmd->lock))
379 return BLK_EH_RESET_TIMER;
381 if (!refcount_inc_not_zero(&nbd->config_refs)) {
382 cmd->status = BLK_STS_TIMEOUT;
383 mutex_unlock(&cmd->lock);
386 config = nbd->config;
388 if (config->num_connections > 1 ||
389 (config->num_connections == 1 && nbd->tag_set.timeout)) {
390 dev_err_ratelimited(nbd_to_dev(nbd),
391 "Connection timed out, retrying (%d/%d alive)\n",
392 atomic_read(&config->live_connections),
393 config->num_connections);
395 * Hooray we have more connections, requeue this IO, the submit
396 * path will put it on a real connection. Or if only one
397 * connection is configured, the submit path will wait util
398 * a new connection is reconfigured or util dead timeout.
401 if (cmd->index < config->num_connections) {
402 struct nbd_sock *nsock =
403 config->socks[cmd->index];
404 mutex_lock(&nsock->tx_lock);
405 /* We can have multiple outstanding requests, so
406 * we don't want to mark the nsock dead if we've
407 * already reconnected with a new socket, so
408 * only mark it dead if its the same socket we
411 if (cmd->cookie == nsock->cookie)
412 nbd_mark_nsock_dead(nbd, nsock, 1);
413 mutex_unlock(&nsock->tx_lock);
415 mutex_unlock(&cmd->lock);
416 nbd_requeue_cmd(cmd);
422 if (!nbd->tag_set.timeout) {
424 * Userspace sets timeout=0 to disable socket disconnection,
425 * so just warn and reset the timer.
427 struct nbd_sock *nsock = config->socks[cmd->index];
429 dev_info(nbd_to_dev(nbd), "Possible stuck request %p: control (%s@%llu,%uB). Runtime %u seconds\n",
430 req, nbdcmd_to_ascii(req_to_nbd_cmd_type(req)),
431 (unsigned long long)blk_rq_pos(req) << 9,
432 blk_rq_bytes(req), (req->timeout / HZ) * cmd->retries);
434 mutex_lock(&nsock->tx_lock);
435 if (cmd->cookie != nsock->cookie) {
436 nbd_requeue_cmd(cmd);
437 mutex_unlock(&nsock->tx_lock);
438 mutex_unlock(&cmd->lock);
442 mutex_unlock(&nsock->tx_lock);
443 mutex_unlock(&cmd->lock);
445 return BLK_EH_RESET_TIMER;
448 dev_err_ratelimited(nbd_to_dev(nbd), "Connection timed out\n");
449 set_bit(NBD_RT_TIMEDOUT, &config->runtime_flags);
450 cmd->status = BLK_STS_IOERR;
451 mutex_unlock(&cmd->lock);
455 blk_mq_complete_request(req);
460 * Send or receive packet.
462 static int sock_xmit(struct nbd_device *nbd, int index, int send,
463 struct iov_iter *iter, int msg_flags, int *sent)
465 struct nbd_config *config = nbd->config;
466 struct socket *sock = config->socks[index]->sock;
469 unsigned int noreclaim_flag;
471 if (unlikely(!sock)) {
472 dev_err_ratelimited(disk_to_dev(nbd->disk),
473 "Attempted %s on closed socket in sock_xmit\n",
474 (send ? "send" : "recv"));
478 msg.msg_iter = *iter;
480 noreclaim_flag = memalloc_noreclaim_save();
482 sock->sk->sk_allocation = GFP_NOIO | __GFP_MEMALLOC;
485 msg.msg_control = NULL;
486 msg.msg_controllen = 0;
487 msg.msg_flags = msg_flags | MSG_NOSIGNAL;
490 result = sock_sendmsg(sock, &msg);
492 result = sock_recvmsg(sock, &msg, msg.msg_flags);
496 result = -EPIPE; /* short read */
501 } while (msg_data_left(&msg));
503 memalloc_noreclaim_restore(noreclaim_flag);
509 * Different settings for sk->sk_sndtimeo can result in different return values
510 * if there is a signal pending when we enter sendmsg, because reasons?
512 static inline int was_interrupted(int result)
514 return result == -ERESTARTSYS || result == -EINTR;
517 /* always call with the tx_lock held */
518 static int nbd_send_cmd(struct nbd_device *nbd, struct nbd_cmd *cmd, int index)
520 struct request *req = blk_mq_rq_from_pdu(cmd);
521 struct nbd_config *config = nbd->config;
522 struct nbd_sock *nsock = config->socks[index];
524 struct nbd_request request = {.magic = htonl(NBD_REQUEST_MAGIC)};
525 struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
526 struct iov_iter from;
527 unsigned long size = blk_rq_bytes(req);
531 u32 nbd_cmd_flags = 0;
532 int sent = nsock->sent, skip = 0;
534 iov_iter_kvec(&from, WRITE, &iov, 1, sizeof(request));
536 type = req_to_nbd_cmd_type(req);
540 if (rq_data_dir(req) == WRITE &&
541 (config->flags & NBD_FLAG_READ_ONLY)) {
542 dev_err_ratelimited(disk_to_dev(nbd->disk),
543 "Write on read-only\n");
547 if (req->cmd_flags & REQ_FUA)
548 nbd_cmd_flags |= NBD_CMD_FLAG_FUA;
550 /* We did a partial send previously, and we at least sent the whole
551 * request struct, so just go and send the rest of the pages in the
555 if (sent >= sizeof(request)) {
556 skip = sent - sizeof(request);
558 /* initialize handle for tracing purposes */
559 handle = nbd_cmd_handle(cmd);
563 iov_iter_advance(&from, sent);
568 cmd->cookie = nsock->cookie;
570 request.type = htonl(type | nbd_cmd_flags);
571 if (type != NBD_CMD_FLUSH) {
572 request.from = cpu_to_be64((u64)blk_rq_pos(req) << 9);
573 request.len = htonl(size);
575 handle = nbd_cmd_handle(cmd);
576 memcpy(request.handle, &handle, sizeof(handle));
578 trace_nbd_send_request(&request, nbd->index, blk_mq_rq_from_pdu(cmd));
580 dev_dbg(nbd_to_dev(nbd), "request %p: sending control (%s@%llu,%uB)\n",
581 req, nbdcmd_to_ascii(type),
582 (unsigned long long)blk_rq_pos(req) << 9, blk_rq_bytes(req));
583 result = sock_xmit(nbd, index, 1, &from,
584 (type == NBD_CMD_WRITE) ? MSG_MORE : 0, &sent);
585 trace_nbd_header_sent(req, handle);
587 if (was_interrupted(result)) {
588 /* If we havne't sent anything we can just return BUSY,
589 * however if we have sent something we need to make
590 * sure we only allow this req to be sent until we are
594 nsock->pending = req;
597 set_bit(NBD_CMD_REQUEUED, &cmd->flags);
598 return BLK_STS_RESOURCE;
600 dev_err_ratelimited(disk_to_dev(nbd->disk),
601 "Send control failed (result %d)\n", result);
605 if (type != NBD_CMD_WRITE)
610 struct bio *next = bio->bi_next;
611 struct bvec_iter iter;
614 bio_for_each_segment(bvec, bio, iter) {
615 bool is_last = !next && bio_iter_last(bvec, iter);
616 int flags = is_last ? 0 : MSG_MORE;
618 dev_dbg(nbd_to_dev(nbd), "request %p: sending %d bytes data\n",
620 iov_iter_bvec(&from, WRITE, &bvec, 1, bvec.bv_len);
622 if (skip >= iov_iter_count(&from)) {
623 skip -= iov_iter_count(&from);
626 iov_iter_advance(&from, skip);
629 result = sock_xmit(nbd, index, 1, &from, flags, &sent);
631 if (was_interrupted(result)) {
632 /* We've already sent the header, we
633 * have no choice but to set pending and
636 nsock->pending = req;
638 set_bit(NBD_CMD_REQUEUED, &cmd->flags);
639 return BLK_STS_RESOURCE;
641 dev_err(disk_to_dev(nbd->disk),
642 "Send data failed (result %d)\n",
647 * The completion might already have come in,
648 * so break for the last one instead of letting
649 * the iterator do it. This prevents use-after-free
658 trace_nbd_payload_sent(req, handle);
659 nsock->pending = NULL;
664 /* NULL returned = something went wrong, inform userspace */
665 static struct nbd_cmd *nbd_read_stat(struct nbd_device *nbd, int index)
667 struct nbd_config *config = nbd->config;
669 struct nbd_reply reply;
671 struct request *req = NULL;
675 struct kvec iov = {.iov_base = &reply, .iov_len = sizeof(reply)};
680 iov_iter_kvec(&to, READ, &iov, 1, sizeof(reply));
681 result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
683 if (!nbd_disconnected(config))
684 dev_err(disk_to_dev(nbd->disk),
685 "Receive control failed (result %d)\n", result);
686 return ERR_PTR(result);
689 if (ntohl(reply.magic) != NBD_REPLY_MAGIC) {
690 dev_err(disk_to_dev(nbd->disk), "Wrong magic (0x%lx)\n",
691 (unsigned long)ntohl(reply.magic));
692 return ERR_PTR(-EPROTO);
695 memcpy(&handle, reply.handle, sizeof(handle));
696 tag = nbd_handle_to_tag(handle);
697 hwq = blk_mq_unique_tag_to_hwq(tag);
698 if (hwq < nbd->tag_set.nr_hw_queues)
699 req = blk_mq_tag_to_rq(nbd->tag_set.tags[hwq],
700 blk_mq_unique_tag_to_tag(tag));
701 if (!req || !blk_mq_request_started(req)) {
702 dev_err(disk_to_dev(nbd->disk), "Unexpected reply (%d) %p\n",
704 return ERR_PTR(-ENOENT);
706 trace_nbd_header_received(req, handle);
707 cmd = blk_mq_rq_to_pdu(req);
709 mutex_lock(&cmd->lock);
710 if (cmd->cmd_cookie != nbd_handle_to_cookie(handle)) {
711 dev_err(disk_to_dev(nbd->disk), "Double reply on req %p, cmd_cookie %u, handle cookie %u\n",
712 req, cmd->cmd_cookie, nbd_handle_to_cookie(handle));
716 if (cmd->status != BLK_STS_OK) {
717 dev_err(disk_to_dev(nbd->disk), "Command already handled %p\n",
722 if (test_bit(NBD_CMD_REQUEUED, &cmd->flags)) {
723 dev_err(disk_to_dev(nbd->disk), "Raced with timeout on req %p\n",
728 if (ntohl(reply.error)) {
729 dev_err(disk_to_dev(nbd->disk), "Other side returned error (%d)\n",
731 cmd->status = BLK_STS_IOERR;
735 dev_dbg(nbd_to_dev(nbd), "request %p: got reply\n", req);
736 if (rq_data_dir(req) != WRITE) {
737 struct req_iterator iter;
740 rq_for_each_segment(bvec, req, iter) {
741 iov_iter_bvec(&to, READ, &bvec, 1, bvec.bv_len);
742 result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
744 dev_err(disk_to_dev(nbd->disk), "Receive data failed (result %d)\n",
747 * If we've disconnected, we need to make sure we
748 * complete this request, otherwise error out
749 * and let the timeout stuff handle resubmitting
750 * this request onto another connection.
752 if (nbd_disconnected(config)) {
753 cmd->status = BLK_STS_IOERR;
759 dev_dbg(nbd_to_dev(nbd), "request %p: got %d bytes data\n",
764 trace_nbd_payload_received(req, handle);
765 mutex_unlock(&cmd->lock);
766 return ret ? ERR_PTR(ret) : cmd;
769 static void recv_work(struct work_struct *work)
771 struct recv_thread_args *args = container_of(work,
772 struct recv_thread_args,
774 struct nbd_device *nbd = args->nbd;
775 struct nbd_config *config = nbd->config;
780 cmd = nbd_read_stat(nbd, args->index);
782 struct nbd_sock *nsock = config->socks[args->index];
784 mutex_lock(&nsock->tx_lock);
785 nbd_mark_nsock_dead(nbd, nsock, 1);
786 mutex_unlock(&nsock->tx_lock);
790 rq = blk_mq_rq_from_pdu(cmd);
791 if (likely(!blk_should_fake_timeout(rq->q)))
792 blk_mq_complete_request(rq);
795 atomic_dec(&config->recv_threads);
796 wake_up(&config->recv_wq);
800 static bool nbd_clear_req(struct request *req, void *data, bool reserved)
802 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
804 mutex_lock(&cmd->lock);
805 cmd->status = BLK_STS_IOERR;
806 mutex_unlock(&cmd->lock);
808 blk_mq_complete_request(req);
812 static void nbd_clear_que(struct nbd_device *nbd)
814 blk_mq_quiesce_queue(nbd->disk->queue);
815 blk_mq_tagset_busy_iter(&nbd->tag_set, nbd_clear_req, NULL);
816 blk_mq_unquiesce_queue(nbd->disk->queue);
817 dev_dbg(disk_to_dev(nbd->disk), "queue cleared\n");
820 static int find_fallback(struct nbd_device *nbd, int index)
822 struct nbd_config *config = nbd->config;
824 struct nbd_sock *nsock = config->socks[index];
825 int fallback = nsock->fallback_index;
827 if (test_bit(NBD_RT_DISCONNECTED, &config->runtime_flags))
830 if (config->num_connections <= 1) {
831 dev_err_ratelimited(disk_to_dev(nbd->disk),
832 "Dead connection, failed to find a fallback\n");
836 if (fallback >= 0 && fallback < config->num_connections &&
837 !config->socks[fallback]->dead)
840 if (nsock->fallback_index < 0 ||
841 nsock->fallback_index >= config->num_connections ||
842 config->socks[nsock->fallback_index]->dead) {
844 for (i = 0; i < config->num_connections; i++) {
847 if (!config->socks[i]->dead) {
852 nsock->fallback_index = new_index;
854 dev_err_ratelimited(disk_to_dev(nbd->disk),
855 "Dead connection, failed to find a fallback\n");
859 new_index = nsock->fallback_index;
863 static int wait_for_reconnect(struct nbd_device *nbd)
865 struct nbd_config *config = nbd->config;
866 if (!config->dead_conn_timeout)
868 if (test_bit(NBD_RT_DISCONNECTED, &config->runtime_flags))
870 return wait_event_timeout(config->conn_wait,
871 atomic_read(&config->live_connections) > 0,
872 config->dead_conn_timeout) > 0;
875 static int nbd_handle_cmd(struct nbd_cmd *cmd, int index)
877 struct request *req = blk_mq_rq_from_pdu(cmd);
878 struct nbd_device *nbd = cmd->nbd;
879 struct nbd_config *config;
880 struct nbd_sock *nsock;
883 if (!refcount_inc_not_zero(&nbd->config_refs)) {
884 dev_err_ratelimited(disk_to_dev(nbd->disk),
885 "Socks array is empty\n");
886 blk_mq_start_request(req);
889 config = nbd->config;
891 if (index >= config->num_connections) {
892 dev_err_ratelimited(disk_to_dev(nbd->disk),
893 "Attempted send on invalid socket\n");
895 blk_mq_start_request(req);
898 cmd->status = BLK_STS_OK;
900 nsock = config->socks[index];
901 mutex_lock(&nsock->tx_lock);
903 int old_index = index;
904 index = find_fallback(nbd, index);
905 mutex_unlock(&nsock->tx_lock);
907 if (wait_for_reconnect(nbd)) {
911 /* All the sockets should already be down at this point,
912 * we just want to make sure that DISCONNECTED is set so
913 * any requests that come in that were queue'ed waiting
914 * for the reconnect timer don't trigger the timer again
915 * and instead just error out.
919 blk_mq_start_request(req);
925 /* Handle the case that we have a pending request that was partially
926 * transmitted that _has_ to be serviced first. We need to call requeue
927 * here so that it gets put _after_ the request that is already on the
930 blk_mq_start_request(req);
931 if (unlikely(nsock->pending && nsock->pending != req)) {
932 nbd_requeue_cmd(cmd);
937 * Some failures are related to the link going down, so anything that
938 * returns EAGAIN can be retried on a different socket.
940 ret = nbd_send_cmd(nbd, cmd, index);
941 if (ret == -EAGAIN) {
942 dev_err_ratelimited(disk_to_dev(nbd->disk),
943 "Request send failed, requeueing\n");
944 nbd_mark_nsock_dead(nbd, nsock, 1);
945 nbd_requeue_cmd(cmd);
949 mutex_unlock(&nsock->tx_lock);
954 static blk_status_t nbd_queue_rq(struct blk_mq_hw_ctx *hctx,
955 const struct blk_mq_queue_data *bd)
957 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(bd->rq);
961 * Since we look at the bio's to send the request over the network we
962 * need to make sure the completion work doesn't mark this request done
963 * before we are done doing our send. This keeps us from dereferencing
964 * freed data if we have particularly fast completions (ie we get the
965 * completion before we exit sock_xmit on the last bvec) or in the case
966 * that the server is misbehaving (or there was an error) before we're
967 * done sending everything over the wire.
969 mutex_lock(&cmd->lock);
970 clear_bit(NBD_CMD_REQUEUED, &cmd->flags);
972 /* We can be called directly from the user space process, which means we
973 * could possibly have signals pending so our sendmsg will fail. In
974 * this case we need to return that we are busy, otherwise error out as
977 ret = nbd_handle_cmd(cmd, hctx->queue_num);
982 mutex_unlock(&cmd->lock);
987 static struct socket *nbd_get_socket(struct nbd_device *nbd, unsigned long fd,
993 sock = sockfd_lookup(fd, err);
997 if (sock->ops->shutdown == sock_no_shutdown) {
998 dev_err(disk_to_dev(nbd->disk), "Unsupported socket: shutdown callout must be supported.\n");
1007 static int nbd_add_socket(struct nbd_device *nbd, unsigned long arg,
1010 struct nbd_config *config = nbd->config;
1011 struct socket *sock;
1012 struct nbd_sock **socks;
1013 struct nbd_sock *nsock;
1016 sock = nbd_get_socket(nbd, arg, &err);
1021 * We need to make sure we don't get any errant requests while we're
1022 * reallocating the ->socks array.
1024 blk_mq_freeze_queue(nbd->disk->queue);
1026 if (!netlink && !nbd->task_setup &&
1027 !test_bit(NBD_RT_BOUND, &config->runtime_flags))
1028 nbd->task_setup = current;
1031 (nbd->task_setup != current ||
1032 test_bit(NBD_RT_BOUND, &config->runtime_flags))) {
1033 dev_err(disk_to_dev(nbd->disk),
1034 "Device being setup by another task");
1039 nsock = kzalloc(sizeof(*nsock), GFP_KERNEL);
1045 socks = krealloc(config->socks, (config->num_connections + 1) *
1046 sizeof(struct nbd_sock *), GFP_KERNEL);
1053 config->socks = socks;
1055 nsock->fallback_index = -1;
1056 nsock->dead = false;
1057 mutex_init(&nsock->tx_lock);
1059 nsock->pending = NULL;
1062 socks[config->num_connections++] = nsock;
1063 atomic_inc(&config->live_connections);
1064 blk_mq_unfreeze_queue(nbd->disk->queue);
1069 blk_mq_unfreeze_queue(nbd->disk->queue);
1074 static int nbd_reconnect_socket(struct nbd_device *nbd, unsigned long arg)
1076 struct nbd_config *config = nbd->config;
1077 struct socket *sock, *old;
1078 struct recv_thread_args *args;
1082 sock = nbd_get_socket(nbd, arg, &err);
1086 args = kzalloc(sizeof(*args), GFP_KERNEL);
1092 for (i = 0; i < config->num_connections; i++) {
1093 struct nbd_sock *nsock = config->socks[i];
1098 mutex_lock(&nsock->tx_lock);
1100 mutex_unlock(&nsock->tx_lock);
1103 sk_set_memalloc(sock->sk);
1104 if (nbd->tag_set.timeout)
1105 sock->sk->sk_sndtimeo = nbd->tag_set.timeout;
1106 atomic_inc(&config->recv_threads);
1107 refcount_inc(&nbd->config_refs);
1109 nsock->fallback_index = -1;
1111 nsock->dead = false;
1112 INIT_WORK(&args->work, recv_work);
1116 mutex_unlock(&nsock->tx_lock);
1119 clear_bit(NBD_RT_DISCONNECTED, &config->runtime_flags);
1121 /* We take the tx_mutex in an error path in the recv_work, so we
1122 * need to queue_work outside of the tx_mutex.
1124 queue_work(nbd->recv_workq, &args->work);
1126 atomic_inc(&config->live_connections);
1127 wake_up(&config->conn_wait);
1135 static void nbd_bdev_reset(struct block_device *bdev)
1137 if (bdev->bd_openers > 1)
1139 set_capacity(bdev->bd_disk, 0);
1142 static void nbd_parse_flags(struct nbd_device *nbd)
1144 struct nbd_config *config = nbd->config;
1145 if (config->flags & NBD_FLAG_READ_ONLY)
1146 set_disk_ro(nbd->disk, true);
1148 set_disk_ro(nbd->disk, false);
1149 if (config->flags & NBD_FLAG_SEND_TRIM)
1150 blk_queue_flag_set(QUEUE_FLAG_DISCARD, nbd->disk->queue);
1151 if (config->flags & NBD_FLAG_SEND_FLUSH) {
1152 if (config->flags & NBD_FLAG_SEND_FUA)
1153 blk_queue_write_cache(nbd->disk->queue, true, true);
1155 blk_queue_write_cache(nbd->disk->queue, true, false);
1158 blk_queue_write_cache(nbd->disk->queue, false, false);
1161 static void send_disconnects(struct nbd_device *nbd)
1163 struct nbd_config *config = nbd->config;
1164 struct nbd_request request = {
1165 .magic = htonl(NBD_REQUEST_MAGIC),
1166 .type = htonl(NBD_CMD_DISC),
1168 struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
1169 struct iov_iter from;
1172 for (i = 0; i < config->num_connections; i++) {
1173 struct nbd_sock *nsock = config->socks[i];
1175 iov_iter_kvec(&from, WRITE, &iov, 1, sizeof(request));
1176 mutex_lock(&nsock->tx_lock);
1177 ret = sock_xmit(nbd, i, 1, &from, 0, NULL);
1179 dev_err(disk_to_dev(nbd->disk),
1180 "Send disconnect failed %d\n", ret);
1181 mutex_unlock(&nsock->tx_lock);
1185 static int nbd_disconnect(struct nbd_device *nbd)
1187 struct nbd_config *config = nbd->config;
1189 dev_info(disk_to_dev(nbd->disk), "NBD_DISCONNECT\n");
1190 set_bit(NBD_RT_DISCONNECT_REQUESTED, &config->runtime_flags);
1191 set_bit(NBD_DISCONNECT_REQUESTED, &nbd->flags);
1192 send_disconnects(nbd);
1196 static void nbd_clear_sock(struct nbd_device *nbd)
1200 nbd->task_setup = NULL;
1203 static void nbd_config_put(struct nbd_device *nbd)
1205 if (refcount_dec_and_mutex_lock(&nbd->config_refs,
1206 &nbd->config_lock)) {
1207 struct nbd_config *config = nbd->config;
1208 nbd_dev_dbg_close(nbd);
1209 nbd_size_clear(nbd);
1210 if (test_and_clear_bit(NBD_RT_HAS_PID_FILE,
1211 &config->runtime_flags))
1212 device_remove_file(disk_to_dev(nbd->disk), &pid_attr);
1213 nbd->task_recv = NULL;
1214 nbd_clear_sock(nbd);
1215 if (config->num_connections) {
1217 for (i = 0; i < config->num_connections; i++) {
1218 sockfd_put(config->socks[i]->sock);
1219 kfree(config->socks[i]);
1221 kfree(config->socks);
1226 if (nbd->recv_workq)
1227 destroy_workqueue(nbd->recv_workq);
1228 nbd->recv_workq = NULL;
1230 nbd->tag_set.timeout = 0;
1231 nbd->disk->queue->limits.discard_granularity = 0;
1232 nbd->disk->queue->limits.discard_alignment = 0;
1233 blk_queue_max_discard_sectors(nbd->disk->queue, UINT_MAX);
1234 blk_queue_flag_clear(QUEUE_FLAG_DISCARD, nbd->disk->queue);
1236 mutex_unlock(&nbd->config_lock);
1238 module_put(THIS_MODULE);
1242 static int nbd_start_device(struct nbd_device *nbd)
1244 struct nbd_config *config = nbd->config;
1245 int num_connections = config->num_connections;
1252 if (num_connections > 1 &&
1253 !(config->flags & NBD_FLAG_CAN_MULTI_CONN)) {
1254 dev_err(disk_to_dev(nbd->disk), "server does not support multiple connections per device.\n");
1258 nbd->recv_workq = alloc_workqueue("knbd%d-recv",
1259 WQ_MEM_RECLAIM | WQ_HIGHPRI |
1260 WQ_UNBOUND, 0, nbd->index);
1261 if (!nbd->recv_workq) {
1262 dev_err(disk_to_dev(nbd->disk), "Could not allocate knbd recv work queue.\n");
1266 blk_mq_update_nr_hw_queues(&nbd->tag_set, config->num_connections);
1267 nbd->task_recv = current;
1269 nbd_parse_flags(nbd);
1271 error = device_create_file(disk_to_dev(nbd->disk), &pid_attr);
1273 dev_err(disk_to_dev(nbd->disk), "device_create_file failed!\n");
1276 set_bit(NBD_RT_HAS_PID_FILE, &config->runtime_flags);
1278 nbd_dev_dbg_init(nbd);
1279 for (i = 0; i < num_connections; i++) {
1280 struct recv_thread_args *args;
1282 args = kzalloc(sizeof(*args), GFP_KERNEL);
1286 * If num_connections is m (2 < m),
1287 * and NO.1 ~ NO.n(1 < n < m) kzallocs are successful.
1288 * But NO.(n + 1) failed. We still have n recv threads.
1289 * So, add flush_workqueue here to prevent recv threads
1290 * dropping the last config_refs and trying to destroy
1291 * the workqueue from inside the workqueue.
1294 flush_workqueue(nbd->recv_workq);
1297 sk_set_memalloc(config->socks[i]->sock->sk);
1298 if (nbd->tag_set.timeout)
1299 config->socks[i]->sock->sk->sk_sndtimeo =
1300 nbd->tag_set.timeout;
1301 atomic_inc(&config->recv_threads);
1302 refcount_inc(&nbd->config_refs);
1303 INIT_WORK(&args->work, recv_work);
1306 queue_work(nbd->recv_workq, &args->work);
1308 return nbd_set_size(nbd, config->bytesize, config->blksize);
1311 static int nbd_start_device_ioctl(struct nbd_device *nbd, struct block_device *bdev)
1313 struct nbd_config *config = nbd->config;
1316 ret = nbd_start_device(nbd);
1321 set_bit(GD_NEED_PART_SCAN, &nbd->disk->state);
1322 mutex_unlock(&nbd->config_lock);
1323 ret = wait_event_interruptible(config->recv_wq,
1324 atomic_read(&config->recv_threads) == 0);
1327 flush_workqueue(nbd->recv_workq);
1329 mutex_lock(&nbd->config_lock);
1330 nbd_bdev_reset(bdev);
1331 /* user requested, ignore socket errors */
1332 if (test_bit(NBD_RT_DISCONNECT_REQUESTED, &config->runtime_flags))
1334 if (test_bit(NBD_RT_TIMEDOUT, &config->runtime_flags))
1339 static void nbd_clear_sock_ioctl(struct nbd_device *nbd,
1340 struct block_device *bdev)
1343 __invalidate_device(bdev, true);
1344 nbd_bdev_reset(bdev);
1345 if (test_and_clear_bit(NBD_RT_HAS_CONFIG_REF,
1346 &nbd->config->runtime_flags))
1347 nbd_config_put(nbd);
1350 static void nbd_set_cmd_timeout(struct nbd_device *nbd, u64 timeout)
1352 nbd->tag_set.timeout = timeout * HZ;
1354 blk_queue_rq_timeout(nbd->disk->queue, timeout * HZ);
1356 blk_queue_rq_timeout(nbd->disk->queue, 30 * HZ);
1359 /* Must be called with config_lock held */
1360 static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
1361 unsigned int cmd, unsigned long arg)
1363 struct nbd_config *config = nbd->config;
1366 case NBD_DISCONNECT:
1367 return nbd_disconnect(nbd);
1368 case NBD_CLEAR_SOCK:
1369 nbd_clear_sock_ioctl(nbd, bdev);
1372 return nbd_add_socket(nbd, arg, false);
1373 case NBD_SET_BLKSIZE:
1374 return nbd_set_size(nbd, config->bytesize, arg);
1376 return nbd_set_size(nbd, arg, config->blksize);
1377 case NBD_SET_SIZE_BLOCKS:
1378 return nbd_set_size(nbd, arg * config->blksize,
1380 case NBD_SET_TIMEOUT:
1381 nbd_set_cmd_timeout(nbd, arg);
1385 config->flags = arg;
1388 return nbd_start_device_ioctl(nbd, bdev);
1391 * This is for compatibility only. The queue is always cleared
1392 * by NBD_DO_IT or NBD_CLEAR_SOCK.
1395 case NBD_PRINT_DEBUG:
1397 * For compatibility only, we no longer keep a list of
1398 * outstanding requests.
1405 static int nbd_ioctl(struct block_device *bdev, fmode_t mode,
1406 unsigned int cmd, unsigned long arg)
1408 struct nbd_device *nbd = bdev->bd_disk->private_data;
1409 struct nbd_config *config = nbd->config;
1410 int error = -EINVAL;
1412 if (!capable(CAP_SYS_ADMIN))
1415 /* The block layer will pass back some non-nbd ioctls in case we have
1416 * special handling for them, but we don't so just return an error.
1418 if (_IOC_TYPE(cmd) != 0xab)
1421 mutex_lock(&nbd->config_lock);
1423 /* Don't allow ioctl operations on a nbd device that was created with
1424 * netlink, unless it's DISCONNECT or CLEAR_SOCK, which are fine.
1426 if (!test_bit(NBD_RT_BOUND, &config->runtime_flags) ||
1427 (cmd == NBD_DISCONNECT || cmd == NBD_CLEAR_SOCK))
1428 error = __nbd_ioctl(bdev, nbd, cmd, arg);
1430 dev_err(nbd_to_dev(nbd), "Cannot use ioctl interface on a netlink controlled device.\n");
1431 mutex_unlock(&nbd->config_lock);
1435 static struct nbd_config *nbd_alloc_config(void)
1437 struct nbd_config *config;
1439 config = kzalloc(sizeof(struct nbd_config), GFP_NOFS);
1442 atomic_set(&config->recv_threads, 0);
1443 init_waitqueue_head(&config->recv_wq);
1444 init_waitqueue_head(&config->conn_wait);
1445 config->blksize = NBD_DEF_BLKSIZE;
1446 atomic_set(&config->live_connections, 0);
1447 try_module_get(THIS_MODULE);
1451 static int nbd_open(struct block_device *bdev, fmode_t mode)
1453 struct nbd_device *nbd;
1456 mutex_lock(&nbd_index_mutex);
1457 nbd = bdev->bd_disk->private_data;
1462 if (!refcount_inc_not_zero(&nbd->refs)) {
1466 if (!refcount_inc_not_zero(&nbd->config_refs)) {
1467 struct nbd_config *config;
1469 mutex_lock(&nbd->config_lock);
1470 if (refcount_inc_not_zero(&nbd->config_refs)) {
1471 mutex_unlock(&nbd->config_lock);
1474 config = nbd->config = nbd_alloc_config();
1477 mutex_unlock(&nbd->config_lock);
1480 refcount_set(&nbd->config_refs, 1);
1481 refcount_inc(&nbd->refs);
1482 mutex_unlock(&nbd->config_lock);
1484 set_bit(GD_NEED_PART_SCAN, &bdev->bd_disk->state);
1485 } else if (nbd_disconnected(nbd->config)) {
1487 set_bit(GD_NEED_PART_SCAN, &bdev->bd_disk->state);
1490 mutex_unlock(&nbd_index_mutex);
1494 static void nbd_release(struct gendisk *disk, fmode_t mode)
1496 struct nbd_device *nbd = disk->private_data;
1498 if (test_bit(NBD_RT_DISCONNECT_ON_CLOSE, &nbd->config->runtime_flags) &&
1499 disk->part0->bd_openers == 0)
1500 nbd_disconnect_and_put(nbd);
1502 nbd_config_put(nbd);
1506 static const struct block_device_operations nbd_fops =
1508 .owner = THIS_MODULE,
1510 .release = nbd_release,
1512 .compat_ioctl = nbd_ioctl,
1515 #if IS_ENABLED(CONFIG_DEBUG_FS)
1517 static int nbd_dbg_tasks_show(struct seq_file *s, void *unused)
1519 struct nbd_device *nbd = s->private;
1522 seq_printf(s, "recv: %d\n", task_pid_nr(nbd->task_recv));
1527 DEFINE_SHOW_ATTRIBUTE(nbd_dbg_tasks);
1529 static int nbd_dbg_flags_show(struct seq_file *s, void *unused)
1531 struct nbd_device *nbd = s->private;
1532 u32 flags = nbd->config->flags;
1534 seq_printf(s, "Hex: 0x%08x\n\n", flags);
1536 seq_puts(s, "Known flags:\n");
1538 if (flags & NBD_FLAG_HAS_FLAGS)
1539 seq_puts(s, "NBD_FLAG_HAS_FLAGS\n");
1540 if (flags & NBD_FLAG_READ_ONLY)
1541 seq_puts(s, "NBD_FLAG_READ_ONLY\n");
1542 if (flags & NBD_FLAG_SEND_FLUSH)
1543 seq_puts(s, "NBD_FLAG_SEND_FLUSH\n");
1544 if (flags & NBD_FLAG_SEND_FUA)
1545 seq_puts(s, "NBD_FLAG_SEND_FUA\n");
1546 if (flags & NBD_FLAG_SEND_TRIM)
1547 seq_puts(s, "NBD_FLAG_SEND_TRIM\n");
1552 DEFINE_SHOW_ATTRIBUTE(nbd_dbg_flags);
1554 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1557 struct nbd_config *config = nbd->config;
1562 dir = debugfs_create_dir(nbd_name(nbd), nbd_dbg_dir);
1564 dev_err(nbd_to_dev(nbd), "Failed to create debugfs dir for '%s'\n",
1568 config->dbg_dir = dir;
1570 debugfs_create_file("tasks", 0444, dir, nbd, &nbd_dbg_tasks_fops);
1571 debugfs_create_u64("size_bytes", 0444, dir, &config->bytesize);
1572 debugfs_create_u32("timeout", 0444, dir, &nbd->tag_set.timeout);
1573 debugfs_create_u64("blocksize", 0444, dir, &config->blksize);
1574 debugfs_create_file("flags", 0444, dir, nbd, &nbd_dbg_flags_fops);
1579 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1581 debugfs_remove_recursive(nbd->config->dbg_dir);
1584 static int nbd_dbg_init(void)
1586 struct dentry *dbg_dir;
1588 dbg_dir = debugfs_create_dir("nbd", NULL);
1592 nbd_dbg_dir = dbg_dir;
1597 static void nbd_dbg_close(void)
1599 debugfs_remove_recursive(nbd_dbg_dir);
1602 #else /* IS_ENABLED(CONFIG_DEBUG_FS) */
1604 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1609 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1613 static int nbd_dbg_init(void)
1618 static void nbd_dbg_close(void)
1624 static int nbd_init_request(struct blk_mq_tag_set *set, struct request *rq,
1625 unsigned int hctx_idx, unsigned int numa_node)
1627 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(rq);
1628 cmd->nbd = set->driver_data;
1630 mutex_init(&cmd->lock);
1634 static const struct blk_mq_ops nbd_mq_ops = {
1635 .queue_rq = nbd_queue_rq,
1636 .complete = nbd_complete_rq,
1637 .init_request = nbd_init_request,
1638 .timeout = nbd_xmit_timeout,
1641 static int nbd_dev_add(int index)
1643 struct nbd_device *nbd;
1644 struct gendisk *disk;
1647 nbd = kzalloc(sizeof(struct nbd_device), GFP_KERNEL);
1651 nbd->tag_set.ops = &nbd_mq_ops;
1652 nbd->tag_set.nr_hw_queues = 1;
1653 nbd->tag_set.queue_depth = 128;
1654 nbd->tag_set.numa_node = NUMA_NO_NODE;
1655 nbd->tag_set.cmd_size = sizeof(struct nbd_cmd);
1656 nbd->tag_set.flags = BLK_MQ_F_SHOULD_MERGE |
1658 nbd->tag_set.driver_data = nbd;
1659 nbd->destroy_complete = NULL;
1661 err = blk_mq_alloc_tag_set(&nbd->tag_set);
1666 err = idr_alloc(&nbd_index_idr, nbd, index, index + 1,
1671 err = idr_alloc(&nbd_index_idr, nbd, 0, 0, GFP_KERNEL);
1679 disk = blk_mq_alloc_disk(&nbd->tag_set, NULL);
1681 err = PTR_ERR(disk);
1687 * Tell the block layer that we are not a rotational device
1689 blk_queue_flag_set(QUEUE_FLAG_NONROT, disk->queue);
1690 blk_queue_flag_clear(QUEUE_FLAG_ADD_RANDOM, disk->queue);
1691 disk->queue->limits.discard_granularity = 0;
1692 disk->queue->limits.discard_alignment = 0;
1693 blk_queue_max_discard_sectors(disk->queue, 0);
1694 blk_queue_max_segment_size(disk->queue, UINT_MAX);
1695 blk_queue_max_segments(disk->queue, USHRT_MAX);
1696 blk_queue_max_hw_sectors(disk->queue, 65536);
1697 disk->queue->limits.max_sectors = 256;
1699 mutex_init(&nbd->config_lock);
1700 refcount_set(&nbd->config_refs, 0);
1701 refcount_set(&nbd->refs, 1);
1702 INIT_LIST_HEAD(&nbd->list);
1703 disk->major = NBD_MAJOR;
1704 disk->first_minor = index << part_shift;
1705 disk->minors = 1 << part_shift;
1706 disk->fops = &nbd_fops;
1707 disk->private_data = nbd;
1708 sprintf(disk->disk_name, "nbd%d", index);
1710 nbd_total_devices++;
1714 idr_remove(&nbd_index_idr, index);
1716 blk_mq_free_tag_set(&nbd->tag_set);
1723 static int find_free_cb(int id, void *ptr, void *data)
1725 struct nbd_device *nbd = ptr;
1726 struct nbd_device **found = data;
1728 if (!refcount_read(&nbd->config_refs)) {
1735 /* Netlink interface. */
1736 static const struct nla_policy nbd_attr_policy[NBD_ATTR_MAX + 1] = {
1737 [NBD_ATTR_INDEX] = { .type = NLA_U32 },
1738 [NBD_ATTR_SIZE_BYTES] = { .type = NLA_U64 },
1739 [NBD_ATTR_BLOCK_SIZE_BYTES] = { .type = NLA_U64 },
1740 [NBD_ATTR_TIMEOUT] = { .type = NLA_U64 },
1741 [NBD_ATTR_SERVER_FLAGS] = { .type = NLA_U64 },
1742 [NBD_ATTR_CLIENT_FLAGS] = { .type = NLA_U64 },
1743 [NBD_ATTR_SOCKETS] = { .type = NLA_NESTED},
1744 [NBD_ATTR_DEAD_CONN_TIMEOUT] = { .type = NLA_U64 },
1745 [NBD_ATTR_DEVICE_LIST] = { .type = NLA_NESTED},
1748 static const struct nla_policy nbd_sock_policy[NBD_SOCK_MAX + 1] = {
1749 [NBD_SOCK_FD] = { .type = NLA_U32 },
1752 /* We don't use this right now since we don't parse the incoming list, but we
1753 * still want it here so userspace knows what to expect.
1755 static const struct nla_policy __attribute__((unused))
1756 nbd_device_policy[NBD_DEVICE_ATTR_MAX + 1] = {
1757 [NBD_DEVICE_INDEX] = { .type = NLA_U32 },
1758 [NBD_DEVICE_CONNECTED] = { .type = NLA_U8 },
1761 static int nbd_genl_size_set(struct genl_info *info, struct nbd_device *nbd)
1763 struct nbd_config *config = nbd->config;
1764 u64 bsize = config->blksize;
1765 u64 bytes = config->bytesize;
1767 if (info->attrs[NBD_ATTR_SIZE_BYTES])
1768 bytes = nla_get_u64(info->attrs[NBD_ATTR_SIZE_BYTES]);
1770 if (info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES])
1771 bsize = nla_get_u64(info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]);
1773 if (bytes != config->bytesize || bsize != config->blksize)
1774 return nbd_set_size(nbd, bytes, bsize);
1778 static int nbd_genl_connect(struct sk_buff *skb, struct genl_info *info)
1780 DECLARE_COMPLETION_ONSTACK(destroy_complete);
1781 struct nbd_device *nbd = NULL;
1782 struct nbd_config *config;
1785 bool put_dev = false;
1787 if (!netlink_capable(skb, CAP_SYS_ADMIN))
1790 if (info->attrs[NBD_ATTR_INDEX])
1791 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1792 if (!info->attrs[NBD_ATTR_SOCKETS]) {
1793 printk(KERN_ERR "nbd: must specify at least one socket\n");
1796 if (!info->attrs[NBD_ATTR_SIZE_BYTES]) {
1797 printk(KERN_ERR "nbd: must specify a size in bytes for the device\n");
1801 mutex_lock(&nbd_index_mutex);
1803 ret = idr_for_each(&nbd_index_idr, &find_free_cb, &nbd);
1806 new_index = nbd_dev_add(-1);
1807 if (new_index < 0) {
1808 mutex_unlock(&nbd_index_mutex);
1809 printk(KERN_ERR "nbd: failed to add new device\n");
1812 nbd = idr_find(&nbd_index_idr, new_index);
1815 nbd = idr_find(&nbd_index_idr, index);
1817 ret = nbd_dev_add(index);
1819 mutex_unlock(&nbd_index_mutex);
1820 printk(KERN_ERR "nbd: failed to add new device\n");
1823 nbd = idr_find(&nbd_index_idr, index);
1827 printk(KERN_ERR "nbd: couldn't find device at index %d\n",
1829 mutex_unlock(&nbd_index_mutex);
1833 if (test_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags) &&
1834 test_bit(NBD_DISCONNECT_REQUESTED, &nbd->flags)) {
1835 nbd->destroy_complete = &destroy_complete;
1836 mutex_unlock(&nbd_index_mutex);
1838 /* Wait untill the the nbd stuff is totally destroyed */
1839 wait_for_completion(&destroy_complete);
1843 if (!refcount_inc_not_zero(&nbd->refs)) {
1844 mutex_unlock(&nbd_index_mutex);
1847 printk(KERN_ERR "nbd: device at index %d is going down\n",
1851 mutex_unlock(&nbd_index_mutex);
1853 mutex_lock(&nbd->config_lock);
1854 if (refcount_read(&nbd->config_refs)) {
1855 mutex_unlock(&nbd->config_lock);
1859 printk(KERN_ERR "nbd: nbd%d already in use\n", index);
1862 if (WARN_ON(nbd->config)) {
1863 mutex_unlock(&nbd->config_lock);
1867 config = nbd->config = nbd_alloc_config();
1869 mutex_unlock(&nbd->config_lock);
1871 printk(KERN_ERR "nbd: couldn't allocate config\n");
1874 refcount_set(&nbd->config_refs, 1);
1875 set_bit(NBD_RT_BOUND, &config->runtime_flags);
1877 ret = nbd_genl_size_set(info, nbd);
1881 if (info->attrs[NBD_ATTR_TIMEOUT])
1882 nbd_set_cmd_timeout(nbd,
1883 nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]));
1884 if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
1885 config->dead_conn_timeout =
1886 nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
1887 config->dead_conn_timeout *= HZ;
1889 if (info->attrs[NBD_ATTR_SERVER_FLAGS])
1891 nla_get_u64(info->attrs[NBD_ATTR_SERVER_FLAGS]);
1892 if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
1893 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
1894 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
1896 * We have 1 ref to keep the device around, and then 1
1897 * ref for our current operation here, which will be
1898 * inherited by the config. If we already have
1899 * DESTROY_ON_DISCONNECT set then we know we don't have
1900 * that extra ref already held so we don't need the
1903 if (!test_and_set_bit(NBD_DESTROY_ON_DISCONNECT,
1907 if (test_and_clear_bit(NBD_DESTROY_ON_DISCONNECT,
1909 refcount_inc(&nbd->refs);
1911 if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
1912 set_bit(NBD_RT_DISCONNECT_ON_CLOSE,
1913 &config->runtime_flags);
1917 if (info->attrs[NBD_ATTR_SOCKETS]) {
1918 struct nlattr *attr;
1921 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
1923 struct nlattr *socks[NBD_SOCK_MAX+1];
1925 if (nla_type(attr) != NBD_SOCK_ITEM) {
1926 printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
1930 ret = nla_parse_nested_deprecated(socks, NBD_SOCK_MAX,
1935 printk(KERN_ERR "nbd: error processing sock list\n");
1939 if (!socks[NBD_SOCK_FD])
1941 fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
1942 ret = nbd_add_socket(nbd, fd, true);
1947 ret = nbd_start_device(nbd);
1949 mutex_unlock(&nbd->config_lock);
1951 set_bit(NBD_RT_HAS_CONFIG_REF, &config->runtime_flags);
1952 refcount_inc(&nbd->config_refs);
1953 nbd_connect_reply(info, nbd->index);
1955 nbd_config_put(nbd);
1961 static void nbd_disconnect_and_put(struct nbd_device *nbd)
1963 mutex_lock(&nbd->config_lock);
1964 nbd_disconnect(nbd);
1965 nbd_clear_sock(nbd);
1966 mutex_unlock(&nbd->config_lock);
1968 * Make sure recv thread has finished, so it does not drop the last
1969 * config ref and try to destroy the workqueue from inside the work
1972 if (nbd->recv_workq)
1973 flush_workqueue(nbd->recv_workq);
1974 if (test_and_clear_bit(NBD_RT_HAS_CONFIG_REF,
1975 &nbd->config->runtime_flags))
1976 nbd_config_put(nbd);
1979 static int nbd_genl_disconnect(struct sk_buff *skb, struct genl_info *info)
1981 struct nbd_device *nbd;
1984 if (!netlink_capable(skb, CAP_SYS_ADMIN))
1987 if (!info->attrs[NBD_ATTR_INDEX]) {
1988 printk(KERN_ERR "nbd: must specify an index to disconnect\n");
1991 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1992 mutex_lock(&nbd_index_mutex);
1993 nbd = idr_find(&nbd_index_idr, index);
1995 mutex_unlock(&nbd_index_mutex);
1996 printk(KERN_ERR "nbd: couldn't find device at index %d\n",
2000 if (!refcount_inc_not_zero(&nbd->refs)) {
2001 mutex_unlock(&nbd_index_mutex);
2002 printk(KERN_ERR "nbd: device at index %d is going down\n",
2006 mutex_unlock(&nbd_index_mutex);
2007 if (!refcount_inc_not_zero(&nbd->config_refs))
2009 nbd_disconnect_and_put(nbd);
2010 nbd_config_put(nbd);
2016 static int nbd_genl_reconfigure(struct sk_buff *skb, struct genl_info *info)
2018 struct nbd_device *nbd = NULL;
2019 struct nbd_config *config;
2022 bool put_dev = false;
2024 if (!netlink_capable(skb, CAP_SYS_ADMIN))
2027 if (!info->attrs[NBD_ATTR_INDEX]) {
2028 printk(KERN_ERR "nbd: must specify a device to reconfigure\n");
2031 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2032 mutex_lock(&nbd_index_mutex);
2033 nbd = idr_find(&nbd_index_idr, index);
2035 mutex_unlock(&nbd_index_mutex);
2036 printk(KERN_ERR "nbd: couldn't find a device at index %d\n",
2040 if (!refcount_inc_not_zero(&nbd->refs)) {
2041 mutex_unlock(&nbd_index_mutex);
2042 printk(KERN_ERR "nbd: device at index %d is going down\n",
2046 mutex_unlock(&nbd_index_mutex);
2048 if (!refcount_inc_not_zero(&nbd->config_refs)) {
2049 dev_err(nbd_to_dev(nbd),
2050 "not configured, cannot reconfigure\n");
2055 mutex_lock(&nbd->config_lock);
2056 config = nbd->config;
2057 if (!test_bit(NBD_RT_BOUND, &config->runtime_flags) ||
2059 dev_err(nbd_to_dev(nbd),
2060 "not configured, cannot reconfigure\n");
2065 ret = nbd_genl_size_set(info, nbd);
2069 if (info->attrs[NBD_ATTR_TIMEOUT])
2070 nbd_set_cmd_timeout(nbd,
2071 nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]));
2072 if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
2073 config->dead_conn_timeout =
2074 nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
2075 config->dead_conn_timeout *= HZ;
2077 if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
2078 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
2079 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
2080 if (!test_and_set_bit(NBD_DESTROY_ON_DISCONNECT,
2084 if (test_and_clear_bit(NBD_DESTROY_ON_DISCONNECT,
2086 refcount_inc(&nbd->refs);
2089 if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
2090 set_bit(NBD_RT_DISCONNECT_ON_CLOSE,
2091 &config->runtime_flags);
2093 clear_bit(NBD_RT_DISCONNECT_ON_CLOSE,
2094 &config->runtime_flags);
2098 if (info->attrs[NBD_ATTR_SOCKETS]) {
2099 struct nlattr *attr;
2102 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
2104 struct nlattr *socks[NBD_SOCK_MAX+1];
2106 if (nla_type(attr) != NBD_SOCK_ITEM) {
2107 printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
2111 ret = nla_parse_nested_deprecated(socks, NBD_SOCK_MAX,
2116 printk(KERN_ERR "nbd: error processing sock list\n");
2120 if (!socks[NBD_SOCK_FD])
2122 fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
2123 ret = nbd_reconnect_socket(nbd, fd);
2129 dev_info(nbd_to_dev(nbd), "reconnected socket\n");
2133 mutex_unlock(&nbd->config_lock);
2134 nbd_config_put(nbd);
2141 static const struct genl_small_ops nbd_connect_genl_ops[] = {
2143 .cmd = NBD_CMD_CONNECT,
2144 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2145 .doit = nbd_genl_connect,
2148 .cmd = NBD_CMD_DISCONNECT,
2149 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2150 .doit = nbd_genl_disconnect,
2153 .cmd = NBD_CMD_RECONFIGURE,
2154 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2155 .doit = nbd_genl_reconfigure,
2158 .cmd = NBD_CMD_STATUS,
2159 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2160 .doit = nbd_genl_status,
2164 static const struct genl_multicast_group nbd_mcast_grps[] = {
2165 { .name = NBD_GENL_MCAST_GROUP_NAME, },
2168 static struct genl_family nbd_genl_family __ro_after_init = {
2170 .name = NBD_GENL_FAMILY_NAME,
2171 .version = NBD_GENL_VERSION,
2172 .module = THIS_MODULE,
2173 .small_ops = nbd_connect_genl_ops,
2174 .n_small_ops = ARRAY_SIZE(nbd_connect_genl_ops),
2175 .maxattr = NBD_ATTR_MAX,
2176 .policy = nbd_attr_policy,
2177 .mcgrps = nbd_mcast_grps,
2178 .n_mcgrps = ARRAY_SIZE(nbd_mcast_grps),
2181 static int populate_nbd_status(struct nbd_device *nbd, struct sk_buff *reply)
2183 struct nlattr *dev_opt;
2187 /* This is a little racey, but for status it's ok. The
2188 * reason we don't take a ref here is because we can't
2189 * take a ref in the index == -1 case as we would need
2190 * to put under the nbd_index_mutex, which could
2191 * deadlock if we are configured to remove ourselves
2192 * once we're disconnected.
2194 if (refcount_read(&nbd->config_refs))
2196 dev_opt = nla_nest_start_noflag(reply, NBD_DEVICE_ITEM);
2199 ret = nla_put_u32(reply, NBD_DEVICE_INDEX, nbd->index);
2202 ret = nla_put_u8(reply, NBD_DEVICE_CONNECTED,
2206 nla_nest_end(reply, dev_opt);
2210 static int status_cb(int id, void *ptr, void *data)
2212 struct nbd_device *nbd = ptr;
2213 return populate_nbd_status(nbd, (struct sk_buff *)data);
2216 static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info)
2218 struct nlattr *dev_list;
2219 struct sk_buff *reply;
2225 if (info->attrs[NBD_ATTR_INDEX])
2226 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2228 mutex_lock(&nbd_index_mutex);
2230 msg_size = nla_total_size(nla_attr_size(sizeof(u32)) +
2231 nla_attr_size(sizeof(u8)));
2232 msg_size *= (index == -1) ? nbd_total_devices : 1;
2234 reply = genlmsg_new(msg_size, GFP_KERNEL);
2237 reply_head = genlmsg_put_reply(reply, info, &nbd_genl_family, 0,
2244 dev_list = nla_nest_start_noflag(reply, NBD_ATTR_DEVICE_LIST);
2246 ret = idr_for_each(&nbd_index_idr, &status_cb, reply);
2252 struct nbd_device *nbd;
2253 nbd = idr_find(&nbd_index_idr, index);
2255 ret = populate_nbd_status(nbd, reply);
2262 nla_nest_end(reply, dev_list);
2263 genlmsg_end(reply, reply_head);
2264 ret = genlmsg_reply(reply, info);
2266 mutex_unlock(&nbd_index_mutex);
2270 static void nbd_connect_reply(struct genl_info *info, int index)
2272 struct sk_buff *skb;
2276 skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2279 msg_head = genlmsg_put_reply(skb, info, &nbd_genl_family, 0,
2285 ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2290 genlmsg_end(skb, msg_head);
2291 genlmsg_reply(skb, info);
2294 static void nbd_mcast_index(int index)
2296 struct sk_buff *skb;
2300 skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2303 msg_head = genlmsg_put(skb, 0, 0, &nbd_genl_family, 0,
2309 ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2314 genlmsg_end(skb, msg_head);
2315 genlmsg_multicast(&nbd_genl_family, skb, 0, 0, GFP_KERNEL);
2318 static void nbd_dead_link_work(struct work_struct *work)
2320 struct link_dead_args *args = container_of(work, struct link_dead_args,
2322 nbd_mcast_index(args->index);
2326 static int __init nbd_init(void)
2330 BUILD_BUG_ON(sizeof(struct nbd_request) != 28);
2333 printk(KERN_ERR "nbd: max_part must be >= 0\n");
2339 part_shift = fls(max_part);
2342 * Adjust max_part according to part_shift as it is exported
2343 * to user space so that user can know the max number of
2344 * partition kernel should be able to manage.
2346 * Note that -1 is required because partition 0 is reserved
2347 * for the whole disk.
2349 max_part = (1UL << part_shift) - 1;
2352 if ((1UL << part_shift) > DISK_MAX_PARTS)
2355 if (nbds_max > 1UL << (MINORBITS - part_shift))
2358 if (register_blkdev(NBD_MAJOR, "nbd"))
2361 if (genl_register_family(&nbd_genl_family)) {
2362 unregister_blkdev(NBD_MAJOR, "nbd");
2367 mutex_lock(&nbd_index_mutex);
2368 for (i = 0; i < nbds_max; i++)
2370 mutex_unlock(&nbd_index_mutex);
2374 static int nbd_exit_cb(int id, void *ptr, void *data)
2376 struct list_head *list = (struct list_head *)data;
2377 struct nbd_device *nbd = ptr;
2379 list_add_tail(&nbd->list, list);
2383 static void __exit nbd_cleanup(void)
2385 struct nbd_device *nbd;
2386 LIST_HEAD(del_list);
2390 mutex_lock(&nbd_index_mutex);
2391 idr_for_each(&nbd_index_idr, &nbd_exit_cb, &del_list);
2392 mutex_unlock(&nbd_index_mutex);
2394 while (!list_empty(&del_list)) {
2395 nbd = list_first_entry(&del_list, struct nbd_device, list);
2396 list_del_init(&nbd->list);
2397 if (refcount_read(&nbd->refs) != 1)
2398 printk(KERN_ERR "nbd: possibly leaking a device\n");
2402 idr_destroy(&nbd_index_idr);
2403 genl_unregister_family(&nbd_genl_family);
2404 unregister_blkdev(NBD_MAJOR, "nbd");
2407 module_init(nbd_init);
2408 module_exit(nbd_cleanup);
2410 MODULE_DESCRIPTION("Network Block Device");
2411 MODULE_LICENSE("GPL");
2413 module_param(nbds_max, int, 0444);
2414 MODULE_PARM_DESC(nbds_max, "number of network block devices to initialize (default: 16)");
2415 module_param(max_part, int, 0444);
2416 MODULE_PARM_DESC(max_part, "number of partitions per device (default: 16)");