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 nbd->disk->queue->limits.discard_alignment = config->blksize;
250 blk_queue_max_discard_sectors(nbd->disk->queue, UINT_MAX);
252 blk_queue_logical_block_size(nbd->disk->queue, config->blksize);
253 blk_queue_physical_block_size(nbd->disk->queue, config->blksize);
254 set_capacity(nbd->disk, config->bytesize >> 9);
257 bd_set_size(bdev, config->bytesize);
259 bdev->bd_invalidated = 1;
262 kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
265 static void nbd_size_set(struct nbd_device *nbd, loff_t blocksize,
268 struct nbd_config *config = nbd->config;
269 config->blksize = blocksize;
270 config->bytesize = blocksize * nr_blocks;
271 if (nbd->task_recv != NULL)
272 nbd_size_update(nbd);
275 static void nbd_complete_rq(struct request *req)
277 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
279 dev_dbg(nbd_to_dev(cmd->nbd), "request %p: %s\n", req,
280 cmd->status ? "failed" : "done");
282 blk_mq_end_request(req, cmd->status);
286 * Forcibly shutdown the socket causing all listeners to error
288 static void sock_shutdown(struct nbd_device *nbd)
290 struct nbd_config *config = nbd->config;
293 if (config->num_connections == 0)
295 if (test_and_set_bit(NBD_DISCONNECTED, &config->runtime_flags))
298 for (i = 0; i < config->num_connections; i++) {
299 struct nbd_sock *nsock = config->socks[i];
300 mutex_lock(&nsock->tx_lock);
301 nbd_mark_nsock_dead(nbd, nsock, 0);
302 mutex_unlock(&nsock->tx_lock);
304 dev_warn(disk_to_dev(nbd->disk), "shutting down sockets\n");
307 static enum blk_eh_timer_return nbd_xmit_timeout(struct request *req,
310 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
311 struct nbd_device *nbd = cmd->nbd;
312 struct nbd_config *config;
314 if (!refcount_inc_not_zero(&nbd->config_refs)) {
315 cmd->status = BLK_STS_TIMEOUT;
318 config = nbd->config;
320 if (config->num_connections > 1) {
321 dev_err_ratelimited(nbd_to_dev(nbd),
322 "Connection timed out, retrying (%d/%d alive)\n",
323 atomic_read(&config->live_connections),
324 config->num_connections);
326 * Hooray we have more connections, requeue this IO, the submit
327 * path will put it on a real connection.
329 if (config->socks && config->num_connections > 1) {
330 if (cmd->index < config->num_connections) {
331 struct nbd_sock *nsock =
332 config->socks[cmd->index];
333 mutex_lock(&nsock->tx_lock);
334 /* We can have multiple outstanding requests, so
335 * we don't want to mark the nsock dead if we've
336 * already reconnected with a new socket, so
337 * only mark it dead if its the same socket we
340 if (cmd->cookie == nsock->cookie)
341 nbd_mark_nsock_dead(nbd, nsock, 1);
342 mutex_unlock(&nsock->tx_lock);
344 blk_mq_requeue_request(req, true);
349 dev_err_ratelimited(nbd_to_dev(nbd),
350 "Connection timed out\n");
352 set_bit(NBD_TIMEDOUT, &config->runtime_flags);
353 cmd->status = BLK_STS_IOERR;
357 blk_mq_complete_request(req);
362 * Send or receive packet.
364 static int sock_xmit(struct nbd_device *nbd, int index, int send,
365 struct iov_iter *iter, int msg_flags, int *sent)
367 struct nbd_config *config = nbd->config;
368 struct socket *sock = config->socks[index]->sock;
371 unsigned int noreclaim_flag;
373 if (unlikely(!sock)) {
374 dev_err_ratelimited(disk_to_dev(nbd->disk),
375 "Attempted %s on closed socket in sock_xmit\n",
376 (send ? "send" : "recv"));
380 msg.msg_iter = *iter;
382 noreclaim_flag = memalloc_noreclaim_save();
384 sock->sk->sk_allocation = GFP_NOIO | __GFP_MEMALLOC;
387 msg.msg_control = NULL;
388 msg.msg_controllen = 0;
389 msg.msg_flags = msg_flags | MSG_NOSIGNAL;
392 result = sock_sendmsg(sock, &msg);
394 result = sock_recvmsg(sock, &msg, msg.msg_flags);
398 result = -EPIPE; /* short read */
403 } while (msg_data_left(&msg));
405 memalloc_noreclaim_restore(noreclaim_flag);
411 * Different settings for sk->sk_sndtimeo can result in different return values
412 * if there is a signal pending when we enter sendmsg, because reasons?
414 static inline int was_interrupted(int result)
416 return result == -ERESTARTSYS || result == -EINTR;
419 /* always call with the tx_lock held */
420 static int nbd_send_cmd(struct nbd_device *nbd, struct nbd_cmd *cmd, int index)
422 struct request *req = blk_mq_rq_from_pdu(cmd);
423 struct nbd_config *config = nbd->config;
424 struct nbd_sock *nsock = config->socks[index];
426 struct nbd_request request = {.magic = htonl(NBD_REQUEST_MAGIC)};
427 struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
428 struct iov_iter from;
429 unsigned long size = blk_rq_bytes(req);
432 u32 nbd_cmd_flags = 0;
433 u32 tag = blk_mq_unique_tag(req);
434 int sent = nsock->sent, skip = 0;
436 iov_iter_kvec(&from, WRITE | ITER_KVEC, &iov, 1, sizeof(request));
438 switch (req_op(req)) {
443 type = NBD_CMD_FLUSH;
446 type = NBD_CMD_WRITE;
455 if (rq_data_dir(req) == WRITE &&
456 (config->flags & NBD_FLAG_READ_ONLY)) {
457 dev_err_ratelimited(disk_to_dev(nbd->disk),
458 "Write on read-only\n");
462 if (req->cmd_flags & REQ_FUA)
463 nbd_cmd_flags |= NBD_CMD_FLAG_FUA;
465 /* We did a partial send previously, and we at least sent the whole
466 * request struct, so just go and send the rest of the pages in the
470 if (sent >= sizeof(request)) {
471 skip = sent - sizeof(request);
474 iov_iter_advance(&from, sent);
477 cmd->cookie = nsock->cookie;
478 request.type = htonl(type | nbd_cmd_flags);
479 if (type != NBD_CMD_FLUSH) {
480 request.from = cpu_to_be64((u64)blk_rq_pos(req) << 9);
481 request.len = htonl(size);
483 memcpy(request.handle, &tag, sizeof(tag));
485 dev_dbg(nbd_to_dev(nbd), "request %p: sending control (%s@%llu,%uB)\n",
486 req, nbdcmd_to_ascii(type),
487 (unsigned long long)blk_rq_pos(req) << 9, blk_rq_bytes(req));
488 result = sock_xmit(nbd, index, 1, &from,
489 (type == NBD_CMD_WRITE) ? MSG_MORE : 0, &sent);
491 if (was_interrupted(result)) {
492 /* If we havne't sent anything we can just return BUSY,
493 * however if we have sent something we need to make
494 * sure we only allow this req to be sent until we are
498 nsock->pending = req;
501 return BLK_STS_RESOURCE;
503 dev_err_ratelimited(disk_to_dev(nbd->disk),
504 "Send control failed (result %d)\n", result);
508 if (type != NBD_CMD_WRITE)
513 struct bio *next = bio->bi_next;
514 struct bvec_iter iter;
517 bio_for_each_segment(bvec, bio, iter) {
518 bool is_last = !next && bio_iter_last(bvec, iter);
519 int flags = is_last ? 0 : MSG_MORE;
521 dev_dbg(nbd_to_dev(nbd), "request %p: sending %d bytes data\n",
523 iov_iter_bvec(&from, ITER_BVEC | WRITE,
524 &bvec, 1, bvec.bv_len);
526 if (skip >= iov_iter_count(&from)) {
527 skip -= iov_iter_count(&from);
530 iov_iter_advance(&from, skip);
533 result = sock_xmit(nbd, index, 1, &from, flags, &sent);
535 if (was_interrupted(result)) {
536 /* We've already sent the header, we
537 * have no choice but to set pending and
540 nsock->pending = req;
542 return BLK_STS_RESOURCE;
544 dev_err(disk_to_dev(nbd->disk),
545 "Send data failed (result %d)\n",
550 * The completion might already have come in,
551 * so break for the last one instead of letting
552 * the iterator do it. This prevents use-after-free
561 nsock->pending = NULL;
566 /* NULL returned = something went wrong, inform userspace */
567 static struct nbd_cmd *nbd_read_stat(struct nbd_device *nbd, int index)
569 struct nbd_config *config = nbd->config;
571 struct nbd_reply reply;
573 struct request *req = NULL;
576 struct kvec iov = {.iov_base = &reply, .iov_len = sizeof(reply)};
580 iov_iter_kvec(&to, READ | ITER_KVEC, &iov, 1, sizeof(reply));
581 result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
583 if (!nbd_disconnected(config))
584 dev_err(disk_to_dev(nbd->disk),
585 "Receive control failed (result %d)\n", result);
586 return ERR_PTR(result);
589 if (ntohl(reply.magic) != NBD_REPLY_MAGIC) {
590 dev_err(disk_to_dev(nbd->disk), "Wrong magic (0x%lx)\n",
591 (unsigned long)ntohl(reply.magic));
592 return ERR_PTR(-EPROTO);
595 memcpy(&tag, reply.handle, sizeof(u32));
597 hwq = blk_mq_unique_tag_to_hwq(tag);
598 if (hwq < nbd->tag_set.nr_hw_queues)
599 req = blk_mq_tag_to_rq(nbd->tag_set.tags[hwq],
600 blk_mq_unique_tag_to_tag(tag));
601 if (!req || !blk_mq_request_started(req)) {
602 dev_err(disk_to_dev(nbd->disk), "Unexpected reply (%d) %p\n",
604 return ERR_PTR(-ENOENT);
606 cmd = blk_mq_rq_to_pdu(req);
607 if (ntohl(reply.error)) {
608 dev_err(disk_to_dev(nbd->disk), "Other side returned error (%d)\n",
610 cmd->status = BLK_STS_IOERR;
614 dev_dbg(nbd_to_dev(nbd), "request %p: got reply\n", req);
615 if (rq_data_dir(req) != WRITE) {
616 struct req_iterator iter;
619 rq_for_each_segment(bvec, req, iter) {
620 iov_iter_bvec(&to, ITER_BVEC | READ,
621 &bvec, 1, bvec.bv_len);
622 result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
624 dev_err(disk_to_dev(nbd->disk), "Receive data failed (result %d)\n",
627 * If we've disconnected or we only have 1
628 * connection then we need to make sure we
629 * complete this request, otherwise error out
630 * and let the timeout stuff handle resubmitting
631 * this request onto another connection.
633 if (nbd_disconnected(config) ||
634 config->num_connections <= 1) {
635 cmd->status = BLK_STS_IOERR;
638 return ERR_PTR(-EIO);
640 dev_dbg(nbd_to_dev(nbd), "request %p: got %d bytes data\n",
644 /* See the comment in nbd_queue_rq. */
645 wait_for_completion(&cmd->send_complete);
650 static void recv_work(struct work_struct *work)
652 struct recv_thread_args *args = container_of(work,
653 struct recv_thread_args,
655 struct nbd_device *nbd = args->nbd;
656 struct nbd_config *config = nbd->config;
660 cmd = nbd_read_stat(nbd, args->index);
662 struct nbd_sock *nsock = config->socks[args->index];
664 mutex_lock(&nsock->tx_lock);
665 nbd_mark_nsock_dead(nbd, nsock, 1);
666 mutex_unlock(&nsock->tx_lock);
670 blk_mq_complete_request(blk_mq_rq_from_pdu(cmd));
672 atomic_dec(&config->recv_threads);
673 wake_up(&config->recv_wq);
678 static void nbd_clear_req(struct request *req, void *data, bool reserved)
680 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
682 cmd->status = BLK_STS_IOERR;
683 blk_mq_complete_request(req);
686 static void nbd_clear_que(struct nbd_device *nbd)
688 blk_mq_quiesce_queue(nbd->disk->queue);
689 blk_mq_tagset_busy_iter(&nbd->tag_set, nbd_clear_req, NULL);
690 blk_mq_unquiesce_queue(nbd->disk->queue);
691 dev_dbg(disk_to_dev(nbd->disk), "queue cleared\n");
694 static int find_fallback(struct nbd_device *nbd, int index)
696 struct nbd_config *config = nbd->config;
698 struct nbd_sock *nsock = config->socks[index];
699 int fallback = nsock->fallback_index;
701 if (test_bit(NBD_DISCONNECTED, &config->runtime_flags))
704 if (config->num_connections <= 1) {
705 dev_err_ratelimited(disk_to_dev(nbd->disk),
706 "Attempted send on invalid socket\n");
710 if (fallback >= 0 && fallback < config->num_connections &&
711 !config->socks[fallback]->dead)
714 if (nsock->fallback_index < 0 ||
715 nsock->fallback_index >= config->num_connections ||
716 config->socks[nsock->fallback_index]->dead) {
718 for (i = 0; i < config->num_connections; i++) {
721 if (!config->socks[i]->dead) {
726 nsock->fallback_index = new_index;
728 dev_err_ratelimited(disk_to_dev(nbd->disk),
729 "Dead connection, failed to find a fallback\n");
733 new_index = nsock->fallback_index;
737 static int wait_for_reconnect(struct nbd_device *nbd)
739 struct nbd_config *config = nbd->config;
740 if (!config->dead_conn_timeout)
742 if (test_bit(NBD_DISCONNECTED, &config->runtime_flags))
744 return wait_event_timeout(config->conn_wait,
745 atomic_read(&config->live_connections) > 0,
746 config->dead_conn_timeout) > 0;
749 static int nbd_handle_cmd(struct nbd_cmd *cmd, int index)
751 struct request *req = blk_mq_rq_from_pdu(cmd);
752 struct nbd_device *nbd = cmd->nbd;
753 struct nbd_config *config;
754 struct nbd_sock *nsock;
757 if (!refcount_inc_not_zero(&nbd->config_refs)) {
758 dev_err_ratelimited(disk_to_dev(nbd->disk),
759 "Socks array is empty\n");
760 blk_mq_start_request(req);
763 config = nbd->config;
765 if (index >= config->num_connections) {
766 dev_err_ratelimited(disk_to_dev(nbd->disk),
767 "Attempted send on invalid socket\n");
769 blk_mq_start_request(req);
772 cmd->status = BLK_STS_OK;
774 nsock = config->socks[index];
775 mutex_lock(&nsock->tx_lock);
777 int old_index = index;
778 index = find_fallback(nbd, index);
779 mutex_unlock(&nsock->tx_lock);
781 if (wait_for_reconnect(nbd)) {
785 /* All the sockets should already be down at this point,
786 * we just want to make sure that DISCONNECTED is set so
787 * any requests that come in that were queue'ed waiting
788 * for the reconnect timer don't trigger the timer again
789 * and instead just error out.
793 blk_mq_start_request(req);
799 /* Handle the case that we have a pending request that was partially
800 * transmitted that _has_ to be serviced first. We need to call requeue
801 * here so that it gets put _after_ the request that is already on the
804 blk_mq_start_request(req);
805 if (unlikely(nsock->pending && nsock->pending != req)) {
806 blk_mq_requeue_request(req, true);
811 * Some failures are related to the link going down, so anything that
812 * returns EAGAIN can be retried on a different socket.
814 ret = nbd_send_cmd(nbd, cmd, index);
815 if (ret == -EAGAIN) {
816 dev_err_ratelimited(disk_to_dev(nbd->disk),
817 "Request send failed, requeueing\n");
818 nbd_mark_nsock_dead(nbd, nsock, 1);
819 blk_mq_requeue_request(req, true);
823 mutex_unlock(&nsock->tx_lock);
828 static blk_status_t nbd_queue_rq(struct blk_mq_hw_ctx *hctx,
829 const struct blk_mq_queue_data *bd)
831 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(bd->rq);
835 * Since we look at the bio's to send the request over the network we
836 * need to make sure the completion work doesn't mark this request done
837 * before we are done doing our send. This keeps us from dereferencing
838 * freed data if we have particularly fast completions (ie we get the
839 * completion before we exit sock_xmit on the last bvec) or in the case
840 * that the server is misbehaving (or there was an error) before we're
841 * done sending everything over the wire.
843 init_completion(&cmd->send_complete);
845 /* We can be called directly from the user space process, which means we
846 * could possibly have signals pending so our sendmsg will fail. In
847 * this case we need to return that we are busy, otherwise error out as
850 ret = nbd_handle_cmd(cmd, hctx->queue_num);
855 complete(&cmd->send_complete);
860 static int nbd_add_socket(struct nbd_device *nbd, unsigned long arg,
863 struct nbd_config *config = nbd->config;
865 struct nbd_sock **socks;
866 struct nbd_sock *nsock;
869 sock = sockfd_lookup(arg, &err);
873 if (!netlink && !nbd->task_setup &&
874 !test_bit(NBD_BOUND, &config->runtime_flags))
875 nbd->task_setup = current;
878 (nbd->task_setup != current ||
879 test_bit(NBD_BOUND, &config->runtime_flags))) {
880 dev_err(disk_to_dev(nbd->disk),
881 "Device being setup by another task");
886 socks = krealloc(config->socks, (config->num_connections + 1) *
887 sizeof(struct nbd_sock *), GFP_KERNEL);
892 nsock = kzalloc(sizeof(struct nbd_sock), GFP_KERNEL);
898 config->socks = socks;
900 nsock->fallback_index = -1;
902 mutex_init(&nsock->tx_lock);
904 nsock->pending = NULL;
907 socks[config->num_connections++] = nsock;
908 atomic_inc(&config->live_connections);
913 static int nbd_reconnect_socket(struct nbd_device *nbd, unsigned long arg)
915 struct nbd_config *config = nbd->config;
916 struct socket *sock, *old;
917 struct recv_thread_args *args;
921 sock = sockfd_lookup(arg, &err);
925 args = kzalloc(sizeof(*args), GFP_KERNEL);
931 for (i = 0; i < config->num_connections; i++) {
932 struct nbd_sock *nsock = config->socks[i];
937 mutex_lock(&nsock->tx_lock);
939 mutex_unlock(&nsock->tx_lock);
942 sk_set_memalloc(sock->sk);
943 if (nbd->tag_set.timeout)
944 sock->sk->sk_sndtimeo = nbd->tag_set.timeout;
945 atomic_inc(&config->recv_threads);
946 refcount_inc(&nbd->config_refs);
948 nsock->fallback_index = -1;
951 INIT_WORK(&args->work, recv_work);
955 mutex_unlock(&nsock->tx_lock);
958 clear_bit(NBD_DISCONNECTED, &config->runtime_flags);
960 /* We take the tx_mutex in an error path in the recv_work, so we
961 * need to queue_work outside of the tx_mutex.
963 queue_work(recv_workqueue, &args->work);
965 atomic_inc(&config->live_connections);
966 wake_up(&config->conn_wait);
974 static void nbd_bdev_reset(struct block_device *bdev)
976 if (bdev->bd_openers > 1)
978 bd_set_size(bdev, 0);
981 static void nbd_parse_flags(struct nbd_device *nbd)
983 struct nbd_config *config = nbd->config;
984 if (config->flags & NBD_FLAG_READ_ONLY)
985 set_disk_ro(nbd->disk, true);
987 set_disk_ro(nbd->disk, false);
988 if (config->flags & NBD_FLAG_SEND_TRIM)
989 blk_queue_flag_set(QUEUE_FLAG_DISCARD, nbd->disk->queue);
990 if (config->flags & NBD_FLAG_SEND_FLUSH) {
991 if (config->flags & NBD_FLAG_SEND_FUA)
992 blk_queue_write_cache(nbd->disk->queue, true, true);
994 blk_queue_write_cache(nbd->disk->queue, true, false);
997 blk_queue_write_cache(nbd->disk->queue, false, false);
1000 static void send_disconnects(struct nbd_device *nbd)
1002 struct nbd_config *config = nbd->config;
1003 struct nbd_request request = {
1004 .magic = htonl(NBD_REQUEST_MAGIC),
1005 .type = htonl(NBD_CMD_DISC),
1007 struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
1008 struct iov_iter from;
1011 for (i = 0; i < config->num_connections; i++) {
1012 struct nbd_sock *nsock = config->socks[i];
1014 iov_iter_kvec(&from, WRITE | ITER_KVEC, &iov, 1, sizeof(request));
1015 mutex_lock(&nsock->tx_lock);
1016 ret = sock_xmit(nbd, i, 1, &from, 0, NULL);
1018 dev_err(disk_to_dev(nbd->disk),
1019 "Send disconnect failed %d\n", ret);
1020 mutex_unlock(&nsock->tx_lock);
1024 static int nbd_disconnect(struct nbd_device *nbd)
1026 struct nbd_config *config = nbd->config;
1028 dev_info(disk_to_dev(nbd->disk), "NBD_DISCONNECT\n");
1029 set_bit(NBD_DISCONNECT_REQUESTED, &config->runtime_flags);
1030 send_disconnects(nbd);
1034 static void nbd_clear_sock(struct nbd_device *nbd)
1038 nbd->task_setup = NULL;
1041 static void nbd_config_put(struct nbd_device *nbd)
1043 if (refcount_dec_and_mutex_lock(&nbd->config_refs,
1044 &nbd->config_lock)) {
1045 struct nbd_config *config = nbd->config;
1046 nbd_dev_dbg_close(nbd);
1047 nbd_size_clear(nbd);
1048 if (test_and_clear_bit(NBD_HAS_PID_FILE,
1049 &config->runtime_flags))
1050 device_remove_file(disk_to_dev(nbd->disk), &pid_attr);
1051 nbd->task_recv = NULL;
1052 nbd_clear_sock(nbd);
1053 if (config->num_connections) {
1055 for (i = 0; i < config->num_connections; i++) {
1056 sockfd_put(config->socks[i]->sock);
1057 kfree(config->socks[i]);
1059 kfree(config->socks);
1064 nbd->tag_set.timeout = 0;
1065 nbd->disk->queue->limits.discard_granularity = 0;
1066 nbd->disk->queue->limits.discard_alignment = 0;
1067 blk_queue_max_discard_sectors(nbd->disk->queue, UINT_MAX);
1068 blk_queue_flag_clear(QUEUE_FLAG_DISCARD, nbd->disk->queue);
1070 mutex_unlock(&nbd->config_lock);
1072 module_put(THIS_MODULE);
1076 static int nbd_start_device(struct nbd_device *nbd)
1078 struct nbd_config *config = nbd->config;
1079 int num_connections = config->num_connections;
1086 if (num_connections > 1 &&
1087 !(config->flags & NBD_FLAG_CAN_MULTI_CONN)) {
1088 dev_err(disk_to_dev(nbd->disk), "server does not support multiple connections per device.\n");
1092 blk_mq_update_nr_hw_queues(&nbd->tag_set, config->num_connections);
1093 nbd->task_recv = current;
1095 nbd_parse_flags(nbd);
1097 error = device_create_file(disk_to_dev(nbd->disk), &pid_attr);
1099 dev_err(disk_to_dev(nbd->disk), "device_create_file failed!\n");
1102 set_bit(NBD_HAS_PID_FILE, &config->runtime_flags);
1104 nbd_dev_dbg_init(nbd);
1105 for (i = 0; i < num_connections; i++) {
1106 struct recv_thread_args *args;
1108 args = kzalloc(sizeof(*args), GFP_KERNEL);
1113 sk_set_memalloc(config->socks[i]->sock->sk);
1114 if (nbd->tag_set.timeout)
1115 config->socks[i]->sock->sk->sk_sndtimeo =
1116 nbd->tag_set.timeout;
1117 atomic_inc(&config->recv_threads);
1118 refcount_inc(&nbd->config_refs);
1119 INIT_WORK(&args->work, recv_work);
1122 queue_work(recv_workqueue, &args->work);
1124 nbd_size_update(nbd);
1128 static int nbd_start_device_ioctl(struct nbd_device *nbd, struct block_device *bdev)
1130 struct nbd_config *config = nbd->config;
1133 ret = nbd_start_device(nbd);
1138 bdev->bd_invalidated = 1;
1139 mutex_unlock(&nbd->config_lock);
1140 ret = wait_event_interruptible(config->recv_wq,
1141 atomic_read(&config->recv_threads) == 0);
1144 mutex_lock(&nbd->config_lock);
1145 nbd_bdev_reset(bdev);
1146 /* user requested, ignore socket errors */
1147 if (test_bit(NBD_DISCONNECT_REQUESTED, &config->runtime_flags))
1149 if (test_bit(NBD_TIMEDOUT, &config->runtime_flags))
1154 static void nbd_clear_sock_ioctl(struct nbd_device *nbd,
1155 struct block_device *bdev)
1159 nbd_bdev_reset(bdev);
1160 if (test_and_clear_bit(NBD_HAS_CONFIG_REF,
1161 &nbd->config->runtime_flags))
1162 nbd_config_put(nbd);
1165 /* Must be called with config_lock held */
1166 static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
1167 unsigned int cmd, unsigned long arg)
1169 struct nbd_config *config = nbd->config;
1172 case NBD_DISCONNECT:
1173 return nbd_disconnect(nbd);
1174 case NBD_CLEAR_SOCK:
1175 nbd_clear_sock_ioctl(nbd, bdev);
1178 return nbd_add_socket(nbd, arg, false);
1179 case NBD_SET_BLKSIZE:
1180 nbd_size_set(nbd, arg,
1181 div_s64(config->bytesize, arg));
1184 nbd_size_set(nbd, config->blksize,
1185 div_s64(arg, config->blksize));
1187 case NBD_SET_SIZE_BLOCKS:
1188 nbd_size_set(nbd, config->blksize, arg);
1190 case NBD_SET_TIMEOUT:
1192 nbd->tag_set.timeout = arg * HZ;
1193 blk_queue_rq_timeout(nbd->disk->queue, arg * HZ);
1198 config->flags = arg;
1201 return nbd_start_device_ioctl(nbd, bdev);
1204 * This is for compatibility only. The queue is always cleared
1205 * by NBD_DO_IT or NBD_CLEAR_SOCK.
1208 case NBD_PRINT_DEBUG:
1210 * For compatibility only, we no longer keep a list of
1211 * outstanding requests.
1218 static int nbd_ioctl(struct block_device *bdev, fmode_t mode,
1219 unsigned int cmd, unsigned long arg)
1221 struct nbd_device *nbd = bdev->bd_disk->private_data;
1222 struct nbd_config *config = nbd->config;
1223 int error = -EINVAL;
1225 if (!capable(CAP_SYS_ADMIN))
1228 /* The block layer will pass back some non-nbd ioctls in case we have
1229 * special handling for them, but we don't so just return an error.
1231 if (_IOC_TYPE(cmd) != 0xab)
1234 mutex_lock(&nbd->config_lock);
1236 /* Don't allow ioctl operations on a nbd device that was created with
1237 * netlink, unless it's DISCONNECT or CLEAR_SOCK, which are fine.
1239 if (!test_bit(NBD_BOUND, &config->runtime_flags) ||
1240 (cmd == NBD_DISCONNECT || cmd == NBD_CLEAR_SOCK))
1241 error = __nbd_ioctl(bdev, nbd, cmd, arg);
1243 dev_err(nbd_to_dev(nbd), "Cannot use ioctl interface on a netlink controlled device.\n");
1244 mutex_unlock(&nbd->config_lock);
1248 static struct nbd_config *nbd_alloc_config(void)
1250 struct nbd_config *config;
1252 config = kzalloc(sizeof(struct nbd_config), GFP_NOFS);
1255 atomic_set(&config->recv_threads, 0);
1256 init_waitqueue_head(&config->recv_wq);
1257 init_waitqueue_head(&config->conn_wait);
1258 config->blksize = 1024;
1259 atomic_set(&config->live_connections, 0);
1260 try_module_get(THIS_MODULE);
1264 static int nbd_open(struct block_device *bdev, fmode_t mode)
1266 struct nbd_device *nbd;
1269 mutex_lock(&nbd_index_mutex);
1270 nbd = bdev->bd_disk->private_data;
1275 if (!refcount_inc_not_zero(&nbd->refs)) {
1279 if (!refcount_inc_not_zero(&nbd->config_refs)) {
1280 struct nbd_config *config;
1282 mutex_lock(&nbd->config_lock);
1283 if (refcount_inc_not_zero(&nbd->config_refs)) {
1284 mutex_unlock(&nbd->config_lock);
1287 config = nbd->config = nbd_alloc_config();
1290 mutex_unlock(&nbd->config_lock);
1293 refcount_set(&nbd->config_refs, 1);
1294 refcount_inc(&nbd->refs);
1295 mutex_unlock(&nbd->config_lock);
1296 bdev->bd_invalidated = 1;
1297 } else if (nbd_disconnected(nbd->config)) {
1298 bdev->bd_invalidated = 1;
1301 mutex_unlock(&nbd_index_mutex);
1305 static void nbd_release(struct gendisk *disk, fmode_t mode)
1307 struct nbd_device *nbd = disk->private_data;
1308 nbd_config_put(nbd);
1312 static const struct block_device_operations nbd_fops =
1314 .owner = THIS_MODULE,
1316 .release = nbd_release,
1318 .compat_ioctl = nbd_ioctl,
1321 #if IS_ENABLED(CONFIG_DEBUG_FS)
1323 static int nbd_dbg_tasks_show(struct seq_file *s, void *unused)
1325 struct nbd_device *nbd = s->private;
1328 seq_printf(s, "recv: %d\n", task_pid_nr(nbd->task_recv));
1333 static int nbd_dbg_tasks_open(struct inode *inode, struct file *file)
1335 return single_open(file, nbd_dbg_tasks_show, inode->i_private);
1338 static const struct file_operations nbd_dbg_tasks_ops = {
1339 .open = nbd_dbg_tasks_open,
1341 .llseek = seq_lseek,
1342 .release = single_release,
1345 static int nbd_dbg_flags_show(struct seq_file *s, void *unused)
1347 struct nbd_device *nbd = s->private;
1348 u32 flags = nbd->config->flags;
1350 seq_printf(s, "Hex: 0x%08x\n\n", flags);
1352 seq_puts(s, "Known flags:\n");
1354 if (flags & NBD_FLAG_HAS_FLAGS)
1355 seq_puts(s, "NBD_FLAG_HAS_FLAGS\n");
1356 if (flags & NBD_FLAG_READ_ONLY)
1357 seq_puts(s, "NBD_FLAG_READ_ONLY\n");
1358 if (flags & NBD_FLAG_SEND_FLUSH)
1359 seq_puts(s, "NBD_FLAG_SEND_FLUSH\n");
1360 if (flags & NBD_FLAG_SEND_FUA)
1361 seq_puts(s, "NBD_FLAG_SEND_FUA\n");
1362 if (flags & NBD_FLAG_SEND_TRIM)
1363 seq_puts(s, "NBD_FLAG_SEND_TRIM\n");
1368 static int nbd_dbg_flags_open(struct inode *inode, struct file *file)
1370 return single_open(file, nbd_dbg_flags_show, inode->i_private);
1373 static const struct file_operations nbd_dbg_flags_ops = {
1374 .open = nbd_dbg_flags_open,
1376 .llseek = seq_lseek,
1377 .release = single_release,
1380 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1383 struct nbd_config *config = nbd->config;
1388 dir = debugfs_create_dir(nbd_name(nbd), nbd_dbg_dir);
1390 dev_err(nbd_to_dev(nbd), "Failed to create debugfs dir for '%s'\n",
1394 config->dbg_dir = dir;
1396 debugfs_create_file("tasks", 0444, dir, nbd, &nbd_dbg_tasks_ops);
1397 debugfs_create_u64("size_bytes", 0444, dir, &config->bytesize);
1398 debugfs_create_u32("timeout", 0444, dir, &nbd->tag_set.timeout);
1399 debugfs_create_u64("blocksize", 0444, dir, &config->blksize);
1400 debugfs_create_file("flags", 0444, dir, nbd, &nbd_dbg_flags_ops);
1405 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1407 debugfs_remove_recursive(nbd->config->dbg_dir);
1410 static int nbd_dbg_init(void)
1412 struct dentry *dbg_dir;
1414 dbg_dir = debugfs_create_dir("nbd", NULL);
1418 nbd_dbg_dir = dbg_dir;
1423 static void nbd_dbg_close(void)
1425 debugfs_remove_recursive(nbd_dbg_dir);
1428 #else /* IS_ENABLED(CONFIG_DEBUG_FS) */
1430 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1435 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1439 static int nbd_dbg_init(void)
1444 static void nbd_dbg_close(void)
1450 static int nbd_init_request(struct blk_mq_tag_set *set, struct request *rq,
1451 unsigned int hctx_idx, unsigned int numa_node)
1453 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(rq);
1454 cmd->nbd = set->driver_data;
1458 static const struct blk_mq_ops nbd_mq_ops = {
1459 .queue_rq = nbd_queue_rq,
1460 .complete = nbd_complete_rq,
1461 .init_request = nbd_init_request,
1462 .timeout = nbd_xmit_timeout,
1465 static int nbd_dev_add(int index)
1467 struct nbd_device *nbd;
1468 struct gendisk *disk;
1469 struct request_queue *q;
1472 nbd = kzalloc(sizeof(struct nbd_device), GFP_KERNEL);
1476 disk = alloc_disk(1 << part_shift);
1481 err = idr_alloc(&nbd_index_idr, nbd, index, index + 1,
1486 err = idr_alloc(&nbd_index_idr, nbd, 0, 0, GFP_KERNEL);
1495 nbd->tag_set.ops = &nbd_mq_ops;
1496 nbd->tag_set.nr_hw_queues = 1;
1497 nbd->tag_set.queue_depth = 128;
1498 nbd->tag_set.numa_node = NUMA_NO_NODE;
1499 nbd->tag_set.cmd_size = sizeof(struct nbd_cmd);
1500 nbd->tag_set.flags = BLK_MQ_F_SHOULD_MERGE |
1501 BLK_MQ_F_SG_MERGE | BLK_MQ_F_BLOCKING;
1502 nbd->tag_set.driver_data = nbd;
1504 err = blk_mq_alloc_tag_set(&nbd->tag_set);
1508 q = blk_mq_init_queue(&nbd->tag_set);
1516 * Tell the block layer that we are not a rotational device
1518 blk_queue_flag_set(QUEUE_FLAG_NONROT, disk->queue);
1519 blk_queue_flag_clear(QUEUE_FLAG_ADD_RANDOM, disk->queue);
1520 disk->queue->limits.discard_granularity = 0;
1521 disk->queue->limits.discard_alignment = 0;
1522 blk_queue_max_discard_sectors(disk->queue, 0);
1523 blk_queue_max_segment_size(disk->queue, UINT_MAX);
1524 blk_queue_max_segments(disk->queue, USHRT_MAX);
1525 blk_queue_max_hw_sectors(disk->queue, 65536);
1526 disk->queue->limits.max_sectors = 256;
1528 mutex_init(&nbd->config_lock);
1529 refcount_set(&nbd->config_refs, 0);
1530 refcount_set(&nbd->refs, 1);
1531 INIT_LIST_HEAD(&nbd->list);
1532 disk->major = NBD_MAJOR;
1533 disk->first_minor = index << part_shift;
1534 disk->fops = &nbd_fops;
1535 disk->private_data = nbd;
1536 sprintf(disk->disk_name, "nbd%d", index);
1538 nbd_total_devices++;
1542 blk_mq_free_tag_set(&nbd->tag_set);
1544 idr_remove(&nbd_index_idr, index);
1553 static int find_free_cb(int id, void *ptr, void *data)
1555 struct nbd_device *nbd = ptr;
1556 struct nbd_device **found = data;
1558 if (!refcount_read(&nbd->config_refs)) {
1565 /* Netlink interface. */
1566 static struct nla_policy nbd_attr_policy[NBD_ATTR_MAX + 1] = {
1567 [NBD_ATTR_INDEX] = { .type = NLA_U32 },
1568 [NBD_ATTR_SIZE_BYTES] = { .type = NLA_U64 },
1569 [NBD_ATTR_BLOCK_SIZE_BYTES] = { .type = NLA_U64 },
1570 [NBD_ATTR_TIMEOUT] = { .type = NLA_U64 },
1571 [NBD_ATTR_SERVER_FLAGS] = { .type = NLA_U64 },
1572 [NBD_ATTR_CLIENT_FLAGS] = { .type = NLA_U64 },
1573 [NBD_ATTR_SOCKETS] = { .type = NLA_NESTED},
1574 [NBD_ATTR_DEAD_CONN_TIMEOUT] = { .type = NLA_U64 },
1575 [NBD_ATTR_DEVICE_LIST] = { .type = NLA_NESTED},
1578 static struct nla_policy nbd_sock_policy[NBD_SOCK_MAX + 1] = {
1579 [NBD_SOCK_FD] = { .type = NLA_U32 },
1582 /* We don't use this right now since we don't parse the incoming list, but we
1583 * still want it here so userspace knows what to expect.
1585 static struct nla_policy __attribute__((unused))
1586 nbd_device_policy[NBD_DEVICE_ATTR_MAX + 1] = {
1587 [NBD_DEVICE_INDEX] = { .type = NLA_U32 },
1588 [NBD_DEVICE_CONNECTED] = { .type = NLA_U8 },
1591 static int nbd_genl_connect(struct sk_buff *skb, struct genl_info *info)
1593 struct nbd_device *nbd = NULL;
1594 struct nbd_config *config;
1597 bool put_dev = false;
1599 if (!netlink_capable(skb, CAP_SYS_ADMIN))
1602 if (info->attrs[NBD_ATTR_INDEX])
1603 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1604 if (!info->attrs[NBD_ATTR_SOCKETS]) {
1605 printk(KERN_ERR "nbd: must specify at least one socket\n");
1608 if (!info->attrs[NBD_ATTR_SIZE_BYTES]) {
1609 printk(KERN_ERR "nbd: must specify a size in bytes for the device\n");
1613 mutex_lock(&nbd_index_mutex);
1615 ret = idr_for_each(&nbd_index_idr, &find_free_cb, &nbd);
1618 new_index = nbd_dev_add(-1);
1619 if (new_index < 0) {
1620 mutex_unlock(&nbd_index_mutex);
1621 printk(KERN_ERR "nbd: failed to add new device\n");
1624 nbd = idr_find(&nbd_index_idr, new_index);
1627 nbd = idr_find(&nbd_index_idr, index);
1629 ret = nbd_dev_add(index);
1631 mutex_unlock(&nbd_index_mutex);
1632 printk(KERN_ERR "nbd: failed to add new device\n");
1635 nbd = idr_find(&nbd_index_idr, index);
1639 printk(KERN_ERR "nbd: couldn't find device at index %d\n",
1641 mutex_unlock(&nbd_index_mutex);
1644 if (!refcount_inc_not_zero(&nbd->refs)) {
1645 mutex_unlock(&nbd_index_mutex);
1648 printk(KERN_ERR "nbd: device at index %d is going down\n",
1652 mutex_unlock(&nbd_index_mutex);
1654 mutex_lock(&nbd->config_lock);
1655 if (refcount_read(&nbd->config_refs)) {
1656 mutex_unlock(&nbd->config_lock);
1660 printk(KERN_ERR "nbd: nbd%d already in use\n", index);
1663 if (WARN_ON(nbd->config)) {
1664 mutex_unlock(&nbd->config_lock);
1668 config = nbd->config = nbd_alloc_config();
1670 mutex_unlock(&nbd->config_lock);
1672 printk(KERN_ERR "nbd: couldn't allocate config\n");
1675 refcount_set(&nbd->config_refs, 1);
1676 set_bit(NBD_BOUND, &config->runtime_flags);
1678 if (info->attrs[NBD_ATTR_SIZE_BYTES]) {
1679 u64 bytes = nla_get_u64(info->attrs[NBD_ATTR_SIZE_BYTES]);
1680 nbd_size_set(nbd, config->blksize,
1681 div64_u64(bytes, config->blksize));
1683 if (info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]) {
1685 nla_get_u64(info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]);
1686 nbd_size_set(nbd, bsize, div64_u64(config->bytesize, bsize));
1688 if (info->attrs[NBD_ATTR_TIMEOUT]) {
1689 u64 timeout = nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]);
1690 nbd->tag_set.timeout = timeout * HZ;
1691 blk_queue_rq_timeout(nbd->disk->queue, timeout * HZ);
1693 if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
1694 config->dead_conn_timeout =
1695 nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
1696 config->dead_conn_timeout *= HZ;
1698 if (info->attrs[NBD_ATTR_SERVER_FLAGS])
1700 nla_get_u64(info->attrs[NBD_ATTR_SERVER_FLAGS]);
1701 if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
1702 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
1703 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
1704 set_bit(NBD_DESTROY_ON_DISCONNECT,
1705 &config->runtime_flags);
1710 if (info->attrs[NBD_ATTR_SOCKETS]) {
1711 struct nlattr *attr;
1714 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
1716 struct nlattr *socks[NBD_SOCK_MAX+1];
1718 if (nla_type(attr) != NBD_SOCK_ITEM) {
1719 printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
1723 ret = nla_parse_nested(socks, NBD_SOCK_MAX, attr,
1724 nbd_sock_policy, info->extack);
1726 printk(KERN_ERR "nbd: error processing sock list\n");
1730 if (!socks[NBD_SOCK_FD])
1732 fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
1733 ret = nbd_add_socket(nbd, fd, true);
1738 ret = nbd_start_device(nbd);
1740 mutex_unlock(&nbd->config_lock);
1742 set_bit(NBD_HAS_CONFIG_REF, &config->runtime_flags);
1743 refcount_inc(&nbd->config_refs);
1744 nbd_connect_reply(info, nbd->index);
1746 nbd_config_put(nbd);
1752 static int nbd_genl_disconnect(struct sk_buff *skb, struct genl_info *info)
1754 struct nbd_device *nbd;
1757 if (!netlink_capable(skb, CAP_SYS_ADMIN))
1760 if (!info->attrs[NBD_ATTR_INDEX]) {
1761 printk(KERN_ERR "nbd: must specify an index to disconnect\n");
1764 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1765 mutex_lock(&nbd_index_mutex);
1766 nbd = idr_find(&nbd_index_idr, index);
1768 mutex_unlock(&nbd_index_mutex);
1769 printk(KERN_ERR "nbd: couldn't find device at index %d\n",
1773 if (!refcount_inc_not_zero(&nbd->refs)) {
1774 mutex_unlock(&nbd_index_mutex);
1775 printk(KERN_ERR "nbd: device at index %d is going down\n",
1779 mutex_unlock(&nbd_index_mutex);
1780 if (!refcount_inc_not_zero(&nbd->config_refs)) {
1784 mutex_lock(&nbd->config_lock);
1785 nbd_disconnect(nbd);
1786 nbd_clear_sock(nbd);
1787 mutex_unlock(&nbd->config_lock);
1788 if (test_and_clear_bit(NBD_HAS_CONFIG_REF,
1789 &nbd->config->runtime_flags))
1790 nbd_config_put(nbd);
1791 nbd_config_put(nbd);
1796 static int nbd_genl_reconfigure(struct sk_buff *skb, struct genl_info *info)
1798 struct nbd_device *nbd = NULL;
1799 struct nbd_config *config;
1802 bool put_dev = false;
1804 if (!netlink_capable(skb, CAP_SYS_ADMIN))
1807 if (!info->attrs[NBD_ATTR_INDEX]) {
1808 printk(KERN_ERR "nbd: must specify a device to reconfigure\n");
1811 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1812 mutex_lock(&nbd_index_mutex);
1813 nbd = idr_find(&nbd_index_idr, index);
1815 mutex_unlock(&nbd_index_mutex);
1816 printk(KERN_ERR "nbd: couldn't find a device at index %d\n",
1820 if (!refcount_inc_not_zero(&nbd->refs)) {
1821 mutex_unlock(&nbd_index_mutex);
1822 printk(KERN_ERR "nbd: device at index %d is going down\n",
1826 mutex_unlock(&nbd_index_mutex);
1828 if (!refcount_inc_not_zero(&nbd->config_refs)) {
1829 dev_err(nbd_to_dev(nbd),
1830 "not configured, cannot reconfigure\n");
1835 mutex_lock(&nbd->config_lock);
1836 config = nbd->config;
1837 if (!test_bit(NBD_BOUND, &config->runtime_flags) ||
1839 dev_err(nbd_to_dev(nbd),
1840 "not configured, cannot reconfigure\n");
1844 if (info->attrs[NBD_ATTR_TIMEOUT]) {
1845 u64 timeout = nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]);
1846 nbd->tag_set.timeout = timeout * HZ;
1847 blk_queue_rq_timeout(nbd->disk->queue, timeout * HZ);
1849 if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
1850 config->dead_conn_timeout =
1851 nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
1852 config->dead_conn_timeout *= HZ;
1854 if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
1855 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
1856 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
1857 if (!test_and_set_bit(NBD_DESTROY_ON_DISCONNECT,
1858 &config->runtime_flags))
1861 if (test_and_clear_bit(NBD_DESTROY_ON_DISCONNECT,
1862 &config->runtime_flags))
1863 refcount_inc(&nbd->refs);
1867 if (info->attrs[NBD_ATTR_SOCKETS]) {
1868 struct nlattr *attr;
1871 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
1873 struct nlattr *socks[NBD_SOCK_MAX+1];
1875 if (nla_type(attr) != NBD_SOCK_ITEM) {
1876 printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
1880 ret = nla_parse_nested(socks, NBD_SOCK_MAX, attr,
1881 nbd_sock_policy, info->extack);
1883 printk(KERN_ERR "nbd: error processing sock list\n");
1887 if (!socks[NBD_SOCK_FD])
1889 fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
1890 ret = nbd_reconnect_socket(nbd, fd);
1896 dev_info(nbd_to_dev(nbd), "reconnected socket\n");
1900 mutex_unlock(&nbd->config_lock);
1901 nbd_config_put(nbd);
1908 static const struct genl_ops nbd_connect_genl_ops[] = {
1910 .cmd = NBD_CMD_CONNECT,
1911 .policy = nbd_attr_policy,
1912 .doit = nbd_genl_connect,
1915 .cmd = NBD_CMD_DISCONNECT,
1916 .policy = nbd_attr_policy,
1917 .doit = nbd_genl_disconnect,
1920 .cmd = NBD_CMD_RECONFIGURE,
1921 .policy = nbd_attr_policy,
1922 .doit = nbd_genl_reconfigure,
1925 .cmd = NBD_CMD_STATUS,
1926 .policy = nbd_attr_policy,
1927 .doit = nbd_genl_status,
1931 static const struct genl_multicast_group nbd_mcast_grps[] = {
1932 { .name = NBD_GENL_MCAST_GROUP_NAME, },
1935 static struct genl_family nbd_genl_family __ro_after_init = {
1937 .name = NBD_GENL_FAMILY_NAME,
1938 .version = NBD_GENL_VERSION,
1939 .module = THIS_MODULE,
1940 .ops = nbd_connect_genl_ops,
1941 .n_ops = ARRAY_SIZE(nbd_connect_genl_ops),
1942 .maxattr = NBD_ATTR_MAX,
1943 .mcgrps = nbd_mcast_grps,
1944 .n_mcgrps = ARRAY_SIZE(nbd_mcast_grps),
1947 static int populate_nbd_status(struct nbd_device *nbd, struct sk_buff *reply)
1949 struct nlattr *dev_opt;
1953 /* This is a little racey, but for status it's ok. The
1954 * reason we don't take a ref here is because we can't
1955 * take a ref in the index == -1 case as we would need
1956 * to put under the nbd_index_mutex, which could
1957 * deadlock if we are configured to remove ourselves
1958 * once we're disconnected.
1960 if (refcount_read(&nbd->config_refs))
1962 dev_opt = nla_nest_start(reply, NBD_DEVICE_ITEM);
1965 ret = nla_put_u32(reply, NBD_DEVICE_INDEX, nbd->index);
1968 ret = nla_put_u8(reply, NBD_DEVICE_CONNECTED,
1972 nla_nest_end(reply, dev_opt);
1976 static int status_cb(int id, void *ptr, void *data)
1978 struct nbd_device *nbd = ptr;
1979 return populate_nbd_status(nbd, (struct sk_buff *)data);
1982 static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info)
1984 struct nlattr *dev_list;
1985 struct sk_buff *reply;
1991 if (info->attrs[NBD_ATTR_INDEX])
1992 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1994 mutex_lock(&nbd_index_mutex);
1996 msg_size = nla_total_size(nla_attr_size(sizeof(u32)) +
1997 nla_attr_size(sizeof(u8)));
1998 msg_size *= (index == -1) ? nbd_total_devices : 1;
2000 reply = genlmsg_new(msg_size, GFP_KERNEL);
2003 reply_head = genlmsg_put_reply(reply, info, &nbd_genl_family, 0,
2010 dev_list = nla_nest_start(reply, NBD_ATTR_DEVICE_LIST);
2012 ret = idr_for_each(&nbd_index_idr, &status_cb, reply);
2018 struct nbd_device *nbd;
2019 nbd = idr_find(&nbd_index_idr, index);
2021 ret = populate_nbd_status(nbd, reply);
2028 nla_nest_end(reply, dev_list);
2029 genlmsg_end(reply, reply_head);
2030 genlmsg_reply(reply, info);
2033 mutex_unlock(&nbd_index_mutex);
2037 static void nbd_connect_reply(struct genl_info *info, int index)
2039 struct sk_buff *skb;
2043 skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2046 msg_head = genlmsg_put_reply(skb, info, &nbd_genl_family, 0,
2052 ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2057 genlmsg_end(skb, msg_head);
2058 genlmsg_reply(skb, info);
2061 static void nbd_mcast_index(int index)
2063 struct sk_buff *skb;
2067 skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2070 msg_head = genlmsg_put(skb, 0, 0, &nbd_genl_family, 0,
2076 ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2081 genlmsg_end(skb, msg_head);
2082 genlmsg_multicast(&nbd_genl_family, skb, 0, 0, GFP_KERNEL);
2085 static void nbd_dead_link_work(struct work_struct *work)
2087 struct link_dead_args *args = container_of(work, struct link_dead_args,
2089 nbd_mcast_index(args->index);
2093 static int __init nbd_init(void)
2097 BUILD_BUG_ON(sizeof(struct nbd_request) != 28);
2100 printk(KERN_ERR "nbd: max_part must be >= 0\n");
2106 part_shift = fls(max_part);
2109 * Adjust max_part according to part_shift as it is exported
2110 * to user space so that user can know the max number of
2111 * partition kernel should be able to manage.
2113 * Note that -1 is required because partition 0 is reserved
2114 * for the whole disk.
2116 max_part = (1UL << part_shift) - 1;
2119 if ((1UL << part_shift) > DISK_MAX_PARTS)
2122 if (nbds_max > 1UL << (MINORBITS - part_shift))
2124 recv_workqueue = alloc_workqueue("knbd-recv",
2125 WQ_MEM_RECLAIM | WQ_HIGHPRI |
2127 if (!recv_workqueue)
2130 if (register_blkdev(NBD_MAJOR, "nbd")) {
2131 destroy_workqueue(recv_workqueue);
2135 if (genl_register_family(&nbd_genl_family)) {
2136 unregister_blkdev(NBD_MAJOR, "nbd");
2137 destroy_workqueue(recv_workqueue);
2142 mutex_lock(&nbd_index_mutex);
2143 for (i = 0; i < nbds_max; i++)
2145 mutex_unlock(&nbd_index_mutex);
2149 static int nbd_exit_cb(int id, void *ptr, void *data)
2151 struct list_head *list = (struct list_head *)data;
2152 struct nbd_device *nbd = ptr;
2154 list_add_tail(&nbd->list, list);
2158 static void __exit nbd_cleanup(void)
2160 struct nbd_device *nbd;
2161 LIST_HEAD(del_list);
2165 mutex_lock(&nbd_index_mutex);
2166 idr_for_each(&nbd_index_idr, &nbd_exit_cb, &del_list);
2167 mutex_unlock(&nbd_index_mutex);
2169 while (!list_empty(&del_list)) {
2170 nbd = list_first_entry(&del_list, struct nbd_device, list);
2171 list_del_init(&nbd->list);
2172 if (refcount_read(&nbd->refs) != 1)
2173 printk(KERN_ERR "nbd: possibly leaking a device\n");
2177 idr_destroy(&nbd_index_idr);
2178 genl_unregister_family(&nbd_genl_family);
2179 destroy_workqueue(recv_workqueue);
2180 unregister_blkdev(NBD_MAJOR, "nbd");
2183 module_init(nbd_init);
2184 module_exit(nbd_cleanup);
2186 MODULE_DESCRIPTION("Network Block Device");
2187 MODULE_LICENSE("GPL");
2189 module_param(nbds_max, int, 0444);
2190 MODULE_PARM_DESC(nbds_max, "number of network block devices to initialize (default: 16)");
2191 module_param(max_part, int, 0444);
2192 MODULE_PARM_DESC(max_part, "number of partitions per device (default: 16)");