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
82 #define NBD_RT_HAS_BACKEND_FILE 7
84 #define NBD_DESTROY_ON_DISCONNECT 0
85 #define NBD_DISCONNECT_REQUESTED 1
89 unsigned long runtime_flags;
90 u64 dead_conn_timeout;
92 struct nbd_sock **socks;
94 atomic_t live_connections;
95 wait_queue_head_t conn_wait;
97 atomic_t recv_threads;
98 wait_queue_head_t recv_wq;
101 #if IS_ENABLED(CONFIG_DEBUG_FS)
102 struct dentry *dbg_dir;
107 struct blk_mq_tag_set tag_set;
110 refcount_t config_refs;
112 struct nbd_config *config;
113 struct mutex config_lock;
114 struct gendisk *disk;
115 struct workqueue_struct *recv_workq;
117 struct list_head list;
118 struct task_struct *task_recv;
119 struct task_struct *task_setup;
121 struct completion *destroy_complete;
127 #define NBD_CMD_REQUEUED 1
130 struct nbd_device *nbd;
140 #if IS_ENABLED(CONFIG_DEBUG_FS)
141 static struct dentry *nbd_dbg_dir;
144 #define nbd_name(nbd) ((nbd)->disk->disk_name)
146 #define NBD_MAGIC 0x68797548
148 #define NBD_DEF_BLKSIZE 1024
150 static unsigned int nbds_max = 16;
151 static int max_part = 16;
152 static int part_shift;
154 static int nbd_dev_dbg_init(struct nbd_device *nbd);
155 static void nbd_dev_dbg_close(struct nbd_device *nbd);
156 static void nbd_config_put(struct nbd_device *nbd);
157 static void nbd_connect_reply(struct genl_info *info, int index);
158 static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info);
159 static void nbd_dead_link_work(struct work_struct *work);
160 static void nbd_disconnect_and_put(struct nbd_device *nbd);
162 static inline struct device *nbd_to_dev(struct nbd_device *nbd)
164 return disk_to_dev(nbd->disk);
167 static void nbd_requeue_cmd(struct nbd_cmd *cmd)
169 struct request *req = blk_mq_rq_from_pdu(cmd);
171 if (!test_and_set_bit(NBD_CMD_REQUEUED, &cmd->flags))
172 blk_mq_requeue_request(req, true);
175 #define NBD_COOKIE_BITS 32
177 static u64 nbd_cmd_handle(struct nbd_cmd *cmd)
179 struct request *req = blk_mq_rq_from_pdu(cmd);
180 u32 tag = blk_mq_unique_tag(req);
181 u64 cookie = cmd->cmd_cookie;
183 return (cookie << NBD_COOKIE_BITS) | tag;
186 static u32 nbd_handle_to_tag(u64 handle)
191 static u32 nbd_handle_to_cookie(u64 handle)
193 return (u32)(handle >> NBD_COOKIE_BITS);
196 static const char *nbdcmd_to_ascii(int cmd)
199 case NBD_CMD_READ: return "read";
200 case NBD_CMD_WRITE: return "write";
201 case NBD_CMD_DISC: return "disconnect";
202 case NBD_CMD_FLUSH: return "flush";
203 case NBD_CMD_TRIM: return "trim/discard";
208 static ssize_t pid_show(struct device *dev,
209 struct device_attribute *attr, char *buf)
211 struct gendisk *disk = dev_to_disk(dev);
212 struct nbd_device *nbd = (struct nbd_device *)disk->private_data;
214 return sprintf(buf, "%d\n", task_pid_nr(nbd->task_recv));
217 static const struct device_attribute pid_attr = {
218 .attr = { .name = "pid", .mode = 0444},
222 static ssize_t backend_show(struct device *dev,
223 struct device_attribute *attr, char *buf)
225 struct gendisk *disk = dev_to_disk(dev);
226 struct nbd_device *nbd = (struct nbd_device *)disk->private_data;
228 return sprintf(buf, "%s\n", nbd->backend ?: "");
231 static const struct device_attribute backend_attr = {
232 .attr = { .name = "backend", .mode = 0444},
233 .show = backend_show,
236 static void nbd_dev_remove(struct nbd_device *nbd)
238 struct gendisk *disk = nbd->disk;
242 blk_cleanup_disk(disk);
243 blk_mq_free_tag_set(&nbd->tag_set);
247 * Place this in the last just before the nbd is freed to
248 * make sure that the disk and the related kobject are also
249 * totally removed to avoid duplicate creation of the same
252 if (test_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags) && nbd->destroy_complete)
253 complete(nbd->destroy_complete);
258 static void nbd_put(struct nbd_device *nbd)
260 if (refcount_dec_and_mutex_lock(&nbd->refs,
262 idr_remove(&nbd_index_idr, nbd->index);
264 mutex_unlock(&nbd_index_mutex);
268 static int nbd_disconnected(struct nbd_config *config)
270 return test_bit(NBD_RT_DISCONNECTED, &config->runtime_flags) ||
271 test_bit(NBD_RT_DISCONNECT_REQUESTED, &config->runtime_flags);
274 static void nbd_mark_nsock_dead(struct nbd_device *nbd, struct nbd_sock *nsock,
277 if (!nsock->dead && notify && !nbd_disconnected(nbd->config)) {
278 struct link_dead_args *args;
279 args = kmalloc(sizeof(struct link_dead_args), GFP_NOIO);
281 INIT_WORK(&args->work, nbd_dead_link_work);
282 args->index = nbd->index;
283 queue_work(system_wq, &args->work);
287 kernel_sock_shutdown(nsock->sock, SHUT_RDWR);
288 if (atomic_dec_return(&nbd->config->live_connections) == 0) {
289 if (test_and_clear_bit(NBD_RT_DISCONNECT_REQUESTED,
290 &nbd->config->runtime_flags)) {
291 set_bit(NBD_RT_DISCONNECTED,
292 &nbd->config->runtime_flags);
293 dev_info(nbd_to_dev(nbd),
294 "Disconnected due to user request.\n");
299 nsock->pending = NULL;
303 static void nbd_size_clear(struct nbd_device *nbd)
305 if (nbd->config->bytesize) {
306 set_capacity(nbd->disk, 0);
307 kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
311 static int nbd_set_size(struct nbd_device *nbd, loff_t bytesize,
315 blksize = NBD_DEF_BLKSIZE;
316 if (blksize < 512 || blksize > PAGE_SIZE || !is_power_of_2(blksize))
319 nbd->config->bytesize = bytesize;
320 nbd->config->blksize = blksize;
325 if (nbd->config->flags & NBD_FLAG_SEND_TRIM) {
326 nbd->disk->queue->limits.discard_granularity = blksize;
327 nbd->disk->queue->limits.discard_alignment = blksize;
328 blk_queue_max_discard_sectors(nbd->disk->queue, UINT_MAX);
330 blk_queue_logical_block_size(nbd->disk->queue, blksize);
331 blk_queue_physical_block_size(nbd->disk->queue, blksize);
334 set_bit(GD_NEED_PART_SCAN, &nbd->disk->state);
335 if (!set_capacity_and_notify(nbd->disk, bytesize >> 9))
336 kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
340 static void nbd_complete_rq(struct request *req)
342 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
344 dev_dbg(nbd_to_dev(cmd->nbd), "request %p: %s\n", req,
345 cmd->status ? "failed" : "done");
347 blk_mq_end_request(req, cmd->status);
351 * Forcibly shutdown the socket causing all listeners to error
353 static void sock_shutdown(struct nbd_device *nbd)
355 struct nbd_config *config = nbd->config;
358 if (config->num_connections == 0)
360 if (test_and_set_bit(NBD_RT_DISCONNECTED, &config->runtime_flags))
363 for (i = 0; i < config->num_connections; i++) {
364 struct nbd_sock *nsock = config->socks[i];
365 mutex_lock(&nsock->tx_lock);
366 nbd_mark_nsock_dead(nbd, nsock, 0);
367 mutex_unlock(&nsock->tx_lock);
369 dev_warn(disk_to_dev(nbd->disk), "shutting down sockets\n");
372 static u32 req_to_nbd_cmd_type(struct request *req)
374 switch (req_op(req)) {
378 return NBD_CMD_FLUSH;
380 return NBD_CMD_WRITE;
388 static enum blk_eh_timer_return nbd_xmit_timeout(struct request *req,
391 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
392 struct nbd_device *nbd = cmd->nbd;
393 struct nbd_config *config;
395 if (!mutex_trylock(&cmd->lock))
396 return BLK_EH_RESET_TIMER;
398 if (!refcount_inc_not_zero(&nbd->config_refs)) {
399 cmd->status = BLK_STS_TIMEOUT;
400 mutex_unlock(&cmd->lock);
403 config = nbd->config;
405 if (config->num_connections > 1 ||
406 (config->num_connections == 1 && nbd->tag_set.timeout)) {
407 dev_err_ratelimited(nbd_to_dev(nbd),
408 "Connection timed out, retrying (%d/%d alive)\n",
409 atomic_read(&config->live_connections),
410 config->num_connections);
412 * Hooray we have more connections, requeue this IO, the submit
413 * path will put it on a real connection. Or if only one
414 * connection is configured, the submit path will wait util
415 * a new connection is reconfigured or util dead timeout.
418 if (cmd->index < config->num_connections) {
419 struct nbd_sock *nsock =
420 config->socks[cmd->index];
421 mutex_lock(&nsock->tx_lock);
422 /* We can have multiple outstanding requests, so
423 * we don't want to mark the nsock dead if we've
424 * already reconnected with a new socket, so
425 * only mark it dead if its the same socket we
428 if (cmd->cookie == nsock->cookie)
429 nbd_mark_nsock_dead(nbd, nsock, 1);
430 mutex_unlock(&nsock->tx_lock);
432 mutex_unlock(&cmd->lock);
433 nbd_requeue_cmd(cmd);
439 if (!nbd->tag_set.timeout) {
441 * Userspace sets timeout=0 to disable socket disconnection,
442 * so just warn and reset the timer.
444 struct nbd_sock *nsock = config->socks[cmd->index];
446 dev_info(nbd_to_dev(nbd), "Possible stuck request %p: control (%s@%llu,%uB). Runtime %u seconds\n",
447 req, nbdcmd_to_ascii(req_to_nbd_cmd_type(req)),
448 (unsigned long long)blk_rq_pos(req) << 9,
449 blk_rq_bytes(req), (req->timeout / HZ) * cmd->retries);
451 mutex_lock(&nsock->tx_lock);
452 if (cmd->cookie != nsock->cookie) {
453 nbd_requeue_cmd(cmd);
454 mutex_unlock(&nsock->tx_lock);
455 mutex_unlock(&cmd->lock);
459 mutex_unlock(&nsock->tx_lock);
460 mutex_unlock(&cmd->lock);
462 return BLK_EH_RESET_TIMER;
465 dev_err_ratelimited(nbd_to_dev(nbd), "Connection timed out\n");
466 set_bit(NBD_RT_TIMEDOUT, &config->runtime_flags);
467 cmd->status = BLK_STS_IOERR;
468 mutex_unlock(&cmd->lock);
472 blk_mq_complete_request(req);
477 * Send or receive packet.
479 static int sock_xmit(struct nbd_device *nbd, int index, int send,
480 struct iov_iter *iter, int msg_flags, int *sent)
482 struct nbd_config *config = nbd->config;
483 struct socket *sock = config->socks[index]->sock;
486 unsigned int noreclaim_flag;
488 if (unlikely(!sock)) {
489 dev_err_ratelimited(disk_to_dev(nbd->disk),
490 "Attempted %s on closed socket in sock_xmit\n",
491 (send ? "send" : "recv"));
495 msg.msg_iter = *iter;
497 noreclaim_flag = memalloc_noreclaim_save();
499 sock->sk->sk_allocation = GFP_NOIO | __GFP_MEMALLOC;
502 msg.msg_control = NULL;
503 msg.msg_controllen = 0;
504 msg.msg_flags = msg_flags | MSG_NOSIGNAL;
507 result = sock_sendmsg(sock, &msg);
509 result = sock_recvmsg(sock, &msg, msg.msg_flags);
513 result = -EPIPE; /* short read */
518 } while (msg_data_left(&msg));
520 memalloc_noreclaim_restore(noreclaim_flag);
526 * Different settings for sk->sk_sndtimeo can result in different return values
527 * if there is a signal pending when we enter sendmsg, because reasons?
529 static inline int was_interrupted(int result)
531 return result == -ERESTARTSYS || result == -EINTR;
534 /* always call with the tx_lock held */
535 static int nbd_send_cmd(struct nbd_device *nbd, struct nbd_cmd *cmd, int index)
537 struct request *req = blk_mq_rq_from_pdu(cmd);
538 struct nbd_config *config = nbd->config;
539 struct nbd_sock *nsock = config->socks[index];
541 struct nbd_request request = {.magic = htonl(NBD_REQUEST_MAGIC)};
542 struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
543 struct iov_iter from;
544 unsigned long size = blk_rq_bytes(req);
548 u32 nbd_cmd_flags = 0;
549 int sent = nsock->sent, skip = 0;
551 iov_iter_kvec(&from, WRITE, &iov, 1, sizeof(request));
553 type = req_to_nbd_cmd_type(req);
557 if (rq_data_dir(req) == WRITE &&
558 (config->flags & NBD_FLAG_READ_ONLY)) {
559 dev_err_ratelimited(disk_to_dev(nbd->disk),
560 "Write on read-only\n");
564 if (req->cmd_flags & REQ_FUA)
565 nbd_cmd_flags |= NBD_CMD_FLAG_FUA;
567 /* We did a partial send previously, and we at least sent the whole
568 * request struct, so just go and send the rest of the pages in the
572 if (sent >= sizeof(request)) {
573 skip = sent - sizeof(request);
575 /* initialize handle for tracing purposes */
576 handle = nbd_cmd_handle(cmd);
580 iov_iter_advance(&from, sent);
585 cmd->cookie = nsock->cookie;
587 request.type = htonl(type | nbd_cmd_flags);
588 if (type != NBD_CMD_FLUSH) {
589 request.from = cpu_to_be64((u64)blk_rq_pos(req) << 9);
590 request.len = htonl(size);
592 handle = nbd_cmd_handle(cmd);
593 memcpy(request.handle, &handle, sizeof(handle));
595 trace_nbd_send_request(&request, nbd->index, blk_mq_rq_from_pdu(cmd));
597 dev_dbg(nbd_to_dev(nbd), "request %p: sending control (%s@%llu,%uB)\n",
598 req, nbdcmd_to_ascii(type),
599 (unsigned long long)blk_rq_pos(req) << 9, blk_rq_bytes(req));
600 result = sock_xmit(nbd, index, 1, &from,
601 (type == NBD_CMD_WRITE) ? MSG_MORE : 0, &sent);
602 trace_nbd_header_sent(req, handle);
604 if (was_interrupted(result)) {
605 /* If we havne't sent anything we can just return BUSY,
606 * however if we have sent something we need to make
607 * sure we only allow this req to be sent until we are
611 nsock->pending = req;
614 set_bit(NBD_CMD_REQUEUED, &cmd->flags);
615 return BLK_STS_RESOURCE;
617 dev_err_ratelimited(disk_to_dev(nbd->disk),
618 "Send control failed (result %d)\n", result);
622 if (type != NBD_CMD_WRITE)
627 struct bio *next = bio->bi_next;
628 struct bvec_iter iter;
631 bio_for_each_segment(bvec, bio, iter) {
632 bool is_last = !next && bio_iter_last(bvec, iter);
633 int flags = is_last ? 0 : MSG_MORE;
635 dev_dbg(nbd_to_dev(nbd), "request %p: sending %d bytes data\n",
637 iov_iter_bvec(&from, WRITE, &bvec, 1, bvec.bv_len);
639 if (skip >= iov_iter_count(&from)) {
640 skip -= iov_iter_count(&from);
643 iov_iter_advance(&from, skip);
646 result = sock_xmit(nbd, index, 1, &from, flags, &sent);
648 if (was_interrupted(result)) {
649 /* We've already sent the header, we
650 * have no choice but to set pending and
653 nsock->pending = req;
655 set_bit(NBD_CMD_REQUEUED, &cmd->flags);
656 return BLK_STS_RESOURCE;
658 dev_err(disk_to_dev(nbd->disk),
659 "Send data failed (result %d)\n",
664 * The completion might already have come in,
665 * so break for the last one instead of letting
666 * the iterator do it. This prevents use-after-free
675 trace_nbd_payload_sent(req, handle);
676 nsock->pending = NULL;
681 /* NULL returned = something went wrong, inform userspace */
682 static struct nbd_cmd *nbd_read_stat(struct nbd_device *nbd, int index)
684 struct nbd_config *config = nbd->config;
686 struct nbd_reply reply;
688 struct request *req = NULL;
692 struct kvec iov = {.iov_base = &reply, .iov_len = sizeof(reply)};
697 iov_iter_kvec(&to, READ, &iov, 1, sizeof(reply));
698 result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
700 if (!nbd_disconnected(config))
701 dev_err(disk_to_dev(nbd->disk),
702 "Receive control failed (result %d)\n", result);
703 return ERR_PTR(result);
706 if (ntohl(reply.magic) != NBD_REPLY_MAGIC) {
707 dev_err(disk_to_dev(nbd->disk), "Wrong magic (0x%lx)\n",
708 (unsigned long)ntohl(reply.magic));
709 return ERR_PTR(-EPROTO);
712 memcpy(&handle, reply.handle, sizeof(handle));
713 tag = nbd_handle_to_tag(handle);
714 hwq = blk_mq_unique_tag_to_hwq(tag);
715 if (hwq < nbd->tag_set.nr_hw_queues)
716 req = blk_mq_tag_to_rq(nbd->tag_set.tags[hwq],
717 blk_mq_unique_tag_to_tag(tag));
718 if (!req || !blk_mq_request_started(req)) {
719 dev_err(disk_to_dev(nbd->disk), "Unexpected reply (%d) %p\n",
721 return ERR_PTR(-ENOENT);
723 trace_nbd_header_received(req, handle);
724 cmd = blk_mq_rq_to_pdu(req);
726 mutex_lock(&cmd->lock);
727 if (cmd->cmd_cookie != nbd_handle_to_cookie(handle)) {
728 dev_err(disk_to_dev(nbd->disk), "Double reply on req %p, cmd_cookie %u, handle cookie %u\n",
729 req, cmd->cmd_cookie, nbd_handle_to_cookie(handle));
733 if (cmd->status != BLK_STS_OK) {
734 dev_err(disk_to_dev(nbd->disk), "Command already handled %p\n",
739 if (test_bit(NBD_CMD_REQUEUED, &cmd->flags)) {
740 dev_err(disk_to_dev(nbd->disk), "Raced with timeout on req %p\n",
745 if (ntohl(reply.error)) {
746 dev_err(disk_to_dev(nbd->disk), "Other side returned error (%d)\n",
748 cmd->status = BLK_STS_IOERR;
752 dev_dbg(nbd_to_dev(nbd), "request %p: got reply\n", req);
753 if (rq_data_dir(req) != WRITE) {
754 struct req_iterator iter;
757 rq_for_each_segment(bvec, req, iter) {
758 iov_iter_bvec(&to, READ, &bvec, 1, bvec.bv_len);
759 result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
761 dev_err(disk_to_dev(nbd->disk), "Receive data failed (result %d)\n",
764 * If we've disconnected, we need to make sure we
765 * complete this request, otherwise error out
766 * and let the timeout stuff handle resubmitting
767 * this request onto another connection.
769 if (nbd_disconnected(config)) {
770 cmd->status = BLK_STS_IOERR;
776 dev_dbg(nbd_to_dev(nbd), "request %p: got %d bytes data\n",
781 trace_nbd_payload_received(req, handle);
782 mutex_unlock(&cmd->lock);
783 return ret ? ERR_PTR(ret) : cmd;
786 static void recv_work(struct work_struct *work)
788 struct recv_thread_args *args = container_of(work,
789 struct recv_thread_args,
791 struct nbd_device *nbd = args->nbd;
792 struct nbd_config *config = nbd->config;
797 cmd = nbd_read_stat(nbd, args->index);
799 struct nbd_sock *nsock = config->socks[args->index];
801 mutex_lock(&nsock->tx_lock);
802 nbd_mark_nsock_dead(nbd, nsock, 1);
803 mutex_unlock(&nsock->tx_lock);
807 rq = blk_mq_rq_from_pdu(cmd);
808 if (likely(!blk_should_fake_timeout(rq->q)))
809 blk_mq_complete_request(rq);
812 atomic_dec(&config->recv_threads);
813 wake_up(&config->recv_wq);
817 static bool nbd_clear_req(struct request *req, void *data, bool reserved)
819 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
821 mutex_lock(&cmd->lock);
822 cmd->status = BLK_STS_IOERR;
823 mutex_unlock(&cmd->lock);
825 blk_mq_complete_request(req);
829 static void nbd_clear_que(struct nbd_device *nbd)
831 blk_mq_quiesce_queue(nbd->disk->queue);
832 blk_mq_tagset_busy_iter(&nbd->tag_set, nbd_clear_req, NULL);
833 blk_mq_unquiesce_queue(nbd->disk->queue);
834 dev_dbg(disk_to_dev(nbd->disk), "queue cleared\n");
837 static int find_fallback(struct nbd_device *nbd, int index)
839 struct nbd_config *config = nbd->config;
841 struct nbd_sock *nsock = config->socks[index];
842 int fallback = nsock->fallback_index;
844 if (test_bit(NBD_RT_DISCONNECTED, &config->runtime_flags))
847 if (config->num_connections <= 1) {
848 dev_err_ratelimited(disk_to_dev(nbd->disk),
849 "Dead connection, failed to find a fallback\n");
853 if (fallback >= 0 && fallback < config->num_connections &&
854 !config->socks[fallback]->dead)
857 if (nsock->fallback_index < 0 ||
858 nsock->fallback_index >= config->num_connections ||
859 config->socks[nsock->fallback_index]->dead) {
861 for (i = 0; i < config->num_connections; i++) {
864 if (!config->socks[i]->dead) {
869 nsock->fallback_index = new_index;
871 dev_err_ratelimited(disk_to_dev(nbd->disk),
872 "Dead connection, failed to find a fallback\n");
876 new_index = nsock->fallback_index;
880 static int wait_for_reconnect(struct nbd_device *nbd)
882 struct nbd_config *config = nbd->config;
883 if (!config->dead_conn_timeout)
885 if (test_bit(NBD_RT_DISCONNECTED, &config->runtime_flags))
887 return wait_event_timeout(config->conn_wait,
888 atomic_read(&config->live_connections) > 0,
889 config->dead_conn_timeout) > 0;
892 static int nbd_handle_cmd(struct nbd_cmd *cmd, int index)
894 struct request *req = blk_mq_rq_from_pdu(cmd);
895 struct nbd_device *nbd = cmd->nbd;
896 struct nbd_config *config;
897 struct nbd_sock *nsock;
900 if (!refcount_inc_not_zero(&nbd->config_refs)) {
901 dev_err_ratelimited(disk_to_dev(nbd->disk),
902 "Socks array is empty\n");
903 blk_mq_start_request(req);
906 config = nbd->config;
908 if (index >= config->num_connections) {
909 dev_err_ratelimited(disk_to_dev(nbd->disk),
910 "Attempted send on invalid socket\n");
912 blk_mq_start_request(req);
915 cmd->status = BLK_STS_OK;
917 nsock = config->socks[index];
918 mutex_lock(&nsock->tx_lock);
920 int old_index = index;
921 index = find_fallback(nbd, index);
922 mutex_unlock(&nsock->tx_lock);
924 if (wait_for_reconnect(nbd)) {
928 /* All the sockets should already be down at this point,
929 * we just want to make sure that DISCONNECTED is set so
930 * any requests that come in that were queue'ed waiting
931 * for the reconnect timer don't trigger the timer again
932 * and instead just error out.
936 blk_mq_start_request(req);
942 /* Handle the case that we have a pending request that was partially
943 * transmitted that _has_ to be serviced first. We need to call requeue
944 * here so that it gets put _after_ the request that is already on the
947 blk_mq_start_request(req);
948 if (unlikely(nsock->pending && nsock->pending != req)) {
949 nbd_requeue_cmd(cmd);
954 * Some failures are related to the link going down, so anything that
955 * returns EAGAIN can be retried on a different socket.
957 ret = nbd_send_cmd(nbd, cmd, index);
958 if (ret == -EAGAIN) {
959 dev_err_ratelimited(disk_to_dev(nbd->disk),
960 "Request send failed, requeueing\n");
961 nbd_mark_nsock_dead(nbd, nsock, 1);
962 nbd_requeue_cmd(cmd);
966 mutex_unlock(&nsock->tx_lock);
971 static blk_status_t nbd_queue_rq(struct blk_mq_hw_ctx *hctx,
972 const struct blk_mq_queue_data *bd)
974 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(bd->rq);
978 * Since we look at the bio's to send the request over the network we
979 * need to make sure the completion work doesn't mark this request done
980 * before we are done doing our send. This keeps us from dereferencing
981 * freed data if we have particularly fast completions (ie we get the
982 * completion before we exit sock_xmit on the last bvec) or in the case
983 * that the server is misbehaving (or there was an error) before we're
984 * done sending everything over the wire.
986 mutex_lock(&cmd->lock);
987 clear_bit(NBD_CMD_REQUEUED, &cmd->flags);
989 /* We can be called directly from the user space process, which means we
990 * could possibly have signals pending so our sendmsg will fail. In
991 * this case we need to return that we are busy, otherwise error out as
994 ret = nbd_handle_cmd(cmd, hctx->queue_num);
999 mutex_unlock(&cmd->lock);
1004 static struct socket *nbd_get_socket(struct nbd_device *nbd, unsigned long fd,
1007 struct socket *sock;
1010 sock = sockfd_lookup(fd, err);
1014 if (sock->ops->shutdown == sock_no_shutdown) {
1015 dev_err(disk_to_dev(nbd->disk), "Unsupported socket: shutdown callout must be supported.\n");
1024 static int nbd_add_socket(struct nbd_device *nbd, unsigned long arg,
1027 struct nbd_config *config = nbd->config;
1028 struct socket *sock;
1029 struct nbd_sock **socks;
1030 struct nbd_sock *nsock;
1033 sock = nbd_get_socket(nbd, arg, &err);
1038 * We need to make sure we don't get any errant requests while we're
1039 * reallocating the ->socks array.
1041 blk_mq_freeze_queue(nbd->disk->queue);
1043 if (!netlink && !nbd->task_setup &&
1044 !test_bit(NBD_RT_BOUND, &config->runtime_flags))
1045 nbd->task_setup = current;
1048 (nbd->task_setup != current ||
1049 test_bit(NBD_RT_BOUND, &config->runtime_flags))) {
1050 dev_err(disk_to_dev(nbd->disk),
1051 "Device being setup by another task");
1056 nsock = kzalloc(sizeof(*nsock), GFP_KERNEL);
1062 socks = krealloc(config->socks, (config->num_connections + 1) *
1063 sizeof(struct nbd_sock *), GFP_KERNEL);
1070 config->socks = socks;
1072 nsock->fallback_index = -1;
1073 nsock->dead = false;
1074 mutex_init(&nsock->tx_lock);
1076 nsock->pending = NULL;
1079 socks[config->num_connections++] = nsock;
1080 atomic_inc(&config->live_connections);
1081 blk_mq_unfreeze_queue(nbd->disk->queue);
1086 blk_mq_unfreeze_queue(nbd->disk->queue);
1091 static int nbd_reconnect_socket(struct nbd_device *nbd, unsigned long arg)
1093 struct nbd_config *config = nbd->config;
1094 struct socket *sock, *old;
1095 struct recv_thread_args *args;
1099 sock = nbd_get_socket(nbd, arg, &err);
1103 args = kzalloc(sizeof(*args), GFP_KERNEL);
1109 for (i = 0; i < config->num_connections; i++) {
1110 struct nbd_sock *nsock = config->socks[i];
1115 mutex_lock(&nsock->tx_lock);
1117 mutex_unlock(&nsock->tx_lock);
1120 sk_set_memalloc(sock->sk);
1121 if (nbd->tag_set.timeout)
1122 sock->sk->sk_sndtimeo = nbd->tag_set.timeout;
1123 atomic_inc(&config->recv_threads);
1124 refcount_inc(&nbd->config_refs);
1126 nsock->fallback_index = -1;
1128 nsock->dead = false;
1129 INIT_WORK(&args->work, recv_work);
1133 mutex_unlock(&nsock->tx_lock);
1136 clear_bit(NBD_RT_DISCONNECTED, &config->runtime_flags);
1138 /* We take the tx_mutex in an error path in the recv_work, so we
1139 * need to queue_work outside of the tx_mutex.
1141 queue_work(nbd->recv_workq, &args->work);
1143 atomic_inc(&config->live_connections);
1144 wake_up(&config->conn_wait);
1152 static void nbd_bdev_reset(struct block_device *bdev)
1154 if (bdev->bd_openers > 1)
1156 set_capacity(bdev->bd_disk, 0);
1159 static void nbd_parse_flags(struct nbd_device *nbd)
1161 struct nbd_config *config = nbd->config;
1162 if (config->flags & NBD_FLAG_READ_ONLY)
1163 set_disk_ro(nbd->disk, true);
1165 set_disk_ro(nbd->disk, false);
1166 if (config->flags & NBD_FLAG_SEND_TRIM)
1167 blk_queue_flag_set(QUEUE_FLAG_DISCARD, nbd->disk->queue);
1168 if (config->flags & NBD_FLAG_SEND_FLUSH) {
1169 if (config->flags & NBD_FLAG_SEND_FUA)
1170 blk_queue_write_cache(nbd->disk->queue, true, true);
1172 blk_queue_write_cache(nbd->disk->queue, true, false);
1175 blk_queue_write_cache(nbd->disk->queue, false, false);
1178 static void send_disconnects(struct nbd_device *nbd)
1180 struct nbd_config *config = nbd->config;
1181 struct nbd_request request = {
1182 .magic = htonl(NBD_REQUEST_MAGIC),
1183 .type = htonl(NBD_CMD_DISC),
1185 struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
1186 struct iov_iter from;
1189 for (i = 0; i < config->num_connections; i++) {
1190 struct nbd_sock *nsock = config->socks[i];
1192 iov_iter_kvec(&from, WRITE, &iov, 1, sizeof(request));
1193 mutex_lock(&nsock->tx_lock);
1194 ret = sock_xmit(nbd, i, 1, &from, 0, NULL);
1196 dev_err(disk_to_dev(nbd->disk),
1197 "Send disconnect failed %d\n", ret);
1198 mutex_unlock(&nsock->tx_lock);
1202 static int nbd_disconnect(struct nbd_device *nbd)
1204 struct nbd_config *config = nbd->config;
1206 dev_info(disk_to_dev(nbd->disk), "NBD_DISCONNECT\n");
1207 set_bit(NBD_RT_DISCONNECT_REQUESTED, &config->runtime_flags);
1208 set_bit(NBD_DISCONNECT_REQUESTED, &nbd->flags);
1209 send_disconnects(nbd);
1213 static void nbd_clear_sock(struct nbd_device *nbd)
1217 nbd->task_setup = NULL;
1220 static void nbd_config_put(struct nbd_device *nbd)
1222 if (refcount_dec_and_mutex_lock(&nbd->config_refs,
1223 &nbd->config_lock)) {
1224 struct nbd_config *config = nbd->config;
1225 nbd_dev_dbg_close(nbd);
1226 nbd_size_clear(nbd);
1227 if (test_and_clear_bit(NBD_RT_HAS_PID_FILE,
1228 &config->runtime_flags))
1229 device_remove_file(disk_to_dev(nbd->disk), &pid_attr);
1230 nbd->task_recv = NULL;
1231 if (test_and_clear_bit(NBD_RT_HAS_BACKEND_FILE,
1232 &config->runtime_flags)) {
1233 device_remove_file(disk_to_dev(nbd->disk), &backend_attr);
1234 kfree(nbd->backend);
1235 nbd->backend = NULL;
1237 nbd_clear_sock(nbd);
1238 if (config->num_connections) {
1240 for (i = 0; i < config->num_connections; i++) {
1241 sockfd_put(config->socks[i]->sock);
1242 kfree(config->socks[i]);
1244 kfree(config->socks);
1249 if (nbd->recv_workq)
1250 destroy_workqueue(nbd->recv_workq);
1251 nbd->recv_workq = NULL;
1253 nbd->tag_set.timeout = 0;
1254 nbd->disk->queue->limits.discard_granularity = 0;
1255 nbd->disk->queue->limits.discard_alignment = 0;
1256 blk_queue_max_discard_sectors(nbd->disk->queue, UINT_MAX);
1257 blk_queue_flag_clear(QUEUE_FLAG_DISCARD, nbd->disk->queue);
1259 mutex_unlock(&nbd->config_lock);
1261 module_put(THIS_MODULE);
1265 static int nbd_start_device(struct nbd_device *nbd)
1267 struct nbd_config *config = nbd->config;
1268 int num_connections = config->num_connections;
1275 if (num_connections > 1 &&
1276 !(config->flags & NBD_FLAG_CAN_MULTI_CONN)) {
1277 dev_err(disk_to_dev(nbd->disk), "server does not support multiple connections per device.\n");
1281 nbd->recv_workq = alloc_workqueue("knbd%d-recv",
1282 WQ_MEM_RECLAIM | WQ_HIGHPRI |
1283 WQ_UNBOUND, 0, nbd->index);
1284 if (!nbd->recv_workq) {
1285 dev_err(disk_to_dev(nbd->disk), "Could not allocate knbd recv work queue.\n");
1289 blk_mq_update_nr_hw_queues(&nbd->tag_set, config->num_connections);
1290 nbd->task_recv = current;
1292 nbd_parse_flags(nbd);
1294 error = device_create_file(disk_to_dev(nbd->disk), &pid_attr);
1296 dev_err(disk_to_dev(nbd->disk), "device_create_file failed for pid!\n");
1299 set_bit(NBD_RT_HAS_PID_FILE, &config->runtime_flags);
1301 nbd_dev_dbg_init(nbd);
1302 for (i = 0; i < num_connections; i++) {
1303 struct recv_thread_args *args;
1305 args = kzalloc(sizeof(*args), GFP_KERNEL);
1309 * If num_connections is m (2 < m),
1310 * and NO.1 ~ NO.n(1 < n < m) kzallocs are successful.
1311 * But NO.(n + 1) failed. We still have n recv threads.
1312 * So, add flush_workqueue here to prevent recv threads
1313 * dropping the last config_refs and trying to destroy
1314 * the workqueue from inside the workqueue.
1317 flush_workqueue(nbd->recv_workq);
1320 sk_set_memalloc(config->socks[i]->sock->sk);
1321 if (nbd->tag_set.timeout)
1322 config->socks[i]->sock->sk->sk_sndtimeo =
1323 nbd->tag_set.timeout;
1324 atomic_inc(&config->recv_threads);
1325 refcount_inc(&nbd->config_refs);
1326 INIT_WORK(&args->work, recv_work);
1329 queue_work(nbd->recv_workq, &args->work);
1331 return nbd_set_size(nbd, config->bytesize, config->blksize);
1334 static int nbd_start_device_ioctl(struct nbd_device *nbd, struct block_device *bdev)
1336 struct nbd_config *config = nbd->config;
1339 ret = nbd_start_device(nbd);
1344 set_bit(GD_NEED_PART_SCAN, &nbd->disk->state);
1345 mutex_unlock(&nbd->config_lock);
1346 ret = wait_event_interruptible(config->recv_wq,
1347 atomic_read(&config->recv_threads) == 0);
1350 flush_workqueue(nbd->recv_workq);
1352 mutex_lock(&nbd->config_lock);
1353 nbd_bdev_reset(bdev);
1354 /* user requested, ignore socket errors */
1355 if (test_bit(NBD_RT_DISCONNECT_REQUESTED, &config->runtime_flags))
1357 if (test_bit(NBD_RT_TIMEDOUT, &config->runtime_flags))
1362 static void nbd_clear_sock_ioctl(struct nbd_device *nbd,
1363 struct block_device *bdev)
1366 __invalidate_device(bdev, true);
1367 nbd_bdev_reset(bdev);
1368 if (test_and_clear_bit(NBD_RT_HAS_CONFIG_REF,
1369 &nbd->config->runtime_flags))
1370 nbd_config_put(nbd);
1373 static void nbd_set_cmd_timeout(struct nbd_device *nbd, u64 timeout)
1375 nbd->tag_set.timeout = timeout * HZ;
1377 blk_queue_rq_timeout(nbd->disk->queue, timeout * HZ);
1379 blk_queue_rq_timeout(nbd->disk->queue, 30 * HZ);
1382 /* Must be called with config_lock held */
1383 static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
1384 unsigned int cmd, unsigned long arg)
1386 struct nbd_config *config = nbd->config;
1389 case NBD_DISCONNECT:
1390 return nbd_disconnect(nbd);
1391 case NBD_CLEAR_SOCK:
1392 nbd_clear_sock_ioctl(nbd, bdev);
1395 return nbd_add_socket(nbd, arg, false);
1396 case NBD_SET_BLKSIZE:
1397 return nbd_set_size(nbd, config->bytesize, arg);
1399 return nbd_set_size(nbd, arg, config->blksize);
1400 case NBD_SET_SIZE_BLOCKS:
1401 return nbd_set_size(nbd, arg * config->blksize,
1403 case NBD_SET_TIMEOUT:
1404 nbd_set_cmd_timeout(nbd, arg);
1408 config->flags = arg;
1411 return nbd_start_device_ioctl(nbd, bdev);
1414 * This is for compatibility only. The queue is always cleared
1415 * by NBD_DO_IT or NBD_CLEAR_SOCK.
1418 case NBD_PRINT_DEBUG:
1420 * For compatibility only, we no longer keep a list of
1421 * outstanding requests.
1428 static int nbd_ioctl(struct block_device *bdev, fmode_t mode,
1429 unsigned int cmd, unsigned long arg)
1431 struct nbd_device *nbd = bdev->bd_disk->private_data;
1432 struct nbd_config *config = nbd->config;
1433 int error = -EINVAL;
1435 if (!capable(CAP_SYS_ADMIN))
1438 /* The block layer will pass back some non-nbd ioctls in case we have
1439 * special handling for them, but we don't so just return an error.
1441 if (_IOC_TYPE(cmd) != 0xab)
1444 mutex_lock(&nbd->config_lock);
1446 /* Don't allow ioctl operations on a nbd device that was created with
1447 * netlink, unless it's DISCONNECT or CLEAR_SOCK, which are fine.
1449 if (!test_bit(NBD_RT_BOUND, &config->runtime_flags) ||
1450 (cmd == NBD_DISCONNECT || cmd == NBD_CLEAR_SOCK))
1451 error = __nbd_ioctl(bdev, nbd, cmd, arg);
1453 dev_err(nbd_to_dev(nbd), "Cannot use ioctl interface on a netlink controlled device.\n");
1454 mutex_unlock(&nbd->config_lock);
1458 static struct nbd_config *nbd_alloc_config(void)
1460 struct nbd_config *config;
1462 config = kzalloc(sizeof(struct nbd_config), GFP_NOFS);
1465 atomic_set(&config->recv_threads, 0);
1466 init_waitqueue_head(&config->recv_wq);
1467 init_waitqueue_head(&config->conn_wait);
1468 config->blksize = NBD_DEF_BLKSIZE;
1469 atomic_set(&config->live_connections, 0);
1470 try_module_get(THIS_MODULE);
1474 static int nbd_open(struct block_device *bdev, fmode_t mode)
1476 struct nbd_device *nbd;
1479 mutex_lock(&nbd_index_mutex);
1480 nbd = bdev->bd_disk->private_data;
1485 if (!refcount_inc_not_zero(&nbd->refs)) {
1489 if (!refcount_inc_not_zero(&nbd->config_refs)) {
1490 struct nbd_config *config;
1492 mutex_lock(&nbd->config_lock);
1493 if (refcount_inc_not_zero(&nbd->config_refs)) {
1494 mutex_unlock(&nbd->config_lock);
1497 config = nbd->config = nbd_alloc_config();
1500 mutex_unlock(&nbd->config_lock);
1503 refcount_set(&nbd->config_refs, 1);
1504 refcount_inc(&nbd->refs);
1505 mutex_unlock(&nbd->config_lock);
1507 set_bit(GD_NEED_PART_SCAN, &bdev->bd_disk->state);
1508 } else if (nbd_disconnected(nbd->config)) {
1510 set_bit(GD_NEED_PART_SCAN, &bdev->bd_disk->state);
1513 mutex_unlock(&nbd_index_mutex);
1517 static void nbd_release(struct gendisk *disk, fmode_t mode)
1519 struct nbd_device *nbd = disk->private_data;
1521 if (test_bit(NBD_RT_DISCONNECT_ON_CLOSE, &nbd->config->runtime_flags) &&
1522 disk->part0->bd_openers == 0)
1523 nbd_disconnect_and_put(nbd);
1525 nbd_config_put(nbd);
1529 static const struct block_device_operations nbd_fops =
1531 .owner = THIS_MODULE,
1533 .release = nbd_release,
1535 .compat_ioctl = nbd_ioctl,
1538 #if IS_ENABLED(CONFIG_DEBUG_FS)
1540 static int nbd_dbg_tasks_show(struct seq_file *s, void *unused)
1542 struct nbd_device *nbd = s->private;
1545 seq_printf(s, "recv: %d\n", task_pid_nr(nbd->task_recv));
1550 DEFINE_SHOW_ATTRIBUTE(nbd_dbg_tasks);
1552 static int nbd_dbg_flags_show(struct seq_file *s, void *unused)
1554 struct nbd_device *nbd = s->private;
1555 u32 flags = nbd->config->flags;
1557 seq_printf(s, "Hex: 0x%08x\n\n", flags);
1559 seq_puts(s, "Known flags:\n");
1561 if (flags & NBD_FLAG_HAS_FLAGS)
1562 seq_puts(s, "NBD_FLAG_HAS_FLAGS\n");
1563 if (flags & NBD_FLAG_READ_ONLY)
1564 seq_puts(s, "NBD_FLAG_READ_ONLY\n");
1565 if (flags & NBD_FLAG_SEND_FLUSH)
1566 seq_puts(s, "NBD_FLAG_SEND_FLUSH\n");
1567 if (flags & NBD_FLAG_SEND_FUA)
1568 seq_puts(s, "NBD_FLAG_SEND_FUA\n");
1569 if (flags & NBD_FLAG_SEND_TRIM)
1570 seq_puts(s, "NBD_FLAG_SEND_TRIM\n");
1575 DEFINE_SHOW_ATTRIBUTE(nbd_dbg_flags);
1577 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1580 struct nbd_config *config = nbd->config;
1585 dir = debugfs_create_dir(nbd_name(nbd), nbd_dbg_dir);
1587 dev_err(nbd_to_dev(nbd), "Failed to create debugfs dir for '%s'\n",
1591 config->dbg_dir = dir;
1593 debugfs_create_file("tasks", 0444, dir, nbd, &nbd_dbg_tasks_fops);
1594 debugfs_create_u64("size_bytes", 0444, dir, &config->bytesize);
1595 debugfs_create_u32("timeout", 0444, dir, &nbd->tag_set.timeout);
1596 debugfs_create_u64("blocksize", 0444, dir, &config->blksize);
1597 debugfs_create_file("flags", 0444, dir, nbd, &nbd_dbg_flags_fops);
1602 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1604 debugfs_remove_recursive(nbd->config->dbg_dir);
1607 static int nbd_dbg_init(void)
1609 struct dentry *dbg_dir;
1611 dbg_dir = debugfs_create_dir("nbd", NULL);
1615 nbd_dbg_dir = dbg_dir;
1620 static void nbd_dbg_close(void)
1622 debugfs_remove_recursive(nbd_dbg_dir);
1625 #else /* IS_ENABLED(CONFIG_DEBUG_FS) */
1627 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1632 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1636 static int nbd_dbg_init(void)
1641 static void nbd_dbg_close(void)
1647 static int nbd_init_request(struct blk_mq_tag_set *set, struct request *rq,
1648 unsigned int hctx_idx, unsigned int numa_node)
1650 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(rq);
1651 cmd->nbd = set->driver_data;
1653 mutex_init(&cmd->lock);
1657 static const struct blk_mq_ops nbd_mq_ops = {
1658 .queue_rq = nbd_queue_rq,
1659 .complete = nbd_complete_rq,
1660 .init_request = nbd_init_request,
1661 .timeout = nbd_xmit_timeout,
1664 static int nbd_dev_add(int index)
1666 struct nbd_device *nbd;
1667 struct gendisk *disk;
1670 nbd = kzalloc(sizeof(struct nbd_device), GFP_KERNEL);
1674 nbd->tag_set.ops = &nbd_mq_ops;
1675 nbd->tag_set.nr_hw_queues = 1;
1676 nbd->tag_set.queue_depth = 128;
1677 nbd->tag_set.numa_node = NUMA_NO_NODE;
1678 nbd->tag_set.cmd_size = sizeof(struct nbd_cmd);
1679 nbd->tag_set.flags = BLK_MQ_F_SHOULD_MERGE |
1681 nbd->tag_set.driver_data = nbd;
1682 nbd->destroy_complete = NULL;
1683 nbd->backend = NULL;
1685 err = blk_mq_alloc_tag_set(&nbd->tag_set);
1690 err = idr_alloc(&nbd_index_idr, nbd, index, index + 1,
1695 err = idr_alloc(&nbd_index_idr, nbd, 0, 0, GFP_KERNEL);
1703 disk = blk_mq_alloc_disk(&nbd->tag_set, NULL);
1705 err = PTR_ERR(disk);
1711 * Tell the block layer that we are not a rotational device
1713 blk_queue_flag_set(QUEUE_FLAG_NONROT, disk->queue);
1714 blk_queue_flag_clear(QUEUE_FLAG_ADD_RANDOM, disk->queue);
1715 disk->queue->limits.discard_granularity = 0;
1716 disk->queue->limits.discard_alignment = 0;
1717 blk_queue_max_discard_sectors(disk->queue, 0);
1718 blk_queue_max_segment_size(disk->queue, UINT_MAX);
1719 blk_queue_max_segments(disk->queue, USHRT_MAX);
1720 blk_queue_max_hw_sectors(disk->queue, 65536);
1721 disk->queue->limits.max_sectors = 256;
1723 mutex_init(&nbd->config_lock);
1724 refcount_set(&nbd->config_refs, 0);
1725 refcount_set(&nbd->refs, 1);
1726 INIT_LIST_HEAD(&nbd->list);
1727 disk->major = NBD_MAJOR;
1728 disk->first_minor = index << part_shift;
1729 disk->minors = 1 << part_shift;
1730 disk->fops = &nbd_fops;
1731 disk->private_data = nbd;
1732 sprintf(disk->disk_name, "nbd%d", index);
1734 nbd_total_devices++;
1738 idr_remove(&nbd_index_idr, index);
1740 blk_mq_free_tag_set(&nbd->tag_set);
1747 static int find_free_cb(int id, void *ptr, void *data)
1749 struct nbd_device *nbd = ptr;
1750 struct nbd_device **found = data;
1752 if (!refcount_read(&nbd->config_refs)) {
1759 /* Netlink interface. */
1760 static const struct nla_policy nbd_attr_policy[NBD_ATTR_MAX + 1] = {
1761 [NBD_ATTR_INDEX] = { .type = NLA_U32 },
1762 [NBD_ATTR_SIZE_BYTES] = { .type = NLA_U64 },
1763 [NBD_ATTR_BLOCK_SIZE_BYTES] = { .type = NLA_U64 },
1764 [NBD_ATTR_TIMEOUT] = { .type = NLA_U64 },
1765 [NBD_ATTR_SERVER_FLAGS] = { .type = NLA_U64 },
1766 [NBD_ATTR_CLIENT_FLAGS] = { .type = NLA_U64 },
1767 [NBD_ATTR_SOCKETS] = { .type = NLA_NESTED},
1768 [NBD_ATTR_DEAD_CONN_TIMEOUT] = { .type = NLA_U64 },
1769 [NBD_ATTR_DEVICE_LIST] = { .type = NLA_NESTED},
1770 [NBD_ATTR_BACKEND_IDENTIFIER] = { .type = NLA_STRING},
1773 static const struct nla_policy nbd_sock_policy[NBD_SOCK_MAX + 1] = {
1774 [NBD_SOCK_FD] = { .type = NLA_U32 },
1777 /* We don't use this right now since we don't parse the incoming list, but we
1778 * still want it here so userspace knows what to expect.
1780 static const struct nla_policy __attribute__((unused))
1781 nbd_device_policy[NBD_DEVICE_ATTR_MAX + 1] = {
1782 [NBD_DEVICE_INDEX] = { .type = NLA_U32 },
1783 [NBD_DEVICE_CONNECTED] = { .type = NLA_U8 },
1786 static int nbd_genl_size_set(struct genl_info *info, struct nbd_device *nbd)
1788 struct nbd_config *config = nbd->config;
1789 u64 bsize = config->blksize;
1790 u64 bytes = config->bytesize;
1792 if (info->attrs[NBD_ATTR_SIZE_BYTES])
1793 bytes = nla_get_u64(info->attrs[NBD_ATTR_SIZE_BYTES]);
1795 if (info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES])
1796 bsize = nla_get_u64(info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]);
1798 if (bytes != config->bytesize || bsize != config->blksize)
1799 return nbd_set_size(nbd, bytes, bsize);
1803 static int nbd_genl_connect(struct sk_buff *skb, struct genl_info *info)
1805 DECLARE_COMPLETION_ONSTACK(destroy_complete);
1806 struct nbd_device *nbd = NULL;
1807 struct nbd_config *config;
1810 bool put_dev = false;
1812 if (!netlink_capable(skb, CAP_SYS_ADMIN))
1815 if (info->attrs[NBD_ATTR_INDEX])
1816 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1817 if (!info->attrs[NBD_ATTR_SOCKETS]) {
1818 printk(KERN_ERR "nbd: must specify at least one socket\n");
1821 if (!info->attrs[NBD_ATTR_SIZE_BYTES]) {
1822 printk(KERN_ERR "nbd: must specify a size in bytes for the device\n");
1826 mutex_lock(&nbd_index_mutex);
1828 ret = idr_for_each(&nbd_index_idr, &find_free_cb, &nbd);
1831 new_index = nbd_dev_add(-1);
1832 if (new_index < 0) {
1833 mutex_unlock(&nbd_index_mutex);
1834 printk(KERN_ERR "nbd: failed to add new device\n");
1837 nbd = idr_find(&nbd_index_idr, new_index);
1840 nbd = idr_find(&nbd_index_idr, index);
1842 ret = nbd_dev_add(index);
1844 mutex_unlock(&nbd_index_mutex);
1845 printk(KERN_ERR "nbd: failed to add new device\n");
1848 nbd = idr_find(&nbd_index_idr, index);
1852 printk(KERN_ERR "nbd: couldn't find device at index %d\n",
1854 mutex_unlock(&nbd_index_mutex);
1858 if (test_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags) &&
1859 test_bit(NBD_DISCONNECT_REQUESTED, &nbd->flags)) {
1860 nbd->destroy_complete = &destroy_complete;
1861 mutex_unlock(&nbd_index_mutex);
1863 /* Wait untill the the nbd stuff is totally destroyed */
1864 wait_for_completion(&destroy_complete);
1868 if (!refcount_inc_not_zero(&nbd->refs)) {
1869 mutex_unlock(&nbd_index_mutex);
1872 printk(KERN_ERR "nbd: device at index %d is going down\n",
1876 mutex_unlock(&nbd_index_mutex);
1878 mutex_lock(&nbd->config_lock);
1879 if (refcount_read(&nbd->config_refs)) {
1880 mutex_unlock(&nbd->config_lock);
1884 printk(KERN_ERR "nbd: nbd%d already in use\n", index);
1887 if (WARN_ON(nbd->config)) {
1888 mutex_unlock(&nbd->config_lock);
1892 config = nbd->config = nbd_alloc_config();
1894 mutex_unlock(&nbd->config_lock);
1896 printk(KERN_ERR "nbd: couldn't allocate config\n");
1899 refcount_set(&nbd->config_refs, 1);
1900 set_bit(NBD_RT_BOUND, &config->runtime_flags);
1902 ret = nbd_genl_size_set(info, nbd);
1906 if (info->attrs[NBD_ATTR_TIMEOUT])
1907 nbd_set_cmd_timeout(nbd,
1908 nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]));
1909 if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
1910 config->dead_conn_timeout =
1911 nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
1912 config->dead_conn_timeout *= HZ;
1914 if (info->attrs[NBD_ATTR_SERVER_FLAGS])
1916 nla_get_u64(info->attrs[NBD_ATTR_SERVER_FLAGS]);
1917 if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
1918 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
1919 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
1921 * We have 1 ref to keep the device around, and then 1
1922 * ref for our current operation here, which will be
1923 * inherited by the config. If we already have
1924 * DESTROY_ON_DISCONNECT set then we know we don't have
1925 * that extra ref already held so we don't need the
1928 if (!test_and_set_bit(NBD_DESTROY_ON_DISCONNECT,
1932 if (test_and_clear_bit(NBD_DESTROY_ON_DISCONNECT,
1934 refcount_inc(&nbd->refs);
1936 if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
1937 set_bit(NBD_RT_DISCONNECT_ON_CLOSE,
1938 &config->runtime_flags);
1942 if (info->attrs[NBD_ATTR_SOCKETS]) {
1943 struct nlattr *attr;
1946 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
1948 struct nlattr *socks[NBD_SOCK_MAX+1];
1950 if (nla_type(attr) != NBD_SOCK_ITEM) {
1951 printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
1955 ret = nla_parse_nested_deprecated(socks, NBD_SOCK_MAX,
1960 printk(KERN_ERR "nbd: error processing sock list\n");
1964 if (!socks[NBD_SOCK_FD])
1966 fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
1967 ret = nbd_add_socket(nbd, fd, true);
1972 ret = nbd_start_device(nbd);
1975 if (info->attrs[NBD_ATTR_BACKEND_IDENTIFIER]) {
1976 nbd->backend = nla_strdup(info->attrs[NBD_ATTR_BACKEND_IDENTIFIER],
1978 if (!nbd->backend) {
1983 ret = device_create_file(disk_to_dev(nbd->disk), &backend_attr);
1985 dev_err(disk_to_dev(nbd->disk),
1986 "device_create_file failed for backend!\n");
1989 set_bit(NBD_RT_HAS_BACKEND_FILE, &config->runtime_flags);
1991 mutex_unlock(&nbd->config_lock);
1993 set_bit(NBD_RT_HAS_CONFIG_REF, &config->runtime_flags);
1994 refcount_inc(&nbd->config_refs);
1995 nbd_connect_reply(info, nbd->index);
1997 nbd_config_put(nbd);
2003 static void nbd_disconnect_and_put(struct nbd_device *nbd)
2005 mutex_lock(&nbd->config_lock);
2006 nbd_disconnect(nbd);
2007 nbd_clear_sock(nbd);
2008 mutex_unlock(&nbd->config_lock);
2010 * Make sure recv thread has finished, so it does not drop the last
2011 * config ref and try to destroy the workqueue from inside the work
2014 if (nbd->recv_workq)
2015 flush_workqueue(nbd->recv_workq);
2016 if (test_and_clear_bit(NBD_RT_HAS_CONFIG_REF,
2017 &nbd->config->runtime_flags))
2018 nbd_config_put(nbd);
2021 static int nbd_genl_disconnect(struct sk_buff *skb, struct genl_info *info)
2023 struct nbd_device *nbd;
2026 if (!netlink_capable(skb, CAP_SYS_ADMIN))
2029 if (!info->attrs[NBD_ATTR_INDEX]) {
2030 printk(KERN_ERR "nbd: must specify an index to disconnect\n");
2033 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2034 mutex_lock(&nbd_index_mutex);
2035 nbd = idr_find(&nbd_index_idr, index);
2037 mutex_unlock(&nbd_index_mutex);
2038 printk(KERN_ERR "nbd: couldn't find device at index %d\n",
2042 if (!refcount_inc_not_zero(&nbd->refs)) {
2043 mutex_unlock(&nbd_index_mutex);
2044 printk(KERN_ERR "nbd: device at index %d is going down\n",
2048 mutex_unlock(&nbd_index_mutex);
2049 if (!refcount_inc_not_zero(&nbd->config_refs))
2051 nbd_disconnect_and_put(nbd);
2052 nbd_config_put(nbd);
2058 static int nbd_genl_reconfigure(struct sk_buff *skb, struct genl_info *info)
2060 struct nbd_device *nbd = NULL;
2061 struct nbd_config *config;
2064 bool put_dev = false;
2066 if (!netlink_capable(skb, CAP_SYS_ADMIN))
2069 if (!info->attrs[NBD_ATTR_INDEX]) {
2070 printk(KERN_ERR "nbd: must specify a device to reconfigure\n");
2073 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2074 mutex_lock(&nbd_index_mutex);
2075 nbd = idr_find(&nbd_index_idr, index);
2077 mutex_unlock(&nbd_index_mutex);
2078 printk(KERN_ERR "nbd: couldn't find a device at index %d\n",
2083 if (info->attrs[NBD_ATTR_BACKEND_IDENTIFIER]) {
2084 if (nla_strcmp(info->attrs[NBD_ATTR_BACKEND_IDENTIFIER],
2086 mutex_unlock(&nbd_index_mutex);
2087 dev_err(nbd_to_dev(nbd),
2088 "backend image doesn't match with %s\n",
2093 mutex_unlock(&nbd_index_mutex);
2094 dev_err(nbd_to_dev(nbd), "must specify backend\n");
2098 if (!refcount_inc_not_zero(&nbd->refs)) {
2099 mutex_unlock(&nbd_index_mutex);
2100 printk(KERN_ERR "nbd: device at index %d is going down\n",
2104 mutex_unlock(&nbd_index_mutex);
2106 if (!refcount_inc_not_zero(&nbd->config_refs)) {
2107 dev_err(nbd_to_dev(nbd),
2108 "not configured, cannot reconfigure\n");
2113 mutex_lock(&nbd->config_lock);
2114 config = nbd->config;
2115 if (!test_bit(NBD_RT_BOUND, &config->runtime_flags) ||
2117 dev_err(nbd_to_dev(nbd),
2118 "not configured, cannot reconfigure\n");
2123 ret = nbd_genl_size_set(info, nbd);
2127 if (info->attrs[NBD_ATTR_TIMEOUT])
2128 nbd_set_cmd_timeout(nbd,
2129 nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]));
2130 if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
2131 config->dead_conn_timeout =
2132 nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
2133 config->dead_conn_timeout *= HZ;
2135 if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
2136 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
2137 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
2138 if (!test_and_set_bit(NBD_DESTROY_ON_DISCONNECT,
2142 if (test_and_clear_bit(NBD_DESTROY_ON_DISCONNECT,
2144 refcount_inc(&nbd->refs);
2147 if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
2148 set_bit(NBD_RT_DISCONNECT_ON_CLOSE,
2149 &config->runtime_flags);
2151 clear_bit(NBD_RT_DISCONNECT_ON_CLOSE,
2152 &config->runtime_flags);
2156 if (info->attrs[NBD_ATTR_SOCKETS]) {
2157 struct nlattr *attr;
2160 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
2162 struct nlattr *socks[NBD_SOCK_MAX+1];
2164 if (nla_type(attr) != NBD_SOCK_ITEM) {
2165 printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
2169 ret = nla_parse_nested_deprecated(socks, NBD_SOCK_MAX,
2174 printk(KERN_ERR "nbd: error processing sock list\n");
2178 if (!socks[NBD_SOCK_FD])
2180 fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
2181 ret = nbd_reconnect_socket(nbd, fd);
2187 dev_info(nbd_to_dev(nbd), "reconnected socket\n");
2191 mutex_unlock(&nbd->config_lock);
2192 nbd_config_put(nbd);
2199 static const struct genl_small_ops nbd_connect_genl_ops[] = {
2201 .cmd = NBD_CMD_CONNECT,
2202 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2203 .doit = nbd_genl_connect,
2206 .cmd = NBD_CMD_DISCONNECT,
2207 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2208 .doit = nbd_genl_disconnect,
2211 .cmd = NBD_CMD_RECONFIGURE,
2212 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2213 .doit = nbd_genl_reconfigure,
2216 .cmd = NBD_CMD_STATUS,
2217 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2218 .doit = nbd_genl_status,
2222 static const struct genl_multicast_group nbd_mcast_grps[] = {
2223 { .name = NBD_GENL_MCAST_GROUP_NAME, },
2226 static struct genl_family nbd_genl_family __ro_after_init = {
2228 .name = NBD_GENL_FAMILY_NAME,
2229 .version = NBD_GENL_VERSION,
2230 .module = THIS_MODULE,
2231 .small_ops = nbd_connect_genl_ops,
2232 .n_small_ops = ARRAY_SIZE(nbd_connect_genl_ops),
2233 .maxattr = NBD_ATTR_MAX,
2234 .policy = nbd_attr_policy,
2235 .mcgrps = nbd_mcast_grps,
2236 .n_mcgrps = ARRAY_SIZE(nbd_mcast_grps),
2239 static int populate_nbd_status(struct nbd_device *nbd, struct sk_buff *reply)
2241 struct nlattr *dev_opt;
2245 /* This is a little racey, but for status it's ok. The
2246 * reason we don't take a ref here is because we can't
2247 * take a ref in the index == -1 case as we would need
2248 * to put under the nbd_index_mutex, which could
2249 * deadlock if we are configured to remove ourselves
2250 * once we're disconnected.
2252 if (refcount_read(&nbd->config_refs))
2254 dev_opt = nla_nest_start_noflag(reply, NBD_DEVICE_ITEM);
2257 ret = nla_put_u32(reply, NBD_DEVICE_INDEX, nbd->index);
2260 ret = nla_put_u8(reply, NBD_DEVICE_CONNECTED,
2264 nla_nest_end(reply, dev_opt);
2268 static int status_cb(int id, void *ptr, void *data)
2270 struct nbd_device *nbd = ptr;
2271 return populate_nbd_status(nbd, (struct sk_buff *)data);
2274 static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info)
2276 struct nlattr *dev_list;
2277 struct sk_buff *reply;
2283 if (info->attrs[NBD_ATTR_INDEX])
2284 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2286 mutex_lock(&nbd_index_mutex);
2288 msg_size = nla_total_size(nla_attr_size(sizeof(u32)) +
2289 nla_attr_size(sizeof(u8)));
2290 msg_size *= (index == -1) ? nbd_total_devices : 1;
2292 reply = genlmsg_new(msg_size, GFP_KERNEL);
2295 reply_head = genlmsg_put_reply(reply, info, &nbd_genl_family, 0,
2302 dev_list = nla_nest_start_noflag(reply, NBD_ATTR_DEVICE_LIST);
2304 ret = idr_for_each(&nbd_index_idr, &status_cb, reply);
2310 struct nbd_device *nbd;
2311 nbd = idr_find(&nbd_index_idr, index);
2313 ret = populate_nbd_status(nbd, reply);
2320 nla_nest_end(reply, dev_list);
2321 genlmsg_end(reply, reply_head);
2322 ret = genlmsg_reply(reply, info);
2324 mutex_unlock(&nbd_index_mutex);
2328 static void nbd_connect_reply(struct genl_info *info, int index)
2330 struct sk_buff *skb;
2334 skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2337 msg_head = genlmsg_put_reply(skb, info, &nbd_genl_family, 0,
2343 ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2348 genlmsg_end(skb, msg_head);
2349 genlmsg_reply(skb, info);
2352 static void nbd_mcast_index(int index)
2354 struct sk_buff *skb;
2358 skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2361 msg_head = genlmsg_put(skb, 0, 0, &nbd_genl_family, 0,
2367 ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2372 genlmsg_end(skb, msg_head);
2373 genlmsg_multicast(&nbd_genl_family, skb, 0, 0, GFP_KERNEL);
2376 static void nbd_dead_link_work(struct work_struct *work)
2378 struct link_dead_args *args = container_of(work, struct link_dead_args,
2380 nbd_mcast_index(args->index);
2384 static int __init nbd_init(void)
2388 BUILD_BUG_ON(sizeof(struct nbd_request) != 28);
2391 printk(KERN_ERR "nbd: max_part must be >= 0\n");
2397 part_shift = fls(max_part);
2400 * Adjust max_part according to part_shift as it is exported
2401 * to user space so that user can know the max number of
2402 * partition kernel should be able to manage.
2404 * Note that -1 is required because partition 0 is reserved
2405 * for the whole disk.
2407 max_part = (1UL << part_shift) - 1;
2410 if ((1UL << part_shift) > DISK_MAX_PARTS)
2413 if (nbds_max > 1UL << (MINORBITS - part_shift))
2416 if (register_blkdev(NBD_MAJOR, "nbd"))
2419 if (genl_register_family(&nbd_genl_family)) {
2420 unregister_blkdev(NBD_MAJOR, "nbd");
2425 mutex_lock(&nbd_index_mutex);
2426 for (i = 0; i < nbds_max; i++)
2428 mutex_unlock(&nbd_index_mutex);
2432 static int nbd_exit_cb(int id, void *ptr, void *data)
2434 struct list_head *list = (struct list_head *)data;
2435 struct nbd_device *nbd = ptr;
2437 list_add_tail(&nbd->list, list);
2441 static void __exit nbd_cleanup(void)
2443 struct nbd_device *nbd;
2444 LIST_HEAD(del_list);
2448 mutex_lock(&nbd_index_mutex);
2449 idr_for_each(&nbd_index_idr, &nbd_exit_cb, &del_list);
2450 mutex_unlock(&nbd_index_mutex);
2452 while (!list_empty(&del_list)) {
2453 nbd = list_first_entry(&del_list, struct nbd_device, list);
2454 list_del_init(&nbd->list);
2455 if (refcount_read(&nbd->refs) != 1)
2456 printk(KERN_ERR "nbd: possibly leaking a device\n");
2460 idr_destroy(&nbd_index_idr);
2461 genl_unregister_family(&nbd_genl_family);
2462 unregister_blkdev(NBD_MAJOR, "nbd");
2465 module_init(nbd_init);
2466 module_exit(nbd_cleanup);
2468 MODULE_DESCRIPTION("Network Block Device");
2469 MODULE_LICENSE("GPL");
2471 module_param(nbds_max, int, 0444);
2472 MODULE_PARM_DESC(nbds_max, "number of network block devices to initialize (default: 16)");
2473 module_param(max_part, int, 0444);
2474 MODULE_PARM_DESC(max_part, "number of partitions per device (default: 16)");