2 * Network block device - make block devices work over TCP
4 * Note that you can not swap over this thing, yet. Seems to work but
5 * deadlocks sometimes - you can not swap over TCP in general.
7 * Copyright 1997-2000, 2008 Pavel Machek <pavel@ucw.cz>
8 * Parts copyright 2001 Steven Whitehouse <steve@chygwyn.com>
10 * This file is released under GPLv2 or later.
12 * (part of code stolen from loop.c)
15 #include <linux/major.h>
17 #include <linux/blkdev.h>
18 #include <linux/module.h>
19 #include <linux/init.h>
20 #include <linux/sched.h>
21 #include <linux/sched/mm.h>
23 #include <linux/bio.h>
24 #include <linux/stat.h>
25 #include <linux/errno.h>
26 #include <linux/file.h>
27 #include <linux/ioctl.h>
28 #include <linux/mutex.h>
29 #include <linux/compiler.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 static DEFINE_IDR(nbd_index_idr);
48 static DEFINE_MUTEX(nbd_index_mutex);
49 static int nbd_total_devices = 0;
54 struct request *pending;
61 struct recv_thread_args {
62 struct work_struct work;
63 struct nbd_device *nbd;
67 struct link_dead_args {
68 struct work_struct work;
72 #define NBD_TIMEDOUT 0
73 #define NBD_DISCONNECT_REQUESTED 1
74 #define NBD_DISCONNECTED 2
75 #define NBD_HAS_PID_FILE 3
76 #define NBD_HAS_CONFIG_REF 4
78 #define NBD_DESTROY_ON_DISCONNECT 6
79 #define NBD_DISCONNECT_ON_CLOSE 7
83 unsigned long runtime_flags;
84 u64 dead_conn_timeout;
86 struct nbd_sock **socks;
88 atomic_t live_connections;
89 wait_queue_head_t conn_wait;
91 atomic_t recv_threads;
92 wait_queue_head_t recv_wq;
95 #if IS_ENABLED(CONFIG_DEBUG_FS)
96 struct dentry *dbg_dir;
101 struct blk_mq_tag_set tag_set;
104 refcount_t config_refs;
106 struct nbd_config *config;
107 struct mutex config_lock;
108 struct gendisk *disk;
109 struct workqueue_struct *recv_workq;
111 struct list_head list;
112 struct task_struct *task_recv;
113 struct task_struct *task_setup;
116 #define NBD_CMD_REQUEUED 1
119 struct nbd_device *nbd;
128 #if IS_ENABLED(CONFIG_DEBUG_FS)
129 static struct dentry *nbd_dbg_dir;
132 #define nbd_name(nbd) ((nbd)->disk->disk_name)
134 #define NBD_MAGIC 0x68797548
136 #define NBD_DEF_BLKSIZE 1024
138 static unsigned int nbds_max = 16;
139 static int max_part = 16;
140 static int part_shift;
142 static int nbd_dev_dbg_init(struct nbd_device *nbd);
143 static void nbd_dev_dbg_close(struct nbd_device *nbd);
144 static void nbd_config_put(struct nbd_device *nbd);
145 static void nbd_connect_reply(struct genl_info *info, int index);
146 static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info);
147 static void nbd_dead_link_work(struct work_struct *work);
148 static void nbd_disconnect_and_put(struct nbd_device *nbd);
150 static inline struct device *nbd_to_dev(struct nbd_device *nbd)
152 return disk_to_dev(nbd->disk);
155 static void nbd_requeue_cmd(struct nbd_cmd *cmd)
157 struct request *req = blk_mq_rq_from_pdu(cmd);
159 if (!test_and_set_bit(NBD_CMD_REQUEUED, &cmd->flags))
160 blk_mq_requeue_request(req, true);
163 #define NBD_COOKIE_BITS 32
165 static u64 nbd_cmd_handle(struct nbd_cmd *cmd)
167 struct request *req = blk_mq_rq_from_pdu(cmd);
168 u32 tag = blk_mq_unique_tag(req);
169 u64 cookie = cmd->cmd_cookie;
171 return (cookie << NBD_COOKIE_BITS) | tag;
174 static u32 nbd_handle_to_tag(u64 handle)
179 static u32 nbd_handle_to_cookie(u64 handle)
181 return (u32)(handle >> NBD_COOKIE_BITS);
184 static const char *nbdcmd_to_ascii(int cmd)
187 case NBD_CMD_READ: return "read";
188 case NBD_CMD_WRITE: return "write";
189 case NBD_CMD_DISC: return "disconnect";
190 case NBD_CMD_FLUSH: return "flush";
191 case NBD_CMD_TRIM: return "trim/discard";
196 static ssize_t pid_show(struct device *dev,
197 struct device_attribute *attr, char *buf)
199 struct gendisk *disk = dev_to_disk(dev);
200 struct nbd_device *nbd = (struct nbd_device *)disk->private_data;
202 return sprintf(buf, "%d\n", task_pid_nr(nbd->task_recv));
205 static const struct device_attribute pid_attr = {
206 .attr = { .name = "pid", .mode = 0444},
210 static void nbd_dev_remove(struct nbd_device *nbd)
212 struct gendisk *disk = nbd->disk;
213 struct request_queue *q;
218 blk_cleanup_queue(q);
219 blk_mq_free_tag_set(&nbd->tag_set);
220 disk->private_data = NULL;
226 static void nbd_put(struct nbd_device *nbd)
228 if (refcount_dec_and_mutex_lock(&nbd->refs,
230 idr_remove(&nbd_index_idr, nbd->index);
232 mutex_unlock(&nbd_index_mutex);
236 static int nbd_disconnected(struct nbd_config *config)
238 return test_bit(NBD_DISCONNECTED, &config->runtime_flags) ||
239 test_bit(NBD_DISCONNECT_REQUESTED, &config->runtime_flags);
242 static void nbd_mark_nsock_dead(struct nbd_device *nbd, struct nbd_sock *nsock,
245 if (!nsock->dead && notify && !nbd_disconnected(nbd->config)) {
246 struct link_dead_args *args;
247 args = kmalloc(sizeof(struct link_dead_args), GFP_NOIO);
249 INIT_WORK(&args->work, nbd_dead_link_work);
250 args->index = nbd->index;
251 queue_work(system_wq, &args->work);
255 kernel_sock_shutdown(nsock->sock, SHUT_RDWR);
256 if (atomic_dec_return(&nbd->config->live_connections) == 0) {
257 if (test_and_clear_bit(NBD_DISCONNECT_REQUESTED,
258 &nbd->config->runtime_flags)) {
259 set_bit(NBD_DISCONNECTED,
260 &nbd->config->runtime_flags);
261 dev_info(nbd_to_dev(nbd),
262 "Disconnected due to user request.\n");
267 nsock->pending = NULL;
271 static void nbd_size_clear(struct nbd_device *nbd)
273 if (nbd->config->bytesize) {
274 set_capacity(nbd->disk, 0);
275 kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
279 static void nbd_size_update(struct nbd_device *nbd, bool start)
281 struct nbd_config *config = nbd->config;
282 struct block_device *bdev = bdget_disk(nbd->disk, 0);
284 if (config->flags & NBD_FLAG_SEND_TRIM) {
285 nbd->disk->queue->limits.discard_granularity = config->blksize;
286 nbd->disk->queue->limits.discard_alignment = config->blksize;
287 blk_queue_max_discard_sectors(nbd->disk->queue, UINT_MAX);
289 blk_queue_logical_block_size(nbd->disk->queue, config->blksize);
290 blk_queue_physical_block_size(nbd->disk->queue, config->blksize);
291 set_capacity(nbd->disk, config->bytesize >> 9);
294 bd_set_size(bdev, config->bytesize);
296 set_blocksize(bdev, config->blksize);
298 bdev->bd_invalidated = 1;
301 kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
304 static void nbd_size_set(struct nbd_device *nbd, loff_t blocksize,
307 struct nbd_config *config = nbd->config;
308 config->blksize = blocksize;
309 config->bytesize = blocksize * nr_blocks;
310 if (nbd->task_recv != NULL)
311 nbd_size_update(nbd, false);
314 static void nbd_complete_rq(struct request *req)
316 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
318 dev_dbg(nbd_to_dev(cmd->nbd), "request %p: %s\n", req,
319 cmd->status ? "failed" : "done");
321 blk_mq_end_request(req, cmd->status);
325 * Forcibly shutdown the socket causing all listeners to error
327 static void sock_shutdown(struct nbd_device *nbd)
329 struct nbd_config *config = nbd->config;
332 if (config->num_connections == 0)
334 if (test_and_set_bit(NBD_DISCONNECTED, &config->runtime_flags))
337 for (i = 0; i < config->num_connections; i++) {
338 struct nbd_sock *nsock = config->socks[i];
339 mutex_lock(&nsock->tx_lock);
340 nbd_mark_nsock_dead(nbd, nsock, 0);
341 mutex_unlock(&nsock->tx_lock);
343 dev_warn(disk_to_dev(nbd->disk), "shutting down sockets\n");
346 static enum blk_eh_timer_return nbd_xmit_timeout(struct request *req,
349 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
350 struct nbd_device *nbd = cmd->nbd;
351 struct nbd_config *config;
353 if (!mutex_trylock(&cmd->lock))
354 return BLK_EH_RESET_TIMER;
356 if (!refcount_inc_not_zero(&nbd->config_refs)) {
357 cmd->status = BLK_STS_TIMEOUT;
358 mutex_unlock(&cmd->lock);
361 config = nbd->config;
363 if (config->num_connections > 1) {
364 dev_err_ratelimited(nbd_to_dev(nbd),
365 "Connection timed out, retrying (%d/%d alive)\n",
366 atomic_read(&config->live_connections),
367 config->num_connections);
369 * Hooray we have more connections, requeue this IO, the submit
370 * path will put it on a real connection.
372 if (config->socks && config->num_connections > 1) {
373 if (cmd->index < config->num_connections) {
374 struct nbd_sock *nsock =
375 config->socks[cmd->index];
376 mutex_lock(&nsock->tx_lock);
377 /* We can have multiple outstanding requests, so
378 * we don't want to mark the nsock dead if we've
379 * already reconnected with a new socket, so
380 * only mark it dead if its the same socket we
383 if (cmd->cookie == nsock->cookie)
384 nbd_mark_nsock_dead(nbd, nsock, 1);
385 mutex_unlock(&nsock->tx_lock);
387 mutex_unlock(&cmd->lock);
388 nbd_requeue_cmd(cmd);
393 dev_err_ratelimited(nbd_to_dev(nbd),
394 "Connection timed out\n");
396 set_bit(NBD_TIMEDOUT, &config->runtime_flags);
397 cmd->status = BLK_STS_IOERR;
398 mutex_unlock(&cmd->lock);
402 blk_mq_complete_request(req);
407 * Send or receive packet.
409 static int sock_xmit(struct nbd_device *nbd, int index, int send,
410 struct iov_iter *iter, int msg_flags, int *sent)
412 struct nbd_config *config = nbd->config;
413 struct socket *sock = config->socks[index]->sock;
416 unsigned int noreclaim_flag;
418 if (unlikely(!sock)) {
419 dev_err_ratelimited(disk_to_dev(nbd->disk),
420 "Attempted %s on closed socket in sock_xmit\n",
421 (send ? "send" : "recv"));
425 msg.msg_iter = *iter;
427 noreclaim_flag = memalloc_noreclaim_save();
429 sock->sk->sk_allocation = GFP_NOIO | __GFP_MEMALLOC;
432 msg.msg_control = NULL;
433 msg.msg_controllen = 0;
434 msg.msg_flags = msg_flags | MSG_NOSIGNAL;
437 result = sock_sendmsg(sock, &msg);
439 result = sock_recvmsg(sock, &msg, msg.msg_flags);
443 result = -EPIPE; /* short read */
448 } while (msg_data_left(&msg));
450 memalloc_noreclaim_restore(noreclaim_flag);
456 * Different settings for sk->sk_sndtimeo can result in different return values
457 * if there is a signal pending when we enter sendmsg, because reasons?
459 static inline int was_interrupted(int result)
461 return result == -ERESTARTSYS || result == -EINTR;
464 /* always call with the tx_lock held */
465 static int nbd_send_cmd(struct nbd_device *nbd, struct nbd_cmd *cmd, int index)
467 struct request *req = blk_mq_rq_from_pdu(cmd);
468 struct nbd_config *config = nbd->config;
469 struct nbd_sock *nsock = config->socks[index];
471 struct nbd_request request = {.magic = htonl(NBD_REQUEST_MAGIC)};
472 struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
473 struct iov_iter from;
474 unsigned long size = blk_rq_bytes(req);
478 u32 nbd_cmd_flags = 0;
479 int sent = nsock->sent, skip = 0;
481 iov_iter_kvec(&from, WRITE | ITER_KVEC, &iov, 1, sizeof(request));
483 switch (req_op(req)) {
488 type = NBD_CMD_FLUSH;
491 type = NBD_CMD_WRITE;
500 if (rq_data_dir(req) == WRITE &&
501 (config->flags & NBD_FLAG_READ_ONLY)) {
502 dev_err_ratelimited(disk_to_dev(nbd->disk),
503 "Write on read-only\n");
507 if (req->cmd_flags & REQ_FUA)
508 nbd_cmd_flags |= NBD_CMD_FLAG_FUA;
510 /* We did a partial send previously, and we at least sent the whole
511 * request struct, so just go and send the rest of the pages in the
515 if (sent >= sizeof(request)) {
516 skip = sent - sizeof(request);
519 iov_iter_advance(&from, sent);
524 cmd->cookie = nsock->cookie;
525 request.type = htonl(type | nbd_cmd_flags);
526 if (type != NBD_CMD_FLUSH) {
527 request.from = cpu_to_be64((u64)blk_rq_pos(req) << 9);
528 request.len = htonl(size);
530 handle = nbd_cmd_handle(cmd);
531 memcpy(request.handle, &handle, sizeof(handle));
533 dev_dbg(nbd_to_dev(nbd), "request %p: sending control (%s@%llu,%uB)\n",
534 req, nbdcmd_to_ascii(type),
535 (unsigned long long)blk_rq_pos(req) << 9, blk_rq_bytes(req));
536 result = sock_xmit(nbd, index, 1, &from,
537 (type == NBD_CMD_WRITE) ? MSG_MORE : 0, &sent);
539 if (was_interrupted(result)) {
540 /* If we havne't sent anything we can just return BUSY,
541 * however if we have sent something we need to make
542 * sure we only allow this req to be sent until we are
546 nsock->pending = req;
549 set_bit(NBD_CMD_REQUEUED, &cmd->flags);
550 return BLK_STS_RESOURCE;
552 dev_err_ratelimited(disk_to_dev(nbd->disk),
553 "Send control failed (result %d)\n", result);
557 if (type != NBD_CMD_WRITE)
562 struct bio *next = bio->bi_next;
563 struct bvec_iter iter;
566 bio_for_each_segment(bvec, bio, iter) {
567 bool is_last = !next && bio_iter_last(bvec, iter);
568 int flags = is_last ? 0 : MSG_MORE;
570 dev_dbg(nbd_to_dev(nbd), "request %p: sending %d bytes data\n",
572 iov_iter_bvec(&from, ITER_BVEC | WRITE,
573 &bvec, 1, bvec.bv_len);
575 if (skip >= iov_iter_count(&from)) {
576 skip -= iov_iter_count(&from);
579 iov_iter_advance(&from, skip);
582 result = sock_xmit(nbd, index, 1, &from, flags, &sent);
584 if (was_interrupted(result)) {
585 /* We've already sent the header, we
586 * have no choice but to set pending and
589 nsock->pending = req;
591 set_bit(NBD_CMD_REQUEUED, &cmd->flags);
592 return BLK_STS_RESOURCE;
594 dev_err(disk_to_dev(nbd->disk),
595 "Send data failed (result %d)\n",
600 * The completion might already have come in,
601 * so break for the last one instead of letting
602 * the iterator do it. This prevents use-after-free
611 nsock->pending = NULL;
616 /* NULL returned = something went wrong, inform userspace */
617 static struct nbd_cmd *nbd_read_stat(struct nbd_device *nbd, int index)
619 struct nbd_config *config = nbd->config;
621 struct nbd_reply reply;
623 struct request *req = NULL;
627 struct kvec iov = {.iov_base = &reply, .iov_len = sizeof(reply)};
632 iov_iter_kvec(&to, READ | ITER_KVEC, &iov, 1, sizeof(reply));
633 result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
635 if (!nbd_disconnected(config))
636 dev_err(disk_to_dev(nbd->disk),
637 "Receive control failed (result %d)\n", result);
638 return ERR_PTR(result);
641 if (ntohl(reply.magic) != NBD_REPLY_MAGIC) {
642 dev_err(disk_to_dev(nbd->disk), "Wrong magic (0x%lx)\n",
643 (unsigned long)ntohl(reply.magic));
644 return ERR_PTR(-EPROTO);
647 memcpy(&handle, reply.handle, sizeof(handle));
648 tag = nbd_handle_to_tag(handle);
649 hwq = blk_mq_unique_tag_to_hwq(tag);
650 if (hwq < nbd->tag_set.nr_hw_queues)
651 req = blk_mq_tag_to_rq(nbd->tag_set.tags[hwq],
652 blk_mq_unique_tag_to_tag(tag));
653 if (!req || !blk_mq_request_started(req)) {
654 dev_err(disk_to_dev(nbd->disk), "Unexpected reply (%d) %p\n",
656 return ERR_PTR(-ENOENT);
658 cmd = blk_mq_rq_to_pdu(req);
660 mutex_lock(&cmd->lock);
661 if (cmd->cmd_cookie != nbd_handle_to_cookie(handle)) {
662 dev_err(disk_to_dev(nbd->disk), "Double reply on req %p, cmd_cookie %u, handle cookie %u\n",
663 req, cmd->cmd_cookie, nbd_handle_to_cookie(handle));
667 if (cmd->status != BLK_STS_OK) {
668 dev_err(disk_to_dev(nbd->disk), "Command already handled %p\n",
673 if (test_bit(NBD_CMD_REQUEUED, &cmd->flags)) {
674 dev_err(disk_to_dev(nbd->disk), "Raced with timeout on req %p\n",
679 if (ntohl(reply.error)) {
680 dev_err(disk_to_dev(nbd->disk), "Other side returned error (%d)\n",
682 cmd->status = BLK_STS_IOERR;
686 dev_dbg(nbd_to_dev(nbd), "request %p: got reply\n", req);
687 if (rq_data_dir(req) != WRITE) {
688 struct req_iterator iter;
691 rq_for_each_segment(bvec, req, iter) {
692 iov_iter_bvec(&to, ITER_BVEC | READ,
693 &bvec, 1, bvec.bv_len);
694 result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
696 dev_err(disk_to_dev(nbd->disk), "Receive data failed (result %d)\n",
699 * If we've disconnected or we only have 1
700 * connection then we need to make sure we
701 * complete this request, otherwise error out
702 * and let the timeout stuff handle resubmitting
703 * this request onto another connection.
705 if (nbd_disconnected(config) ||
706 config->num_connections <= 1) {
707 cmd->status = BLK_STS_IOERR;
713 dev_dbg(nbd_to_dev(nbd), "request %p: got %d bytes data\n",
718 mutex_unlock(&cmd->lock);
719 return ret ? ERR_PTR(ret) : cmd;
722 static void recv_work(struct work_struct *work)
724 struct recv_thread_args *args = container_of(work,
725 struct recv_thread_args,
727 struct nbd_device *nbd = args->nbd;
728 struct nbd_config *config = nbd->config;
732 cmd = nbd_read_stat(nbd, args->index);
734 struct nbd_sock *nsock = config->socks[args->index];
736 mutex_lock(&nsock->tx_lock);
737 nbd_mark_nsock_dead(nbd, nsock, 1);
738 mutex_unlock(&nsock->tx_lock);
742 blk_mq_complete_request(blk_mq_rq_from_pdu(cmd));
745 atomic_dec(&config->recv_threads);
746 wake_up(&config->recv_wq);
750 static void nbd_clear_req(struct request *req, void *data, bool reserved)
752 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
754 mutex_lock(&cmd->lock);
755 cmd->status = BLK_STS_IOERR;
756 mutex_unlock(&cmd->lock);
758 blk_mq_complete_request(req);
761 static void nbd_clear_que(struct nbd_device *nbd)
763 blk_mq_quiesce_queue(nbd->disk->queue);
764 blk_mq_tagset_busy_iter(&nbd->tag_set, nbd_clear_req, NULL);
765 blk_mq_unquiesce_queue(nbd->disk->queue);
766 dev_dbg(disk_to_dev(nbd->disk), "queue cleared\n");
769 static int find_fallback(struct nbd_device *nbd, int index)
771 struct nbd_config *config = nbd->config;
773 struct nbd_sock *nsock = config->socks[index];
774 int fallback = nsock->fallback_index;
776 if (test_bit(NBD_DISCONNECTED, &config->runtime_flags))
779 if (config->num_connections <= 1) {
780 dev_err_ratelimited(disk_to_dev(nbd->disk),
781 "Attempted send on invalid socket\n");
785 if (fallback >= 0 && fallback < config->num_connections &&
786 !config->socks[fallback]->dead)
789 if (nsock->fallback_index < 0 ||
790 nsock->fallback_index >= config->num_connections ||
791 config->socks[nsock->fallback_index]->dead) {
793 for (i = 0; i < config->num_connections; i++) {
796 if (!config->socks[i]->dead) {
801 nsock->fallback_index = new_index;
803 dev_err_ratelimited(disk_to_dev(nbd->disk),
804 "Dead connection, failed to find a fallback\n");
808 new_index = nsock->fallback_index;
812 static int wait_for_reconnect(struct nbd_device *nbd)
814 struct nbd_config *config = nbd->config;
815 if (!config->dead_conn_timeout)
817 if (test_bit(NBD_DISCONNECTED, &config->runtime_flags))
819 return wait_event_timeout(config->conn_wait,
820 atomic_read(&config->live_connections) > 0,
821 config->dead_conn_timeout) > 0;
824 static int nbd_handle_cmd(struct nbd_cmd *cmd, int index)
826 struct request *req = blk_mq_rq_from_pdu(cmd);
827 struct nbd_device *nbd = cmd->nbd;
828 struct nbd_config *config;
829 struct nbd_sock *nsock;
832 if (!refcount_inc_not_zero(&nbd->config_refs)) {
833 dev_err_ratelimited(disk_to_dev(nbd->disk),
834 "Socks array is empty\n");
835 blk_mq_start_request(req);
838 config = nbd->config;
840 if (index >= config->num_connections) {
841 dev_err_ratelimited(disk_to_dev(nbd->disk),
842 "Attempted send on invalid socket\n");
844 blk_mq_start_request(req);
847 cmd->status = BLK_STS_OK;
849 nsock = config->socks[index];
850 mutex_lock(&nsock->tx_lock);
852 int old_index = index;
853 index = find_fallback(nbd, index);
854 mutex_unlock(&nsock->tx_lock);
856 if (wait_for_reconnect(nbd)) {
860 /* All the sockets should already be down at this point,
861 * we just want to make sure that DISCONNECTED is set so
862 * any requests that come in that were queue'ed waiting
863 * for the reconnect timer don't trigger the timer again
864 * and instead just error out.
868 blk_mq_start_request(req);
874 /* Handle the case that we have a pending request that was partially
875 * transmitted that _has_ to be serviced first. We need to call requeue
876 * here so that it gets put _after_ the request that is already on the
879 blk_mq_start_request(req);
880 if (unlikely(nsock->pending && nsock->pending != req)) {
881 nbd_requeue_cmd(cmd);
886 * Some failures are related to the link going down, so anything that
887 * returns EAGAIN can be retried on a different socket.
889 ret = nbd_send_cmd(nbd, cmd, index);
890 if (ret == -EAGAIN) {
891 dev_err_ratelimited(disk_to_dev(nbd->disk),
892 "Request send failed, requeueing\n");
893 nbd_mark_nsock_dead(nbd, nsock, 1);
894 nbd_requeue_cmd(cmd);
898 mutex_unlock(&nsock->tx_lock);
903 static blk_status_t nbd_queue_rq(struct blk_mq_hw_ctx *hctx,
904 const struct blk_mq_queue_data *bd)
906 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(bd->rq);
910 * Since we look at the bio's to send the request over the network we
911 * need to make sure the completion work doesn't mark this request done
912 * before we are done doing our send. This keeps us from dereferencing
913 * freed data if we have particularly fast completions (ie we get the
914 * completion before we exit sock_xmit on the last bvec) or in the case
915 * that the server is misbehaving (or there was an error) before we're
916 * done sending everything over the wire.
918 mutex_lock(&cmd->lock);
919 clear_bit(NBD_CMD_REQUEUED, &cmd->flags);
921 /* We can be called directly from the user space process, which means we
922 * could possibly have signals pending so our sendmsg will fail. In
923 * this case we need to return that we are busy, otherwise error out as
926 ret = nbd_handle_cmd(cmd, hctx->queue_num);
931 mutex_unlock(&cmd->lock);
936 static struct socket *nbd_get_socket(struct nbd_device *nbd, unsigned long fd,
942 sock = sockfd_lookup(fd, err);
946 if (sock->ops->shutdown == sock_no_shutdown) {
947 dev_err(disk_to_dev(nbd->disk), "Unsupported socket: shutdown callout must be supported.\n");
956 static int nbd_add_socket(struct nbd_device *nbd, unsigned long arg,
959 struct nbd_config *config = nbd->config;
961 struct nbd_sock **socks;
962 struct nbd_sock *nsock;
965 sock = nbd_get_socket(nbd, arg, &err);
970 * We need to make sure we don't get any errant requests while we're
971 * reallocating the ->socks array.
973 blk_mq_freeze_queue(nbd->disk->queue);
975 if (!netlink && !nbd->task_setup &&
976 !test_bit(NBD_BOUND, &config->runtime_flags))
977 nbd->task_setup = current;
980 (nbd->task_setup != current ||
981 test_bit(NBD_BOUND, &config->runtime_flags))) {
982 dev_err(disk_to_dev(nbd->disk),
983 "Device being setup by another task");
988 nsock = kzalloc(sizeof(*nsock), GFP_KERNEL);
994 socks = krealloc(config->socks, (config->num_connections + 1) *
995 sizeof(struct nbd_sock *), GFP_KERNEL);
1002 config->socks = socks;
1004 nsock->fallback_index = -1;
1005 nsock->dead = false;
1006 mutex_init(&nsock->tx_lock);
1008 nsock->pending = NULL;
1011 socks[config->num_connections++] = nsock;
1012 atomic_inc(&config->live_connections);
1013 blk_mq_unfreeze_queue(nbd->disk->queue);
1018 blk_mq_unfreeze_queue(nbd->disk->queue);
1023 static int nbd_reconnect_socket(struct nbd_device *nbd, unsigned long arg)
1025 struct nbd_config *config = nbd->config;
1026 struct socket *sock, *old;
1027 struct recv_thread_args *args;
1031 sock = nbd_get_socket(nbd, arg, &err);
1035 args = kzalloc(sizeof(*args), GFP_KERNEL);
1041 for (i = 0; i < config->num_connections; i++) {
1042 struct nbd_sock *nsock = config->socks[i];
1047 mutex_lock(&nsock->tx_lock);
1049 mutex_unlock(&nsock->tx_lock);
1052 sk_set_memalloc(sock->sk);
1053 if (nbd->tag_set.timeout)
1054 sock->sk->sk_sndtimeo = nbd->tag_set.timeout;
1055 atomic_inc(&config->recv_threads);
1056 refcount_inc(&nbd->config_refs);
1058 nsock->fallback_index = -1;
1060 nsock->dead = false;
1061 INIT_WORK(&args->work, recv_work);
1065 mutex_unlock(&nsock->tx_lock);
1068 clear_bit(NBD_DISCONNECTED, &config->runtime_flags);
1070 /* We take the tx_mutex in an error path in the recv_work, so we
1071 * need to queue_work outside of the tx_mutex.
1073 queue_work(nbd->recv_workq, &args->work);
1075 atomic_inc(&config->live_connections);
1076 wake_up(&config->conn_wait);
1084 static void nbd_bdev_reset(struct block_device *bdev)
1086 if (bdev->bd_openers > 1)
1088 bd_set_size(bdev, 0);
1091 static void nbd_parse_flags(struct nbd_device *nbd)
1093 struct nbd_config *config = nbd->config;
1094 if (config->flags & NBD_FLAG_READ_ONLY)
1095 set_disk_ro(nbd->disk, true);
1097 set_disk_ro(nbd->disk, false);
1098 if (config->flags & NBD_FLAG_SEND_TRIM)
1099 blk_queue_flag_set(QUEUE_FLAG_DISCARD, nbd->disk->queue);
1100 if (config->flags & NBD_FLAG_SEND_FLUSH) {
1101 if (config->flags & NBD_FLAG_SEND_FUA)
1102 blk_queue_write_cache(nbd->disk->queue, true, true);
1104 blk_queue_write_cache(nbd->disk->queue, true, false);
1107 blk_queue_write_cache(nbd->disk->queue, false, false);
1110 static void send_disconnects(struct nbd_device *nbd)
1112 struct nbd_config *config = nbd->config;
1113 struct nbd_request request = {
1114 .magic = htonl(NBD_REQUEST_MAGIC),
1115 .type = htonl(NBD_CMD_DISC),
1117 struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
1118 struct iov_iter from;
1121 for (i = 0; i < config->num_connections; i++) {
1122 struct nbd_sock *nsock = config->socks[i];
1124 iov_iter_kvec(&from, WRITE | ITER_KVEC, &iov, 1, sizeof(request));
1125 mutex_lock(&nsock->tx_lock);
1126 ret = sock_xmit(nbd, i, 1, &from, 0, NULL);
1128 dev_err(disk_to_dev(nbd->disk),
1129 "Send disconnect failed %d\n", ret);
1130 mutex_unlock(&nsock->tx_lock);
1134 static int nbd_disconnect(struct nbd_device *nbd)
1136 struct nbd_config *config = nbd->config;
1138 dev_info(disk_to_dev(nbd->disk), "NBD_DISCONNECT\n");
1139 set_bit(NBD_DISCONNECT_REQUESTED, &config->runtime_flags);
1140 send_disconnects(nbd);
1144 static void nbd_clear_sock(struct nbd_device *nbd)
1148 nbd->task_setup = NULL;
1151 static void nbd_config_put(struct nbd_device *nbd)
1153 if (refcount_dec_and_mutex_lock(&nbd->config_refs,
1154 &nbd->config_lock)) {
1155 struct nbd_config *config = nbd->config;
1156 nbd_dev_dbg_close(nbd);
1157 nbd_size_clear(nbd);
1158 if (test_and_clear_bit(NBD_HAS_PID_FILE,
1159 &config->runtime_flags))
1160 device_remove_file(disk_to_dev(nbd->disk), &pid_attr);
1161 nbd->task_recv = NULL;
1162 nbd_clear_sock(nbd);
1163 if (config->num_connections) {
1165 for (i = 0; i < config->num_connections; i++) {
1166 sockfd_put(config->socks[i]->sock);
1167 kfree(config->socks[i]);
1169 kfree(config->socks);
1174 if (nbd->recv_workq)
1175 destroy_workqueue(nbd->recv_workq);
1176 nbd->recv_workq = NULL;
1178 nbd->tag_set.timeout = 0;
1179 nbd->disk->queue->limits.discard_granularity = 0;
1180 nbd->disk->queue->limits.discard_alignment = 0;
1181 blk_queue_max_discard_sectors(nbd->disk->queue, UINT_MAX);
1182 blk_queue_flag_clear(QUEUE_FLAG_DISCARD, nbd->disk->queue);
1184 mutex_unlock(&nbd->config_lock);
1186 module_put(THIS_MODULE);
1190 static int nbd_start_device(struct nbd_device *nbd)
1192 struct nbd_config *config = nbd->config;
1193 int num_connections = config->num_connections;
1200 if (num_connections > 1 &&
1201 !(config->flags & NBD_FLAG_CAN_MULTI_CONN)) {
1202 dev_err(disk_to_dev(nbd->disk), "server does not support multiple connections per device.\n");
1206 nbd->recv_workq = alloc_workqueue("knbd%d-recv",
1207 WQ_MEM_RECLAIM | WQ_HIGHPRI |
1208 WQ_UNBOUND, 0, nbd->index);
1209 if (!nbd->recv_workq) {
1210 dev_err(disk_to_dev(nbd->disk), "Could not allocate knbd recv work queue.\n");
1214 blk_mq_update_nr_hw_queues(&nbd->tag_set, config->num_connections);
1215 nbd->task_recv = current;
1217 nbd_parse_flags(nbd);
1219 error = device_create_file(disk_to_dev(nbd->disk), &pid_attr);
1221 dev_err(disk_to_dev(nbd->disk), "device_create_file failed!\n");
1224 set_bit(NBD_HAS_PID_FILE, &config->runtime_flags);
1226 nbd_dev_dbg_init(nbd);
1227 for (i = 0; i < num_connections; i++) {
1228 struct recv_thread_args *args;
1230 args = kzalloc(sizeof(*args), GFP_KERNEL);
1234 * If num_connections is m (2 < m),
1235 * and NO.1 ~ NO.n(1 < n < m) kzallocs are successful.
1236 * But NO.(n + 1) failed. We still have n recv threads.
1237 * So, add flush_workqueue here to prevent recv threads
1238 * dropping the last config_refs and trying to destroy
1239 * the workqueue from inside the workqueue.
1242 flush_workqueue(nbd->recv_workq);
1245 sk_set_memalloc(config->socks[i]->sock->sk);
1246 if (nbd->tag_set.timeout)
1247 config->socks[i]->sock->sk->sk_sndtimeo =
1248 nbd->tag_set.timeout;
1249 atomic_inc(&config->recv_threads);
1250 refcount_inc(&nbd->config_refs);
1251 INIT_WORK(&args->work, recv_work);
1254 queue_work(nbd->recv_workq, &args->work);
1256 nbd_size_update(nbd, true);
1260 static int nbd_start_device_ioctl(struct nbd_device *nbd, struct block_device *bdev)
1262 struct nbd_config *config = nbd->config;
1265 ret = nbd_start_device(nbd);
1270 bdev->bd_invalidated = 1;
1271 mutex_unlock(&nbd->config_lock);
1272 ret = wait_event_interruptible(config->recv_wq,
1273 atomic_read(&config->recv_threads) == 0);
1276 flush_workqueue(nbd->recv_workq);
1278 mutex_lock(&nbd->config_lock);
1279 nbd_bdev_reset(bdev);
1280 /* user requested, ignore socket errors */
1281 if (test_bit(NBD_DISCONNECT_REQUESTED, &config->runtime_flags))
1283 if (test_bit(NBD_TIMEDOUT, &config->runtime_flags))
1288 static void nbd_clear_sock_ioctl(struct nbd_device *nbd,
1289 struct block_device *bdev)
1292 __invalidate_device(bdev, true);
1293 nbd_bdev_reset(bdev);
1294 if (test_and_clear_bit(NBD_HAS_CONFIG_REF,
1295 &nbd->config->runtime_flags))
1296 nbd_config_put(nbd);
1299 static bool nbd_is_valid_blksize(unsigned long blksize)
1301 if (!blksize || !is_power_of_2(blksize) || blksize < 512 ||
1302 blksize > PAGE_SIZE)
1307 /* Must be called with config_lock held */
1308 static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
1309 unsigned int cmd, unsigned long arg)
1311 struct nbd_config *config = nbd->config;
1314 case NBD_DISCONNECT:
1315 return nbd_disconnect(nbd);
1316 case NBD_CLEAR_SOCK:
1317 nbd_clear_sock_ioctl(nbd, bdev);
1320 return nbd_add_socket(nbd, arg, false);
1321 case NBD_SET_BLKSIZE:
1323 arg = NBD_DEF_BLKSIZE;
1324 if (!nbd_is_valid_blksize(arg))
1326 nbd_size_set(nbd, arg,
1327 div_s64(config->bytesize, arg));
1330 nbd_size_set(nbd, config->blksize,
1331 div_s64(arg, config->blksize));
1333 case NBD_SET_SIZE_BLOCKS:
1334 nbd_size_set(nbd, config->blksize, arg);
1336 case NBD_SET_TIMEOUT:
1338 nbd->tag_set.timeout = arg * HZ;
1339 blk_queue_rq_timeout(nbd->disk->queue, arg * HZ);
1344 config->flags = arg;
1347 return nbd_start_device_ioctl(nbd, bdev);
1350 * This is for compatibility only. The queue is always cleared
1351 * by NBD_DO_IT or NBD_CLEAR_SOCK.
1354 case NBD_PRINT_DEBUG:
1356 * For compatibility only, we no longer keep a list of
1357 * outstanding requests.
1364 static int nbd_ioctl(struct block_device *bdev, fmode_t mode,
1365 unsigned int cmd, unsigned long arg)
1367 struct nbd_device *nbd = bdev->bd_disk->private_data;
1368 struct nbd_config *config = nbd->config;
1369 int error = -EINVAL;
1371 if (!capable(CAP_SYS_ADMIN))
1374 /* The block layer will pass back some non-nbd ioctls in case we have
1375 * special handling for them, but we don't so just return an error.
1377 if (_IOC_TYPE(cmd) != 0xab)
1380 mutex_lock(&nbd->config_lock);
1382 /* Don't allow ioctl operations on a nbd device that was created with
1383 * netlink, unless it's DISCONNECT or CLEAR_SOCK, which are fine.
1385 if (!test_bit(NBD_BOUND, &config->runtime_flags) ||
1386 (cmd == NBD_DISCONNECT || cmd == NBD_CLEAR_SOCK))
1387 error = __nbd_ioctl(bdev, nbd, cmd, arg);
1389 dev_err(nbd_to_dev(nbd), "Cannot use ioctl interface on a netlink controlled device.\n");
1390 mutex_unlock(&nbd->config_lock);
1394 static struct nbd_config *nbd_alloc_config(void)
1396 struct nbd_config *config;
1398 config = kzalloc(sizeof(struct nbd_config), GFP_NOFS);
1401 atomic_set(&config->recv_threads, 0);
1402 init_waitqueue_head(&config->recv_wq);
1403 init_waitqueue_head(&config->conn_wait);
1404 config->blksize = NBD_DEF_BLKSIZE;
1405 atomic_set(&config->live_connections, 0);
1406 try_module_get(THIS_MODULE);
1410 static int nbd_open(struct block_device *bdev, fmode_t mode)
1412 struct nbd_device *nbd;
1415 mutex_lock(&nbd_index_mutex);
1416 nbd = bdev->bd_disk->private_data;
1421 if (!refcount_inc_not_zero(&nbd->refs)) {
1425 if (!refcount_inc_not_zero(&nbd->config_refs)) {
1426 struct nbd_config *config;
1428 mutex_lock(&nbd->config_lock);
1429 if (refcount_inc_not_zero(&nbd->config_refs)) {
1430 mutex_unlock(&nbd->config_lock);
1433 config = nbd->config = nbd_alloc_config();
1436 mutex_unlock(&nbd->config_lock);
1439 refcount_set(&nbd->config_refs, 1);
1440 refcount_inc(&nbd->refs);
1441 mutex_unlock(&nbd->config_lock);
1442 bdev->bd_invalidated = 1;
1443 } else if (nbd_disconnected(nbd->config)) {
1444 bdev->bd_invalidated = 1;
1447 mutex_unlock(&nbd_index_mutex);
1451 static void nbd_release(struct gendisk *disk, fmode_t mode)
1453 struct nbd_device *nbd = disk->private_data;
1454 struct block_device *bdev = bdget_disk(disk, 0);
1456 if (test_bit(NBD_DISCONNECT_ON_CLOSE, &nbd->config->runtime_flags) &&
1457 bdev->bd_openers == 0)
1458 nbd_disconnect_and_put(nbd);
1461 nbd_config_put(nbd);
1465 static const struct block_device_operations nbd_fops =
1467 .owner = THIS_MODULE,
1469 .release = nbd_release,
1471 .compat_ioctl = nbd_ioctl,
1474 #if IS_ENABLED(CONFIG_DEBUG_FS)
1476 static int nbd_dbg_tasks_show(struct seq_file *s, void *unused)
1478 struct nbd_device *nbd = s->private;
1481 seq_printf(s, "recv: %d\n", task_pid_nr(nbd->task_recv));
1486 static int nbd_dbg_tasks_open(struct inode *inode, struct file *file)
1488 return single_open(file, nbd_dbg_tasks_show, inode->i_private);
1491 static const struct file_operations nbd_dbg_tasks_ops = {
1492 .open = nbd_dbg_tasks_open,
1494 .llseek = seq_lseek,
1495 .release = single_release,
1498 static int nbd_dbg_flags_show(struct seq_file *s, void *unused)
1500 struct nbd_device *nbd = s->private;
1501 u32 flags = nbd->config->flags;
1503 seq_printf(s, "Hex: 0x%08x\n\n", flags);
1505 seq_puts(s, "Known flags:\n");
1507 if (flags & NBD_FLAG_HAS_FLAGS)
1508 seq_puts(s, "NBD_FLAG_HAS_FLAGS\n");
1509 if (flags & NBD_FLAG_READ_ONLY)
1510 seq_puts(s, "NBD_FLAG_READ_ONLY\n");
1511 if (flags & NBD_FLAG_SEND_FLUSH)
1512 seq_puts(s, "NBD_FLAG_SEND_FLUSH\n");
1513 if (flags & NBD_FLAG_SEND_FUA)
1514 seq_puts(s, "NBD_FLAG_SEND_FUA\n");
1515 if (flags & NBD_FLAG_SEND_TRIM)
1516 seq_puts(s, "NBD_FLAG_SEND_TRIM\n");
1521 static int nbd_dbg_flags_open(struct inode *inode, struct file *file)
1523 return single_open(file, nbd_dbg_flags_show, inode->i_private);
1526 static const struct file_operations nbd_dbg_flags_ops = {
1527 .open = nbd_dbg_flags_open,
1529 .llseek = seq_lseek,
1530 .release = single_release,
1533 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1536 struct nbd_config *config = nbd->config;
1541 dir = debugfs_create_dir(nbd_name(nbd), nbd_dbg_dir);
1543 dev_err(nbd_to_dev(nbd), "Failed to create debugfs dir for '%s'\n",
1547 config->dbg_dir = dir;
1549 debugfs_create_file("tasks", 0444, dir, nbd, &nbd_dbg_tasks_ops);
1550 debugfs_create_u64("size_bytes", 0444, dir, &config->bytesize);
1551 debugfs_create_u32("timeout", 0444, dir, &nbd->tag_set.timeout);
1552 debugfs_create_u64("blocksize", 0444, dir, &config->blksize);
1553 debugfs_create_file("flags", 0444, dir, nbd, &nbd_dbg_flags_ops);
1558 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1560 debugfs_remove_recursive(nbd->config->dbg_dir);
1563 static int nbd_dbg_init(void)
1565 struct dentry *dbg_dir;
1567 dbg_dir = debugfs_create_dir("nbd", NULL);
1571 nbd_dbg_dir = dbg_dir;
1576 static void nbd_dbg_close(void)
1578 debugfs_remove_recursive(nbd_dbg_dir);
1581 #else /* IS_ENABLED(CONFIG_DEBUG_FS) */
1583 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1588 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1592 static int nbd_dbg_init(void)
1597 static void nbd_dbg_close(void)
1603 static int nbd_init_request(struct blk_mq_tag_set *set, struct request *rq,
1604 unsigned int hctx_idx, unsigned int numa_node)
1606 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(rq);
1607 cmd->nbd = set->driver_data;
1609 mutex_init(&cmd->lock);
1613 static const struct blk_mq_ops nbd_mq_ops = {
1614 .queue_rq = nbd_queue_rq,
1615 .complete = nbd_complete_rq,
1616 .init_request = nbd_init_request,
1617 .timeout = nbd_xmit_timeout,
1620 static int nbd_dev_add(int index)
1622 struct nbd_device *nbd;
1623 struct gendisk *disk;
1624 struct request_queue *q;
1627 nbd = kzalloc(sizeof(struct nbd_device), GFP_KERNEL);
1631 disk = alloc_disk(1 << part_shift);
1636 err = idr_alloc(&nbd_index_idr, nbd, index, index + 1,
1641 err = idr_alloc(&nbd_index_idr, nbd, 0, 0, GFP_KERNEL);
1650 nbd->tag_set.ops = &nbd_mq_ops;
1651 nbd->tag_set.nr_hw_queues = 1;
1652 nbd->tag_set.queue_depth = 128;
1653 nbd->tag_set.numa_node = NUMA_NO_NODE;
1654 nbd->tag_set.cmd_size = sizeof(struct nbd_cmd);
1655 nbd->tag_set.flags = BLK_MQ_F_SHOULD_MERGE |
1656 BLK_MQ_F_SG_MERGE | BLK_MQ_F_BLOCKING;
1657 nbd->tag_set.driver_data = nbd;
1659 err = blk_mq_alloc_tag_set(&nbd->tag_set);
1663 q = blk_mq_init_queue(&nbd->tag_set);
1671 * Tell the block layer that we are not a rotational device
1673 blk_queue_flag_set(QUEUE_FLAG_NONROT, disk->queue);
1674 blk_queue_flag_clear(QUEUE_FLAG_ADD_RANDOM, disk->queue);
1675 disk->queue->limits.discard_granularity = 0;
1676 disk->queue->limits.discard_alignment = 0;
1677 blk_queue_max_discard_sectors(disk->queue, 0);
1678 blk_queue_max_segment_size(disk->queue, UINT_MAX);
1679 blk_queue_max_segments(disk->queue, USHRT_MAX);
1680 blk_queue_max_hw_sectors(disk->queue, 65536);
1681 disk->queue->limits.max_sectors = 256;
1683 mutex_init(&nbd->config_lock);
1684 refcount_set(&nbd->config_refs, 0);
1685 refcount_set(&nbd->refs, 1);
1686 INIT_LIST_HEAD(&nbd->list);
1687 disk->major = NBD_MAJOR;
1688 disk->first_minor = index << part_shift;
1689 disk->fops = &nbd_fops;
1690 disk->private_data = nbd;
1691 sprintf(disk->disk_name, "nbd%d", index);
1693 nbd_total_devices++;
1697 blk_mq_free_tag_set(&nbd->tag_set);
1699 idr_remove(&nbd_index_idr, index);
1708 static int find_free_cb(int id, void *ptr, void *data)
1710 struct nbd_device *nbd = ptr;
1711 struct nbd_device **found = data;
1713 if (!refcount_read(&nbd->config_refs)) {
1720 /* Netlink interface. */
1721 static const struct nla_policy nbd_attr_policy[NBD_ATTR_MAX + 1] = {
1722 [NBD_ATTR_INDEX] = { .type = NLA_U32 },
1723 [NBD_ATTR_SIZE_BYTES] = { .type = NLA_U64 },
1724 [NBD_ATTR_BLOCK_SIZE_BYTES] = { .type = NLA_U64 },
1725 [NBD_ATTR_TIMEOUT] = { .type = NLA_U64 },
1726 [NBD_ATTR_SERVER_FLAGS] = { .type = NLA_U64 },
1727 [NBD_ATTR_CLIENT_FLAGS] = { .type = NLA_U64 },
1728 [NBD_ATTR_SOCKETS] = { .type = NLA_NESTED},
1729 [NBD_ATTR_DEAD_CONN_TIMEOUT] = { .type = NLA_U64 },
1730 [NBD_ATTR_DEVICE_LIST] = { .type = NLA_NESTED},
1733 static const struct nla_policy nbd_sock_policy[NBD_SOCK_MAX + 1] = {
1734 [NBD_SOCK_FD] = { .type = NLA_U32 },
1737 /* We don't use this right now since we don't parse the incoming list, but we
1738 * still want it here so userspace knows what to expect.
1740 static const struct nla_policy __attribute__((unused))
1741 nbd_device_policy[NBD_DEVICE_ATTR_MAX + 1] = {
1742 [NBD_DEVICE_INDEX] = { .type = NLA_U32 },
1743 [NBD_DEVICE_CONNECTED] = { .type = NLA_U8 },
1746 static int nbd_genl_connect(struct sk_buff *skb, struct genl_info *info)
1748 struct nbd_device *nbd = NULL;
1749 struct nbd_config *config;
1752 bool put_dev = false;
1754 if (!netlink_capable(skb, CAP_SYS_ADMIN))
1757 if (info->attrs[NBD_ATTR_INDEX])
1758 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1759 if (!info->attrs[NBD_ATTR_SOCKETS]) {
1760 printk(KERN_ERR "nbd: must specify at least one socket\n");
1763 if (!info->attrs[NBD_ATTR_SIZE_BYTES]) {
1764 printk(KERN_ERR "nbd: must specify a size in bytes for the device\n");
1768 mutex_lock(&nbd_index_mutex);
1770 ret = idr_for_each(&nbd_index_idr, &find_free_cb, &nbd);
1773 new_index = nbd_dev_add(-1);
1774 if (new_index < 0) {
1775 mutex_unlock(&nbd_index_mutex);
1776 printk(KERN_ERR "nbd: failed to add new device\n");
1779 nbd = idr_find(&nbd_index_idr, new_index);
1782 nbd = idr_find(&nbd_index_idr, index);
1784 ret = nbd_dev_add(index);
1786 mutex_unlock(&nbd_index_mutex);
1787 printk(KERN_ERR "nbd: failed to add new device\n");
1790 nbd = idr_find(&nbd_index_idr, index);
1794 printk(KERN_ERR "nbd: couldn't find device at index %d\n",
1796 mutex_unlock(&nbd_index_mutex);
1799 if (!refcount_inc_not_zero(&nbd->refs)) {
1800 mutex_unlock(&nbd_index_mutex);
1803 printk(KERN_ERR "nbd: device at index %d is going down\n",
1807 mutex_unlock(&nbd_index_mutex);
1809 mutex_lock(&nbd->config_lock);
1810 if (refcount_read(&nbd->config_refs)) {
1811 mutex_unlock(&nbd->config_lock);
1815 printk(KERN_ERR "nbd: nbd%d already in use\n", index);
1818 if (WARN_ON(nbd->config)) {
1819 mutex_unlock(&nbd->config_lock);
1823 config = nbd->config = nbd_alloc_config();
1825 mutex_unlock(&nbd->config_lock);
1827 printk(KERN_ERR "nbd: couldn't allocate config\n");
1830 refcount_set(&nbd->config_refs, 1);
1831 set_bit(NBD_BOUND, &config->runtime_flags);
1833 if (info->attrs[NBD_ATTR_SIZE_BYTES]) {
1834 u64 bytes = nla_get_u64(info->attrs[NBD_ATTR_SIZE_BYTES]);
1835 nbd_size_set(nbd, config->blksize,
1836 div64_u64(bytes, config->blksize));
1838 if (info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]) {
1840 nla_get_u64(info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]);
1842 bsize = NBD_DEF_BLKSIZE;
1843 if (!nbd_is_valid_blksize(bsize)) {
1847 nbd_size_set(nbd, bsize, div64_u64(config->bytesize, bsize));
1849 if (info->attrs[NBD_ATTR_TIMEOUT]) {
1850 u64 timeout = nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]);
1851 nbd->tag_set.timeout = timeout * HZ;
1852 blk_queue_rq_timeout(nbd->disk->queue, timeout * HZ);
1854 if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
1855 config->dead_conn_timeout =
1856 nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
1857 config->dead_conn_timeout *= HZ;
1859 if (info->attrs[NBD_ATTR_SERVER_FLAGS])
1861 nla_get_u64(info->attrs[NBD_ATTR_SERVER_FLAGS]);
1862 if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
1863 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
1864 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
1865 set_bit(NBD_DESTROY_ON_DISCONNECT,
1866 &config->runtime_flags);
1869 if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
1870 set_bit(NBD_DISCONNECT_ON_CLOSE,
1871 &config->runtime_flags);
1875 if (info->attrs[NBD_ATTR_SOCKETS]) {
1876 struct nlattr *attr;
1879 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
1881 struct nlattr *socks[NBD_SOCK_MAX+1];
1883 if (nla_type(attr) != NBD_SOCK_ITEM) {
1884 printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
1888 ret = nla_parse_nested(socks, NBD_SOCK_MAX, attr,
1889 nbd_sock_policy, info->extack);
1891 printk(KERN_ERR "nbd: error processing sock list\n");
1895 if (!socks[NBD_SOCK_FD])
1897 fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
1898 ret = nbd_add_socket(nbd, fd, true);
1903 ret = nbd_start_device(nbd);
1905 mutex_unlock(&nbd->config_lock);
1907 set_bit(NBD_HAS_CONFIG_REF, &config->runtime_flags);
1908 refcount_inc(&nbd->config_refs);
1909 nbd_connect_reply(info, nbd->index);
1911 nbd_config_put(nbd);
1917 static void nbd_disconnect_and_put(struct nbd_device *nbd)
1919 mutex_lock(&nbd->config_lock);
1920 nbd_disconnect(nbd);
1921 nbd_clear_sock(nbd);
1922 mutex_unlock(&nbd->config_lock);
1924 * Make sure recv thread has finished, so it does not drop the last
1925 * config ref and try to destroy the workqueue from inside the work
1928 flush_workqueue(nbd->recv_workq);
1929 if (test_and_clear_bit(NBD_HAS_CONFIG_REF,
1930 &nbd->config->runtime_flags))
1931 nbd_config_put(nbd);
1934 static int nbd_genl_disconnect(struct sk_buff *skb, struct genl_info *info)
1936 struct nbd_device *nbd;
1939 if (!netlink_capable(skb, CAP_SYS_ADMIN))
1942 if (!info->attrs[NBD_ATTR_INDEX]) {
1943 printk(KERN_ERR "nbd: must specify an index to disconnect\n");
1946 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1947 mutex_lock(&nbd_index_mutex);
1948 nbd = idr_find(&nbd_index_idr, index);
1950 mutex_unlock(&nbd_index_mutex);
1951 printk(KERN_ERR "nbd: couldn't find device at index %d\n",
1955 if (!refcount_inc_not_zero(&nbd->refs)) {
1956 mutex_unlock(&nbd_index_mutex);
1957 printk(KERN_ERR "nbd: device at index %d is going down\n",
1961 mutex_unlock(&nbd_index_mutex);
1962 if (!refcount_inc_not_zero(&nbd->config_refs)) {
1966 nbd_disconnect_and_put(nbd);
1967 nbd_config_put(nbd);
1972 static int nbd_genl_reconfigure(struct sk_buff *skb, struct genl_info *info)
1974 struct nbd_device *nbd = NULL;
1975 struct nbd_config *config;
1978 bool put_dev = false;
1980 if (!netlink_capable(skb, CAP_SYS_ADMIN))
1983 if (!info->attrs[NBD_ATTR_INDEX]) {
1984 printk(KERN_ERR "nbd: must specify a device to reconfigure\n");
1987 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1988 mutex_lock(&nbd_index_mutex);
1989 nbd = idr_find(&nbd_index_idr, index);
1991 mutex_unlock(&nbd_index_mutex);
1992 printk(KERN_ERR "nbd: couldn't find a device at index %d\n",
1996 if (!refcount_inc_not_zero(&nbd->refs)) {
1997 mutex_unlock(&nbd_index_mutex);
1998 printk(KERN_ERR "nbd: device at index %d is going down\n",
2002 mutex_unlock(&nbd_index_mutex);
2004 if (!refcount_inc_not_zero(&nbd->config_refs)) {
2005 dev_err(nbd_to_dev(nbd),
2006 "not configured, cannot reconfigure\n");
2011 mutex_lock(&nbd->config_lock);
2012 config = nbd->config;
2013 if (!test_bit(NBD_BOUND, &config->runtime_flags) ||
2015 dev_err(nbd_to_dev(nbd),
2016 "not configured, cannot reconfigure\n");
2021 if (info->attrs[NBD_ATTR_TIMEOUT]) {
2022 u64 timeout = nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]);
2023 nbd->tag_set.timeout = timeout * HZ;
2024 blk_queue_rq_timeout(nbd->disk->queue, timeout * HZ);
2026 if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
2027 config->dead_conn_timeout =
2028 nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
2029 config->dead_conn_timeout *= HZ;
2031 if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
2032 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
2033 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
2034 if (!test_and_set_bit(NBD_DESTROY_ON_DISCONNECT,
2035 &config->runtime_flags))
2038 if (test_and_clear_bit(NBD_DESTROY_ON_DISCONNECT,
2039 &config->runtime_flags))
2040 refcount_inc(&nbd->refs);
2043 if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
2044 set_bit(NBD_DISCONNECT_ON_CLOSE,
2045 &config->runtime_flags);
2047 clear_bit(NBD_DISCONNECT_ON_CLOSE,
2048 &config->runtime_flags);
2052 if (info->attrs[NBD_ATTR_SOCKETS]) {
2053 struct nlattr *attr;
2056 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
2058 struct nlattr *socks[NBD_SOCK_MAX+1];
2060 if (nla_type(attr) != NBD_SOCK_ITEM) {
2061 printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
2065 ret = nla_parse_nested(socks, NBD_SOCK_MAX, attr,
2066 nbd_sock_policy, info->extack);
2068 printk(KERN_ERR "nbd: error processing sock list\n");
2072 if (!socks[NBD_SOCK_FD])
2074 fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
2075 ret = nbd_reconnect_socket(nbd, fd);
2081 dev_info(nbd_to_dev(nbd), "reconnected socket\n");
2085 mutex_unlock(&nbd->config_lock);
2086 nbd_config_put(nbd);
2093 static const struct genl_ops nbd_connect_genl_ops[] = {
2095 .cmd = NBD_CMD_CONNECT,
2096 .policy = nbd_attr_policy,
2097 .doit = nbd_genl_connect,
2100 .cmd = NBD_CMD_DISCONNECT,
2101 .policy = nbd_attr_policy,
2102 .doit = nbd_genl_disconnect,
2105 .cmd = NBD_CMD_RECONFIGURE,
2106 .policy = nbd_attr_policy,
2107 .doit = nbd_genl_reconfigure,
2110 .cmd = NBD_CMD_STATUS,
2111 .policy = nbd_attr_policy,
2112 .doit = nbd_genl_status,
2116 static const struct genl_multicast_group nbd_mcast_grps[] = {
2117 { .name = NBD_GENL_MCAST_GROUP_NAME, },
2120 static struct genl_family nbd_genl_family __ro_after_init = {
2122 .name = NBD_GENL_FAMILY_NAME,
2123 .version = NBD_GENL_VERSION,
2124 .module = THIS_MODULE,
2125 .ops = nbd_connect_genl_ops,
2126 .n_ops = ARRAY_SIZE(nbd_connect_genl_ops),
2127 .maxattr = NBD_ATTR_MAX,
2128 .mcgrps = nbd_mcast_grps,
2129 .n_mcgrps = ARRAY_SIZE(nbd_mcast_grps),
2132 static int populate_nbd_status(struct nbd_device *nbd, struct sk_buff *reply)
2134 struct nlattr *dev_opt;
2138 /* This is a little racey, but for status it's ok. The
2139 * reason we don't take a ref here is because we can't
2140 * take a ref in the index == -1 case as we would need
2141 * to put under the nbd_index_mutex, which could
2142 * deadlock if we are configured to remove ourselves
2143 * once we're disconnected.
2145 if (refcount_read(&nbd->config_refs))
2147 dev_opt = nla_nest_start(reply, NBD_DEVICE_ITEM);
2150 ret = nla_put_u32(reply, NBD_DEVICE_INDEX, nbd->index);
2153 ret = nla_put_u8(reply, NBD_DEVICE_CONNECTED,
2157 nla_nest_end(reply, dev_opt);
2161 static int status_cb(int id, void *ptr, void *data)
2163 struct nbd_device *nbd = ptr;
2164 return populate_nbd_status(nbd, (struct sk_buff *)data);
2167 static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info)
2169 struct nlattr *dev_list;
2170 struct sk_buff *reply;
2176 if (info->attrs[NBD_ATTR_INDEX])
2177 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2179 mutex_lock(&nbd_index_mutex);
2181 msg_size = nla_total_size(nla_attr_size(sizeof(u32)) +
2182 nla_attr_size(sizeof(u8)));
2183 msg_size *= (index == -1) ? nbd_total_devices : 1;
2185 reply = genlmsg_new(msg_size, GFP_KERNEL);
2188 reply_head = genlmsg_put_reply(reply, info, &nbd_genl_family, 0,
2195 dev_list = nla_nest_start(reply, NBD_ATTR_DEVICE_LIST);
2197 ret = idr_for_each(&nbd_index_idr, &status_cb, reply);
2203 struct nbd_device *nbd;
2204 nbd = idr_find(&nbd_index_idr, index);
2206 ret = populate_nbd_status(nbd, reply);
2213 nla_nest_end(reply, dev_list);
2214 genlmsg_end(reply, reply_head);
2215 genlmsg_reply(reply, info);
2218 mutex_unlock(&nbd_index_mutex);
2222 static void nbd_connect_reply(struct genl_info *info, int index)
2224 struct sk_buff *skb;
2228 skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2231 msg_head = genlmsg_put_reply(skb, info, &nbd_genl_family, 0,
2237 ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2242 genlmsg_end(skb, msg_head);
2243 genlmsg_reply(skb, info);
2246 static void nbd_mcast_index(int index)
2248 struct sk_buff *skb;
2252 skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2255 msg_head = genlmsg_put(skb, 0, 0, &nbd_genl_family, 0,
2261 ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2266 genlmsg_end(skb, msg_head);
2267 genlmsg_multicast(&nbd_genl_family, skb, 0, 0, GFP_KERNEL);
2270 static void nbd_dead_link_work(struct work_struct *work)
2272 struct link_dead_args *args = container_of(work, struct link_dead_args,
2274 nbd_mcast_index(args->index);
2278 static int __init nbd_init(void)
2282 BUILD_BUG_ON(sizeof(struct nbd_request) != 28);
2285 printk(KERN_ERR "nbd: max_part must be >= 0\n");
2291 part_shift = fls(max_part);
2294 * Adjust max_part according to part_shift as it is exported
2295 * to user space so that user can know the max number of
2296 * partition kernel should be able to manage.
2298 * Note that -1 is required because partition 0 is reserved
2299 * for the whole disk.
2301 max_part = (1UL << part_shift) - 1;
2304 if ((1UL << part_shift) > DISK_MAX_PARTS)
2307 if (nbds_max > 1UL << (MINORBITS - part_shift))
2310 if (register_blkdev(NBD_MAJOR, "nbd"))
2313 if (genl_register_family(&nbd_genl_family)) {
2314 unregister_blkdev(NBD_MAJOR, "nbd");
2319 mutex_lock(&nbd_index_mutex);
2320 for (i = 0; i < nbds_max; i++)
2322 mutex_unlock(&nbd_index_mutex);
2326 static int nbd_exit_cb(int id, void *ptr, void *data)
2328 struct list_head *list = (struct list_head *)data;
2329 struct nbd_device *nbd = ptr;
2331 list_add_tail(&nbd->list, list);
2335 static void __exit nbd_cleanup(void)
2337 struct nbd_device *nbd;
2338 LIST_HEAD(del_list);
2342 mutex_lock(&nbd_index_mutex);
2343 idr_for_each(&nbd_index_idr, &nbd_exit_cb, &del_list);
2344 mutex_unlock(&nbd_index_mutex);
2346 while (!list_empty(&del_list)) {
2347 nbd = list_first_entry(&del_list, struct nbd_device, list);
2348 list_del_init(&nbd->list);
2349 if (refcount_read(&nbd->refs) != 1)
2350 printk(KERN_ERR "nbd: possibly leaking a device\n");
2354 idr_destroy(&nbd_index_idr);
2355 genl_unregister_family(&nbd_genl_family);
2356 unregister_blkdev(NBD_MAJOR, "nbd");
2359 module_init(nbd_init);
2360 module_exit(nbd_cleanup);
2362 MODULE_DESCRIPTION("Network Block Device");
2363 MODULE_LICENSE("GPL");
2365 module_param(nbds_max, int, 0444);
2366 MODULE_PARM_DESC(nbds_max, "number of network block devices to initialize (default: 16)");
2367 module_param(max_part, int, 0444);
2368 MODULE_PARM_DESC(max_part, "number of partitions per device (default: 16)");