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 int nbd_set_size(struct nbd_device *nbd, loff_t bytesize,
303 blksize = NBD_DEF_BLKSIZE;
304 if (blksize < 512 || blksize > PAGE_SIZE || !is_power_of_2(blksize))
307 nbd->config->bytesize = bytesize;
308 nbd->config->blksize = blksize;
313 if (nbd->config->flags & NBD_FLAG_SEND_TRIM) {
314 nbd->disk->queue->limits.discard_granularity = blksize;
315 nbd->disk->queue->limits.discard_alignment = blksize;
316 blk_queue_max_discard_sectors(nbd->disk->queue, UINT_MAX);
318 blk_queue_logical_block_size(nbd->disk->queue, blksize);
319 blk_queue_physical_block_size(nbd->disk->queue, blksize);
321 set_bit(GD_NEED_PART_SCAN, &nbd->disk->state);
322 if (!set_capacity_and_notify(nbd->disk, bytesize >> 9))
323 kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
327 static void nbd_complete_rq(struct request *req)
329 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
331 dev_dbg(nbd_to_dev(cmd->nbd), "request %p: %s\n", req,
332 cmd->status ? "failed" : "done");
334 blk_mq_end_request(req, cmd->status);
338 * Forcibly shutdown the socket causing all listeners to error
340 static void sock_shutdown(struct nbd_device *nbd)
342 struct nbd_config *config = nbd->config;
345 if (config->num_connections == 0)
347 if (test_and_set_bit(NBD_RT_DISCONNECTED, &config->runtime_flags))
350 for (i = 0; i < config->num_connections; i++) {
351 struct nbd_sock *nsock = config->socks[i];
352 mutex_lock(&nsock->tx_lock);
353 nbd_mark_nsock_dead(nbd, nsock, 0);
354 mutex_unlock(&nsock->tx_lock);
356 dev_warn(disk_to_dev(nbd->disk), "shutting down sockets\n");
359 static u32 req_to_nbd_cmd_type(struct request *req)
361 switch (req_op(req)) {
365 return NBD_CMD_FLUSH;
367 return NBD_CMD_WRITE;
375 static enum blk_eh_timer_return nbd_xmit_timeout(struct request *req,
378 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
379 struct nbd_device *nbd = cmd->nbd;
380 struct nbd_config *config;
382 if (!mutex_trylock(&cmd->lock))
383 return BLK_EH_RESET_TIMER;
385 if (!refcount_inc_not_zero(&nbd->config_refs)) {
386 cmd->status = BLK_STS_TIMEOUT;
387 mutex_unlock(&cmd->lock);
390 config = nbd->config;
392 if (config->num_connections > 1 ||
393 (config->num_connections == 1 && nbd->tag_set.timeout)) {
394 dev_err_ratelimited(nbd_to_dev(nbd),
395 "Connection timed out, retrying (%d/%d alive)\n",
396 atomic_read(&config->live_connections),
397 config->num_connections);
399 * Hooray we have more connections, requeue this IO, the submit
400 * path will put it on a real connection. Or if only one
401 * connection is configured, the submit path will wait util
402 * a new connection is reconfigured or util dead timeout.
405 if (cmd->index < config->num_connections) {
406 struct nbd_sock *nsock =
407 config->socks[cmd->index];
408 mutex_lock(&nsock->tx_lock);
409 /* We can have multiple outstanding requests, so
410 * we don't want to mark the nsock dead if we've
411 * already reconnected with a new socket, so
412 * only mark it dead if its the same socket we
415 if (cmd->cookie == nsock->cookie)
416 nbd_mark_nsock_dead(nbd, nsock, 1);
417 mutex_unlock(&nsock->tx_lock);
419 mutex_unlock(&cmd->lock);
420 nbd_requeue_cmd(cmd);
426 if (!nbd->tag_set.timeout) {
428 * Userspace sets timeout=0 to disable socket disconnection,
429 * so just warn and reset the timer.
431 struct nbd_sock *nsock = config->socks[cmd->index];
433 dev_info(nbd_to_dev(nbd), "Possible stuck request %p: control (%s@%llu,%uB). Runtime %u seconds\n",
434 req, nbdcmd_to_ascii(req_to_nbd_cmd_type(req)),
435 (unsigned long long)blk_rq_pos(req) << 9,
436 blk_rq_bytes(req), (req->timeout / HZ) * cmd->retries);
438 mutex_lock(&nsock->tx_lock);
439 if (cmd->cookie != nsock->cookie) {
440 nbd_requeue_cmd(cmd);
441 mutex_unlock(&nsock->tx_lock);
442 mutex_unlock(&cmd->lock);
446 mutex_unlock(&nsock->tx_lock);
447 mutex_unlock(&cmd->lock);
449 return BLK_EH_RESET_TIMER;
452 dev_err_ratelimited(nbd_to_dev(nbd), "Connection timed out\n");
453 set_bit(NBD_RT_TIMEDOUT, &config->runtime_flags);
454 cmd->status = BLK_STS_IOERR;
455 mutex_unlock(&cmd->lock);
459 blk_mq_complete_request(req);
464 * Send or receive packet.
466 static int sock_xmit(struct nbd_device *nbd, int index, int send,
467 struct iov_iter *iter, int msg_flags, int *sent)
469 struct nbd_config *config = nbd->config;
470 struct socket *sock = config->socks[index]->sock;
473 unsigned int noreclaim_flag;
475 if (unlikely(!sock)) {
476 dev_err_ratelimited(disk_to_dev(nbd->disk),
477 "Attempted %s on closed socket in sock_xmit\n",
478 (send ? "send" : "recv"));
482 msg.msg_iter = *iter;
484 noreclaim_flag = memalloc_noreclaim_save();
486 sock->sk->sk_allocation = GFP_NOIO | __GFP_MEMALLOC;
489 msg.msg_control = NULL;
490 msg.msg_controllen = 0;
491 msg.msg_flags = msg_flags | MSG_NOSIGNAL;
494 result = sock_sendmsg(sock, &msg);
496 result = sock_recvmsg(sock, &msg, msg.msg_flags);
500 result = -EPIPE; /* short read */
505 } while (msg_data_left(&msg));
507 memalloc_noreclaim_restore(noreclaim_flag);
513 * Different settings for sk->sk_sndtimeo can result in different return values
514 * if there is a signal pending when we enter sendmsg, because reasons?
516 static inline int was_interrupted(int result)
518 return result == -ERESTARTSYS || result == -EINTR;
521 /* always call with the tx_lock held */
522 static int nbd_send_cmd(struct nbd_device *nbd, struct nbd_cmd *cmd, int index)
524 struct request *req = blk_mq_rq_from_pdu(cmd);
525 struct nbd_config *config = nbd->config;
526 struct nbd_sock *nsock = config->socks[index];
528 struct nbd_request request = {.magic = htonl(NBD_REQUEST_MAGIC)};
529 struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
530 struct iov_iter from;
531 unsigned long size = blk_rq_bytes(req);
535 u32 nbd_cmd_flags = 0;
536 int sent = nsock->sent, skip = 0;
538 iov_iter_kvec(&from, WRITE, &iov, 1, sizeof(request));
540 type = req_to_nbd_cmd_type(req);
544 if (rq_data_dir(req) == WRITE &&
545 (config->flags & NBD_FLAG_READ_ONLY)) {
546 dev_err_ratelimited(disk_to_dev(nbd->disk),
547 "Write on read-only\n");
551 if (req->cmd_flags & REQ_FUA)
552 nbd_cmd_flags |= NBD_CMD_FLAG_FUA;
554 /* We did a partial send previously, and we at least sent the whole
555 * request struct, so just go and send the rest of the pages in the
559 if (sent >= sizeof(request)) {
560 skip = sent - sizeof(request);
562 /* initialize handle for tracing purposes */
563 handle = nbd_cmd_handle(cmd);
567 iov_iter_advance(&from, sent);
572 cmd->cookie = nsock->cookie;
574 request.type = htonl(type | nbd_cmd_flags);
575 if (type != NBD_CMD_FLUSH) {
576 request.from = cpu_to_be64((u64)blk_rq_pos(req) << 9);
577 request.len = htonl(size);
579 handle = nbd_cmd_handle(cmd);
580 memcpy(request.handle, &handle, sizeof(handle));
582 trace_nbd_send_request(&request, nbd->index, blk_mq_rq_from_pdu(cmd));
584 dev_dbg(nbd_to_dev(nbd), "request %p: sending control (%s@%llu,%uB)\n",
585 req, nbdcmd_to_ascii(type),
586 (unsigned long long)blk_rq_pos(req) << 9, blk_rq_bytes(req));
587 result = sock_xmit(nbd, index, 1, &from,
588 (type == NBD_CMD_WRITE) ? MSG_MORE : 0, &sent);
589 trace_nbd_header_sent(req, handle);
591 if (was_interrupted(result)) {
592 /* If we havne't sent anything we can just return BUSY,
593 * however if we have sent something we need to make
594 * sure we only allow this req to be sent until we are
598 nsock->pending = req;
601 set_bit(NBD_CMD_REQUEUED, &cmd->flags);
602 return BLK_STS_RESOURCE;
604 dev_err_ratelimited(disk_to_dev(nbd->disk),
605 "Send control failed (result %d)\n", result);
609 if (type != NBD_CMD_WRITE)
614 struct bio *next = bio->bi_next;
615 struct bvec_iter iter;
618 bio_for_each_segment(bvec, bio, iter) {
619 bool is_last = !next && bio_iter_last(bvec, iter);
620 int flags = is_last ? 0 : MSG_MORE;
622 dev_dbg(nbd_to_dev(nbd), "request %p: sending %d bytes data\n",
624 iov_iter_bvec(&from, WRITE, &bvec, 1, bvec.bv_len);
626 if (skip >= iov_iter_count(&from)) {
627 skip -= iov_iter_count(&from);
630 iov_iter_advance(&from, skip);
633 result = sock_xmit(nbd, index, 1, &from, flags, &sent);
635 if (was_interrupted(result)) {
636 /* We've already sent the header, we
637 * have no choice but to set pending and
640 nsock->pending = req;
642 set_bit(NBD_CMD_REQUEUED, &cmd->flags);
643 return BLK_STS_RESOURCE;
645 dev_err(disk_to_dev(nbd->disk),
646 "Send data failed (result %d)\n",
651 * The completion might already have come in,
652 * so break for the last one instead of letting
653 * the iterator do it. This prevents use-after-free
662 trace_nbd_payload_sent(req, handle);
663 nsock->pending = NULL;
668 /* NULL returned = something went wrong, inform userspace */
669 static struct nbd_cmd *nbd_read_stat(struct nbd_device *nbd, int index)
671 struct nbd_config *config = nbd->config;
673 struct nbd_reply reply;
675 struct request *req = NULL;
679 struct kvec iov = {.iov_base = &reply, .iov_len = sizeof(reply)};
684 iov_iter_kvec(&to, READ, &iov, 1, sizeof(reply));
685 result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
687 if (!nbd_disconnected(config))
688 dev_err(disk_to_dev(nbd->disk),
689 "Receive control failed (result %d)\n", result);
690 return ERR_PTR(result);
693 if (ntohl(reply.magic) != NBD_REPLY_MAGIC) {
694 dev_err(disk_to_dev(nbd->disk), "Wrong magic (0x%lx)\n",
695 (unsigned long)ntohl(reply.magic));
696 return ERR_PTR(-EPROTO);
699 memcpy(&handle, reply.handle, sizeof(handle));
700 tag = nbd_handle_to_tag(handle);
701 hwq = blk_mq_unique_tag_to_hwq(tag);
702 if (hwq < nbd->tag_set.nr_hw_queues)
703 req = blk_mq_tag_to_rq(nbd->tag_set.tags[hwq],
704 blk_mq_unique_tag_to_tag(tag));
705 if (!req || !blk_mq_request_started(req)) {
706 dev_err(disk_to_dev(nbd->disk), "Unexpected reply (%d) %p\n",
708 return ERR_PTR(-ENOENT);
710 trace_nbd_header_received(req, handle);
711 cmd = blk_mq_rq_to_pdu(req);
713 mutex_lock(&cmd->lock);
714 if (cmd->cmd_cookie != nbd_handle_to_cookie(handle)) {
715 dev_err(disk_to_dev(nbd->disk), "Double reply on req %p, cmd_cookie %u, handle cookie %u\n",
716 req, cmd->cmd_cookie, nbd_handle_to_cookie(handle));
720 if (cmd->status != BLK_STS_OK) {
721 dev_err(disk_to_dev(nbd->disk), "Command already handled %p\n",
726 if (test_bit(NBD_CMD_REQUEUED, &cmd->flags)) {
727 dev_err(disk_to_dev(nbd->disk), "Raced with timeout on req %p\n",
732 if (ntohl(reply.error)) {
733 dev_err(disk_to_dev(nbd->disk), "Other side returned error (%d)\n",
735 cmd->status = BLK_STS_IOERR;
739 dev_dbg(nbd_to_dev(nbd), "request %p: got reply\n", req);
740 if (rq_data_dir(req) != WRITE) {
741 struct req_iterator iter;
744 rq_for_each_segment(bvec, req, iter) {
745 iov_iter_bvec(&to, READ, &bvec, 1, bvec.bv_len);
746 result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
748 dev_err(disk_to_dev(nbd->disk), "Receive data failed (result %d)\n",
751 * If we've disconnected, we need to make sure we
752 * complete this request, otherwise error out
753 * and let the timeout stuff handle resubmitting
754 * this request onto another connection.
756 if (nbd_disconnected(config)) {
757 cmd->status = BLK_STS_IOERR;
763 dev_dbg(nbd_to_dev(nbd), "request %p: got %d bytes data\n",
768 trace_nbd_payload_received(req, handle);
769 mutex_unlock(&cmd->lock);
770 return ret ? ERR_PTR(ret) : cmd;
773 static void recv_work(struct work_struct *work)
775 struct recv_thread_args *args = container_of(work,
776 struct recv_thread_args,
778 struct nbd_device *nbd = args->nbd;
779 struct nbd_config *config = nbd->config;
784 cmd = nbd_read_stat(nbd, args->index);
786 struct nbd_sock *nsock = config->socks[args->index];
788 mutex_lock(&nsock->tx_lock);
789 nbd_mark_nsock_dead(nbd, nsock, 1);
790 mutex_unlock(&nsock->tx_lock);
794 rq = blk_mq_rq_from_pdu(cmd);
795 if (likely(!blk_should_fake_timeout(rq->q)))
796 blk_mq_complete_request(rq);
799 atomic_dec(&config->recv_threads);
800 wake_up(&config->recv_wq);
804 static bool nbd_clear_req(struct request *req, void *data, bool reserved)
806 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
808 mutex_lock(&cmd->lock);
809 cmd->status = BLK_STS_IOERR;
810 mutex_unlock(&cmd->lock);
812 blk_mq_complete_request(req);
816 static void nbd_clear_que(struct nbd_device *nbd)
818 blk_mq_quiesce_queue(nbd->disk->queue);
819 blk_mq_tagset_busy_iter(&nbd->tag_set, nbd_clear_req, NULL);
820 blk_mq_unquiesce_queue(nbd->disk->queue);
821 dev_dbg(disk_to_dev(nbd->disk), "queue cleared\n");
824 static int find_fallback(struct nbd_device *nbd, int index)
826 struct nbd_config *config = nbd->config;
828 struct nbd_sock *nsock = config->socks[index];
829 int fallback = nsock->fallback_index;
831 if (test_bit(NBD_RT_DISCONNECTED, &config->runtime_flags))
834 if (config->num_connections <= 1) {
835 dev_err_ratelimited(disk_to_dev(nbd->disk),
836 "Dead connection, failed to find a fallback\n");
840 if (fallback >= 0 && fallback < config->num_connections &&
841 !config->socks[fallback]->dead)
844 if (nsock->fallback_index < 0 ||
845 nsock->fallback_index >= config->num_connections ||
846 config->socks[nsock->fallback_index]->dead) {
848 for (i = 0; i < config->num_connections; i++) {
851 if (!config->socks[i]->dead) {
856 nsock->fallback_index = new_index;
858 dev_err_ratelimited(disk_to_dev(nbd->disk),
859 "Dead connection, failed to find a fallback\n");
863 new_index = nsock->fallback_index;
867 static int wait_for_reconnect(struct nbd_device *nbd)
869 struct nbd_config *config = nbd->config;
870 if (!config->dead_conn_timeout)
872 if (test_bit(NBD_RT_DISCONNECTED, &config->runtime_flags))
874 return wait_event_timeout(config->conn_wait,
875 atomic_read(&config->live_connections) > 0,
876 config->dead_conn_timeout) > 0;
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);
1024 if (!netlink && !nbd->task_setup &&
1025 !test_bit(NBD_RT_BOUND, &config->runtime_flags))
1026 nbd->task_setup = current;
1029 (nbd->task_setup != current ||
1030 test_bit(NBD_RT_BOUND, &config->runtime_flags))) {
1031 dev_err(disk_to_dev(nbd->disk),
1032 "Device being setup by another task");
1037 nsock = kzalloc(sizeof(*nsock), GFP_KERNEL);
1043 socks = krealloc(config->socks, (config->num_connections + 1) *
1044 sizeof(struct nbd_sock *), GFP_KERNEL);
1051 config->socks = socks;
1053 nsock->fallback_index = -1;
1054 nsock->dead = false;
1055 mutex_init(&nsock->tx_lock);
1057 nsock->pending = NULL;
1060 socks[config->num_connections++] = nsock;
1061 atomic_inc(&config->live_connections);
1070 static int nbd_reconnect_socket(struct nbd_device *nbd, unsigned long arg)
1072 struct nbd_config *config = nbd->config;
1073 struct socket *sock, *old;
1074 struct recv_thread_args *args;
1078 sock = nbd_get_socket(nbd, arg, &err);
1082 args = kzalloc(sizeof(*args), GFP_KERNEL);
1088 for (i = 0; i < config->num_connections; i++) {
1089 struct nbd_sock *nsock = config->socks[i];
1094 mutex_lock(&nsock->tx_lock);
1096 mutex_unlock(&nsock->tx_lock);
1099 sk_set_memalloc(sock->sk);
1100 if (nbd->tag_set.timeout)
1101 sock->sk->sk_sndtimeo = nbd->tag_set.timeout;
1102 atomic_inc(&config->recv_threads);
1103 refcount_inc(&nbd->config_refs);
1105 nsock->fallback_index = -1;
1107 nsock->dead = false;
1108 INIT_WORK(&args->work, recv_work);
1112 mutex_unlock(&nsock->tx_lock);
1115 clear_bit(NBD_RT_DISCONNECTED, &config->runtime_flags);
1117 /* We take the tx_mutex in an error path in the recv_work, so we
1118 * need to queue_work outside of the tx_mutex.
1120 queue_work(nbd->recv_workq, &args->work);
1122 atomic_inc(&config->live_connections);
1123 wake_up(&config->conn_wait);
1131 static void nbd_bdev_reset(struct block_device *bdev)
1133 if (bdev->bd_openers > 1)
1135 bd_set_nr_sectors(bdev, 0);
1138 static void nbd_parse_flags(struct nbd_device *nbd)
1140 struct nbd_config *config = nbd->config;
1141 if (config->flags & NBD_FLAG_READ_ONLY)
1142 set_disk_ro(nbd->disk, true);
1144 set_disk_ro(nbd->disk, false);
1145 if (config->flags & NBD_FLAG_SEND_TRIM)
1146 blk_queue_flag_set(QUEUE_FLAG_DISCARD, nbd->disk->queue);
1147 if (config->flags & NBD_FLAG_SEND_FLUSH) {
1148 if (config->flags & NBD_FLAG_SEND_FUA)
1149 blk_queue_write_cache(nbd->disk->queue, true, true);
1151 blk_queue_write_cache(nbd->disk->queue, true, false);
1154 blk_queue_write_cache(nbd->disk->queue, false, false);
1157 static void send_disconnects(struct nbd_device *nbd)
1159 struct nbd_config *config = nbd->config;
1160 struct nbd_request request = {
1161 .magic = htonl(NBD_REQUEST_MAGIC),
1162 .type = htonl(NBD_CMD_DISC),
1164 struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
1165 struct iov_iter from;
1168 for (i = 0; i < config->num_connections; i++) {
1169 struct nbd_sock *nsock = config->socks[i];
1171 iov_iter_kvec(&from, WRITE, &iov, 1, sizeof(request));
1172 mutex_lock(&nsock->tx_lock);
1173 ret = sock_xmit(nbd, i, 1, &from, 0, NULL);
1175 dev_err(disk_to_dev(nbd->disk),
1176 "Send disconnect failed %d\n", ret);
1177 mutex_unlock(&nsock->tx_lock);
1181 static int nbd_disconnect(struct nbd_device *nbd)
1183 struct nbd_config *config = nbd->config;
1185 dev_info(disk_to_dev(nbd->disk), "NBD_DISCONNECT\n");
1186 set_bit(NBD_RT_DISCONNECT_REQUESTED, &config->runtime_flags);
1187 set_bit(NBD_DISCONNECT_REQUESTED, &nbd->flags);
1188 send_disconnects(nbd);
1192 static void nbd_clear_sock(struct nbd_device *nbd)
1196 nbd->task_setup = NULL;
1199 static void nbd_config_put(struct nbd_device *nbd)
1201 if (refcount_dec_and_mutex_lock(&nbd->config_refs,
1202 &nbd->config_lock)) {
1203 struct nbd_config *config = nbd->config;
1204 nbd_dev_dbg_close(nbd);
1205 nbd_size_clear(nbd);
1206 if (test_and_clear_bit(NBD_RT_HAS_PID_FILE,
1207 &config->runtime_flags))
1208 device_remove_file(disk_to_dev(nbd->disk), &pid_attr);
1209 nbd->task_recv = NULL;
1210 nbd_clear_sock(nbd);
1211 if (config->num_connections) {
1213 for (i = 0; i < config->num_connections; i++) {
1214 sockfd_put(config->socks[i]->sock);
1215 kfree(config->socks[i]);
1217 kfree(config->socks);
1222 if (nbd->recv_workq)
1223 destroy_workqueue(nbd->recv_workq);
1224 nbd->recv_workq = NULL;
1226 nbd->tag_set.timeout = 0;
1227 nbd->disk->queue->limits.discard_granularity = 0;
1228 nbd->disk->queue->limits.discard_alignment = 0;
1229 blk_queue_max_discard_sectors(nbd->disk->queue, UINT_MAX);
1230 blk_queue_flag_clear(QUEUE_FLAG_DISCARD, nbd->disk->queue);
1232 mutex_unlock(&nbd->config_lock);
1234 module_put(THIS_MODULE);
1238 static int nbd_start_device(struct nbd_device *nbd)
1240 struct nbd_config *config = nbd->config;
1241 int num_connections = config->num_connections;
1248 if (num_connections > 1 &&
1249 !(config->flags & NBD_FLAG_CAN_MULTI_CONN)) {
1250 dev_err(disk_to_dev(nbd->disk), "server does not support multiple connections per device.\n");
1254 nbd->recv_workq = alloc_workqueue("knbd%d-recv",
1255 WQ_MEM_RECLAIM | WQ_HIGHPRI |
1256 WQ_UNBOUND, 0, nbd->index);
1257 if (!nbd->recv_workq) {
1258 dev_err(disk_to_dev(nbd->disk), "Could not allocate knbd recv work queue.\n");
1262 blk_mq_update_nr_hw_queues(&nbd->tag_set, config->num_connections);
1263 nbd->task_recv = current;
1265 nbd_parse_flags(nbd);
1267 error = device_create_file(disk_to_dev(nbd->disk), &pid_attr);
1269 dev_err(disk_to_dev(nbd->disk), "device_create_file failed!\n");
1272 set_bit(NBD_RT_HAS_PID_FILE, &config->runtime_flags);
1274 nbd_dev_dbg_init(nbd);
1275 for (i = 0; i < num_connections; i++) {
1276 struct recv_thread_args *args;
1278 args = kzalloc(sizeof(*args), GFP_KERNEL);
1282 * If num_connections is m (2 < m),
1283 * and NO.1 ~ NO.n(1 < n < m) kzallocs are successful.
1284 * But NO.(n + 1) failed. We still have n recv threads.
1285 * So, add flush_workqueue here to prevent recv threads
1286 * dropping the last config_refs and trying to destroy
1287 * the workqueue from inside the workqueue.
1290 flush_workqueue(nbd->recv_workq);
1293 sk_set_memalloc(config->socks[i]->sock->sk);
1294 if (nbd->tag_set.timeout)
1295 config->socks[i]->sock->sk->sk_sndtimeo =
1296 nbd->tag_set.timeout;
1297 atomic_inc(&config->recv_threads);
1298 refcount_inc(&nbd->config_refs);
1299 INIT_WORK(&args->work, recv_work);
1302 queue_work(nbd->recv_workq, &args->work);
1304 return nbd_set_size(nbd, config->bytesize, config->blksize);
1307 static int nbd_start_device_ioctl(struct nbd_device *nbd, struct block_device *bdev)
1309 struct nbd_config *config = nbd->config;
1312 ret = nbd_start_device(nbd);
1317 set_bit(GD_NEED_PART_SCAN, &nbd->disk->state);
1318 mutex_unlock(&nbd->config_lock);
1319 ret = wait_event_interruptible(config->recv_wq,
1320 atomic_read(&config->recv_threads) == 0);
1323 flush_workqueue(nbd->recv_workq);
1325 mutex_lock(&nbd->config_lock);
1326 nbd_bdev_reset(bdev);
1327 /* user requested, ignore socket errors */
1328 if (test_bit(NBD_RT_DISCONNECT_REQUESTED, &config->runtime_flags))
1330 if (test_bit(NBD_RT_TIMEDOUT, &config->runtime_flags))
1335 static void nbd_clear_sock_ioctl(struct nbd_device *nbd,
1336 struct block_device *bdev)
1339 __invalidate_device(bdev, true);
1340 nbd_bdev_reset(bdev);
1341 if (test_and_clear_bit(NBD_RT_HAS_CONFIG_REF,
1342 &nbd->config->runtime_flags))
1343 nbd_config_put(nbd);
1346 static void nbd_set_cmd_timeout(struct nbd_device *nbd, u64 timeout)
1348 nbd->tag_set.timeout = timeout * HZ;
1350 blk_queue_rq_timeout(nbd->disk->queue, timeout * HZ);
1352 blk_queue_rq_timeout(nbd->disk->queue, 30 * HZ);
1355 /* Must be called with config_lock held */
1356 static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
1357 unsigned int cmd, unsigned long arg)
1359 struct nbd_config *config = nbd->config;
1362 case NBD_DISCONNECT:
1363 return nbd_disconnect(nbd);
1364 case NBD_CLEAR_SOCK:
1365 nbd_clear_sock_ioctl(nbd, bdev);
1368 return nbd_add_socket(nbd, arg, false);
1369 case NBD_SET_BLKSIZE:
1370 return nbd_set_size(nbd, config->bytesize, arg);
1372 return nbd_set_size(nbd, arg, config->blksize);
1373 case NBD_SET_SIZE_BLOCKS:
1374 return nbd_set_size(nbd, arg * config->blksize,
1376 case NBD_SET_TIMEOUT:
1377 nbd_set_cmd_timeout(nbd, arg);
1381 config->flags = arg;
1384 return nbd_start_device_ioctl(nbd, bdev);
1387 * This is for compatibility only. The queue is always cleared
1388 * by NBD_DO_IT or NBD_CLEAR_SOCK.
1391 case NBD_PRINT_DEBUG:
1393 * For compatibility only, we no longer keep a list of
1394 * outstanding requests.
1401 static int nbd_ioctl(struct block_device *bdev, fmode_t mode,
1402 unsigned int cmd, unsigned long arg)
1404 struct nbd_device *nbd = bdev->bd_disk->private_data;
1405 struct nbd_config *config = nbd->config;
1406 int error = -EINVAL;
1408 if (!capable(CAP_SYS_ADMIN))
1411 /* The block layer will pass back some non-nbd ioctls in case we have
1412 * special handling for them, but we don't so just return an error.
1414 if (_IOC_TYPE(cmd) != 0xab)
1417 mutex_lock(&nbd->config_lock);
1419 /* Don't allow ioctl operations on a nbd device that was created with
1420 * netlink, unless it's DISCONNECT or CLEAR_SOCK, which are fine.
1422 if (!test_bit(NBD_RT_BOUND, &config->runtime_flags) ||
1423 (cmd == NBD_DISCONNECT || cmd == NBD_CLEAR_SOCK))
1424 error = __nbd_ioctl(bdev, nbd, cmd, arg);
1426 dev_err(nbd_to_dev(nbd), "Cannot use ioctl interface on a netlink controlled device.\n");
1427 mutex_unlock(&nbd->config_lock);
1431 static struct nbd_config *nbd_alloc_config(void)
1433 struct nbd_config *config;
1435 config = kzalloc(sizeof(struct nbd_config), GFP_NOFS);
1438 atomic_set(&config->recv_threads, 0);
1439 init_waitqueue_head(&config->recv_wq);
1440 init_waitqueue_head(&config->conn_wait);
1441 config->blksize = NBD_DEF_BLKSIZE;
1442 atomic_set(&config->live_connections, 0);
1443 try_module_get(THIS_MODULE);
1447 static int nbd_open(struct block_device *bdev, fmode_t mode)
1449 struct nbd_device *nbd;
1452 mutex_lock(&nbd_index_mutex);
1453 nbd = bdev->bd_disk->private_data;
1458 if (!refcount_inc_not_zero(&nbd->refs)) {
1462 if (!refcount_inc_not_zero(&nbd->config_refs)) {
1463 struct nbd_config *config;
1465 mutex_lock(&nbd->config_lock);
1466 if (refcount_inc_not_zero(&nbd->config_refs)) {
1467 mutex_unlock(&nbd->config_lock);
1470 config = nbd->config = nbd_alloc_config();
1473 mutex_unlock(&nbd->config_lock);
1476 refcount_set(&nbd->config_refs, 1);
1477 refcount_inc(&nbd->refs);
1478 mutex_unlock(&nbd->config_lock);
1479 set_bit(GD_NEED_PART_SCAN, &bdev->bd_disk->state);
1480 } else if (nbd_disconnected(nbd->config)) {
1481 set_bit(GD_NEED_PART_SCAN, &bdev->bd_disk->state);
1484 mutex_unlock(&nbd_index_mutex);
1488 static void nbd_release(struct gendisk *disk, fmode_t mode)
1490 struct nbd_device *nbd = disk->private_data;
1491 struct block_device *bdev = bdget_disk(disk, 0);
1493 if (test_bit(NBD_RT_DISCONNECT_ON_CLOSE, &nbd->config->runtime_flags) &&
1494 bdev->bd_openers == 0)
1495 nbd_disconnect_and_put(nbd);
1498 nbd_config_put(nbd);
1502 static const struct block_device_operations nbd_fops =
1504 .owner = THIS_MODULE,
1506 .release = nbd_release,
1508 .compat_ioctl = nbd_ioctl,
1511 #if IS_ENABLED(CONFIG_DEBUG_FS)
1513 static int nbd_dbg_tasks_show(struct seq_file *s, void *unused)
1515 struct nbd_device *nbd = s->private;
1518 seq_printf(s, "recv: %d\n", task_pid_nr(nbd->task_recv));
1523 static int nbd_dbg_tasks_open(struct inode *inode, struct file *file)
1525 return single_open(file, nbd_dbg_tasks_show, inode->i_private);
1528 static const struct file_operations nbd_dbg_tasks_ops = {
1529 .open = nbd_dbg_tasks_open,
1531 .llseek = seq_lseek,
1532 .release = single_release,
1535 static int nbd_dbg_flags_show(struct seq_file *s, void *unused)
1537 struct nbd_device *nbd = s->private;
1538 u32 flags = nbd->config->flags;
1540 seq_printf(s, "Hex: 0x%08x\n\n", flags);
1542 seq_puts(s, "Known flags:\n");
1544 if (flags & NBD_FLAG_HAS_FLAGS)
1545 seq_puts(s, "NBD_FLAG_HAS_FLAGS\n");
1546 if (flags & NBD_FLAG_READ_ONLY)
1547 seq_puts(s, "NBD_FLAG_READ_ONLY\n");
1548 if (flags & NBD_FLAG_SEND_FLUSH)
1549 seq_puts(s, "NBD_FLAG_SEND_FLUSH\n");
1550 if (flags & NBD_FLAG_SEND_FUA)
1551 seq_puts(s, "NBD_FLAG_SEND_FUA\n");
1552 if (flags & NBD_FLAG_SEND_TRIM)
1553 seq_puts(s, "NBD_FLAG_SEND_TRIM\n");
1558 static int nbd_dbg_flags_open(struct inode *inode, struct file *file)
1560 return single_open(file, nbd_dbg_flags_show, inode->i_private);
1563 static const struct file_operations nbd_dbg_flags_ops = {
1564 .open = nbd_dbg_flags_open,
1566 .llseek = seq_lseek,
1567 .release = single_release,
1570 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1573 struct nbd_config *config = nbd->config;
1578 dir = debugfs_create_dir(nbd_name(nbd), nbd_dbg_dir);
1580 dev_err(nbd_to_dev(nbd), "Failed to create debugfs dir for '%s'\n",
1584 config->dbg_dir = dir;
1586 debugfs_create_file("tasks", 0444, dir, nbd, &nbd_dbg_tasks_ops);
1587 debugfs_create_u64("size_bytes", 0444, dir, &config->bytesize);
1588 debugfs_create_u32("timeout", 0444, dir, &nbd->tag_set.timeout);
1589 debugfs_create_u64("blocksize", 0444, dir, &config->blksize);
1590 debugfs_create_file("flags", 0444, dir, nbd, &nbd_dbg_flags_ops);
1595 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1597 debugfs_remove_recursive(nbd->config->dbg_dir);
1600 static int nbd_dbg_init(void)
1602 struct dentry *dbg_dir;
1604 dbg_dir = debugfs_create_dir("nbd", NULL);
1608 nbd_dbg_dir = dbg_dir;
1613 static void nbd_dbg_close(void)
1615 debugfs_remove_recursive(nbd_dbg_dir);
1618 #else /* IS_ENABLED(CONFIG_DEBUG_FS) */
1620 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1625 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1629 static int nbd_dbg_init(void)
1634 static void nbd_dbg_close(void)
1640 static int nbd_init_request(struct blk_mq_tag_set *set, struct request *rq,
1641 unsigned int hctx_idx, unsigned int numa_node)
1643 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(rq);
1644 cmd->nbd = set->driver_data;
1646 mutex_init(&cmd->lock);
1650 static const struct blk_mq_ops nbd_mq_ops = {
1651 .queue_rq = nbd_queue_rq,
1652 .complete = nbd_complete_rq,
1653 .init_request = nbd_init_request,
1654 .timeout = nbd_xmit_timeout,
1657 static int nbd_dev_add(int index)
1659 struct nbd_device *nbd;
1660 struct gendisk *disk;
1661 struct request_queue *q;
1664 nbd = kzalloc(sizeof(struct nbd_device), GFP_KERNEL);
1668 disk = alloc_disk(1 << part_shift);
1673 err = idr_alloc(&nbd_index_idr, nbd, index, index + 1,
1678 err = idr_alloc(&nbd_index_idr, nbd, 0, 0, GFP_KERNEL);
1687 nbd->tag_set.ops = &nbd_mq_ops;
1688 nbd->tag_set.nr_hw_queues = 1;
1689 nbd->tag_set.queue_depth = 128;
1690 nbd->tag_set.numa_node = NUMA_NO_NODE;
1691 nbd->tag_set.cmd_size = sizeof(struct nbd_cmd);
1692 nbd->tag_set.flags = BLK_MQ_F_SHOULD_MERGE |
1694 nbd->tag_set.driver_data = nbd;
1695 nbd->destroy_complete = NULL;
1697 err = blk_mq_alloc_tag_set(&nbd->tag_set);
1701 q = blk_mq_init_queue(&nbd->tag_set);
1709 * Tell the block layer that we are not a rotational device
1711 blk_queue_flag_set(QUEUE_FLAG_NONROT, disk->queue);
1712 blk_queue_flag_clear(QUEUE_FLAG_ADD_RANDOM, disk->queue);
1713 disk->queue->limits.discard_granularity = 0;
1714 disk->queue->limits.discard_alignment = 0;
1715 blk_queue_max_discard_sectors(disk->queue, 0);
1716 blk_queue_max_segment_size(disk->queue, UINT_MAX);
1717 blk_queue_max_segments(disk->queue, USHRT_MAX);
1718 blk_queue_max_hw_sectors(disk->queue, 65536);
1719 disk->queue->limits.max_sectors = 256;
1721 mutex_init(&nbd->config_lock);
1722 refcount_set(&nbd->config_refs, 0);
1723 refcount_set(&nbd->refs, 1);
1724 INIT_LIST_HEAD(&nbd->list);
1725 disk->major = NBD_MAJOR;
1726 disk->first_minor = index << part_shift;
1727 disk->fops = &nbd_fops;
1728 disk->private_data = nbd;
1729 sprintf(disk->disk_name, "nbd%d", index);
1731 nbd_total_devices++;
1735 blk_mq_free_tag_set(&nbd->tag_set);
1737 idr_remove(&nbd_index_idr, index);
1746 static int find_free_cb(int id, void *ptr, void *data)
1748 struct nbd_device *nbd = ptr;
1749 struct nbd_device **found = data;
1751 if (!refcount_read(&nbd->config_refs)) {
1758 /* Netlink interface. */
1759 static const struct nla_policy nbd_attr_policy[NBD_ATTR_MAX + 1] = {
1760 [NBD_ATTR_INDEX] = { .type = NLA_U32 },
1761 [NBD_ATTR_SIZE_BYTES] = { .type = NLA_U64 },
1762 [NBD_ATTR_BLOCK_SIZE_BYTES] = { .type = NLA_U64 },
1763 [NBD_ATTR_TIMEOUT] = { .type = NLA_U64 },
1764 [NBD_ATTR_SERVER_FLAGS] = { .type = NLA_U64 },
1765 [NBD_ATTR_CLIENT_FLAGS] = { .type = NLA_U64 },
1766 [NBD_ATTR_SOCKETS] = { .type = NLA_NESTED},
1767 [NBD_ATTR_DEAD_CONN_TIMEOUT] = { .type = NLA_U64 },
1768 [NBD_ATTR_DEVICE_LIST] = { .type = NLA_NESTED},
1771 static const struct nla_policy nbd_sock_policy[NBD_SOCK_MAX + 1] = {
1772 [NBD_SOCK_FD] = { .type = NLA_U32 },
1775 /* We don't use this right now since we don't parse the incoming list, but we
1776 * still want it here so userspace knows what to expect.
1778 static const struct nla_policy __attribute__((unused))
1779 nbd_device_policy[NBD_DEVICE_ATTR_MAX + 1] = {
1780 [NBD_DEVICE_INDEX] = { .type = NLA_U32 },
1781 [NBD_DEVICE_CONNECTED] = { .type = NLA_U8 },
1784 static int nbd_genl_size_set(struct genl_info *info, struct nbd_device *nbd)
1786 struct nbd_config *config = nbd->config;
1787 u64 bsize = config->blksize;
1788 u64 bytes = config->bytesize;
1790 if (info->attrs[NBD_ATTR_SIZE_BYTES])
1791 bytes = nla_get_u64(info->attrs[NBD_ATTR_SIZE_BYTES]);
1793 if (info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES])
1794 bsize = nla_get_u64(info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]);
1796 if (bytes != config->bytesize || bsize != config->blksize)
1797 return nbd_set_size(nbd, bytes, bsize);
1801 static int nbd_genl_connect(struct sk_buff *skb, struct genl_info *info)
1803 DECLARE_COMPLETION_ONSTACK(destroy_complete);
1804 struct nbd_device *nbd = NULL;
1805 struct nbd_config *config;
1808 bool put_dev = false;
1810 if (!netlink_capable(skb, CAP_SYS_ADMIN))
1813 if (info->attrs[NBD_ATTR_INDEX])
1814 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1815 if (!info->attrs[NBD_ATTR_SOCKETS]) {
1816 printk(KERN_ERR "nbd: must specify at least one socket\n");
1819 if (!info->attrs[NBD_ATTR_SIZE_BYTES]) {
1820 printk(KERN_ERR "nbd: must specify a size in bytes for the device\n");
1824 mutex_lock(&nbd_index_mutex);
1826 ret = idr_for_each(&nbd_index_idr, &find_free_cb, &nbd);
1829 new_index = nbd_dev_add(-1);
1830 if (new_index < 0) {
1831 mutex_unlock(&nbd_index_mutex);
1832 printk(KERN_ERR "nbd: failed to add new device\n");
1835 nbd = idr_find(&nbd_index_idr, new_index);
1838 nbd = idr_find(&nbd_index_idr, index);
1840 ret = nbd_dev_add(index);
1842 mutex_unlock(&nbd_index_mutex);
1843 printk(KERN_ERR "nbd: failed to add new device\n");
1846 nbd = idr_find(&nbd_index_idr, index);
1850 printk(KERN_ERR "nbd: couldn't find device at index %d\n",
1852 mutex_unlock(&nbd_index_mutex);
1856 if (test_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags) &&
1857 test_bit(NBD_DISCONNECT_REQUESTED, &nbd->flags)) {
1858 nbd->destroy_complete = &destroy_complete;
1859 mutex_unlock(&nbd_index_mutex);
1861 /* Wait untill the the nbd stuff is totally destroyed */
1862 wait_for_completion(&destroy_complete);
1866 if (!refcount_inc_not_zero(&nbd->refs)) {
1867 mutex_unlock(&nbd_index_mutex);
1870 printk(KERN_ERR "nbd: device at index %d is going down\n",
1874 mutex_unlock(&nbd_index_mutex);
1876 mutex_lock(&nbd->config_lock);
1877 if (refcount_read(&nbd->config_refs)) {
1878 mutex_unlock(&nbd->config_lock);
1882 printk(KERN_ERR "nbd: nbd%d already in use\n", index);
1885 if (WARN_ON(nbd->config)) {
1886 mutex_unlock(&nbd->config_lock);
1890 config = nbd->config = nbd_alloc_config();
1892 mutex_unlock(&nbd->config_lock);
1894 printk(KERN_ERR "nbd: couldn't allocate config\n");
1897 refcount_set(&nbd->config_refs, 1);
1898 set_bit(NBD_RT_BOUND, &config->runtime_flags);
1900 ret = nbd_genl_size_set(info, nbd);
1904 if (info->attrs[NBD_ATTR_TIMEOUT])
1905 nbd_set_cmd_timeout(nbd,
1906 nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]));
1907 if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
1908 config->dead_conn_timeout =
1909 nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
1910 config->dead_conn_timeout *= HZ;
1912 if (info->attrs[NBD_ATTR_SERVER_FLAGS])
1914 nla_get_u64(info->attrs[NBD_ATTR_SERVER_FLAGS]);
1915 if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
1916 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
1917 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
1918 set_bit(NBD_RT_DESTROY_ON_DISCONNECT,
1919 &config->runtime_flags);
1920 set_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags);
1923 clear_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags);
1925 if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
1926 set_bit(NBD_RT_DISCONNECT_ON_CLOSE,
1927 &config->runtime_flags);
1931 if (info->attrs[NBD_ATTR_SOCKETS]) {
1932 struct nlattr *attr;
1935 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
1937 struct nlattr *socks[NBD_SOCK_MAX+1];
1939 if (nla_type(attr) != NBD_SOCK_ITEM) {
1940 printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
1944 ret = nla_parse_nested_deprecated(socks, NBD_SOCK_MAX,
1949 printk(KERN_ERR "nbd: error processing sock list\n");
1953 if (!socks[NBD_SOCK_FD])
1955 fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
1956 ret = nbd_add_socket(nbd, fd, true);
1961 ret = nbd_start_device(nbd);
1963 mutex_unlock(&nbd->config_lock);
1965 set_bit(NBD_RT_HAS_CONFIG_REF, &config->runtime_flags);
1966 refcount_inc(&nbd->config_refs);
1967 nbd_connect_reply(info, nbd->index);
1969 nbd_config_put(nbd);
1975 static void nbd_disconnect_and_put(struct nbd_device *nbd)
1977 mutex_lock(&nbd->config_lock);
1978 nbd_disconnect(nbd);
1979 nbd_clear_sock(nbd);
1980 mutex_unlock(&nbd->config_lock);
1982 * Make sure recv thread has finished, so it does not drop the last
1983 * config ref and try to destroy the workqueue from inside the work
1986 flush_workqueue(nbd->recv_workq);
1987 if (test_and_clear_bit(NBD_RT_HAS_CONFIG_REF,
1988 &nbd->config->runtime_flags))
1989 nbd_config_put(nbd);
1992 static int nbd_genl_disconnect(struct sk_buff *skb, struct genl_info *info)
1994 struct nbd_device *nbd;
1997 if (!netlink_capable(skb, CAP_SYS_ADMIN))
2000 if (!info->attrs[NBD_ATTR_INDEX]) {
2001 printk(KERN_ERR "nbd: must specify an index to disconnect\n");
2004 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2005 mutex_lock(&nbd_index_mutex);
2006 nbd = idr_find(&nbd_index_idr, index);
2008 mutex_unlock(&nbd_index_mutex);
2009 printk(KERN_ERR "nbd: couldn't find device at index %d\n",
2013 if (!refcount_inc_not_zero(&nbd->refs)) {
2014 mutex_unlock(&nbd_index_mutex);
2015 printk(KERN_ERR "nbd: device at index %d is going down\n",
2019 mutex_unlock(&nbd_index_mutex);
2020 if (!refcount_inc_not_zero(&nbd->config_refs)) {
2024 nbd_disconnect_and_put(nbd);
2025 nbd_config_put(nbd);
2030 static int nbd_genl_reconfigure(struct sk_buff *skb, struct genl_info *info)
2032 struct nbd_device *nbd = NULL;
2033 struct nbd_config *config;
2036 bool put_dev = false;
2038 if (!netlink_capable(skb, CAP_SYS_ADMIN))
2041 if (!info->attrs[NBD_ATTR_INDEX]) {
2042 printk(KERN_ERR "nbd: must specify a device to reconfigure\n");
2045 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2046 mutex_lock(&nbd_index_mutex);
2047 nbd = idr_find(&nbd_index_idr, index);
2049 mutex_unlock(&nbd_index_mutex);
2050 printk(KERN_ERR "nbd: couldn't find a device at index %d\n",
2054 if (!refcount_inc_not_zero(&nbd->refs)) {
2055 mutex_unlock(&nbd_index_mutex);
2056 printk(KERN_ERR "nbd: device at index %d is going down\n",
2060 mutex_unlock(&nbd_index_mutex);
2062 if (!refcount_inc_not_zero(&nbd->config_refs)) {
2063 dev_err(nbd_to_dev(nbd),
2064 "not configured, cannot reconfigure\n");
2069 mutex_lock(&nbd->config_lock);
2070 config = nbd->config;
2071 if (!test_bit(NBD_RT_BOUND, &config->runtime_flags) ||
2073 dev_err(nbd_to_dev(nbd),
2074 "not configured, cannot reconfigure\n");
2079 ret = nbd_genl_size_set(info, nbd);
2083 if (info->attrs[NBD_ATTR_TIMEOUT])
2084 nbd_set_cmd_timeout(nbd,
2085 nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]));
2086 if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
2087 config->dead_conn_timeout =
2088 nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
2089 config->dead_conn_timeout *= HZ;
2091 if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
2092 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
2093 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
2094 if (!test_and_set_bit(NBD_RT_DESTROY_ON_DISCONNECT,
2095 &config->runtime_flags))
2097 set_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags);
2099 if (test_and_clear_bit(NBD_RT_DESTROY_ON_DISCONNECT,
2100 &config->runtime_flags))
2101 refcount_inc(&nbd->refs);
2102 clear_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags);
2105 if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
2106 set_bit(NBD_RT_DISCONNECT_ON_CLOSE,
2107 &config->runtime_flags);
2109 clear_bit(NBD_RT_DISCONNECT_ON_CLOSE,
2110 &config->runtime_flags);
2114 if (info->attrs[NBD_ATTR_SOCKETS]) {
2115 struct nlattr *attr;
2118 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
2120 struct nlattr *socks[NBD_SOCK_MAX+1];
2122 if (nla_type(attr) != NBD_SOCK_ITEM) {
2123 printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
2127 ret = nla_parse_nested_deprecated(socks, NBD_SOCK_MAX,
2132 printk(KERN_ERR "nbd: error processing sock list\n");
2136 if (!socks[NBD_SOCK_FD])
2138 fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
2139 ret = nbd_reconnect_socket(nbd, fd);
2145 dev_info(nbd_to_dev(nbd), "reconnected socket\n");
2149 mutex_unlock(&nbd->config_lock);
2150 nbd_config_put(nbd);
2157 static const struct genl_small_ops nbd_connect_genl_ops[] = {
2159 .cmd = NBD_CMD_CONNECT,
2160 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2161 .doit = nbd_genl_connect,
2164 .cmd = NBD_CMD_DISCONNECT,
2165 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2166 .doit = nbd_genl_disconnect,
2169 .cmd = NBD_CMD_RECONFIGURE,
2170 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2171 .doit = nbd_genl_reconfigure,
2174 .cmd = NBD_CMD_STATUS,
2175 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2176 .doit = nbd_genl_status,
2180 static const struct genl_multicast_group nbd_mcast_grps[] = {
2181 { .name = NBD_GENL_MCAST_GROUP_NAME, },
2184 static struct genl_family nbd_genl_family __ro_after_init = {
2186 .name = NBD_GENL_FAMILY_NAME,
2187 .version = NBD_GENL_VERSION,
2188 .module = THIS_MODULE,
2189 .small_ops = nbd_connect_genl_ops,
2190 .n_small_ops = ARRAY_SIZE(nbd_connect_genl_ops),
2191 .maxattr = NBD_ATTR_MAX,
2192 .policy = nbd_attr_policy,
2193 .mcgrps = nbd_mcast_grps,
2194 .n_mcgrps = ARRAY_SIZE(nbd_mcast_grps),
2197 static int populate_nbd_status(struct nbd_device *nbd, struct sk_buff *reply)
2199 struct nlattr *dev_opt;
2203 /* This is a little racey, but for status it's ok. The
2204 * reason we don't take a ref here is because we can't
2205 * take a ref in the index == -1 case as we would need
2206 * to put under the nbd_index_mutex, which could
2207 * deadlock if we are configured to remove ourselves
2208 * once we're disconnected.
2210 if (refcount_read(&nbd->config_refs))
2212 dev_opt = nla_nest_start_noflag(reply, NBD_DEVICE_ITEM);
2215 ret = nla_put_u32(reply, NBD_DEVICE_INDEX, nbd->index);
2218 ret = nla_put_u8(reply, NBD_DEVICE_CONNECTED,
2222 nla_nest_end(reply, dev_opt);
2226 static int status_cb(int id, void *ptr, void *data)
2228 struct nbd_device *nbd = ptr;
2229 return populate_nbd_status(nbd, (struct sk_buff *)data);
2232 static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info)
2234 struct nlattr *dev_list;
2235 struct sk_buff *reply;
2241 if (info->attrs[NBD_ATTR_INDEX])
2242 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2244 mutex_lock(&nbd_index_mutex);
2246 msg_size = nla_total_size(nla_attr_size(sizeof(u32)) +
2247 nla_attr_size(sizeof(u8)));
2248 msg_size *= (index == -1) ? nbd_total_devices : 1;
2250 reply = genlmsg_new(msg_size, GFP_KERNEL);
2253 reply_head = genlmsg_put_reply(reply, info, &nbd_genl_family, 0,
2260 dev_list = nla_nest_start_noflag(reply, NBD_ATTR_DEVICE_LIST);
2262 ret = idr_for_each(&nbd_index_idr, &status_cb, reply);
2268 struct nbd_device *nbd;
2269 nbd = idr_find(&nbd_index_idr, index);
2271 ret = populate_nbd_status(nbd, reply);
2278 nla_nest_end(reply, dev_list);
2279 genlmsg_end(reply, reply_head);
2280 ret = genlmsg_reply(reply, info);
2282 mutex_unlock(&nbd_index_mutex);
2286 static void nbd_connect_reply(struct genl_info *info, int index)
2288 struct sk_buff *skb;
2292 skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2295 msg_head = genlmsg_put_reply(skb, info, &nbd_genl_family, 0,
2301 ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2306 genlmsg_end(skb, msg_head);
2307 genlmsg_reply(skb, info);
2310 static void nbd_mcast_index(int index)
2312 struct sk_buff *skb;
2316 skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2319 msg_head = genlmsg_put(skb, 0, 0, &nbd_genl_family, 0,
2325 ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2330 genlmsg_end(skb, msg_head);
2331 genlmsg_multicast(&nbd_genl_family, skb, 0, 0, GFP_KERNEL);
2334 static void nbd_dead_link_work(struct work_struct *work)
2336 struct link_dead_args *args = container_of(work, struct link_dead_args,
2338 nbd_mcast_index(args->index);
2342 static int __init nbd_init(void)
2346 BUILD_BUG_ON(sizeof(struct nbd_request) != 28);
2349 printk(KERN_ERR "nbd: max_part must be >= 0\n");
2355 part_shift = fls(max_part);
2358 * Adjust max_part according to part_shift as it is exported
2359 * to user space so that user can know the max number of
2360 * partition kernel should be able to manage.
2362 * Note that -1 is required because partition 0 is reserved
2363 * for the whole disk.
2365 max_part = (1UL << part_shift) - 1;
2368 if ((1UL << part_shift) > DISK_MAX_PARTS)
2371 if (nbds_max > 1UL << (MINORBITS - part_shift))
2374 if (register_blkdev(NBD_MAJOR, "nbd"))
2377 if (genl_register_family(&nbd_genl_family)) {
2378 unregister_blkdev(NBD_MAJOR, "nbd");
2383 mutex_lock(&nbd_index_mutex);
2384 for (i = 0; i < nbds_max; i++)
2386 mutex_unlock(&nbd_index_mutex);
2390 static int nbd_exit_cb(int id, void *ptr, void *data)
2392 struct list_head *list = (struct list_head *)data;
2393 struct nbd_device *nbd = ptr;
2395 list_add_tail(&nbd->list, list);
2399 static void __exit nbd_cleanup(void)
2401 struct nbd_device *nbd;
2402 LIST_HEAD(del_list);
2406 mutex_lock(&nbd_index_mutex);
2407 idr_for_each(&nbd_index_idr, &nbd_exit_cb, &del_list);
2408 mutex_unlock(&nbd_index_mutex);
2410 while (!list_empty(&del_list)) {
2411 nbd = list_first_entry(&del_list, struct nbd_device, list);
2412 list_del_init(&nbd->list);
2413 if (refcount_read(&nbd->refs) != 1)
2414 printk(KERN_ERR "nbd: possibly leaking a device\n");
2418 idr_destroy(&nbd_index_idr);
2419 genl_unregister_family(&nbd_genl_family);
2420 unregister_blkdev(NBD_MAJOR, "nbd");
2423 module_init(nbd_init);
2424 module_exit(nbd_cleanup);
2426 MODULE_DESCRIPTION("Network Block Device");
2427 MODULE_LICENSE("GPL");
2429 module_param(nbds_max, int, 0444);
2430 MODULE_PARM_DESC(nbds_max, "number of network block devices to initialize (default: 16)");
2431 module_param(max_part, int, 0444);
2432 MODULE_PARM_DESC(max_part, "number of partitions per device (default: 16)");