1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * Network block device - make block devices work over TCP
5 * Note that you can not swap over this thing, yet. Seems to work but
6 * deadlocks sometimes - you can not swap over TCP in general.
8 * Copyright 1997-2000, 2008 Pavel Machek <pavel@ucw.cz>
9 * Parts copyright 2001 Steven Whitehouse <steve@chygwyn.com>
11 * (part of code stolen from loop.c)
14 #include <linux/major.h>
16 #include <linux/blkdev.h>
17 #include <linux/module.h>
18 #include <linux/init.h>
19 #include <linux/sched.h>
20 #include <linux/sched/mm.h>
22 #include <linux/bio.h>
23 #include <linux/stat.h>
24 #include <linux/errno.h>
25 #include <linux/file.h>
26 #include <linux/ioctl.h>
27 #include <linux/mutex.h>
28 #include <linux/compiler.h>
29 #include <linux/completion.h>
30 #include <linux/err.h>
31 #include <linux/kernel.h>
32 #include <linux/slab.h>
34 #include <linux/net.h>
35 #include <linux/kthread.h>
36 #include <linux/types.h>
37 #include <linux/debugfs.h>
38 #include <linux/blk-mq.h>
40 #include <linux/uaccess.h>
41 #include <asm/types.h>
43 #include <linux/nbd.h>
44 #include <linux/nbd-netlink.h>
45 #include <net/genetlink.h>
47 #define CREATE_TRACE_POINTS
48 #include <trace/events/nbd.h>
50 static DEFINE_IDR(nbd_index_idr);
51 static DEFINE_MUTEX(nbd_index_mutex);
52 static int nbd_total_devices = 0;
57 struct request *pending;
64 struct recv_thread_args {
65 struct work_struct work;
66 struct nbd_device *nbd;
70 struct link_dead_args {
71 struct work_struct work;
75 #define NBD_RT_TIMEDOUT 0
76 #define NBD_RT_DISCONNECT_REQUESTED 1
77 #define NBD_RT_DISCONNECTED 2
78 #define NBD_RT_HAS_PID_FILE 3
79 #define NBD_RT_HAS_CONFIG_REF 4
80 #define NBD_RT_BOUND 5
81 #define NBD_RT_DISCONNECT_ON_CLOSE 6
83 #define NBD_DESTROY_ON_DISCONNECT 0
84 #define NBD_DISCONNECT_REQUESTED 1
88 unsigned long runtime_flags;
89 u64 dead_conn_timeout;
91 struct nbd_sock **socks;
93 atomic_t live_connections;
94 wait_queue_head_t conn_wait;
96 atomic_t recv_threads;
97 wait_queue_head_t recv_wq;
100 #if IS_ENABLED(CONFIG_DEBUG_FS)
101 struct dentry *dbg_dir;
106 struct blk_mq_tag_set tag_set;
109 refcount_t config_refs;
111 struct nbd_config *config;
112 struct mutex config_lock;
113 struct gendisk *disk;
114 struct workqueue_struct *recv_workq;
116 struct list_head list;
117 struct task_struct *task_recv;
118 struct task_struct *task_setup;
120 struct completion *destroy_complete;
124 #define NBD_CMD_REQUEUED 1
127 struct nbd_device *nbd;
137 #if IS_ENABLED(CONFIG_DEBUG_FS)
138 static struct dentry *nbd_dbg_dir;
141 #define nbd_name(nbd) ((nbd)->disk->disk_name)
143 #define NBD_MAGIC 0x68797548
145 #define NBD_DEF_BLKSIZE 1024
147 static unsigned int nbds_max = 16;
148 static int max_part = 16;
149 static int part_shift;
151 static int nbd_dev_dbg_init(struct nbd_device *nbd);
152 static void nbd_dev_dbg_close(struct nbd_device *nbd);
153 static void nbd_config_put(struct nbd_device *nbd);
154 static void nbd_connect_reply(struct genl_info *info, int index);
155 static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info);
156 static void nbd_dead_link_work(struct work_struct *work);
157 static void nbd_disconnect_and_put(struct nbd_device *nbd);
159 static inline struct device *nbd_to_dev(struct nbd_device *nbd)
161 return disk_to_dev(nbd->disk);
164 static void nbd_requeue_cmd(struct nbd_cmd *cmd)
166 struct request *req = blk_mq_rq_from_pdu(cmd);
168 if (!test_and_set_bit(NBD_CMD_REQUEUED, &cmd->flags))
169 blk_mq_requeue_request(req, true);
172 #define NBD_COOKIE_BITS 32
174 static u64 nbd_cmd_handle(struct nbd_cmd *cmd)
176 struct request *req = blk_mq_rq_from_pdu(cmd);
177 u32 tag = blk_mq_unique_tag(req);
178 u64 cookie = cmd->cmd_cookie;
180 return (cookie << NBD_COOKIE_BITS) | tag;
183 static u32 nbd_handle_to_tag(u64 handle)
188 static u32 nbd_handle_to_cookie(u64 handle)
190 return (u32)(handle >> NBD_COOKIE_BITS);
193 static const char *nbdcmd_to_ascii(int cmd)
196 case NBD_CMD_READ: return "read";
197 case NBD_CMD_WRITE: return "write";
198 case NBD_CMD_DISC: return "disconnect";
199 case NBD_CMD_FLUSH: return "flush";
200 case NBD_CMD_TRIM: return "trim/discard";
205 static ssize_t pid_show(struct device *dev,
206 struct device_attribute *attr, char *buf)
208 struct gendisk *disk = dev_to_disk(dev);
209 struct nbd_device *nbd = (struct nbd_device *)disk->private_data;
211 return sprintf(buf, "%d\n", task_pid_nr(nbd->task_recv));
214 static const struct device_attribute pid_attr = {
215 .attr = { .name = "pid", .mode = 0444},
219 static void nbd_dev_remove(struct nbd_device *nbd)
221 struct gendisk *disk = nbd->disk;
222 struct request_queue *q;
227 blk_cleanup_queue(q);
228 blk_mq_free_tag_set(&nbd->tag_set);
229 disk->private_data = NULL;
234 * Place this in the last just before the nbd is freed to
235 * make sure that the disk and the related kobject are also
236 * totally removed to avoid duplicate creation of the same
239 if (test_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags) && nbd->destroy_complete)
240 complete(nbd->destroy_complete);
245 static void nbd_put(struct nbd_device *nbd)
247 if (refcount_dec_and_mutex_lock(&nbd->refs,
249 idr_remove(&nbd_index_idr, nbd->index);
251 mutex_unlock(&nbd_index_mutex);
255 static int nbd_disconnected(struct nbd_config *config)
257 return test_bit(NBD_RT_DISCONNECTED, &config->runtime_flags) ||
258 test_bit(NBD_RT_DISCONNECT_REQUESTED, &config->runtime_flags);
261 static void nbd_mark_nsock_dead(struct nbd_device *nbd, struct nbd_sock *nsock,
264 if (!nsock->dead && notify && !nbd_disconnected(nbd->config)) {
265 struct link_dead_args *args;
266 args = kmalloc(sizeof(struct link_dead_args), GFP_NOIO);
268 INIT_WORK(&args->work, nbd_dead_link_work);
269 args->index = nbd->index;
270 queue_work(system_wq, &args->work);
274 kernel_sock_shutdown(nsock->sock, SHUT_RDWR);
275 if (atomic_dec_return(&nbd->config->live_connections) == 0) {
276 if (test_and_clear_bit(NBD_RT_DISCONNECT_REQUESTED,
277 &nbd->config->runtime_flags)) {
278 set_bit(NBD_RT_DISCONNECTED,
279 &nbd->config->runtime_flags);
280 dev_info(nbd_to_dev(nbd),
281 "Disconnected due to user request.\n");
286 nsock->pending = NULL;
290 static void nbd_size_clear(struct nbd_device *nbd)
292 if (nbd->config->bytesize) {
293 set_capacity(nbd->disk, 0);
294 kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
298 static void nbd_size_update(struct nbd_device *nbd, bool start)
300 struct nbd_config *config = nbd->config;
301 struct block_device *bdev = bdget_disk(nbd->disk, 0);
303 if (config->flags & NBD_FLAG_SEND_TRIM) {
304 nbd->disk->queue->limits.discard_granularity = config->blksize;
305 nbd->disk->queue->limits.discard_alignment = config->blksize;
306 blk_queue_max_discard_sectors(nbd->disk->queue, UINT_MAX);
308 blk_queue_logical_block_size(nbd->disk->queue, config->blksize);
309 blk_queue_physical_block_size(nbd->disk->queue, config->blksize);
310 set_capacity(nbd->disk, config->bytesize >> 9);
313 bd_set_size(bdev, config->bytesize);
315 set_blocksize(bdev, config->blksize);
317 bdev->bd_invalidated = 1;
320 kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
323 static void nbd_size_set(struct nbd_device *nbd, loff_t blocksize,
326 struct nbd_config *config = nbd->config;
327 config->blksize = blocksize;
328 config->bytesize = blocksize * nr_blocks;
329 if (nbd->task_recv != NULL)
330 nbd_size_update(nbd, false);
333 static void nbd_complete_rq(struct request *req)
335 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
337 dev_dbg(nbd_to_dev(cmd->nbd), "request %p: %s\n", req,
338 cmd->status ? "failed" : "done");
340 blk_mq_end_request(req, cmd->status);
344 * Forcibly shutdown the socket causing all listeners to error
346 static void sock_shutdown(struct nbd_device *nbd)
348 struct nbd_config *config = nbd->config;
351 if (config->num_connections == 0)
353 if (test_and_set_bit(NBD_RT_DISCONNECTED, &config->runtime_flags))
356 for (i = 0; i < config->num_connections; i++) {
357 struct nbd_sock *nsock = config->socks[i];
358 mutex_lock(&nsock->tx_lock);
359 nbd_mark_nsock_dead(nbd, nsock, 0);
360 mutex_unlock(&nsock->tx_lock);
362 dev_warn(disk_to_dev(nbd->disk), "shutting down sockets\n");
365 static u32 req_to_nbd_cmd_type(struct request *req)
367 switch (req_op(req)) {
371 return NBD_CMD_FLUSH;
373 return NBD_CMD_WRITE;
381 static enum blk_eh_timer_return nbd_xmit_timeout(struct request *req,
384 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
385 struct nbd_device *nbd = cmd->nbd;
386 struct nbd_config *config;
388 if (!mutex_trylock(&cmd->lock))
389 return BLK_EH_RESET_TIMER;
391 if (!refcount_inc_not_zero(&nbd->config_refs)) {
392 cmd->status = BLK_STS_TIMEOUT;
393 mutex_unlock(&cmd->lock);
396 config = nbd->config;
398 if (config->num_connections > 1) {
399 dev_err_ratelimited(nbd_to_dev(nbd),
400 "Connection timed out, retrying (%d/%d alive)\n",
401 atomic_read(&config->live_connections),
402 config->num_connections);
404 * Hooray we have more connections, requeue this IO, the submit
405 * path will put it on a real connection.
407 if (config->socks && config->num_connections > 1) {
408 if (cmd->index < config->num_connections) {
409 struct nbd_sock *nsock =
410 config->socks[cmd->index];
411 mutex_lock(&nsock->tx_lock);
412 /* We can have multiple outstanding requests, so
413 * we don't want to mark the nsock dead if we've
414 * already reconnected with a new socket, so
415 * only mark it dead if its the same socket we
418 if (cmd->cookie == nsock->cookie)
419 nbd_mark_nsock_dead(nbd, nsock, 1);
420 mutex_unlock(&nsock->tx_lock);
422 mutex_unlock(&cmd->lock);
423 nbd_requeue_cmd(cmd);
429 if (!nbd->tag_set.timeout) {
431 * Userspace sets timeout=0 to disable socket disconnection,
432 * so just warn and reset the timer.
435 dev_info(nbd_to_dev(nbd), "Possible stuck request %p: control (%s@%llu,%uB). Runtime %u seconds\n",
436 req, nbdcmd_to_ascii(req_to_nbd_cmd_type(req)),
437 (unsigned long long)blk_rq_pos(req) << 9,
438 blk_rq_bytes(req), (req->timeout / HZ) * cmd->retries);
440 mutex_unlock(&cmd->lock);
442 return BLK_EH_RESET_TIMER;
445 dev_err_ratelimited(nbd_to_dev(nbd), "Connection timed out\n");
446 set_bit(NBD_RT_TIMEDOUT, &config->runtime_flags);
447 cmd->status = BLK_STS_IOERR;
448 mutex_unlock(&cmd->lock);
452 blk_mq_complete_request(req);
457 * Send or receive packet.
459 static int sock_xmit(struct nbd_device *nbd, int index, int send,
460 struct iov_iter *iter, int msg_flags, int *sent)
462 struct nbd_config *config = nbd->config;
463 struct socket *sock = config->socks[index]->sock;
466 unsigned int noreclaim_flag;
468 if (unlikely(!sock)) {
469 dev_err_ratelimited(disk_to_dev(nbd->disk),
470 "Attempted %s on closed socket in sock_xmit\n",
471 (send ? "send" : "recv"));
475 msg.msg_iter = *iter;
477 noreclaim_flag = memalloc_noreclaim_save();
479 sock->sk->sk_allocation = GFP_NOIO | __GFP_MEMALLOC;
482 msg.msg_control = NULL;
483 msg.msg_controllen = 0;
484 msg.msg_flags = msg_flags | MSG_NOSIGNAL;
487 result = sock_sendmsg(sock, &msg);
489 result = sock_recvmsg(sock, &msg, msg.msg_flags);
493 result = -EPIPE; /* short read */
498 } while (msg_data_left(&msg));
500 memalloc_noreclaim_restore(noreclaim_flag);
506 * Different settings for sk->sk_sndtimeo can result in different return values
507 * if there is a signal pending when we enter sendmsg, because reasons?
509 static inline int was_interrupted(int result)
511 return result == -ERESTARTSYS || result == -EINTR;
514 /* always call with the tx_lock held */
515 static int nbd_send_cmd(struct nbd_device *nbd, struct nbd_cmd *cmd, int index)
517 struct request *req = blk_mq_rq_from_pdu(cmd);
518 struct nbd_config *config = nbd->config;
519 struct nbd_sock *nsock = config->socks[index];
521 struct nbd_request request = {.magic = htonl(NBD_REQUEST_MAGIC)};
522 struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
523 struct iov_iter from;
524 unsigned long size = blk_rq_bytes(req);
528 u32 nbd_cmd_flags = 0;
529 int sent = nsock->sent, skip = 0;
531 iov_iter_kvec(&from, WRITE, &iov, 1, sizeof(request));
533 type = req_to_nbd_cmd_type(req);
537 if (rq_data_dir(req) == WRITE &&
538 (config->flags & NBD_FLAG_READ_ONLY)) {
539 dev_err_ratelimited(disk_to_dev(nbd->disk),
540 "Write on read-only\n");
544 if (req->cmd_flags & REQ_FUA)
545 nbd_cmd_flags |= NBD_CMD_FLAG_FUA;
547 /* We did a partial send previously, and we at least sent the whole
548 * request struct, so just go and send the rest of the pages in the
552 if (sent >= sizeof(request)) {
553 skip = sent - sizeof(request);
555 /* initialize handle for tracing purposes */
556 handle = nbd_cmd_handle(cmd);
560 iov_iter_advance(&from, sent);
565 cmd->cookie = nsock->cookie;
567 request.type = htonl(type | nbd_cmd_flags);
568 if (type != NBD_CMD_FLUSH) {
569 request.from = cpu_to_be64((u64)blk_rq_pos(req) << 9);
570 request.len = htonl(size);
572 handle = nbd_cmd_handle(cmd);
573 memcpy(request.handle, &handle, sizeof(handle));
575 trace_nbd_send_request(&request, nbd->index, blk_mq_rq_from_pdu(cmd));
577 dev_dbg(nbd_to_dev(nbd), "request %p: sending control (%s@%llu,%uB)\n",
578 req, nbdcmd_to_ascii(type),
579 (unsigned long long)blk_rq_pos(req) << 9, blk_rq_bytes(req));
580 result = sock_xmit(nbd, index, 1, &from,
581 (type == NBD_CMD_WRITE) ? MSG_MORE : 0, &sent);
582 trace_nbd_header_sent(req, handle);
584 if (was_interrupted(result)) {
585 /* If we havne't sent anything we can just return BUSY,
586 * however if we have sent something we need to make
587 * sure we only allow this req to be sent until we are
591 nsock->pending = req;
594 set_bit(NBD_CMD_REQUEUED, &cmd->flags);
595 return BLK_STS_RESOURCE;
597 dev_err_ratelimited(disk_to_dev(nbd->disk),
598 "Send control failed (result %d)\n", result);
602 if (type != NBD_CMD_WRITE)
607 struct bio *next = bio->bi_next;
608 struct bvec_iter iter;
611 bio_for_each_segment(bvec, bio, iter) {
612 bool is_last = !next && bio_iter_last(bvec, iter);
613 int flags = is_last ? 0 : MSG_MORE;
615 dev_dbg(nbd_to_dev(nbd), "request %p: sending %d bytes data\n",
617 iov_iter_bvec(&from, WRITE, &bvec, 1, bvec.bv_len);
619 if (skip >= iov_iter_count(&from)) {
620 skip -= iov_iter_count(&from);
623 iov_iter_advance(&from, skip);
626 result = sock_xmit(nbd, index, 1, &from, flags, &sent);
628 if (was_interrupted(result)) {
629 /* We've already sent the header, we
630 * have no choice but to set pending and
633 nsock->pending = req;
635 set_bit(NBD_CMD_REQUEUED, &cmd->flags);
636 return BLK_STS_RESOURCE;
638 dev_err(disk_to_dev(nbd->disk),
639 "Send data failed (result %d)\n",
644 * The completion might already have come in,
645 * so break for the last one instead of letting
646 * the iterator do it. This prevents use-after-free
655 trace_nbd_payload_sent(req, handle);
656 nsock->pending = NULL;
661 /* NULL returned = something went wrong, inform userspace */
662 static struct nbd_cmd *nbd_read_stat(struct nbd_device *nbd, int index)
664 struct nbd_config *config = nbd->config;
666 struct nbd_reply reply;
668 struct request *req = NULL;
672 struct kvec iov = {.iov_base = &reply, .iov_len = sizeof(reply)};
677 iov_iter_kvec(&to, READ, &iov, 1, sizeof(reply));
678 result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
680 if (!nbd_disconnected(config))
681 dev_err(disk_to_dev(nbd->disk),
682 "Receive control failed (result %d)\n", result);
683 return ERR_PTR(result);
686 if (ntohl(reply.magic) != NBD_REPLY_MAGIC) {
687 dev_err(disk_to_dev(nbd->disk), "Wrong magic (0x%lx)\n",
688 (unsigned long)ntohl(reply.magic));
689 return ERR_PTR(-EPROTO);
692 memcpy(&handle, reply.handle, sizeof(handle));
693 tag = nbd_handle_to_tag(handle);
694 hwq = blk_mq_unique_tag_to_hwq(tag);
695 if (hwq < nbd->tag_set.nr_hw_queues)
696 req = blk_mq_tag_to_rq(nbd->tag_set.tags[hwq],
697 blk_mq_unique_tag_to_tag(tag));
698 if (!req || !blk_mq_request_started(req)) {
699 dev_err(disk_to_dev(nbd->disk), "Unexpected reply (%d) %p\n",
701 return ERR_PTR(-ENOENT);
703 trace_nbd_header_received(req, handle);
704 cmd = blk_mq_rq_to_pdu(req);
706 mutex_lock(&cmd->lock);
707 if (cmd->cmd_cookie != nbd_handle_to_cookie(handle)) {
708 dev_err(disk_to_dev(nbd->disk), "Double reply on req %p, cmd_cookie %u, handle cookie %u\n",
709 req, cmd->cmd_cookie, nbd_handle_to_cookie(handle));
713 if (cmd->status != BLK_STS_OK) {
714 dev_err(disk_to_dev(nbd->disk), "Command already handled %p\n",
719 if (test_bit(NBD_CMD_REQUEUED, &cmd->flags)) {
720 dev_err(disk_to_dev(nbd->disk), "Raced with timeout on req %p\n",
725 if (ntohl(reply.error)) {
726 dev_err(disk_to_dev(nbd->disk), "Other side returned error (%d)\n",
728 cmd->status = BLK_STS_IOERR;
732 dev_dbg(nbd_to_dev(nbd), "request %p: got reply\n", req);
733 if (rq_data_dir(req) != WRITE) {
734 struct req_iterator iter;
737 rq_for_each_segment(bvec, req, iter) {
738 iov_iter_bvec(&to, READ, &bvec, 1, bvec.bv_len);
739 result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
741 dev_err(disk_to_dev(nbd->disk), "Receive data failed (result %d)\n",
744 * If we've disconnected or we only have 1
745 * connection then we need to make sure we
746 * complete this request, otherwise error out
747 * and let the timeout stuff handle resubmitting
748 * this request onto another connection.
750 if (nbd_disconnected(config) ||
751 config->num_connections <= 1) {
752 cmd->status = BLK_STS_IOERR;
758 dev_dbg(nbd_to_dev(nbd), "request %p: got %d bytes data\n",
763 trace_nbd_payload_received(req, handle);
764 mutex_unlock(&cmd->lock);
765 return ret ? ERR_PTR(ret) : cmd;
768 static void recv_work(struct work_struct *work)
770 struct recv_thread_args *args = container_of(work,
771 struct recv_thread_args,
773 struct nbd_device *nbd = args->nbd;
774 struct nbd_config *config = nbd->config;
778 cmd = nbd_read_stat(nbd, args->index);
780 struct nbd_sock *nsock = config->socks[args->index];
782 mutex_lock(&nsock->tx_lock);
783 nbd_mark_nsock_dead(nbd, nsock, 1);
784 mutex_unlock(&nsock->tx_lock);
788 blk_mq_complete_request(blk_mq_rq_from_pdu(cmd));
791 atomic_dec(&config->recv_threads);
792 wake_up(&config->recv_wq);
796 static bool nbd_clear_req(struct request *req, void *data, bool reserved)
798 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
800 /* don't abort one completed request */
801 if (blk_mq_request_completed(req))
804 mutex_lock(&cmd->lock);
805 cmd->status = BLK_STS_IOERR;
806 mutex_unlock(&cmd->lock);
808 blk_mq_complete_request(req);
812 static void nbd_clear_que(struct nbd_device *nbd)
814 blk_mq_quiesce_queue(nbd->disk->queue);
815 blk_mq_tagset_busy_iter(&nbd->tag_set, nbd_clear_req, NULL);
816 blk_mq_unquiesce_queue(nbd->disk->queue);
817 dev_dbg(disk_to_dev(nbd->disk), "queue cleared\n");
820 static int find_fallback(struct nbd_device *nbd, int index)
822 struct nbd_config *config = nbd->config;
824 struct nbd_sock *nsock = config->socks[index];
825 int fallback = nsock->fallback_index;
827 if (test_bit(NBD_RT_DISCONNECTED, &config->runtime_flags))
830 if (config->num_connections <= 1) {
831 dev_err_ratelimited(disk_to_dev(nbd->disk),
832 "Attempted send on invalid socket\n");
836 if (fallback >= 0 && fallback < config->num_connections &&
837 !config->socks[fallback]->dead)
840 if (nsock->fallback_index < 0 ||
841 nsock->fallback_index >= config->num_connections ||
842 config->socks[nsock->fallback_index]->dead) {
844 for (i = 0; i < config->num_connections; i++) {
847 if (!config->socks[i]->dead) {
852 nsock->fallback_index = new_index;
854 dev_err_ratelimited(disk_to_dev(nbd->disk),
855 "Dead connection, failed to find a fallback\n");
859 new_index = nsock->fallback_index;
863 static int wait_for_reconnect(struct nbd_device *nbd)
865 struct nbd_config *config = nbd->config;
866 if (!config->dead_conn_timeout)
869 if (!wait_event_timeout(config->conn_wait,
870 test_bit(NBD_RT_DISCONNECTED,
871 &config->runtime_flags) ||
872 atomic_read(&config->live_connections) > 0,
873 config->dead_conn_timeout))
876 return !test_bit(NBD_RT_DISCONNECTED, &config->runtime_flags);
879 static int nbd_handle_cmd(struct nbd_cmd *cmd, int index)
881 struct request *req = blk_mq_rq_from_pdu(cmd);
882 struct nbd_device *nbd = cmd->nbd;
883 struct nbd_config *config;
884 struct nbd_sock *nsock;
887 if (!refcount_inc_not_zero(&nbd->config_refs)) {
888 dev_err_ratelimited(disk_to_dev(nbd->disk),
889 "Socks array is empty\n");
890 blk_mq_start_request(req);
893 config = nbd->config;
895 if (index >= config->num_connections) {
896 dev_err_ratelimited(disk_to_dev(nbd->disk),
897 "Attempted send on invalid socket\n");
899 blk_mq_start_request(req);
902 cmd->status = BLK_STS_OK;
904 nsock = config->socks[index];
905 mutex_lock(&nsock->tx_lock);
907 int old_index = index;
908 index = find_fallback(nbd, index);
909 mutex_unlock(&nsock->tx_lock);
911 if (wait_for_reconnect(nbd)) {
915 /* All the sockets should already be down at this point,
916 * we just want to make sure that DISCONNECTED is set so
917 * any requests that come in that were queue'ed waiting
918 * for the reconnect timer don't trigger the timer again
919 * and instead just error out.
923 blk_mq_start_request(req);
929 /* Handle the case that we have a pending request that was partially
930 * transmitted that _has_ to be serviced first. We need to call requeue
931 * here so that it gets put _after_ the request that is already on the
934 blk_mq_start_request(req);
935 if (unlikely(nsock->pending && nsock->pending != req)) {
936 nbd_requeue_cmd(cmd);
941 * Some failures are related to the link going down, so anything that
942 * returns EAGAIN can be retried on a different socket.
944 ret = nbd_send_cmd(nbd, cmd, index);
945 if (ret == -EAGAIN) {
946 dev_err_ratelimited(disk_to_dev(nbd->disk),
947 "Request send failed, requeueing\n");
948 nbd_mark_nsock_dead(nbd, nsock, 1);
949 nbd_requeue_cmd(cmd);
953 mutex_unlock(&nsock->tx_lock);
958 static blk_status_t nbd_queue_rq(struct blk_mq_hw_ctx *hctx,
959 const struct blk_mq_queue_data *bd)
961 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(bd->rq);
965 * Since we look at the bio's to send the request over the network we
966 * need to make sure the completion work doesn't mark this request done
967 * before we are done doing our send. This keeps us from dereferencing
968 * freed data if we have particularly fast completions (ie we get the
969 * completion before we exit sock_xmit on the last bvec) or in the case
970 * that the server is misbehaving (or there was an error) before we're
971 * done sending everything over the wire.
973 mutex_lock(&cmd->lock);
974 clear_bit(NBD_CMD_REQUEUED, &cmd->flags);
976 /* We can be called directly from the user space process, which means we
977 * could possibly have signals pending so our sendmsg will fail. In
978 * this case we need to return that we are busy, otherwise error out as
981 ret = nbd_handle_cmd(cmd, hctx->queue_num);
986 mutex_unlock(&cmd->lock);
991 static struct socket *nbd_get_socket(struct nbd_device *nbd, unsigned long fd,
997 sock = sockfd_lookup(fd, err);
1001 if (sock->ops->shutdown == sock_no_shutdown) {
1002 dev_err(disk_to_dev(nbd->disk), "Unsupported socket: shutdown callout must be supported.\n");
1011 static int nbd_add_socket(struct nbd_device *nbd, unsigned long arg,
1014 struct nbd_config *config = nbd->config;
1015 struct socket *sock;
1016 struct nbd_sock **socks;
1017 struct nbd_sock *nsock;
1020 sock = nbd_get_socket(nbd, arg, &err);
1025 * We need to make sure we don't get any errant requests while we're
1026 * reallocating the ->socks array.
1028 blk_mq_freeze_queue(nbd->disk->queue);
1030 if (!netlink && !nbd->task_setup &&
1031 !test_bit(NBD_RT_BOUND, &config->runtime_flags))
1032 nbd->task_setup = current;
1035 (nbd->task_setup != current ||
1036 test_bit(NBD_RT_BOUND, &config->runtime_flags))) {
1037 dev_err(disk_to_dev(nbd->disk),
1038 "Device being setup by another task");
1043 nsock = kzalloc(sizeof(*nsock), GFP_KERNEL);
1049 socks = krealloc(config->socks, (config->num_connections + 1) *
1050 sizeof(struct nbd_sock *), GFP_KERNEL);
1057 config->socks = socks;
1059 nsock->fallback_index = -1;
1060 nsock->dead = false;
1061 mutex_init(&nsock->tx_lock);
1063 nsock->pending = NULL;
1066 socks[config->num_connections++] = nsock;
1067 atomic_inc(&config->live_connections);
1068 blk_mq_unfreeze_queue(nbd->disk->queue);
1073 blk_mq_unfreeze_queue(nbd->disk->queue);
1078 static int nbd_reconnect_socket(struct nbd_device *nbd, unsigned long arg)
1080 struct nbd_config *config = nbd->config;
1081 struct socket *sock, *old;
1082 struct recv_thread_args *args;
1086 sock = nbd_get_socket(nbd, arg, &err);
1090 args = kzalloc(sizeof(*args), GFP_KERNEL);
1096 for (i = 0; i < config->num_connections; i++) {
1097 struct nbd_sock *nsock = config->socks[i];
1102 mutex_lock(&nsock->tx_lock);
1104 mutex_unlock(&nsock->tx_lock);
1107 sk_set_memalloc(sock->sk);
1108 if (nbd->tag_set.timeout)
1109 sock->sk->sk_sndtimeo = nbd->tag_set.timeout;
1110 atomic_inc(&config->recv_threads);
1111 refcount_inc(&nbd->config_refs);
1113 nsock->fallback_index = -1;
1115 nsock->dead = false;
1116 INIT_WORK(&args->work, recv_work);
1120 mutex_unlock(&nsock->tx_lock);
1123 clear_bit(NBD_RT_DISCONNECTED, &config->runtime_flags);
1125 /* We take the tx_mutex in an error path in the recv_work, so we
1126 * need to queue_work outside of the tx_mutex.
1128 queue_work(nbd->recv_workq, &args->work);
1130 atomic_inc(&config->live_connections);
1131 wake_up(&config->conn_wait);
1139 static void nbd_bdev_reset(struct block_device *bdev)
1141 if (bdev->bd_openers > 1)
1143 bd_set_size(bdev, 0);
1146 static void nbd_parse_flags(struct nbd_device *nbd)
1148 struct nbd_config *config = nbd->config;
1149 if (config->flags & NBD_FLAG_READ_ONLY)
1150 set_disk_ro(nbd->disk, true);
1152 set_disk_ro(nbd->disk, false);
1153 if (config->flags & NBD_FLAG_SEND_TRIM)
1154 blk_queue_flag_set(QUEUE_FLAG_DISCARD, nbd->disk->queue);
1155 if (config->flags & NBD_FLAG_SEND_FLUSH) {
1156 if (config->flags & NBD_FLAG_SEND_FUA)
1157 blk_queue_write_cache(nbd->disk->queue, true, true);
1159 blk_queue_write_cache(nbd->disk->queue, true, false);
1162 blk_queue_write_cache(nbd->disk->queue, false, false);
1165 static void send_disconnects(struct nbd_device *nbd)
1167 struct nbd_config *config = nbd->config;
1168 struct nbd_request request = {
1169 .magic = htonl(NBD_REQUEST_MAGIC),
1170 .type = htonl(NBD_CMD_DISC),
1172 struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
1173 struct iov_iter from;
1176 for (i = 0; i < config->num_connections; i++) {
1177 struct nbd_sock *nsock = config->socks[i];
1179 iov_iter_kvec(&from, WRITE, &iov, 1, sizeof(request));
1180 mutex_lock(&nsock->tx_lock);
1181 ret = sock_xmit(nbd, i, 1, &from, 0, NULL);
1183 dev_err(disk_to_dev(nbd->disk),
1184 "Send disconnect failed %d\n", ret);
1185 mutex_unlock(&nsock->tx_lock);
1189 static int nbd_disconnect(struct nbd_device *nbd)
1191 struct nbd_config *config = nbd->config;
1193 dev_info(disk_to_dev(nbd->disk), "NBD_DISCONNECT\n");
1194 set_bit(NBD_RT_DISCONNECT_REQUESTED, &config->runtime_flags);
1195 set_bit(NBD_DISCONNECT_REQUESTED, &nbd->flags);
1196 send_disconnects(nbd);
1200 static void nbd_clear_sock(struct nbd_device *nbd)
1204 nbd->task_setup = NULL;
1207 static void nbd_config_put(struct nbd_device *nbd)
1209 if (refcount_dec_and_mutex_lock(&nbd->config_refs,
1210 &nbd->config_lock)) {
1211 struct nbd_config *config = nbd->config;
1212 nbd_dev_dbg_close(nbd);
1213 nbd_size_clear(nbd);
1214 if (test_and_clear_bit(NBD_RT_HAS_PID_FILE,
1215 &config->runtime_flags))
1216 device_remove_file(disk_to_dev(nbd->disk), &pid_attr);
1217 nbd->task_recv = NULL;
1218 nbd_clear_sock(nbd);
1219 if (config->num_connections) {
1221 for (i = 0; i < config->num_connections; i++) {
1222 sockfd_put(config->socks[i]->sock);
1223 kfree(config->socks[i]);
1225 kfree(config->socks);
1230 if (nbd->recv_workq)
1231 destroy_workqueue(nbd->recv_workq);
1232 nbd->recv_workq = NULL;
1234 nbd->tag_set.timeout = 0;
1235 nbd->disk->queue->limits.discard_granularity = 0;
1236 nbd->disk->queue->limits.discard_alignment = 0;
1237 blk_queue_max_discard_sectors(nbd->disk->queue, UINT_MAX);
1238 blk_queue_flag_clear(QUEUE_FLAG_DISCARD, nbd->disk->queue);
1240 mutex_unlock(&nbd->config_lock);
1242 module_put(THIS_MODULE);
1246 static int nbd_start_device(struct nbd_device *nbd)
1248 struct nbd_config *config = nbd->config;
1249 int num_connections = config->num_connections;
1256 if (num_connections > 1 &&
1257 !(config->flags & NBD_FLAG_CAN_MULTI_CONN)) {
1258 dev_err(disk_to_dev(nbd->disk), "server does not support multiple connections per device.\n");
1262 nbd->recv_workq = alloc_workqueue("knbd%d-recv",
1263 WQ_MEM_RECLAIM | WQ_HIGHPRI |
1264 WQ_UNBOUND, 0, nbd->index);
1265 if (!nbd->recv_workq) {
1266 dev_err(disk_to_dev(nbd->disk), "Could not allocate knbd recv work queue.\n");
1270 blk_mq_update_nr_hw_queues(&nbd->tag_set, config->num_connections);
1271 nbd->task_recv = current;
1273 nbd_parse_flags(nbd);
1275 error = device_create_file(disk_to_dev(nbd->disk), &pid_attr);
1277 dev_err(disk_to_dev(nbd->disk), "device_create_file failed!\n");
1280 set_bit(NBD_RT_HAS_PID_FILE, &config->runtime_flags);
1282 nbd_dev_dbg_init(nbd);
1283 for (i = 0; i < num_connections; i++) {
1284 struct recv_thread_args *args;
1286 args = kzalloc(sizeof(*args), GFP_KERNEL);
1290 * If num_connections is m (2 < m),
1291 * and NO.1 ~ NO.n(1 < n < m) kzallocs are successful.
1292 * But NO.(n + 1) failed. We still have n recv threads.
1293 * So, add flush_workqueue here to prevent recv threads
1294 * dropping the last config_refs and trying to destroy
1295 * the workqueue from inside the workqueue.
1298 flush_workqueue(nbd->recv_workq);
1301 sk_set_memalloc(config->socks[i]->sock->sk);
1302 if (nbd->tag_set.timeout)
1303 config->socks[i]->sock->sk->sk_sndtimeo =
1304 nbd->tag_set.timeout;
1305 atomic_inc(&config->recv_threads);
1306 refcount_inc(&nbd->config_refs);
1307 INIT_WORK(&args->work, recv_work);
1310 queue_work(nbd->recv_workq, &args->work);
1312 nbd_size_update(nbd, true);
1316 static int nbd_start_device_ioctl(struct nbd_device *nbd, struct block_device *bdev)
1318 struct nbd_config *config = nbd->config;
1321 ret = nbd_start_device(nbd);
1326 bdev->bd_invalidated = 1;
1327 mutex_unlock(&nbd->config_lock);
1328 ret = wait_event_interruptible(config->recv_wq,
1329 atomic_read(&config->recv_threads) == 0);
1335 flush_workqueue(nbd->recv_workq);
1336 mutex_lock(&nbd->config_lock);
1337 nbd_bdev_reset(bdev);
1338 /* user requested, ignore socket errors */
1339 if (test_bit(NBD_RT_DISCONNECT_REQUESTED, &config->runtime_flags))
1341 if (test_bit(NBD_RT_TIMEDOUT, &config->runtime_flags))
1346 static void nbd_clear_sock_ioctl(struct nbd_device *nbd,
1347 struct block_device *bdev)
1349 nbd_clear_sock(nbd);
1350 __invalidate_device(bdev, true);
1351 nbd_bdev_reset(bdev);
1352 if (test_and_clear_bit(NBD_RT_HAS_CONFIG_REF,
1353 &nbd->config->runtime_flags))
1354 nbd_config_put(nbd);
1357 static bool nbd_is_valid_blksize(unsigned long blksize)
1359 if (!blksize || !is_power_of_2(blksize) || blksize < 512 ||
1360 blksize > PAGE_SIZE)
1365 static void nbd_set_cmd_timeout(struct nbd_device *nbd, u64 timeout)
1367 nbd->tag_set.timeout = timeout * HZ;
1369 blk_queue_rq_timeout(nbd->disk->queue, timeout * HZ);
1371 blk_queue_rq_timeout(nbd->disk->queue, 30 * HZ);
1374 /* Must be called with config_lock held */
1375 static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
1376 unsigned int cmd, unsigned long arg)
1378 struct nbd_config *config = nbd->config;
1381 case NBD_DISCONNECT:
1382 return nbd_disconnect(nbd);
1383 case NBD_CLEAR_SOCK:
1384 nbd_clear_sock_ioctl(nbd, bdev);
1387 return nbd_add_socket(nbd, arg, false);
1388 case NBD_SET_BLKSIZE:
1390 arg = NBD_DEF_BLKSIZE;
1391 if (!nbd_is_valid_blksize(arg))
1393 nbd_size_set(nbd, arg,
1394 div_s64(config->bytesize, arg));
1397 nbd_size_set(nbd, config->blksize,
1398 div_s64(arg, config->blksize));
1400 case NBD_SET_SIZE_BLOCKS:
1401 nbd_size_set(nbd, config->blksize, arg);
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 if (!try_module_get(THIS_MODULE))
1463 return ERR_PTR(-ENODEV);
1465 config = kzalloc(sizeof(struct nbd_config), GFP_NOFS);
1467 module_put(THIS_MODULE);
1468 return ERR_PTR(-ENOMEM);
1471 atomic_set(&config->recv_threads, 0);
1472 init_waitqueue_head(&config->recv_wq);
1473 init_waitqueue_head(&config->conn_wait);
1474 config->blksize = NBD_DEF_BLKSIZE;
1475 atomic_set(&config->live_connections, 0);
1479 static int nbd_open(struct block_device *bdev, fmode_t mode)
1481 struct nbd_device *nbd;
1484 mutex_lock(&nbd_index_mutex);
1485 nbd = bdev->bd_disk->private_data;
1490 if (!refcount_inc_not_zero(&nbd->refs)) {
1494 if (!refcount_inc_not_zero(&nbd->config_refs)) {
1495 struct nbd_config *config;
1497 mutex_lock(&nbd->config_lock);
1498 if (refcount_inc_not_zero(&nbd->config_refs)) {
1499 mutex_unlock(&nbd->config_lock);
1502 config = nbd_alloc_config();
1503 if (IS_ERR(config)) {
1504 ret = PTR_ERR(config);
1505 mutex_unlock(&nbd->config_lock);
1508 nbd->config = config;
1509 refcount_set(&nbd->config_refs, 1);
1510 refcount_inc(&nbd->refs);
1511 mutex_unlock(&nbd->config_lock);
1512 bdev->bd_invalidated = 1;
1513 } else if (nbd_disconnected(nbd->config)) {
1514 bdev->bd_invalidated = 1;
1517 mutex_unlock(&nbd_index_mutex);
1521 static void nbd_release(struct gendisk *disk, fmode_t mode)
1523 struct nbd_device *nbd = disk->private_data;
1524 struct block_device *bdev = bdget_disk(disk, 0);
1526 if (test_bit(NBD_RT_DISCONNECT_ON_CLOSE, &nbd->config->runtime_flags) &&
1527 bdev->bd_openers == 0)
1528 nbd_disconnect_and_put(nbd);
1531 nbd_config_put(nbd);
1535 static const struct block_device_operations nbd_fops =
1537 .owner = THIS_MODULE,
1539 .release = nbd_release,
1541 .compat_ioctl = nbd_ioctl,
1544 #if IS_ENABLED(CONFIG_DEBUG_FS)
1546 static int nbd_dbg_tasks_show(struct seq_file *s, void *unused)
1548 struct nbd_device *nbd = s->private;
1551 seq_printf(s, "recv: %d\n", task_pid_nr(nbd->task_recv));
1556 static int nbd_dbg_tasks_open(struct inode *inode, struct file *file)
1558 return single_open(file, nbd_dbg_tasks_show, inode->i_private);
1561 static const struct file_operations nbd_dbg_tasks_ops = {
1562 .open = nbd_dbg_tasks_open,
1564 .llseek = seq_lseek,
1565 .release = single_release,
1568 static int nbd_dbg_flags_show(struct seq_file *s, void *unused)
1570 struct nbd_device *nbd = s->private;
1571 u32 flags = nbd->config->flags;
1573 seq_printf(s, "Hex: 0x%08x\n\n", flags);
1575 seq_puts(s, "Known flags:\n");
1577 if (flags & NBD_FLAG_HAS_FLAGS)
1578 seq_puts(s, "NBD_FLAG_HAS_FLAGS\n");
1579 if (flags & NBD_FLAG_READ_ONLY)
1580 seq_puts(s, "NBD_FLAG_READ_ONLY\n");
1581 if (flags & NBD_FLAG_SEND_FLUSH)
1582 seq_puts(s, "NBD_FLAG_SEND_FLUSH\n");
1583 if (flags & NBD_FLAG_SEND_FUA)
1584 seq_puts(s, "NBD_FLAG_SEND_FUA\n");
1585 if (flags & NBD_FLAG_SEND_TRIM)
1586 seq_puts(s, "NBD_FLAG_SEND_TRIM\n");
1591 static int nbd_dbg_flags_open(struct inode *inode, struct file *file)
1593 return single_open(file, nbd_dbg_flags_show, inode->i_private);
1596 static const struct file_operations nbd_dbg_flags_ops = {
1597 .open = nbd_dbg_flags_open,
1599 .llseek = seq_lseek,
1600 .release = single_release,
1603 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1606 struct nbd_config *config = nbd->config;
1611 dir = debugfs_create_dir(nbd_name(nbd), nbd_dbg_dir);
1613 dev_err(nbd_to_dev(nbd), "Failed to create debugfs dir for '%s'\n",
1617 config->dbg_dir = dir;
1619 debugfs_create_file("tasks", 0444, dir, nbd, &nbd_dbg_tasks_ops);
1620 debugfs_create_u64("size_bytes", 0444, dir, &config->bytesize);
1621 debugfs_create_u32("timeout", 0444, dir, &nbd->tag_set.timeout);
1622 debugfs_create_u64("blocksize", 0444, dir, &config->blksize);
1623 debugfs_create_file("flags", 0444, dir, nbd, &nbd_dbg_flags_ops);
1628 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1630 debugfs_remove_recursive(nbd->config->dbg_dir);
1633 static int nbd_dbg_init(void)
1635 struct dentry *dbg_dir;
1637 dbg_dir = debugfs_create_dir("nbd", NULL);
1641 nbd_dbg_dir = dbg_dir;
1646 static void nbd_dbg_close(void)
1648 debugfs_remove_recursive(nbd_dbg_dir);
1651 #else /* IS_ENABLED(CONFIG_DEBUG_FS) */
1653 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1658 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1662 static int nbd_dbg_init(void)
1667 static void nbd_dbg_close(void)
1673 static int nbd_init_request(struct blk_mq_tag_set *set, struct request *rq,
1674 unsigned int hctx_idx, unsigned int numa_node)
1676 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(rq);
1677 cmd->nbd = set->driver_data;
1679 mutex_init(&cmd->lock);
1683 static const struct blk_mq_ops nbd_mq_ops = {
1684 .queue_rq = nbd_queue_rq,
1685 .complete = nbd_complete_rq,
1686 .init_request = nbd_init_request,
1687 .timeout = nbd_xmit_timeout,
1690 static int nbd_dev_add(int index)
1692 struct nbd_device *nbd;
1693 struct gendisk *disk;
1694 struct request_queue *q;
1697 nbd = kzalloc(sizeof(struct nbd_device), GFP_KERNEL);
1701 disk = alloc_disk(1 << part_shift);
1706 err = idr_alloc(&nbd_index_idr, nbd, index, index + 1,
1711 err = idr_alloc(&nbd_index_idr, nbd, 0, 0, GFP_KERNEL);
1720 nbd->tag_set.ops = &nbd_mq_ops;
1721 nbd->tag_set.nr_hw_queues = 1;
1722 nbd->tag_set.queue_depth = 128;
1723 nbd->tag_set.numa_node = NUMA_NO_NODE;
1724 nbd->tag_set.cmd_size = sizeof(struct nbd_cmd);
1725 nbd->tag_set.flags = BLK_MQ_F_SHOULD_MERGE |
1727 nbd->tag_set.driver_data = nbd;
1728 nbd->destroy_complete = NULL;
1730 err = blk_mq_alloc_tag_set(&nbd->tag_set);
1734 q = blk_mq_init_queue(&nbd->tag_set);
1742 * Tell the block layer that we are not a rotational device
1744 blk_queue_flag_set(QUEUE_FLAG_NONROT, disk->queue);
1745 blk_queue_flag_clear(QUEUE_FLAG_ADD_RANDOM, disk->queue);
1746 disk->queue->limits.discard_granularity = 0;
1747 disk->queue->limits.discard_alignment = 0;
1748 blk_queue_max_discard_sectors(disk->queue, 0);
1749 blk_queue_max_segment_size(disk->queue, UINT_MAX);
1750 blk_queue_max_segments(disk->queue, USHRT_MAX);
1751 blk_queue_max_hw_sectors(disk->queue, 65536);
1752 disk->queue->limits.max_sectors = 256;
1754 mutex_init(&nbd->config_lock);
1755 refcount_set(&nbd->config_refs, 0);
1756 refcount_set(&nbd->refs, 1);
1757 INIT_LIST_HEAD(&nbd->list);
1758 disk->major = NBD_MAJOR;
1759 disk->first_minor = index << part_shift;
1760 disk->fops = &nbd_fops;
1761 disk->private_data = nbd;
1762 sprintf(disk->disk_name, "nbd%d", index);
1764 nbd_total_devices++;
1768 blk_mq_free_tag_set(&nbd->tag_set);
1770 idr_remove(&nbd_index_idr, index);
1779 static int find_free_cb(int id, void *ptr, void *data)
1781 struct nbd_device *nbd = ptr;
1782 struct nbd_device **found = data;
1784 if (!refcount_read(&nbd->config_refs)) {
1791 /* Netlink interface. */
1792 static const struct nla_policy nbd_attr_policy[NBD_ATTR_MAX + 1] = {
1793 [NBD_ATTR_INDEX] = { .type = NLA_U32 },
1794 [NBD_ATTR_SIZE_BYTES] = { .type = NLA_U64 },
1795 [NBD_ATTR_BLOCK_SIZE_BYTES] = { .type = NLA_U64 },
1796 [NBD_ATTR_TIMEOUT] = { .type = NLA_U64 },
1797 [NBD_ATTR_SERVER_FLAGS] = { .type = NLA_U64 },
1798 [NBD_ATTR_CLIENT_FLAGS] = { .type = NLA_U64 },
1799 [NBD_ATTR_SOCKETS] = { .type = NLA_NESTED},
1800 [NBD_ATTR_DEAD_CONN_TIMEOUT] = { .type = NLA_U64 },
1801 [NBD_ATTR_DEVICE_LIST] = { .type = NLA_NESTED},
1804 static const struct nla_policy nbd_sock_policy[NBD_SOCK_MAX + 1] = {
1805 [NBD_SOCK_FD] = { .type = NLA_U32 },
1808 /* We don't use this right now since we don't parse the incoming list, but we
1809 * still want it here so userspace knows what to expect.
1811 static const struct nla_policy __attribute__((unused))
1812 nbd_device_policy[NBD_DEVICE_ATTR_MAX + 1] = {
1813 [NBD_DEVICE_INDEX] = { .type = NLA_U32 },
1814 [NBD_DEVICE_CONNECTED] = { .type = NLA_U8 },
1817 static int nbd_genl_size_set(struct genl_info *info, struct nbd_device *nbd)
1819 struct nbd_config *config = nbd->config;
1820 u64 bsize = config->blksize;
1821 u64 bytes = config->bytesize;
1823 if (info->attrs[NBD_ATTR_SIZE_BYTES])
1824 bytes = nla_get_u64(info->attrs[NBD_ATTR_SIZE_BYTES]);
1826 if (info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]) {
1827 bsize = nla_get_u64(info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]);
1829 bsize = NBD_DEF_BLKSIZE;
1830 if (!nbd_is_valid_blksize(bsize)) {
1831 printk(KERN_ERR "Invalid block size %llu\n", bsize);
1836 if (bytes != config->bytesize || bsize != config->blksize)
1837 nbd_size_set(nbd, bsize, div64_u64(bytes, bsize));
1841 static int nbd_genl_connect(struct sk_buff *skb, struct genl_info *info)
1843 DECLARE_COMPLETION_ONSTACK(destroy_complete);
1844 struct nbd_device *nbd = NULL;
1845 struct nbd_config *config;
1848 bool put_dev = false;
1850 if (!netlink_capable(skb, CAP_SYS_ADMIN))
1853 if (info->attrs[NBD_ATTR_INDEX])
1854 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1855 if (!info->attrs[NBD_ATTR_SOCKETS]) {
1856 printk(KERN_ERR "nbd: must specify at least one socket\n");
1859 if (!info->attrs[NBD_ATTR_SIZE_BYTES]) {
1860 printk(KERN_ERR "nbd: must specify a size in bytes for the device\n");
1864 mutex_lock(&nbd_index_mutex);
1866 ret = idr_for_each(&nbd_index_idr, &find_free_cb, &nbd);
1869 new_index = nbd_dev_add(-1);
1870 if (new_index < 0) {
1871 mutex_unlock(&nbd_index_mutex);
1872 printk(KERN_ERR "nbd: failed to add new device\n");
1875 nbd = idr_find(&nbd_index_idr, new_index);
1878 nbd = idr_find(&nbd_index_idr, index);
1880 ret = nbd_dev_add(index);
1882 mutex_unlock(&nbd_index_mutex);
1883 printk(KERN_ERR "nbd: failed to add new device\n");
1886 nbd = idr_find(&nbd_index_idr, index);
1890 printk(KERN_ERR "nbd: couldn't find device at index %d\n",
1892 mutex_unlock(&nbd_index_mutex);
1896 if (test_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags) &&
1897 test_bit(NBD_DISCONNECT_REQUESTED, &nbd->flags)) {
1898 nbd->destroy_complete = &destroy_complete;
1899 mutex_unlock(&nbd_index_mutex);
1901 /* Wait untill the the nbd stuff is totally destroyed */
1902 wait_for_completion(&destroy_complete);
1906 if (!refcount_inc_not_zero(&nbd->refs)) {
1907 mutex_unlock(&nbd_index_mutex);
1910 printk(KERN_ERR "nbd: device at index %d is going down\n",
1914 mutex_unlock(&nbd_index_mutex);
1916 mutex_lock(&nbd->config_lock);
1917 if (refcount_read(&nbd->config_refs)) {
1918 mutex_unlock(&nbd->config_lock);
1922 printk(KERN_ERR "nbd: nbd%d already in use\n", index);
1925 if (WARN_ON(nbd->config)) {
1926 mutex_unlock(&nbd->config_lock);
1930 config = nbd_alloc_config();
1931 if (IS_ERR(config)) {
1932 mutex_unlock(&nbd->config_lock);
1934 printk(KERN_ERR "nbd: couldn't allocate config\n");
1935 return PTR_ERR(config);
1937 nbd->config = config;
1938 refcount_set(&nbd->config_refs, 1);
1939 set_bit(NBD_RT_BOUND, &config->runtime_flags);
1941 ret = nbd_genl_size_set(info, nbd);
1945 if (info->attrs[NBD_ATTR_TIMEOUT])
1946 nbd_set_cmd_timeout(nbd,
1947 nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]));
1948 if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
1949 config->dead_conn_timeout =
1950 nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
1951 config->dead_conn_timeout *= HZ;
1953 if (info->attrs[NBD_ATTR_SERVER_FLAGS])
1955 nla_get_u64(info->attrs[NBD_ATTR_SERVER_FLAGS]);
1956 if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
1957 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
1958 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
1960 * We have 1 ref to keep the device around, and then 1
1961 * ref for our current operation here, which will be
1962 * inherited by the config. If we already have
1963 * DESTROY_ON_DISCONNECT set then we know we don't have
1964 * that extra ref already held so we don't need the
1967 if (!test_and_set_bit(NBD_DESTROY_ON_DISCONNECT,
1971 if (test_and_clear_bit(NBD_DESTROY_ON_DISCONNECT,
1973 refcount_inc(&nbd->refs);
1975 if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
1976 set_bit(NBD_RT_DISCONNECT_ON_CLOSE,
1977 &config->runtime_flags);
1981 if (info->attrs[NBD_ATTR_SOCKETS]) {
1982 struct nlattr *attr;
1985 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
1987 struct nlattr *socks[NBD_SOCK_MAX+1];
1989 if (nla_type(attr) != NBD_SOCK_ITEM) {
1990 printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
1994 ret = nla_parse_nested_deprecated(socks, NBD_SOCK_MAX,
1999 printk(KERN_ERR "nbd: error processing sock list\n");
2003 if (!socks[NBD_SOCK_FD])
2005 fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
2006 ret = nbd_add_socket(nbd, fd, true);
2011 ret = nbd_start_device(nbd);
2013 mutex_unlock(&nbd->config_lock);
2015 set_bit(NBD_RT_HAS_CONFIG_REF, &config->runtime_flags);
2016 refcount_inc(&nbd->config_refs);
2017 nbd_connect_reply(info, nbd->index);
2019 nbd_config_put(nbd);
2025 static void nbd_disconnect_and_put(struct nbd_device *nbd)
2027 mutex_lock(&nbd->config_lock);
2028 nbd_disconnect(nbd);
2030 wake_up(&nbd->config->conn_wait);
2032 * Make sure recv thread has finished, so it does not drop the last
2033 * config ref and try to destroy the workqueue from inside the work
2034 * queue. And this also ensure that we can safely call nbd_clear_que()
2035 * to cancel the inflight I/Os.
2037 if (nbd->recv_workq)
2038 flush_workqueue(nbd->recv_workq);
2040 nbd->task_setup = NULL;
2041 mutex_unlock(&nbd->config_lock);
2043 if (test_and_clear_bit(NBD_RT_HAS_CONFIG_REF,
2044 &nbd->config->runtime_flags))
2045 nbd_config_put(nbd);
2048 static int nbd_genl_disconnect(struct sk_buff *skb, struct genl_info *info)
2050 struct nbd_device *nbd;
2053 if (!netlink_capable(skb, CAP_SYS_ADMIN))
2056 if (!info->attrs[NBD_ATTR_INDEX]) {
2057 printk(KERN_ERR "nbd: must specify an index to disconnect\n");
2060 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2061 mutex_lock(&nbd_index_mutex);
2062 nbd = idr_find(&nbd_index_idr, index);
2064 mutex_unlock(&nbd_index_mutex);
2065 printk(KERN_ERR "nbd: couldn't find device at index %d\n",
2069 if (!refcount_inc_not_zero(&nbd->refs)) {
2070 mutex_unlock(&nbd_index_mutex);
2071 printk(KERN_ERR "nbd: device at index %d is going down\n",
2075 mutex_unlock(&nbd_index_mutex);
2076 if (!refcount_inc_not_zero(&nbd->config_refs)) {
2080 nbd_disconnect_and_put(nbd);
2081 nbd_config_put(nbd);
2086 static int nbd_genl_reconfigure(struct sk_buff *skb, struct genl_info *info)
2088 struct nbd_device *nbd = NULL;
2089 struct nbd_config *config;
2092 bool put_dev = false;
2094 if (!netlink_capable(skb, CAP_SYS_ADMIN))
2097 if (!info->attrs[NBD_ATTR_INDEX]) {
2098 printk(KERN_ERR "nbd: must specify a device to reconfigure\n");
2101 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2102 mutex_lock(&nbd_index_mutex);
2103 nbd = idr_find(&nbd_index_idr, index);
2105 mutex_unlock(&nbd_index_mutex);
2106 printk(KERN_ERR "nbd: couldn't find a device at index %d\n",
2110 if (!refcount_inc_not_zero(&nbd->refs)) {
2111 mutex_unlock(&nbd_index_mutex);
2112 printk(KERN_ERR "nbd: device at index %d is going down\n",
2116 mutex_unlock(&nbd_index_mutex);
2118 if (!refcount_inc_not_zero(&nbd->config_refs)) {
2119 dev_err(nbd_to_dev(nbd),
2120 "not configured, cannot reconfigure\n");
2125 mutex_lock(&nbd->config_lock);
2126 config = nbd->config;
2127 if (!test_bit(NBD_RT_BOUND, &config->runtime_flags) ||
2129 dev_err(nbd_to_dev(nbd),
2130 "not configured, cannot reconfigure\n");
2135 ret = nbd_genl_size_set(info, nbd);
2139 if (info->attrs[NBD_ATTR_TIMEOUT])
2140 nbd_set_cmd_timeout(nbd,
2141 nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]));
2142 if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
2143 config->dead_conn_timeout =
2144 nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
2145 config->dead_conn_timeout *= HZ;
2147 if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
2148 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
2149 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
2150 if (!test_and_set_bit(NBD_DESTROY_ON_DISCONNECT,
2154 if (test_and_clear_bit(NBD_DESTROY_ON_DISCONNECT,
2156 refcount_inc(&nbd->refs);
2159 if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
2160 set_bit(NBD_RT_DISCONNECT_ON_CLOSE,
2161 &config->runtime_flags);
2163 clear_bit(NBD_RT_DISCONNECT_ON_CLOSE,
2164 &config->runtime_flags);
2168 if (info->attrs[NBD_ATTR_SOCKETS]) {
2169 struct nlattr *attr;
2172 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
2174 struct nlattr *socks[NBD_SOCK_MAX+1];
2176 if (nla_type(attr) != NBD_SOCK_ITEM) {
2177 printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
2181 ret = nla_parse_nested_deprecated(socks, NBD_SOCK_MAX,
2186 printk(KERN_ERR "nbd: error processing sock list\n");
2190 if (!socks[NBD_SOCK_FD])
2192 fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
2193 ret = nbd_reconnect_socket(nbd, fd);
2199 dev_info(nbd_to_dev(nbd), "reconnected socket\n");
2203 mutex_unlock(&nbd->config_lock);
2204 nbd_config_put(nbd);
2211 static const struct genl_ops nbd_connect_genl_ops[] = {
2213 .cmd = NBD_CMD_CONNECT,
2214 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2215 .doit = nbd_genl_connect,
2218 .cmd = NBD_CMD_DISCONNECT,
2219 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2220 .doit = nbd_genl_disconnect,
2223 .cmd = NBD_CMD_RECONFIGURE,
2224 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2225 .doit = nbd_genl_reconfigure,
2228 .cmd = NBD_CMD_STATUS,
2229 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2230 .doit = nbd_genl_status,
2234 static const struct genl_multicast_group nbd_mcast_grps[] = {
2235 { .name = NBD_GENL_MCAST_GROUP_NAME, },
2238 static struct genl_family nbd_genl_family __ro_after_init = {
2240 .name = NBD_GENL_FAMILY_NAME,
2241 .version = NBD_GENL_VERSION,
2242 .module = THIS_MODULE,
2243 .ops = nbd_connect_genl_ops,
2244 .n_ops = ARRAY_SIZE(nbd_connect_genl_ops),
2245 .maxattr = NBD_ATTR_MAX,
2246 .policy = nbd_attr_policy,
2247 .mcgrps = nbd_mcast_grps,
2248 .n_mcgrps = ARRAY_SIZE(nbd_mcast_grps),
2251 static int populate_nbd_status(struct nbd_device *nbd, struct sk_buff *reply)
2253 struct nlattr *dev_opt;
2257 /* This is a little racey, but for status it's ok. The
2258 * reason we don't take a ref here is because we can't
2259 * take a ref in the index == -1 case as we would need
2260 * to put under the nbd_index_mutex, which could
2261 * deadlock if we are configured to remove ourselves
2262 * once we're disconnected.
2264 if (refcount_read(&nbd->config_refs))
2266 dev_opt = nla_nest_start_noflag(reply, NBD_DEVICE_ITEM);
2269 ret = nla_put_u32(reply, NBD_DEVICE_INDEX, nbd->index);
2272 ret = nla_put_u8(reply, NBD_DEVICE_CONNECTED,
2276 nla_nest_end(reply, dev_opt);
2280 static int status_cb(int id, void *ptr, void *data)
2282 struct nbd_device *nbd = ptr;
2283 return populate_nbd_status(nbd, (struct sk_buff *)data);
2286 static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info)
2288 struct nlattr *dev_list;
2289 struct sk_buff *reply;
2295 if (info->attrs[NBD_ATTR_INDEX])
2296 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2298 mutex_lock(&nbd_index_mutex);
2300 msg_size = nla_total_size(nla_attr_size(sizeof(u32)) +
2301 nla_attr_size(sizeof(u8)));
2302 msg_size *= (index == -1) ? nbd_total_devices : 1;
2304 reply = genlmsg_new(msg_size, GFP_KERNEL);
2307 reply_head = genlmsg_put_reply(reply, info, &nbd_genl_family, 0,
2314 dev_list = nla_nest_start_noflag(reply, NBD_ATTR_DEVICE_LIST);
2316 ret = idr_for_each(&nbd_index_idr, &status_cb, reply);
2322 struct nbd_device *nbd;
2323 nbd = idr_find(&nbd_index_idr, index);
2325 ret = populate_nbd_status(nbd, reply);
2332 nla_nest_end(reply, dev_list);
2333 genlmsg_end(reply, reply_head);
2334 ret = genlmsg_reply(reply, info);
2336 mutex_unlock(&nbd_index_mutex);
2340 static void nbd_connect_reply(struct genl_info *info, int index)
2342 struct sk_buff *skb;
2346 skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2349 msg_head = genlmsg_put_reply(skb, info, &nbd_genl_family, 0,
2355 ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2360 genlmsg_end(skb, msg_head);
2361 genlmsg_reply(skb, info);
2364 static void nbd_mcast_index(int index)
2366 struct sk_buff *skb;
2370 skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2373 msg_head = genlmsg_put(skb, 0, 0, &nbd_genl_family, 0,
2379 ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2384 genlmsg_end(skb, msg_head);
2385 genlmsg_multicast(&nbd_genl_family, skb, 0, 0, GFP_KERNEL);
2388 static void nbd_dead_link_work(struct work_struct *work)
2390 struct link_dead_args *args = container_of(work, struct link_dead_args,
2392 nbd_mcast_index(args->index);
2396 static int __init nbd_init(void)
2400 BUILD_BUG_ON(sizeof(struct nbd_request) != 28);
2403 printk(KERN_ERR "nbd: max_part must be >= 0\n");
2409 part_shift = fls(max_part);
2412 * Adjust max_part according to part_shift as it is exported
2413 * to user space so that user can know the max number of
2414 * partition kernel should be able to manage.
2416 * Note that -1 is required because partition 0 is reserved
2417 * for the whole disk.
2419 max_part = (1UL << part_shift) - 1;
2422 if ((1UL << part_shift) > DISK_MAX_PARTS)
2425 if (nbds_max > 1UL << (MINORBITS - part_shift))
2428 if (register_blkdev(NBD_MAJOR, "nbd"))
2431 if (genl_register_family(&nbd_genl_family)) {
2432 unregister_blkdev(NBD_MAJOR, "nbd");
2437 mutex_lock(&nbd_index_mutex);
2438 for (i = 0; i < nbds_max; i++)
2440 mutex_unlock(&nbd_index_mutex);
2444 static int nbd_exit_cb(int id, void *ptr, void *data)
2446 struct list_head *list = (struct list_head *)data;
2447 struct nbd_device *nbd = ptr;
2449 list_add_tail(&nbd->list, list);
2453 static void __exit nbd_cleanup(void)
2455 struct nbd_device *nbd;
2456 LIST_HEAD(del_list);
2459 * Unregister netlink interface prior to waiting
2460 * for the completion of netlink commands.
2462 genl_unregister_family(&nbd_genl_family);
2466 mutex_lock(&nbd_index_mutex);
2467 idr_for_each(&nbd_index_idr, &nbd_exit_cb, &del_list);
2468 mutex_unlock(&nbd_index_mutex);
2470 while (!list_empty(&del_list)) {
2471 nbd = list_first_entry(&del_list, struct nbd_device, list);
2472 list_del_init(&nbd->list);
2473 if (refcount_read(&nbd->config_refs))
2474 printk(KERN_ERR "nbd: possibly leaking nbd_config (ref %d)\n",
2475 refcount_read(&nbd->config_refs));
2476 if (refcount_read(&nbd->refs) != 1)
2477 printk(KERN_ERR "nbd: possibly leaking a device\n");
2481 idr_destroy(&nbd_index_idr);
2482 unregister_blkdev(NBD_MAJOR, "nbd");
2485 module_init(nbd_init);
2486 module_exit(nbd_cleanup);
2488 MODULE_DESCRIPTION("Network Block Device");
2489 MODULE_LICENSE("GPL");
2491 module_param(nbds_max, int, 0444);
2492 MODULE_PARM_DESC(nbds_max, "number of network block devices to initialize (default: 16)");
2493 module_param(max_part, int, 0444);
2494 MODULE_PARM_DESC(max_part, "number of partitions per device (default: 16)");