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
82 unsigned long runtime_flags;
83 u64 dead_conn_timeout;
85 struct nbd_sock **socks;
87 atomic_t live_connections;
88 wait_queue_head_t conn_wait;
90 atomic_t recv_threads;
91 wait_queue_head_t recv_wq;
94 #if IS_ENABLED(CONFIG_DEBUG_FS)
95 struct dentry *dbg_dir;
100 struct blk_mq_tag_set tag_set;
103 refcount_t config_refs;
105 struct nbd_config *config;
106 struct mutex config_lock;
107 struct gendisk *disk;
109 struct list_head list;
110 struct task_struct *task_recv;
111 struct task_struct *task_setup;
115 struct nbd_device *nbd;
118 struct completion send_complete;
122 #if IS_ENABLED(CONFIG_DEBUG_FS)
123 static struct dentry *nbd_dbg_dir;
126 #define nbd_name(nbd) ((nbd)->disk->disk_name)
128 #define NBD_MAGIC 0x68797548
130 static unsigned int nbds_max = 16;
131 static int max_part = 16;
132 static struct workqueue_struct *recv_workqueue;
133 static int part_shift;
135 static int nbd_dev_dbg_init(struct nbd_device *nbd);
136 static void nbd_dev_dbg_close(struct nbd_device *nbd);
137 static void nbd_config_put(struct nbd_device *nbd);
138 static void nbd_connect_reply(struct genl_info *info, int index);
139 static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info);
140 static void nbd_dead_link_work(struct work_struct *work);
142 static inline struct device *nbd_to_dev(struct nbd_device *nbd)
144 return disk_to_dev(nbd->disk);
147 static const char *nbdcmd_to_ascii(int cmd)
150 case NBD_CMD_READ: return "read";
151 case NBD_CMD_WRITE: return "write";
152 case NBD_CMD_DISC: return "disconnect";
153 case NBD_CMD_FLUSH: return "flush";
154 case NBD_CMD_TRIM: return "trim/discard";
159 static ssize_t pid_show(struct device *dev,
160 struct device_attribute *attr, char *buf)
162 struct gendisk *disk = dev_to_disk(dev);
163 struct nbd_device *nbd = (struct nbd_device *)disk->private_data;
165 return sprintf(buf, "%d\n", task_pid_nr(nbd->task_recv));
168 static const struct device_attribute pid_attr = {
169 .attr = { .name = "pid", .mode = 0444},
173 static void nbd_dev_remove(struct nbd_device *nbd)
175 struct gendisk *disk = nbd->disk;
176 struct request_queue *q;
181 blk_cleanup_queue(q);
182 blk_mq_free_tag_set(&nbd->tag_set);
183 disk->private_data = NULL;
189 static void nbd_put(struct nbd_device *nbd)
191 if (refcount_dec_and_mutex_lock(&nbd->refs,
193 idr_remove(&nbd_index_idr, nbd->index);
194 mutex_unlock(&nbd_index_mutex);
199 static int nbd_disconnected(struct nbd_config *config)
201 return test_bit(NBD_DISCONNECTED, &config->runtime_flags) ||
202 test_bit(NBD_DISCONNECT_REQUESTED, &config->runtime_flags);
205 static void nbd_mark_nsock_dead(struct nbd_device *nbd, struct nbd_sock *nsock,
208 if (!nsock->dead && notify && !nbd_disconnected(nbd->config)) {
209 struct link_dead_args *args;
210 args = kmalloc(sizeof(struct link_dead_args), GFP_NOIO);
212 INIT_WORK(&args->work, nbd_dead_link_work);
213 args->index = nbd->index;
214 queue_work(system_wq, &args->work);
218 kernel_sock_shutdown(nsock->sock, SHUT_RDWR);
219 if (atomic_dec_return(&nbd->config->live_connections) == 0) {
220 if (test_and_clear_bit(NBD_DISCONNECT_REQUESTED,
221 &nbd->config->runtime_flags)) {
222 set_bit(NBD_DISCONNECTED,
223 &nbd->config->runtime_flags);
224 dev_info(nbd_to_dev(nbd),
225 "Disconnected due to user request.\n");
230 nsock->pending = NULL;
234 static void nbd_size_clear(struct nbd_device *nbd)
236 if (nbd->config->bytesize) {
237 set_capacity(nbd->disk, 0);
238 kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
242 static void nbd_size_update(struct nbd_device *nbd)
244 struct nbd_config *config = nbd->config;
245 struct block_device *bdev = bdget_disk(nbd->disk, 0);
247 if (config->flags & NBD_FLAG_SEND_TRIM) {
248 nbd->disk->queue->limits.discard_granularity = config->blksize;
249 blk_queue_max_discard_sectors(nbd->disk->queue, UINT_MAX);
251 blk_queue_logical_block_size(nbd->disk->queue, config->blksize);
252 blk_queue_physical_block_size(nbd->disk->queue, config->blksize);
253 set_capacity(nbd->disk, config->bytesize >> 9);
256 bd_set_size(bdev, config->bytesize);
258 bdev->bd_invalidated = 1;
261 kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
264 static void nbd_size_set(struct nbd_device *nbd, loff_t blocksize,
267 struct nbd_config *config = nbd->config;
268 config->blksize = blocksize;
269 config->bytesize = blocksize * nr_blocks;
270 if (nbd->task_recv != NULL)
271 nbd_size_update(nbd);
274 static void nbd_complete_rq(struct request *req)
276 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
278 dev_dbg(nbd_to_dev(cmd->nbd), "request %p: %s\n", cmd,
279 cmd->status ? "failed" : "done");
281 blk_mq_end_request(req, cmd->status);
285 * Forcibly shutdown the socket causing all listeners to error
287 static void sock_shutdown(struct nbd_device *nbd)
289 struct nbd_config *config = nbd->config;
292 if (config->num_connections == 0)
294 if (test_and_set_bit(NBD_DISCONNECTED, &config->runtime_flags))
297 for (i = 0; i < config->num_connections; i++) {
298 struct nbd_sock *nsock = config->socks[i];
299 mutex_lock(&nsock->tx_lock);
300 nbd_mark_nsock_dead(nbd, nsock, 0);
301 mutex_unlock(&nsock->tx_lock);
303 dev_warn(disk_to_dev(nbd->disk), "shutting down sockets\n");
306 static enum blk_eh_timer_return nbd_xmit_timeout(struct request *req,
309 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
310 struct nbd_device *nbd = cmd->nbd;
311 struct nbd_config *config;
313 if (!refcount_inc_not_zero(&nbd->config_refs)) {
314 cmd->status = BLK_STS_TIMEOUT;
317 config = nbd->config;
319 if (config->num_connections > 1) {
320 dev_err_ratelimited(nbd_to_dev(nbd),
321 "Connection timed out, retrying (%d/%d alive)\n",
322 atomic_read(&config->live_connections),
323 config->num_connections);
325 * Hooray we have more connections, requeue this IO, the submit
326 * path will put it on a real connection.
328 if (config->socks && config->num_connections > 1) {
329 if (cmd->index < config->num_connections) {
330 struct nbd_sock *nsock =
331 config->socks[cmd->index];
332 mutex_lock(&nsock->tx_lock);
333 /* We can have multiple outstanding requests, so
334 * we don't want to mark the nsock dead if we've
335 * already reconnected with a new socket, so
336 * only mark it dead if its the same socket we
339 if (cmd->cookie == nsock->cookie)
340 nbd_mark_nsock_dead(nbd, nsock, 1);
341 mutex_unlock(&nsock->tx_lock);
343 blk_mq_requeue_request(req, true);
348 dev_err_ratelimited(nbd_to_dev(nbd),
349 "Connection timed out\n");
351 set_bit(NBD_TIMEDOUT, &config->runtime_flags);
352 cmd->status = BLK_STS_IOERR;
356 blk_mq_complete_request(req);
361 * Send or receive packet.
363 static int sock_xmit(struct nbd_device *nbd, int index, int send,
364 struct iov_iter *iter, int msg_flags, int *sent)
366 struct nbd_config *config = nbd->config;
367 struct socket *sock = config->socks[index]->sock;
370 unsigned int noreclaim_flag;
372 if (unlikely(!sock)) {
373 dev_err_ratelimited(disk_to_dev(nbd->disk),
374 "Attempted %s on closed socket in sock_xmit\n",
375 (send ? "send" : "recv"));
379 msg.msg_iter = *iter;
381 noreclaim_flag = memalloc_noreclaim_save();
383 sock->sk->sk_allocation = GFP_NOIO | __GFP_MEMALLOC;
386 msg.msg_control = NULL;
387 msg.msg_controllen = 0;
388 msg.msg_flags = msg_flags | MSG_NOSIGNAL;
391 result = sock_sendmsg(sock, &msg);
393 result = sock_recvmsg(sock, &msg, msg.msg_flags);
397 result = -EPIPE; /* short read */
402 } while (msg_data_left(&msg));
404 memalloc_noreclaim_restore(noreclaim_flag);
410 * Different settings for sk->sk_sndtimeo can result in different return values
411 * if there is a signal pending when we enter sendmsg, because reasons?
413 static inline int was_interrupted(int result)
415 return result == -ERESTARTSYS || result == -EINTR;
418 /* always call with the tx_lock held */
419 static int nbd_send_cmd(struct nbd_device *nbd, struct nbd_cmd *cmd, int index)
421 struct request *req = blk_mq_rq_from_pdu(cmd);
422 struct nbd_config *config = nbd->config;
423 struct nbd_sock *nsock = config->socks[index];
425 struct nbd_request request = {.magic = htonl(NBD_REQUEST_MAGIC)};
426 struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
427 struct iov_iter from;
428 unsigned long size = blk_rq_bytes(req);
431 u32 nbd_cmd_flags = 0;
432 u32 tag = blk_mq_unique_tag(req);
433 int sent = nsock->sent, skip = 0;
435 iov_iter_kvec(&from, WRITE | ITER_KVEC, &iov, 1, sizeof(request));
437 switch (req_op(req)) {
442 type = NBD_CMD_FLUSH;
445 type = NBD_CMD_WRITE;
454 if (rq_data_dir(req) == WRITE &&
455 (config->flags & NBD_FLAG_READ_ONLY)) {
456 dev_err_ratelimited(disk_to_dev(nbd->disk),
457 "Write on read-only\n");
461 if (req->cmd_flags & REQ_FUA)
462 nbd_cmd_flags |= NBD_CMD_FLAG_FUA;
464 /* We did a partial send previously, and we at least sent the whole
465 * request struct, so just go and send the rest of the pages in the
469 if (sent >= sizeof(request)) {
470 skip = sent - sizeof(request);
473 iov_iter_advance(&from, sent);
476 cmd->cookie = nsock->cookie;
477 request.type = htonl(type | nbd_cmd_flags);
478 if (type != NBD_CMD_FLUSH) {
479 request.from = cpu_to_be64((u64)blk_rq_pos(req) << 9);
480 request.len = htonl(size);
482 memcpy(request.handle, &tag, sizeof(tag));
484 dev_dbg(nbd_to_dev(nbd), "request %p: sending control (%s@%llu,%uB)\n",
485 cmd, nbdcmd_to_ascii(type),
486 (unsigned long long)blk_rq_pos(req) << 9, blk_rq_bytes(req));
487 result = sock_xmit(nbd, index, 1, &from,
488 (type == NBD_CMD_WRITE) ? MSG_MORE : 0, &sent);
490 if (was_interrupted(result)) {
491 /* If we havne't sent anything we can just return BUSY,
492 * however if we have sent something we need to make
493 * sure we only allow this req to be sent until we are
497 nsock->pending = req;
500 return BLK_STS_RESOURCE;
502 dev_err_ratelimited(disk_to_dev(nbd->disk),
503 "Send control failed (result %d)\n", result);
507 if (type != NBD_CMD_WRITE)
512 struct bio *next = bio->bi_next;
513 struct bvec_iter iter;
516 bio_for_each_segment(bvec, bio, iter) {
517 bool is_last = !next && bio_iter_last(bvec, iter);
518 int flags = is_last ? 0 : MSG_MORE;
520 dev_dbg(nbd_to_dev(nbd), "request %p: sending %d bytes data\n",
522 iov_iter_bvec(&from, ITER_BVEC | WRITE,
523 &bvec, 1, bvec.bv_len);
525 if (skip >= iov_iter_count(&from)) {
526 skip -= iov_iter_count(&from);
529 iov_iter_advance(&from, skip);
532 result = sock_xmit(nbd, index, 1, &from, flags, &sent);
534 if (was_interrupted(result)) {
535 /* We've already sent the header, we
536 * have no choice but to set pending and
539 nsock->pending = req;
541 return BLK_STS_RESOURCE;
543 dev_err(disk_to_dev(nbd->disk),
544 "Send data failed (result %d)\n",
549 * The completion might already have come in,
550 * so break for the last one instead of letting
551 * the iterator do it. This prevents use-after-free
560 nsock->pending = NULL;
565 /* NULL returned = something went wrong, inform userspace */
566 static struct nbd_cmd *nbd_read_stat(struct nbd_device *nbd, int index)
568 struct nbd_config *config = nbd->config;
570 struct nbd_reply reply;
572 struct request *req = NULL;
575 struct kvec iov = {.iov_base = &reply, .iov_len = sizeof(reply)};
579 iov_iter_kvec(&to, READ | ITER_KVEC, &iov, 1, sizeof(reply));
580 result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
582 if (!nbd_disconnected(config))
583 dev_err(disk_to_dev(nbd->disk),
584 "Receive control failed (result %d)\n", result);
585 return ERR_PTR(result);
588 if (ntohl(reply.magic) != NBD_REPLY_MAGIC) {
589 dev_err(disk_to_dev(nbd->disk), "Wrong magic (0x%lx)\n",
590 (unsigned long)ntohl(reply.magic));
591 return ERR_PTR(-EPROTO);
594 memcpy(&tag, reply.handle, sizeof(u32));
596 hwq = blk_mq_unique_tag_to_hwq(tag);
597 if (hwq < nbd->tag_set.nr_hw_queues)
598 req = blk_mq_tag_to_rq(nbd->tag_set.tags[hwq],
599 blk_mq_unique_tag_to_tag(tag));
600 if (!req || !blk_mq_request_started(req)) {
601 dev_err(disk_to_dev(nbd->disk), "Unexpected reply (%d) %p\n",
603 return ERR_PTR(-ENOENT);
605 cmd = blk_mq_rq_to_pdu(req);
606 if (ntohl(reply.error)) {
607 dev_err(disk_to_dev(nbd->disk), "Other side returned error (%d)\n",
609 cmd->status = BLK_STS_IOERR;
613 dev_dbg(nbd_to_dev(nbd), "request %p: got reply\n", cmd);
614 if (rq_data_dir(req) != WRITE) {
615 struct req_iterator iter;
618 rq_for_each_segment(bvec, req, iter) {
619 iov_iter_bvec(&to, ITER_BVEC | READ,
620 &bvec, 1, bvec.bv_len);
621 result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
623 dev_err(disk_to_dev(nbd->disk), "Receive data failed (result %d)\n",
626 * If we've disconnected or we only have 1
627 * connection then we need to make sure we
628 * complete this request, otherwise error out
629 * and let the timeout stuff handle resubmitting
630 * this request onto another connection.
632 if (nbd_disconnected(config) ||
633 config->num_connections <= 1) {
634 cmd->status = BLK_STS_IOERR;
637 return ERR_PTR(-EIO);
639 dev_dbg(nbd_to_dev(nbd), "request %p: got %d bytes data\n",
643 /* See the comment in nbd_queue_rq. */
644 wait_for_completion(&cmd->send_complete);
649 static void recv_work(struct work_struct *work)
651 struct recv_thread_args *args = container_of(work,
652 struct recv_thread_args,
654 struct nbd_device *nbd = args->nbd;
655 struct nbd_config *config = nbd->config;
659 cmd = nbd_read_stat(nbd, args->index);
661 struct nbd_sock *nsock = config->socks[args->index];
663 mutex_lock(&nsock->tx_lock);
664 nbd_mark_nsock_dead(nbd, nsock, 1);
665 mutex_unlock(&nsock->tx_lock);
669 blk_mq_complete_request(blk_mq_rq_from_pdu(cmd));
671 atomic_dec(&config->recv_threads);
672 wake_up(&config->recv_wq);
677 static void nbd_clear_req(struct request *req, void *data, bool reserved)
679 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
681 cmd->status = BLK_STS_IOERR;
682 blk_mq_complete_request(req);
685 static void nbd_clear_que(struct nbd_device *nbd)
687 blk_mq_quiesce_queue(nbd->disk->queue);
688 blk_mq_tagset_busy_iter(&nbd->tag_set, nbd_clear_req, NULL);
689 blk_mq_unquiesce_queue(nbd->disk->queue);
690 dev_dbg(disk_to_dev(nbd->disk), "queue cleared\n");
693 static int find_fallback(struct nbd_device *nbd, int index)
695 struct nbd_config *config = nbd->config;
697 struct nbd_sock *nsock = config->socks[index];
698 int fallback = nsock->fallback_index;
700 if (test_bit(NBD_DISCONNECTED, &config->runtime_flags))
703 if (config->num_connections <= 1) {
704 dev_err_ratelimited(disk_to_dev(nbd->disk),
705 "Attempted send on invalid socket\n");
709 if (fallback >= 0 && fallback < config->num_connections &&
710 !config->socks[fallback]->dead)
713 if (nsock->fallback_index < 0 ||
714 nsock->fallback_index >= config->num_connections ||
715 config->socks[nsock->fallback_index]->dead) {
717 for (i = 0; i < config->num_connections; i++) {
720 if (!config->socks[i]->dead) {
725 nsock->fallback_index = new_index;
727 dev_err_ratelimited(disk_to_dev(nbd->disk),
728 "Dead connection, failed to find a fallback\n");
732 new_index = nsock->fallback_index;
736 static int wait_for_reconnect(struct nbd_device *nbd)
738 struct nbd_config *config = nbd->config;
739 if (!config->dead_conn_timeout)
741 if (test_bit(NBD_DISCONNECTED, &config->runtime_flags))
743 return wait_event_timeout(config->conn_wait,
744 atomic_read(&config->live_connections) > 0,
745 config->dead_conn_timeout) > 0;
748 static int nbd_handle_cmd(struct nbd_cmd *cmd, int index)
750 struct request *req = blk_mq_rq_from_pdu(cmd);
751 struct nbd_device *nbd = cmd->nbd;
752 struct nbd_config *config;
753 struct nbd_sock *nsock;
756 if (!refcount_inc_not_zero(&nbd->config_refs)) {
757 dev_err_ratelimited(disk_to_dev(nbd->disk),
758 "Socks array is empty\n");
759 blk_mq_start_request(req);
762 config = nbd->config;
764 if (index >= config->num_connections) {
765 dev_err_ratelimited(disk_to_dev(nbd->disk),
766 "Attempted send on invalid socket\n");
768 blk_mq_start_request(req);
771 cmd->status = BLK_STS_OK;
773 nsock = config->socks[index];
774 mutex_lock(&nsock->tx_lock);
776 int old_index = index;
777 index = find_fallback(nbd, index);
778 mutex_unlock(&nsock->tx_lock);
780 if (wait_for_reconnect(nbd)) {
784 /* All the sockets should already be down at this point,
785 * we just want to make sure that DISCONNECTED is set so
786 * any requests that come in that were queue'ed waiting
787 * for the reconnect timer don't trigger the timer again
788 * and instead just error out.
792 blk_mq_start_request(req);
798 /* Handle the case that we have a pending request that was partially
799 * transmitted that _has_ to be serviced first. We need to call requeue
800 * here so that it gets put _after_ the request that is already on the
803 blk_mq_start_request(req);
804 if (unlikely(nsock->pending && nsock->pending != req)) {
805 blk_mq_requeue_request(req, true);
810 * Some failures are related to the link going down, so anything that
811 * returns EAGAIN can be retried on a different socket.
813 ret = nbd_send_cmd(nbd, cmd, index);
814 if (ret == -EAGAIN) {
815 dev_err_ratelimited(disk_to_dev(nbd->disk),
816 "Request send failed, requeueing\n");
817 nbd_mark_nsock_dead(nbd, nsock, 1);
818 blk_mq_requeue_request(req, true);
822 mutex_unlock(&nsock->tx_lock);
827 static blk_status_t nbd_queue_rq(struct blk_mq_hw_ctx *hctx,
828 const struct blk_mq_queue_data *bd)
830 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(bd->rq);
834 * Since we look at the bio's to send the request over the network we
835 * need to make sure the completion work doesn't mark this request done
836 * before we are done doing our send. This keeps us from dereferencing
837 * freed data if we have particularly fast completions (ie we get the
838 * completion before we exit sock_xmit on the last bvec) or in the case
839 * that the server is misbehaving (or there was an error) before we're
840 * done sending everything over the wire.
842 init_completion(&cmd->send_complete);
844 /* We can be called directly from the user space process, which means we
845 * could possibly have signals pending so our sendmsg will fail. In
846 * this case we need to return that we are busy, otherwise error out as
849 ret = nbd_handle_cmd(cmd, hctx->queue_num);
854 complete(&cmd->send_complete);
859 static int nbd_add_socket(struct nbd_device *nbd, unsigned long arg,
862 struct nbd_config *config = nbd->config;
864 struct nbd_sock **socks;
865 struct nbd_sock *nsock;
868 sock = sockfd_lookup(arg, &err);
872 if (!netlink && !nbd->task_setup &&
873 !test_bit(NBD_BOUND, &config->runtime_flags))
874 nbd->task_setup = current;
877 (nbd->task_setup != current ||
878 test_bit(NBD_BOUND, &config->runtime_flags))) {
879 dev_err(disk_to_dev(nbd->disk),
880 "Device being setup by another task");
885 socks = krealloc(config->socks, (config->num_connections + 1) *
886 sizeof(struct nbd_sock *), GFP_KERNEL);
891 nsock = kzalloc(sizeof(struct nbd_sock), GFP_KERNEL);
897 config->socks = socks;
899 nsock->fallback_index = -1;
901 mutex_init(&nsock->tx_lock);
903 nsock->pending = NULL;
906 socks[config->num_connections++] = nsock;
907 atomic_inc(&config->live_connections);
912 static int nbd_reconnect_socket(struct nbd_device *nbd, unsigned long arg)
914 struct nbd_config *config = nbd->config;
915 struct socket *sock, *old;
916 struct recv_thread_args *args;
920 sock = sockfd_lookup(arg, &err);
924 args = kzalloc(sizeof(*args), GFP_KERNEL);
930 for (i = 0; i < config->num_connections; i++) {
931 struct nbd_sock *nsock = config->socks[i];
936 mutex_lock(&nsock->tx_lock);
938 mutex_unlock(&nsock->tx_lock);
941 sk_set_memalloc(sock->sk);
942 if (nbd->tag_set.timeout)
943 sock->sk->sk_sndtimeo = nbd->tag_set.timeout;
944 atomic_inc(&config->recv_threads);
945 refcount_inc(&nbd->config_refs);
947 nsock->fallback_index = -1;
950 INIT_WORK(&args->work, recv_work);
954 mutex_unlock(&nsock->tx_lock);
957 clear_bit(NBD_DISCONNECTED, &config->runtime_flags);
959 /* We take the tx_mutex in an error path in the recv_work, so we
960 * need to queue_work outside of the tx_mutex.
962 queue_work(recv_workqueue, &args->work);
964 atomic_inc(&config->live_connections);
965 wake_up(&config->conn_wait);
973 static void nbd_bdev_reset(struct block_device *bdev)
975 if (bdev->bd_openers > 1)
977 bd_set_size(bdev, 0);
980 static void nbd_parse_flags(struct nbd_device *nbd)
982 struct nbd_config *config = nbd->config;
983 if (config->flags & NBD_FLAG_READ_ONLY)
984 set_disk_ro(nbd->disk, true);
986 set_disk_ro(nbd->disk, false);
987 if (config->flags & NBD_FLAG_SEND_TRIM)
988 blk_queue_flag_set(QUEUE_FLAG_DISCARD, nbd->disk->queue);
989 if (config->flags & NBD_FLAG_SEND_FLUSH) {
990 if (config->flags & NBD_FLAG_SEND_FUA)
991 blk_queue_write_cache(nbd->disk->queue, true, true);
993 blk_queue_write_cache(nbd->disk->queue, true, false);
996 blk_queue_write_cache(nbd->disk->queue, false, false);
999 static void send_disconnects(struct nbd_device *nbd)
1001 struct nbd_config *config = nbd->config;
1002 struct nbd_request request = {
1003 .magic = htonl(NBD_REQUEST_MAGIC),
1004 .type = htonl(NBD_CMD_DISC),
1006 struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
1007 struct iov_iter from;
1010 for (i = 0; i < config->num_connections; i++) {
1011 struct nbd_sock *nsock = config->socks[i];
1013 iov_iter_kvec(&from, WRITE | ITER_KVEC, &iov, 1, sizeof(request));
1014 mutex_lock(&nsock->tx_lock);
1015 ret = sock_xmit(nbd, i, 1, &from, 0, NULL);
1017 dev_err(disk_to_dev(nbd->disk),
1018 "Send disconnect failed %d\n", ret);
1019 mutex_unlock(&nsock->tx_lock);
1023 static int nbd_disconnect(struct nbd_device *nbd)
1025 struct nbd_config *config = nbd->config;
1027 dev_info(disk_to_dev(nbd->disk), "NBD_DISCONNECT\n");
1028 set_bit(NBD_DISCONNECT_REQUESTED, &config->runtime_flags);
1029 send_disconnects(nbd);
1033 static void nbd_clear_sock(struct nbd_device *nbd)
1037 nbd->task_setup = NULL;
1040 static void nbd_config_put(struct nbd_device *nbd)
1042 if (refcount_dec_and_mutex_lock(&nbd->config_refs,
1043 &nbd->config_lock)) {
1044 struct nbd_config *config = nbd->config;
1045 nbd_dev_dbg_close(nbd);
1046 nbd_size_clear(nbd);
1047 if (test_and_clear_bit(NBD_HAS_PID_FILE,
1048 &config->runtime_flags))
1049 device_remove_file(disk_to_dev(nbd->disk), &pid_attr);
1050 nbd->task_recv = NULL;
1051 nbd_clear_sock(nbd);
1052 if (config->num_connections) {
1054 for (i = 0; i < config->num_connections; i++) {
1055 sockfd_put(config->socks[i]->sock);
1056 kfree(config->socks[i]);
1058 kfree(config->socks);
1063 nbd->tag_set.timeout = 0;
1064 nbd->disk->queue->limits.discard_granularity = 0;
1065 blk_queue_max_discard_sectors(nbd->disk->queue, UINT_MAX);
1066 blk_queue_flag_clear(QUEUE_FLAG_DISCARD, nbd->disk->queue);
1068 mutex_unlock(&nbd->config_lock);
1070 module_put(THIS_MODULE);
1074 static int nbd_start_device(struct nbd_device *nbd)
1076 struct nbd_config *config = nbd->config;
1077 int num_connections = config->num_connections;
1084 if (num_connections > 1 &&
1085 !(config->flags & NBD_FLAG_CAN_MULTI_CONN)) {
1086 dev_err(disk_to_dev(nbd->disk), "server does not support multiple connections per device.\n");
1090 blk_mq_update_nr_hw_queues(&nbd->tag_set, config->num_connections);
1091 nbd->task_recv = current;
1093 nbd_parse_flags(nbd);
1095 error = device_create_file(disk_to_dev(nbd->disk), &pid_attr);
1097 dev_err(disk_to_dev(nbd->disk), "device_create_file failed!\n");
1100 set_bit(NBD_HAS_PID_FILE, &config->runtime_flags);
1102 nbd_dev_dbg_init(nbd);
1103 for (i = 0; i < num_connections; i++) {
1104 struct recv_thread_args *args;
1106 args = kzalloc(sizeof(*args), GFP_KERNEL);
1111 sk_set_memalloc(config->socks[i]->sock->sk);
1112 if (nbd->tag_set.timeout)
1113 config->socks[i]->sock->sk->sk_sndtimeo =
1114 nbd->tag_set.timeout;
1115 atomic_inc(&config->recv_threads);
1116 refcount_inc(&nbd->config_refs);
1117 INIT_WORK(&args->work, recv_work);
1120 queue_work(recv_workqueue, &args->work);
1122 nbd_size_update(nbd);
1126 static int nbd_start_device_ioctl(struct nbd_device *nbd, struct block_device *bdev)
1128 struct nbd_config *config = nbd->config;
1131 ret = nbd_start_device(nbd);
1136 bdev->bd_invalidated = 1;
1137 mutex_unlock(&nbd->config_lock);
1138 ret = wait_event_interruptible(config->recv_wq,
1139 atomic_read(&config->recv_threads) == 0);
1142 mutex_lock(&nbd->config_lock);
1143 nbd_bdev_reset(bdev);
1144 /* user requested, ignore socket errors */
1145 if (test_bit(NBD_DISCONNECT_REQUESTED, &config->runtime_flags))
1147 if (test_bit(NBD_TIMEDOUT, &config->runtime_flags))
1152 static void nbd_clear_sock_ioctl(struct nbd_device *nbd,
1153 struct block_device *bdev)
1157 nbd_bdev_reset(bdev);
1158 if (test_and_clear_bit(NBD_HAS_CONFIG_REF,
1159 &nbd->config->runtime_flags))
1160 nbd_config_put(nbd);
1163 /* Must be called with config_lock held */
1164 static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
1165 unsigned int cmd, unsigned long arg)
1167 struct nbd_config *config = nbd->config;
1170 case NBD_DISCONNECT:
1171 return nbd_disconnect(nbd);
1172 case NBD_CLEAR_SOCK:
1173 nbd_clear_sock_ioctl(nbd, bdev);
1176 return nbd_add_socket(nbd, arg, false);
1177 case NBD_SET_BLKSIZE:
1178 nbd_size_set(nbd, arg,
1179 div_s64(config->bytesize, arg));
1182 nbd_size_set(nbd, config->blksize,
1183 div_s64(arg, config->blksize));
1185 case NBD_SET_SIZE_BLOCKS:
1186 nbd_size_set(nbd, config->blksize, arg);
1188 case NBD_SET_TIMEOUT:
1190 nbd->tag_set.timeout = arg * HZ;
1191 blk_queue_rq_timeout(nbd->disk->queue, arg * HZ);
1196 config->flags = arg;
1199 return nbd_start_device_ioctl(nbd, bdev);
1202 * This is for compatibility only. The queue is always cleared
1203 * by NBD_DO_IT or NBD_CLEAR_SOCK.
1206 case NBD_PRINT_DEBUG:
1208 * For compatibility only, we no longer keep a list of
1209 * outstanding requests.
1216 static int nbd_ioctl(struct block_device *bdev, fmode_t mode,
1217 unsigned int cmd, unsigned long arg)
1219 struct nbd_device *nbd = bdev->bd_disk->private_data;
1220 struct nbd_config *config = nbd->config;
1221 int error = -EINVAL;
1223 if (!capable(CAP_SYS_ADMIN))
1226 /* The block layer will pass back some non-nbd ioctls in case we have
1227 * special handling for them, but we don't so just return an error.
1229 if (_IOC_TYPE(cmd) != 0xab)
1232 mutex_lock(&nbd->config_lock);
1234 /* Don't allow ioctl operations on a nbd device that was created with
1235 * netlink, unless it's DISCONNECT or CLEAR_SOCK, which are fine.
1237 if (!test_bit(NBD_BOUND, &config->runtime_flags) ||
1238 (cmd == NBD_DISCONNECT || cmd == NBD_CLEAR_SOCK))
1239 error = __nbd_ioctl(bdev, nbd, cmd, arg);
1241 dev_err(nbd_to_dev(nbd), "Cannot use ioctl interface on a netlink controlled device.\n");
1242 mutex_unlock(&nbd->config_lock);
1246 static struct nbd_config *nbd_alloc_config(void)
1248 struct nbd_config *config;
1250 config = kzalloc(sizeof(struct nbd_config), GFP_NOFS);
1253 atomic_set(&config->recv_threads, 0);
1254 init_waitqueue_head(&config->recv_wq);
1255 init_waitqueue_head(&config->conn_wait);
1256 config->blksize = 1024;
1257 atomic_set(&config->live_connections, 0);
1258 try_module_get(THIS_MODULE);
1262 static int nbd_open(struct block_device *bdev, fmode_t mode)
1264 struct nbd_device *nbd;
1267 mutex_lock(&nbd_index_mutex);
1268 nbd = bdev->bd_disk->private_data;
1273 if (!refcount_inc_not_zero(&nbd->refs)) {
1277 if (!refcount_inc_not_zero(&nbd->config_refs)) {
1278 struct nbd_config *config;
1280 mutex_lock(&nbd->config_lock);
1281 if (refcount_inc_not_zero(&nbd->config_refs)) {
1282 mutex_unlock(&nbd->config_lock);
1285 config = nbd->config = nbd_alloc_config();
1288 mutex_unlock(&nbd->config_lock);
1291 refcount_set(&nbd->config_refs, 1);
1292 refcount_inc(&nbd->refs);
1293 mutex_unlock(&nbd->config_lock);
1294 bdev->bd_invalidated = 1;
1295 } else if (nbd_disconnected(nbd->config)) {
1296 bdev->bd_invalidated = 1;
1299 mutex_unlock(&nbd_index_mutex);
1303 static void nbd_release(struct gendisk *disk, fmode_t mode)
1305 struct nbd_device *nbd = disk->private_data;
1306 nbd_config_put(nbd);
1310 static const struct block_device_operations nbd_fops =
1312 .owner = THIS_MODULE,
1314 .release = nbd_release,
1316 .compat_ioctl = nbd_ioctl,
1319 #if IS_ENABLED(CONFIG_DEBUG_FS)
1321 static int nbd_dbg_tasks_show(struct seq_file *s, void *unused)
1323 struct nbd_device *nbd = s->private;
1326 seq_printf(s, "recv: %d\n", task_pid_nr(nbd->task_recv));
1331 static int nbd_dbg_tasks_open(struct inode *inode, struct file *file)
1333 return single_open(file, nbd_dbg_tasks_show, inode->i_private);
1336 static const struct file_operations nbd_dbg_tasks_ops = {
1337 .open = nbd_dbg_tasks_open,
1339 .llseek = seq_lseek,
1340 .release = single_release,
1343 static int nbd_dbg_flags_show(struct seq_file *s, void *unused)
1345 struct nbd_device *nbd = s->private;
1346 u32 flags = nbd->config->flags;
1348 seq_printf(s, "Hex: 0x%08x\n\n", flags);
1350 seq_puts(s, "Known flags:\n");
1352 if (flags & NBD_FLAG_HAS_FLAGS)
1353 seq_puts(s, "NBD_FLAG_HAS_FLAGS\n");
1354 if (flags & NBD_FLAG_READ_ONLY)
1355 seq_puts(s, "NBD_FLAG_READ_ONLY\n");
1356 if (flags & NBD_FLAG_SEND_FLUSH)
1357 seq_puts(s, "NBD_FLAG_SEND_FLUSH\n");
1358 if (flags & NBD_FLAG_SEND_FUA)
1359 seq_puts(s, "NBD_FLAG_SEND_FUA\n");
1360 if (flags & NBD_FLAG_SEND_TRIM)
1361 seq_puts(s, "NBD_FLAG_SEND_TRIM\n");
1366 static int nbd_dbg_flags_open(struct inode *inode, struct file *file)
1368 return single_open(file, nbd_dbg_flags_show, inode->i_private);
1371 static const struct file_operations nbd_dbg_flags_ops = {
1372 .open = nbd_dbg_flags_open,
1374 .llseek = seq_lseek,
1375 .release = single_release,
1378 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1381 struct nbd_config *config = nbd->config;
1386 dir = debugfs_create_dir(nbd_name(nbd), nbd_dbg_dir);
1388 dev_err(nbd_to_dev(nbd), "Failed to create debugfs dir for '%s'\n",
1392 config->dbg_dir = dir;
1394 debugfs_create_file("tasks", 0444, dir, nbd, &nbd_dbg_tasks_ops);
1395 debugfs_create_u64("size_bytes", 0444, dir, &config->bytesize);
1396 debugfs_create_u32("timeout", 0444, dir, &nbd->tag_set.timeout);
1397 debugfs_create_u64("blocksize", 0444, dir, &config->blksize);
1398 debugfs_create_file("flags", 0444, dir, nbd, &nbd_dbg_flags_ops);
1403 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1405 debugfs_remove_recursive(nbd->config->dbg_dir);
1408 static int nbd_dbg_init(void)
1410 struct dentry *dbg_dir;
1412 dbg_dir = debugfs_create_dir("nbd", NULL);
1416 nbd_dbg_dir = dbg_dir;
1421 static void nbd_dbg_close(void)
1423 debugfs_remove_recursive(nbd_dbg_dir);
1426 #else /* IS_ENABLED(CONFIG_DEBUG_FS) */
1428 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1433 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1437 static int nbd_dbg_init(void)
1442 static void nbd_dbg_close(void)
1448 static int nbd_init_request(struct blk_mq_tag_set *set, struct request *rq,
1449 unsigned int hctx_idx, unsigned int numa_node)
1451 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(rq);
1452 cmd->nbd = set->driver_data;
1456 static const struct blk_mq_ops nbd_mq_ops = {
1457 .queue_rq = nbd_queue_rq,
1458 .complete = nbd_complete_rq,
1459 .init_request = nbd_init_request,
1460 .timeout = nbd_xmit_timeout,
1463 static int nbd_dev_add(int index)
1465 struct nbd_device *nbd;
1466 struct gendisk *disk;
1467 struct request_queue *q;
1470 nbd = kzalloc(sizeof(struct nbd_device), GFP_KERNEL);
1474 disk = alloc_disk(1 << part_shift);
1479 err = idr_alloc(&nbd_index_idr, nbd, index, index + 1,
1484 err = idr_alloc(&nbd_index_idr, nbd, 0, 0, GFP_KERNEL);
1493 nbd->tag_set.ops = &nbd_mq_ops;
1494 nbd->tag_set.nr_hw_queues = 1;
1495 nbd->tag_set.queue_depth = 128;
1496 nbd->tag_set.numa_node = NUMA_NO_NODE;
1497 nbd->tag_set.cmd_size = sizeof(struct nbd_cmd);
1498 nbd->tag_set.flags = BLK_MQ_F_SHOULD_MERGE |
1499 BLK_MQ_F_SG_MERGE | BLK_MQ_F_BLOCKING;
1500 nbd->tag_set.driver_data = nbd;
1502 err = blk_mq_alloc_tag_set(&nbd->tag_set);
1506 q = blk_mq_init_queue(&nbd->tag_set);
1514 * Tell the block layer that we are not a rotational device
1516 blk_queue_flag_set(QUEUE_FLAG_NONROT, disk->queue);
1517 blk_queue_flag_clear(QUEUE_FLAG_ADD_RANDOM, disk->queue);
1518 disk->queue->limits.discard_granularity = 0;
1519 blk_queue_max_discard_sectors(disk->queue, 0);
1520 blk_queue_max_segment_size(disk->queue, UINT_MAX);
1521 blk_queue_max_segments(disk->queue, USHRT_MAX);
1522 blk_queue_max_hw_sectors(disk->queue, 65536);
1523 disk->queue->limits.max_sectors = 256;
1525 mutex_init(&nbd->config_lock);
1526 refcount_set(&nbd->config_refs, 0);
1527 refcount_set(&nbd->refs, 1);
1528 INIT_LIST_HEAD(&nbd->list);
1529 disk->major = NBD_MAJOR;
1530 disk->first_minor = index << part_shift;
1531 disk->fops = &nbd_fops;
1532 disk->private_data = nbd;
1533 sprintf(disk->disk_name, "nbd%d", index);
1535 nbd_total_devices++;
1539 blk_mq_free_tag_set(&nbd->tag_set);
1541 idr_remove(&nbd_index_idr, index);
1550 static int find_free_cb(int id, void *ptr, void *data)
1552 struct nbd_device *nbd = ptr;
1553 struct nbd_device **found = data;
1555 if (!refcount_read(&nbd->config_refs)) {
1562 /* Netlink interface. */
1563 static struct nla_policy nbd_attr_policy[NBD_ATTR_MAX + 1] = {
1564 [NBD_ATTR_INDEX] = { .type = NLA_U32 },
1565 [NBD_ATTR_SIZE_BYTES] = { .type = NLA_U64 },
1566 [NBD_ATTR_BLOCK_SIZE_BYTES] = { .type = NLA_U64 },
1567 [NBD_ATTR_TIMEOUT] = { .type = NLA_U64 },
1568 [NBD_ATTR_SERVER_FLAGS] = { .type = NLA_U64 },
1569 [NBD_ATTR_CLIENT_FLAGS] = { .type = NLA_U64 },
1570 [NBD_ATTR_SOCKETS] = { .type = NLA_NESTED},
1571 [NBD_ATTR_DEAD_CONN_TIMEOUT] = { .type = NLA_U64 },
1572 [NBD_ATTR_DEVICE_LIST] = { .type = NLA_NESTED},
1575 static struct nla_policy nbd_sock_policy[NBD_SOCK_MAX + 1] = {
1576 [NBD_SOCK_FD] = { .type = NLA_U32 },
1579 /* We don't use this right now since we don't parse the incoming list, but we
1580 * still want it here so userspace knows what to expect.
1582 static struct nla_policy __attribute__((unused))
1583 nbd_device_policy[NBD_DEVICE_ATTR_MAX + 1] = {
1584 [NBD_DEVICE_INDEX] = { .type = NLA_U32 },
1585 [NBD_DEVICE_CONNECTED] = { .type = NLA_U8 },
1588 static int nbd_genl_connect(struct sk_buff *skb, struct genl_info *info)
1590 struct nbd_device *nbd = NULL;
1591 struct nbd_config *config;
1594 bool put_dev = false;
1596 if (!netlink_capable(skb, CAP_SYS_ADMIN))
1599 if (info->attrs[NBD_ATTR_INDEX])
1600 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1601 if (!info->attrs[NBD_ATTR_SOCKETS]) {
1602 printk(KERN_ERR "nbd: must specify at least one socket\n");
1605 if (!info->attrs[NBD_ATTR_SIZE_BYTES]) {
1606 printk(KERN_ERR "nbd: must specify a size in bytes for the device\n");
1610 mutex_lock(&nbd_index_mutex);
1612 ret = idr_for_each(&nbd_index_idr, &find_free_cb, &nbd);
1615 new_index = nbd_dev_add(-1);
1616 if (new_index < 0) {
1617 mutex_unlock(&nbd_index_mutex);
1618 printk(KERN_ERR "nbd: failed to add new device\n");
1621 nbd = idr_find(&nbd_index_idr, new_index);
1624 nbd = idr_find(&nbd_index_idr, index);
1626 ret = nbd_dev_add(index);
1628 mutex_unlock(&nbd_index_mutex);
1629 printk(KERN_ERR "nbd: failed to add new device\n");
1632 nbd = idr_find(&nbd_index_idr, index);
1636 printk(KERN_ERR "nbd: couldn't find device at index %d\n",
1638 mutex_unlock(&nbd_index_mutex);
1641 if (!refcount_inc_not_zero(&nbd->refs)) {
1642 mutex_unlock(&nbd_index_mutex);
1645 printk(KERN_ERR "nbd: device at index %d is going down\n",
1649 mutex_unlock(&nbd_index_mutex);
1651 mutex_lock(&nbd->config_lock);
1652 if (refcount_read(&nbd->config_refs)) {
1653 mutex_unlock(&nbd->config_lock);
1657 printk(KERN_ERR "nbd: nbd%d already in use\n", index);
1660 if (WARN_ON(nbd->config)) {
1661 mutex_unlock(&nbd->config_lock);
1665 config = nbd->config = nbd_alloc_config();
1667 mutex_unlock(&nbd->config_lock);
1669 printk(KERN_ERR "nbd: couldn't allocate config\n");
1672 refcount_set(&nbd->config_refs, 1);
1673 set_bit(NBD_BOUND, &config->runtime_flags);
1675 if (info->attrs[NBD_ATTR_SIZE_BYTES]) {
1676 u64 bytes = nla_get_u64(info->attrs[NBD_ATTR_SIZE_BYTES]);
1677 nbd_size_set(nbd, config->blksize,
1678 div64_u64(bytes, config->blksize));
1680 if (info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]) {
1682 nla_get_u64(info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]);
1683 nbd_size_set(nbd, bsize, div64_u64(config->bytesize, bsize));
1685 if (info->attrs[NBD_ATTR_TIMEOUT]) {
1686 u64 timeout = nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]);
1687 nbd->tag_set.timeout = timeout * HZ;
1688 blk_queue_rq_timeout(nbd->disk->queue, timeout * HZ);
1690 if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
1691 config->dead_conn_timeout =
1692 nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
1693 config->dead_conn_timeout *= HZ;
1695 if (info->attrs[NBD_ATTR_SERVER_FLAGS])
1697 nla_get_u64(info->attrs[NBD_ATTR_SERVER_FLAGS]);
1698 if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
1699 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
1700 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
1701 set_bit(NBD_DESTROY_ON_DISCONNECT,
1702 &config->runtime_flags);
1707 if (info->attrs[NBD_ATTR_SOCKETS]) {
1708 struct nlattr *attr;
1711 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
1713 struct nlattr *socks[NBD_SOCK_MAX+1];
1715 if (nla_type(attr) != NBD_SOCK_ITEM) {
1716 printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
1720 ret = nla_parse_nested(socks, NBD_SOCK_MAX, attr,
1721 nbd_sock_policy, info->extack);
1723 printk(KERN_ERR "nbd: error processing sock list\n");
1727 if (!socks[NBD_SOCK_FD])
1729 fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
1730 ret = nbd_add_socket(nbd, fd, true);
1735 ret = nbd_start_device(nbd);
1737 mutex_unlock(&nbd->config_lock);
1739 set_bit(NBD_HAS_CONFIG_REF, &config->runtime_flags);
1740 refcount_inc(&nbd->config_refs);
1741 nbd_connect_reply(info, nbd->index);
1743 nbd_config_put(nbd);
1749 static int nbd_genl_disconnect(struct sk_buff *skb, struct genl_info *info)
1751 struct nbd_device *nbd;
1754 if (!netlink_capable(skb, CAP_SYS_ADMIN))
1757 if (!info->attrs[NBD_ATTR_INDEX]) {
1758 printk(KERN_ERR "nbd: must specify an index to disconnect\n");
1761 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1762 mutex_lock(&nbd_index_mutex);
1763 nbd = idr_find(&nbd_index_idr, index);
1765 mutex_unlock(&nbd_index_mutex);
1766 printk(KERN_ERR "nbd: couldn't find device at index %d\n",
1770 if (!refcount_inc_not_zero(&nbd->refs)) {
1771 mutex_unlock(&nbd_index_mutex);
1772 printk(KERN_ERR "nbd: device at index %d is going down\n",
1776 mutex_unlock(&nbd_index_mutex);
1777 if (!refcount_inc_not_zero(&nbd->config_refs)) {
1781 mutex_lock(&nbd->config_lock);
1782 nbd_disconnect(nbd);
1783 nbd_clear_sock(nbd);
1784 mutex_unlock(&nbd->config_lock);
1785 if (test_and_clear_bit(NBD_HAS_CONFIG_REF,
1786 &nbd->config->runtime_flags))
1787 nbd_config_put(nbd);
1788 nbd_config_put(nbd);
1793 static int nbd_genl_reconfigure(struct sk_buff *skb, struct genl_info *info)
1795 struct nbd_device *nbd = NULL;
1796 struct nbd_config *config;
1799 bool put_dev = false;
1801 if (!netlink_capable(skb, CAP_SYS_ADMIN))
1804 if (!info->attrs[NBD_ATTR_INDEX]) {
1805 printk(KERN_ERR "nbd: must specify a device to reconfigure\n");
1808 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1809 mutex_lock(&nbd_index_mutex);
1810 nbd = idr_find(&nbd_index_idr, index);
1812 mutex_unlock(&nbd_index_mutex);
1813 printk(KERN_ERR "nbd: couldn't find a device at index %d\n",
1817 if (!refcount_inc_not_zero(&nbd->refs)) {
1818 mutex_unlock(&nbd_index_mutex);
1819 printk(KERN_ERR "nbd: device at index %d is going down\n",
1823 mutex_unlock(&nbd_index_mutex);
1825 if (!refcount_inc_not_zero(&nbd->config_refs)) {
1826 dev_err(nbd_to_dev(nbd),
1827 "not configured, cannot reconfigure\n");
1832 mutex_lock(&nbd->config_lock);
1833 config = nbd->config;
1834 if (!test_bit(NBD_BOUND, &config->runtime_flags) ||
1836 dev_err(nbd_to_dev(nbd),
1837 "not configured, cannot reconfigure\n");
1841 if (info->attrs[NBD_ATTR_TIMEOUT]) {
1842 u64 timeout = nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]);
1843 nbd->tag_set.timeout = timeout * HZ;
1844 blk_queue_rq_timeout(nbd->disk->queue, timeout * HZ);
1846 if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
1847 config->dead_conn_timeout =
1848 nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
1849 config->dead_conn_timeout *= HZ;
1851 if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
1852 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
1853 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
1854 if (!test_and_set_bit(NBD_DESTROY_ON_DISCONNECT,
1855 &config->runtime_flags))
1858 if (test_and_clear_bit(NBD_DESTROY_ON_DISCONNECT,
1859 &config->runtime_flags))
1860 refcount_inc(&nbd->refs);
1864 if (info->attrs[NBD_ATTR_SOCKETS]) {
1865 struct nlattr *attr;
1868 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
1870 struct nlattr *socks[NBD_SOCK_MAX+1];
1872 if (nla_type(attr) != NBD_SOCK_ITEM) {
1873 printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
1877 ret = nla_parse_nested(socks, NBD_SOCK_MAX, attr,
1878 nbd_sock_policy, info->extack);
1880 printk(KERN_ERR "nbd: error processing sock list\n");
1884 if (!socks[NBD_SOCK_FD])
1886 fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
1887 ret = nbd_reconnect_socket(nbd, fd);
1893 dev_info(nbd_to_dev(nbd), "reconnected socket\n");
1897 mutex_unlock(&nbd->config_lock);
1898 nbd_config_put(nbd);
1905 static const struct genl_ops nbd_connect_genl_ops[] = {
1907 .cmd = NBD_CMD_CONNECT,
1908 .policy = nbd_attr_policy,
1909 .doit = nbd_genl_connect,
1912 .cmd = NBD_CMD_DISCONNECT,
1913 .policy = nbd_attr_policy,
1914 .doit = nbd_genl_disconnect,
1917 .cmd = NBD_CMD_RECONFIGURE,
1918 .policy = nbd_attr_policy,
1919 .doit = nbd_genl_reconfigure,
1922 .cmd = NBD_CMD_STATUS,
1923 .policy = nbd_attr_policy,
1924 .doit = nbd_genl_status,
1928 static const struct genl_multicast_group nbd_mcast_grps[] = {
1929 { .name = NBD_GENL_MCAST_GROUP_NAME, },
1932 static struct genl_family nbd_genl_family __ro_after_init = {
1934 .name = NBD_GENL_FAMILY_NAME,
1935 .version = NBD_GENL_VERSION,
1936 .module = THIS_MODULE,
1937 .ops = nbd_connect_genl_ops,
1938 .n_ops = ARRAY_SIZE(nbd_connect_genl_ops),
1939 .maxattr = NBD_ATTR_MAX,
1940 .mcgrps = nbd_mcast_grps,
1941 .n_mcgrps = ARRAY_SIZE(nbd_mcast_grps),
1944 static int populate_nbd_status(struct nbd_device *nbd, struct sk_buff *reply)
1946 struct nlattr *dev_opt;
1950 /* This is a little racey, but for status it's ok. The
1951 * reason we don't take a ref here is because we can't
1952 * take a ref in the index == -1 case as we would need
1953 * to put under the nbd_index_mutex, which could
1954 * deadlock if we are configured to remove ourselves
1955 * once we're disconnected.
1957 if (refcount_read(&nbd->config_refs))
1959 dev_opt = nla_nest_start(reply, NBD_DEVICE_ITEM);
1962 ret = nla_put_u32(reply, NBD_DEVICE_INDEX, nbd->index);
1965 ret = nla_put_u8(reply, NBD_DEVICE_CONNECTED,
1969 nla_nest_end(reply, dev_opt);
1973 static int status_cb(int id, void *ptr, void *data)
1975 struct nbd_device *nbd = ptr;
1976 return populate_nbd_status(nbd, (struct sk_buff *)data);
1979 static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info)
1981 struct nlattr *dev_list;
1982 struct sk_buff *reply;
1988 if (info->attrs[NBD_ATTR_INDEX])
1989 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1991 mutex_lock(&nbd_index_mutex);
1993 msg_size = nla_total_size(nla_attr_size(sizeof(u32)) +
1994 nla_attr_size(sizeof(u8)));
1995 msg_size *= (index == -1) ? nbd_total_devices : 1;
1997 reply = genlmsg_new(msg_size, GFP_KERNEL);
2000 reply_head = genlmsg_put_reply(reply, info, &nbd_genl_family, 0,
2007 dev_list = nla_nest_start(reply, NBD_ATTR_DEVICE_LIST);
2009 ret = idr_for_each(&nbd_index_idr, &status_cb, reply);
2015 struct nbd_device *nbd;
2016 nbd = idr_find(&nbd_index_idr, index);
2018 ret = populate_nbd_status(nbd, reply);
2025 nla_nest_end(reply, dev_list);
2026 genlmsg_end(reply, reply_head);
2027 genlmsg_reply(reply, info);
2030 mutex_unlock(&nbd_index_mutex);
2034 static void nbd_connect_reply(struct genl_info *info, int index)
2036 struct sk_buff *skb;
2040 skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2043 msg_head = genlmsg_put_reply(skb, info, &nbd_genl_family, 0,
2049 ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2054 genlmsg_end(skb, msg_head);
2055 genlmsg_reply(skb, info);
2058 static void nbd_mcast_index(int index)
2060 struct sk_buff *skb;
2064 skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2067 msg_head = genlmsg_put(skb, 0, 0, &nbd_genl_family, 0,
2073 ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2078 genlmsg_end(skb, msg_head);
2079 genlmsg_multicast(&nbd_genl_family, skb, 0, 0, GFP_KERNEL);
2082 static void nbd_dead_link_work(struct work_struct *work)
2084 struct link_dead_args *args = container_of(work, struct link_dead_args,
2086 nbd_mcast_index(args->index);
2090 static int __init nbd_init(void)
2094 BUILD_BUG_ON(sizeof(struct nbd_request) != 28);
2097 printk(KERN_ERR "nbd: max_part must be >= 0\n");
2103 part_shift = fls(max_part);
2106 * Adjust max_part according to part_shift as it is exported
2107 * to user space so that user can know the max number of
2108 * partition kernel should be able to manage.
2110 * Note that -1 is required because partition 0 is reserved
2111 * for the whole disk.
2113 max_part = (1UL << part_shift) - 1;
2116 if ((1UL << part_shift) > DISK_MAX_PARTS)
2119 if (nbds_max > 1UL << (MINORBITS - part_shift))
2121 recv_workqueue = alloc_workqueue("knbd-recv",
2122 WQ_MEM_RECLAIM | WQ_HIGHPRI |
2124 if (!recv_workqueue)
2127 if (register_blkdev(NBD_MAJOR, "nbd")) {
2128 destroy_workqueue(recv_workqueue);
2132 if (genl_register_family(&nbd_genl_family)) {
2133 unregister_blkdev(NBD_MAJOR, "nbd");
2134 destroy_workqueue(recv_workqueue);
2139 mutex_lock(&nbd_index_mutex);
2140 for (i = 0; i < nbds_max; i++)
2142 mutex_unlock(&nbd_index_mutex);
2146 static int nbd_exit_cb(int id, void *ptr, void *data)
2148 struct list_head *list = (struct list_head *)data;
2149 struct nbd_device *nbd = ptr;
2151 list_add_tail(&nbd->list, list);
2155 static void __exit nbd_cleanup(void)
2157 struct nbd_device *nbd;
2158 LIST_HEAD(del_list);
2162 mutex_lock(&nbd_index_mutex);
2163 idr_for_each(&nbd_index_idr, &nbd_exit_cb, &del_list);
2164 mutex_unlock(&nbd_index_mutex);
2166 while (!list_empty(&del_list)) {
2167 nbd = list_first_entry(&del_list, struct nbd_device, list);
2168 list_del_init(&nbd->list);
2169 if (refcount_read(&nbd->refs) != 1)
2170 printk(KERN_ERR "nbd: possibly leaking a device\n");
2174 idr_destroy(&nbd_index_idr);
2175 genl_unregister_family(&nbd_genl_family);
2176 destroy_workqueue(recv_workqueue);
2177 unregister_blkdev(NBD_MAJOR, "nbd");
2180 module_init(nbd_init);
2181 module_exit(nbd_cleanup);
2183 MODULE_DESCRIPTION("Network Block Device");
2184 MODULE_LICENSE("GPL");
2186 module_param(nbds_max, int, 0444);
2187 MODULE_PARM_DESC(nbds_max, "number of network block devices to initialize (default: 16)");
2188 module_param(max_part, int, 0444);
2189 MODULE_PARM_DESC(max_part, "number of partitions per device (default: 16)");