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_DESTROY_ON_DISCONNECT 6
82 #define NBD_RT_DISCONNECT_ON_CLOSE 7
84 #define NBD_DESTROY_ON_DISCONNECT 0
85 #define NBD_DISCONNECT_REQUESTED 1
89 unsigned long runtime_flags;
90 u64 dead_conn_timeout;
92 struct nbd_sock **socks;
94 atomic_t live_connections;
95 wait_queue_head_t conn_wait;
97 atomic_t recv_threads;
98 wait_queue_head_t recv_wq;
101 #if IS_ENABLED(CONFIG_DEBUG_FS)
102 struct dentry *dbg_dir;
107 struct blk_mq_tag_set tag_set;
110 refcount_t config_refs;
112 struct nbd_config *config;
113 struct mutex config_lock;
114 struct gendisk *disk;
115 struct workqueue_struct *recv_workq;
117 struct list_head list;
118 struct task_struct *task_recv;
119 struct task_struct *task_setup;
121 struct completion *destroy_complete;
125 #define NBD_CMD_REQUEUED 1
128 struct nbd_device *nbd;
138 #if IS_ENABLED(CONFIG_DEBUG_FS)
139 static struct dentry *nbd_dbg_dir;
142 #define nbd_name(nbd) ((nbd)->disk->disk_name)
144 #define NBD_MAGIC 0x68797548
146 #define NBD_DEF_BLKSIZE 1024
148 static unsigned int nbds_max = 16;
149 static int max_part = 16;
150 static int part_shift;
152 static int nbd_dev_dbg_init(struct nbd_device *nbd);
153 static void nbd_dev_dbg_close(struct nbd_device *nbd);
154 static void nbd_config_put(struct nbd_device *nbd);
155 static void nbd_connect_reply(struct genl_info *info, int index);
156 static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info);
157 static void nbd_dead_link_work(struct work_struct *work);
158 static void nbd_disconnect_and_put(struct nbd_device *nbd);
160 static inline struct device *nbd_to_dev(struct nbd_device *nbd)
162 return disk_to_dev(nbd->disk);
165 static void nbd_requeue_cmd(struct nbd_cmd *cmd)
167 struct request *req = blk_mq_rq_from_pdu(cmd);
169 if (!test_and_set_bit(NBD_CMD_REQUEUED, &cmd->flags))
170 blk_mq_requeue_request(req, true);
173 #define NBD_COOKIE_BITS 32
175 static u64 nbd_cmd_handle(struct nbd_cmd *cmd)
177 struct request *req = blk_mq_rq_from_pdu(cmd);
178 u32 tag = blk_mq_unique_tag(req);
179 u64 cookie = cmd->cmd_cookie;
181 return (cookie << NBD_COOKIE_BITS) | tag;
184 static u32 nbd_handle_to_tag(u64 handle)
189 static u32 nbd_handle_to_cookie(u64 handle)
191 return (u32)(handle >> NBD_COOKIE_BITS);
194 static const char *nbdcmd_to_ascii(int cmd)
197 case NBD_CMD_READ: return "read";
198 case NBD_CMD_WRITE: return "write";
199 case NBD_CMD_DISC: return "disconnect";
200 case NBD_CMD_FLUSH: return "flush";
201 case NBD_CMD_TRIM: return "trim/discard";
206 static ssize_t pid_show(struct device *dev,
207 struct device_attribute *attr, char *buf)
209 struct gendisk *disk = dev_to_disk(dev);
210 struct nbd_device *nbd = (struct nbd_device *)disk->private_data;
212 return sprintf(buf, "%d\n", task_pid_nr(nbd->task_recv));
215 static const struct device_attribute pid_attr = {
216 .attr = { .name = "pid", .mode = 0444},
220 static void nbd_dev_remove(struct nbd_device *nbd)
222 struct gendisk *disk = nbd->disk;
223 struct request_queue *q;
228 blk_cleanup_queue(q);
229 blk_mq_free_tag_set(&nbd->tag_set);
230 disk->private_data = NULL;
235 * Place this in the last just before the nbd is freed to
236 * make sure that the disk and the related kobject are also
237 * totally removed to avoid duplicate creation of the same
240 if (test_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags) && nbd->destroy_complete)
241 complete(nbd->destroy_complete);
246 static void nbd_put(struct nbd_device *nbd)
248 if (refcount_dec_and_mutex_lock(&nbd->refs,
250 idr_remove(&nbd_index_idr, nbd->index);
252 mutex_unlock(&nbd_index_mutex);
256 static int nbd_disconnected(struct nbd_config *config)
258 return test_bit(NBD_RT_DISCONNECTED, &config->runtime_flags) ||
259 test_bit(NBD_RT_DISCONNECT_REQUESTED, &config->runtime_flags);
262 static void nbd_mark_nsock_dead(struct nbd_device *nbd, struct nbd_sock *nsock,
265 if (!nsock->dead && notify && !nbd_disconnected(nbd->config)) {
266 struct link_dead_args *args;
267 args = kmalloc(sizeof(struct link_dead_args), GFP_NOIO);
269 INIT_WORK(&args->work, nbd_dead_link_work);
270 args->index = nbd->index;
271 queue_work(system_wq, &args->work);
275 kernel_sock_shutdown(nsock->sock, SHUT_RDWR);
276 if (atomic_dec_return(&nbd->config->live_connections) == 0) {
277 if (test_and_clear_bit(NBD_RT_DISCONNECT_REQUESTED,
278 &nbd->config->runtime_flags)) {
279 set_bit(NBD_RT_DISCONNECTED,
280 &nbd->config->runtime_flags);
281 dev_info(nbd_to_dev(nbd),
282 "Disconnected due to user request.\n");
287 nsock->pending = NULL;
291 static void nbd_size_clear(struct nbd_device *nbd)
293 if (nbd->config->bytesize) {
294 set_capacity(nbd->disk, 0);
295 kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
299 static void nbd_size_update(struct nbd_device *nbd)
301 struct nbd_config *config = nbd->config;
302 struct block_device *bdev = bdget_disk(nbd->disk, 0);
303 sector_t nr_sectors = config->bytesize >> 9;
305 if (config->flags & NBD_FLAG_SEND_TRIM) {
306 nbd->disk->queue->limits.discard_granularity = config->blksize;
307 nbd->disk->queue->limits.discard_alignment = config->blksize;
308 blk_queue_max_discard_sectors(nbd->disk->queue, UINT_MAX);
310 blk_queue_logical_block_size(nbd->disk->queue, config->blksize);
311 blk_queue_physical_block_size(nbd->disk->queue, config->blksize);
312 set_capacity(nbd->disk, nr_sectors);
315 bd_set_nr_sectors(bdev, nr_sectors);
316 set_blocksize(bdev, config->blksize);
318 set_bit(GD_NEED_PART_SCAN, &nbd->disk->state);
321 kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
324 static void nbd_size_set(struct nbd_device *nbd, loff_t blocksize,
327 struct nbd_config *config = nbd->config;
328 config->blksize = blocksize;
329 config->bytesize = blocksize * nr_blocks;
330 if (nbd->task_recv != NULL)
331 nbd_size_update(nbd);
334 static void nbd_complete_rq(struct request *req)
336 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
338 dev_dbg(nbd_to_dev(cmd->nbd), "request %p: %s\n", req,
339 cmd->status ? "failed" : "done");
341 blk_mq_end_request(req, cmd->status);
345 * Forcibly shutdown the socket causing all listeners to error
347 static void sock_shutdown(struct nbd_device *nbd)
349 struct nbd_config *config = nbd->config;
352 if (config->num_connections == 0)
354 if (test_and_set_bit(NBD_RT_DISCONNECTED, &config->runtime_flags))
357 for (i = 0; i < config->num_connections; i++) {
358 struct nbd_sock *nsock = config->socks[i];
359 mutex_lock(&nsock->tx_lock);
360 nbd_mark_nsock_dead(nbd, nsock, 0);
361 mutex_unlock(&nsock->tx_lock);
363 dev_warn(disk_to_dev(nbd->disk), "shutting down sockets\n");
366 static u32 req_to_nbd_cmd_type(struct request *req)
368 switch (req_op(req)) {
372 return NBD_CMD_FLUSH;
374 return NBD_CMD_WRITE;
382 static enum blk_eh_timer_return nbd_xmit_timeout(struct request *req,
385 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
386 struct nbd_device *nbd = cmd->nbd;
387 struct nbd_config *config;
389 if (!mutex_trylock(&cmd->lock))
390 return BLK_EH_RESET_TIMER;
392 if (!refcount_inc_not_zero(&nbd->config_refs)) {
393 cmd->status = BLK_STS_TIMEOUT;
394 mutex_unlock(&cmd->lock);
397 config = nbd->config;
399 if (config->num_connections > 1 ||
400 (config->num_connections == 1 && nbd->tag_set.timeout)) {
401 dev_err_ratelimited(nbd_to_dev(nbd),
402 "Connection timed out, retrying (%d/%d alive)\n",
403 atomic_read(&config->live_connections),
404 config->num_connections);
406 * Hooray we have more connections, requeue this IO, the submit
407 * path will put it on a real connection. Or if only one
408 * connection is configured, the submit path will wait util
409 * a new connection is reconfigured or util dead timeout.
412 if (cmd->index < config->num_connections) {
413 struct nbd_sock *nsock =
414 config->socks[cmd->index];
415 mutex_lock(&nsock->tx_lock);
416 /* We can have multiple outstanding requests, so
417 * we don't want to mark the nsock dead if we've
418 * already reconnected with a new socket, so
419 * only mark it dead if its the same socket we
422 if (cmd->cookie == nsock->cookie)
423 nbd_mark_nsock_dead(nbd, nsock, 1);
424 mutex_unlock(&nsock->tx_lock);
426 mutex_unlock(&cmd->lock);
427 nbd_requeue_cmd(cmd);
433 if (!nbd->tag_set.timeout) {
435 * Userspace sets timeout=0 to disable socket disconnection,
436 * so just warn and reset the timer.
438 struct nbd_sock *nsock = config->socks[cmd->index];
440 dev_info(nbd_to_dev(nbd), "Possible stuck request %p: control (%s@%llu,%uB). Runtime %u seconds\n",
441 req, nbdcmd_to_ascii(req_to_nbd_cmd_type(req)),
442 (unsigned long long)blk_rq_pos(req) << 9,
443 blk_rq_bytes(req), (req->timeout / HZ) * cmd->retries);
445 mutex_lock(&nsock->tx_lock);
446 if (cmd->cookie != nsock->cookie) {
447 nbd_requeue_cmd(cmd);
448 mutex_unlock(&nsock->tx_lock);
449 mutex_unlock(&cmd->lock);
453 mutex_unlock(&nsock->tx_lock);
454 mutex_unlock(&cmd->lock);
456 return BLK_EH_RESET_TIMER;
459 dev_err_ratelimited(nbd_to_dev(nbd), "Connection timed out\n");
460 set_bit(NBD_RT_TIMEDOUT, &config->runtime_flags);
461 cmd->status = BLK_STS_IOERR;
462 mutex_unlock(&cmd->lock);
466 blk_mq_complete_request(req);
471 * Send or receive packet.
473 static int sock_xmit(struct nbd_device *nbd, int index, int send,
474 struct iov_iter *iter, int msg_flags, int *sent)
476 struct nbd_config *config = nbd->config;
477 struct socket *sock = config->socks[index]->sock;
480 unsigned int noreclaim_flag;
482 if (unlikely(!sock)) {
483 dev_err_ratelimited(disk_to_dev(nbd->disk),
484 "Attempted %s on closed socket in sock_xmit\n",
485 (send ? "send" : "recv"));
489 msg.msg_iter = *iter;
491 noreclaim_flag = memalloc_noreclaim_save();
493 sock->sk->sk_allocation = GFP_NOIO | __GFP_MEMALLOC;
496 msg.msg_control = NULL;
497 msg.msg_controllen = 0;
498 msg.msg_flags = msg_flags | MSG_NOSIGNAL;
501 result = sock_sendmsg(sock, &msg);
503 result = sock_recvmsg(sock, &msg, msg.msg_flags);
507 result = -EPIPE; /* short read */
512 } while (msg_data_left(&msg));
514 memalloc_noreclaim_restore(noreclaim_flag);
520 * Different settings for sk->sk_sndtimeo can result in different return values
521 * if there is a signal pending when we enter sendmsg, because reasons?
523 static inline int was_interrupted(int result)
525 return result == -ERESTARTSYS || result == -EINTR;
528 /* always call with the tx_lock held */
529 static int nbd_send_cmd(struct nbd_device *nbd, struct nbd_cmd *cmd, int index)
531 struct request *req = blk_mq_rq_from_pdu(cmd);
532 struct nbd_config *config = nbd->config;
533 struct nbd_sock *nsock = config->socks[index];
535 struct nbd_request request = {.magic = htonl(NBD_REQUEST_MAGIC)};
536 struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
537 struct iov_iter from;
538 unsigned long size = blk_rq_bytes(req);
542 u32 nbd_cmd_flags = 0;
543 int sent = nsock->sent, skip = 0;
545 iov_iter_kvec(&from, WRITE, &iov, 1, sizeof(request));
547 type = req_to_nbd_cmd_type(req);
551 if (rq_data_dir(req) == WRITE &&
552 (config->flags & NBD_FLAG_READ_ONLY)) {
553 dev_err_ratelimited(disk_to_dev(nbd->disk),
554 "Write on read-only\n");
558 if (req->cmd_flags & REQ_FUA)
559 nbd_cmd_flags |= NBD_CMD_FLAG_FUA;
561 /* We did a partial send previously, and we at least sent the whole
562 * request struct, so just go and send the rest of the pages in the
566 if (sent >= sizeof(request)) {
567 skip = sent - sizeof(request);
569 /* initialize handle for tracing purposes */
570 handle = nbd_cmd_handle(cmd);
574 iov_iter_advance(&from, sent);
579 cmd->cookie = nsock->cookie;
581 request.type = htonl(type | nbd_cmd_flags);
582 if (type != NBD_CMD_FLUSH) {
583 request.from = cpu_to_be64((u64)blk_rq_pos(req) << 9);
584 request.len = htonl(size);
586 handle = nbd_cmd_handle(cmd);
587 memcpy(request.handle, &handle, sizeof(handle));
589 trace_nbd_send_request(&request, nbd->index, blk_mq_rq_from_pdu(cmd));
591 dev_dbg(nbd_to_dev(nbd), "request %p: sending control (%s@%llu,%uB)\n",
592 req, nbdcmd_to_ascii(type),
593 (unsigned long long)blk_rq_pos(req) << 9, blk_rq_bytes(req));
594 result = sock_xmit(nbd, index, 1, &from,
595 (type == NBD_CMD_WRITE) ? MSG_MORE : 0, &sent);
596 trace_nbd_header_sent(req, handle);
598 if (was_interrupted(result)) {
599 /* If we havne't sent anything we can just return BUSY,
600 * however if we have sent something we need to make
601 * sure we only allow this req to be sent until we are
605 nsock->pending = req;
608 set_bit(NBD_CMD_REQUEUED, &cmd->flags);
609 return BLK_STS_RESOURCE;
611 dev_err_ratelimited(disk_to_dev(nbd->disk),
612 "Send control failed (result %d)\n", result);
616 if (type != NBD_CMD_WRITE)
621 struct bio *next = bio->bi_next;
622 struct bvec_iter iter;
625 bio_for_each_segment(bvec, bio, iter) {
626 bool is_last = !next && bio_iter_last(bvec, iter);
627 int flags = is_last ? 0 : MSG_MORE;
629 dev_dbg(nbd_to_dev(nbd), "request %p: sending %d bytes data\n",
631 iov_iter_bvec(&from, WRITE, &bvec, 1, bvec.bv_len);
633 if (skip >= iov_iter_count(&from)) {
634 skip -= iov_iter_count(&from);
637 iov_iter_advance(&from, skip);
640 result = sock_xmit(nbd, index, 1, &from, flags, &sent);
642 if (was_interrupted(result)) {
643 /* We've already sent the header, we
644 * have no choice but to set pending and
647 nsock->pending = req;
649 set_bit(NBD_CMD_REQUEUED, &cmd->flags);
650 return BLK_STS_RESOURCE;
652 dev_err(disk_to_dev(nbd->disk),
653 "Send data failed (result %d)\n",
658 * The completion might already have come in,
659 * so break for the last one instead of letting
660 * the iterator do it. This prevents use-after-free
669 trace_nbd_payload_sent(req, handle);
670 nsock->pending = NULL;
675 /* NULL returned = something went wrong, inform userspace */
676 static struct nbd_cmd *nbd_read_stat(struct nbd_device *nbd, int index)
678 struct nbd_config *config = nbd->config;
680 struct nbd_reply reply;
682 struct request *req = NULL;
686 struct kvec iov = {.iov_base = &reply, .iov_len = sizeof(reply)};
691 iov_iter_kvec(&to, READ, &iov, 1, sizeof(reply));
692 result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
694 if (!nbd_disconnected(config))
695 dev_err(disk_to_dev(nbd->disk),
696 "Receive control failed (result %d)\n", result);
697 return ERR_PTR(result);
700 if (ntohl(reply.magic) != NBD_REPLY_MAGIC) {
701 dev_err(disk_to_dev(nbd->disk), "Wrong magic (0x%lx)\n",
702 (unsigned long)ntohl(reply.magic));
703 return ERR_PTR(-EPROTO);
706 memcpy(&handle, reply.handle, sizeof(handle));
707 tag = nbd_handle_to_tag(handle);
708 hwq = blk_mq_unique_tag_to_hwq(tag);
709 if (hwq < nbd->tag_set.nr_hw_queues)
710 req = blk_mq_tag_to_rq(nbd->tag_set.tags[hwq],
711 blk_mq_unique_tag_to_tag(tag));
712 if (!req || !blk_mq_request_started(req)) {
713 dev_err(disk_to_dev(nbd->disk), "Unexpected reply (%d) %p\n",
715 return ERR_PTR(-ENOENT);
717 trace_nbd_header_received(req, handle);
718 cmd = blk_mq_rq_to_pdu(req);
720 mutex_lock(&cmd->lock);
721 if (cmd->cmd_cookie != nbd_handle_to_cookie(handle)) {
722 dev_err(disk_to_dev(nbd->disk), "Double reply on req %p, cmd_cookie %u, handle cookie %u\n",
723 req, cmd->cmd_cookie, nbd_handle_to_cookie(handle));
727 if (cmd->status != BLK_STS_OK) {
728 dev_err(disk_to_dev(nbd->disk), "Command already handled %p\n",
733 if (test_bit(NBD_CMD_REQUEUED, &cmd->flags)) {
734 dev_err(disk_to_dev(nbd->disk), "Raced with timeout on req %p\n",
739 if (ntohl(reply.error)) {
740 dev_err(disk_to_dev(nbd->disk), "Other side returned error (%d)\n",
742 cmd->status = BLK_STS_IOERR;
746 dev_dbg(nbd_to_dev(nbd), "request %p: got reply\n", req);
747 if (rq_data_dir(req) != WRITE) {
748 struct req_iterator iter;
751 rq_for_each_segment(bvec, req, iter) {
752 iov_iter_bvec(&to, READ, &bvec, 1, bvec.bv_len);
753 result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
755 dev_err(disk_to_dev(nbd->disk), "Receive data failed (result %d)\n",
758 * If we've disconnected, we need to make sure we
759 * complete this request, otherwise error out
760 * and let the timeout stuff handle resubmitting
761 * this request onto another connection.
763 if (nbd_disconnected(config)) {
764 cmd->status = BLK_STS_IOERR;
770 dev_dbg(nbd_to_dev(nbd), "request %p: got %d bytes data\n",
775 trace_nbd_payload_received(req, handle);
776 mutex_unlock(&cmd->lock);
777 return ret ? ERR_PTR(ret) : cmd;
780 static void recv_work(struct work_struct *work)
782 struct recv_thread_args *args = container_of(work,
783 struct recv_thread_args,
785 struct nbd_device *nbd = args->nbd;
786 struct nbd_config *config = nbd->config;
791 cmd = nbd_read_stat(nbd, args->index);
793 struct nbd_sock *nsock = config->socks[args->index];
795 mutex_lock(&nsock->tx_lock);
796 nbd_mark_nsock_dead(nbd, nsock, 1);
797 mutex_unlock(&nsock->tx_lock);
801 rq = blk_mq_rq_from_pdu(cmd);
802 if (likely(!blk_should_fake_timeout(rq->q)))
803 blk_mq_complete_request(rq);
806 atomic_dec(&config->recv_threads);
807 wake_up(&config->recv_wq);
811 static bool nbd_clear_req(struct request *req, void *data, bool reserved)
813 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
815 mutex_lock(&cmd->lock);
816 cmd->status = BLK_STS_IOERR;
817 mutex_unlock(&cmd->lock);
819 blk_mq_complete_request(req);
823 static void nbd_clear_que(struct nbd_device *nbd)
825 blk_mq_quiesce_queue(nbd->disk->queue);
826 blk_mq_tagset_busy_iter(&nbd->tag_set, nbd_clear_req, NULL);
827 blk_mq_unquiesce_queue(nbd->disk->queue);
828 dev_dbg(disk_to_dev(nbd->disk), "queue cleared\n");
831 static int find_fallback(struct nbd_device *nbd, int index)
833 struct nbd_config *config = nbd->config;
835 struct nbd_sock *nsock = config->socks[index];
836 int fallback = nsock->fallback_index;
838 if (test_bit(NBD_RT_DISCONNECTED, &config->runtime_flags))
841 if (config->num_connections <= 1) {
842 dev_err_ratelimited(disk_to_dev(nbd->disk),
843 "Dead connection, failed to find a fallback\n");
847 if (fallback >= 0 && fallback < config->num_connections &&
848 !config->socks[fallback]->dead)
851 if (nsock->fallback_index < 0 ||
852 nsock->fallback_index >= config->num_connections ||
853 config->socks[nsock->fallback_index]->dead) {
855 for (i = 0; i < config->num_connections; i++) {
858 if (!config->socks[i]->dead) {
863 nsock->fallback_index = new_index;
865 dev_err_ratelimited(disk_to_dev(nbd->disk),
866 "Dead connection, failed to find a fallback\n");
870 new_index = nsock->fallback_index;
874 static int wait_for_reconnect(struct nbd_device *nbd)
876 struct nbd_config *config = nbd->config;
877 if (!config->dead_conn_timeout)
879 if (test_bit(NBD_RT_DISCONNECTED, &config->runtime_flags))
881 return wait_event_timeout(config->conn_wait,
882 atomic_read(&config->live_connections) > 0,
883 config->dead_conn_timeout) > 0;
886 static int nbd_handle_cmd(struct nbd_cmd *cmd, int index)
888 struct request *req = blk_mq_rq_from_pdu(cmd);
889 struct nbd_device *nbd = cmd->nbd;
890 struct nbd_config *config;
891 struct nbd_sock *nsock;
894 if (!refcount_inc_not_zero(&nbd->config_refs)) {
895 dev_err_ratelimited(disk_to_dev(nbd->disk),
896 "Socks array is empty\n");
897 blk_mq_start_request(req);
900 config = nbd->config;
902 if (index >= config->num_connections) {
903 dev_err_ratelimited(disk_to_dev(nbd->disk),
904 "Attempted send on invalid socket\n");
906 blk_mq_start_request(req);
909 cmd->status = BLK_STS_OK;
911 nsock = config->socks[index];
912 mutex_lock(&nsock->tx_lock);
914 int old_index = index;
915 index = find_fallback(nbd, index);
916 mutex_unlock(&nsock->tx_lock);
918 if (wait_for_reconnect(nbd)) {
922 /* All the sockets should already be down at this point,
923 * we just want to make sure that DISCONNECTED is set so
924 * any requests that come in that were queue'ed waiting
925 * for the reconnect timer don't trigger the timer again
926 * and instead just error out.
930 blk_mq_start_request(req);
936 /* Handle the case that we have a pending request that was partially
937 * transmitted that _has_ to be serviced first. We need to call requeue
938 * here so that it gets put _after_ the request that is already on the
941 blk_mq_start_request(req);
942 if (unlikely(nsock->pending && nsock->pending != req)) {
943 nbd_requeue_cmd(cmd);
948 * Some failures are related to the link going down, so anything that
949 * returns EAGAIN can be retried on a different socket.
951 ret = nbd_send_cmd(nbd, cmd, index);
952 if (ret == -EAGAIN) {
953 dev_err_ratelimited(disk_to_dev(nbd->disk),
954 "Request send failed, requeueing\n");
955 nbd_mark_nsock_dead(nbd, nsock, 1);
956 nbd_requeue_cmd(cmd);
960 mutex_unlock(&nsock->tx_lock);
965 static blk_status_t nbd_queue_rq(struct blk_mq_hw_ctx *hctx,
966 const struct blk_mq_queue_data *bd)
968 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(bd->rq);
972 * Since we look at the bio's to send the request over the network we
973 * need to make sure the completion work doesn't mark this request done
974 * before we are done doing our send. This keeps us from dereferencing
975 * freed data if we have particularly fast completions (ie we get the
976 * completion before we exit sock_xmit on the last bvec) or in the case
977 * that the server is misbehaving (or there was an error) before we're
978 * done sending everything over the wire.
980 mutex_lock(&cmd->lock);
981 clear_bit(NBD_CMD_REQUEUED, &cmd->flags);
983 /* We can be called directly from the user space process, which means we
984 * could possibly have signals pending so our sendmsg will fail. In
985 * this case we need to return that we are busy, otherwise error out as
988 ret = nbd_handle_cmd(cmd, hctx->queue_num);
993 mutex_unlock(&cmd->lock);
998 static struct socket *nbd_get_socket(struct nbd_device *nbd, unsigned long fd,
1001 struct socket *sock;
1004 sock = sockfd_lookup(fd, err);
1008 if (sock->ops->shutdown == sock_no_shutdown) {
1009 dev_err(disk_to_dev(nbd->disk), "Unsupported socket: shutdown callout must be supported.\n");
1018 static int nbd_add_socket(struct nbd_device *nbd, unsigned long arg,
1021 struct nbd_config *config = nbd->config;
1022 struct socket *sock;
1023 struct nbd_sock **socks;
1024 struct nbd_sock *nsock;
1027 sock = nbd_get_socket(nbd, arg, &err);
1031 if (!netlink && !nbd->task_setup &&
1032 !test_bit(NBD_RT_BOUND, &config->runtime_flags))
1033 nbd->task_setup = current;
1036 (nbd->task_setup != current ||
1037 test_bit(NBD_RT_BOUND, &config->runtime_flags))) {
1038 dev_err(disk_to_dev(nbd->disk),
1039 "Device being setup by another task");
1044 nsock = kzalloc(sizeof(*nsock), GFP_KERNEL);
1050 socks = krealloc(config->socks, (config->num_connections + 1) *
1051 sizeof(struct nbd_sock *), GFP_KERNEL);
1058 config->socks = socks;
1060 nsock->fallback_index = -1;
1061 nsock->dead = false;
1062 mutex_init(&nsock->tx_lock);
1064 nsock->pending = NULL;
1067 socks[config->num_connections++] = nsock;
1068 atomic_inc(&config->live_connections);
1077 static int nbd_reconnect_socket(struct nbd_device *nbd, unsigned long arg)
1079 struct nbd_config *config = nbd->config;
1080 struct socket *sock, *old;
1081 struct recv_thread_args *args;
1085 sock = nbd_get_socket(nbd, arg, &err);
1089 args = kzalloc(sizeof(*args), GFP_KERNEL);
1095 for (i = 0; i < config->num_connections; i++) {
1096 struct nbd_sock *nsock = config->socks[i];
1101 mutex_lock(&nsock->tx_lock);
1103 mutex_unlock(&nsock->tx_lock);
1106 sk_set_memalloc(sock->sk);
1107 if (nbd->tag_set.timeout)
1108 sock->sk->sk_sndtimeo = nbd->tag_set.timeout;
1109 atomic_inc(&config->recv_threads);
1110 refcount_inc(&nbd->config_refs);
1112 nsock->fallback_index = -1;
1114 nsock->dead = false;
1115 INIT_WORK(&args->work, recv_work);
1119 mutex_unlock(&nsock->tx_lock);
1122 clear_bit(NBD_RT_DISCONNECTED, &config->runtime_flags);
1124 /* We take the tx_mutex in an error path in the recv_work, so we
1125 * need to queue_work outside of the tx_mutex.
1127 queue_work(nbd->recv_workq, &args->work);
1129 atomic_inc(&config->live_connections);
1130 wake_up(&config->conn_wait);
1138 static void nbd_bdev_reset(struct block_device *bdev)
1140 if (bdev->bd_openers > 1)
1142 bd_set_nr_sectors(bdev, 0);
1145 static void nbd_parse_flags(struct nbd_device *nbd)
1147 struct nbd_config *config = nbd->config;
1148 if (config->flags & NBD_FLAG_READ_ONLY)
1149 set_disk_ro(nbd->disk, true);
1151 set_disk_ro(nbd->disk, false);
1152 if (config->flags & NBD_FLAG_SEND_TRIM)
1153 blk_queue_flag_set(QUEUE_FLAG_DISCARD, nbd->disk->queue);
1154 if (config->flags & NBD_FLAG_SEND_FLUSH) {
1155 if (config->flags & NBD_FLAG_SEND_FUA)
1156 blk_queue_write_cache(nbd->disk->queue, true, true);
1158 blk_queue_write_cache(nbd->disk->queue, true, false);
1161 blk_queue_write_cache(nbd->disk->queue, false, false);
1164 static void send_disconnects(struct nbd_device *nbd)
1166 struct nbd_config *config = nbd->config;
1167 struct nbd_request request = {
1168 .magic = htonl(NBD_REQUEST_MAGIC),
1169 .type = htonl(NBD_CMD_DISC),
1171 struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
1172 struct iov_iter from;
1175 for (i = 0; i < config->num_connections; i++) {
1176 struct nbd_sock *nsock = config->socks[i];
1178 iov_iter_kvec(&from, WRITE, &iov, 1, sizeof(request));
1179 mutex_lock(&nsock->tx_lock);
1180 ret = sock_xmit(nbd, i, 1, &from, 0, NULL);
1182 dev_err(disk_to_dev(nbd->disk),
1183 "Send disconnect failed %d\n", ret);
1184 mutex_unlock(&nsock->tx_lock);
1188 static int nbd_disconnect(struct nbd_device *nbd)
1190 struct nbd_config *config = nbd->config;
1192 dev_info(disk_to_dev(nbd->disk), "NBD_DISCONNECT\n");
1193 set_bit(NBD_RT_DISCONNECT_REQUESTED, &config->runtime_flags);
1194 set_bit(NBD_DISCONNECT_REQUESTED, &nbd->flags);
1195 send_disconnects(nbd);
1199 static void nbd_clear_sock(struct nbd_device *nbd)
1203 nbd->task_setup = NULL;
1206 static void nbd_config_put(struct nbd_device *nbd)
1208 if (refcount_dec_and_mutex_lock(&nbd->config_refs,
1209 &nbd->config_lock)) {
1210 struct nbd_config *config = nbd->config;
1211 nbd_dev_dbg_close(nbd);
1212 nbd_size_clear(nbd);
1213 if (test_and_clear_bit(NBD_RT_HAS_PID_FILE,
1214 &config->runtime_flags))
1215 device_remove_file(disk_to_dev(nbd->disk), &pid_attr);
1216 nbd->task_recv = NULL;
1217 nbd_clear_sock(nbd);
1218 if (config->num_connections) {
1220 for (i = 0; i < config->num_connections; i++) {
1221 sockfd_put(config->socks[i]->sock);
1222 kfree(config->socks[i]);
1224 kfree(config->socks);
1229 if (nbd->recv_workq)
1230 destroy_workqueue(nbd->recv_workq);
1231 nbd->recv_workq = NULL;
1233 nbd->tag_set.timeout = 0;
1234 nbd->disk->queue->limits.discard_granularity = 0;
1235 nbd->disk->queue->limits.discard_alignment = 0;
1236 blk_queue_max_discard_sectors(nbd->disk->queue, UINT_MAX);
1237 blk_queue_flag_clear(QUEUE_FLAG_DISCARD, nbd->disk->queue);
1239 mutex_unlock(&nbd->config_lock);
1241 module_put(THIS_MODULE);
1245 static int nbd_start_device(struct nbd_device *nbd)
1247 struct nbd_config *config = nbd->config;
1248 int num_connections = config->num_connections;
1255 if (num_connections > 1 &&
1256 !(config->flags & NBD_FLAG_CAN_MULTI_CONN)) {
1257 dev_err(disk_to_dev(nbd->disk), "server does not support multiple connections per device.\n");
1261 nbd->recv_workq = alloc_workqueue("knbd%d-recv",
1262 WQ_MEM_RECLAIM | WQ_HIGHPRI |
1263 WQ_UNBOUND, 0, nbd->index);
1264 if (!nbd->recv_workq) {
1265 dev_err(disk_to_dev(nbd->disk), "Could not allocate knbd recv work queue.\n");
1269 blk_mq_update_nr_hw_queues(&nbd->tag_set, config->num_connections);
1270 nbd->task_recv = current;
1272 nbd_parse_flags(nbd);
1274 error = device_create_file(disk_to_dev(nbd->disk), &pid_attr);
1276 dev_err(disk_to_dev(nbd->disk), "device_create_file failed!\n");
1279 set_bit(NBD_RT_HAS_PID_FILE, &config->runtime_flags);
1281 nbd_dev_dbg_init(nbd);
1282 for (i = 0; i < num_connections; i++) {
1283 struct recv_thread_args *args;
1285 args = kzalloc(sizeof(*args), GFP_KERNEL);
1289 * If num_connections is m (2 < m),
1290 * and NO.1 ~ NO.n(1 < n < m) kzallocs are successful.
1291 * But NO.(n + 1) failed. We still have n recv threads.
1292 * So, add flush_workqueue here to prevent recv threads
1293 * dropping the last config_refs and trying to destroy
1294 * the workqueue from inside the workqueue.
1297 flush_workqueue(nbd->recv_workq);
1300 sk_set_memalloc(config->socks[i]->sock->sk);
1301 if (nbd->tag_set.timeout)
1302 config->socks[i]->sock->sk->sk_sndtimeo =
1303 nbd->tag_set.timeout;
1304 atomic_inc(&config->recv_threads);
1305 refcount_inc(&nbd->config_refs);
1306 INIT_WORK(&args->work, recv_work);
1309 queue_work(nbd->recv_workq, &args->work);
1311 nbd_size_update(nbd);
1315 static int nbd_start_device_ioctl(struct nbd_device *nbd, struct block_device *bdev)
1317 struct nbd_config *config = nbd->config;
1320 ret = nbd_start_device(nbd);
1325 set_bit(GD_NEED_PART_SCAN, &nbd->disk->state);
1326 mutex_unlock(&nbd->config_lock);
1327 ret = wait_event_interruptible(config->recv_wq,
1328 atomic_read(&config->recv_threads) == 0);
1331 flush_workqueue(nbd->recv_workq);
1333 mutex_lock(&nbd->config_lock);
1334 nbd_bdev_reset(bdev);
1335 /* user requested, ignore socket errors */
1336 if (test_bit(NBD_RT_DISCONNECT_REQUESTED, &config->runtime_flags))
1338 if (test_bit(NBD_RT_TIMEDOUT, &config->runtime_flags))
1343 static void nbd_clear_sock_ioctl(struct nbd_device *nbd,
1344 struct block_device *bdev)
1347 __invalidate_device(bdev, true);
1348 nbd_bdev_reset(bdev);
1349 if (test_and_clear_bit(NBD_RT_HAS_CONFIG_REF,
1350 &nbd->config->runtime_flags))
1351 nbd_config_put(nbd);
1354 static bool nbd_is_valid_blksize(unsigned long blksize)
1356 if (!blksize || !is_power_of_2(blksize) || blksize < 512 ||
1357 blksize > PAGE_SIZE)
1362 static void nbd_set_cmd_timeout(struct nbd_device *nbd, u64 timeout)
1364 nbd->tag_set.timeout = timeout * HZ;
1366 blk_queue_rq_timeout(nbd->disk->queue, timeout * HZ);
1368 blk_queue_rq_timeout(nbd->disk->queue, 30 * HZ);
1371 /* Must be called with config_lock held */
1372 static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
1373 unsigned int cmd, unsigned long arg)
1375 struct nbd_config *config = nbd->config;
1378 case NBD_DISCONNECT:
1379 return nbd_disconnect(nbd);
1380 case NBD_CLEAR_SOCK:
1381 nbd_clear_sock_ioctl(nbd, bdev);
1384 return nbd_add_socket(nbd, arg, false);
1385 case NBD_SET_BLKSIZE:
1387 arg = NBD_DEF_BLKSIZE;
1388 if (!nbd_is_valid_blksize(arg))
1390 nbd_size_set(nbd, arg,
1391 div_s64(config->bytesize, arg));
1394 nbd_size_set(nbd, config->blksize,
1395 div_s64(arg, config->blksize));
1397 case NBD_SET_SIZE_BLOCKS:
1398 nbd_size_set(nbd, config->blksize, arg);
1400 case NBD_SET_TIMEOUT:
1401 nbd_set_cmd_timeout(nbd, arg);
1405 config->flags = arg;
1408 return nbd_start_device_ioctl(nbd, bdev);
1411 * This is for compatibility only. The queue is always cleared
1412 * by NBD_DO_IT or NBD_CLEAR_SOCK.
1415 case NBD_PRINT_DEBUG:
1417 * For compatibility only, we no longer keep a list of
1418 * outstanding requests.
1425 static int nbd_ioctl(struct block_device *bdev, fmode_t mode,
1426 unsigned int cmd, unsigned long arg)
1428 struct nbd_device *nbd = bdev->bd_disk->private_data;
1429 struct nbd_config *config = nbd->config;
1430 int error = -EINVAL;
1432 if (!capable(CAP_SYS_ADMIN))
1435 /* The block layer will pass back some non-nbd ioctls in case we have
1436 * special handling for them, but we don't so just return an error.
1438 if (_IOC_TYPE(cmd) != 0xab)
1441 mutex_lock(&nbd->config_lock);
1443 /* Don't allow ioctl operations on a nbd device that was created with
1444 * netlink, unless it's DISCONNECT or CLEAR_SOCK, which are fine.
1446 if (!test_bit(NBD_RT_BOUND, &config->runtime_flags) ||
1447 (cmd == NBD_DISCONNECT || cmd == NBD_CLEAR_SOCK))
1448 error = __nbd_ioctl(bdev, nbd, cmd, arg);
1450 dev_err(nbd_to_dev(nbd), "Cannot use ioctl interface on a netlink controlled device.\n");
1451 mutex_unlock(&nbd->config_lock);
1455 static struct nbd_config *nbd_alloc_config(void)
1457 struct nbd_config *config;
1459 config = kzalloc(sizeof(struct nbd_config), GFP_NOFS);
1462 atomic_set(&config->recv_threads, 0);
1463 init_waitqueue_head(&config->recv_wq);
1464 init_waitqueue_head(&config->conn_wait);
1465 config->blksize = NBD_DEF_BLKSIZE;
1466 atomic_set(&config->live_connections, 0);
1467 try_module_get(THIS_MODULE);
1471 static int nbd_open(struct block_device *bdev, fmode_t mode)
1473 struct nbd_device *nbd;
1476 mutex_lock(&nbd_index_mutex);
1477 nbd = bdev->bd_disk->private_data;
1482 if (!refcount_inc_not_zero(&nbd->refs)) {
1486 if (!refcount_inc_not_zero(&nbd->config_refs)) {
1487 struct nbd_config *config;
1489 mutex_lock(&nbd->config_lock);
1490 if (refcount_inc_not_zero(&nbd->config_refs)) {
1491 mutex_unlock(&nbd->config_lock);
1494 config = nbd->config = nbd_alloc_config();
1497 mutex_unlock(&nbd->config_lock);
1500 refcount_set(&nbd->config_refs, 1);
1501 refcount_inc(&nbd->refs);
1502 mutex_unlock(&nbd->config_lock);
1503 set_bit(GD_NEED_PART_SCAN, &bdev->bd_disk->state);
1504 } else if (nbd_disconnected(nbd->config)) {
1505 set_bit(GD_NEED_PART_SCAN, &bdev->bd_disk->state);
1508 mutex_unlock(&nbd_index_mutex);
1512 static void nbd_release(struct gendisk *disk, fmode_t mode)
1514 struct nbd_device *nbd = disk->private_data;
1515 struct block_device *bdev = bdget_disk(disk, 0);
1517 if (test_bit(NBD_RT_DISCONNECT_ON_CLOSE, &nbd->config->runtime_flags) &&
1518 bdev->bd_openers == 0)
1519 nbd_disconnect_and_put(nbd);
1521 nbd_config_put(nbd);
1525 static const struct block_device_operations nbd_fops =
1527 .owner = THIS_MODULE,
1529 .release = nbd_release,
1531 .compat_ioctl = nbd_ioctl,
1534 #if IS_ENABLED(CONFIG_DEBUG_FS)
1536 static int nbd_dbg_tasks_show(struct seq_file *s, void *unused)
1538 struct nbd_device *nbd = s->private;
1541 seq_printf(s, "recv: %d\n", task_pid_nr(nbd->task_recv));
1546 static int nbd_dbg_tasks_open(struct inode *inode, struct file *file)
1548 return single_open(file, nbd_dbg_tasks_show, inode->i_private);
1551 static const struct file_operations nbd_dbg_tasks_ops = {
1552 .open = nbd_dbg_tasks_open,
1554 .llseek = seq_lseek,
1555 .release = single_release,
1558 static int nbd_dbg_flags_show(struct seq_file *s, void *unused)
1560 struct nbd_device *nbd = s->private;
1561 u32 flags = nbd->config->flags;
1563 seq_printf(s, "Hex: 0x%08x\n\n", flags);
1565 seq_puts(s, "Known flags:\n");
1567 if (flags & NBD_FLAG_HAS_FLAGS)
1568 seq_puts(s, "NBD_FLAG_HAS_FLAGS\n");
1569 if (flags & NBD_FLAG_READ_ONLY)
1570 seq_puts(s, "NBD_FLAG_READ_ONLY\n");
1571 if (flags & NBD_FLAG_SEND_FLUSH)
1572 seq_puts(s, "NBD_FLAG_SEND_FLUSH\n");
1573 if (flags & NBD_FLAG_SEND_FUA)
1574 seq_puts(s, "NBD_FLAG_SEND_FUA\n");
1575 if (flags & NBD_FLAG_SEND_TRIM)
1576 seq_puts(s, "NBD_FLAG_SEND_TRIM\n");
1581 static int nbd_dbg_flags_open(struct inode *inode, struct file *file)
1583 return single_open(file, nbd_dbg_flags_show, inode->i_private);
1586 static const struct file_operations nbd_dbg_flags_ops = {
1587 .open = nbd_dbg_flags_open,
1589 .llseek = seq_lseek,
1590 .release = single_release,
1593 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1596 struct nbd_config *config = nbd->config;
1601 dir = debugfs_create_dir(nbd_name(nbd), nbd_dbg_dir);
1603 dev_err(nbd_to_dev(nbd), "Failed to create debugfs dir for '%s'\n",
1607 config->dbg_dir = dir;
1609 debugfs_create_file("tasks", 0444, dir, nbd, &nbd_dbg_tasks_ops);
1610 debugfs_create_u64("size_bytes", 0444, dir, &config->bytesize);
1611 debugfs_create_u32("timeout", 0444, dir, &nbd->tag_set.timeout);
1612 debugfs_create_u64("blocksize", 0444, dir, &config->blksize);
1613 debugfs_create_file("flags", 0444, dir, nbd, &nbd_dbg_flags_ops);
1618 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1620 debugfs_remove_recursive(nbd->config->dbg_dir);
1623 static int nbd_dbg_init(void)
1625 struct dentry *dbg_dir;
1627 dbg_dir = debugfs_create_dir("nbd", NULL);
1631 nbd_dbg_dir = dbg_dir;
1636 static void nbd_dbg_close(void)
1638 debugfs_remove_recursive(nbd_dbg_dir);
1641 #else /* IS_ENABLED(CONFIG_DEBUG_FS) */
1643 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1648 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1652 static int nbd_dbg_init(void)
1657 static void nbd_dbg_close(void)
1663 static int nbd_init_request(struct blk_mq_tag_set *set, struct request *rq,
1664 unsigned int hctx_idx, unsigned int numa_node)
1666 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(rq);
1667 cmd->nbd = set->driver_data;
1669 mutex_init(&cmd->lock);
1673 static const struct blk_mq_ops nbd_mq_ops = {
1674 .queue_rq = nbd_queue_rq,
1675 .complete = nbd_complete_rq,
1676 .init_request = nbd_init_request,
1677 .timeout = nbd_xmit_timeout,
1680 static int nbd_dev_add(int index)
1682 struct nbd_device *nbd;
1683 struct gendisk *disk;
1684 struct request_queue *q;
1687 nbd = kzalloc(sizeof(struct nbd_device), GFP_KERNEL);
1691 disk = alloc_disk(1 << part_shift);
1696 err = idr_alloc(&nbd_index_idr, nbd, index, index + 1,
1701 err = idr_alloc(&nbd_index_idr, nbd, 0, 0, GFP_KERNEL);
1710 nbd->tag_set.ops = &nbd_mq_ops;
1711 nbd->tag_set.nr_hw_queues = 1;
1712 nbd->tag_set.queue_depth = 128;
1713 nbd->tag_set.numa_node = NUMA_NO_NODE;
1714 nbd->tag_set.cmd_size = sizeof(struct nbd_cmd);
1715 nbd->tag_set.flags = BLK_MQ_F_SHOULD_MERGE |
1717 nbd->tag_set.driver_data = nbd;
1718 nbd->destroy_complete = NULL;
1720 err = blk_mq_alloc_tag_set(&nbd->tag_set);
1724 q = blk_mq_init_queue(&nbd->tag_set);
1732 * Tell the block layer that we are not a rotational device
1734 blk_queue_flag_set(QUEUE_FLAG_NONROT, disk->queue);
1735 blk_queue_flag_clear(QUEUE_FLAG_ADD_RANDOM, disk->queue);
1736 disk->queue->limits.discard_granularity = 0;
1737 disk->queue->limits.discard_alignment = 0;
1738 blk_queue_max_discard_sectors(disk->queue, 0);
1739 blk_queue_max_segment_size(disk->queue, UINT_MAX);
1740 blk_queue_max_segments(disk->queue, USHRT_MAX);
1741 blk_queue_max_hw_sectors(disk->queue, 65536);
1742 disk->queue->limits.max_sectors = 256;
1744 mutex_init(&nbd->config_lock);
1745 refcount_set(&nbd->config_refs, 0);
1746 refcount_set(&nbd->refs, 1);
1747 INIT_LIST_HEAD(&nbd->list);
1748 disk->major = NBD_MAJOR;
1749 disk->first_minor = index << part_shift;
1750 disk->fops = &nbd_fops;
1751 disk->private_data = nbd;
1752 sprintf(disk->disk_name, "nbd%d", index);
1754 nbd_total_devices++;
1758 blk_mq_free_tag_set(&nbd->tag_set);
1760 idr_remove(&nbd_index_idr, index);
1769 static int find_free_cb(int id, void *ptr, void *data)
1771 struct nbd_device *nbd = ptr;
1772 struct nbd_device **found = data;
1774 if (!refcount_read(&nbd->config_refs)) {
1781 /* Netlink interface. */
1782 static const struct nla_policy nbd_attr_policy[NBD_ATTR_MAX + 1] = {
1783 [NBD_ATTR_INDEX] = { .type = NLA_U32 },
1784 [NBD_ATTR_SIZE_BYTES] = { .type = NLA_U64 },
1785 [NBD_ATTR_BLOCK_SIZE_BYTES] = { .type = NLA_U64 },
1786 [NBD_ATTR_TIMEOUT] = { .type = NLA_U64 },
1787 [NBD_ATTR_SERVER_FLAGS] = { .type = NLA_U64 },
1788 [NBD_ATTR_CLIENT_FLAGS] = { .type = NLA_U64 },
1789 [NBD_ATTR_SOCKETS] = { .type = NLA_NESTED},
1790 [NBD_ATTR_DEAD_CONN_TIMEOUT] = { .type = NLA_U64 },
1791 [NBD_ATTR_DEVICE_LIST] = { .type = NLA_NESTED},
1794 static const struct nla_policy nbd_sock_policy[NBD_SOCK_MAX + 1] = {
1795 [NBD_SOCK_FD] = { .type = NLA_U32 },
1798 /* We don't use this right now since we don't parse the incoming list, but we
1799 * still want it here so userspace knows what to expect.
1801 static const struct nla_policy __attribute__((unused))
1802 nbd_device_policy[NBD_DEVICE_ATTR_MAX + 1] = {
1803 [NBD_DEVICE_INDEX] = { .type = NLA_U32 },
1804 [NBD_DEVICE_CONNECTED] = { .type = NLA_U8 },
1807 static int nbd_genl_size_set(struct genl_info *info, struct nbd_device *nbd)
1809 struct nbd_config *config = nbd->config;
1810 u64 bsize = config->blksize;
1811 u64 bytes = config->bytesize;
1813 if (info->attrs[NBD_ATTR_SIZE_BYTES])
1814 bytes = nla_get_u64(info->attrs[NBD_ATTR_SIZE_BYTES]);
1816 if (info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]) {
1817 bsize = nla_get_u64(info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]);
1819 bsize = NBD_DEF_BLKSIZE;
1820 if (!nbd_is_valid_blksize(bsize)) {
1821 printk(KERN_ERR "Invalid block size %llu\n", bsize);
1826 if (bytes != config->bytesize || bsize != config->blksize)
1827 nbd_size_set(nbd, bsize, div64_u64(bytes, bsize));
1831 static int nbd_genl_connect(struct sk_buff *skb, struct genl_info *info)
1833 DECLARE_COMPLETION_ONSTACK(destroy_complete);
1834 struct nbd_device *nbd = NULL;
1835 struct nbd_config *config;
1838 bool put_dev = false;
1840 if (!netlink_capable(skb, CAP_SYS_ADMIN))
1843 if (info->attrs[NBD_ATTR_INDEX])
1844 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1845 if (!info->attrs[NBD_ATTR_SOCKETS]) {
1846 printk(KERN_ERR "nbd: must specify at least one socket\n");
1849 if (!info->attrs[NBD_ATTR_SIZE_BYTES]) {
1850 printk(KERN_ERR "nbd: must specify a size in bytes for the device\n");
1854 mutex_lock(&nbd_index_mutex);
1856 ret = idr_for_each(&nbd_index_idr, &find_free_cb, &nbd);
1859 new_index = nbd_dev_add(-1);
1860 if (new_index < 0) {
1861 mutex_unlock(&nbd_index_mutex);
1862 printk(KERN_ERR "nbd: failed to add new device\n");
1865 nbd = idr_find(&nbd_index_idr, new_index);
1868 nbd = idr_find(&nbd_index_idr, index);
1870 ret = nbd_dev_add(index);
1872 mutex_unlock(&nbd_index_mutex);
1873 printk(KERN_ERR "nbd: failed to add new device\n");
1876 nbd = idr_find(&nbd_index_idr, index);
1880 printk(KERN_ERR "nbd: couldn't find device at index %d\n",
1882 mutex_unlock(&nbd_index_mutex);
1886 if (test_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags) &&
1887 test_bit(NBD_DISCONNECT_REQUESTED, &nbd->flags)) {
1888 nbd->destroy_complete = &destroy_complete;
1889 mutex_unlock(&nbd_index_mutex);
1891 /* Wait untill the the nbd stuff is totally destroyed */
1892 wait_for_completion(&destroy_complete);
1896 if (!refcount_inc_not_zero(&nbd->refs)) {
1897 mutex_unlock(&nbd_index_mutex);
1900 printk(KERN_ERR "nbd: device at index %d is going down\n",
1904 mutex_unlock(&nbd_index_mutex);
1906 mutex_lock(&nbd->config_lock);
1907 if (refcount_read(&nbd->config_refs)) {
1908 mutex_unlock(&nbd->config_lock);
1912 printk(KERN_ERR "nbd: nbd%d already in use\n", index);
1915 if (WARN_ON(nbd->config)) {
1916 mutex_unlock(&nbd->config_lock);
1920 config = nbd->config = nbd_alloc_config();
1922 mutex_unlock(&nbd->config_lock);
1924 printk(KERN_ERR "nbd: couldn't allocate config\n");
1927 refcount_set(&nbd->config_refs, 1);
1928 set_bit(NBD_RT_BOUND, &config->runtime_flags);
1930 ret = nbd_genl_size_set(info, nbd);
1934 if (info->attrs[NBD_ATTR_TIMEOUT])
1935 nbd_set_cmd_timeout(nbd,
1936 nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]));
1937 if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
1938 config->dead_conn_timeout =
1939 nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
1940 config->dead_conn_timeout *= HZ;
1942 if (info->attrs[NBD_ATTR_SERVER_FLAGS])
1944 nla_get_u64(info->attrs[NBD_ATTR_SERVER_FLAGS]);
1945 if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
1946 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
1947 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
1948 set_bit(NBD_RT_DESTROY_ON_DISCONNECT,
1949 &config->runtime_flags);
1950 set_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags);
1953 clear_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags);
1955 if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
1956 set_bit(NBD_RT_DISCONNECT_ON_CLOSE,
1957 &config->runtime_flags);
1961 if (info->attrs[NBD_ATTR_SOCKETS]) {
1962 struct nlattr *attr;
1965 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
1967 struct nlattr *socks[NBD_SOCK_MAX+1];
1969 if (nla_type(attr) != NBD_SOCK_ITEM) {
1970 printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
1974 ret = nla_parse_nested_deprecated(socks, NBD_SOCK_MAX,
1979 printk(KERN_ERR "nbd: error processing sock list\n");
1983 if (!socks[NBD_SOCK_FD])
1985 fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
1986 ret = nbd_add_socket(nbd, fd, true);
1991 ret = nbd_start_device(nbd);
1993 mutex_unlock(&nbd->config_lock);
1995 set_bit(NBD_RT_HAS_CONFIG_REF, &config->runtime_flags);
1996 refcount_inc(&nbd->config_refs);
1997 nbd_connect_reply(info, nbd->index);
1999 nbd_config_put(nbd);
2005 static void nbd_disconnect_and_put(struct nbd_device *nbd)
2007 mutex_lock(&nbd->config_lock);
2008 nbd_disconnect(nbd);
2009 nbd_clear_sock(nbd);
2010 mutex_unlock(&nbd->config_lock);
2012 * Make sure recv thread has finished, so it does not drop the last
2013 * config ref and try to destroy the workqueue from inside the work
2016 flush_workqueue(nbd->recv_workq);
2017 if (test_and_clear_bit(NBD_RT_HAS_CONFIG_REF,
2018 &nbd->config->runtime_flags))
2019 nbd_config_put(nbd);
2022 static int nbd_genl_disconnect(struct sk_buff *skb, struct genl_info *info)
2024 struct nbd_device *nbd;
2027 if (!netlink_capable(skb, CAP_SYS_ADMIN))
2030 if (!info->attrs[NBD_ATTR_INDEX]) {
2031 printk(KERN_ERR "nbd: must specify an index to disconnect\n");
2034 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2035 mutex_lock(&nbd_index_mutex);
2036 nbd = idr_find(&nbd_index_idr, index);
2038 mutex_unlock(&nbd_index_mutex);
2039 printk(KERN_ERR "nbd: couldn't find device at index %d\n",
2043 if (!refcount_inc_not_zero(&nbd->refs)) {
2044 mutex_unlock(&nbd_index_mutex);
2045 printk(KERN_ERR "nbd: device at index %d is going down\n",
2049 mutex_unlock(&nbd_index_mutex);
2050 if (!refcount_inc_not_zero(&nbd->config_refs)) {
2054 nbd_disconnect_and_put(nbd);
2055 nbd_config_put(nbd);
2060 static int nbd_genl_reconfigure(struct sk_buff *skb, struct genl_info *info)
2062 struct nbd_device *nbd = NULL;
2063 struct nbd_config *config;
2066 bool put_dev = false;
2068 if (!netlink_capable(skb, CAP_SYS_ADMIN))
2071 if (!info->attrs[NBD_ATTR_INDEX]) {
2072 printk(KERN_ERR "nbd: must specify a device to reconfigure\n");
2075 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2076 mutex_lock(&nbd_index_mutex);
2077 nbd = idr_find(&nbd_index_idr, index);
2079 mutex_unlock(&nbd_index_mutex);
2080 printk(KERN_ERR "nbd: couldn't find a device at index %d\n",
2084 if (!refcount_inc_not_zero(&nbd->refs)) {
2085 mutex_unlock(&nbd_index_mutex);
2086 printk(KERN_ERR "nbd: device at index %d is going down\n",
2090 mutex_unlock(&nbd_index_mutex);
2092 if (!refcount_inc_not_zero(&nbd->config_refs)) {
2093 dev_err(nbd_to_dev(nbd),
2094 "not configured, cannot reconfigure\n");
2099 mutex_lock(&nbd->config_lock);
2100 config = nbd->config;
2101 if (!test_bit(NBD_RT_BOUND, &config->runtime_flags) ||
2103 dev_err(nbd_to_dev(nbd),
2104 "not configured, cannot reconfigure\n");
2109 ret = nbd_genl_size_set(info, nbd);
2113 if (info->attrs[NBD_ATTR_TIMEOUT])
2114 nbd_set_cmd_timeout(nbd,
2115 nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]));
2116 if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
2117 config->dead_conn_timeout =
2118 nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
2119 config->dead_conn_timeout *= HZ;
2121 if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
2122 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
2123 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
2124 if (!test_and_set_bit(NBD_RT_DESTROY_ON_DISCONNECT,
2125 &config->runtime_flags))
2127 set_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags);
2129 if (test_and_clear_bit(NBD_RT_DESTROY_ON_DISCONNECT,
2130 &config->runtime_flags))
2131 refcount_inc(&nbd->refs);
2132 clear_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags);
2135 if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
2136 set_bit(NBD_RT_DISCONNECT_ON_CLOSE,
2137 &config->runtime_flags);
2139 clear_bit(NBD_RT_DISCONNECT_ON_CLOSE,
2140 &config->runtime_flags);
2144 if (info->attrs[NBD_ATTR_SOCKETS]) {
2145 struct nlattr *attr;
2148 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
2150 struct nlattr *socks[NBD_SOCK_MAX+1];
2152 if (nla_type(attr) != NBD_SOCK_ITEM) {
2153 printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
2157 ret = nla_parse_nested_deprecated(socks, NBD_SOCK_MAX,
2162 printk(KERN_ERR "nbd: error processing sock list\n");
2166 if (!socks[NBD_SOCK_FD])
2168 fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
2169 ret = nbd_reconnect_socket(nbd, fd);
2175 dev_info(nbd_to_dev(nbd), "reconnected socket\n");
2179 mutex_unlock(&nbd->config_lock);
2180 nbd_config_put(nbd);
2187 static const struct genl_small_ops nbd_connect_genl_ops[] = {
2189 .cmd = NBD_CMD_CONNECT,
2190 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2191 .doit = nbd_genl_connect,
2194 .cmd = NBD_CMD_DISCONNECT,
2195 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2196 .doit = nbd_genl_disconnect,
2199 .cmd = NBD_CMD_RECONFIGURE,
2200 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2201 .doit = nbd_genl_reconfigure,
2204 .cmd = NBD_CMD_STATUS,
2205 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2206 .doit = nbd_genl_status,
2210 static const struct genl_multicast_group nbd_mcast_grps[] = {
2211 { .name = NBD_GENL_MCAST_GROUP_NAME, },
2214 static struct genl_family nbd_genl_family __ro_after_init = {
2216 .name = NBD_GENL_FAMILY_NAME,
2217 .version = NBD_GENL_VERSION,
2218 .module = THIS_MODULE,
2219 .small_ops = nbd_connect_genl_ops,
2220 .n_small_ops = ARRAY_SIZE(nbd_connect_genl_ops),
2221 .maxattr = NBD_ATTR_MAX,
2222 .policy = nbd_attr_policy,
2223 .mcgrps = nbd_mcast_grps,
2224 .n_mcgrps = ARRAY_SIZE(nbd_mcast_grps),
2227 static int populate_nbd_status(struct nbd_device *nbd, struct sk_buff *reply)
2229 struct nlattr *dev_opt;
2233 /* This is a little racey, but for status it's ok. The
2234 * reason we don't take a ref here is because we can't
2235 * take a ref in the index == -1 case as we would need
2236 * to put under the nbd_index_mutex, which could
2237 * deadlock if we are configured to remove ourselves
2238 * once we're disconnected.
2240 if (refcount_read(&nbd->config_refs))
2242 dev_opt = nla_nest_start_noflag(reply, NBD_DEVICE_ITEM);
2245 ret = nla_put_u32(reply, NBD_DEVICE_INDEX, nbd->index);
2248 ret = nla_put_u8(reply, NBD_DEVICE_CONNECTED,
2252 nla_nest_end(reply, dev_opt);
2256 static int status_cb(int id, void *ptr, void *data)
2258 struct nbd_device *nbd = ptr;
2259 return populate_nbd_status(nbd, (struct sk_buff *)data);
2262 static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info)
2264 struct nlattr *dev_list;
2265 struct sk_buff *reply;
2271 if (info->attrs[NBD_ATTR_INDEX])
2272 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2274 mutex_lock(&nbd_index_mutex);
2276 msg_size = nla_total_size(nla_attr_size(sizeof(u32)) +
2277 nla_attr_size(sizeof(u8)));
2278 msg_size *= (index == -1) ? nbd_total_devices : 1;
2280 reply = genlmsg_new(msg_size, GFP_KERNEL);
2283 reply_head = genlmsg_put_reply(reply, info, &nbd_genl_family, 0,
2290 dev_list = nla_nest_start_noflag(reply, NBD_ATTR_DEVICE_LIST);
2292 ret = idr_for_each(&nbd_index_idr, &status_cb, reply);
2298 struct nbd_device *nbd;
2299 nbd = idr_find(&nbd_index_idr, index);
2301 ret = populate_nbd_status(nbd, reply);
2308 nla_nest_end(reply, dev_list);
2309 genlmsg_end(reply, reply_head);
2310 ret = genlmsg_reply(reply, info);
2312 mutex_unlock(&nbd_index_mutex);
2316 static void nbd_connect_reply(struct genl_info *info, int index)
2318 struct sk_buff *skb;
2322 skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2325 msg_head = genlmsg_put_reply(skb, info, &nbd_genl_family, 0,
2331 ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2336 genlmsg_end(skb, msg_head);
2337 genlmsg_reply(skb, info);
2340 static void nbd_mcast_index(int index)
2342 struct sk_buff *skb;
2346 skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2349 msg_head = genlmsg_put(skb, 0, 0, &nbd_genl_family, 0,
2355 ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2360 genlmsg_end(skb, msg_head);
2361 genlmsg_multicast(&nbd_genl_family, skb, 0, 0, GFP_KERNEL);
2364 static void nbd_dead_link_work(struct work_struct *work)
2366 struct link_dead_args *args = container_of(work, struct link_dead_args,
2368 nbd_mcast_index(args->index);
2372 static int __init nbd_init(void)
2376 BUILD_BUG_ON(sizeof(struct nbd_request) != 28);
2379 printk(KERN_ERR "nbd: max_part must be >= 0\n");
2385 part_shift = fls(max_part);
2388 * Adjust max_part according to part_shift as it is exported
2389 * to user space so that user can know the max number of
2390 * partition kernel should be able to manage.
2392 * Note that -1 is required because partition 0 is reserved
2393 * for the whole disk.
2395 max_part = (1UL << part_shift) - 1;
2398 if ((1UL << part_shift) > DISK_MAX_PARTS)
2401 if (nbds_max > 1UL << (MINORBITS - part_shift))
2404 if (register_blkdev(NBD_MAJOR, "nbd"))
2407 if (genl_register_family(&nbd_genl_family)) {
2408 unregister_blkdev(NBD_MAJOR, "nbd");
2413 mutex_lock(&nbd_index_mutex);
2414 for (i = 0; i < nbds_max; i++)
2416 mutex_unlock(&nbd_index_mutex);
2420 static int nbd_exit_cb(int id, void *ptr, void *data)
2422 struct list_head *list = (struct list_head *)data;
2423 struct nbd_device *nbd = ptr;
2425 list_add_tail(&nbd->list, list);
2429 static void __exit nbd_cleanup(void)
2431 struct nbd_device *nbd;
2432 LIST_HEAD(del_list);
2436 mutex_lock(&nbd_index_mutex);
2437 idr_for_each(&nbd_index_idr, &nbd_exit_cb, &del_list);
2438 mutex_unlock(&nbd_index_mutex);
2440 while (!list_empty(&del_list)) {
2441 nbd = list_first_entry(&del_list, struct nbd_device, list);
2442 list_del_init(&nbd->list);
2443 if (refcount_read(&nbd->refs) != 1)
2444 printk(KERN_ERR "nbd: possibly leaking a device\n");
2448 idr_destroy(&nbd_index_idr);
2449 genl_unregister_family(&nbd_genl_family);
2450 unregister_blkdev(NBD_MAJOR, "nbd");
2453 module_init(nbd_init);
2454 module_exit(nbd_cleanup);
2456 MODULE_DESCRIPTION("Network Block Device");
2457 MODULE_LICENSE("GPL");
2459 module_param(nbds_max, int, 0444);
2460 MODULE_PARM_DESC(nbds_max, "number of network block devices to initialize (default: 16)");
2461 module_param(max_part, int, 0444);
2462 MODULE_PARM_DESC(max_part, "number of partitions per device (default: 16)");