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/err.h>
30 #include <linux/kernel.h>
31 #include <linux/slab.h>
33 #include <linux/net.h>
34 #include <linux/kthread.h>
35 #include <linux/types.h>
36 #include <linux/debugfs.h>
37 #include <linux/blk-mq.h>
39 #include <linux/uaccess.h>
40 #include <asm/types.h>
42 #include <linux/nbd.h>
43 #include <linux/nbd-netlink.h>
44 #include <net/genetlink.h>
46 #define CREATE_TRACE_POINTS
47 #include <trace/events/nbd.h>
49 static DEFINE_IDR(nbd_index_idr);
50 static DEFINE_MUTEX(nbd_index_mutex);
51 static int nbd_total_devices = 0;
56 struct request *pending;
63 struct recv_thread_args {
64 struct work_struct work;
65 struct nbd_device *nbd;
69 struct link_dead_args {
70 struct work_struct work;
74 #define NBD_TIMEDOUT 0
75 #define NBD_DISCONNECT_REQUESTED 1
76 #define NBD_DISCONNECTED 2
77 #define NBD_HAS_PID_FILE 3
78 #define NBD_HAS_CONFIG_REF 4
80 #define NBD_DESTROY_ON_DISCONNECT 6
81 #define NBD_DISCONNECT_ON_CLOSE 7
85 unsigned long runtime_flags;
86 u64 dead_conn_timeout;
88 struct nbd_sock **socks;
90 atomic_t live_connections;
91 wait_queue_head_t conn_wait;
93 atomic_t recv_threads;
94 wait_queue_head_t recv_wq;
97 #if IS_ENABLED(CONFIG_DEBUG_FS)
98 struct dentry *dbg_dir;
103 struct blk_mq_tag_set tag_set;
106 refcount_t config_refs;
108 struct nbd_config *config;
109 struct mutex config_lock;
110 struct gendisk *disk;
112 struct list_head list;
113 struct task_struct *task_recv;
114 struct task_struct *task_setup;
117 #define NBD_CMD_REQUEUED 1
120 struct nbd_device *nbd;
129 #if IS_ENABLED(CONFIG_DEBUG_FS)
130 static struct dentry *nbd_dbg_dir;
133 #define nbd_name(nbd) ((nbd)->disk->disk_name)
135 #define NBD_MAGIC 0x68797548
137 #define NBD_DEF_BLKSIZE 1024
139 static unsigned int nbds_max = 16;
140 static int max_part = 16;
141 static struct workqueue_struct *recv_workqueue;
142 static int part_shift;
144 static int nbd_dev_dbg_init(struct nbd_device *nbd);
145 static void nbd_dev_dbg_close(struct nbd_device *nbd);
146 static void nbd_config_put(struct nbd_device *nbd);
147 static void nbd_connect_reply(struct genl_info *info, int index);
148 static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info);
149 static void nbd_dead_link_work(struct work_struct *work);
150 static void nbd_disconnect_and_put(struct nbd_device *nbd);
152 static inline struct device *nbd_to_dev(struct nbd_device *nbd)
154 return disk_to_dev(nbd->disk);
157 static void nbd_requeue_cmd(struct nbd_cmd *cmd)
159 struct request *req = blk_mq_rq_from_pdu(cmd);
161 if (!test_and_set_bit(NBD_CMD_REQUEUED, &cmd->flags))
162 blk_mq_requeue_request(req, true);
165 #define NBD_COOKIE_BITS 32
167 static u64 nbd_cmd_handle(struct nbd_cmd *cmd)
169 struct request *req = blk_mq_rq_from_pdu(cmd);
170 u32 tag = blk_mq_unique_tag(req);
171 u64 cookie = cmd->cmd_cookie;
173 return (cookie << NBD_COOKIE_BITS) | tag;
176 static u32 nbd_handle_to_tag(u64 handle)
181 static u32 nbd_handle_to_cookie(u64 handle)
183 return (u32)(handle >> NBD_COOKIE_BITS);
186 static const char *nbdcmd_to_ascii(int cmd)
189 case NBD_CMD_READ: return "read";
190 case NBD_CMD_WRITE: return "write";
191 case NBD_CMD_DISC: return "disconnect";
192 case NBD_CMD_FLUSH: return "flush";
193 case NBD_CMD_TRIM: return "trim/discard";
198 static ssize_t pid_show(struct device *dev,
199 struct device_attribute *attr, char *buf)
201 struct gendisk *disk = dev_to_disk(dev);
202 struct nbd_device *nbd = (struct nbd_device *)disk->private_data;
204 return sprintf(buf, "%d\n", task_pid_nr(nbd->task_recv));
207 static const struct device_attribute pid_attr = {
208 .attr = { .name = "pid", .mode = 0444},
212 static void nbd_dev_remove(struct nbd_device *nbd)
214 struct gendisk *disk = nbd->disk;
215 struct request_queue *q;
220 blk_cleanup_queue(q);
221 blk_mq_free_tag_set(&nbd->tag_set);
222 disk->private_data = NULL;
228 static void nbd_put(struct nbd_device *nbd)
230 if (refcount_dec_and_mutex_lock(&nbd->refs,
232 idr_remove(&nbd_index_idr, nbd->index);
233 mutex_unlock(&nbd_index_mutex);
238 static int nbd_disconnected(struct nbd_config *config)
240 return test_bit(NBD_DISCONNECTED, &config->runtime_flags) ||
241 test_bit(NBD_DISCONNECT_REQUESTED, &config->runtime_flags);
244 static void nbd_mark_nsock_dead(struct nbd_device *nbd, struct nbd_sock *nsock,
247 if (!nsock->dead && notify && !nbd_disconnected(nbd->config)) {
248 struct link_dead_args *args;
249 args = kmalloc(sizeof(struct link_dead_args), GFP_NOIO);
251 INIT_WORK(&args->work, nbd_dead_link_work);
252 args->index = nbd->index;
253 queue_work(system_wq, &args->work);
257 kernel_sock_shutdown(nsock->sock, SHUT_RDWR);
258 if (atomic_dec_return(&nbd->config->live_connections) == 0) {
259 if (test_and_clear_bit(NBD_DISCONNECT_REQUESTED,
260 &nbd->config->runtime_flags)) {
261 set_bit(NBD_DISCONNECTED,
262 &nbd->config->runtime_flags);
263 dev_info(nbd_to_dev(nbd),
264 "Disconnected due to user request.\n");
269 nsock->pending = NULL;
273 static void nbd_size_clear(struct nbd_device *nbd)
275 if (nbd->config->bytesize) {
276 set_capacity(nbd->disk, 0);
277 kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
281 static void nbd_size_update(struct nbd_device *nbd)
283 struct nbd_config *config = nbd->config;
284 struct block_device *bdev = bdget_disk(nbd->disk, 0);
286 if (config->flags & NBD_FLAG_SEND_TRIM) {
287 nbd->disk->queue->limits.discard_granularity = config->blksize;
288 nbd->disk->queue->limits.discard_alignment = config->blksize;
289 blk_queue_max_discard_sectors(nbd->disk->queue, UINT_MAX);
291 blk_queue_logical_block_size(nbd->disk->queue, config->blksize);
292 blk_queue_physical_block_size(nbd->disk->queue, config->blksize);
293 set_capacity(nbd->disk, config->bytesize >> 9);
296 bd_set_size(bdev, config->bytesize);
297 set_blocksize(bdev, config->blksize);
299 bdev->bd_invalidated = 1;
302 kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
305 static void nbd_size_set(struct nbd_device *nbd, loff_t blocksize,
308 struct nbd_config *config = nbd->config;
309 config->blksize = blocksize;
310 config->bytesize = blocksize * nr_blocks;
311 if (nbd->task_recv != NULL)
312 nbd_size_update(nbd);
315 static void nbd_complete_rq(struct request *req)
317 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
319 dev_dbg(nbd_to_dev(cmd->nbd), "request %p: %s\n", req,
320 cmd->status ? "failed" : "done");
322 blk_mq_end_request(req, cmd->status);
326 * Forcibly shutdown the socket causing all listeners to error
328 static void sock_shutdown(struct nbd_device *nbd)
330 struct nbd_config *config = nbd->config;
333 if (config->num_connections == 0)
335 if (test_and_set_bit(NBD_DISCONNECTED, &config->runtime_flags))
338 for (i = 0; i < config->num_connections; i++) {
339 struct nbd_sock *nsock = config->socks[i];
340 mutex_lock(&nsock->tx_lock);
341 nbd_mark_nsock_dead(nbd, nsock, 0);
342 mutex_unlock(&nsock->tx_lock);
344 dev_warn(disk_to_dev(nbd->disk), "shutting down sockets\n");
347 static enum blk_eh_timer_return nbd_xmit_timeout(struct request *req,
350 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
351 struct nbd_device *nbd = cmd->nbd;
352 struct nbd_config *config;
354 if (!refcount_inc_not_zero(&nbd->config_refs)) {
355 cmd->status = BLK_STS_TIMEOUT;
358 config = nbd->config;
360 if (!mutex_trylock(&cmd->lock))
361 return BLK_EH_RESET_TIMER;
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, &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);
518 /* initialize handle for tracing purposes */
519 handle = nbd_cmd_handle(cmd);
523 iov_iter_advance(&from, sent);
528 cmd->cookie = nsock->cookie;
529 request.type = htonl(type | nbd_cmd_flags);
530 if (type != NBD_CMD_FLUSH) {
531 request.from = cpu_to_be64((u64)blk_rq_pos(req) << 9);
532 request.len = htonl(size);
534 handle = nbd_cmd_handle(cmd);
535 memcpy(request.handle, &handle, sizeof(handle));
537 trace_nbd_send_request(&request, nbd->index, blk_mq_rq_from_pdu(cmd));
539 dev_dbg(nbd_to_dev(nbd), "request %p: sending control (%s@%llu,%uB)\n",
540 req, nbdcmd_to_ascii(type),
541 (unsigned long long)blk_rq_pos(req) << 9, blk_rq_bytes(req));
542 result = sock_xmit(nbd, index, 1, &from,
543 (type == NBD_CMD_WRITE) ? MSG_MORE : 0, &sent);
544 trace_nbd_header_sent(req, handle);
546 if (was_interrupted(result)) {
547 /* If we havne't sent anything we can just return BUSY,
548 * however if we have sent something we need to make
549 * sure we only allow this req to be sent until we are
553 nsock->pending = req;
556 set_bit(NBD_CMD_REQUEUED, &cmd->flags);
557 return BLK_STS_RESOURCE;
559 dev_err_ratelimited(disk_to_dev(nbd->disk),
560 "Send control failed (result %d)\n", result);
564 if (type != NBD_CMD_WRITE)
569 struct bio *next = bio->bi_next;
570 struct bvec_iter iter;
573 bio_for_each_segment(bvec, bio, iter) {
574 bool is_last = !next && bio_iter_last(bvec, iter);
575 int flags = is_last ? 0 : MSG_MORE;
577 dev_dbg(nbd_to_dev(nbd), "request %p: sending %d bytes data\n",
579 iov_iter_bvec(&from, WRITE, &bvec, 1, bvec.bv_len);
581 if (skip >= iov_iter_count(&from)) {
582 skip -= iov_iter_count(&from);
585 iov_iter_advance(&from, skip);
588 result = sock_xmit(nbd, index, 1, &from, flags, &sent);
590 if (was_interrupted(result)) {
591 /* We've already sent the header, we
592 * have no choice but to set pending and
595 nsock->pending = req;
597 set_bit(NBD_CMD_REQUEUED, &cmd->flags);
598 return BLK_STS_RESOURCE;
600 dev_err(disk_to_dev(nbd->disk),
601 "Send data failed (result %d)\n",
606 * The completion might already have come in,
607 * so break for the last one instead of letting
608 * the iterator do it. This prevents use-after-free
617 trace_nbd_payload_sent(req, handle);
618 nsock->pending = NULL;
623 /* NULL returned = something went wrong, inform userspace */
624 static struct nbd_cmd *nbd_read_stat(struct nbd_device *nbd, int index)
626 struct nbd_config *config = nbd->config;
628 struct nbd_reply reply;
630 struct request *req = NULL;
634 struct kvec iov = {.iov_base = &reply, .iov_len = sizeof(reply)};
639 iov_iter_kvec(&to, READ, &iov, 1, sizeof(reply));
640 result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
642 if (!nbd_disconnected(config))
643 dev_err(disk_to_dev(nbd->disk),
644 "Receive control failed (result %d)\n", result);
645 return ERR_PTR(result);
648 if (ntohl(reply.magic) != NBD_REPLY_MAGIC) {
649 dev_err(disk_to_dev(nbd->disk), "Wrong magic (0x%lx)\n",
650 (unsigned long)ntohl(reply.magic));
651 return ERR_PTR(-EPROTO);
654 memcpy(&handle, reply.handle, sizeof(handle));
655 tag = nbd_handle_to_tag(handle);
656 hwq = blk_mq_unique_tag_to_hwq(tag);
657 if (hwq < nbd->tag_set.nr_hw_queues)
658 req = blk_mq_tag_to_rq(nbd->tag_set.tags[hwq],
659 blk_mq_unique_tag_to_tag(tag));
660 if (!req || !blk_mq_request_started(req)) {
661 dev_err(disk_to_dev(nbd->disk), "Unexpected reply (%d) %p\n",
663 return ERR_PTR(-ENOENT);
665 trace_nbd_header_received(req, handle);
666 cmd = blk_mq_rq_to_pdu(req);
668 mutex_lock(&cmd->lock);
669 if (cmd->cmd_cookie != nbd_handle_to_cookie(handle)) {
670 dev_err(disk_to_dev(nbd->disk), "Double reply on req %p, cmd_cookie %u, handle cookie %u\n",
671 req, cmd->cmd_cookie, nbd_handle_to_cookie(handle));
675 if (test_bit(NBD_CMD_REQUEUED, &cmd->flags)) {
676 dev_err(disk_to_dev(nbd->disk), "Raced with timeout on req %p\n",
681 if (ntohl(reply.error)) {
682 dev_err(disk_to_dev(nbd->disk), "Other side returned error (%d)\n",
684 cmd->status = BLK_STS_IOERR;
688 dev_dbg(nbd_to_dev(nbd), "request %p: got reply\n", req);
689 if (rq_data_dir(req) != WRITE) {
690 struct req_iterator iter;
693 rq_for_each_segment(bvec, req, iter) {
694 iov_iter_bvec(&to, READ, &bvec, 1, bvec.bv_len);
695 result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
697 dev_err(disk_to_dev(nbd->disk), "Receive data failed (result %d)\n",
700 * If we've disconnected or we only have 1
701 * connection then we need to make sure we
702 * complete this request, otherwise error out
703 * and let the timeout stuff handle resubmitting
704 * this request onto another connection.
706 if (nbd_disconnected(config) ||
707 config->num_connections <= 1) {
708 cmd->status = BLK_STS_IOERR;
714 dev_dbg(nbd_to_dev(nbd), "request %p: got %d bytes data\n",
719 trace_nbd_payload_received(req, handle);
720 mutex_unlock(&cmd->lock);
721 return ret ? ERR_PTR(ret) : cmd;
724 static void recv_work(struct work_struct *work)
726 struct recv_thread_args *args = container_of(work,
727 struct recv_thread_args,
729 struct nbd_device *nbd = args->nbd;
730 struct nbd_config *config = nbd->config;
734 cmd = nbd_read_stat(nbd, args->index);
736 struct nbd_sock *nsock = config->socks[args->index];
738 mutex_lock(&nsock->tx_lock);
739 nbd_mark_nsock_dead(nbd, nsock, 1);
740 mutex_unlock(&nsock->tx_lock);
744 blk_mq_complete_request(blk_mq_rq_from_pdu(cmd));
746 atomic_dec(&config->recv_threads);
747 wake_up(&config->recv_wq);
752 static bool nbd_clear_req(struct request *req, void *data, bool reserved)
754 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
756 cmd->status = BLK_STS_IOERR;
757 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 int nbd_add_socket(struct nbd_device *nbd, unsigned long arg,
939 struct nbd_config *config = nbd->config;
941 struct nbd_sock **socks;
942 struct nbd_sock *nsock;
945 sock = sockfd_lookup(arg, &err);
949 if (!netlink && !nbd->task_setup &&
950 !test_bit(NBD_BOUND, &config->runtime_flags))
951 nbd->task_setup = current;
954 (nbd->task_setup != current ||
955 test_bit(NBD_BOUND, &config->runtime_flags))) {
956 dev_err(disk_to_dev(nbd->disk),
957 "Device being setup by another task");
962 socks = krealloc(config->socks, (config->num_connections + 1) *
963 sizeof(struct nbd_sock *), GFP_KERNEL);
968 nsock = kzalloc(sizeof(struct nbd_sock), GFP_KERNEL);
974 config->socks = socks;
976 nsock->fallback_index = -1;
978 mutex_init(&nsock->tx_lock);
980 nsock->pending = NULL;
983 socks[config->num_connections++] = nsock;
984 atomic_inc(&config->live_connections);
989 static int nbd_reconnect_socket(struct nbd_device *nbd, unsigned long arg)
991 struct nbd_config *config = nbd->config;
992 struct socket *sock, *old;
993 struct recv_thread_args *args;
997 sock = sockfd_lookup(arg, &err);
1001 args = kzalloc(sizeof(*args), GFP_KERNEL);
1007 for (i = 0; i < config->num_connections; i++) {
1008 struct nbd_sock *nsock = config->socks[i];
1013 mutex_lock(&nsock->tx_lock);
1015 mutex_unlock(&nsock->tx_lock);
1018 sk_set_memalloc(sock->sk);
1019 if (nbd->tag_set.timeout)
1020 sock->sk->sk_sndtimeo = nbd->tag_set.timeout;
1021 atomic_inc(&config->recv_threads);
1022 refcount_inc(&nbd->config_refs);
1024 nsock->fallback_index = -1;
1026 nsock->dead = false;
1027 INIT_WORK(&args->work, recv_work);
1031 mutex_unlock(&nsock->tx_lock);
1034 clear_bit(NBD_DISCONNECTED, &config->runtime_flags);
1036 /* We take the tx_mutex in an error path in the recv_work, so we
1037 * need to queue_work outside of the tx_mutex.
1039 queue_work(recv_workqueue, &args->work);
1041 atomic_inc(&config->live_connections);
1042 wake_up(&config->conn_wait);
1050 static void nbd_bdev_reset(struct block_device *bdev)
1052 if (bdev->bd_openers > 1)
1054 bd_set_size(bdev, 0);
1057 static void nbd_parse_flags(struct nbd_device *nbd)
1059 struct nbd_config *config = nbd->config;
1060 if (config->flags & NBD_FLAG_READ_ONLY)
1061 set_disk_ro(nbd->disk, true);
1063 set_disk_ro(nbd->disk, false);
1064 if (config->flags & NBD_FLAG_SEND_TRIM)
1065 blk_queue_flag_set(QUEUE_FLAG_DISCARD, nbd->disk->queue);
1066 if (config->flags & NBD_FLAG_SEND_FLUSH) {
1067 if (config->flags & NBD_FLAG_SEND_FUA)
1068 blk_queue_write_cache(nbd->disk->queue, true, true);
1070 blk_queue_write_cache(nbd->disk->queue, true, false);
1073 blk_queue_write_cache(nbd->disk->queue, false, false);
1076 static void send_disconnects(struct nbd_device *nbd)
1078 struct nbd_config *config = nbd->config;
1079 struct nbd_request request = {
1080 .magic = htonl(NBD_REQUEST_MAGIC),
1081 .type = htonl(NBD_CMD_DISC),
1083 struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
1084 struct iov_iter from;
1087 for (i = 0; i < config->num_connections; i++) {
1088 struct nbd_sock *nsock = config->socks[i];
1090 iov_iter_kvec(&from, WRITE, &iov, 1, sizeof(request));
1091 mutex_lock(&nsock->tx_lock);
1092 ret = sock_xmit(nbd, i, 1, &from, 0, NULL);
1094 dev_err(disk_to_dev(nbd->disk),
1095 "Send disconnect failed %d\n", ret);
1096 mutex_unlock(&nsock->tx_lock);
1100 static int nbd_disconnect(struct nbd_device *nbd)
1102 struct nbd_config *config = nbd->config;
1104 dev_info(disk_to_dev(nbd->disk), "NBD_DISCONNECT\n");
1105 set_bit(NBD_DISCONNECT_REQUESTED, &config->runtime_flags);
1106 send_disconnects(nbd);
1110 static void nbd_clear_sock(struct nbd_device *nbd)
1114 nbd->task_setup = NULL;
1117 static void nbd_config_put(struct nbd_device *nbd)
1119 if (refcount_dec_and_mutex_lock(&nbd->config_refs,
1120 &nbd->config_lock)) {
1121 struct nbd_config *config = nbd->config;
1122 nbd_dev_dbg_close(nbd);
1123 nbd_size_clear(nbd);
1124 if (test_and_clear_bit(NBD_HAS_PID_FILE,
1125 &config->runtime_flags))
1126 device_remove_file(disk_to_dev(nbd->disk), &pid_attr);
1127 nbd->task_recv = NULL;
1128 nbd_clear_sock(nbd);
1129 if (config->num_connections) {
1131 for (i = 0; i < config->num_connections; i++) {
1132 sockfd_put(config->socks[i]->sock);
1133 kfree(config->socks[i]);
1135 kfree(config->socks);
1140 nbd->tag_set.timeout = 0;
1141 nbd->disk->queue->limits.discard_granularity = 0;
1142 nbd->disk->queue->limits.discard_alignment = 0;
1143 blk_queue_max_discard_sectors(nbd->disk->queue, UINT_MAX);
1144 blk_queue_flag_clear(QUEUE_FLAG_DISCARD, nbd->disk->queue);
1146 mutex_unlock(&nbd->config_lock);
1148 module_put(THIS_MODULE);
1152 static int nbd_start_device(struct nbd_device *nbd)
1154 struct nbd_config *config = nbd->config;
1155 int num_connections = config->num_connections;
1162 if (num_connections > 1 &&
1163 !(config->flags & NBD_FLAG_CAN_MULTI_CONN)) {
1164 dev_err(disk_to_dev(nbd->disk), "server does not support multiple connections per device.\n");
1168 blk_mq_update_nr_hw_queues(&nbd->tag_set, config->num_connections);
1169 nbd->task_recv = current;
1171 nbd_parse_flags(nbd);
1173 error = device_create_file(disk_to_dev(nbd->disk), &pid_attr);
1175 dev_err(disk_to_dev(nbd->disk), "device_create_file failed!\n");
1178 set_bit(NBD_HAS_PID_FILE, &config->runtime_flags);
1180 nbd_dev_dbg_init(nbd);
1181 for (i = 0; i < num_connections; i++) {
1182 struct recv_thread_args *args;
1184 args = kzalloc(sizeof(*args), GFP_KERNEL);
1189 sk_set_memalloc(config->socks[i]->sock->sk);
1190 if (nbd->tag_set.timeout)
1191 config->socks[i]->sock->sk->sk_sndtimeo =
1192 nbd->tag_set.timeout;
1193 atomic_inc(&config->recv_threads);
1194 refcount_inc(&nbd->config_refs);
1195 INIT_WORK(&args->work, recv_work);
1198 queue_work(recv_workqueue, &args->work);
1200 nbd_size_update(nbd);
1204 static int nbd_start_device_ioctl(struct nbd_device *nbd, struct block_device *bdev)
1206 struct nbd_config *config = nbd->config;
1209 ret = nbd_start_device(nbd);
1214 bdev->bd_invalidated = 1;
1215 mutex_unlock(&nbd->config_lock);
1216 ret = wait_event_interruptible(config->recv_wq,
1217 atomic_read(&config->recv_threads) == 0);
1220 mutex_lock(&nbd->config_lock);
1221 nbd_bdev_reset(bdev);
1222 /* user requested, ignore socket errors */
1223 if (test_bit(NBD_DISCONNECT_REQUESTED, &config->runtime_flags))
1225 if (test_bit(NBD_TIMEDOUT, &config->runtime_flags))
1230 static void nbd_clear_sock_ioctl(struct nbd_device *nbd,
1231 struct block_device *bdev)
1234 __invalidate_device(bdev, true);
1235 nbd_bdev_reset(bdev);
1236 if (test_and_clear_bit(NBD_HAS_CONFIG_REF,
1237 &nbd->config->runtime_flags))
1238 nbd_config_put(nbd);
1241 static bool nbd_is_valid_blksize(unsigned long blksize)
1243 if (!blksize || !is_power_of_2(blksize) || blksize < 512 ||
1244 blksize > PAGE_SIZE)
1249 /* Must be called with config_lock held */
1250 static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
1251 unsigned int cmd, unsigned long arg)
1253 struct nbd_config *config = nbd->config;
1256 case NBD_DISCONNECT:
1257 return nbd_disconnect(nbd);
1258 case NBD_CLEAR_SOCK:
1259 nbd_clear_sock_ioctl(nbd, bdev);
1262 return nbd_add_socket(nbd, arg, false);
1263 case NBD_SET_BLKSIZE:
1265 arg = NBD_DEF_BLKSIZE;
1266 if (!nbd_is_valid_blksize(arg))
1268 nbd_size_set(nbd, arg,
1269 div_s64(config->bytesize, arg));
1272 nbd_size_set(nbd, config->blksize,
1273 div_s64(arg, config->blksize));
1275 case NBD_SET_SIZE_BLOCKS:
1276 nbd_size_set(nbd, config->blksize, arg);
1278 case NBD_SET_TIMEOUT:
1280 nbd->tag_set.timeout = arg * HZ;
1281 blk_queue_rq_timeout(nbd->disk->queue, arg * HZ);
1286 config->flags = arg;
1289 return nbd_start_device_ioctl(nbd, bdev);
1292 * This is for compatibility only. The queue is always cleared
1293 * by NBD_DO_IT or NBD_CLEAR_SOCK.
1296 case NBD_PRINT_DEBUG:
1298 * For compatibility only, we no longer keep a list of
1299 * outstanding requests.
1306 static int nbd_ioctl(struct block_device *bdev, fmode_t mode,
1307 unsigned int cmd, unsigned long arg)
1309 struct nbd_device *nbd = bdev->bd_disk->private_data;
1310 struct nbd_config *config = nbd->config;
1311 int error = -EINVAL;
1313 if (!capable(CAP_SYS_ADMIN))
1316 /* The block layer will pass back some non-nbd ioctls in case we have
1317 * special handling for them, but we don't so just return an error.
1319 if (_IOC_TYPE(cmd) != 0xab)
1322 mutex_lock(&nbd->config_lock);
1324 /* Don't allow ioctl operations on a nbd device that was created with
1325 * netlink, unless it's DISCONNECT or CLEAR_SOCK, which are fine.
1327 if (!test_bit(NBD_BOUND, &config->runtime_flags) ||
1328 (cmd == NBD_DISCONNECT || cmd == NBD_CLEAR_SOCK))
1329 error = __nbd_ioctl(bdev, nbd, cmd, arg);
1331 dev_err(nbd_to_dev(nbd), "Cannot use ioctl interface on a netlink controlled device.\n");
1332 mutex_unlock(&nbd->config_lock);
1336 static struct nbd_config *nbd_alloc_config(void)
1338 struct nbd_config *config;
1340 config = kzalloc(sizeof(struct nbd_config), GFP_NOFS);
1343 atomic_set(&config->recv_threads, 0);
1344 init_waitqueue_head(&config->recv_wq);
1345 init_waitqueue_head(&config->conn_wait);
1346 config->blksize = NBD_DEF_BLKSIZE;
1347 atomic_set(&config->live_connections, 0);
1348 try_module_get(THIS_MODULE);
1352 static int nbd_open(struct block_device *bdev, fmode_t mode)
1354 struct nbd_device *nbd;
1357 mutex_lock(&nbd_index_mutex);
1358 nbd = bdev->bd_disk->private_data;
1363 if (!refcount_inc_not_zero(&nbd->refs)) {
1367 if (!refcount_inc_not_zero(&nbd->config_refs)) {
1368 struct nbd_config *config;
1370 mutex_lock(&nbd->config_lock);
1371 if (refcount_inc_not_zero(&nbd->config_refs)) {
1372 mutex_unlock(&nbd->config_lock);
1375 config = nbd->config = nbd_alloc_config();
1378 mutex_unlock(&nbd->config_lock);
1381 refcount_set(&nbd->config_refs, 1);
1382 refcount_inc(&nbd->refs);
1383 mutex_unlock(&nbd->config_lock);
1384 bdev->bd_invalidated = 1;
1385 } else if (nbd_disconnected(nbd->config)) {
1386 bdev->bd_invalidated = 1;
1389 mutex_unlock(&nbd_index_mutex);
1393 static void nbd_release(struct gendisk *disk, fmode_t mode)
1395 struct nbd_device *nbd = disk->private_data;
1396 struct block_device *bdev = bdget_disk(disk, 0);
1398 if (test_bit(NBD_DISCONNECT_ON_CLOSE, &nbd->config->runtime_flags) &&
1399 bdev->bd_openers == 0)
1400 nbd_disconnect_and_put(nbd);
1402 nbd_config_put(nbd);
1406 static const struct block_device_operations nbd_fops =
1408 .owner = THIS_MODULE,
1410 .release = nbd_release,
1412 .compat_ioctl = nbd_ioctl,
1415 #if IS_ENABLED(CONFIG_DEBUG_FS)
1417 static int nbd_dbg_tasks_show(struct seq_file *s, void *unused)
1419 struct nbd_device *nbd = s->private;
1422 seq_printf(s, "recv: %d\n", task_pid_nr(nbd->task_recv));
1427 static int nbd_dbg_tasks_open(struct inode *inode, struct file *file)
1429 return single_open(file, nbd_dbg_tasks_show, inode->i_private);
1432 static const struct file_operations nbd_dbg_tasks_ops = {
1433 .open = nbd_dbg_tasks_open,
1435 .llseek = seq_lseek,
1436 .release = single_release,
1439 static int nbd_dbg_flags_show(struct seq_file *s, void *unused)
1441 struct nbd_device *nbd = s->private;
1442 u32 flags = nbd->config->flags;
1444 seq_printf(s, "Hex: 0x%08x\n\n", flags);
1446 seq_puts(s, "Known flags:\n");
1448 if (flags & NBD_FLAG_HAS_FLAGS)
1449 seq_puts(s, "NBD_FLAG_HAS_FLAGS\n");
1450 if (flags & NBD_FLAG_READ_ONLY)
1451 seq_puts(s, "NBD_FLAG_READ_ONLY\n");
1452 if (flags & NBD_FLAG_SEND_FLUSH)
1453 seq_puts(s, "NBD_FLAG_SEND_FLUSH\n");
1454 if (flags & NBD_FLAG_SEND_FUA)
1455 seq_puts(s, "NBD_FLAG_SEND_FUA\n");
1456 if (flags & NBD_FLAG_SEND_TRIM)
1457 seq_puts(s, "NBD_FLAG_SEND_TRIM\n");
1462 static int nbd_dbg_flags_open(struct inode *inode, struct file *file)
1464 return single_open(file, nbd_dbg_flags_show, inode->i_private);
1467 static const struct file_operations nbd_dbg_flags_ops = {
1468 .open = nbd_dbg_flags_open,
1470 .llseek = seq_lseek,
1471 .release = single_release,
1474 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1477 struct nbd_config *config = nbd->config;
1482 dir = debugfs_create_dir(nbd_name(nbd), nbd_dbg_dir);
1484 dev_err(nbd_to_dev(nbd), "Failed to create debugfs dir for '%s'\n",
1488 config->dbg_dir = dir;
1490 debugfs_create_file("tasks", 0444, dir, nbd, &nbd_dbg_tasks_ops);
1491 debugfs_create_u64("size_bytes", 0444, dir, &config->bytesize);
1492 debugfs_create_u32("timeout", 0444, dir, &nbd->tag_set.timeout);
1493 debugfs_create_u64("blocksize", 0444, dir, &config->blksize);
1494 debugfs_create_file("flags", 0444, dir, nbd, &nbd_dbg_flags_ops);
1499 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1501 debugfs_remove_recursive(nbd->config->dbg_dir);
1504 static int nbd_dbg_init(void)
1506 struct dentry *dbg_dir;
1508 dbg_dir = debugfs_create_dir("nbd", NULL);
1512 nbd_dbg_dir = dbg_dir;
1517 static void nbd_dbg_close(void)
1519 debugfs_remove_recursive(nbd_dbg_dir);
1522 #else /* IS_ENABLED(CONFIG_DEBUG_FS) */
1524 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1529 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1533 static int nbd_dbg_init(void)
1538 static void nbd_dbg_close(void)
1544 static int nbd_init_request(struct blk_mq_tag_set *set, struct request *rq,
1545 unsigned int hctx_idx, unsigned int numa_node)
1547 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(rq);
1548 cmd->nbd = set->driver_data;
1550 mutex_init(&cmd->lock);
1554 static const struct blk_mq_ops nbd_mq_ops = {
1555 .queue_rq = nbd_queue_rq,
1556 .complete = nbd_complete_rq,
1557 .init_request = nbd_init_request,
1558 .timeout = nbd_xmit_timeout,
1561 static int nbd_dev_add(int index)
1563 struct nbd_device *nbd;
1564 struct gendisk *disk;
1565 struct request_queue *q;
1568 nbd = kzalloc(sizeof(struct nbd_device), GFP_KERNEL);
1572 disk = alloc_disk(1 << part_shift);
1577 err = idr_alloc(&nbd_index_idr, nbd, index, index + 1,
1582 err = idr_alloc(&nbd_index_idr, nbd, 0, 0, GFP_KERNEL);
1591 nbd->tag_set.ops = &nbd_mq_ops;
1592 nbd->tag_set.nr_hw_queues = 1;
1593 nbd->tag_set.queue_depth = 128;
1594 nbd->tag_set.numa_node = NUMA_NO_NODE;
1595 nbd->tag_set.cmd_size = sizeof(struct nbd_cmd);
1596 nbd->tag_set.flags = BLK_MQ_F_SHOULD_MERGE |
1598 nbd->tag_set.driver_data = nbd;
1600 err = blk_mq_alloc_tag_set(&nbd->tag_set);
1604 q = blk_mq_init_queue(&nbd->tag_set);
1612 * Tell the block layer that we are not a rotational device
1614 blk_queue_flag_set(QUEUE_FLAG_NONROT, disk->queue);
1615 blk_queue_flag_clear(QUEUE_FLAG_ADD_RANDOM, disk->queue);
1616 disk->queue->limits.discard_granularity = 0;
1617 disk->queue->limits.discard_alignment = 0;
1618 blk_queue_max_discard_sectors(disk->queue, 0);
1619 blk_queue_max_segment_size(disk->queue, UINT_MAX);
1620 blk_queue_max_segments(disk->queue, USHRT_MAX);
1621 blk_queue_max_hw_sectors(disk->queue, 65536);
1622 disk->queue->limits.max_sectors = 256;
1624 mutex_init(&nbd->config_lock);
1625 refcount_set(&nbd->config_refs, 0);
1626 refcount_set(&nbd->refs, 1);
1627 INIT_LIST_HEAD(&nbd->list);
1628 disk->major = NBD_MAJOR;
1629 disk->first_minor = index << part_shift;
1630 disk->fops = &nbd_fops;
1631 disk->private_data = nbd;
1632 sprintf(disk->disk_name, "nbd%d", index);
1634 nbd_total_devices++;
1638 blk_mq_free_tag_set(&nbd->tag_set);
1640 idr_remove(&nbd_index_idr, index);
1649 static int find_free_cb(int id, void *ptr, void *data)
1651 struct nbd_device *nbd = ptr;
1652 struct nbd_device **found = data;
1654 if (!refcount_read(&nbd->config_refs)) {
1661 /* Netlink interface. */
1662 static const struct nla_policy nbd_attr_policy[NBD_ATTR_MAX + 1] = {
1663 [NBD_ATTR_INDEX] = { .type = NLA_U32 },
1664 [NBD_ATTR_SIZE_BYTES] = { .type = NLA_U64 },
1665 [NBD_ATTR_BLOCK_SIZE_BYTES] = { .type = NLA_U64 },
1666 [NBD_ATTR_TIMEOUT] = { .type = NLA_U64 },
1667 [NBD_ATTR_SERVER_FLAGS] = { .type = NLA_U64 },
1668 [NBD_ATTR_CLIENT_FLAGS] = { .type = NLA_U64 },
1669 [NBD_ATTR_SOCKETS] = { .type = NLA_NESTED},
1670 [NBD_ATTR_DEAD_CONN_TIMEOUT] = { .type = NLA_U64 },
1671 [NBD_ATTR_DEVICE_LIST] = { .type = NLA_NESTED},
1674 static const struct nla_policy nbd_sock_policy[NBD_SOCK_MAX + 1] = {
1675 [NBD_SOCK_FD] = { .type = NLA_U32 },
1678 /* We don't use this right now since we don't parse the incoming list, but we
1679 * still want it here so userspace knows what to expect.
1681 static const struct nla_policy __attribute__((unused))
1682 nbd_device_policy[NBD_DEVICE_ATTR_MAX + 1] = {
1683 [NBD_DEVICE_INDEX] = { .type = NLA_U32 },
1684 [NBD_DEVICE_CONNECTED] = { .type = NLA_U8 },
1687 static int nbd_genl_size_set(struct genl_info *info, struct nbd_device *nbd)
1689 struct nbd_config *config = nbd->config;
1690 u64 bsize = config->blksize;
1691 u64 bytes = config->bytesize;
1693 if (info->attrs[NBD_ATTR_SIZE_BYTES])
1694 bytes = nla_get_u64(info->attrs[NBD_ATTR_SIZE_BYTES]);
1696 if (info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]) {
1697 bsize = nla_get_u64(info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]);
1699 bsize = NBD_DEF_BLKSIZE;
1700 if (!nbd_is_valid_blksize(bsize)) {
1701 printk(KERN_ERR "Invalid block size %llu\n", bsize);
1706 if (bytes != config->bytesize || bsize != config->blksize)
1707 nbd_size_set(nbd, bsize, div64_u64(bytes, bsize));
1711 static int nbd_genl_connect(struct sk_buff *skb, struct genl_info *info)
1713 struct nbd_device *nbd = NULL;
1714 struct nbd_config *config;
1717 bool put_dev = false;
1719 if (!netlink_capable(skb, CAP_SYS_ADMIN))
1722 if (info->attrs[NBD_ATTR_INDEX])
1723 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1724 if (!info->attrs[NBD_ATTR_SOCKETS]) {
1725 printk(KERN_ERR "nbd: must specify at least one socket\n");
1728 if (!info->attrs[NBD_ATTR_SIZE_BYTES]) {
1729 printk(KERN_ERR "nbd: must specify a size in bytes for the device\n");
1733 mutex_lock(&nbd_index_mutex);
1735 ret = idr_for_each(&nbd_index_idr, &find_free_cb, &nbd);
1738 new_index = nbd_dev_add(-1);
1739 if (new_index < 0) {
1740 mutex_unlock(&nbd_index_mutex);
1741 printk(KERN_ERR "nbd: failed to add new device\n");
1744 nbd = idr_find(&nbd_index_idr, new_index);
1747 nbd = idr_find(&nbd_index_idr, index);
1749 ret = nbd_dev_add(index);
1751 mutex_unlock(&nbd_index_mutex);
1752 printk(KERN_ERR "nbd: failed to add new device\n");
1755 nbd = idr_find(&nbd_index_idr, index);
1759 printk(KERN_ERR "nbd: couldn't find device at index %d\n",
1761 mutex_unlock(&nbd_index_mutex);
1764 if (!refcount_inc_not_zero(&nbd->refs)) {
1765 mutex_unlock(&nbd_index_mutex);
1768 printk(KERN_ERR "nbd: device at index %d is going down\n",
1772 mutex_unlock(&nbd_index_mutex);
1774 mutex_lock(&nbd->config_lock);
1775 if (refcount_read(&nbd->config_refs)) {
1776 mutex_unlock(&nbd->config_lock);
1780 printk(KERN_ERR "nbd: nbd%d already in use\n", index);
1783 if (WARN_ON(nbd->config)) {
1784 mutex_unlock(&nbd->config_lock);
1788 config = nbd->config = nbd_alloc_config();
1790 mutex_unlock(&nbd->config_lock);
1792 printk(KERN_ERR "nbd: couldn't allocate config\n");
1795 refcount_set(&nbd->config_refs, 1);
1796 set_bit(NBD_BOUND, &config->runtime_flags);
1798 ret = nbd_genl_size_set(info, nbd);
1802 if (info->attrs[NBD_ATTR_TIMEOUT]) {
1803 u64 timeout = nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]);
1804 nbd->tag_set.timeout = timeout * HZ;
1805 blk_queue_rq_timeout(nbd->disk->queue, timeout * HZ);
1807 if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
1808 config->dead_conn_timeout =
1809 nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
1810 config->dead_conn_timeout *= HZ;
1812 if (info->attrs[NBD_ATTR_SERVER_FLAGS])
1814 nla_get_u64(info->attrs[NBD_ATTR_SERVER_FLAGS]);
1815 if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
1816 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
1817 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
1818 set_bit(NBD_DESTROY_ON_DISCONNECT,
1819 &config->runtime_flags);
1822 if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
1823 set_bit(NBD_DISCONNECT_ON_CLOSE,
1824 &config->runtime_flags);
1828 if (info->attrs[NBD_ATTR_SOCKETS]) {
1829 struct nlattr *attr;
1832 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
1834 struct nlattr *socks[NBD_SOCK_MAX+1];
1836 if (nla_type(attr) != NBD_SOCK_ITEM) {
1837 printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
1841 ret = nla_parse_nested_deprecated(socks, NBD_SOCK_MAX,
1846 printk(KERN_ERR "nbd: error processing sock list\n");
1850 if (!socks[NBD_SOCK_FD])
1852 fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
1853 ret = nbd_add_socket(nbd, fd, true);
1858 ret = nbd_start_device(nbd);
1860 mutex_unlock(&nbd->config_lock);
1862 set_bit(NBD_HAS_CONFIG_REF, &config->runtime_flags);
1863 refcount_inc(&nbd->config_refs);
1864 nbd_connect_reply(info, nbd->index);
1866 nbd_config_put(nbd);
1872 static void nbd_disconnect_and_put(struct nbd_device *nbd)
1874 mutex_lock(&nbd->config_lock);
1875 nbd_disconnect(nbd);
1876 nbd_clear_sock(nbd);
1877 mutex_unlock(&nbd->config_lock);
1878 if (test_and_clear_bit(NBD_HAS_CONFIG_REF,
1879 &nbd->config->runtime_flags))
1880 nbd_config_put(nbd);
1883 static int nbd_genl_disconnect(struct sk_buff *skb, struct genl_info *info)
1885 struct nbd_device *nbd;
1888 if (!netlink_capable(skb, CAP_SYS_ADMIN))
1891 if (!info->attrs[NBD_ATTR_INDEX]) {
1892 printk(KERN_ERR "nbd: must specify an index to disconnect\n");
1895 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1896 mutex_lock(&nbd_index_mutex);
1897 nbd = idr_find(&nbd_index_idr, index);
1899 mutex_unlock(&nbd_index_mutex);
1900 printk(KERN_ERR "nbd: couldn't find device at index %d\n",
1904 if (!refcount_inc_not_zero(&nbd->refs)) {
1905 mutex_unlock(&nbd_index_mutex);
1906 printk(KERN_ERR "nbd: device at index %d is going down\n",
1910 mutex_unlock(&nbd_index_mutex);
1911 if (!refcount_inc_not_zero(&nbd->config_refs)) {
1915 nbd_disconnect_and_put(nbd);
1916 nbd_config_put(nbd);
1921 static int nbd_genl_reconfigure(struct sk_buff *skb, struct genl_info *info)
1923 struct nbd_device *nbd = NULL;
1924 struct nbd_config *config;
1927 bool put_dev = false;
1929 if (!netlink_capable(skb, CAP_SYS_ADMIN))
1932 if (!info->attrs[NBD_ATTR_INDEX]) {
1933 printk(KERN_ERR "nbd: must specify a device to reconfigure\n");
1936 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1937 mutex_lock(&nbd_index_mutex);
1938 nbd = idr_find(&nbd_index_idr, index);
1940 mutex_unlock(&nbd_index_mutex);
1941 printk(KERN_ERR "nbd: couldn't find a device at index %d\n",
1945 if (!refcount_inc_not_zero(&nbd->refs)) {
1946 mutex_unlock(&nbd_index_mutex);
1947 printk(KERN_ERR "nbd: device at index %d is going down\n",
1951 mutex_unlock(&nbd_index_mutex);
1953 if (!refcount_inc_not_zero(&nbd->config_refs)) {
1954 dev_err(nbd_to_dev(nbd),
1955 "not configured, cannot reconfigure\n");
1960 mutex_lock(&nbd->config_lock);
1961 config = nbd->config;
1962 if (!test_bit(NBD_BOUND, &config->runtime_flags) ||
1964 dev_err(nbd_to_dev(nbd),
1965 "not configured, cannot reconfigure\n");
1970 ret = nbd_genl_size_set(info, nbd);
1974 if (info->attrs[NBD_ATTR_TIMEOUT]) {
1975 u64 timeout = nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]);
1976 nbd->tag_set.timeout = timeout * HZ;
1977 blk_queue_rq_timeout(nbd->disk->queue, timeout * HZ);
1979 if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
1980 config->dead_conn_timeout =
1981 nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
1982 config->dead_conn_timeout *= HZ;
1984 if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
1985 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
1986 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
1987 if (!test_and_set_bit(NBD_DESTROY_ON_DISCONNECT,
1988 &config->runtime_flags))
1991 if (test_and_clear_bit(NBD_DESTROY_ON_DISCONNECT,
1992 &config->runtime_flags))
1993 refcount_inc(&nbd->refs);
1996 if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
1997 set_bit(NBD_DISCONNECT_ON_CLOSE,
1998 &config->runtime_flags);
2000 clear_bit(NBD_DISCONNECT_ON_CLOSE,
2001 &config->runtime_flags);
2005 if (info->attrs[NBD_ATTR_SOCKETS]) {
2006 struct nlattr *attr;
2009 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
2011 struct nlattr *socks[NBD_SOCK_MAX+1];
2013 if (nla_type(attr) != NBD_SOCK_ITEM) {
2014 printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
2018 ret = nla_parse_nested_deprecated(socks, NBD_SOCK_MAX,
2023 printk(KERN_ERR "nbd: error processing sock list\n");
2027 if (!socks[NBD_SOCK_FD])
2029 fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
2030 ret = nbd_reconnect_socket(nbd, fd);
2036 dev_info(nbd_to_dev(nbd), "reconnected socket\n");
2040 mutex_unlock(&nbd->config_lock);
2041 nbd_config_put(nbd);
2048 static const struct genl_ops nbd_connect_genl_ops[] = {
2050 .cmd = NBD_CMD_CONNECT,
2051 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2052 .doit = nbd_genl_connect,
2055 .cmd = NBD_CMD_DISCONNECT,
2056 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2057 .doit = nbd_genl_disconnect,
2060 .cmd = NBD_CMD_RECONFIGURE,
2061 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2062 .doit = nbd_genl_reconfigure,
2065 .cmd = NBD_CMD_STATUS,
2066 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2067 .doit = nbd_genl_status,
2071 static const struct genl_multicast_group nbd_mcast_grps[] = {
2072 { .name = NBD_GENL_MCAST_GROUP_NAME, },
2075 static struct genl_family nbd_genl_family __ro_after_init = {
2077 .name = NBD_GENL_FAMILY_NAME,
2078 .version = NBD_GENL_VERSION,
2079 .module = THIS_MODULE,
2080 .ops = nbd_connect_genl_ops,
2081 .n_ops = ARRAY_SIZE(nbd_connect_genl_ops),
2082 .maxattr = NBD_ATTR_MAX,
2083 .policy = nbd_attr_policy,
2084 .mcgrps = nbd_mcast_grps,
2085 .n_mcgrps = ARRAY_SIZE(nbd_mcast_grps),
2088 static int populate_nbd_status(struct nbd_device *nbd, struct sk_buff *reply)
2090 struct nlattr *dev_opt;
2094 /* This is a little racey, but for status it's ok. The
2095 * reason we don't take a ref here is because we can't
2096 * take a ref in the index == -1 case as we would need
2097 * to put under the nbd_index_mutex, which could
2098 * deadlock if we are configured to remove ourselves
2099 * once we're disconnected.
2101 if (refcount_read(&nbd->config_refs))
2103 dev_opt = nla_nest_start_noflag(reply, NBD_DEVICE_ITEM);
2106 ret = nla_put_u32(reply, NBD_DEVICE_INDEX, nbd->index);
2109 ret = nla_put_u8(reply, NBD_DEVICE_CONNECTED,
2113 nla_nest_end(reply, dev_opt);
2117 static int status_cb(int id, void *ptr, void *data)
2119 struct nbd_device *nbd = ptr;
2120 return populate_nbd_status(nbd, (struct sk_buff *)data);
2123 static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info)
2125 struct nlattr *dev_list;
2126 struct sk_buff *reply;
2132 if (info->attrs[NBD_ATTR_INDEX])
2133 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2135 mutex_lock(&nbd_index_mutex);
2137 msg_size = nla_total_size(nla_attr_size(sizeof(u32)) +
2138 nla_attr_size(sizeof(u8)));
2139 msg_size *= (index == -1) ? nbd_total_devices : 1;
2141 reply = genlmsg_new(msg_size, GFP_KERNEL);
2144 reply_head = genlmsg_put_reply(reply, info, &nbd_genl_family, 0,
2151 dev_list = nla_nest_start_noflag(reply, NBD_ATTR_DEVICE_LIST);
2153 ret = idr_for_each(&nbd_index_idr, &status_cb, reply);
2159 struct nbd_device *nbd;
2160 nbd = idr_find(&nbd_index_idr, index);
2162 ret = populate_nbd_status(nbd, reply);
2169 nla_nest_end(reply, dev_list);
2170 genlmsg_end(reply, reply_head);
2171 ret = genlmsg_reply(reply, info);
2173 mutex_unlock(&nbd_index_mutex);
2177 static void nbd_connect_reply(struct genl_info *info, int index)
2179 struct sk_buff *skb;
2183 skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2186 msg_head = genlmsg_put_reply(skb, info, &nbd_genl_family, 0,
2192 ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2197 genlmsg_end(skb, msg_head);
2198 genlmsg_reply(skb, info);
2201 static void nbd_mcast_index(int index)
2203 struct sk_buff *skb;
2207 skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2210 msg_head = genlmsg_put(skb, 0, 0, &nbd_genl_family, 0,
2216 ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2221 genlmsg_end(skb, msg_head);
2222 genlmsg_multicast(&nbd_genl_family, skb, 0, 0, GFP_KERNEL);
2225 static void nbd_dead_link_work(struct work_struct *work)
2227 struct link_dead_args *args = container_of(work, struct link_dead_args,
2229 nbd_mcast_index(args->index);
2233 static int __init nbd_init(void)
2237 BUILD_BUG_ON(sizeof(struct nbd_request) != 28);
2240 printk(KERN_ERR "nbd: max_part must be >= 0\n");
2246 part_shift = fls(max_part);
2249 * Adjust max_part according to part_shift as it is exported
2250 * to user space so that user can know the max number of
2251 * partition kernel should be able to manage.
2253 * Note that -1 is required because partition 0 is reserved
2254 * for the whole disk.
2256 max_part = (1UL << part_shift) - 1;
2259 if ((1UL << part_shift) > DISK_MAX_PARTS)
2262 if (nbds_max > 1UL << (MINORBITS - part_shift))
2264 recv_workqueue = alloc_workqueue("knbd-recv",
2265 WQ_MEM_RECLAIM | WQ_HIGHPRI |
2267 if (!recv_workqueue)
2270 if (register_blkdev(NBD_MAJOR, "nbd")) {
2271 destroy_workqueue(recv_workqueue);
2275 if (genl_register_family(&nbd_genl_family)) {
2276 unregister_blkdev(NBD_MAJOR, "nbd");
2277 destroy_workqueue(recv_workqueue);
2282 mutex_lock(&nbd_index_mutex);
2283 for (i = 0; i < nbds_max; i++)
2285 mutex_unlock(&nbd_index_mutex);
2289 static int nbd_exit_cb(int id, void *ptr, void *data)
2291 struct list_head *list = (struct list_head *)data;
2292 struct nbd_device *nbd = ptr;
2294 list_add_tail(&nbd->list, list);
2298 static void __exit nbd_cleanup(void)
2300 struct nbd_device *nbd;
2301 LIST_HEAD(del_list);
2305 mutex_lock(&nbd_index_mutex);
2306 idr_for_each(&nbd_index_idr, &nbd_exit_cb, &del_list);
2307 mutex_unlock(&nbd_index_mutex);
2309 while (!list_empty(&del_list)) {
2310 nbd = list_first_entry(&del_list, struct nbd_device, list);
2311 list_del_init(&nbd->list);
2312 if (refcount_read(&nbd->refs) != 1)
2313 printk(KERN_ERR "nbd: possibly leaking a device\n");
2317 idr_destroy(&nbd_index_idr);
2318 genl_unregister_family(&nbd_genl_family);
2319 destroy_workqueue(recv_workqueue);
2320 unregister_blkdev(NBD_MAJOR, "nbd");
2323 module_init(nbd_init);
2324 module_exit(nbd_cleanup);
2326 MODULE_DESCRIPTION("Network Block Device");
2327 MODULE_LICENSE("GPL");
2329 module_param(nbds_max, int, 0444);
2330 MODULE_PARM_DESC(nbds_max, "number of network block devices to initialize (default: 16)");
2331 module_param(max_part, int, 0444);
2332 MODULE_PARM_DESC(max_part, "number of partitions per device (default: 16)");