2 * Network block device - make block devices work over TCP
4 * Note that you can not swap over this thing, yet. Seems to work but
5 * deadlocks sometimes - you can not swap over TCP in general.
7 * Copyright 1997-2000, 2008 Pavel Machek <pavel@ucw.cz>
8 * Parts copyright 2001 Steven Whitehouse <steve@chygwyn.com>
10 * This file is released under GPLv2 or later.
12 * (part of code stolen from loop.c)
15 #include <linux/major.h>
17 #include <linux/blkdev.h>
18 #include <linux/module.h>
19 #include <linux/init.h>
20 #include <linux/sched.h>
21 #include <linux/sched/mm.h>
23 #include <linux/bio.h>
24 #include <linux/stat.h>
25 #include <linux/errno.h>
26 #include <linux/file.h>
27 #include <linux/ioctl.h>
28 #include <linux/mutex.h>
29 #include <linux/compiler.h>
30 #include <linux/err.h>
31 #include <linux/kernel.h>
32 #include <linux/slab.h>
34 #include <linux/net.h>
35 #include <linux/kthread.h>
36 #include <linux/types.h>
37 #include <linux/debugfs.h>
38 #include <linux/blk-mq.h>
40 #include <linux/uaccess.h>
41 #include <asm/types.h>
43 #include <linux/nbd.h>
44 #include <linux/nbd-netlink.h>
45 #include <net/genetlink.h>
47 static DEFINE_IDR(nbd_index_idr
);
48 static DEFINE_MUTEX(nbd_index_mutex
);
49 static int nbd_total_devices
= 0;
54 struct request
*pending
;
61 struct recv_thread_args
{
62 struct work_struct work
;
63 struct nbd_device
*nbd
;
67 struct link_dead_args
{
68 struct work_struct work
;
72 #define NBD_TIMEDOUT 0
73 #define NBD_DISCONNECT_REQUESTED 1
74 #define NBD_DISCONNECTED 2
75 #define NBD_HAS_PID_FILE 3
76 #define NBD_HAS_CONFIG_REF 4
78 #define NBD_DESTROY_ON_DISCONNECT 6
79 #define NBD_DISCONNECT_ON_CLOSE 7
83 unsigned long runtime_flags
;
84 u64 dead_conn_timeout
;
86 struct nbd_sock
**socks
;
88 atomic_t live_connections
;
89 wait_queue_head_t conn_wait
;
91 atomic_t recv_threads
;
92 wait_queue_head_t recv_wq
;
95 #if IS_ENABLED(CONFIG_DEBUG_FS)
96 struct dentry
*dbg_dir
;
101 struct blk_mq_tag_set tag_set
;
104 refcount_t config_refs
;
106 struct nbd_config
*config
;
107 struct mutex config_lock
;
108 struct gendisk
*disk
;
109 struct workqueue_struct
*recv_workq
;
111 struct list_head list
;
112 struct task_struct
*task_recv
;
113 struct task_struct
*task_setup
;
116 #define NBD_CMD_REQUEUED 1
119 struct nbd_device
*nbd
;
128 #if IS_ENABLED(CONFIG_DEBUG_FS)
129 static struct dentry
*nbd_dbg_dir
;
132 #define nbd_name(nbd) ((nbd)->disk->disk_name)
134 #define NBD_MAGIC 0x68797548
136 #define NBD_DEF_BLKSIZE 1024
138 static unsigned int nbds_max
= 16;
139 static int max_part
= 16;
140 static int part_shift
;
142 static int nbd_dev_dbg_init(struct nbd_device
*nbd
);
143 static void nbd_dev_dbg_close(struct nbd_device
*nbd
);
144 static void nbd_config_put(struct nbd_device
*nbd
);
145 static void nbd_connect_reply(struct genl_info
*info
, int index
);
146 static int nbd_genl_status(struct sk_buff
*skb
, struct genl_info
*info
);
147 static void nbd_dead_link_work(struct work_struct
*work
);
148 static void nbd_disconnect_and_put(struct nbd_device
*nbd
);
150 static inline struct device
*nbd_to_dev(struct nbd_device
*nbd
)
152 return disk_to_dev(nbd
->disk
);
155 static void nbd_requeue_cmd(struct nbd_cmd
*cmd
)
157 struct request
*req
= blk_mq_rq_from_pdu(cmd
);
159 if (!test_and_set_bit(NBD_CMD_REQUEUED
, &cmd
->flags
))
160 blk_mq_requeue_request(req
, true);
163 #define NBD_COOKIE_BITS 32
165 static u64
nbd_cmd_handle(struct nbd_cmd
*cmd
)
167 struct request
*req
= blk_mq_rq_from_pdu(cmd
);
168 u32 tag
= blk_mq_unique_tag(req
);
169 u64 cookie
= cmd
->cmd_cookie
;
171 return (cookie
<< NBD_COOKIE_BITS
) | tag
;
174 static u32
nbd_handle_to_tag(u64 handle
)
179 static u32
nbd_handle_to_cookie(u64 handle
)
181 return (u32
)(handle
>> NBD_COOKIE_BITS
);
184 static const char *nbdcmd_to_ascii(int cmd
)
187 case NBD_CMD_READ
: return "read";
188 case NBD_CMD_WRITE
: return "write";
189 case NBD_CMD_DISC
: return "disconnect";
190 case NBD_CMD_FLUSH
: return "flush";
191 case NBD_CMD_TRIM
: return "trim/discard";
196 static ssize_t
pid_show(struct device
*dev
,
197 struct device_attribute
*attr
, char *buf
)
199 struct gendisk
*disk
= dev_to_disk(dev
);
200 struct nbd_device
*nbd
= (struct nbd_device
*)disk
->private_data
;
202 return sprintf(buf
, "%d\n", task_pid_nr(nbd
->task_recv
));
205 static const struct device_attribute pid_attr
= {
206 .attr
= { .name
= "pid", .mode
= 0444},
210 static void nbd_dev_remove(struct nbd_device
*nbd
)
212 struct gendisk
*disk
= nbd
->disk
;
213 struct request_queue
*q
;
218 blk_cleanup_queue(q
);
219 blk_mq_free_tag_set(&nbd
->tag_set
);
220 disk
->private_data
= NULL
;
226 static void nbd_put(struct nbd_device
*nbd
)
228 if (refcount_dec_and_mutex_lock(&nbd
->refs
,
230 idr_remove(&nbd_index_idr
, nbd
->index
);
232 mutex_unlock(&nbd_index_mutex
);
236 static int nbd_disconnected(struct nbd_config
*config
)
238 return test_bit(NBD_DISCONNECTED
, &config
->runtime_flags
) ||
239 test_bit(NBD_DISCONNECT_REQUESTED
, &config
->runtime_flags
);
242 static void nbd_mark_nsock_dead(struct nbd_device
*nbd
, struct nbd_sock
*nsock
,
245 if (!nsock
->dead
&& notify
&& !nbd_disconnected(nbd
->config
)) {
246 struct link_dead_args
*args
;
247 args
= kmalloc(sizeof(struct link_dead_args
), GFP_NOIO
);
249 INIT_WORK(&args
->work
, nbd_dead_link_work
);
250 args
->index
= nbd
->index
;
251 queue_work(system_wq
, &args
->work
);
255 kernel_sock_shutdown(nsock
->sock
, SHUT_RDWR
);
256 if (atomic_dec_return(&nbd
->config
->live_connections
) == 0) {
257 if (test_and_clear_bit(NBD_DISCONNECT_REQUESTED
,
258 &nbd
->config
->runtime_flags
)) {
259 set_bit(NBD_DISCONNECTED
,
260 &nbd
->config
->runtime_flags
);
261 dev_info(nbd_to_dev(nbd
),
262 "Disconnected due to user request.\n");
267 nsock
->pending
= NULL
;
271 static void nbd_size_clear(struct nbd_device
*nbd
)
273 if (nbd
->config
->bytesize
) {
274 set_capacity(nbd
->disk
, 0);
275 kobject_uevent(&nbd_to_dev(nbd
)->kobj
, KOBJ_CHANGE
);
279 static void nbd_size_update(struct nbd_device
*nbd
)
281 struct nbd_config
*config
= nbd
->config
;
282 struct block_device
*bdev
= bdget_disk(nbd
->disk
, 0);
284 if (config
->flags
& NBD_FLAG_SEND_TRIM
) {
285 nbd
->disk
->queue
->limits
.discard_granularity
= config
->blksize
;
286 nbd
->disk
->queue
->limits
.discard_alignment
= config
->blksize
;
287 blk_queue_max_discard_sectors(nbd
->disk
->queue
, UINT_MAX
);
289 blk_queue_logical_block_size(nbd
->disk
->queue
, config
->blksize
);
290 blk_queue_physical_block_size(nbd
->disk
->queue
, config
->blksize
);
291 set_capacity(nbd
->disk
, config
->bytesize
>> 9);
294 bd_set_size(bdev
, config
->bytesize
);
295 set_blocksize(bdev
, config
->blksize
);
297 bdev
->bd_invalidated
= 1;
300 kobject_uevent(&nbd_to_dev(nbd
)->kobj
, KOBJ_CHANGE
);
303 static void nbd_size_set(struct nbd_device
*nbd
, loff_t blocksize
,
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
;
331 if (config
->num_connections
== 0)
333 if (test_and_set_bit(NBD_DISCONNECTED
, &config
->runtime_flags
))
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
,
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
);
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
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
);
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
);
401 blk_mq_complete_request(req
);
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
;
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"));
424 msg
.msg_iter
= *iter
;
426 noreclaim_flag
= memalloc_noreclaim_save();
428 sock
->sk
->sk_allocation
= GFP_NOIO
| __GFP_MEMALLOC
;
431 msg
.msg_control
= NULL
;
432 msg
.msg_controllen
= 0;
433 msg
.msg_flags
= msg_flags
| MSG_NOSIGNAL
;
436 result
= sock_sendmsg(sock
, &msg
);
438 result
= sock_recvmsg(sock
, &msg
, msg
.msg_flags
);
442 result
= -EPIPE
; /* short read */
447 } while (msg_data_left(&msg
));
449 memalloc_noreclaim_restore(noreclaim_flag
);
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
];
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
);
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
)) {
487 type
= NBD_CMD_FLUSH
;
490 type
= NBD_CMD_WRITE
;
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");
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
514 if (sent
>= sizeof(request
)) {
515 skip
= sent
- sizeof(request
);
518 iov_iter_advance(&from
, sent
);
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
);
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
545 nsock
->pending
= req
;
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
);
556 if (type
!= NBD_CMD_WRITE
)
561 struct bio
*next
= bio
->bi_next
;
562 struct bvec_iter iter
;
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",
571 iov_iter_bvec(&from
, ITER_BVEC
| WRITE
,
572 &bvec
, 1, bvec
.bv_len
);
574 if (skip
>= iov_iter_count(&from
)) {
575 skip
-= iov_iter_count(&from
);
578 iov_iter_advance(&from
, skip
);
581 result
= sock_xmit(nbd
, index
, 1, &from
, flags
, &sent
);
583 if (was_interrupted(result
)) {
584 /* We've already sent the header, we
585 * have no choice but to set pending and
588 nsock
->pending
= req
;
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",
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
610 nsock
->pending
= NULL
;
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
;
620 struct nbd_reply reply
;
622 struct request
*req
= NULL
;
626 struct kvec iov
= {.iov_base
= &reply
, .iov_len
= sizeof(reply
)};
631 iov_iter_kvec(&to
, READ
| ITER_KVEC
, &iov
, 1, sizeof(reply
));
632 result
= sock_xmit(nbd
, index
, 0, &to
, MSG_WAITALL
, NULL
);
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",
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
));
666 if (cmd
->status
!= BLK_STS_OK
) {
667 dev_err(disk_to_dev(nbd
->disk
), "Command already handled %p\n",
672 if (test_bit(NBD_CMD_REQUEUED
, &cmd
->flags
)) {
673 dev_err(disk_to_dev(nbd
->disk
), "Raced with timeout on req %p\n",
678 if (ntohl(reply
.error
)) {
679 dev_err(disk_to_dev(nbd
->disk
), "Other side returned error (%d)\n",
681 cmd
->status
= BLK_STS_IOERR
;
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
;
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
);
695 dev_err(disk_to_dev(nbd
->disk
), "Receive data failed (result %d)\n",
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
;
712 dev_dbg(nbd_to_dev(nbd
), "request %p: got %d bytes data\n",
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
,
726 struct nbd_device
*nbd
= args
->nbd
;
727 struct nbd_config
*config
= nbd
->config
;
731 cmd
= nbd_read_stat(nbd
, args
->index
);
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
);
741 blk_mq_complete_request(blk_mq_rq_from_pdu(cmd
));
743 atomic_dec(&config
->recv_threads
);
744 wake_up(&config
->recv_wq
);
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
;
772 struct nbd_sock
*nsock
= config
->socks
[index
];
773 int fallback
= nsock
->fallback_index
;
775 if (test_bit(NBD_DISCONNECTED
, &config
->runtime_flags
))
778 if (config
->num_connections
<= 1) {
779 dev_err_ratelimited(disk_to_dev(nbd
->disk
),
780 "Attempted send on invalid socket\n");
784 if (fallback
>= 0 && fallback
< config
->num_connections
&&
785 !config
->socks
[fallback
]->dead
)
788 if (nsock
->fallback_index
< 0 ||
789 nsock
->fallback_index
>= config
->num_connections
||
790 config
->socks
[nsock
->fallback_index
]->dead
) {
792 for (i
= 0; i
< config
->num_connections
; i
++) {
795 if (!config
->socks
[i
]->dead
) {
800 nsock
->fallback_index
= new_index
;
802 dev_err_ratelimited(disk_to_dev(nbd
->disk
),
803 "Dead connection, failed to find a fallback\n");
807 new_index
= nsock
->fallback_index
;
811 static int wait_for_reconnect(struct nbd_device
*nbd
)
813 struct nbd_config
*config
= nbd
->config
;
814 if (!config
->dead_conn_timeout
)
816 if (test_bit(NBD_DISCONNECTED
, &config
->runtime_flags
))
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
;
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
);
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");
843 blk_mq_start_request(req
);
846 cmd
->status
= BLK_STS_OK
;
848 nsock
= config
->socks
[index
];
849 mutex_lock(&nsock
->tx_lock
);
851 int old_index
= index
;
852 index
= find_fallback(nbd
, index
);
853 mutex_unlock(&nsock
->tx_lock
);
855 if (wait_for_reconnect(nbd
)) {
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.
867 blk_mq_start_request(req
);
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
878 blk_mq_start_request(req
);
879 if (unlikely(nsock
->pending
&& nsock
->pending
!= req
)) {
880 nbd_requeue_cmd(cmd
);
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
);
897 mutex_unlock(&nsock
->tx_lock
);
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
);
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
925 ret
= nbd_handle_cmd(cmd
, hctx
->queue_num
);
930 mutex_unlock(&cmd
->lock
);
935 static struct socket
*nbd_get_socket(struct nbd_device
*nbd
, unsigned long fd
,
941 sock
= sockfd_lookup(fd
, err
);
945 if (sock
->ops
->shutdown
== sock_no_shutdown
) {
946 dev_err(disk_to_dev(nbd
->disk
), "Unsupported socket: shutdown callout must be supported.\n");
955 static int nbd_add_socket(struct nbd_device
*nbd
, unsigned long arg
,
958 struct nbd_config
*config
= nbd
->config
;
960 struct nbd_sock
**socks
;
961 struct nbd_sock
*nsock
;
964 sock
= nbd_get_socket(nbd
, arg
, &err
);
968 if (!netlink
&& !nbd
->task_setup
&&
969 !test_bit(NBD_BOUND
, &config
->runtime_flags
))
970 nbd
->task_setup
= current
;
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");
981 nsock
= kzalloc(sizeof(*nsock
), GFP_KERNEL
);
987 socks
= krealloc(config
->socks
, (config
->num_connections
+ 1) *
988 sizeof(struct nbd_sock
*), GFP_KERNEL
);
995 config
->socks
= socks
;
997 nsock
->fallback_index
= -1;
999 mutex_init(&nsock
->tx_lock
);
1001 nsock
->pending
= NULL
;
1004 socks
[config
->num_connections
++] = nsock
;
1005 atomic_inc(&config
->live_connections
);
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
;
1022 sock
= nbd_get_socket(nbd
, arg
, &err
);
1026 args
= kzalloc(sizeof(*args
), GFP_KERNEL
);
1032 for (i
= 0; i
< config
->num_connections
; i
++) {
1033 struct nbd_sock
*nsock
= config
->socks
[i
];
1038 mutex_lock(&nsock
->tx_lock
);
1040 mutex_unlock(&nsock
->tx_lock
);
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
);
1049 nsock
->fallback_index
= -1;
1051 nsock
->dead
= false;
1052 INIT_WORK(&args
->work
, recv_work
);
1056 mutex_unlock(&nsock
->tx_lock
);
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
);
1075 static void nbd_bdev_reset(struct block_device
*bdev
)
1077 if (bdev
->bd_openers
> 1)
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);
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);
1095 blk_queue_write_cache(nbd
->disk
->queue
, true, false);
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
;
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
);
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
);
1135 static void nbd_clear_sock(struct nbd_device
*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
) {
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
);
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
);
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
;
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");
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");
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
);
1212 dev_err(disk_to_dev(nbd
->disk
), "device_create_file failed!\n");
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
);
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.
1233 flush_workqueue(nbd
->recv_workq
);
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
);
1245 queue_work(nbd
->recv_workq
, &args
->work
);
1247 nbd_size_update(nbd
);
1251 static int nbd_start_device_ioctl(struct nbd_device
*nbd
, struct block_device
*bdev
)
1253 struct nbd_config
*config
= nbd
->config
;
1256 ret
= nbd_start_device(nbd
);
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);
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
))
1274 if (test_bit(NBD_TIMEDOUT
, &config
->runtime_flags
))
1279 static void nbd_clear_sock_ioctl(struct nbd_device
*nbd
,
1280 struct block_device
*bdev
)
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
)
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
;
1305 case NBD_DISCONNECT
:
1306 return nbd_disconnect(nbd
);
1307 case NBD_CLEAR_SOCK
:
1308 nbd_clear_sock_ioctl(nbd
, bdev
);
1311 return nbd_add_socket(nbd
, arg
, false);
1312 case NBD_SET_BLKSIZE
:
1314 arg
= NBD_DEF_BLKSIZE
;
1315 if (!nbd_is_valid_blksize(arg
))
1317 nbd_size_set(nbd
, arg
,
1318 div_s64(config
->bytesize
, arg
));
1321 nbd_size_set(nbd
, config
->blksize
,
1322 div_s64(arg
, config
->blksize
));
1324 case NBD_SET_SIZE_BLOCKS
:
1325 nbd_size_set(nbd
, config
->blksize
, arg
);
1327 case NBD_SET_TIMEOUT
:
1329 nbd
->tag_set
.timeout
= arg
* HZ
;
1330 blk_queue_rq_timeout(nbd
->disk
->queue
, arg
* HZ
);
1335 config
->flags
= arg
;
1338 return nbd_start_device_ioctl(nbd
, bdev
);
1341 * This is for compatibility only. The queue is always cleared
1342 * by NBD_DO_IT or NBD_CLEAR_SOCK.
1345 case NBD_PRINT_DEBUG
:
1347 * For compatibility only, we no longer keep a list of
1348 * outstanding requests.
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
))
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)
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
);
1380 dev_err(nbd_to_dev(nbd
), "Cannot use ioctl interface on a netlink controlled device.\n");
1381 mutex_unlock(&nbd
->config_lock
);
1385 static struct nbd_config
*nbd_alloc_config(void)
1387 struct nbd_config
*config
;
1389 config
= kzalloc(sizeof(struct nbd_config
), GFP_NOFS
);
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
);
1401 static int nbd_open(struct block_device
*bdev
, fmode_t mode
)
1403 struct nbd_device
*nbd
;
1406 mutex_lock(&nbd_index_mutex
);
1407 nbd
= bdev
->bd_disk
->private_data
;
1412 if (!refcount_inc_not_zero(&nbd
->refs
)) {
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
);
1424 config
= nbd
->config
= nbd_alloc_config();
1427 mutex_unlock(&nbd
->config_lock
);
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;
1438 mutex_unlock(&nbd_index_mutex
);
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
);
1455 static const struct block_device_operations nbd_fops
=
1457 .owner
= THIS_MODULE
,
1459 .release
= nbd_release
,
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;
1471 seq_printf(s
, "recv: %d\n", task_pid_nr(nbd
->task_recv
));
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
,
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");
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
,
1519 .llseek
= seq_lseek
,
1520 .release
= single_release
,
1523 static int nbd_dev_dbg_init(struct nbd_device
*nbd
)
1526 struct nbd_config
*config
= nbd
->config
;
1531 dir
= debugfs_create_dir(nbd_name(nbd
), nbd_dbg_dir
);
1533 dev_err(nbd_to_dev(nbd
), "Failed to create debugfs dir for '%s'\n",
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
);
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
);
1561 nbd_dbg_dir
= dbg_dir
;
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
)
1578 static void nbd_dev_dbg_close(struct nbd_device
*nbd
)
1582 static int nbd_dbg_init(void)
1587 static void nbd_dbg_close(void)
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
;
1599 mutex_init(&cmd
->lock
);
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
;
1617 nbd
= kzalloc(sizeof(struct nbd_device
), GFP_KERNEL
);
1621 disk
= alloc_disk(1 << part_shift
);
1626 err
= idr_alloc(&nbd_index_idr
, nbd
, index
, index
+ 1,
1631 err
= idr_alloc(&nbd_index_idr
, nbd
, 0, 0, GFP_KERNEL
);
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
);
1653 q
= blk_mq_init_queue(&nbd
->tag_set
);
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
);
1683 nbd_total_devices
++;
1687 blk_mq_free_tag_set(&nbd
->tag_set
);
1689 idr_remove(&nbd_index_idr
, index
);
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
)) {
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
;
1742 bool put_dev
= false;
1744 if (!netlink_capable(skb
, CAP_SYS_ADMIN
))
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");
1753 if (!info
->attrs
[NBD_ATTR_SIZE_BYTES
]) {
1754 printk(KERN_ERR
"nbd: must specify a size in bytes for the device\n");
1758 mutex_lock(&nbd_index_mutex
);
1760 ret
= idr_for_each(&nbd_index_idr
, &find_free_cb
, &nbd
);
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");
1769 nbd
= idr_find(&nbd_index_idr
, new_index
);
1772 nbd
= idr_find(&nbd_index_idr
, index
);
1774 ret
= nbd_dev_add(index
);
1776 mutex_unlock(&nbd_index_mutex
);
1777 printk(KERN_ERR
"nbd: failed to add new device\n");
1780 nbd
= idr_find(&nbd_index_idr
, index
);
1784 printk(KERN_ERR
"nbd: couldn't find device at index %d\n",
1786 mutex_unlock(&nbd_index_mutex
);
1789 if (!refcount_inc_not_zero(&nbd
->refs
)) {
1790 mutex_unlock(&nbd_index_mutex
);
1793 printk(KERN_ERR
"nbd: device at index %d is going down\n",
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
);
1805 printk(KERN_ERR
"nbd: nbd%d already in use\n", index
);
1808 if (WARN_ON(nbd
->config
)) {
1809 mutex_unlock(&nbd
->config_lock
);
1813 config
= nbd
->config
= nbd_alloc_config();
1815 mutex_unlock(&nbd
->config_lock
);
1817 printk(KERN_ERR
"nbd: couldn't allocate config\n");
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
]) {
1830 nla_get_u64(info
->attrs
[NBD_ATTR_BLOCK_SIZE_BYTES
]);
1832 bsize
= NBD_DEF_BLKSIZE
;
1833 if (!nbd_is_valid_blksize(bsize
)) {
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
])
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
);
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
;
1869 nla_for_each_nested(attr
, info
->attrs
[NBD_ATTR_SOCKETS
],
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");
1878 ret
= nla_parse_nested(socks
, NBD_SOCK_MAX
, attr
,
1879 nbd_sock_policy
, info
->extack
);
1881 printk(KERN_ERR
"nbd: error processing sock list\n");
1885 if (!socks
[NBD_SOCK_FD
])
1887 fd
= (int)nla_get_u32(socks
[NBD_SOCK_FD
]);
1888 ret
= nbd_add_socket(nbd
, fd
, true);
1893 ret
= nbd_start_device(nbd
);
1895 mutex_unlock(&nbd
->config_lock
);
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
);
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
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
;
1929 if (!netlink_capable(skb
, CAP_SYS_ADMIN
))
1932 if (!info
->attrs
[NBD_ATTR_INDEX
]) {
1933 printk(KERN_ERR
"nbd: must specify an index to disconnect\n");
1936 index
= nla_get_u32(info
->attrs
[NBD_ATTR_INDEX
]);
1937 mutex_lock(&nbd_index_mutex
);
1938 nbd
= idr_find(&nbd_index_idr
, index
);
1940 mutex_unlock(&nbd_index_mutex
);
1941 printk(KERN_ERR
"nbd: couldn't find device at index %d\n",
1945 if (!refcount_inc_not_zero(&nbd
->refs
)) {
1946 mutex_unlock(&nbd_index_mutex
);
1947 printk(KERN_ERR
"nbd: device at index %d is going down\n",
1951 mutex_unlock(&nbd_index_mutex
);
1952 if (!refcount_inc_not_zero(&nbd
->config_refs
)) {
1956 nbd_disconnect_and_put(nbd
);
1957 nbd_config_put(nbd
);
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
;
1968 bool put_dev
= false;
1970 if (!netlink_capable(skb
, CAP_SYS_ADMIN
))
1973 if (!info
->attrs
[NBD_ATTR_INDEX
]) {
1974 printk(KERN_ERR
"nbd: must specify a device to reconfigure\n");
1977 index
= nla_get_u32(info
->attrs
[NBD_ATTR_INDEX
]);
1978 mutex_lock(&nbd_index_mutex
);
1979 nbd
= idr_find(&nbd_index_idr
, index
);
1981 mutex_unlock(&nbd_index_mutex
);
1982 printk(KERN_ERR
"nbd: couldn't find a device at index %d\n",
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",
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");
2001 mutex_lock(&nbd
->config_lock
);
2002 config
= nbd
->config
;
2003 if (!test_bit(NBD_BOUND
, &config
->runtime_flags
) ||
2005 dev_err(nbd_to_dev(nbd
),
2006 "not configured, cannot reconfigure\n");
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
))
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
);
2037 clear_bit(NBD_DISCONNECT_ON_CLOSE
,
2038 &config
->runtime_flags
);
2042 if (info
->attrs
[NBD_ATTR_SOCKETS
]) {
2043 struct nlattr
*attr
;
2046 nla_for_each_nested(attr
, info
->attrs
[NBD_ATTR_SOCKETS
],
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");
2055 ret
= nla_parse_nested(socks
, NBD_SOCK_MAX
, attr
,
2056 nbd_sock_policy
, info
->extack
);
2058 printk(KERN_ERR
"nbd: error processing sock list\n");
2062 if (!socks
[NBD_SOCK_FD
])
2064 fd
= (int)nla_get_u32(socks
[NBD_SOCK_FD
]);
2065 ret
= nbd_reconnect_socket(nbd
, fd
);
2071 dev_info(nbd_to_dev(nbd
), "reconnected socket\n");
2075 mutex_unlock(&nbd
->config_lock
);
2076 nbd_config_put(nbd
);
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
= {
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
;
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
))
2137 dev_opt
= nla_nest_start(reply
, NBD_DEVICE_ITEM
);
2140 ret
= nla_put_u32(reply
, NBD_DEVICE_INDEX
, nbd
->index
);
2143 ret
= nla_put_u8(reply
, NBD_DEVICE_CONNECTED
,
2147 nla_nest_end(reply
, dev_opt
);
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
;
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
);
2178 reply_head
= genlmsg_put_reply(reply
, info
, &nbd_genl_family
, 0,
2185 dev_list
= nla_nest_start(reply
, NBD_ATTR_DEVICE_LIST
);
2187 ret
= idr_for_each(&nbd_index_idr
, &status_cb
, reply
);
2193 struct nbd_device
*nbd
;
2194 nbd
= idr_find(&nbd_index_idr
, index
);
2196 ret
= populate_nbd_status(nbd
, reply
);
2203 nla_nest_end(reply
, dev_list
);
2204 genlmsg_end(reply
, reply_head
);
2205 genlmsg_reply(reply
, info
);
2208 mutex_unlock(&nbd_index_mutex
);
2212 static void nbd_connect_reply(struct genl_info
*info
, int index
)
2214 struct sk_buff
*skb
;
2218 skb
= genlmsg_new(nla_total_size(sizeof(u32
)), GFP_KERNEL
);
2221 msg_head
= genlmsg_put_reply(skb
, info
, &nbd_genl_family
, 0,
2227 ret
= nla_put_u32(skb
, NBD_ATTR_INDEX
, index
);
2232 genlmsg_end(skb
, msg_head
);
2233 genlmsg_reply(skb
, info
);
2236 static void nbd_mcast_index(int index
)
2238 struct sk_buff
*skb
;
2242 skb
= genlmsg_new(nla_total_size(sizeof(u32
)), GFP_KERNEL
);
2245 msg_head
= genlmsg_put(skb
, 0, 0, &nbd_genl_family
, 0,
2251 ret
= nla_put_u32(skb
, NBD_ATTR_INDEX
, index
);
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
,
2264 nbd_mcast_index(args
->index
);
2268 static int __init
nbd_init(void)
2272 BUILD_BUG_ON(sizeof(struct nbd_request
) != 28);
2275 printk(KERN_ERR
"nbd: max_part must be >= 0\n");
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
)
2297 if (nbds_max
> 1UL << (MINORBITS
- part_shift
))
2300 if (register_blkdev(NBD_MAJOR
, "nbd"))
2303 if (genl_register_family(&nbd_genl_family
)) {
2304 unregister_blkdev(NBD_MAJOR
, "nbd");
2309 mutex_lock(&nbd_index_mutex
);
2310 for (i
= 0; i
< nbds_max
; i
++)
2312 mutex_unlock(&nbd_index_mutex
);
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
);
2325 static void __exit
nbd_cleanup(void)
2327 struct nbd_device
*nbd
;
2328 LIST_HEAD(del_list
);
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");
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)");