Linux 4.19.133
[linux/fpc-iii.git] / drivers / block / nbd.c
blobd7c7232e438c93d2c510e8c2aa99f82b60e71db4
1 /*
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.
6 *
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>
22 #include <linux/fs.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>
33 #include <net/sock.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;
51 struct nbd_sock {
52 struct socket *sock;
53 struct mutex tx_lock;
54 struct request *pending;
55 int sent;
56 bool dead;
57 int fallback_index;
58 int cookie;
61 struct recv_thread_args {
62 struct work_struct work;
63 struct nbd_device *nbd;
64 int index;
67 struct link_dead_args {
68 struct work_struct work;
69 int index;
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
77 #define NBD_BOUND 5
78 #define NBD_DESTROY_ON_DISCONNECT 6
79 #define NBD_DISCONNECT_ON_CLOSE 7
81 struct nbd_config {
82 u32 flags;
83 unsigned long runtime_flags;
84 u64 dead_conn_timeout;
86 struct nbd_sock **socks;
87 int num_connections;
88 atomic_t live_connections;
89 wait_queue_head_t conn_wait;
91 atomic_t recv_threads;
92 wait_queue_head_t recv_wq;
93 loff_t blksize;
94 loff_t bytesize;
95 #if IS_ENABLED(CONFIG_DEBUG_FS)
96 struct dentry *dbg_dir;
97 #endif
100 struct nbd_device {
101 struct blk_mq_tag_set tag_set;
103 int index;
104 refcount_t config_refs;
105 refcount_t refs;
106 struct nbd_config *config;
107 struct mutex config_lock;
108 struct gendisk *disk;
109 struct workqueue_struct *recv_workq;
111 struct list_head list;
112 struct task_struct *task_recv;
113 struct task_struct *task_setup;
116 #define NBD_CMD_REQUEUED 1
118 struct nbd_cmd {
119 struct nbd_device *nbd;
120 struct mutex lock;
121 int index;
122 int cookie;
123 blk_status_t status;
124 unsigned long flags;
125 u32 cmd_cookie;
128 #if IS_ENABLED(CONFIG_DEBUG_FS)
129 static struct dentry *nbd_dbg_dir;
130 #endif
132 #define nbd_name(nbd) ((nbd)->disk->disk_name)
134 #define NBD_MAGIC 0x68797548
136 #define NBD_DEF_BLKSIZE 1024
138 static unsigned int nbds_max = 16;
139 static int max_part = 16;
140 static int part_shift;
142 static int nbd_dev_dbg_init(struct nbd_device *nbd);
143 static void nbd_dev_dbg_close(struct nbd_device *nbd);
144 static void nbd_config_put(struct nbd_device *nbd);
145 static void nbd_connect_reply(struct genl_info *info, int index);
146 static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info);
147 static void nbd_dead_link_work(struct work_struct *work);
148 static void nbd_disconnect_and_put(struct nbd_device *nbd);
150 static inline struct device *nbd_to_dev(struct nbd_device *nbd)
152 return disk_to_dev(nbd->disk);
155 static void nbd_requeue_cmd(struct nbd_cmd *cmd)
157 struct request *req = blk_mq_rq_from_pdu(cmd);
159 if (!test_and_set_bit(NBD_CMD_REQUEUED, &cmd->flags))
160 blk_mq_requeue_request(req, true);
163 #define NBD_COOKIE_BITS 32
165 static u64 nbd_cmd_handle(struct nbd_cmd *cmd)
167 struct request *req = blk_mq_rq_from_pdu(cmd);
168 u32 tag = blk_mq_unique_tag(req);
169 u64 cookie = cmd->cmd_cookie;
171 return (cookie << NBD_COOKIE_BITS) | tag;
174 static u32 nbd_handle_to_tag(u64 handle)
176 return (u32)handle;
179 static u32 nbd_handle_to_cookie(u64 handle)
181 return (u32)(handle >> NBD_COOKIE_BITS);
184 static const char *nbdcmd_to_ascii(int cmd)
186 switch (cmd) {
187 case NBD_CMD_READ: return "read";
188 case NBD_CMD_WRITE: return "write";
189 case NBD_CMD_DISC: return "disconnect";
190 case NBD_CMD_FLUSH: return "flush";
191 case NBD_CMD_TRIM: return "trim/discard";
193 return "invalid";
196 static ssize_t pid_show(struct device *dev,
197 struct device_attribute *attr, char *buf)
199 struct gendisk *disk = dev_to_disk(dev);
200 struct nbd_device *nbd = (struct nbd_device *)disk->private_data;
202 return sprintf(buf, "%d\n", task_pid_nr(nbd->task_recv));
205 static const struct device_attribute pid_attr = {
206 .attr = { .name = "pid", .mode = 0444},
207 .show = pid_show,
210 static void nbd_dev_remove(struct nbd_device *nbd)
212 struct gendisk *disk = nbd->disk;
213 struct request_queue *q;
215 if (disk) {
216 q = disk->queue;
217 del_gendisk(disk);
218 blk_cleanup_queue(q);
219 blk_mq_free_tag_set(&nbd->tag_set);
220 disk->private_data = NULL;
221 put_disk(disk);
223 kfree(nbd);
226 static void nbd_put(struct nbd_device *nbd)
228 if (refcount_dec_and_mutex_lock(&nbd->refs,
229 &nbd_index_mutex)) {
230 idr_remove(&nbd_index_idr, nbd->index);
231 nbd_dev_remove(nbd);
232 mutex_unlock(&nbd_index_mutex);
236 static int nbd_disconnected(struct nbd_config *config)
238 return test_bit(NBD_DISCONNECTED, &config->runtime_flags) ||
239 test_bit(NBD_DISCONNECT_REQUESTED, &config->runtime_flags);
242 static void nbd_mark_nsock_dead(struct nbd_device *nbd, struct nbd_sock *nsock,
243 int notify)
245 if (!nsock->dead && notify && !nbd_disconnected(nbd->config)) {
246 struct link_dead_args *args;
247 args = kmalloc(sizeof(struct link_dead_args), GFP_NOIO);
248 if (args) {
249 INIT_WORK(&args->work, nbd_dead_link_work);
250 args->index = nbd->index;
251 queue_work(system_wq, &args->work);
254 if (!nsock->dead) {
255 kernel_sock_shutdown(nsock->sock, SHUT_RDWR);
256 if (atomic_dec_return(&nbd->config->live_connections) == 0) {
257 if (test_and_clear_bit(NBD_DISCONNECT_REQUESTED,
258 &nbd->config->runtime_flags)) {
259 set_bit(NBD_DISCONNECTED,
260 &nbd->config->runtime_flags);
261 dev_info(nbd_to_dev(nbd),
262 "Disconnected due to user request.\n");
266 nsock->dead = true;
267 nsock->pending = NULL;
268 nsock->sent = 0;
271 static void nbd_size_clear(struct nbd_device *nbd)
273 if (nbd->config->bytesize) {
274 set_capacity(nbd->disk, 0);
275 kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
279 static void nbd_size_update(struct nbd_device *nbd)
281 struct nbd_config *config = nbd->config;
282 struct block_device *bdev = bdget_disk(nbd->disk, 0);
284 if (config->flags & NBD_FLAG_SEND_TRIM) {
285 nbd->disk->queue->limits.discard_granularity = config->blksize;
286 nbd->disk->queue->limits.discard_alignment = config->blksize;
287 blk_queue_max_discard_sectors(nbd->disk->queue, UINT_MAX);
289 blk_queue_logical_block_size(nbd->disk->queue, config->blksize);
290 blk_queue_physical_block_size(nbd->disk->queue, config->blksize);
291 set_capacity(nbd->disk, config->bytesize >> 9);
292 if (bdev) {
293 if (bdev->bd_disk) {
294 bd_set_size(bdev, config->bytesize);
295 set_blocksize(bdev, config->blksize);
296 } else
297 bdev->bd_invalidated = 1;
298 bdput(bdev);
300 kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
303 static void nbd_size_set(struct nbd_device *nbd, loff_t blocksize,
304 loff_t nr_blocks)
306 struct nbd_config *config = nbd->config;
307 config->blksize = blocksize;
308 config->bytesize = blocksize * nr_blocks;
309 if (nbd->task_recv != NULL)
310 nbd_size_update(nbd);
313 static void nbd_complete_rq(struct request *req)
315 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
317 dev_dbg(nbd_to_dev(cmd->nbd), "request %p: %s\n", req,
318 cmd->status ? "failed" : "done");
320 blk_mq_end_request(req, cmd->status);
324 * Forcibly shutdown the socket causing all listeners to error
326 static void sock_shutdown(struct nbd_device *nbd)
328 struct nbd_config *config = nbd->config;
329 int i;
331 if (config->num_connections == 0)
332 return;
333 if (test_and_set_bit(NBD_DISCONNECTED, &config->runtime_flags))
334 return;
336 for (i = 0; i < config->num_connections; i++) {
337 struct nbd_sock *nsock = config->socks[i];
338 mutex_lock(&nsock->tx_lock);
339 nbd_mark_nsock_dead(nbd, nsock, 0);
340 mutex_unlock(&nsock->tx_lock);
342 dev_warn(disk_to_dev(nbd->disk), "shutting down sockets\n");
345 static enum blk_eh_timer_return nbd_xmit_timeout(struct request *req,
346 bool reserved)
348 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
349 struct nbd_device *nbd = cmd->nbd;
350 struct nbd_config *config;
352 if (!mutex_trylock(&cmd->lock))
353 return BLK_EH_RESET_TIMER;
355 if (!refcount_inc_not_zero(&nbd->config_refs)) {
356 cmd->status = BLK_STS_TIMEOUT;
357 mutex_unlock(&cmd->lock);
358 goto done;
360 config = nbd->config;
362 if (config->num_connections > 1) {
363 dev_err_ratelimited(nbd_to_dev(nbd),
364 "Connection timed out, retrying (%d/%d alive)\n",
365 atomic_read(&config->live_connections),
366 config->num_connections);
368 * Hooray we have more connections, requeue this IO, the submit
369 * path will put it on a real connection.
371 if (config->socks && config->num_connections > 1) {
372 if (cmd->index < config->num_connections) {
373 struct nbd_sock *nsock =
374 config->socks[cmd->index];
375 mutex_lock(&nsock->tx_lock);
376 /* We can have multiple outstanding requests, so
377 * we don't want to mark the nsock dead if we've
378 * already reconnected with a new socket, so
379 * only mark it dead if its the same socket we
380 * were sent out on.
382 if (cmd->cookie == nsock->cookie)
383 nbd_mark_nsock_dead(nbd, nsock, 1);
384 mutex_unlock(&nsock->tx_lock);
386 mutex_unlock(&cmd->lock);
387 nbd_requeue_cmd(cmd);
388 nbd_config_put(nbd);
389 return BLK_EH_DONE;
391 } else {
392 dev_err_ratelimited(nbd_to_dev(nbd),
393 "Connection timed out\n");
395 set_bit(NBD_TIMEDOUT, &config->runtime_flags);
396 cmd->status = BLK_STS_IOERR;
397 mutex_unlock(&cmd->lock);
398 sock_shutdown(nbd);
399 nbd_config_put(nbd);
400 done:
401 blk_mq_complete_request(req);
402 return BLK_EH_DONE;
406 * Send or receive packet.
408 static int sock_xmit(struct nbd_device *nbd, int index, int send,
409 struct iov_iter *iter, int msg_flags, int *sent)
411 struct nbd_config *config = nbd->config;
412 struct socket *sock = config->socks[index]->sock;
413 int result;
414 struct msghdr msg;
415 unsigned int noreclaim_flag;
417 if (unlikely(!sock)) {
418 dev_err_ratelimited(disk_to_dev(nbd->disk),
419 "Attempted %s on closed socket in sock_xmit\n",
420 (send ? "send" : "recv"));
421 return -EINVAL;
424 msg.msg_iter = *iter;
426 noreclaim_flag = memalloc_noreclaim_save();
427 do {
428 sock->sk->sk_allocation = GFP_NOIO | __GFP_MEMALLOC;
429 msg.msg_name = NULL;
430 msg.msg_namelen = 0;
431 msg.msg_control = NULL;
432 msg.msg_controllen = 0;
433 msg.msg_flags = msg_flags | MSG_NOSIGNAL;
435 if (send)
436 result = sock_sendmsg(sock, &msg);
437 else
438 result = sock_recvmsg(sock, &msg, msg.msg_flags);
440 if (result <= 0) {
441 if (result == 0)
442 result = -EPIPE; /* short read */
443 break;
445 if (sent)
446 *sent += result;
447 } while (msg_data_left(&msg));
449 memalloc_noreclaim_restore(noreclaim_flag);
451 return result;
455 * Different settings for sk->sk_sndtimeo can result in different return values
456 * if there is a signal pending when we enter sendmsg, because reasons?
458 static inline int was_interrupted(int result)
460 return result == -ERESTARTSYS || result == -EINTR;
463 /* always call with the tx_lock held */
464 static int nbd_send_cmd(struct nbd_device *nbd, struct nbd_cmd *cmd, int index)
466 struct request *req = blk_mq_rq_from_pdu(cmd);
467 struct nbd_config *config = nbd->config;
468 struct nbd_sock *nsock = config->socks[index];
469 int result;
470 struct nbd_request request = {.magic = htonl(NBD_REQUEST_MAGIC)};
471 struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
472 struct iov_iter from;
473 unsigned long size = blk_rq_bytes(req);
474 struct bio *bio;
475 u64 handle;
476 u32 type;
477 u32 nbd_cmd_flags = 0;
478 int sent = nsock->sent, skip = 0;
480 iov_iter_kvec(&from, WRITE | ITER_KVEC, &iov, 1, sizeof(request));
482 switch (req_op(req)) {
483 case REQ_OP_DISCARD:
484 type = NBD_CMD_TRIM;
485 break;
486 case REQ_OP_FLUSH:
487 type = NBD_CMD_FLUSH;
488 break;
489 case REQ_OP_WRITE:
490 type = NBD_CMD_WRITE;
491 break;
492 case REQ_OP_READ:
493 type = NBD_CMD_READ;
494 break;
495 default:
496 return -EIO;
499 if (rq_data_dir(req) == WRITE &&
500 (config->flags & NBD_FLAG_READ_ONLY)) {
501 dev_err_ratelimited(disk_to_dev(nbd->disk),
502 "Write on read-only\n");
503 return -EIO;
506 if (req->cmd_flags & REQ_FUA)
507 nbd_cmd_flags |= NBD_CMD_FLAG_FUA;
509 /* We did a partial send previously, and we at least sent the whole
510 * request struct, so just go and send the rest of the pages in the
511 * request.
513 if (sent) {
514 if (sent >= sizeof(request)) {
515 skip = sent - sizeof(request);
516 goto send_pages;
518 iov_iter_advance(&from, sent);
519 } else {
520 cmd->cmd_cookie++;
522 cmd->index = index;
523 cmd->cookie = nsock->cookie;
524 request.type = htonl(type | nbd_cmd_flags);
525 if (type != NBD_CMD_FLUSH) {
526 request.from = cpu_to_be64((u64)blk_rq_pos(req) << 9);
527 request.len = htonl(size);
529 handle = nbd_cmd_handle(cmd);
530 memcpy(request.handle, &handle, sizeof(handle));
532 dev_dbg(nbd_to_dev(nbd), "request %p: sending control (%s@%llu,%uB)\n",
533 req, nbdcmd_to_ascii(type),
534 (unsigned long long)blk_rq_pos(req) << 9, blk_rq_bytes(req));
535 result = sock_xmit(nbd, index, 1, &from,
536 (type == NBD_CMD_WRITE) ? MSG_MORE : 0, &sent);
537 if (result <= 0) {
538 if (was_interrupted(result)) {
539 /* If we havne't sent anything we can just return BUSY,
540 * however if we have sent something we need to make
541 * sure we only allow this req to be sent until we are
542 * completely done.
544 if (sent) {
545 nsock->pending = req;
546 nsock->sent = sent;
548 set_bit(NBD_CMD_REQUEUED, &cmd->flags);
549 return BLK_STS_RESOURCE;
551 dev_err_ratelimited(disk_to_dev(nbd->disk),
552 "Send control failed (result %d)\n", result);
553 return -EAGAIN;
555 send_pages:
556 if (type != NBD_CMD_WRITE)
557 goto out;
559 bio = req->bio;
560 while (bio) {
561 struct bio *next = bio->bi_next;
562 struct bvec_iter iter;
563 struct bio_vec bvec;
565 bio_for_each_segment(bvec, bio, iter) {
566 bool is_last = !next && bio_iter_last(bvec, iter);
567 int flags = is_last ? 0 : MSG_MORE;
569 dev_dbg(nbd_to_dev(nbd), "request %p: sending %d bytes data\n",
570 req, bvec.bv_len);
571 iov_iter_bvec(&from, ITER_BVEC | WRITE,
572 &bvec, 1, bvec.bv_len);
573 if (skip) {
574 if (skip >= iov_iter_count(&from)) {
575 skip -= iov_iter_count(&from);
576 continue;
578 iov_iter_advance(&from, skip);
579 skip = 0;
581 result = sock_xmit(nbd, index, 1, &from, flags, &sent);
582 if (result <= 0) {
583 if (was_interrupted(result)) {
584 /* We've already sent the header, we
585 * have no choice but to set pending and
586 * return BUSY.
588 nsock->pending = req;
589 nsock->sent = sent;
590 set_bit(NBD_CMD_REQUEUED, &cmd->flags);
591 return BLK_STS_RESOURCE;
593 dev_err(disk_to_dev(nbd->disk),
594 "Send data failed (result %d)\n",
595 result);
596 return -EAGAIN;
599 * The completion might already have come in,
600 * so break for the last one instead of letting
601 * the iterator do it. This prevents use-after-free
602 * of the bio.
604 if (is_last)
605 break;
607 bio = next;
609 out:
610 nsock->pending = NULL;
611 nsock->sent = 0;
612 return 0;
615 /* NULL returned = something went wrong, inform userspace */
616 static struct nbd_cmd *nbd_read_stat(struct nbd_device *nbd, int index)
618 struct nbd_config *config = nbd->config;
619 int result;
620 struct nbd_reply reply;
621 struct nbd_cmd *cmd;
622 struct request *req = NULL;
623 u64 handle;
624 u16 hwq;
625 u32 tag;
626 struct kvec iov = {.iov_base = &reply, .iov_len = sizeof(reply)};
627 struct iov_iter to;
628 int ret = 0;
630 reply.magic = 0;
631 iov_iter_kvec(&to, READ | ITER_KVEC, &iov, 1, sizeof(reply));
632 result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
633 if (result <= 0) {
634 if (!nbd_disconnected(config))
635 dev_err(disk_to_dev(nbd->disk),
636 "Receive control failed (result %d)\n", result);
637 return ERR_PTR(result);
640 if (ntohl(reply.magic) != NBD_REPLY_MAGIC) {
641 dev_err(disk_to_dev(nbd->disk), "Wrong magic (0x%lx)\n",
642 (unsigned long)ntohl(reply.magic));
643 return ERR_PTR(-EPROTO);
646 memcpy(&handle, reply.handle, sizeof(handle));
647 tag = nbd_handle_to_tag(handle);
648 hwq = blk_mq_unique_tag_to_hwq(tag);
649 if (hwq < nbd->tag_set.nr_hw_queues)
650 req = blk_mq_tag_to_rq(nbd->tag_set.tags[hwq],
651 blk_mq_unique_tag_to_tag(tag));
652 if (!req || !blk_mq_request_started(req)) {
653 dev_err(disk_to_dev(nbd->disk), "Unexpected reply (%d) %p\n",
654 tag, req);
655 return ERR_PTR(-ENOENT);
657 cmd = blk_mq_rq_to_pdu(req);
659 mutex_lock(&cmd->lock);
660 if (cmd->cmd_cookie != nbd_handle_to_cookie(handle)) {
661 dev_err(disk_to_dev(nbd->disk), "Double reply on req %p, cmd_cookie %u, handle cookie %u\n",
662 req, cmd->cmd_cookie, nbd_handle_to_cookie(handle));
663 ret = -ENOENT;
664 goto out;
666 if (cmd->status != BLK_STS_OK) {
667 dev_err(disk_to_dev(nbd->disk), "Command already handled %p\n",
668 req);
669 ret = -ENOENT;
670 goto out;
672 if (test_bit(NBD_CMD_REQUEUED, &cmd->flags)) {
673 dev_err(disk_to_dev(nbd->disk), "Raced with timeout on req %p\n",
674 req);
675 ret = -ENOENT;
676 goto out;
678 if (ntohl(reply.error)) {
679 dev_err(disk_to_dev(nbd->disk), "Other side returned error (%d)\n",
680 ntohl(reply.error));
681 cmd->status = BLK_STS_IOERR;
682 goto out;
685 dev_dbg(nbd_to_dev(nbd), "request %p: got reply\n", req);
686 if (rq_data_dir(req) != WRITE) {
687 struct req_iterator iter;
688 struct bio_vec bvec;
690 rq_for_each_segment(bvec, req, iter) {
691 iov_iter_bvec(&to, ITER_BVEC | READ,
692 &bvec, 1, bvec.bv_len);
693 result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
694 if (result <= 0) {
695 dev_err(disk_to_dev(nbd->disk), "Receive data failed (result %d)\n",
696 result);
698 * If we've disconnected or we only have 1
699 * connection then we need to make sure we
700 * complete this request, otherwise error out
701 * and let the timeout stuff handle resubmitting
702 * this request onto another connection.
704 if (nbd_disconnected(config) ||
705 config->num_connections <= 1) {
706 cmd->status = BLK_STS_IOERR;
707 goto out;
709 ret = -EIO;
710 goto out;
712 dev_dbg(nbd_to_dev(nbd), "request %p: got %d bytes data\n",
713 req, bvec.bv_len);
716 out:
717 mutex_unlock(&cmd->lock);
718 return ret ? ERR_PTR(ret) : cmd;
721 static void recv_work(struct work_struct *work)
723 struct recv_thread_args *args = container_of(work,
724 struct recv_thread_args,
725 work);
726 struct nbd_device *nbd = args->nbd;
727 struct nbd_config *config = nbd->config;
728 struct nbd_cmd *cmd;
730 while (1) {
731 cmd = nbd_read_stat(nbd, args->index);
732 if (IS_ERR(cmd)) {
733 struct nbd_sock *nsock = config->socks[args->index];
735 mutex_lock(&nsock->tx_lock);
736 nbd_mark_nsock_dead(nbd, nsock, 1);
737 mutex_unlock(&nsock->tx_lock);
738 break;
741 blk_mq_complete_request(blk_mq_rq_from_pdu(cmd));
743 atomic_dec(&config->recv_threads);
744 wake_up(&config->recv_wq);
745 nbd_config_put(nbd);
746 kfree(args);
749 static void nbd_clear_req(struct request *req, void *data, bool reserved)
751 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
753 mutex_lock(&cmd->lock);
754 cmd->status = BLK_STS_IOERR;
755 mutex_unlock(&cmd->lock);
757 blk_mq_complete_request(req);
760 static void nbd_clear_que(struct nbd_device *nbd)
762 blk_mq_quiesce_queue(nbd->disk->queue);
763 blk_mq_tagset_busy_iter(&nbd->tag_set, nbd_clear_req, NULL);
764 blk_mq_unquiesce_queue(nbd->disk->queue);
765 dev_dbg(disk_to_dev(nbd->disk), "queue cleared\n");
768 static int find_fallback(struct nbd_device *nbd, int index)
770 struct nbd_config *config = nbd->config;
771 int new_index = -1;
772 struct nbd_sock *nsock = config->socks[index];
773 int fallback = nsock->fallback_index;
775 if (test_bit(NBD_DISCONNECTED, &config->runtime_flags))
776 return new_index;
778 if (config->num_connections <= 1) {
779 dev_err_ratelimited(disk_to_dev(nbd->disk),
780 "Attempted send on invalid socket\n");
781 return new_index;
784 if (fallback >= 0 && fallback < config->num_connections &&
785 !config->socks[fallback]->dead)
786 return fallback;
788 if (nsock->fallback_index < 0 ||
789 nsock->fallback_index >= config->num_connections ||
790 config->socks[nsock->fallback_index]->dead) {
791 int i;
792 for (i = 0; i < config->num_connections; i++) {
793 if (i == index)
794 continue;
795 if (!config->socks[i]->dead) {
796 new_index = i;
797 break;
800 nsock->fallback_index = new_index;
801 if (new_index < 0) {
802 dev_err_ratelimited(disk_to_dev(nbd->disk),
803 "Dead connection, failed to find a fallback\n");
804 return new_index;
807 new_index = nsock->fallback_index;
808 return new_index;
811 static int wait_for_reconnect(struct nbd_device *nbd)
813 struct nbd_config *config = nbd->config;
814 if (!config->dead_conn_timeout)
815 return 0;
816 if (test_bit(NBD_DISCONNECTED, &config->runtime_flags))
817 return 0;
818 return wait_event_timeout(config->conn_wait,
819 atomic_read(&config->live_connections) > 0,
820 config->dead_conn_timeout) > 0;
823 static int nbd_handle_cmd(struct nbd_cmd *cmd, int index)
825 struct request *req = blk_mq_rq_from_pdu(cmd);
826 struct nbd_device *nbd = cmd->nbd;
827 struct nbd_config *config;
828 struct nbd_sock *nsock;
829 int ret;
831 if (!refcount_inc_not_zero(&nbd->config_refs)) {
832 dev_err_ratelimited(disk_to_dev(nbd->disk),
833 "Socks array is empty\n");
834 blk_mq_start_request(req);
835 return -EINVAL;
837 config = nbd->config;
839 if (index >= config->num_connections) {
840 dev_err_ratelimited(disk_to_dev(nbd->disk),
841 "Attempted send on invalid socket\n");
842 nbd_config_put(nbd);
843 blk_mq_start_request(req);
844 return -EINVAL;
846 cmd->status = BLK_STS_OK;
847 again:
848 nsock = config->socks[index];
849 mutex_lock(&nsock->tx_lock);
850 if (nsock->dead) {
851 int old_index = index;
852 index = find_fallback(nbd, index);
853 mutex_unlock(&nsock->tx_lock);
854 if (index < 0) {
855 if (wait_for_reconnect(nbd)) {
856 index = old_index;
857 goto again;
859 /* All the sockets should already be down at this point,
860 * we just want to make sure that DISCONNECTED is set so
861 * any requests that come in that were queue'ed waiting
862 * for the reconnect timer don't trigger the timer again
863 * and instead just error out.
865 sock_shutdown(nbd);
866 nbd_config_put(nbd);
867 blk_mq_start_request(req);
868 return -EIO;
870 goto again;
873 /* Handle the case that we have a pending request that was partially
874 * transmitted that _has_ to be serviced first. We need to call requeue
875 * here so that it gets put _after_ the request that is already on the
876 * dispatch list.
878 blk_mq_start_request(req);
879 if (unlikely(nsock->pending && nsock->pending != req)) {
880 nbd_requeue_cmd(cmd);
881 ret = 0;
882 goto out;
885 * Some failures are related to the link going down, so anything that
886 * returns EAGAIN can be retried on a different socket.
888 ret = nbd_send_cmd(nbd, cmd, index);
889 if (ret == -EAGAIN) {
890 dev_err_ratelimited(disk_to_dev(nbd->disk),
891 "Request send failed, requeueing\n");
892 nbd_mark_nsock_dead(nbd, nsock, 1);
893 nbd_requeue_cmd(cmd);
894 ret = 0;
896 out:
897 mutex_unlock(&nsock->tx_lock);
898 nbd_config_put(nbd);
899 return ret;
902 static blk_status_t nbd_queue_rq(struct blk_mq_hw_ctx *hctx,
903 const struct blk_mq_queue_data *bd)
905 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(bd->rq);
906 int ret;
909 * Since we look at the bio's to send the request over the network we
910 * need to make sure the completion work doesn't mark this request done
911 * before we are done doing our send. This keeps us from dereferencing
912 * freed data if we have particularly fast completions (ie we get the
913 * completion before we exit sock_xmit on the last bvec) or in the case
914 * that the server is misbehaving (or there was an error) before we're
915 * done sending everything over the wire.
917 mutex_lock(&cmd->lock);
918 clear_bit(NBD_CMD_REQUEUED, &cmd->flags);
920 /* We can be called directly from the user space process, which means we
921 * could possibly have signals pending so our sendmsg will fail. In
922 * this case we need to return that we are busy, otherwise error out as
923 * appropriate.
925 ret = nbd_handle_cmd(cmd, hctx->queue_num);
926 if (ret < 0)
927 ret = BLK_STS_IOERR;
928 else if (!ret)
929 ret = BLK_STS_OK;
930 mutex_unlock(&cmd->lock);
932 return ret;
935 static struct socket *nbd_get_socket(struct nbd_device *nbd, unsigned long fd,
936 int *err)
938 struct socket *sock;
940 *err = 0;
941 sock = sockfd_lookup(fd, err);
942 if (!sock)
943 return NULL;
945 if (sock->ops->shutdown == sock_no_shutdown) {
946 dev_err(disk_to_dev(nbd->disk), "Unsupported socket: shutdown callout must be supported.\n");
947 *err = -EINVAL;
948 sockfd_put(sock);
949 return NULL;
952 return sock;
955 static int nbd_add_socket(struct nbd_device *nbd, unsigned long arg,
956 bool netlink)
958 struct nbd_config *config = nbd->config;
959 struct socket *sock;
960 struct nbd_sock **socks;
961 struct nbd_sock *nsock;
962 int err;
964 sock = nbd_get_socket(nbd, arg, &err);
965 if (!sock)
966 return err;
968 if (!netlink && !nbd->task_setup &&
969 !test_bit(NBD_BOUND, &config->runtime_flags))
970 nbd->task_setup = current;
972 if (!netlink &&
973 (nbd->task_setup != current ||
974 test_bit(NBD_BOUND, &config->runtime_flags))) {
975 dev_err(disk_to_dev(nbd->disk),
976 "Device being setup by another task");
977 err = -EBUSY;
978 goto put_socket;
981 nsock = kzalloc(sizeof(*nsock), GFP_KERNEL);
982 if (!nsock) {
983 err = -ENOMEM;
984 goto put_socket;
987 socks = krealloc(config->socks, (config->num_connections + 1) *
988 sizeof(struct nbd_sock *), GFP_KERNEL);
989 if (!socks) {
990 kfree(nsock);
991 err = -ENOMEM;
992 goto put_socket;
995 config->socks = socks;
997 nsock->fallback_index = -1;
998 nsock->dead = false;
999 mutex_init(&nsock->tx_lock);
1000 nsock->sock = sock;
1001 nsock->pending = NULL;
1002 nsock->sent = 0;
1003 nsock->cookie = 0;
1004 socks[config->num_connections++] = nsock;
1005 atomic_inc(&config->live_connections);
1007 return 0;
1009 put_socket:
1010 sockfd_put(sock);
1011 return err;
1014 static int nbd_reconnect_socket(struct nbd_device *nbd, unsigned long arg)
1016 struct nbd_config *config = nbd->config;
1017 struct socket *sock, *old;
1018 struct recv_thread_args *args;
1019 int i;
1020 int err;
1022 sock = nbd_get_socket(nbd, arg, &err);
1023 if (!sock)
1024 return err;
1026 args = kzalloc(sizeof(*args), GFP_KERNEL);
1027 if (!args) {
1028 sockfd_put(sock);
1029 return -ENOMEM;
1032 for (i = 0; i < config->num_connections; i++) {
1033 struct nbd_sock *nsock = config->socks[i];
1035 if (!nsock->dead)
1036 continue;
1038 mutex_lock(&nsock->tx_lock);
1039 if (!nsock->dead) {
1040 mutex_unlock(&nsock->tx_lock);
1041 continue;
1043 sk_set_memalloc(sock->sk);
1044 if (nbd->tag_set.timeout)
1045 sock->sk->sk_sndtimeo = nbd->tag_set.timeout;
1046 atomic_inc(&config->recv_threads);
1047 refcount_inc(&nbd->config_refs);
1048 old = nsock->sock;
1049 nsock->fallback_index = -1;
1050 nsock->sock = sock;
1051 nsock->dead = false;
1052 INIT_WORK(&args->work, recv_work);
1053 args->index = i;
1054 args->nbd = nbd;
1055 nsock->cookie++;
1056 mutex_unlock(&nsock->tx_lock);
1057 sockfd_put(old);
1059 clear_bit(NBD_DISCONNECTED, &config->runtime_flags);
1061 /* We take the tx_mutex in an error path in the recv_work, so we
1062 * need to queue_work outside of the tx_mutex.
1064 queue_work(nbd->recv_workq, &args->work);
1066 atomic_inc(&config->live_connections);
1067 wake_up(&config->conn_wait);
1068 return 0;
1070 sockfd_put(sock);
1071 kfree(args);
1072 return -ENOSPC;
1075 static void nbd_bdev_reset(struct block_device *bdev)
1077 if (bdev->bd_openers > 1)
1078 return;
1079 bd_set_size(bdev, 0);
1082 static void nbd_parse_flags(struct nbd_device *nbd)
1084 struct nbd_config *config = nbd->config;
1085 if (config->flags & NBD_FLAG_READ_ONLY)
1086 set_disk_ro(nbd->disk, true);
1087 else
1088 set_disk_ro(nbd->disk, false);
1089 if (config->flags & NBD_FLAG_SEND_TRIM)
1090 blk_queue_flag_set(QUEUE_FLAG_DISCARD, nbd->disk->queue);
1091 if (config->flags & NBD_FLAG_SEND_FLUSH) {
1092 if (config->flags & NBD_FLAG_SEND_FUA)
1093 blk_queue_write_cache(nbd->disk->queue, true, true);
1094 else
1095 blk_queue_write_cache(nbd->disk->queue, true, false);
1097 else
1098 blk_queue_write_cache(nbd->disk->queue, false, false);
1101 static void send_disconnects(struct nbd_device *nbd)
1103 struct nbd_config *config = nbd->config;
1104 struct nbd_request request = {
1105 .magic = htonl(NBD_REQUEST_MAGIC),
1106 .type = htonl(NBD_CMD_DISC),
1108 struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
1109 struct iov_iter from;
1110 int i, ret;
1112 for (i = 0; i < config->num_connections; i++) {
1113 struct nbd_sock *nsock = config->socks[i];
1115 iov_iter_kvec(&from, WRITE | ITER_KVEC, &iov, 1, sizeof(request));
1116 mutex_lock(&nsock->tx_lock);
1117 ret = sock_xmit(nbd, i, 1, &from, 0, NULL);
1118 if (ret <= 0)
1119 dev_err(disk_to_dev(nbd->disk),
1120 "Send disconnect failed %d\n", ret);
1121 mutex_unlock(&nsock->tx_lock);
1125 static int nbd_disconnect(struct nbd_device *nbd)
1127 struct nbd_config *config = nbd->config;
1129 dev_info(disk_to_dev(nbd->disk), "NBD_DISCONNECT\n");
1130 set_bit(NBD_DISCONNECT_REQUESTED, &config->runtime_flags);
1131 send_disconnects(nbd);
1132 return 0;
1135 static void nbd_clear_sock(struct nbd_device *nbd)
1137 sock_shutdown(nbd);
1138 nbd_clear_que(nbd);
1139 nbd->task_setup = NULL;
1142 static void nbd_config_put(struct nbd_device *nbd)
1144 if (refcount_dec_and_mutex_lock(&nbd->config_refs,
1145 &nbd->config_lock)) {
1146 struct nbd_config *config = nbd->config;
1147 nbd_dev_dbg_close(nbd);
1148 nbd_size_clear(nbd);
1149 if (test_and_clear_bit(NBD_HAS_PID_FILE,
1150 &config->runtime_flags))
1151 device_remove_file(disk_to_dev(nbd->disk), &pid_attr);
1152 nbd->task_recv = NULL;
1153 nbd_clear_sock(nbd);
1154 if (config->num_connections) {
1155 int i;
1156 for (i = 0; i < config->num_connections; i++) {
1157 sockfd_put(config->socks[i]->sock);
1158 kfree(config->socks[i]);
1160 kfree(config->socks);
1162 kfree(nbd->config);
1163 nbd->config = NULL;
1165 if (nbd->recv_workq)
1166 destroy_workqueue(nbd->recv_workq);
1167 nbd->recv_workq = NULL;
1169 nbd->tag_set.timeout = 0;
1170 nbd->disk->queue->limits.discard_granularity = 0;
1171 nbd->disk->queue->limits.discard_alignment = 0;
1172 blk_queue_max_discard_sectors(nbd->disk->queue, UINT_MAX);
1173 blk_queue_flag_clear(QUEUE_FLAG_DISCARD, nbd->disk->queue);
1175 mutex_unlock(&nbd->config_lock);
1176 nbd_put(nbd);
1177 module_put(THIS_MODULE);
1181 static int nbd_start_device(struct nbd_device *nbd)
1183 struct nbd_config *config = nbd->config;
1184 int num_connections = config->num_connections;
1185 int error = 0, i;
1187 if (nbd->task_recv)
1188 return -EBUSY;
1189 if (!config->socks)
1190 return -EINVAL;
1191 if (num_connections > 1 &&
1192 !(config->flags & NBD_FLAG_CAN_MULTI_CONN)) {
1193 dev_err(disk_to_dev(nbd->disk), "server does not support multiple connections per device.\n");
1194 return -EINVAL;
1197 nbd->recv_workq = alloc_workqueue("knbd%d-recv",
1198 WQ_MEM_RECLAIM | WQ_HIGHPRI |
1199 WQ_UNBOUND, 0, nbd->index);
1200 if (!nbd->recv_workq) {
1201 dev_err(disk_to_dev(nbd->disk), "Could not allocate knbd recv work queue.\n");
1202 return -ENOMEM;
1205 blk_mq_update_nr_hw_queues(&nbd->tag_set, config->num_connections);
1206 nbd->task_recv = current;
1208 nbd_parse_flags(nbd);
1210 error = device_create_file(disk_to_dev(nbd->disk), &pid_attr);
1211 if (error) {
1212 dev_err(disk_to_dev(nbd->disk), "device_create_file failed!\n");
1213 return error;
1215 set_bit(NBD_HAS_PID_FILE, &config->runtime_flags);
1217 nbd_dev_dbg_init(nbd);
1218 for (i = 0; i < num_connections; i++) {
1219 struct recv_thread_args *args;
1221 args = kzalloc(sizeof(*args), GFP_KERNEL);
1222 if (!args) {
1223 sock_shutdown(nbd);
1225 * If num_connections is m (2 < m),
1226 * and NO.1 ~ NO.n(1 < n < m) kzallocs are successful.
1227 * But NO.(n + 1) failed. We still have n recv threads.
1228 * So, add flush_workqueue here to prevent recv threads
1229 * dropping the last config_refs and trying to destroy
1230 * the workqueue from inside the workqueue.
1232 if (i)
1233 flush_workqueue(nbd->recv_workq);
1234 return -ENOMEM;
1236 sk_set_memalloc(config->socks[i]->sock->sk);
1237 if (nbd->tag_set.timeout)
1238 config->socks[i]->sock->sk->sk_sndtimeo =
1239 nbd->tag_set.timeout;
1240 atomic_inc(&config->recv_threads);
1241 refcount_inc(&nbd->config_refs);
1242 INIT_WORK(&args->work, recv_work);
1243 args->nbd = nbd;
1244 args->index = i;
1245 queue_work(nbd->recv_workq, &args->work);
1247 nbd_size_update(nbd);
1248 return error;
1251 static int nbd_start_device_ioctl(struct nbd_device *nbd, struct block_device *bdev)
1253 struct nbd_config *config = nbd->config;
1254 int ret;
1256 ret = nbd_start_device(nbd);
1257 if (ret)
1258 return ret;
1260 if (max_part)
1261 bdev->bd_invalidated = 1;
1262 mutex_unlock(&nbd->config_lock);
1263 ret = wait_event_interruptible(config->recv_wq,
1264 atomic_read(&config->recv_threads) == 0);
1265 if (ret)
1266 sock_shutdown(nbd);
1267 flush_workqueue(nbd->recv_workq);
1269 mutex_lock(&nbd->config_lock);
1270 nbd_bdev_reset(bdev);
1271 /* user requested, ignore socket errors */
1272 if (test_bit(NBD_DISCONNECT_REQUESTED, &config->runtime_flags))
1273 ret = 0;
1274 if (test_bit(NBD_TIMEDOUT, &config->runtime_flags))
1275 ret = -ETIMEDOUT;
1276 return ret;
1279 static void nbd_clear_sock_ioctl(struct nbd_device *nbd,
1280 struct block_device *bdev)
1282 sock_shutdown(nbd);
1283 __invalidate_device(bdev, true);
1284 nbd_bdev_reset(bdev);
1285 if (test_and_clear_bit(NBD_HAS_CONFIG_REF,
1286 &nbd->config->runtime_flags))
1287 nbd_config_put(nbd);
1290 static bool nbd_is_valid_blksize(unsigned long blksize)
1292 if (!blksize || !is_power_of_2(blksize) || blksize < 512 ||
1293 blksize > PAGE_SIZE)
1294 return false;
1295 return true;
1298 /* Must be called with config_lock held */
1299 static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
1300 unsigned int cmd, unsigned long arg)
1302 struct nbd_config *config = nbd->config;
1304 switch (cmd) {
1305 case NBD_DISCONNECT:
1306 return nbd_disconnect(nbd);
1307 case NBD_CLEAR_SOCK:
1308 nbd_clear_sock_ioctl(nbd, bdev);
1309 return 0;
1310 case NBD_SET_SOCK:
1311 return nbd_add_socket(nbd, arg, false);
1312 case NBD_SET_BLKSIZE:
1313 if (!arg)
1314 arg = NBD_DEF_BLKSIZE;
1315 if (!nbd_is_valid_blksize(arg))
1316 return -EINVAL;
1317 nbd_size_set(nbd, arg,
1318 div_s64(config->bytesize, arg));
1319 return 0;
1320 case NBD_SET_SIZE:
1321 nbd_size_set(nbd, config->blksize,
1322 div_s64(arg, config->blksize));
1323 return 0;
1324 case NBD_SET_SIZE_BLOCKS:
1325 nbd_size_set(nbd, config->blksize, arg);
1326 return 0;
1327 case NBD_SET_TIMEOUT:
1328 if (arg) {
1329 nbd->tag_set.timeout = arg * HZ;
1330 blk_queue_rq_timeout(nbd->disk->queue, arg * HZ);
1332 return 0;
1334 case NBD_SET_FLAGS:
1335 config->flags = arg;
1336 return 0;
1337 case NBD_DO_IT:
1338 return nbd_start_device_ioctl(nbd, bdev);
1339 case NBD_CLEAR_QUE:
1341 * This is for compatibility only. The queue is always cleared
1342 * by NBD_DO_IT or NBD_CLEAR_SOCK.
1344 return 0;
1345 case NBD_PRINT_DEBUG:
1347 * For compatibility only, we no longer keep a list of
1348 * outstanding requests.
1350 return 0;
1352 return -ENOTTY;
1355 static int nbd_ioctl(struct block_device *bdev, fmode_t mode,
1356 unsigned int cmd, unsigned long arg)
1358 struct nbd_device *nbd = bdev->bd_disk->private_data;
1359 struct nbd_config *config = nbd->config;
1360 int error = -EINVAL;
1362 if (!capable(CAP_SYS_ADMIN))
1363 return -EPERM;
1365 /* The block layer will pass back some non-nbd ioctls in case we have
1366 * special handling for them, but we don't so just return an error.
1368 if (_IOC_TYPE(cmd) != 0xab)
1369 return -EINVAL;
1371 mutex_lock(&nbd->config_lock);
1373 /* Don't allow ioctl operations on a nbd device that was created with
1374 * netlink, unless it's DISCONNECT or CLEAR_SOCK, which are fine.
1376 if (!test_bit(NBD_BOUND, &config->runtime_flags) ||
1377 (cmd == NBD_DISCONNECT || cmd == NBD_CLEAR_SOCK))
1378 error = __nbd_ioctl(bdev, nbd, cmd, arg);
1379 else
1380 dev_err(nbd_to_dev(nbd), "Cannot use ioctl interface on a netlink controlled device.\n");
1381 mutex_unlock(&nbd->config_lock);
1382 return error;
1385 static struct nbd_config *nbd_alloc_config(void)
1387 struct nbd_config *config;
1389 config = kzalloc(sizeof(struct nbd_config), GFP_NOFS);
1390 if (!config)
1391 return NULL;
1392 atomic_set(&config->recv_threads, 0);
1393 init_waitqueue_head(&config->recv_wq);
1394 init_waitqueue_head(&config->conn_wait);
1395 config->blksize = NBD_DEF_BLKSIZE;
1396 atomic_set(&config->live_connections, 0);
1397 try_module_get(THIS_MODULE);
1398 return config;
1401 static int nbd_open(struct block_device *bdev, fmode_t mode)
1403 struct nbd_device *nbd;
1404 int ret = 0;
1406 mutex_lock(&nbd_index_mutex);
1407 nbd = bdev->bd_disk->private_data;
1408 if (!nbd) {
1409 ret = -ENXIO;
1410 goto out;
1412 if (!refcount_inc_not_zero(&nbd->refs)) {
1413 ret = -ENXIO;
1414 goto out;
1416 if (!refcount_inc_not_zero(&nbd->config_refs)) {
1417 struct nbd_config *config;
1419 mutex_lock(&nbd->config_lock);
1420 if (refcount_inc_not_zero(&nbd->config_refs)) {
1421 mutex_unlock(&nbd->config_lock);
1422 goto out;
1424 config = nbd->config = nbd_alloc_config();
1425 if (!config) {
1426 ret = -ENOMEM;
1427 mutex_unlock(&nbd->config_lock);
1428 goto out;
1430 refcount_set(&nbd->config_refs, 1);
1431 refcount_inc(&nbd->refs);
1432 mutex_unlock(&nbd->config_lock);
1433 bdev->bd_invalidated = 1;
1434 } else if (nbd_disconnected(nbd->config)) {
1435 bdev->bd_invalidated = 1;
1437 out:
1438 mutex_unlock(&nbd_index_mutex);
1439 return ret;
1442 static void nbd_release(struct gendisk *disk, fmode_t mode)
1444 struct nbd_device *nbd = disk->private_data;
1445 struct block_device *bdev = bdget_disk(disk, 0);
1447 if (test_bit(NBD_DISCONNECT_ON_CLOSE, &nbd->config->runtime_flags) &&
1448 bdev->bd_openers == 0)
1449 nbd_disconnect_and_put(nbd);
1451 nbd_config_put(nbd);
1452 nbd_put(nbd);
1455 static const struct block_device_operations nbd_fops =
1457 .owner = THIS_MODULE,
1458 .open = nbd_open,
1459 .release = nbd_release,
1460 .ioctl = nbd_ioctl,
1461 .compat_ioctl = nbd_ioctl,
1464 #if IS_ENABLED(CONFIG_DEBUG_FS)
1466 static int nbd_dbg_tasks_show(struct seq_file *s, void *unused)
1468 struct nbd_device *nbd = s->private;
1470 if (nbd->task_recv)
1471 seq_printf(s, "recv: %d\n", task_pid_nr(nbd->task_recv));
1473 return 0;
1476 static int nbd_dbg_tasks_open(struct inode *inode, struct file *file)
1478 return single_open(file, nbd_dbg_tasks_show, inode->i_private);
1481 static const struct file_operations nbd_dbg_tasks_ops = {
1482 .open = nbd_dbg_tasks_open,
1483 .read = seq_read,
1484 .llseek = seq_lseek,
1485 .release = single_release,
1488 static int nbd_dbg_flags_show(struct seq_file *s, void *unused)
1490 struct nbd_device *nbd = s->private;
1491 u32 flags = nbd->config->flags;
1493 seq_printf(s, "Hex: 0x%08x\n\n", flags);
1495 seq_puts(s, "Known flags:\n");
1497 if (flags & NBD_FLAG_HAS_FLAGS)
1498 seq_puts(s, "NBD_FLAG_HAS_FLAGS\n");
1499 if (flags & NBD_FLAG_READ_ONLY)
1500 seq_puts(s, "NBD_FLAG_READ_ONLY\n");
1501 if (flags & NBD_FLAG_SEND_FLUSH)
1502 seq_puts(s, "NBD_FLAG_SEND_FLUSH\n");
1503 if (flags & NBD_FLAG_SEND_FUA)
1504 seq_puts(s, "NBD_FLAG_SEND_FUA\n");
1505 if (flags & NBD_FLAG_SEND_TRIM)
1506 seq_puts(s, "NBD_FLAG_SEND_TRIM\n");
1508 return 0;
1511 static int nbd_dbg_flags_open(struct inode *inode, struct file *file)
1513 return single_open(file, nbd_dbg_flags_show, inode->i_private);
1516 static const struct file_operations nbd_dbg_flags_ops = {
1517 .open = nbd_dbg_flags_open,
1518 .read = seq_read,
1519 .llseek = seq_lseek,
1520 .release = single_release,
1523 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1525 struct dentry *dir;
1526 struct nbd_config *config = nbd->config;
1528 if (!nbd_dbg_dir)
1529 return -EIO;
1531 dir = debugfs_create_dir(nbd_name(nbd), nbd_dbg_dir);
1532 if (!dir) {
1533 dev_err(nbd_to_dev(nbd), "Failed to create debugfs dir for '%s'\n",
1534 nbd_name(nbd));
1535 return -EIO;
1537 config->dbg_dir = dir;
1539 debugfs_create_file("tasks", 0444, dir, nbd, &nbd_dbg_tasks_ops);
1540 debugfs_create_u64("size_bytes", 0444, dir, &config->bytesize);
1541 debugfs_create_u32("timeout", 0444, dir, &nbd->tag_set.timeout);
1542 debugfs_create_u64("blocksize", 0444, dir, &config->blksize);
1543 debugfs_create_file("flags", 0444, dir, nbd, &nbd_dbg_flags_ops);
1545 return 0;
1548 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1550 debugfs_remove_recursive(nbd->config->dbg_dir);
1553 static int nbd_dbg_init(void)
1555 struct dentry *dbg_dir;
1557 dbg_dir = debugfs_create_dir("nbd", NULL);
1558 if (!dbg_dir)
1559 return -EIO;
1561 nbd_dbg_dir = dbg_dir;
1563 return 0;
1566 static void nbd_dbg_close(void)
1568 debugfs_remove_recursive(nbd_dbg_dir);
1571 #else /* IS_ENABLED(CONFIG_DEBUG_FS) */
1573 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1575 return 0;
1578 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1582 static int nbd_dbg_init(void)
1584 return 0;
1587 static void nbd_dbg_close(void)
1591 #endif
1593 static int nbd_init_request(struct blk_mq_tag_set *set, struct request *rq,
1594 unsigned int hctx_idx, unsigned int numa_node)
1596 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(rq);
1597 cmd->nbd = set->driver_data;
1598 cmd->flags = 0;
1599 mutex_init(&cmd->lock);
1600 return 0;
1603 static const struct blk_mq_ops nbd_mq_ops = {
1604 .queue_rq = nbd_queue_rq,
1605 .complete = nbd_complete_rq,
1606 .init_request = nbd_init_request,
1607 .timeout = nbd_xmit_timeout,
1610 static int nbd_dev_add(int index)
1612 struct nbd_device *nbd;
1613 struct gendisk *disk;
1614 struct request_queue *q;
1615 int err = -ENOMEM;
1617 nbd = kzalloc(sizeof(struct nbd_device), GFP_KERNEL);
1618 if (!nbd)
1619 goto out;
1621 disk = alloc_disk(1 << part_shift);
1622 if (!disk)
1623 goto out_free_nbd;
1625 if (index >= 0) {
1626 err = idr_alloc(&nbd_index_idr, nbd, index, index + 1,
1627 GFP_KERNEL);
1628 if (err == -ENOSPC)
1629 err = -EEXIST;
1630 } else {
1631 err = idr_alloc(&nbd_index_idr, nbd, 0, 0, GFP_KERNEL);
1632 if (err >= 0)
1633 index = err;
1635 if (err < 0)
1636 goto out_free_disk;
1638 nbd->index = index;
1639 nbd->disk = disk;
1640 nbd->tag_set.ops = &nbd_mq_ops;
1641 nbd->tag_set.nr_hw_queues = 1;
1642 nbd->tag_set.queue_depth = 128;
1643 nbd->tag_set.numa_node = NUMA_NO_NODE;
1644 nbd->tag_set.cmd_size = sizeof(struct nbd_cmd);
1645 nbd->tag_set.flags = BLK_MQ_F_SHOULD_MERGE |
1646 BLK_MQ_F_SG_MERGE | BLK_MQ_F_BLOCKING;
1647 nbd->tag_set.driver_data = nbd;
1649 err = blk_mq_alloc_tag_set(&nbd->tag_set);
1650 if (err)
1651 goto out_free_idr;
1653 q = blk_mq_init_queue(&nbd->tag_set);
1654 if (IS_ERR(q)) {
1655 err = PTR_ERR(q);
1656 goto out_free_tags;
1658 disk->queue = q;
1661 * Tell the block layer that we are not a rotational device
1663 blk_queue_flag_set(QUEUE_FLAG_NONROT, disk->queue);
1664 blk_queue_flag_clear(QUEUE_FLAG_ADD_RANDOM, disk->queue);
1665 disk->queue->limits.discard_granularity = 0;
1666 disk->queue->limits.discard_alignment = 0;
1667 blk_queue_max_discard_sectors(disk->queue, 0);
1668 blk_queue_max_segment_size(disk->queue, UINT_MAX);
1669 blk_queue_max_segments(disk->queue, USHRT_MAX);
1670 blk_queue_max_hw_sectors(disk->queue, 65536);
1671 disk->queue->limits.max_sectors = 256;
1673 mutex_init(&nbd->config_lock);
1674 refcount_set(&nbd->config_refs, 0);
1675 refcount_set(&nbd->refs, 1);
1676 INIT_LIST_HEAD(&nbd->list);
1677 disk->major = NBD_MAJOR;
1678 disk->first_minor = index << part_shift;
1679 disk->fops = &nbd_fops;
1680 disk->private_data = nbd;
1681 sprintf(disk->disk_name, "nbd%d", index);
1682 add_disk(disk);
1683 nbd_total_devices++;
1684 return index;
1686 out_free_tags:
1687 blk_mq_free_tag_set(&nbd->tag_set);
1688 out_free_idr:
1689 idr_remove(&nbd_index_idr, index);
1690 out_free_disk:
1691 put_disk(disk);
1692 out_free_nbd:
1693 kfree(nbd);
1694 out:
1695 return err;
1698 static int find_free_cb(int id, void *ptr, void *data)
1700 struct nbd_device *nbd = ptr;
1701 struct nbd_device **found = data;
1703 if (!refcount_read(&nbd->config_refs)) {
1704 *found = nbd;
1705 return 1;
1707 return 0;
1710 /* Netlink interface. */
1711 static const struct nla_policy nbd_attr_policy[NBD_ATTR_MAX + 1] = {
1712 [NBD_ATTR_INDEX] = { .type = NLA_U32 },
1713 [NBD_ATTR_SIZE_BYTES] = { .type = NLA_U64 },
1714 [NBD_ATTR_BLOCK_SIZE_BYTES] = { .type = NLA_U64 },
1715 [NBD_ATTR_TIMEOUT] = { .type = NLA_U64 },
1716 [NBD_ATTR_SERVER_FLAGS] = { .type = NLA_U64 },
1717 [NBD_ATTR_CLIENT_FLAGS] = { .type = NLA_U64 },
1718 [NBD_ATTR_SOCKETS] = { .type = NLA_NESTED},
1719 [NBD_ATTR_DEAD_CONN_TIMEOUT] = { .type = NLA_U64 },
1720 [NBD_ATTR_DEVICE_LIST] = { .type = NLA_NESTED},
1723 static const struct nla_policy nbd_sock_policy[NBD_SOCK_MAX + 1] = {
1724 [NBD_SOCK_FD] = { .type = NLA_U32 },
1727 /* We don't use this right now since we don't parse the incoming list, but we
1728 * still want it here so userspace knows what to expect.
1730 static const struct nla_policy __attribute__((unused))
1731 nbd_device_policy[NBD_DEVICE_ATTR_MAX + 1] = {
1732 [NBD_DEVICE_INDEX] = { .type = NLA_U32 },
1733 [NBD_DEVICE_CONNECTED] = { .type = NLA_U8 },
1736 static int nbd_genl_connect(struct sk_buff *skb, struct genl_info *info)
1738 struct nbd_device *nbd = NULL;
1739 struct nbd_config *config;
1740 int index = -1;
1741 int ret;
1742 bool put_dev = false;
1744 if (!netlink_capable(skb, CAP_SYS_ADMIN))
1745 return -EPERM;
1747 if (info->attrs[NBD_ATTR_INDEX])
1748 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1749 if (!info->attrs[NBD_ATTR_SOCKETS]) {
1750 printk(KERN_ERR "nbd: must specify at least one socket\n");
1751 return -EINVAL;
1753 if (!info->attrs[NBD_ATTR_SIZE_BYTES]) {
1754 printk(KERN_ERR "nbd: must specify a size in bytes for the device\n");
1755 return -EINVAL;
1757 again:
1758 mutex_lock(&nbd_index_mutex);
1759 if (index == -1) {
1760 ret = idr_for_each(&nbd_index_idr, &find_free_cb, &nbd);
1761 if (ret == 0) {
1762 int new_index;
1763 new_index = nbd_dev_add(-1);
1764 if (new_index < 0) {
1765 mutex_unlock(&nbd_index_mutex);
1766 printk(KERN_ERR "nbd: failed to add new device\n");
1767 return new_index;
1769 nbd = idr_find(&nbd_index_idr, new_index);
1771 } else {
1772 nbd = idr_find(&nbd_index_idr, index);
1773 if (!nbd) {
1774 ret = nbd_dev_add(index);
1775 if (ret < 0) {
1776 mutex_unlock(&nbd_index_mutex);
1777 printk(KERN_ERR "nbd: failed to add new device\n");
1778 return ret;
1780 nbd = idr_find(&nbd_index_idr, index);
1783 if (!nbd) {
1784 printk(KERN_ERR "nbd: couldn't find device at index %d\n",
1785 index);
1786 mutex_unlock(&nbd_index_mutex);
1787 return -EINVAL;
1789 if (!refcount_inc_not_zero(&nbd->refs)) {
1790 mutex_unlock(&nbd_index_mutex);
1791 if (index == -1)
1792 goto again;
1793 printk(KERN_ERR "nbd: device at index %d is going down\n",
1794 index);
1795 return -EINVAL;
1797 mutex_unlock(&nbd_index_mutex);
1799 mutex_lock(&nbd->config_lock);
1800 if (refcount_read(&nbd->config_refs)) {
1801 mutex_unlock(&nbd->config_lock);
1802 nbd_put(nbd);
1803 if (index == -1)
1804 goto again;
1805 printk(KERN_ERR "nbd: nbd%d already in use\n", index);
1806 return -EBUSY;
1808 if (WARN_ON(nbd->config)) {
1809 mutex_unlock(&nbd->config_lock);
1810 nbd_put(nbd);
1811 return -EINVAL;
1813 config = nbd->config = nbd_alloc_config();
1814 if (!nbd->config) {
1815 mutex_unlock(&nbd->config_lock);
1816 nbd_put(nbd);
1817 printk(KERN_ERR "nbd: couldn't allocate config\n");
1818 return -ENOMEM;
1820 refcount_set(&nbd->config_refs, 1);
1821 set_bit(NBD_BOUND, &config->runtime_flags);
1823 if (info->attrs[NBD_ATTR_SIZE_BYTES]) {
1824 u64 bytes = nla_get_u64(info->attrs[NBD_ATTR_SIZE_BYTES]);
1825 nbd_size_set(nbd, config->blksize,
1826 div64_u64(bytes, config->blksize));
1828 if (info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]) {
1829 u64 bsize =
1830 nla_get_u64(info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]);
1831 if (!bsize)
1832 bsize = NBD_DEF_BLKSIZE;
1833 if (!nbd_is_valid_blksize(bsize)) {
1834 ret = -EINVAL;
1835 goto out;
1837 nbd_size_set(nbd, bsize, div64_u64(config->bytesize, bsize));
1839 if (info->attrs[NBD_ATTR_TIMEOUT]) {
1840 u64 timeout = nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]);
1841 nbd->tag_set.timeout = timeout * HZ;
1842 blk_queue_rq_timeout(nbd->disk->queue, timeout * HZ);
1844 if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
1845 config->dead_conn_timeout =
1846 nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
1847 config->dead_conn_timeout *= HZ;
1849 if (info->attrs[NBD_ATTR_SERVER_FLAGS])
1850 config->flags =
1851 nla_get_u64(info->attrs[NBD_ATTR_SERVER_FLAGS]);
1852 if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
1853 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
1854 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
1855 set_bit(NBD_DESTROY_ON_DISCONNECT,
1856 &config->runtime_flags);
1857 put_dev = true;
1859 if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
1860 set_bit(NBD_DISCONNECT_ON_CLOSE,
1861 &config->runtime_flags);
1865 if (info->attrs[NBD_ATTR_SOCKETS]) {
1866 struct nlattr *attr;
1867 int rem, fd;
1869 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
1870 rem) {
1871 struct nlattr *socks[NBD_SOCK_MAX+1];
1873 if (nla_type(attr) != NBD_SOCK_ITEM) {
1874 printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
1875 ret = -EINVAL;
1876 goto out;
1878 ret = nla_parse_nested(socks, NBD_SOCK_MAX, attr,
1879 nbd_sock_policy, info->extack);
1880 if (ret != 0) {
1881 printk(KERN_ERR "nbd: error processing sock list\n");
1882 ret = -EINVAL;
1883 goto out;
1885 if (!socks[NBD_SOCK_FD])
1886 continue;
1887 fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
1888 ret = nbd_add_socket(nbd, fd, true);
1889 if (ret)
1890 goto out;
1893 ret = nbd_start_device(nbd);
1894 out:
1895 mutex_unlock(&nbd->config_lock);
1896 if (!ret) {
1897 set_bit(NBD_HAS_CONFIG_REF, &config->runtime_flags);
1898 refcount_inc(&nbd->config_refs);
1899 nbd_connect_reply(info, nbd->index);
1901 nbd_config_put(nbd);
1902 if (put_dev)
1903 nbd_put(nbd);
1904 return ret;
1907 static void nbd_disconnect_and_put(struct nbd_device *nbd)
1909 mutex_lock(&nbd->config_lock);
1910 nbd_disconnect(nbd);
1911 nbd_clear_sock(nbd);
1912 mutex_unlock(&nbd->config_lock);
1914 * Make sure recv thread has finished, so it does not drop the last
1915 * config ref and try to destroy the workqueue from inside the work
1916 * queue.
1918 flush_workqueue(nbd->recv_workq);
1919 if (test_and_clear_bit(NBD_HAS_CONFIG_REF,
1920 &nbd->config->runtime_flags))
1921 nbd_config_put(nbd);
1924 static int nbd_genl_disconnect(struct sk_buff *skb, struct genl_info *info)
1926 struct nbd_device *nbd;
1927 int index;
1929 if (!netlink_capable(skb, CAP_SYS_ADMIN))
1930 return -EPERM;
1932 if (!info->attrs[NBD_ATTR_INDEX]) {
1933 printk(KERN_ERR "nbd: must specify an index to disconnect\n");
1934 return -EINVAL;
1936 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1937 mutex_lock(&nbd_index_mutex);
1938 nbd = idr_find(&nbd_index_idr, index);
1939 if (!nbd) {
1940 mutex_unlock(&nbd_index_mutex);
1941 printk(KERN_ERR "nbd: couldn't find device at index %d\n",
1942 index);
1943 return -EINVAL;
1945 if (!refcount_inc_not_zero(&nbd->refs)) {
1946 mutex_unlock(&nbd_index_mutex);
1947 printk(KERN_ERR "nbd: device at index %d is going down\n",
1948 index);
1949 return -EINVAL;
1951 mutex_unlock(&nbd_index_mutex);
1952 if (!refcount_inc_not_zero(&nbd->config_refs)) {
1953 nbd_put(nbd);
1954 return 0;
1956 nbd_disconnect_and_put(nbd);
1957 nbd_config_put(nbd);
1958 nbd_put(nbd);
1959 return 0;
1962 static int nbd_genl_reconfigure(struct sk_buff *skb, struct genl_info *info)
1964 struct nbd_device *nbd = NULL;
1965 struct nbd_config *config;
1966 int index;
1967 int ret = 0;
1968 bool put_dev = false;
1970 if (!netlink_capable(skb, CAP_SYS_ADMIN))
1971 return -EPERM;
1973 if (!info->attrs[NBD_ATTR_INDEX]) {
1974 printk(KERN_ERR "nbd: must specify a device to reconfigure\n");
1975 return -EINVAL;
1977 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1978 mutex_lock(&nbd_index_mutex);
1979 nbd = idr_find(&nbd_index_idr, index);
1980 if (!nbd) {
1981 mutex_unlock(&nbd_index_mutex);
1982 printk(KERN_ERR "nbd: couldn't find a device at index %d\n",
1983 index);
1984 return -EINVAL;
1986 if (!refcount_inc_not_zero(&nbd->refs)) {
1987 mutex_unlock(&nbd_index_mutex);
1988 printk(KERN_ERR "nbd: device at index %d is going down\n",
1989 index);
1990 return -EINVAL;
1992 mutex_unlock(&nbd_index_mutex);
1994 if (!refcount_inc_not_zero(&nbd->config_refs)) {
1995 dev_err(nbd_to_dev(nbd),
1996 "not configured, cannot reconfigure\n");
1997 nbd_put(nbd);
1998 return -EINVAL;
2001 mutex_lock(&nbd->config_lock);
2002 config = nbd->config;
2003 if (!test_bit(NBD_BOUND, &config->runtime_flags) ||
2004 !nbd->task_recv) {
2005 dev_err(nbd_to_dev(nbd),
2006 "not configured, cannot reconfigure\n");
2007 ret = -EINVAL;
2008 goto out;
2011 if (info->attrs[NBD_ATTR_TIMEOUT]) {
2012 u64 timeout = nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]);
2013 nbd->tag_set.timeout = timeout * HZ;
2014 blk_queue_rq_timeout(nbd->disk->queue, timeout * HZ);
2016 if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
2017 config->dead_conn_timeout =
2018 nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
2019 config->dead_conn_timeout *= HZ;
2021 if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
2022 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
2023 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
2024 if (!test_and_set_bit(NBD_DESTROY_ON_DISCONNECT,
2025 &config->runtime_flags))
2026 put_dev = true;
2027 } else {
2028 if (test_and_clear_bit(NBD_DESTROY_ON_DISCONNECT,
2029 &config->runtime_flags))
2030 refcount_inc(&nbd->refs);
2033 if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
2034 set_bit(NBD_DISCONNECT_ON_CLOSE,
2035 &config->runtime_flags);
2036 } else {
2037 clear_bit(NBD_DISCONNECT_ON_CLOSE,
2038 &config->runtime_flags);
2042 if (info->attrs[NBD_ATTR_SOCKETS]) {
2043 struct nlattr *attr;
2044 int rem, fd;
2046 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
2047 rem) {
2048 struct nlattr *socks[NBD_SOCK_MAX+1];
2050 if (nla_type(attr) != NBD_SOCK_ITEM) {
2051 printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
2052 ret = -EINVAL;
2053 goto out;
2055 ret = nla_parse_nested(socks, NBD_SOCK_MAX, attr,
2056 nbd_sock_policy, info->extack);
2057 if (ret != 0) {
2058 printk(KERN_ERR "nbd: error processing sock list\n");
2059 ret = -EINVAL;
2060 goto out;
2062 if (!socks[NBD_SOCK_FD])
2063 continue;
2064 fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
2065 ret = nbd_reconnect_socket(nbd, fd);
2066 if (ret) {
2067 if (ret == -ENOSPC)
2068 ret = 0;
2069 goto out;
2071 dev_info(nbd_to_dev(nbd), "reconnected socket\n");
2074 out:
2075 mutex_unlock(&nbd->config_lock);
2076 nbd_config_put(nbd);
2077 nbd_put(nbd);
2078 if (put_dev)
2079 nbd_put(nbd);
2080 return ret;
2083 static const struct genl_ops nbd_connect_genl_ops[] = {
2085 .cmd = NBD_CMD_CONNECT,
2086 .policy = nbd_attr_policy,
2087 .doit = nbd_genl_connect,
2090 .cmd = NBD_CMD_DISCONNECT,
2091 .policy = nbd_attr_policy,
2092 .doit = nbd_genl_disconnect,
2095 .cmd = NBD_CMD_RECONFIGURE,
2096 .policy = nbd_attr_policy,
2097 .doit = nbd_genl_reconfigure,
2100 .cmd = NBD_CMD_STATUS,
2101 .policy = nbd_attr_policy,
2102 .doit = nbd_genl_status,
2106 static const struct genl_multicast_group nbd_mcast_grps[] = {
2107 { .name = NBD_GENL_MCAST_GROUP_NAME, },
2110 static struct genl_family nbd_genl_family __ro_after_init = {
2111 .hdrsize = 0,
2112 .name = NBD_GENL_FAMILY_NAME,
2113 .version = NBD_GENL_VERSION,
2114 .module = THIS_MODULE,
2115 .ops = nbd_connect_genl_ops,
2116 .n_ops = ARRAY_SIZE(nbd_connect_genl_ops),
2117 .maxattr = NBD_ATTR_MAX,
2118 .mcgrps = nbd_mcast_grps,
2119 .n_mcgrps = ARRAY_SIZE(nbd_mcast_grps),
2122 static int populate_nbd_status(struct nbd_device *nbd, struct sk_buff *reply)
2124 struct nlattr *dev_opt;
2125 u8 connected = 0;
2126 int ret;
2128 /* This is a little racey, but for status it's ok. The
2129 * reason we don't take a ref here is because we can't
2130 * take a ref in the index == -1 case as we would need
2131 * to put under the nbd_index_mutex, which could
2132 * deadlock if we are configured to remove ourselves
2133 * once we're disconnected.
2135 if (refcount_read(&nbd->config_refs))
2136 connected = 1;
2137 dev_opt = nla_nest_start(reply, NBD_DEVICE_ITEM);
2138 if (!dev_opt)
2139 return -EMSGSIZE;
2140 ret = nla_put_u32(reply, NBD_DEVICE_INDEX, nbd->index);
2141 if (ret)
2142 return -EMSGSIZE;
2143 ret = nla_put_u8(reply, NBD_DEVICE_CONNECTED,
2144 connected);
2145 if (ret)
2146 return -EMSGSIZE;
2147 nla_nest_end(reply, dev_opt);
2148 return 0;
2151 static int status_cb(int id, void *ptr, void *data)
2153 struct nbd_device *nbd = ptr;
2154 return populate_nbd_status(nbd, (struct sk_buff *)data);
2157 static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info)
2159 struct nlattr *dev_list;
2160 struct sk_buff *reply;
2161 void *reply_head;
2162 size_t msg_size;
2163 int index = -1;
2164 int ret = -ENOMEM;
2166 if (info->attrs[NBD_ATTR_INDEX])
2167 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2169 mutex_lock(&nbd_index_mutex);
2171 msg_size = nla_total_size(nla_attr_size(sizeof(u32)) +
2172 nla_attr_size(sizeof(u8)));
2173 msg_size *= (index == -1) ? nbd_total_devices : 1;
2175 reply = genlmsg_new(msg_size, GFP_KERNEL);
2176 if (!reply)
2177 goto out;
2178 reply_head = genlmsg_put_reply(reply, info, &nbd_genl_family, 0,
2179 NBD_CMD_STATUS);
2180 if (!reply_head) {
2181 nlmsg_free(reply);
2182 goto out;
2185 dev_list = nla_nest_start(reply, NBD_ATTR_DEVICE_LIST);
2186 if (index == -1) {
2187 ret = idr_for_each(&nbd_index_idr, &status_cb, reply);
2188 if (ret) {
2189 nlmsg_free(reply);
2190 goto out;
2192 } else {
2193 struct nbd_device *nbd;
2194 nbd = idr_find(&nbd_index_idr, index);
2195 if (nbd) {
2196 ret = populate_nbd_status(nbd, reply);
2197 if (ret) {
2198 nlmsg_free(reply);
2199 goto out;
2203 nla_nest_end(reply, dev_list);
2204 genlmsg_end(reply, reply_head);
2205 genlmsg_reply(reply, info);
2206 ret = 0;
2207 out:
2208 mutex_unlock(&nbd_index_mutex);
2209 return ret;
2212 static void nbd_connect_reply(struct genl_info *info, int index)
2214 struct sk_buff *skb;
2215 void *msg_head;
2216 int ret;
2218 skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2219 if (!skb)
2220 return;
2221 msg_head = genlmsg_put_reply(skb, info, &nbd_genl_family, 0,
2222 NBD_CMD_CONNECT);
2223 if (!msg_head) {
2224 nlmsg_free(skb);
2225 return;
2227 ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2228 if (ret) {
2229 nlmsg_free(skb);
2230 return;
2232 genlmsg_end(skb, msg_head);
2233 genlmsg_reply(skb, info);
2236 static void nbd_mcast_index(int index)
2238 struct sk_buff *skb;
2239 void *msg_head;
2240 int ret;
2242 skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2243 if (!skb)
2244 return;
2245 msg_head = genlmsg_put(skb, 0, 0, &nbd_genl_family, 0,
2246 NBD_CMD_LINK_DEAD);
2247 if (!msg_head) {
2248 nlmsg_free(skb);
2249 return;
2251 ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2252 if (ret) {
2253 nlmsg_free(skb);
2254 return;
2256 genlmsg_end(skb, msg_head);
2257 genlmsg_multicast(&nbd_genl_family, skb, 0, 0, GFP_KERNEL);
2260 static void nbd_dead_link_work(struct work_struct *work)
2262 struct link_dead_args *args = container_of(work, struct link_dead_args,
2263 work);
2264 nbd_mcast_index(args->index);
2265 kfree(args);
2268 static int __init nbd_init(void)
2270 int i;
2272 BUILD_BUG_ON(sizeof(struct nbd_request) != 28);
2274 if (max_part < 0) {
2275 printk(KERN_ERR "nbd: max_part must be >= 0\n");
2276 return -EINVAL;
2279 part_shift = 0;
2280 if (max_part > 0) {
2281 part_shift = fls(max_part);
2284 * Adjust max_part according to part_shift as it is exported
2285 * to user space so that user can know the max number of
2286 * partition kernel should be able to manage.
2288 * Note that -1 is required because partition 0 is reserved
2289 * for the whole disk.
2291 max_part = (1UL << part_shift) - 1;
2294 if ((1UL << part_shift) > DISK_MAX_PARTS)
2295 return -EINVAL;
2297 if (nbds_max > 1UL << (MINORBITS - part_shift))
2298 return -EINVAL;
2300 if (register_blkdev(NBD_MAJOR, "nbd"))
2301 return -EIO;
2303 if (genl_register_family(&nbd_genl_family)) {
2304 unregister_blkdev(NBD_MAJOR, "nbd");
2305 return -EINVAL;
2307 nbd_dbg_init();
2309 mutex_lock(&nbd_index_mutex);
2310 for (i = 0; i < nbds_max; i++)
2311 nbd_dev_add(i);
2312 mutex_unlock(&nbd_index_mutex);
2313 return 0;
2316 static int nbd_exit_cb(int id, void *ptr, void *data)
2318 struct list_head *list = (struct list_head *)data;
2319 struct nbd_device *nbd = ptr;
2321 list_add_tail(&nbd->list, list);
2322 return 0;
2325 static void __exit nbd_cleanup(void)
2327 struct nbd_device *nbd;
2328 LIST_HEAD(del_list);
2330 nbd_dbg_close();
2332 mutex_lock(&nbd_index_mutex);
2333 idr_for_each(&nbd_index_idr, &nbd_exit_cb, &del_list);
2334 mutex_unlock(&nbd_index_mutex);
2336 while (!list_empty(&del_list)) {
2337 nbd = list_first_entry(&del_list, struct nbd_device, list);
2338 list_del_init(&nbd->list);
2339 if (refcount_read(&nbd->refs) != 1)
2340 printk(KERN_ERR "nbd: possibly leaking a device\n");
2341 nbd_put(nbd);
2344 idr_destroy(&nbd_index_idr);
2345 genl_unregister_family(&nbd_genl_family);
2346 unregister_blkdev(NBD_MAJOR, "nbd");
2349 module_init(nbd_init);
2350 module_exit(nbd_cleanup);
2352 MODULE_DESCRIPTION("Network Block Device");
2353 MODULE_LICENSE("GPL");
2355 module_param(nbds_max, int, 0444);
2356 MODULE_PARM_DESC(nbds_max, "number of network block devices to initialize (default: 16)");
2357 module_param(max_part, int, 0444);
2358 MODULE_PARM_DESC(max_part, "number of partitions per device (default: 16)");