1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * Network block device - make block devices work over TCP
5 * Note that you can not swap over this thing, yet. Seems to work but
6 * deadlocks sometimes - you can not swap over TCP in general.
8 * Copyright 1997-2000, 2008 Pavel Machek <pavel@ucw.cz>
9 * Parts copyright 2001 Steven Whitehouse <steve@chygwyn.com>
11 * (part of code stolen from loop.c)
14 #include <linux/major.h>
16 #include <linux/blkdev.h>
17 #include <linux/module.h>
18 #include <linux/init.h>
19 #include <linux/sched.h>
20 #include <linux/sched/mm.h>
22 #include <linux/bio.h>
23 #include <linux/stat.h>
24 #include <linux/errno.h>
25 #include <linux/file.h>
26 #include <linux/ioctl.h>
27 #include <linux/mutex.h>
28 #include <linux/compiler.h>
29 #include <linux/completion.h>
30 #include <linux/err.h>
31 #include <linux/kernel.h>
32 #include <linux/slab.h>
34 #include <linux/net.h>
35 #include <linux/kthread.h>
36 #include <linux/types.h>
37 #include <linux/debugfs.h>
38 #include <linux/blk-mq.h>
40 #include <linux/uaccess.h>
41 #include <asm/types.h>
43 #include <linux/nbd.h>
44 #include <linux/nbd-netlink.h>
45 #include <net/genetlink.h>
47 #define CREATE_TRACE_POINTS
48 #include <trace/events/nbd.h>
50 static DEFINE_IDR(nbd_index_idr);
51 static DEFINE_MUTEX(nbd_index_mutex);
52 static struct workqueue_struct *nbd_del_wq;
53 static int nbd_total_devices = 0;
58 struct request *pending;
65 struct recv_thread_args {
66 struct work_struct work;
67 struct nbd_device *nbd;
71 struct link_dead_args {
72 struct work_struct work;
76 #define NBD_RT_TIMEDOUT 0
77 #define NBD_RT_DISCONNECT_REQUESTED 1
78 #define NBD_RT_DISCONNECTED 2
79 #define NBD_RT_HAS_PID_FILE 3
80 #define NBD_RT_HAS_CONFIG_REF 4
81 #define NBD_RT_BOUND 5
82 #define NBD_RT_DISCONNECT_ON_CLOSE 6
83 #define NBD_RT_HAS_BACKEND_FILE 7
85 #define NBD_DESTROY_ON_DISCONNECT 0
86 #define NBD_DISCONNECT_REQUESTED 1
90 unsigned long runtime_flags;
91 u64 dead_conn_timeout;
93 struct nbd_sock **socks;
95 atomic_t live_connections;
96 wait_queue_head_t conn_wait;
98 atomic_t recv_threads;
99 wait_queue_head_t recv_wq;
102 #if IS_ENABLED(CONFIG_DEBUG_FS)
103 struct dentry *dbg_dir;
108 struct blk_mq_tag_set tag_set;
111 refcount_t config_refs;
113 struct nbd_config *config;
114 struct mutex config_lock;
115 struct gendisk *disk;
116 struct workqueue_struct *recv_workq;
117 struct work_struct remove_work;
119 struct list_head list;
120 struct task_struct *task_recv;
121 struct task_struct *task_setup;
128 #define NBD_CMD_REQUEUED 1
131 struct nbd_device *nbd;
141 #if IS_ENABLED(CONFIG_DEBUG_FS)
142 static struct dentry *nbd_dbg_dir;
145 #define nbd_name(nbd) ((nbd)->disk->disk_name)
147 #define NBD_MAGIC 0x68797548
149 #define NBD_DEF_BLKSIZE 1024
151 static unsigned int nbds_max = 16;
152 static int max_part = 16;
153 static int part_shift;
155 static int nbd_dev_dbg_init(struct nbd_device *nbd);
156 static void nbd_dev_dbg_close(struct nbd_device *nbd);
157 static void nbd_config_put(struct nbd_device *nbd);
158 static void nbd_connect_reply(struct genl_info *info, int index);
159 static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info);
160 static void nbd_dead_link_work(struct work_struct *work);
161 static void nbd_disconnect_and_put(struct nbd_device *nbd);
163 static inline struct device *nbd_to_dev(struct nbd_device *nbd)
165 return disk_to_dev(nbd->disk);
168 static void nbd_requeue_cmd(struct nbd_cmd *cmd)
170 struct request *req = blk_mq_rq_from_pdu(cmd);
172 if (!test_and_set_bit(NBD_CMD_REQUEUED, &cmd->flags))
173 blk_mq_requeue_request(req, true);
176 #define NBD_COOKIE_BITS 32
178 static u64 nbd_cmd_handle(struct nbd_cmd *cmd)
180 struct request *req = blk_mq_rq_from_pdu(cmd);
181 u32 tag = blk_mq_unique_tag(req);
182 u64 cookie = cmd->cmd_cookie;
184 return (cookie << NBD_COOKIE_BITS) | tag;
187 static u32 nbd_handle_to_tag(u64 handle)
192 static u32 nbd_handle_to_cookie(u64 handle)
194 return (u32)(handle >> NBD_COOKIE_BITS);
197 static const char *nbdcmd_to_ascii(int cmd)
200 case NBD_CMD_READ: return "read";
201 case NBD_CMD_WRITE: return "write";
202 case NBD_CMD_DISC: return "disconnect";
203 case NBD_CMD_FLUSH: return "flush";
204 case NBD_CMD_TRIM: return "trim/discard";
209 static ssize_t pid_show(struct device *dev,
210 struct device_attribute *attr, char *buf)
212 struct gendisk *disk = dev_to_disk(dev);
213 struct nbd_device *nbd = (struct nbd_device *)disk->private_data;
215 return sprintf(buf, "%d\n", task_pid_nr(nbd->task_recv));
218 static const struct device_attribute pid_attr = {
219 .attr = { .name = "pid", .mode = 0444},
223 static ssize_t backend_show(struct device *dev,
224 struct device_attribute *attr, char *buf)
226 struct gendisk *disk = dev_to_disk(dev);
227 struct nbd_device *nbd = (struct nbd_device *)disk->private_data;
229 return sprintf(buf, "%s\n", nbd->backend ?: "");
232 static const struct device_attribute backend_attr = {
233 .attr = { .name = "backend", .mode = 0444},
234 .show = backend_show,
237 static void nbd_dev_remove(struct nbd_device *nbd)
239 struct gendisk *disk = nbd->disk;
242 blk_cleanup_disk(disk);
243 blk_mq_free_tag_set(&nbd->tag_set);
246 * Remove from idr after del_gendisk() completes, so if the same ID is
247 * reused, the following add_disk() will succeed.
249 mutex_lock(&nbd_index_mutex);
250 idr_remove(&nbd_index_idr, nbd->index);
251 mutex_unlock(&nbd_index_mutex);
256 static void nbd_dev_remove_work(struct work_struct *work)
258 nbd_dev_remove(container_of(work, struct nbd_device, remove_work));
261 static void nbd_put(struct nbd_device *nbd)
263 if (!refcount_dec_and_test(&nbd->refs))
266 /* Call del_gendisk() asynchrounously to prevent deadlock */
267 if (test_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags))
268 queue_work(nbd_del_wq, &nbd->remove_work);
273 static int nbd_disconnected(struct nbd_config *config)
275 return test_bit(NBD_RT_DISCONNECTED, &config->runtime_flags) ||
276 test_bit(NBD_RT_DISCONNECT_REQUESTED, &config->runtime_flags);
279 static void nbd_mark_nsock_dead(struct nbd_device *nbd, struct nbd_sock *nsock,
282 if (!nsock->dead && notify && !nbd_disconnected(nbd->config)) {
283 struct link_dead_args *args;
284 args = kmalloc(sizeof(struct link_dead_args), GFP_NOIO);
286 INIT_WORK(&args->work, nbd_dead_link_work);
287 args->index = nbd->index;
288 queue_work(system_wq, &args->work);
292 kernel_sock_shutdown(nsock->sock, SHUT_RDWR);
293 if (atomic_dec_return(&nbd->config->live_connections) == 0) {
294 if (test_and_clear_bit(NBD_RT_DISCONNECT_REQUESTED,
295 &nbd->config->runtime_flags)) {
296 set_bit(NBD_RT_DISCONNECTED,
297 &nbd->config->runtime_flags);
298 dev_info(nbd_to_dev(nbd),
299 "Disconnected due to user request.\n");
304 nsock->pending = NULL;
308 static void nbd_size_clear(struct nbd_device *nbd)
310 if (nbd->config->bytesize) {
311 set_capacity(nbd->disk, 0);
312 kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
316 static int nbd_set_size(struct nbd_device *nbd, loff_t bytesize,
320 blksize = NBD_DEF_BLKSIZE;
321 if (blksize < 512 || blksize > PAGE_SIZE || !is_power_of_2(blksize))
324 nbd->config->bytesize = bytesize;
325 nbd->config->blksize = blksize;
330 if (nbd->config->flags & NBD_FLAG_SEND_TRIM) {
331 nbd->disk->queue->limits.discard_granularity = blksize;
332 nbd->disk->queue->limits.discard_alignment = blksize;
333 blk_queue_max_discard_sectors(nbd->disk->queue, UINT_MAX);
335 blk_queue_logical_block_size(nbd->disk->queue, blksize);
336 blk_queue_physical_block_size(nbd->disk->queue, blksize);
339 set_bit(GD_NEED_PART_SCAN, &nbd->disk->state);
340 if (!set_capacity_and_notify(nbd->disk, bytesize >> 9))
341 kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
345 static void nbd_complete_rq(struct request *req)
347 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
349 dev_dbg(nbd_to_dev(cmd->nbd), "request %p: %s\n", req,
350 cmd->status ? "failed" : "done");
352 blk_mq_end_request(req, cmd->status);
356 * Forcibly shutdown the socket causing all listeners to error
358 static void sock_shutdown(struct nbd_device *nbd)
360 struct nbd_config *config = nbd->config;
363 if (config->num_connections == 0)
365 if (test_and_set_bit(NBD_RT_DISCONNECTED, &config->runtime_flags))
368 for (i = 0; i < config->num_connections; i++) {
369 struct nbd_sock *nsock = config->socks[i];
370 mutex_lock(&nsock->tx_lock);
371 nbd_mark_nsock_dead(nbd, nsock, 0);
372 mutex_unlock(&nsock->tx_lock);
374 dev_warn(disk_to_dev(nbd->disk), "shutting down sockets\n");
377 static u32 req_to_nbd_cmd_type(struct request *req)
379 switch (req_op(req)) {
383 return NBD_CMD_FLUSH;
385 return NBD_CMD_WRITE;
393 static enum blk_eh_timer_return nbd_xmit_timeout(struct request *req,
396 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
397 struct nbd_device *nbd = cmd->nbd;
398 struct nbd_config *config;
400 if (!mutex_trylock(&cmd->lock))
401 return BLK_EH_RESET_TIMER;
403 if (!refcount_inc_not_zero(&nbd->config_refs)) {
404 cmd->status = BLK_STS_TIMEOUT;
405 mutex_unlock(&cmd->lock);
408 config = nbd->config;
410 if (config->num_connections > 1 ||
411 (config->num_connections == 1 && nbd->tag_set.timeout)) {
412 dev_err_ratelimited(nbd_to_dev(nbd),
413 "Connection timed out, retrying (%d/%d alive)\n",
414 atomic_read(&config->live_connections),
415 config->num_connections);
417 * Hooray we have more connections, requeue this IO, the submit
418 * path will put it on a real connection. Or if only one
419 * connection is configured, the submit path will wait util
420 * a new connection is reconfigured or util dead timeout.
423 if (cmd->index < config->num_connections) {
424 struct nbd_sock *nsock =
425 config->socks[cmd->index];
426 mutex_lock(&nsock->tx_lock);
427 /* We can have multiple outstanding requests, so
428 * we don't want to mark the nsock dead if we've
429 * already reconnected with a new socket, so
430 * only mark it dead if its the same socket we
433 if (cmd->cookie == nsock->cookie)
434 nbd_mark_nsock_dead(nbd, nsock, 1);
435 mutex_unlock(&nsock->tx_lock);
437 mutex_unlock(&cmd->lock);
438 nbd_requeue_cmd(cmd);
444 if (!nbd->tag_set.timeout) {
446 * Userspace sets timeout=0 to disable socket disconnection,
447 * so just warn and reset the timer.
449 struct nbd_sock *nsock = config->socks[cmd->index];
451 dev_info(nbd_to_dev(nbd), "Possible stuck request %p: control (%s@%llu,%uB). Runtime %u seconds\n",
452 req, nbdcmd_to_ascii(req_to_nbd_cmd_type(req)),
453 (unsigned long long)blk_rq_pos(req) << 9,
454 blk_rq_bytes(req), (req->timeout / HZ) * cmd->retries);
456 mutex_lock(&nsock->tx_lock);
457 if (cmd->cookie != nsock->cookie) {
458 nbd_requeue_cmd(cmd);
459 mutex_unlock(&nsock->tx_lock);
460 mutex_unlock(&cmd->lock);
464 mutex_unlock(&nsock->tx_lock);
465 mutex_unlock(&cmd->lock);
467 return BLK_EH_RESET_TIMER;
470 dev_err_ratelimited(nbd_to_dev(nbd), "Connection timed out\n");
471 set_bit(NBD_RT_TIMEDOUT, &config->runtime_flags);
472 cmd->status = BLK_STS_IOERR;
473 mutex_unlock(&cmd->lock);
477 blk_mq_complete_request(req);
482 * Send or receive packet.
484 static int sock_xmit(struct nbd_device *nbd, int index, int send,
485 struct iov_iter *iter, int msg_flags, int *sent)
487 struct nbd_config *config = nbd->config;
488 struct socket *sock = config->socks[index]->sock;
491 unsigned int noreclaim_flag;
493 if (unlikely(!sock)) {
494 dev_err_ratelimited(disk_to_dev(nbd->disk),
495 "Attempted %s on closed socket in sock_xmit\n",
496 (send ? "send" : "recv"));
500 msg.msg_iter = *iter;
502 noreclaim_flag = memalloc_noreclaim_save();
504 sock->sk->sk_allocation = GFP_NOIO | __GFP_MEMALLOC;
507 msg.msg_control = NULL;
508 msg.msg_controllen = 0;
509 msg.msg_flags = msg_flags | MSG_NOSIGNAL;
512 result = sock_sendmsg(sock, &msg);
514 result = sock_recvmsg(sock, &msg, msg.msg_flags);
518 result = -EPIPE; /* short read */
523 } while (msg_data_left(&msg));
525 memalloc_noreclaim_restore(noreclaim_flag);
531 * Different settings for sk->sk_sndtimeo can result in different return values
532 * if there is a signal pending when we enter sendmsg, because reasons?
534 static inline int was_interrupted(int result)
536 return result == -ERESTARTSYS || result == -EINTR;
539 /* always call with the tx_lock held */
540 static int nbd_send_cmd(struct nbd_device *nbd, struct nbd_cmd *cmd, int index)
542 struct request *req = blk_mq_rq_from_pdu(cmd);
543 struct nbd_config *config = nbd->config;
544 struct nbd_sock *nsock = config->socks[index];
546 struct nbd_request request = {.magic = htonl(NBD_REQUEST_MAGIC)};
547 struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
548 struct iov_iter from;
549 unsigned long size = blk_rq_bytes(req);
553 u32 nbd_cmd_flags = 0;
554 int sent = nsock->sent, skip = 0;
556 iov_iter_kvec(&from, WRITE, &iov, 1, sizeof(request));
558 type = req_to_nbd_cmd_type(req);
562 if (rq_data_dir(req) == WRITE &&
563 (config->flags & NBD_FLAG_READ_ONLY)) {
564 dev_err_ratelimited(disk_to_dev(nbd->disk),
565 "Write on read-only\n");
569 if (req->cmd_flags & REQ_FUA)
570 nbd_cmd_flags |= NBD_CMD_FLAG_FUA;
572 /* We did a partial send previously, and we at least sent the whole
573 * request struct, so just go and send the rest of the pages in the
577 if (sent >= sizeof(request)) {
578 skip = sent - sizeof(request);
580 /* initialize handle for tracing purposes */
581 handle = nbd_cmd_handle(cmd);
585 iov_iter_advance(&from, sent);
590 cmd->cookie = nsock->cookie;
592 request.type = htonl(type | nbd_cmd_flags);
593 if (type != NBD_CMD_FLUSH) {
594 request.from = cpu_to_be64((u64)blk_rq_pos(req) << 9);
595 request.len = htonl(size);
597 handle = nbd_cmd_handle(cmd);
598 memcpy(request.handle, &handle, sizeof(handle));
600 trace_nbd_send_request(&request, nbd->index, blk_mq_rq_from_pdu(cmd));
602 dev_dbg(nbd_to_dev(nbd), "request %p: sending control (%s@%llu,%uB)\n",
603 req, nbdcmd_to_ascii(type),
604 (unsigned long long)blk_rq_pos(req) << 9, blk_rq_bytes(req));
605 result = sock_xmit(nbd, index, 1, &from,
606 (type == NBD_CMD_WRITE) ? MSG_MORE : 0, &sent);
607 trace_nbd_header_sent(req, handle);
609 if (was_interrupted(result)) {
610 /* If we havne't sent anything we can just return BUSY,
611 * however if we have sent something we need to make
612 * sure we only allow this req to be sent until we are
616 nsock->pending = req;
619 set_bit(NBD_CMD_REQUEUED, &cmd->flags);
620 return BLK_STS_RESOURCE;
622 dev_err_ratelimited(disk_to_dev(nbd->disk),
623 "Send control failed (result %d)\n", result);
627 if (type != NBD_CMD_WRITE)
632 struct bio *next = bio->bi_next;
633 struct bvec_iter iter;
636 bio_for_each_segment(bvec, bio, iter) {
637 bool is_last = !next && bio_iter_last(bvec, iter);
638 int flags = is_last ? 0 : MSG_MORE;
640 dev_dbg(nbd_to_dev(nbd), "request %p: sending %d bytes data\n",
642 iov_iter_bvec(&from, WRITE, &bvec, 1, bvec.bv_len);
644 if (skip >= iov_iter_count(&from)) {
645 skip -= iov_iter_count(&from);
648 iov_iter_advance(&from, skip);
651 result = sock_xmit(nbd, index, 1, &from, flags, &sent);
653 if (was_interrupted(result)) {
654 /* We've already sent the header, we
655 * have no choice but to set pending and
658 nsock->pending = req;
660 set_bit(NBD_CMD_REQUEUED, &cmd->flags);
661 return BLK_STS_RESOURCE;
663 dev_err(disk_to_dev(nbd->disk),
664 "Send data failed (result %d)\n",
669 * The completion might already have come in,
670 * so break for the last one instead of letting
671 * the iterator do it. This prevents use-after-free
680 trace_nbd_payload_sent(req, handle);
681 nsock->pending = NULL;
686 /* NULL returned = something went wrong, inform userspace */
687 static struct nbd_cmd *nbd_read_stat(struct nbd_device *nbd, int index)
689 struct nbd_config *config = nbd->config;
691 struct nbd_reply reply;
693 struct request *req = NULL;
697 struct kvec iov = {.iov_base = &reply, .iov_len = sizeof(reply)};
702 iov_iter_kvec(&to, READ, &iov, 1, sizeof(reply));
703 result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
705 if (!nbd_disconnected(config))
706 dev_err(disk_to_dev(nbd->disk),
707 "Receive control failed (result %d)\n", result);
708 return ERR_PTR(result);
711 if (ntohl(reply.magic) != NBD_REPLY_MAGIC) {
712 dev_err(disk_to_dev(nbd->disk), "Wrong magic (0x%lx)\n",
713 (unsigned long)ntohl(reply.magic));
714 return ERR_PTR(-EPROTO);
717 memcpy(&handle, reply.handle, sizeof(handle));
718 tag = nbd_handle_to_tag(handle);
719 hwq = blk_mq_unique_tag_to_hwq(tag);
720 if (hwq < nbd->tag_set.nr_hw_queues)
721 req = blk_mq_tag_to_rq(nbd->tag_set.tags[hwq],
722 blk_mq_unique_tag_to_tag(tag));
723 if (!req || !blk_mq_request_started(req)) {
724 dev_err(disk_to_dev(nbd->disk), "Unexpected reply (%d) %p\n",
726 return ERR_PTR(-ENOENT);
728 trace_nbd_header_received(req, handle);
729 cmd = blk_mq_rq_to_pdu(req);
731 mutex_lock(&cmd->lock);
732 if (cmd->cmd_cookie != nbd_handle_to_cookie(handle)) {
733 dev_err(disk_to_dev(nbd->disk), "Double reply on req %p, cmd_cookie %u, handle cookie %u\n",
734 req, cmd->cmd_cookie, nbd_handle_to_cookie(handle));
738 if (cmd->status != BLK_STS_OK) {
739 dev_err(disk_to_dev(nbd->disk), "Command already handled %p\n",
744 if (test_bit(NBD_CMD_REQUEUED, &cmd->flags)) {
745 dev_err(disk_to_dev(nbd->disk), "Raced with timeout on req %p\n",
750 if (ntohl(reply.error)) {
751 dev_err(disk_to_dev(nbd->disk), "Other side returned error (%d)\n",
753 cmd->status = BLK_STS_IOERR;
757 dev_dbg(nbd_to_dev(nbd), "request %p: got reply\n", req);
758 if (rq_data_dir(req) != WRITE) {
759 struct req_iterator iter;
762 rq_for_each_segment(bvec, req, iter) {
763 iov_iter_bvec(&to, READ, &bvec, 1, bvec.bv_len);
764 result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
766 dev_err(disk_to_dev(nbd->disk), "Receive data failed (result %d)\n",
769 * If we've disconnected, we need to make sure we
770 * complete this request, otherwise error out
771 * and let the timeout stuff handle resubmitting
772 * this request onto another connection.
774 if (nbd_disconnected(config)) {
775 cmd->status = BLK_STS_IOERR;
781 dev_dbg(nbd_to_dev(nbd), "request %p: got %d bytes data\n",
786 trace_nbd_payload_received(req, handle);
787 mutex_unlock(&cmd->lock);
788 return ret ? ERR_PTR(ret) : cmd;
791 static void recv_work(struct work_struct *work)
793 struct recv_thread_args *args = container_of(work,
794 struct recv_thread_args,
796 struct nbd_device *nbd = args->nbd;
797 struct nbd_config *config = nbd->config;
802 cmd = nbd_read_stat(nbd, args->index);
804 struct nbd_sock *nsock = config->socks[args->index];
806 mutex_lock(&nsock->tx_lock);
807 nbd_mark_nsock_dead(nbd, nsock, 1);
808 mutex_unlock(&nsock->tx_lock);
812 rq = blk_mq_rq_from_pdu(cmd);
813 if (likely(!blk_should_fake_timeout(rq->q)))
814 blk_mq_complete_request(rq);
817 atomic_dec(&config->recv_threads);
818 wake_up(&config->recv_wq);
822 static bool nbd_clear_req(struct request *req, void *data, bool reserved)
824 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
826 /* don't abort one completed request */
827 if (blk_mq_request_completed(req))
830 mutex_lock(&cmd->lock);
831 cmd->status = BLK_STS_IOERR;
832 mutex_unlock(&cmd->lock);
834 blk_mq_complete_request(req);
838 static void nbd_clear_que(struct nbd_device *nbd)
840 blk_mq_quiesce_queue(nbd->disk->queue);
841 blk_mq_tagset_busy_iter(&nbd->tag_set, nbd_clear_req, NULL);
842 blk_mq_unquiesce_queue(nbd->disk->queue);
843 dev_dbg(disk_to_dev(nbd->disk), "queue cleared\n");
846 static int find_fallback(struct nbd_device *nbd, int index)
848 struct nbd_config *config = nbd->config;
850 struct nbd_sock *nsock = config->socks[index];
851 int fallback = nsock->fallback_index;
853 if (test_bit(NBD_RT_DISCONNECTED, &config->runtime_flags))
856 if (config->num_connections <= 1) {
857 dev_err_ratelimited(disk_to_dev(nbd->disk),
858 "Dead connection, failed to find a fallback\n");
862 if (fallback >= 0 && fallback < config->num_connections &&
863 !config->socks[fallback]->dead)
866 if (nsock->fallback_index < 0 ||
867 nsock->fallback_index >= config->num_connections ||
868 config->socks[nsock->fallback_index]->dead) {
870 for (i = 0; i < config->num_connections; i++) {
873 if (!config->socks[i]->dead) {
878 nsock->fallback_index = new_index;
880 dev_err_ratelimited(disk_to_dev(nbd->disk),
881 "Dead connection, failed to find a fallback\n");
885 new_index = nsock->fallback_index;
889 static int wait_for_reconnect(struct nbd_device *nbd)
891 struct nbd_config *config = nbd->config;
892 if (!config->dead_conn_timeout)
894 if (test_bit(NBD_RT_DISCONNECTED, &config->runtime_flags))
896 return wait_event_timeout(config->conn_wait,
897 atomic_read(&config->live_connections) > 0,
898 config->dead_conn_timeout) > 0;
901 static int nbd_handle_cmd(struct nbd_cmd *cmd, int index)
903 struct request *req = blk_mq_rq_from_pdu(cmd);
904 struct nbd_device *nbd = cmd->nbd;
905 struct nbd_config *config;
906 struct nbd_sock *nsock;
909 if (!refcount_inc_not_zero(&nbd->config_refs)) {
910 dev_err_ratelimited(disk_to_dev(nbd->disk),
911 "Socks array is empty\n");
912 blk_mq_start_request(req);
915 config = nbd->config;
917 if (index >= config->num_connections) {
918 dev_err_ratelimited(disk_to_dev(nbd->disk),
919 "Attempted send on invalid socket\n");
921 blk_mq_start_request(req);
924 cmd->status = BLK_STS_OK;
926 nsock = config->socks[index];
927 mutex_lock(&nsock->tx_lock);
929 int old_index = index;
930 index = find_fallback(nbd, index);
931 mutex_unlock(&nsock->tx_lock);
933 if (wait_for_reconnect(nbd)) {
937 /* All the sockets should already be down at this point,
938 * we just want to make sure that DISCONNECTED is set so
939 * any requests that come in that were queue'ed waiting
940 * for the reconnect timer don't trigger the timer again
941 * and instead just error out.
945 blk_mq_start_request(req);
951 /* Handle the case that we have a pending request that was partially
952 * transmitted that _has_ to be serviced first. We need to call requeue
953 * here so that it gets put _after_ the request that is already on the
956 blk_mq_start_request(req);
957 if (unlikely(nsock->pending && nsock->pending != req)) {
958 nbd_requeue_cmd(cmd);
963 * Some failures are related to the link going down, so anything that
964 * returns EAGAIN can be retried on a different socket.
966 ret = nbd_send_cmd(nbd, cmd, index);
967 if (ret == -EAGAIN) {
968 dev_err_ratelimited(disk_to_dev(nbd->disk),
969 "Request send failed, requeueing\n");
970 nbd_mark_nsock_dead(nbd, nsock, 1);
971 nbd_requeue_cmd(cmd);
975 mutex_unlock(&nsock->tx_lock);
980 static blk_status_t nbd_queue_rq(struct blk_mq_hw_ctx *hctx,
981 const struct blk_mq_queue_data *bd)
983 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(bd->rq);
987 * Since we look at the bio's to send the request over the network we
988 * need to make sure the completion work doesn't mark this request done
989 * before we are done doing our send. This keeps us from dereferencing
990 * freed data if we have particularly fast completions (ie we get the
991 * completion before we exit sock_xmit on the last bvec) or in the case
992 * that the server is misbehaving (or there was an error) before we're
993 * done sending everything over the wire.
995 mutex_lock(&cmd->lock);
996 clear_bit(NBD_CMD_REQUEUED, &cmd->flags);
998 /* We can be called directly from the user space process, which means we
999 * could possibly have signals pending so our sendmsg will fail. In
1000 * this case we need to return that we are busy, otherwise error out as
1003 ret = nbd_handle_cmd(cmd, hctx->queue_num);
1005 ret = BLK_STS_IOERR;
1008 mutex_unlock(&cmd->lock);
1013 static struct socket *nbd_get_socket(struct nbd_device *nbd, unsigned long fd,
1016 struct socket *sock;
1019 sock = sockfd_lookup(fd, err);
1023 if (sock->ops->shutdown == sock_no_shutdown) {
1024 dev_err(disk_to_dev(nbd->disk), "Unsupported socket: shutdown callout must be supported.\n");
1033 static int nbd_add_socket(struct nbd_device *nbd, unsigned long arg,
1036 struct nbd_config *config = nbd->config;
1037 struct socket *sock;
1038 struct nbd_sock **socks;
1039 struct nbd_sock *nsock;
1042 sock = nbd_get_socket(nbd, arg, &err);
1047 * We need to make sure we don't get any errant requests while we're
1048 * reallocating the ->socks array.
1050 blk_mq_freeze_queue(nbd->disk->queue);
1052 if (!netlink && !nbd->task_setup &&
1053 !test_bit(NBD_RT_BOUND, &config->runtime_flags))
1054 nbd->task_setup = current;
1057 (nbd->task_setup != current ||
1058 test_bit(NBD_RT_BOUND, &config->runtime_flags))) {
1059 dev_err(disk_to_dev(nbd->disk),
1060 "Device being setup by another task");
1065 nsock = kzalloc(sizeof(*nsock), GFP_KERNEL);
1071 socks = krealloc(config->socks, (config->num_connections + 1) *
1072 sizeof(struct nbd_sock *), GFP_KERNEL);
1079 config->socks = socks;
1081 nsock->fallback_index = -1;
1082 nsock->dead = false;
1083 mutex_init(&nsock->tx_lock);
1085 nsock->pending = NULL;
1088 socks[config->num_connections++] = nsock;
1089 atomic_inc(&config->live_connections);
1090 blk_mq_unfreeze_queue(nbd->disk->queue);
1095 blk_mq_unfreeze_queue(nbd->disk->queue);
1100 static int nbd_reconnect_socket(struct nbd_device *nbd, unsigned long arg)
1102 struct nbd_config *config = nbd->config;
1103 struct socket *sock, *old;
1104 struct recv_thread_args *args;
1108 sock = nbd_get_socket(nbd, arg, &err);
1112 args = kzalloc(sizeof(*args), GFP_KERNEL);
1118 for (i = 0; i < config->num_connections; i++) {
1119 struct nbd_sock *nsock = config->socks[i];
1124 mutex_lock(&nsock->tx_lock);
1126 mutex_unlock(&nsock->tx_lock);
1129 sk_set_memalloc(sock->sk);
1130 if (nbd->tag_set.timeout)
1131 sock->sk->sk_sndtimeo = nbd->tag_set.timeout;
1132 atomic_inc(&config->recv_threads);
1133 refcount_inc(&nbd->config_refs);
1135 nsock->fallback_index = -1;
1137 nsock->dead = false;
1138 INIT_WORK(&args->work, recv_work);
1142 mutex_unlock(&nsock->tx_lock);
1145 clear_bit(NBD_RT_DISCONNECTED, &config->runtime_flags);
1147 /* We take the tx_mutex in an error path in the recv_work, so we
1148 * need to queue_work outside of the tx_mutex.
1150 queue_work(nbd->recv_workq, &args->work);
1152 atomic_inc(&config->live_connections);
1153 wake_up(&config->conn_wait);
1161 static void nbd_bdev_reset(struct block_device *bdev)
1163 if (bdev->bd_openers > 1)
1165 set_capacity(bdev->bd_disk, 0);
1168 static void nbd_parse_flags(struct nbd_device *nbd)
1170 struct nbd_config *config = nbd->config;
1171 if (config->flags & NBD_FLAG_READ_ONLY)
1172 set_disk_ro(nbd->disk, true);
1174 set_disk_ro(nbd->disk, false);
1175 if (config->flags & NBD_FLAG_SEND_TRIM)
1176 blk_queue_flag_set(QUEUE_FLAG_DISCARD, nbd->disk->queue);
1177 if (config->flags & NBD_FLAG_SEND_FLUSH) {
1178 if (config->flags & NBD_FLAG_SEND_FUA)
1179 blk_queue_write_cache(nbd->disk->queue, true, true);
1181 blk_queue_write_cache(nbd->disk->queue, true, false);
1184 blk_queue_write_cache(nbd->disk->queue, false, false);
1187 static void send_disconnects(struct nbd_device *nbd)
1189 struct nbd_config *config = nbd->config;
1190 struct nbd_request request = {
1191 .magic = htonl(NBD_REQUEST_MAGIC),
1192 .type = htonl(NBD_CMD_DISC),
1194 struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
1195 struct iov_iter from;
1198 for (i = 0; i < config->num_connections; i++) {
1199 struct nbd_sock *nsock = config->socks[i];
1201 iov_iter_kvec(&from, WRITE, &iov, 1, sizeof(request));
1202 mutex_lock(&nsock->tx_lock);
1203 ret = sock_xmit(nbd, i, 1, &from, 0, NULL);
1205 dev_err(disk_to_dev(nbd->disk),
1206 "Send disconnect failed %d\n", ret);
1207 mutex_unlock(&nsock->tx_lock);
1211 static int nbd_disconnect(struct nbd_device *nbd)
1213 struct nbd_config *config = nbd->config;
1215 dev_info(disk_to_dev(nbd->disk), "NBD_DISCONNECT\n");
1216 set_bit(NBD_RT_DISCONNECT_REQUESTED, &config->runtime_flags);
1217 set_bit(NBD_DISCONNECT_REQUESTED, &nbd->flags);
1218 send_disconnects(nbd);
1222 static void nbd_clear_sock(struct nbd_device *nbd)
1226 nbd->task_setup = NULL;
1229 static void nbd_config_put(struct nbd_device *nbd)
1231 if (refcount_dec_and_mutex_lock(&nbd->config_refs,
1232 &nbd->config_lock)) {
1233 struct nbd_config *config = nbd->config;
1234 nbd_dev_dbg_close(nbd);
1235 nbd_size_clear(nbd);
1236 if (test_and_clear_bit(NBD_RT_HAS_PID_FILE,
1237 &config->runtime_flags))
1238 device_remove_file(disk_to_dev(nbd->disk), &pid_attr);
1239 nbd->task_recv = NULL;
1240 if (test_and_clear_bit(NBD_RT_HAS_BACKEND_FILE,
1241 &config->runtime_flags)) {
1242 device_remove_file(disk_to_dev(nbd->disk), &backend_attr);
1243 kfree(nbd->backend);
1244 nbd->backend = NULL;
1246 nbd_clear_sock(nbd);
1247 if (config->num_connections) {
1249 for (i = 0; i < config->num_connections; i++) {
1250 sockfd_put(config->socks[i]->sock);
1251 kfree(config->socks[i]);
1253 kfree(config->socks);
1258 if (nbd->recv_workq)
1259 destroy_workqueue(nbd->recv_workq);
1260 nbd->recv_workq = NULL;
1262 nbd->tag_set.timeout = 0;
1263 nbd->disk->queue->limits.discard_granularity = 0;
1264 nbd->disk->queue->limits.discard_alignment = 0;
1265 blk_queue_max_discard_sectors(nbd->disk->queue, UINT_MAX);
1266 blk_queue_flag_clear(QUEUE_FLAG_DISCARD, nbd->disk->queue);
1268 mutex_unlock(&nbd->config_lock);
1270 module_put(THIS_MODULE);
1274 static int nbd_start_device(struct nbd_device *nbd)
1276 struct nbd_config *config = nbd->config;
1277 int num_connections = config->num_connections;
1284 if (num_connections > 1 &&
1285 !(config->flags & NBD_FLAG_CAN_MULTI_CONN)) {
1286 dev_err(disk_to_dev(nbd->disk), "server does not support multiple connections per device.\n");
1290 nbd->recv_workq = alloc_workqueue("knbd%d-recv",
1291 WQ_MEM_RECLAIM | WQ_HIGHPRI |
1292 WQ_UNBOUND, 0, nbd->index);
1293 if (!nbd->recv_workq) {
1294 dev_err(disk_to_dev(nbd->disk), "Could not allocate knbd recv work queue.\n");
1298 blk_mq_update_nr_hw_queues(&nbd->tag_set, config->num_connections);
1299 nbd->task_recv = current;
1301 nbd_parse_flags(nbd);
1303 error = device_create_file(disk_to_dev(nbd->disk), &pid_attr);
1305 dev_err(disk_to_dev(nbd->disk), "device_create_file failed for pid!\n");
1308 set_bit(NBD_RT_HAS_PID_FILE, &config->runtime_flags);
1310 nbd_dev_dbg_init(nbd);
1311 for (i = 0; i < num_connections; i++) {
1312 struct recv_thread_args *args;
1314 args = kzalloc(sizeof(*args), GFP_KERNEL);
1318 * If num_connections is m (2 < m),
1319 * and NO.1 ~ NO.n(1 < n < m) kzallocs are successful.
1320 * But NO.(n + 1) failed. We still have n recv threads.
1321 * So, add flush_workqueue here to prevent recv threads
1322 * dropping the last config_refs and trying to destroy
1323 * the workqueue from inside the workqueue.
1326 flush_workqueue(nbd->recv_workq);
1329 sk_set_memalloc(config->socks[i]->sock->sk);
1330 if (nbd->tag_set.timeout)
1331 config->socks[i]->sock->sk->sk_sndtimeo =
1332 nbd->tag_set.timeout;
1333 atomic_inc(&config->recv_threads);
1334 refcount_inc(&nbd->config_refs);
1335 INIT_WORK(&args->work, recv_work);
1338 queue_work(nbd->recv_workq, &args->work);
1340 return nbd_set_size(nbd, config->bytesize, config->blksize);
1343 static int nbd_start_device_ioctl(struct nbd_device *nbd, struct block_device *bdev)
1345 struct nbd_config *config = nbd->config;
1348 ret = nbd_start_device(nbd);
1353 set_bit(GD_NEED_PART_SCAN, &nbd->disk->state);
1354 mutex_unlock(&nbd->config_lock);
1355 ret = wait_event_interruptible(config->recv_wq,
1356 atomic_read(&config->recv_threads) == 0);
1359 flush_workqueue(nbd->recv_workq);
1361 mutex_lock(&nbd->config_lock);
1362 nbd_bdev_reset(bdev);
1363 /* user requested, ignore socket errors */
1364 if (test_bit(NBD_RT_DISCONNECT_REQUESTED, &config->runtime_flags))
1366 if (test_bit(NBD_RT_TIMEDOUT, &config->runtime_flags))
1371 static void nbd_clear_sock_ioctl(struct nbd_device *nbd,
1372 struct block_device *bdev)
1375 __invalidate_device(bdev, true);
1376 nbd_bdev_reset(bdev);
1377 if (test_and_clear_bit(NBD_RT_HAS_CONFIG_REF,
1378 &nbd->config->runtime_flags))
1379 nbd_config_put(nbd);
1382 static void nbd_set_cmd_timeout(struct nbd_device *nbd, u64 timeout)
1384 nbd->tag_set.timeout = timeout * HZ;
1386 blk_queue_rq_timeout(nbd->disk->queue, timeout * HZ);
1388 blk_queue_rq_timeout(nbd->disk->queue, 30 * HZ);
1391 /* Must be called with config_lock held */
1392 static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
1393 unsigned int cmd, unsigned long arg)
1395 struct nbd_config *config = nbd->config;
1399 case NBD_DISCONNECT:
1400 return nbd_disconnect(nbd);
1401 case NBD_CLEAR_SOCK:
1402 nbd_clear_sock_ioctl(nbd, bdev);
1405 return nbd_add_socket(nbd, arg, false);
1406 case NBD_SET_BLKSIZE:
1407 return nbd_set_size(nbd, config->bytesize, arg);
1409 return nbd_set_size(nbd, arg, config->blksize);
1410 case NBD_SET_SIZE_BLOCKS:
1411 if (check_mul_overflow((loff_t)arg, config->blksize, &bytesize))
1413 return nbd_set_size(nbd, bytesize, config->blksize);
1414 case NBD_SET_TIMEOUT:
1415 nbd_set_cmd_timeout(nbd, arg);
1419 config->flags = arg;
1422 return nbd_start_device_ioctl(nbd, bdev);
1425 * This is for compatibility only. The queue is always cleared
1426 * by NBD_DO_IT or NBD_CLEAR_SOCK.
1429 case NBD_PRINT_DEBUG:
1431 * For compatibility only, we no longer keep a list of
1432 * outstanding requests.
1439 static int nbd_ioctl(struct block_device *bdev, fmode_t mode,
1440 unsigned int cmd, unsigned long arg)
1442 struct nbd_device *nbd = bdev->bd_disk->private_data;
1443 struct nbd_config *config = nbd->config;
1444 int error = -EINVAL;
1446 if (!capable(CAP_SYS_ADMIN))
1449 /* The block layer will pass back some non-nbd ioctls in case we have
1450 * special handling for them, but we don't so just return an error.
1452 if (_IOC_TYPE(cmd) != 0xab)
1455 mutex_lock(&nbd->config_lock);
1457 /* Don't allow ioctl operations on a nbd device that was created with
1458 * netlink, unless it's DISCONNECT or CLEAR_SOCK, which are fine.
1460 if (!test_bit(NBD_RT_BOUND, &config->runtime_flags) ||
1461 (cmd == NBD_DISCONNECT || cmd == NBD_CLEAR_SOCK))
1462 error = __nbd_ioctl(bdev, nbd, cmd, arg);
1464 dev_err(nbd_to_dev(nbd), "Cannot use ioctl interface on a netlink controlled device.\n");
1465 mutex_unlock(&nbd->config_lock);
1469 static struct nbd_config *nbd_alloc_config(void)
1471 struct nbd_config *config;
1473 config = kzalloc(sizeof(struct nbd_config), GFP_NOFS);
1476 atomic_set(&config->recv_threads, 0);
1477 init_waitqueue_head(&config->recv_wq);
1478 init_waitqueue_head(&config->conn_wait);
1479 config->blksize = NBD_DEF_BLKSIZE;
1480 atomic_set(&config->live_connections, 0);
1481 try_module_get(THIS_MODULE);
1485 static int nbd_open(struct block_device *bdev, fmode_t mode)
1487 struct nbd_device *nbd;
1490 mutex_lock(&nbd_index_mutex);
1491 nbd = bdev->bd_disk->private_data;
1496 if (!refcount_inc_not_zero(&nbd->refs)) {
1500 if (!refcount_inc_not_zero(&nbd->config_refs)) {
1501 struct nbd_config *config;
1503 mutex_lock(&nbd->config_lock);
1504 if (refcount_inc_not_zero(&nbd->config_refs)) {
1505 mutex_unlock(&nbd->config_lock);
1508 config = nbd->config = nbd_alloc_config();
1511 mutex_unlock(&nbd->config_lock);
1514 refcount_set(&nbd->config_refs, 1);
1515 refcount_inc(&nbd->refs);
1516 mutex_unlock(&nbd->config_lock);
1518 set_bit(GD_NEED_PART_SCAN, &bdev->bd_disk->state);
1519 } else if (nbd_disconnected(nbd->config)) {
1521 set_bit(GD_NEED_PART_SCAN, &bdev->bd_disk->state);
1524 mutex_unlock(&nbd_index_mutex);
1528 static void nbd_release(struct gendisk *disk, fmode_t mode)
1530 struct nbd_device *nbd = disk->private_data;
1532 if (test_bit(NBD_RT_DISCONNECT_ON_CLOSE, &nbd->config->runtime_flags) &&
1533 disk->part0->bd_openers == 0)
1534 nbd_disconnect_and_put(nbd);
1536 nbd_config_put(nbd);
1540 static const struct block_device_operations nbd_fops =
1542 .owner = THIS_MODULE,
1544 .release = nbd_release,
1546 .compat_ioctl = nbd_ioctl,
1549 #if IS_ENABLED(CONFIG_DEBUG_FS)
1551 static int nbd_dbg_tasks_show(struct seq_file *s, void *unused)
1553 struct nbd_device *nbd = s->private;
1556 seq_printf(s, "recv: %d\n", task_pid_nr(nbd->task_recv));
1561 DEFINE_SHOW_ATTRIBUTE(nbd_dbg_tasks);
1563 static int nbd_dbg_flags_show(struct seq_file *s, void *unused)
1565 struct nbd_device *nbd = s->private;
1566 u32 flags = nbd->config->flags;
1568 seq_printf(s, "Hex: 0x%08x\n\n", flags);
1570 seq_puts(s, "Known flags:\n");
1572 if (flags & NBD_FLAG_HAS_FLAGS)
1573 seq_puts(s, "NBD_FLAG_HAS_FLAGS\n");
1574 if (flags & NBD_FLAG_READ_ONLY)
1575 seq_puts(s, "NBD_FLAG_READ_ONLY\n");
1576 if (flags & NBD_FLAG_SEND_FLUSH)
1577 seq_puts(s, "NBD_FLAG_SEND_FLUSH\n");
1578 if (flags & NBD_FLAG_SEND_FUA)
1579 seq_puts(s, "NBD_FLAG_SEND_FUA\n");
1580 if (flags & NBD_FLAG_SEND_TRIM)
1581 seq_puts(s, "NBD_FLAG_SEND_TRIM\n");
1586 DEFINE_SHOW_ATTRIBUTE(nbd_dbg_flags);
1588 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1591 struct nbd_config *config = nbd->config;
1596 dir = debugfs_create_dir(nbd_name(nbd), nbd_dbg_dir);
1598 dev_err(nbd_to_dev(nbd), "Failed to create debugfs dir for '%s'\n",
1602 config->dbg_dir = dir;
1604 debugfs_create_file("tasks", 0444, dir, nbd, &nbd_dbg_tasks_fops);
1605 debugfs_create_u64("size_bytes", 0444, dir, &config->bytesize);
1606 debugfs_create_u32("timeout", 0444, dir, &nbd->tag_set.timeout);
1607 debugfs_create_u64("blocksize", 0444, dir, &config->blksize);
1608 debugfs_create_file("flags", 0444, dir, nbd, &nbd_dbg_flags_fops);
1613 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1615 debugfs_remove_recursive(nbd->config->dbg_dir);
1618 static int nbd_dbg_init(void)
1620 struct dentry *dbg_dir;
1622 dbg_dir = debugfs_create_dir("nbd", NULL);
1626 nbd_dbg_dir = dbg_dir;
1631 static void nbd_dbg_close(void)
1633 debugfs_remove_recursive(nbd_dbg_dir);
1636 #else /* IS_ENABLED(CONFIG_DEBUG_FS) */
1638 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1643 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1647 static int nbd_dbg_init(void)
1652 static void nbd_dbg_close(void)
1658 static int nbd_init_request(struct blk_mq_tag_set *set, struct request *rq,
1659 unsigned int hctx_idx, unsigned int numa_node)
1661 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(rq);
1662 cmd->nbd = set->driver_data;
1664 mutex_init(&cmd->lock);
1668 static const struct blk_mq_ops nbd_mq_ops = {
1669 .queue_rq = nbd_queue_rq,
1670 .complete = nbd_complete_rq,
1671 .init_request = nbd_init_request,
1672 .timeout = nbd_xmit_timeout,
1675 static struct nbd_device *nbd_dev_add(int index, unsigned int refs)
1677 struct nbd_device *nbd;
1678 struct gendisk *disk;
1681 nbd = kzalloc(sizeof(struct nbd_device), GFP_KERNEL);
1685 nbd->tag_set.ops = &nbd_mq_ops;
1686 nbd->tag_set.nr_hw_queues = 1;
1687 nbd->tag_set.queue_depth = 128;
1688 nbd->tag_set.numa_node = NUMA_NO_NODE;
1689 nbd->tag_set.cmd_size = sizeof(struct nbd_cmd);
1690 nbd->tag_set.flags = BLK_MQ_F_SHOULD_MERGE |
1692 nbd->tag_set.driver_data = nbd;
1693 INIT_WORK(&nbd->remove_work, nbd_dev_remove_work);
1694 nbd->backend = NULL;
1696 err = blk_mq_alloc_tag_set(&nbd->tag_set);
1700 mutex_lock(&nbd_index_mutex);
1702 err = idr_alloc(&nbd_index_idr, nbd, index, index + 1,
1707 err = idr_alloc(&nbd_index_idr, nbd, 0, 0, GFP_KERNEL);
1712 mutex_unlock(&nbd_index_mutex);
1716 disk = blk_mq_alloc_disk(&nbd->tag_set, NULL);
1718 err = PTR_ERR(disk);
1724 * Tell the block layer that we are not a rotational device
1726 blk_queue_flag_set(QUEUE_FLAG_NONROT, disk->queue);
1727 blk_queue_flag_clear(QUEUE_FLAG_ADD_RANDOM, disk->queue);
1728 disk->queue->limits.discard_granularity = 0;
1729 disk->queue->limits.discard_alignment = 0;
1730 blk_queue_max_discard_sectors(disk->queue, 0);
1731 blk_queue_max_segment_size(disk->queue, UINT_MAX);
1732 blk_queue_max_segments(disk->queue, USHRT_MAX);
1733 blk_queue_max_hw_sectors(disk->queue, 65536);
1734 disk->queue->limits.max_sectors = 256;
1736 mutex_init(&nbd->config_lock);
1737 refcount_set(&nbd->config_refs, 0);
1739 * Start out with a zero references to keep other threads from using
1740 * this device until it is fully initialized.
1742 refcount_set(&nbd->refs, 0);
1743 INIT_LIST_HEAD(&nbd->list);
1744 disk->major = NBD_MAJOR;
1746 /* Too big first_minor can cause duplicate creation of
1747 * sysfs files/links, since first_minor will be truncated to
1748 * byte in __device_add_disk().
1750 disk->first_minor = index << part_shift;
1751 if (disk->first_minor > 0xff) {
1756 disk->minors = 1 << part_shift;
1757 disk->fops = &nbd_fops;
1758 disk->private_data = nbd;
1759 sprintf(disk->disk_name, "nbd%d", index);
1763 * Now publish the device.
1765 refcount_set(&nbd->refs, refs);
1766 nbd_total_devices++;
1770 mutex_lock(&nbd_index_mutex);
1771 idr_remove(&nbd_index_idr, index);
1772 mutex_unlock(&nbd_index_mutex);
1774 blk_mq_free_tag_set(&nbd->tag_set);
1778 return ERR_PTR(err);
1781 static struct nbd_device *nbd_find_get_unused(void)
1783 struct nbd_device *nbd;
1786 lockdep_assert_held(&nbd_index_mutex);
1788 idr_for_each_entry(&nbd_index_idr, nbd, id) {
1789 if (refcount_read(&nbd->config_refs) ||
1790 test_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags))
1792 if (refcount_inc_not_zero(&nbd->refs))
1799 /* Netlink interface. */
1800 static const struct nla_policy nbd_attr_policy[NBD_ATTR_MAX + 1] = {
1801 [NBD_ATTR_INDEX] = { .type = NLA_U32 },
1802 [NBD_ATTR_SIZE_BYTES] = { .type = NLA_U64 },
1803 [NBD_ATTR_BLOCK_SIZE_BYTES] = { .type = NLA_U64 },
1804 [NBD_ATTR_TIMEOUT] = { .type = NLA_U64 },
1805 [NBD_ATTR_SERVER_FLAGS] = { .type = NLA_U64 },
1806 [NBD_ATTR_CLIENT_FLAGS] = { .type = NLA_U64 },
1807 [NBD_ATTR_SOCKETS] = { .type = NLA_NESTED},
1808 [NBD_ATTR_DEAD_CONN_TIMEOUT] = { .type = NLA_U64 },
1809 [NBD_ATTR_DEVICE_LIST] = { .type = NLA_NESTED},
1810 [NBD_ATTR_BACKEND_IDENTIFIER] = { .type = NLA_STRING},
1813 static const struct nla_policy nbd_sock_policy[NBD_SOCK_MAX + 1] = {
1814 [NBD_SOCK_FD] = { .type = NLA_U32 },
1817 /* We don't use this right now since we don't parse the incoming list, but we
1818 * still want it here so userspace knows what to expect.
1820 static const struct nla_policy __attribute__((unused))
1821 nbd_device_policy[NBD_DEVICE_ATTR_MAX + 1] = {
1822 [NBD_DEVICE_INDEX] = { .type = NLA_U32 },
1823 [NBD_DEVICE_CONNECTED] = { .type = NLA_U8 },
1826 static int nbd_genl_size_set(struct genl_info *info, struct nbd_device *nbd)
1828 struct nbd_config *config = nbd->config;
1829 u64 bsize = config->blksize;
1830 u64 bytes = config->bytesize;
1832 if (info->attrs[NBD_ATTR_SIZE_BYTES])
1833 bytes = nla_get_u64(info->attrs[NBD_ATTR_SIZE_BYTES]);
1835 if (info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES])
1836 bsize = nla_get_u64(info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]);
1838 if (bytes != config->bytesize || bsize != config->blksize)
1839 return nbd_set_size(nbd, bytes, bsize);
1843 static int nbd_genl_connect(struct sk_buff *skb, struct genl_info *info)
1845 struct nbd_device *nbd;
1846 struct nbd_config *config;
1849 bool put_dev = false;
1851 if (!netlink_capable(skb, CAP_SYS_ADMIN))
1854 if (info->attrs[NBD_ATTR_INDEX])
1855 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1856 if (!info->attrs[NBD_ATTR_SOCKETS]) {
1857 printk(KERN_ERR "nbd: must specify at least one socket\n");
1860 if (!info->attrs[NBD_ATTR_SIZE_BYTES]) {
1861 printk(KERN_ERR "nbd: must specify a size in bytes for the device\n");
1865 mutex_lock(&nbd_index_mutex);
1867 nbd = nbd_find_get_unused();
1869 nbd = idr_find(&nbd_index_idr, index);
1871 if ((test_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags) &&
1872 test_bit(NBD_DISCONNECT_REQUESTED, &nbd->flags)) ||
1873 !refcount_inc_not_zero(&nbd->refs)) {
1874 mutex_unlock(&nbd_index_mutex);
1875 pr_err("nbd: device at index %d is going down\n",
1881 mutex_unlock(&nbd_index_mutex);
1884 nbd = nbd_dev_add(index, 2);
1886 pr_err("nbd: failed to add new device\n");
1887 return PTR_ERR(nbd);
1891 mutex_lock(&nbd->config_lock);
1892 if (refcount_read(&nbd->config_refs)) {
1893 mutex_unlock(&nbd->config_lock);
1897 printk(KERN_ERR "nbd: nbd%d already in use\n", index);
1900 if (WARN_ON(nbd->config)) {
1901 mutex_unlock(&nbd->config_lock);
1905 config = nbd->config = nbd_alloc_config();
1907 mutex_unlock(&nbd->config_lock);
1909 printk(KERN_ERR "nbd: couldn't allocate config\n");
1912 refcount_set(&nbd->config_refs, 1);
1913 set_bit(NBD_RT_BOUND, &config->runtime_flags);
1915 ret = nbd_genl_size_set(info, nbd);
1919 if (info->attrs[NBD_ATTR_TIMEOUT])
1920 nbd_set_cmd_timeout(nbd,
1921 nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]));
1922 if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
1923 config->dead_conn_timeout =
1924 nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
1925 config->dead_conn_timeout *= HZ;
1927 if (info->attrs[NBD_ATTR_SERVER_FLAGS])
1929 nla_get_u64(info->attrs[NBD_ATTR_SERVER_FLAGS]);
1930 if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
1931 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
1932 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
1934 * We have 1 ref to keep the device around, and then 1
1935 * ref for our current operation here, which will be
1936 * inherited by the config. If we already have
1937 * DESTROY_ON_DISCONNECT set then we know we don't have
1938 * that extra ref already held so we don't need the
1941 if (!test_and_set_bit(NBD_DESTROY_ON_DISCONNECT,
1945 if (test_and_clear_bit(NBD_DESTROY_ON_DISCONNECT,
1947 refcount_inc(&nbd->refs);
1949 if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
1950 set_bit(NBD_RT_DISCONNECT_ON_CLOSE,
1951 &config->runtime_flags);
1955 if (info->attrs[NBD_ATTR_SOCKETS]) {
1956 struct nlattr *attr;
1959 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
1961 struct nlattr *socks[NBD_SOCK_MAX+1];
1963 if (nla_type(attr) != NBD_SOCK_ITEM) {
1964 printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
1968 ret = nla_parse_nested_deprecated(socks, NBD_SOCK_MAX,
1973 printk(KERN_ERR "nbd: error processing sock list\n");
1977 if (!socks[NBD_SOCK_FD])
1979 fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
1980 ret = nbd_add_socket(nbd, fd, true);
1985 ret = nbd_start_device(nbd);
1988 if (info->attrs[NBD_ATTR_BACKEND_IDENTIFIER]) {
1989 nbd->backend = nla_strdup(info->attrs[NBD_ATTR_BACKEND_IDENTIFIER],
1991 if (!nbd->backend) {
1996 ret = device_create_file(disk_to_dev(nbd->disk), &backend_attr);
1998 dev_err(disk_to_dev(nbd->disk),
1999 "device_create_file failed for backend!\n");
2002 set_bit(NBD_RT_HAS_BACKEND_FILE, &config->runtime_flags);
2004 mutex_unlock(&nbd->config_lock);
2006 set_bit(NBD_RT_HAS_CONFIG_REF, &config->runtime_flags);
2007 refcount_inc(&nbd->config_refs);
2008 nbd_connect_reply(info, nbd->index);
2010 nbd_config_put(nbd);
2016 static void nbd_disconnect_and_put(struct nbd_device *nbd)
2018 mutex_lock(&nbd->config_lock);
2019 nbd_disconnect(nbd);
2022 * Make sure recv thread has finished, so it does not drop the last
2023 * config ref and try to destroy the workqueue from inside the work
2024 * queue. And this also ensure that we can safely call nbd_clear_que()
2025 * to cancel the inflight I/Os.
2027 if (nbd->recv_workq)
2028 flush_workqueue(nbd->recv_workq);
2030 nbd->task_setup = NULL;
2031 mutex_unlock(&nbd->config_lock);
2033 if (test_and_clear_bit(NBD_RT_HAS_CONFIG_REF,
2034 &nbd->config->runtime_flags))
2035 nbd_config_put(nbd);
2038 static int nbd_genl_disconnect(struct sk_buff *skb, struct genl_info *info)
2040 struct nbd_device *nbd;
2043 if (!netlink_capable(skb, CAP_SYS_ADMIN))
2046 if (!info->attrs[NBD_ATTR_INDEX]) {
2047 printk(KERN_ERR "nbd: must specify an index to disconnect\n");
2050 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2051 mutex_lock(&nbd_index_mutex);
2052 nbd = idr_find(&nbd_index_idr, index);
2054 mutex_unlock(&nbd_index_mutex);
2055 printk(KERN_ERR "nbd: couldn't find device at index %d\n",
2059 if (!refcount_inc_not_zero(&nbd->refs)) {
2060 mutex_unlock(&nbd_index_mutex);
2061 printk(KERN_ERR "nbd: device at index %d is going down\n",
2065 mutex_unlock(&nbd_index_mutex);
2066 if (!refcount_inc_not_zero(&nbd->config_refs))
2068 nbd_disconnect_and_put(nbd);
2069 nbd_config_put(nbd);
2075 static int nbd_genl_reconfigure(struct sk_buff *skb, struct genl_info *info)
2077 struct nbd_device *nbd = NULL;
2078 struct nbd_config *config;
2081 bool put_dev = false;
2083 if (!netlink_capable(skb, CAP_SYS_ADMIN))
2086 if (!info->attrs[NBD_ATTR_INDEX]) {
2087 printk(KERN_ERR "nbd: must specify a device to reconfigure\n");
2090 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2091 mutex_lock(&nbd_index_mutex);
2092 nbd = idr_find(&nbd_index_idr, index);
2094 mutex_unlock(&nbd_index_mutex);
2095 printk(KERN_ERR "nbd: couldn't find a device at index %d\n",
2100 if (info->attrs[NBD_ATTR_BACKEND_IDENTIFIER]) {
2101 if (nla_strcmp(info->attrs[NBD_ATTR_BACKEND_IDENTIFIER],
2103 mutex_unlock(&nbd_index_mutex);
2104 dev_err(nbd_to_dev(nbd),
2105 "backend image doesn't match with %s\n",
2110 mutex_unlock(&nbd_index_mutex);
2111 dev_err(nbd_to_dev(nbd), "must specify backend\n");
2115 if (!refcount_inc_not_zero(&nbd->refs)) {
2116 mutex_unlock(&nbd_index_mutex);
2117 printk(KERN_ERR "nbd: device at index %d is going down\n",
2121 mutex_unlock(&nbd_index_mutex);
2123 if (!refcount_inc_not_zero(&nbd->config_refs)) {
2124 dev_err(nbd_to_dev(nbd),
2125 "not configured, cannot reconfigure\n");
2130 mutex_lock(&nbd->config_lock);
2131 config = nbd->config;
2132 if (!test_bit(NBD_RT_BOUND, &config->runtime_flags) ||
2134 dev_err(nbd_to_dev(nbd),
2135 "not configured, cannot reconfigure\n");
2140 ret = nbd_genl_size_set(info, nbd);
2144 if (info->attrs[NBD_ATTR_TIMEOUT])
2145 nbd_set_cmd_timeout(nbd,
2146 nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]));
2147 if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
2148 config->dead_conn_timeout =
2149 nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
2150 config->dead_conn_timeout *= HZ;
2152 if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
2153 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
2154 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
2155 if (!test_and_set_bit(NBD_DESTROY_ON_DISCONNECT,
2159 if (test_and_clear_bit(NBD_DESTROY_ON_DISCONNECT,
2161 refcount_inc(&nbd->refs);
2164 if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
2165 set_bit(NBD_RT_DISCONNECT_ON_CLOSE,
2166 &config->runtime_flags);
2168 clear_bit(NBD_RT_DISCONNECT_ON_CLOSE,
2169 &config->runtime_flags);
2173 if (info->attrs[NBD_ATTR_SOCKETS]) {
2174 struct nlattr *attr;
2177 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
2179 struct nlattr *socks[NBD_SOCK_MAX+1];
2181 if (nla_type(attr) != NBD_SOCK_ITEM) {
2182 printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
2186 ret = nla_parse_nested_deprecated(socks, NBD_SOCK_MAX,
2191 printk(KERN_ERR "nbd: error processing sock list\n");
2195 if (!socks[NBD_SOCK_FD])
2197 fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
2198 ret = nbd_reconnect_socket(nbd, fd);
2204 dev_info(nbd_to_dev(nbd), "reconnected socket\n");
2208 mutex_unlock(&nbd->config_lock);
2209 nbd_config_put(nbd);
2216 static const struct genl_small_ops nbd_connect_genl_ops[] = {
2218 .cmd = NBD_CMD_CONNECT,
2219 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2220 .doit = nbd_genl_connect,
2223 .cmd = NBD_CMD_DISCONNECT,
2224 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2225 .doit = nbd_genl_disconnect,
2228 .cmd = NBD_CMD_RECONFIGURE,
2229 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2230 .doit = nbd_genl_reconfigure,
2233 .cmd = NBD_CMD_STATUS,
2234 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2235 .doit = nbd_genl_status,
2239 static const struct genl_multicast_group nbd_mcast_grps[] = {
2240 { .name = NBD_GENL_MCAST_GROUP_NAME, },
2243 static struct genl_family nbd_genl_family __ro_after_init = {
2245 .name = NBD_GENL_FAMILY_NAME,
2246 .version = NBD_GENL_VERSION,
2247 .module = THIS_MODULE,
2248 .small_ops = nbd_connect_genl_ops,
2249 .n_small_ops = ARRAY_SIZE(nbd_connect_genl_ops),
2250 .maxattr = NBD_ATTR_MAX,
2251 .policy = nbd_attr_policy,
2252 .mcgrps = nbd_mcast_grps,
2253 .n_mcgrps = ARRAY_SIZE(nbd_mcast_grps),
2256 static int populate_nbd_status(struct nbd_device *nbd, struct sk_buff *reply)
2258 struct nlattr *dev_opt;
2262 /* This is a little racey, but for status it's ok. The
2263 * reason we don't take a ref here is because we can't
2264 * take a ref in the index == -1 case as we would need
2265 * to put under the nbd_index_mutex, which could
2266 * deadlock if we are configured to remove ourselves
2267 * once we're disconnected.
2269 if (refcount_read(&nbd->config_refs))
2271 dev_opt = nla_nest_start_noflag(reply, NBD_DEVICE_ITEM);
2274 ret = nla_put_u32(reply, NBD_DEVICE_INDEX, nbd->index);
2277 ret = nla_put_u8(reply, NBD_DEVICE_CONNECTED,
2281 nla_nest_end(reply, dev_opt);
2285 static int status_cb(int id, void *ptr, void *data)
2287 struct nbd_device *nbd = ptr;
2288 return populate_nbd_status(nbd, (struct sk_buff *)data);
2291 static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info)
2293 struct nlattr *dev_list;
2294 struct sk_buff *reply;
2300 if (info->attrs[NBD_ATTR_INDEX])
2301 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2303 mutex_lock(&nbd_index_mutex);
2305 msg_size = nla_total_size(nla_attr_size(sizeof(u32)) +
2306 nla_attr_size(sizeof(u8)));
2307 msg_size *= (index == -1) ? nbd_total_devices : 1;
2309 reply = genlmsg_new(msg_size, GFP_KERNEL);
2312 reply_head = genlmsg_put_reply(reply, info, &nbd_genl_family, 0,
2319 dev_list = nla_nest_start_noflag(reply, NBD_ATTR_DEVICE_LIST);
2321 ret = idr_for_each(&nbd_index_idr, &status_cb, reply);
2327 struct nbd_device *nbd;
2328 nbd = idr_find(&nbd_index_idr, index);
2330 ret = populate_nbd_status(nbd, reply);
2337 nla_nest_end(reply, dev_list);
2338 genlmsg_end(reply, reply_head);
2339 ret = genlmsg_reply(reply, info);
2341 mutex_unlock(&nbd_index_mutex);
2345 static void nbd_connect_reply(struct genl_info *info, int index)
2347 struct sk_buff *skb;
2351 skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2354 msg_head = genlmsg_put_reply(skb, info, &nbd_genl_family, 0,
2360 ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2365 genlmsg_end(skb, msg_head);
2366 genlmsg_reply(skb, info);
2369 static void nbd_mcast_index(int index)
2371 struct sk_buff *skb;
2375 skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2378 msg_head = genlmsg_put(skb, 0, 0, &nbd_genl_family, 0,
2384 ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2389 genlmsg_end(skb, msg_head);
2390 genlmsg_multicast(&nbd_genl_family, skb, 0, 0, GFP_KERNEL);
2393 static void nbd_dead_link_work(struct work_struct *work)
2395 struct link_dead_args *args = container_of(work, struct link_dead_args,
2397 nbd_mcast_index(args->index);
2401 static int __init nbd_init(void)
2405 BUILD_BUG_ON(sizeof(struct nbd_request) != 28);
2408 printk(KERN_ERR "nbd: max_part must be >= 0\n");
2414 part_shift = fls(max_part);
2417 * Adjust max_part according to part_shift as it is exported
2418 * to user space so that user can know the max number of
2419 * partition kernel should be able to manage.
2421 * Note that -1 is required because partition 0 is reserved
2422 * for the whole disk.
2424 max_part = (1UL << part_shift) - 1;
2427 if ((1UL << part_shift) > DISK_MAX_PARTS)
2430 if (nbds_max > 1UL << (MINORBITS - part_shift))
2433 if (register_blkdev(NBD_MAJOR, "nbd"))
2436 nbd_del_wq = alloc_workqueue("nbd-del", WQ_UNBOUND, 0);
2438 unregister_blkdev(NBD_MAJOR, "nbd");
2442 if (genl_register_family(&nbd_genl_family)) {
2443 destroy_workqueue(nbd_del_wq);
2444 unregister_blkdev(NBD_MAJOR, "nbd");
2449 for (i = 0; i < nbds_max; i++)
2454 static int nbd_exit_cb(int id, void *ptr, void *data)
2456 struct list_head *list = (struct list_head *)data;
2457 struct nbd_device *nbd = ptr;
2459 /* Skip nbd that is being removed asynchronously */
2460 if (refcount_read(&nbd->refs))
2461 list_add_tail(&nbd->list, list);
2466 static void __exit nbd_cleanup(void)
2468 struct nbd_device *nbd;
2469 LIST_HEAD(del_list);
2473 mutex_lock(&nbd_index_mutex);
2474 idr_for_each(&nbd_index_idr, &nbd_exit_cb, &del_list);
2475 mutex_unlock(&nbd_index_mutex);
2477 while (!list_empty(&del_list)) {
2478 nbd = list_first_entry(&del_list, struct nbd_device, list);
2479 list_del_init(&nbd->list);
2480 if (refcount_read(&nbd->refs) != 1)
2481 printk(KERN_ERR "nbd: possibly leaking a device\n");
2485 /* Also wait for nbd_dev_remove_work() completes */
2486 destroy_workqueue(nbd_del_wq);
2488 idr_destroy(&nbd_index_idr);
2489 genl_unregister_family(&nbd_genl_family);
2490 unregister_blkdev(NBD_MAJOR, "nbd");
2493 module_init(nbd_init);
2494 module_exit(nbd_cleanup);
2496 MODULE_DESCRIPTION("Network Block Device");
2497 MODULE_LICENSE("GPL");
2499 module_param(nbds_max, int, 0444);
2500 MODULE_PARM_DESC(nbds_max, "number of network block devices to initialize (default: 16)");
2501 module_param(max_part, int, 0444);
2502 MODULE_PARM_DESC(max_part, "number of partitions per device (default: 16)");