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.
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 #define CREATE_TRACE_POINTS
48 #include <trace/events/nbd.h>
50 static DEFINE_IDR(nbd_index_idr);
51 static DEFINE_MUTEX(nbd_index_mutex);
52 static int nbd_total_devices = 0;
57 struct request *pending;
64 struct recv_thread_args {
65 struct work_struct work;
66 struct nbd_device *nbd;
70 struct link_dead_args {
71 struct work_struct work;
75 #define NBD_TIMEDOUT 0
76 #define NBD_DISCONNECT_REQUESTED 1
77 #define NBD_DISCONNECTED 2
78 #define NBD_HAS_PID_FILE 3
79 #define NBD_HAS_CONFIG_REF 4
81 #define NBD_DESTROY_ON_DISCONNECT 6
82 #define NBD_DISCONNECT_ON_CLOSE 7
86 unsigned long runtime_flags;
87 u64 dead_conn_timeout;
89 struct nbd_sock **socks;
91 atomic_t live_connections;
92 wait_queue_head_t conn_wait;
94 atomic_t recv_threads;
95 wait_queue_head_t recv_wq;
98 #if IS_ENABLED(CONFIG_DEBUG_FS)
99 struct dentry *dbg_dir;
104 struct blk_mq_tag_set tag_set;
107 refcount_t config_refs;
109 struct nbd_config *config;
110 struct mutex config_lock;
111 struct gendisk *disk;
113 struct list_head list;
114 struct task_struct *task_recv;
115 struct task_struct *task_setup;
118 #define NBD_CMD_REQUEUED 1
121 struct nbd_device *nbd;
130 #if IS_ENABLED(CONFIG_DEBUG_FS)
131 static struct dentry *nbd_dbg_dir;
134 #define nbd_name(nbd) ((nbd)->disk->disk_name)
136 #define NBD_MAGIC 0x68797548
138 static unsigned int nbds_max = 16;
139 static int max_part = 16;
140 static struct workqueue_struct *recv_workqueue;
141 static int part_shift;
143 static int nbd_dev_dbg_init(struct nbd_device *nbd);
144 static void nbd_dev_dbg_close(struct nbd_device *nbd);
145 static void nbd_config_put(struct nbd_device *nbd);
146 static void nbd_connect_reply(struct genl_info *info, int index);
147 static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info);
148 static void nbd_dead_link_work(struct work_struct *work);
149 static void nbd_disconnect_and_put(struct nbd_device *nbd);
151 static inline struct device *nbd_to_dev(struct nbd_device *nbd)
153 return disk_to_dev(nbd->disk);
156 static void nbd_requeue_cmd(struct nbd_cmd *cmd)
158 struct request *req = blk_mq_rq_from_pdu(cmd);
160 if (!test_and_set_bit(NBD_CMD_REQUEUED, &cmd->flags))
161 blk_mq_requeue_request(req, true);
164 #define NBD_COOKIE_BITS 32
166 static u64 nbd_cmd_handle(struct nbd_cmd *cmd)
168 struct request *req = blk_mq_rq_from_pdu(cmd);
169 u32 tag = blk_mq_unique_tag(req);
170 u64 cookie = cmd->cmd_cookie;
172 return (cookie << NBD_COOKIE_BITS) | tag;
175 static u32 nbd_handle_to_tag(u64 handle)
180 static u32 nbd_handle_to_cookie(u64 handle)
182 return (u32)(handle >> NBD_COOKIE_BITS);
185 static const char *nbdcmd_to_ascii(int cmd)
188 case NBD_CMD_READ: return "read";
189 case NBD_CMD_WRITE: return "write";
190 case NBD_CMD_DISC: return "disconnect";
191 case NBD_CMD_FLUSH: return "flush";
192 case NBD_CMD_TRIM: return "trim/discard";
197 static ssize_t pid_show(struct device *dev,
198 struct device_attribute *attr, char *buf)
200 struct gendisk *disk = dev_to_disk(dev);
201 struct nbd_device *nbd = (struct nbd_device *)disk->private_data;
203 return sprintf(buf, "%d\n", task_pid_nr(nbd->task_recv));
206 static const struct device_attribute pid_attr = {
207 .attr = { .name = "pid", .mode = 0444},
211 static void nbd_dev_remove(struct nbd_device *nbd)
213 struct gendisk *disk = nbd->disk;
214 struct request_queue *q;
219 blk_cleanup_queue(q);
220 blk_mq_free_tag_set(&nbd->tag_set);
221 disk->private_data = NULL;
227 static void nbd_put(struct nbd_device *nbd)
229 if (refcount_dec_and_mutex_lock(&nbd->refs,
231 idr_remove(&nbd_index_idr, nbd->index);
232 mutex_unlock(&nbd_index_mutex);
237 static int nbd_disconnected(struct nbd_config *config)
239 return test_bit(NBD_DISCONNECTED, &config->runtime_flags) ||
240 test_bit(NBD_DISCONNECT_REQUESTED, &config->runtime_flags);
243 static void nbd_mark_nsock_dead(struct nbd_device *nbd, struct nbd_sock *nsock,
246 if (!nsock->dead && notify && !nbd_disconnected(nbd->config)) {
247 struct link_dead_args *args;
248 args = kmalloc(sizeof(struct link_dead_args), GFP_NOIO);
250 INIT_WORK(&args->work, nbd_dead_link_work);
251 args->index = nbd->index;
252 queue_work(system_wq, &args->work);
256 kernel_sock_shutdown(nsock->sock, SHUT_RDWR);
257 if (atomic_dec_return(&nbd->config->live_connections) == 0) {
258 if (test_and_clear_bit(NBD_DISCONNECT_REQUESTED,
259 &nbd->config->runtime_flags)) {
260 set_bit(NBD_DISCONNECTED,
261 &nbd->config->runtime_flags);
262 dev_info(nbd_to_dev(nbd),
263 "Disconnected due to user request.\n");
268 nsock->pending = NULL;
272 static void nbd_size_clear(struct nbd_device *nbd)
274 if (nbd->config->bytesize) {
275 set_capacity(nbd->disk, 0);
276 kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
280 static void nbd_size_update(struct nbd_device *nbd)
282 struct nbd_config *config = nbd->config;
283 struct block_device *bdev = bdget_disk(nbd->disk, 0);
285 if (config->flags & NBD_FLAG_SEND_TRIM) {
286 nbd->disk->queue->limits.discard_granularity = config->blksize;
287 nbd->disk->queue->limits.discard_alignment = config->blksize;
288 blk_queue_max_discard_sectors(nbd->disk->queue, UINT_MAX);
290 blk_queue_logical_block_size(nbd->disk->queue, config->blksize);
291 blk_queue_physical_block_size(nbd->disk->queue, config->blksize);
292 set_capacity(nbd->disk, config->bytesize >> 9);
295 bd_set_size(bdev, config->bytesize);
296 set_blocksize(bdev, config->blksize);
298 bdev->bd_invalidated = 1;
301 kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
304 static void nbd_size_set(struct nbd_device *nbd, loff_t blocksize,
307 struct nbd_config *config = nbd->config;
308 config->blksize = blocksize;
309 config->bytesize = blocksize * nr_blocks;
310 if (nbd->task_recv != NULL)
311 nbd_size_update(nbd);
314 static void nbd_complete_rq(struct request *req)
316 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
318 dev_dbg(nbd_to_dev(cmd->nbd), "request %p: %s\n", req,
319 cmd->status ? "failed" : "done");
321 blk_mq_end_request(req, cmd->status);
325 * Forcibly shutdown the socket causing all listeners to error
327 static void sock_shutdown(struct nbd_device *nbd)
329 struct nbd_config *config = nbd->config;
332 if (config->num_connections == 0)
334 if (test_and_set_bit(NBD_DISCONNECTED, &config->runtime_flags))
337 for (i = 0; i < config->num_connections; i++) {
338 struct nbd_sock *nsock = config->socks[i];
339 mutex_lock(&nsock->tx_lock);
340 nbd_mark_nsock_dead(nbd, nsock, 0);
341 mutex_unlock(&nsock->tx_lock);
343 dev_warn(disk_to_dev(nbd->disk), "shutting down sockets\n");
346 static enum blk_eh_timer_return nbd_xmit_timeout(struct request *req,
349 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
350 struct nbd_device *nbd = cmd->nbd;
351 struct nbd_config *config;
353 if (!refcount_inc_not_zero(&nbd->config_refs)) {
354 cmd->status = BLK_STS_TIMEOUT;
357 config = nbd->config;
359 if (!mutex_trylock(&cmd->lock))
360 return BLK_EH_RESET_TIMER;
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, &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);
517 /* initialize handle for tracing purposes */
518 handle = nbd_cmd_handle(cmd);
522 iov_iter_advance(&from, sent);
527 cmd->cookie = nsock->cookie;
528 request.type = htonl(type | nbd_cmd_flags);
529 if (type != NBD_CMD_FLUSH) {
530 request.from = cpu_to_be64((u64)blk_rq_pos(req) << 9);
531 request.len = htonl(size);
533 handle = nbd_cmd_handle(cmd);
534 memcpy(request.handle, &handle, sizeof(handle));
536 trace_nbd_send_request(&request, nbd->index, blk_mq_rq_from_pdu(cmd));
538 dev_dbg(nbd_to_dev(nbd), "request %p: sending control (%s@%llu,%uB)\n",
539 req, nbdcmd_to_ascii(type),
540 (unsigned long long)blk_rq_pos(req) << 9, blk_rq_bytes(req));
541 result = sock_xmit(nbd, index, 1, &from,
542 (type == NBD_CMD_WRITE) ? MSG_MORE : 0, &sent);
543 trace_nbd_header_sent(req, handle);
545 if (was_interrupted(result)) {
546 /* If we havne't sent anything we can just return BUSY,
547 * however if we have sent something we need to make
548 * sure we only allow this req to be sent until we are
552 nsock->pending = req;
555 set_bit(NBD_CMD_REQUEUED, &cmd->flags);
556 return BLK_STS_RESOURCE;
558 dev_err_ratelimited(disk_to_dev(nbd->disk),
559 "Send control failed (result %d)\n", result);
563 if (type != NBD_CMD_WRITE)
568 struct bio *next = bio->bi_next;
569 struct bvec_iter iter;
572 bio_for_each_segment(bvec, bio, iter) {
573 bool is_last = !next && bio_iter_last(bvec, iter);
574 int flags = is_last ? 0 : MSG_MORE;
576 dev_dbg(nbd_to_dev(nbd), "request %p: sending %d bytes data\n",
578 iov_iter_bvec(&from, WRITE, &bvec, 1, bvec.bv_len);
580 if (skip >= iov_iter_count(&from)) {
581 skip -= iov_iter_count(&from);
584 iov_iter_advance(&from, skip);
587 result = sock_xmit(nbd, index, 1, &from, flags, &sent);
589 if (was_interrupted(result)) {
590 /* We've already sent the header, we
591 * have no choice but to set pending and
594 nsock->pending = req;
596 set_bit(NBD_CMD_REQUEUED, &cmd->flags);
597 return BLK_STS_RESOURCE;
599 dev_err(disk_to_dev(nbd->disk),
600 "Send data failed (result %d)\n",
605 * The completion might already have come in,
606 * so break for the last one instead of letting
607 * the iterator do it. This prevents use-after-free
616 trace_nbd_payload_sent(req, handle);
617 nsock->pending = NULL;
622 /* NULL returned = something went wrong, inform userspace */
623 static struct nbd_cmd *nbd_read_stat(struct nbd_device *nbd, int index)
625 struct nbd_config *config = nbd->config;
627 struct nbd_reply reply;
629 struct request *req = NULL;
633 struct kvec iov = {.iov_base = &reply, .iov_len = sizeof(reply)};
638 iov_iter_kvec(&to, READ, &iov, 1, sizeof(reply));
639 result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
641 if (!nbd_disconnected(config))
642 dev_err(disk_to_dev(nbd->disk),
643 "Receive control failed (result %d)\n", result);
644 return ERR_PTR(result);
647 if (ntohl(reply.magic) != NBD_REPLY_MAGIC) {
648 dev_err(disk_to_dev(nbd->disk), "Wrong magic (0x%lx)\n",
649 (unsigned long)ntohl(reply.magic));
650 return ERR_PTR(-EPROTO);
653 memcpy(&handle, reply.handle, sizeof(handle));
654 tag = nbd_handle_to_tag(handle);
655 hwq = blk_mq_unique_tag_to_hwq(tag);
656 if (hwq < nbd->tag_set.nr_hw_queues)
657 req = blk_mq_tag_to_rq(nbd->tag_set.tags[hwq],
658 blk_mq_unique_tag_to_tag(tag));
659 if (!req || !blk_mq_request_started(req)) {
660 dev_err(disk_to_dev(nbd->disk), "Unexpected reply (%d) %p\n",
662 return ERR_PTR(-ENOENT);
664 trace_nbd_header_received(req, handle);
665 cmd = blk_mq_rq_to_pdu(req);
667 mutex_lock(&cmd->lock);
668 if (cmd->cmd_cookie != nbd_handle_to_cookie(handle)) {
669 dev_err(disk_to_dev(nbd->disk), "Double reply on req %p, cmd_cookie %u, handle cookie %u\n",
670 req, cmd->cmd_cookie, nbd_handle_to_cookie(handle));
674 if (test_bit(NBD_CMD_REQUEUED, &cmd->flags)) {
675 dev_err(disk_to_dev(nbd->disk), "Raced with timeout on req %p\n",
680 if (ntohl(reply.error)) {
681 dev_err(disk_to_dev(nbd->disk), "Other side returned error (%d)\n",
683 cmd->status = BLK_STS_IOERR;
687 dev_dbg(nbd_to_dev(nbd), "request %p: got reply\n", req);
688 if (rq_data_dir(req) != WRITE) {
689 struct req_iterator iter;
692 rq_for_each_segment(bvec, req, iter) {
693 iov_iter_bvec(&to, READ, &bvec, 1, bvec.bv_len);
694 result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
696 dev_err(disk_to_dev(nbd->disk), "Receive data failed (result %d)\n",
699 * If we've disconnected or we only have 1
700 * connection then we need to make sure we
701 * complete this request, otherwise error out
702 * and let the timeout stuff handle resubmitting
703 * this request onto another connection.
705 if (nbd_disconnected(config) ||
706 config->num_connections <= 1) {
707 cmd->status = BLK_STS_IOERR;
713 dev_dbg(nbd_to_dev(nbd), "request %p: got %d bytes data\n",
718 trace_nbd_payload_received(req, handle);
719 mutex_unlock(&cmd->lock);
720 return ret ? ERR_PTR(ret) : cmd;
723 static void recv_work(struct work_struct *work)
725 struct recv_thread_args *args = container_of(work,
726 struct recv_thread_args,
728 struct nbd_device *nbd = args->nbd;
729 struct nbd_config *config = nbd->config;
733 cmd = nbd_read_stat(nbd, args->index);
735 struct nbd_sock *nsock = config->socks[args->index];
737 mutex_lock(&nsock->tx_lock);
738 nbd_mark_nsock_dead(nbd, nsock, 1);
739 mutex_unlock(&nsock->tx_lock);
743 blk_mq_complete_request(blk_mq_rq_from_pdu(cmd));
745 atomic_dec(&config->recv_threads);
746 wake_up(&config->recv_wq);
751 static bool nbd_clear_req(struct request *req, void *data, bool reserved)
753 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
755 cmd->status = BLK_STS_IOERR;
756 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 int nbd_add_socket(struct nbd_device *nbd, unsigned long arg,
938 struct nbd_config *config = nbd->config;
940 struct nbd_sock **socks;
941 struct nbd_sock *nsock;
944 sock = sockfd_lookup(arg, &err);
948 if (!netlink && !nbd->task_setup &&
949 !test_bit(NBD_BOUND, &config->runtime_flags))
950 nbd->task_setup = current;
953 (nbd->task_setup != current ||
954 test_bit(NBD_BOUND, &config->runtime_flags))) {
955 dev_err(disk_to_dev(nbd->disk),
956 "Device being setup by another task");
961 socks = krealloc(config->socks, (config->num_connections + 1) *
962 sizeof(struct nbd_sock *), GFP_KERNEL);
967 nsock = kzalloc(sizeof(struct nbd_sock), GFP_KERNEL);
973 config->socks = socks;
975 nsock->fallback_index = -1;
977 mutex_init(&nsock->tx_lock);
979 nsock->pending = NULL;
982 socks[config->num_connections++] = nsock;
983 atomic_inc(&config->live_connections);
988 static int nbd_reconnect_socket(struct nbd_device *nbd, unsigned long arg)
990 struct nbd_config *config = nbd->config;
991 struct socket *sock, *old;
992 struct recv_thread_args *args;
996 sock = sockfd_lookup(arg, &err);
1000 args = kzalloc(sizeof(*args), GFP_KERNEL);
1006 for (i = 0; i < config->num_connections; i++) {
1007 struct nbd_sock *nsock = config->socks[i];
1012 mutex_lock(&nsock->tx_lock);
1014 mutex_unlock(&nsock->tx_lock);
1017 sk_set_memalloc(sock->sk);
1018 if (nbd->tag_set.timeout)
1019 sock->sk->sk_sndtimeo = nbd->tag_set.timeout;
1020 atomic_inc(&config->recv_threads);
1021 refcount_inc(&nbd->config_refs);
1023 nsock->fallback_index = -1;
1025 nsock->dead = false;
1026 INIT_WORK(&args->work, recv_work);
1030 mutex_unlock(&nsock->tx_lock);
1033 clear_bit(NBD_DISCONNECTED, &config->runtime_flags);
1035 /* We take the tx_mutex in an error path in the recv_work, so we
1036 * need to queue_work outside of the tx_mutex.
1038 queue_work(recv_workqueue, &args->work);
1040 atomic_inc(&config->live_connections);
1041 wake_up(&config->conn_wait);
1049 static void nbd_bdev_reset(struct block_device *bdev)
1051 if (bdev->bd_openers > 1)
1053 bd_set_size(bdev, 0);
1056 static void nbd_parse_flags(struct nbd_device *nbd)
1058 struct nbd_config *config = nbd->config;
1059 if (config->flags & NBD_FLAG_READ_ONLY)
1060 set_disk_ro(nbd->disk, true);
1062 set_disk_ro(nbd->disk, false);
1063 if (config->flags & NBD_FLAG_SEND_TRIM)
1064 blk_queue_flag_set(QUEUE_FLAG_DISCARD, nbd->disk->queue);
1065 if (config->flags & NBD_FLAG_SEND_FLUSH) {
1066 if (config->flags & NBD_FLAG_SEND_FUA)
1067 blk_queue_write_cache(nbd->disk->queue, true, true);
1069 blk_queue_write_cache(nbd->disk->queue, true, false);
1072 blk_queue_write_cache(nbd->disk->queue, false, false);
1075 static void send_disconnects(struct nbd_device *nbd)
1077 struct nbd_config *config = nbd->config;
1078 struct nbd_request request = {
1079 .magic = htonl(NBD_REQUEST_MAGIC),
1080 .type = htonl(NBD_CMD_DISC),
1082 struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
1083 struct iov_iter from;
1086 for (i = 0; i < config->num_connections; i++) {
1087 struct nbd_sock *nsock = config->socks[i];
1089 iov_iter_kvec(&from, WRITE, &iov, 1, sizeof(request));
1090 mutex_lock(&nsock->tx_lock);
1091 ret = sock_xmit(nbd, i, 1, &from, 0, NULL);
1093 dev_err(disk_to_dev(nbd->disk),
1094 "Send disconnect failed %d\n", ret);
1095 mutex_unlock(&nsock->tx_lock);
1099 static int nbd_disconnect(struct nbd_device *nbd)
1101 struct nbd_config *config = nbd->config;
1103 dev_info(disk_to_dev(nbd->disk), "NBD_DISCONNECT\n");
1104 set_bit(NBD_DISCONNECT_REQUESTED, &config->runtime_flags);
1105 send_disconnects(nbd);
1109 static void nbd_clear_sock(struct nbd_device *nbd)
1113 nbd->task_setup = NULL;
1116 static void nbd_config_put(struct nbd_device *nbd)
1118 if (refcount_dec_and_mutex_lock(&nbd->config_refs,
1119 &nbd->config_lock)) {
1120 struct nbd_config *config = nbd->config;
1121 nbd_dev_dbg_close(nbd);
1122 nbd_size_clear(nbd);
1123 if (test_and_clear_bit(NBD_HAS_PID_FILE,
1124 &config->runtime_flags))
1125 device_remove_file(disk_to_dev(nbd->disk), &pid_attr);
1126 nbd->task_recv = NULL;
1127 nbd_clear_sock(nbd);
1128 if (config->num_connections) {
1130 for (i = 0; i < config->num_connections; i++) {
1131 sockfd_put(config->socks[i]->sock);
1132 kfree(config->socks[i]);
1134 kfree(config->socks);
1139 nbd->tag_set.timeout = 0;
1140 nbd->disk->queue->limits.discard_granularity = 0;
1141 nbd->disk->queue->limits.discard_alignment = 0;
1142 blk_queue_max_discard_sectors(nbd->disk->queue, UINT_MAX);
1143 blk_queue_flag_clear(QUEUE_FLAG_DISCARD, nbd->disk->queue);
1145 mutex_unlock(&nbd->config_lock);
1147 module_put(THIS_MODULE);
1151 static int nbd_start_device(struct nbd_device *nbd)
1153 struct nbd_config *config = nbd->config;
1154 int num_connections = config->num_connections;
1161 if (num_connections > 1 &&
1162 !(config->flags & NBD_FLAG_CAN_MULTI_CONN)) {
1163 dev_err(disk_to_dev(nbd->disk), "server does not support multiple connections per device.\n");
1167 blk_mq_update_nr_hw_queues(&nbd->tag_set, config->num_connections);
1168 nbd->task_recv = current;
1170 nbd_parse_flags(nbd);
1172 error = device_create_file(disk_to_dev(nbd->disk), &pid_attr);
1174 dev_err(disk_to_dev(nbd->disk), "device_create_file failed!\n");
1177 set_bit(NBD_HAS_PID_FILE, &config->runtime_flags);
1179 nbd_dev_dbg_init(nbd);
1180 for (i = 0; i < num_connections; i++) {
1181 struct recv_thread_args *args;
1183 args = kzalloc(sizeof(*args), GFP_KERNEL);
1188 sk_set_memalloc(config->socks[i]->sock->sk);
1189 if (nbd->tag_set.timeout)
1190 config->socks[i]->sock->sk->sk_sndtimeo =
1191 nbd->tag_set.timeout;
1192 atomic_inc(&config->recv_threads);
1193 refcount_inc(&nbd->config_refs);
1194 INIT_WORK(&args->work, recv_work);
1197 queue_work(recv_workqueue, &args->work);
1199 nbd_size_update(nbd);
1203 static int nbd_start_device_ioctl(struct nbd_device *nbd, struct block_device *bdev)
1205 struct nbd_config *config = nbd->config;
1208 ret = nbd_start_device(nbd);
1213 bdev->bd_invalidated = 1;
1214 mutex_unlock(&nbd->config_lock);
1215 ret = wait_event_interruptible(config->recv_wq,
1216 atomic_read(&config->recv_threads) == 0);
1219 mutex_lock(&nbd->config_lock);
1220 nbd_bdev_reset(bdev);
1221 /* user requested, ignore socket errors */
1222 if (test_bit(NBD_DISCONNECT_REQUESTED, &config->runtime_flags))
1224 if (test_bit(NBD_TIMEDOUT, &config->runtime_flags))
1229 static void nbd_clear_sock_ioctl(struct nbd_device *nbd,
1230 struct block_device *bdev)
1234 nbd_bdev_reset(bdev);
1235 if (test_and_clear_bit(NBD_HAS_CONFIG_REF,
1236 &nbd->config->runtime_flags))
1237 nbd_config_put(nbd);
1240 /* Must be called with config_lock held */
1241 static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
1242 unsigned int cmd, unsigned long arg)
1244 struct nbd_config *config = nbd->config;
1247 case NBD_DISCONNECT:
1248 return nbd_disconnect(nbd);
1249 case NBD_CLEAR_SOCK:
1250 nbd_clear_sock_ioctl(nbd, bdev);
1253 return nbd_add_socket(nbd, arg, false);
1254 case NBD_SET_BLKSIZE:
1255 if (!arg || !is_power_of_2(arg) || arg < 512 ||
1258 nbd_size_set(nbd, arg,
1259 div_s64(config->bytesize, arg));
1262 nbd_size_set(nbd, config->blksize,
1263 div_s64(arg, config->blksize));
1265 case NBD_SET_SIZE_BLOCKS:
1266 nbd_size_set(nbd, config->blksize, arg);
1268 case NBD_SET_TIMEOUT:
1270 nbd->tag_set.timeout = arg * HZ;
1271 blk_queue_rq_timeout(nbd->disk->queue, arg * HZ);
1276 config->flags = arg;
1279 return nbd_start_device_ioctl(nbd, bdev);
1282 * This is for compatibility only. The queue is always cleared
1283 * by NBD_DO_IT or NBD_CLEAR_SOCK.
1286 case NBD_PRINT_DEBUG:
1288 * For compatibility only, we no longer keep a list of
1289 * outstanding requests.
1296 static int nbd_ioctl(struct block_device *bdev, fmode_t mode,
1297 unsigned int cmd, unsigned long arg)
1299 struct nbd_device *nbd = bdev->bd_disk->private_data;
1300 struct nbd_config *config = nbd->config;
1301 int error = -EINVAL;
1303 if (!capable(CAP_SYS_ADMIN))
1306 /* The block layer will pass back some non-nbd ioctls in case we have
1307 * special handling for them, but we don't so just return an error.
1309 if (_IOC_TYPE(cmd) != 0xab)
1312 mutex_lock(&nbd->config_lock);
1314 /* Don't allow ioctl operations on a nbd device that was created with
1315 * netlink, unless it's DISCONNECT or CLEAR_SOCK, which are fine.
1317 if (!test_bit(NBD_BOUND, &config->runtime_flags) ||
1318 (cmd == NBD_DISCONNECT || cmd == NBD_CLEAR_SOCK))
1319 error = __nbd_ioctl(bdev, nbd, cmd, arg);
1321 dev_err(nbd_to_dev(nbd), "Cannot use ioctl interface on a netlink controlled device.\n");
1322 mutex_unlock(&nbd->config_lock);
1326 static struct nbd_config *nbd_alloc_config(void)
1328 struct nbd_config *config;
1330 config = kzalloc(sizeof(struct nbd_config), GFP_NOFS);
1333 atomic_set(&config->recv_threads, 0);
1334 init_waitqueue_head(&config->recv_wq);
1335 init_waitqueue_head(&config->conn_wait);
1336 config->blksize = 1024;
1337 atomic_set(&config->live_connections, 0);
1338 try_module_get(THIS_MODULE);
1342 static int nbd_open(struct block_device *bdev, fmode_t mode)
1344 struct nbd_device *nbd;
1347 mutex_lock(&nbd_index_mutex);
1348 nbd = bdev->bd_disk->private_data;
1353 if (!refcount_inc_not_zero(&nbd->refs)) {
1357 if (!refcount_inc_not_zero(&nbd->config_refs)) {
1358 struct nbd_config *config;
1360 mutex_lock(&nbd->config_lock);
1361 if (refcount_inc_not_zero(&nbd->config_refs)) {
1362 mutex_unlock(&nbd->config_lock);
1365 config = nbd->config = nbd_alloc_config();
1368 mutex_unlock(&nbd->config_lock);
1371 refcount_set(&nbd->config_refs, 1);
1372 refcount_inc(&nbd->refs);
1373 mutex_unlock(&nbd->config_lock);
1374 bdev->bd_invalidated = 1;
1375 } else if (nbd_disconnected(nbd->config)) {
1376 bdev->bd_invalidated = 1;
1379 mutex_unlock(&nbd_index_mutex);
1383 static void nbd_release(struct gendisk *disk, fmode_t mode)
1385 struct nbd_device *nbd = disk->private_data;
1386 struct block_device *bdev = bdget_disk(disk, 0);
1388 if (test_bit(NBD_DISCONNECT_ON_CLOSE, &nbd->config->runtime_flags) &&
1389 bdev->bd_openers == 0)
1390 nbd_disconnect_and_put(nbd);
1392 nbd_config_put(nbd);
1396 static const struct block_device_operations nbd_fops =
1398 .owner = THIS_MODULE,
1400 .release = nbd_release,
1402 .compat_ioctl = nbd_ioctl,
1405 #if IS_ENABLED(CONFIG_DEBUG_FS)
1407 static int nbd_dbg_tasks_show(struct seq_file *s, void *unused)
1409 struct nbd_device *nbd = s->private;
1412 seq_printf(s, "recv: %d\n", task_pid_nr(nbd->task_recv));
1417 static int nbd_dbg_tasks_open(struct inode *inode, struct file *file)
1419 return single_open(file, nbd_dbg_tasks_show, inode->i_private);
1422 static const struct file_operations nbd_dbg_tasks_ops = {
1423 .open = nbd_dbg_tasks_open,
1425 .llseek = seq_lseek,
1426 .release = single_release,
1429 static int nbd_dbg_flags_show(struct seq_file *s, void *unused)
1431 struct nbd_device *nbd = s->private;
1432 u32 flags = nbd->config->flags;
1434 seq_printf(s, "Hex: 0x%08x\n\n", flags);
1436 seq_puts(s, "Known flags:\n");
1438 if (flags & NBD_FLAG_HAS_FLAGS)
1439 seq_puts(s, "NBD_FLAG_HAS_FLAGS\n");
1440 if (flags & NBD_FLAG_READ_ONLY)
1441 seq_puts(s, "NBD_FLAG_READ_ONLY\n");
1442 if (flags & NBD_FLAG_SEND_FLUSH)
1443 seq_puts(s, "NBD_FLAG_SEND_FLUSH\n");
1444 if (flags & NBD_FLAG_SEND_FUA)
1445 seq_puts(s, "NBD_FLAG_SEND_FUA\n");
1446 if (flags & NBD_FLAG_SEND_TRIM)
1447 seq_puts(s, "NBD_FLAG_SEND_TRIM\n");
1452 static int nbd_dbg_flags_open(struct inode *inode, struct file *file)
1454 return single_open(file, nbd_dbg_flags_show, inode->i_private);
1457 static const struct file_operations nbd_dbg_flags_ops = {
1458 .open = nbd_dbg_flags_open,
1460 .llseek = seq_lseek,
1461 .release = single_release,
1464 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1467 struct nbd_config *config = nbd->config;
1472 dir = debugfs_create_dir(nbd_name(nbd), nbd_dbg_dir);
1474 dev_err(nbd_to_dev(nbd), "Failed to create debugfs dir for '%s'\n",
1478 config->dbg_dir = dir;
1480 debugfs_create_file("tasks", 0444, dir, nbd, &nbd_dbg_tasks_ops);
1481 debugfs_create_u64("size_bytes", 0444, dir, &config->bytesize);
1482 debugfs_create_u32("timeout", 0444, dir, &nbd->tag_set.timeout);
1483 debugfs_create_u64("blocksize", 0444, dir, &config->blksize);
1484 debugfs_create_file("flags", 0444, dir, nbd, &nbd_dbg_flags_ops);
1489 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1491 debugfs_remove_recursive(nbd->config->dbg_dir);
1494 static int nbd_dbg_init(void)
1496 struct dentry *dbg_dir;
1498 dbg_dir = debugfs_create_dir("nbd", NULL);
1502 nbd_dbg_dir = dbg_dir;
1507 static void nbd_dbg_close(void)
1509 debugfs_remove_recursive(nbd_dbg_dir);
1512 #else /* IS_ENABLED(CONFIG_DEBUG_FS) */
1514 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1519 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1523 static int nbd_dbg_init(void)
1528 static void nbd_dbg_close(void)
1534 static int nbd_init_request(struct blk_mq_tag_set *set, struct request *rq,
1535 unsigned int hctx_idx, unsigned int numa_node)
1537 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(rq);
1538 cmd->nbd = set->driver_data;
1540 mutex_init(&cmd->lock);
1544 static const struct blk_mq_ops nbd_mq_ops = {
1545 .queue_rq = nbd_queue_rq,
1546 .complete = nbd_complete_rq,
1547 .init_request = nbd_init_request,
1548 .timeout = nbd_xmit_timeout,
1551 static int nbd_dev_add(int index)
1553 struct nbd_device *nbd;
1554 struct gendisk *disk;
1555 struct request_queue *q;
1558 nbd = kzalloc(sizeof(struct nbd_device), GFP_KERNEL);
1562 disk = alloc_disk(1 << part_shift);
1567 err = idr_alloc(&nbd_index_idr, nbd, index, index + 1,
1572 err = idr_alloc(&nbd_index_idr, nbd, 0, 0, GFP_KERNEL);
1581 nbd->tag_set.ops = &nbd_mq_ops;
1582 nbd->tag_set.nr_hw_queues = 1;
1583 nbd->tag_set.queue_depth = 128;
1584 nbd->tag_set.numa_node = NUMA_NO_NODE;
1585 nbd->tag_set.cmd_size = sizeof(struct nbd_cmd);
1586 nbd->tag_set.flags = BLK_MQ_F_SHOULD_MERGE |
1588 nbd->tag_set.driver_data = nbd;
1590 err = blk_mq_alloc_tag_set(&nbd->tag_set);
1594 q = blk_mq_init_queue(&nbd->tag_set);
1602 * Tell the block layer that we are not a rotational device
1604 blk_queue_flag_set(QUEUE_FLAG_NONROT, disk->queue);
1605 blk_queue_flag_clear(QUEUE_FLAG_ADD_RANDOM, disk->queue);
1606 disk->queue->limits.discard_granularity = 0;
1607 disk->queue->limits.discard_alignment = 0;
1608 blk_queue_max_discard_sectors(disk->queue, 0);
1609 blk_queue_max_segment_size(disk->queue, UINT_MAX);
1610 blk_queue_max_segments(disk->queue, USHRT_MAX);
1611 blk_queue_max_hw_sectors(disk->queue, 65536);
1612 disk->queue->limits.max_sectors = 256;
1614 mutex_init(&nbd->config_lock);
1615 refcount_set(&nbd->config_refs, 0);
1616 refcount_set(&nbd->refs, 1);
1617 INIT_LIST_HEAD(&nbd->list);
1618 disk->major = NBD_MAJOR;
1619 disk->first_minor = index << part_shift;
1620 disk->fops = &nbd_fops;
1621 disk->private_data = nbd;
1622 sprintf(disk->disk_name, "nbd%d", index);
1624 nbd_total_devices++;
1628 blk_mq_free_tag_set(&nbd->tag_set);
1630 idr_remove(&nbd_index_idr, index);
1639 static int find_free_cb(int id, void *ptr, void *data)
1641 struct nbd_device *nbd = ptr;
1642 struct nbd_device **found = data;
1644 if (!refcount_read(&nbd->config_refs)) {
1651 /* Netlink interface. */
1652 static const struct nla_policy nbd_attr_policy[NBD_ATTR_MAX + 1] = {
1653 [NBD_ATTR_INDEX] = { .type = NLA_U32 },
1654 [NBD_ATTR_SIZE_BYTES] = { .type = NLA_U64 },
1655 [NBD_ATTR_BLOCK_SIZE_BYTES] = { .type = NLA_U64 },
1656 [NBD_ATTR_TIMEOUT] = { .type = NLA_U64 },
1657 [NBD_ATTR_SERVER_FLAGS] = { .type = NLA_U64 },
1658 [NBD_ATTR_CLIENT_FLAGS] = { .type = NLA_U64 },
1659 [NBD_ATTR_SOCKETS] = { .type = NLA_NESTED},
1660 [NBD_ATTR_DEAD_CONN_TIMEOUT] = { .type = NLA_U64 },
1661 [NBD_ATTR_DEVICE_LIST] = { .type = NLA_NESTED},
1664 static const struct nla_policy nbd_sock_policy[NBD_SOCK_MAX + 1] = {
1665 [NBD_SOCK_FD] = { .type = NLA_U32 },
1668 /* We don't use this right now since we don't parse the incoming list, but we
1669 * still want it here so userspace knows what to expect.
1671 static const struct nla_policy __attribute__((unused))
1672 nbd_device_policy[NBD_DEVICE_ATTR_MAX + 1] = {
1673 [NBD_DEVICE_INDEX] = { .type = NLA_U32 },
1674 [NBD_DEVICE_CONNECTED] = { .type = NLA_U8 },
1677 static int nbd_genl_connect(struct sk_buff *skb, struct genl_info *info)
1679 struct nbd_device *nbd = NULL;
1680 struct nbd_config *config;
1683 bool put_dev = false;
1685 if (!netlink_capable(skb, CAP_SYS_ADMIN))
1688 if (info->attrs[NBD_ATTR_INDEX])
1689 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1690 if (!info->attrs[NBD_ATTR_SOCKETS]) {
1691 printk(KERN_ERR "nbd: must specify at least one socket\n");
1694 if (!info->attrs[NBD_ATTR_SIZE_BYTES]) {
1695 printk(KERN_ERR "nbd: must specify a size in bytes for the device\n");
1699 mutex_lock(&nbd_index_mutex);
1701 ret = idr_for_each(&nbd_index_idr, &find_free_cb, &nbd);
1704 new_index = nbd_dev_add(-1);
1705 if (new_index < 0) {
1706 mutex_unlock(&nbd_index_mutex);
1707 printk(KERN_ERR "nbd: failed to add new device\n");
1710 nbd = idr_find(&nbd_index_idr, new_index);
1713 nbd = idr_find(&nbd_index_idr, index);
1715 ret = nbd_dev_add(index);
1717 mutex_unlock(&nbd_index_mutex);
1718 printk(KERN_ERR "nbd: failed to add new device\n");
1721 nbd = idr_find(&nbd_index_idr, index);
1725 printk(KERN_ERR "nbd: couldn't find device at index %d\n",
1727 mutex_unlock(&nbd_index_mutex);
1730 if (!refcount_inc_not_zero(&nbd->refs)) {
1731 mutex_unlock(&nbd_index_mutex);
1734 printk(KERN_ERR "nbd: device at index %d is going down\n",
1738 mutex_unlock(&nbd_index_mutex);
1740 mutex_lock(&nbd->config_lock);
1741 if (refcount_read(&nbd->config_refs)) {
1742 mutex_unlock(&nbd->config_lock);
1746 printk(KERN_ERR "nbd: nbd%d already in use\n", index);
1749 if (WARN_ON(nbd->config)) {
1750 mutex_unlock(&nbd->config_lock);
1754 config = nbd->config = nbd_alloc_config();
1756 mutex_unlock(&nbd->config_lock);
1758 printk(KERN_ERR "nbd: couldn't allocate config\n");
1761 refcount_set(&nbd->config_refs, 1);
1762 set_bit(NBD_BOUND, &config->runtime_flags);
1764 if (info->attrs[NBD_ATTR_SIZE_BYTES]) {
1765 u64 bytes = nla_get_u64(info->attrs[NBD_ATTR_SIZE_BYTES]);
1766 nbd_size_set(nbd, config->blksize,
1767 div64_u64(bytes, config->blksize));
1769 if (info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]) {
1771 nla_get_u64(info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]);
1772 nbd_size_set(nbd, bsize, div64_u64(config->bytesize, bsize));
1774 if (info->attrs[NBD_ATTR_TIMEOUT]) {
1775 u64 timeout = nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]);
1776 nbd->tag_set.timeout = timeout * HZ;
1777 blk_queue_rq_timeout(nbd->disk->queue, timeout * HZ);
1779 if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
1780 config->dead_conn_timeout =
1781 nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
1782 config->dead_conn_timeout *= HZ;
1784 if (info->attrs[NBD_ATTR_SERVER_FLAGS])
1786 nla_get_u64(info->attrs[NBD_ATTR_SERVER_FLAGS]);
1787 if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
1788 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
1789 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
1790 set_bit(NBD_DESTROY_ON_DISCONNECT,
1791 &config->runtime_flags);
1794 if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
1795 set_bit(NBD_DISCONNECT_ON_CLOSE,
1796 &config->runtime_flags);
1800 if (info->attrs[NBD_ATTR_SOCKETS]) {
1801 struct nlattr *attr;
1804 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
1806 struct nlattr *socks[NBD_SOCK_MAX+1];
1808 if (nla_type(attr) != NBD_SOCK_ITEM) {
1809 printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
1813 ret = nla_parse_nested_deprecated(socks, NBD_SOCK_MAX,
1818 printk(KERN_ERR "nbd: error processing sock list\n");
1822 if (!socks[NBD_SOCK_FD])
1824 fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
1825 ret = nbd_add_socket(nbd, fd, true);
1830 ret = nbd_start_device(nbd);
1832 mutex_unlock(&nbd->config_lock);
1834 set_bit(NBD_HAS_CONFIG_REF, &config->runtime_flags);
1835 refcount_inc(&nbd->config_refs);
1836 nbd_connect_reply(info, nbd->index);
1838 nbd_config_put(nbd);
1844 static void nbd_disconnect_and_put(struct nbd_device *nbd)
1846 mutex_lock(&nbd->config_lock);
1847 nbd_disconnect(nbd);
1848 nbd_clear_sock(nbd);
1849 mutex_unlock(&nbd->config_lock);
1850 if (test_and_clear_bit(NBD_HAS_CONFIG_REF,
1851 &nbd->config->runtime_flags))
1852 nbd_config_put(nbd);
1855 static int nbd_genl_disconnect(struct sk_buff *skb, struct genl_info *info)
1857 struct nbd_device *nbd;
1860 if (!netlink_capable(skb, CAP_SYS_ADMIN))
1863 if (!info->attrs[NBD_ATTR_INDEX]) {
1864 printk(KERN_ERR "nbd: must specify an index to disconnect\n");
1867 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1868 mutex_lock(&nbd_index_mutex);
1869 nbd = idr_find(&nbd_index_idr, index);
1871 mutex_unlock(&nbd_index_mutex);
1872 printk(KERN_ERR "nbd: couldn't find device at index %d\n",
1876 if (!refcount_inc_not_zero(&nbd->refs)) {
1877 mutex_unlock(&nbd_index_mutex);
1878 printk(KERN_ERR "nbd: device at index %d is going down\n",
1882 mutex_unlock(&nbd_index_mutex);
1883 if (!refcount_inc_not_zero(&nbd->config_refs)) {
1887 nbd_disconnect_and_put(nbd);
1888 nbd_config_put(nbd);
1893 static int nbd_genl_reconfigure(struct sk_buff *skb, struct genl_info *info)
1895 struct nbd_device *nbd = NULL;
1896 struct nbd_config *config;
1899 bool put_dev = false;
1901 if (!netlink_capable(skb, CAP_SYS_ADMIN))
1904 if (!info->attrs[NBD_ATTR_INDEX]) {
1905 printk(KERN_ERR "nbd: must specify a device to reconfigure\n");
1908 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1909 mutex_lock(&nbd_index_mutex);
1910 nbd = idr_find(&nbd_index_idr, index);
1912 mutex_unlock(&nbd_index_mutex);
1913 printk(KERN_ERR "nbd: couldn't find a device at index %d\n",
1917 if (!refcount_inc_not_zero(&nbd->refs)) {
1918 mutex_unlock(&nbd_index_mutex);
1919 printk(KERN_ERR "nbd: device at index %d is going down\n",
1923 mutex_unlock(&nbd_index_mutex);
1925 if (!refcount_inc_not_zero(&nbd->config_refs)) {
1926 dev_err(nbd_to_dev(nbd),
1927 "not configured, cannot reconfigure\n");
1932 mutex_lock(&nbd->config_lock);
1933 config = nbd->config;
1934 if (!test_bit(NBD_BOUND, &config->runtime_flags) ||
1936 dev_err(nbd_to_dev(nbd),
1937 "not configured, cannot reconfigure\n");
1942 if (info->attrs[NBD_ATTR_TIMEOUT]) {
1943 u64 timeout = nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]);
1944 nbd->tag_set.timeout = timeout * HZ;
1945 blk_queue_rq_timeout(nbd->disk->queue, timeout * HZ);
1947 if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
1948 config->dead_conn_timeout =
1949 nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
1950 config->dead_conn_timeout *= HZ;
1952 if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
1953 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
1954 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
1955 if (!test_and_set_bit(NBD_DESTROY_ON_DISCONNECT,
1956 &config->runtime_flags))
1959 if (test_and_clear_bit(NBD_DESTROY_ON_DISCONNECT,
1960 &config->runtime_flags))
1961 refcount_inc(&nbd->refs);
1964 if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
1965 set_bit(NBD_DISCONNECT_ON_CLOSE,
1966 &config->runtime_flags);
1968 clear_bit(NBD_DISCONNECT_ON_CLOSE,
1969 &config->runtime_flags);
1973 if (info->attrs[NBD_ATTR_SOCKETS]) {
1974 struct nlattr *attr;
1977 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
1979 struct nlattr *socks[NBD_SOCK_MAX+1];
1981 if (nla_type(attr) != NBD_SOCK_ITEM) {
1982 printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
1986 ret = nla_parse_nested_deprecated(socks, NBD_SOCK_MAX,
1991 printk(KERN_ERR "nbd: error processing sock list\n");
1995 if (!socks[NBD_SOCK_FD])
1997 fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
1998 ret = nbd_reconnect_socket(nbd, fd);
2004 dev_info(nbd_to_dev(nbd), "reconnected socket\n");
2008 mutex_unlock(&nbd->config_lock);
2009 nbd_config_put(nbd);
2016 static const struct genl_ops nbd_connect_genl_ops[] = {
2018 .cmd = NBD_CMD_CONNECT,
2019 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2020 .doit = nbd_genl_connect,
2023 .cmd = NBD_CMD_DISCONNECT,
2024 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2025 .doit = nbd_genl_disconnect,
2028 .cmd = NBD_CMD_RECONFIGURE,
2029 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2030 .doit = nbd_genl_reconfigure,
2033 .cmd = NBD_CMD_STATUS,
2034 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2035 .doit = nbd_genl_status,
2039 static const struct genl_multicast_group nbd_mcast_grps[] = {
2040 { .name = NBD_GENL_MCAST_GROUP_NAME, },
2043 static struct genl_family nbd_genl_family __ro_after_init = {
2045 .name = NBD_GENL_FAMILY_NAME,
2046 .version = NBD_GENL_VERSION,
2047 .module = THIS_MODULE,
2048 .ops = nbd_connect_genl_ops,
2049 .n_ops = ARRAY_SIZE(nbd_connect_genl_ops),
2050 .maxattr = NBD_ATTR_MAX,
2051 .policy = nbd_attr_policy,
2052 .mcgrps = nbd_mcast_grps,
2053 .n_mcgrps = ARRAY_SIZE(nbd_mcast_grps),
2056 static int populate_nbd_status(struct nbd_device *nbd, struct sk_buff *reply)
2058 struct nlattr *dev_opt;
2062 /* This is a little racey, but for status it's ok. The
2063 * reason we don't take a ref here is because we can't
2064 * take a ref in the index == -1 case as we would need
2065 * to put under the nbd_index_mutex, which could
2066 * deadlock if we are configured to remove ourselves
2067 * once we're disconnected.
2069 if (refcount_read(&nbd->config_refs))
2071 dev_opt = nla_nest_start_noflag(reply, NBD_DEVICE_ITEM);
2074 ret = nla_put_u32(reply, NBD_DEVICE_INDEX, nbd->index);
2077 ret = nla_put_u8(reply, NBD_DEVICE_CONNECTED,
2081 nla_nest_end(reply, dev_opt);
2085 static int status_cb(int id, void *ptr, void *data)
2087 struct nbd_device *nbd = ptr;
2088 return populate_nbd_status(nbd, (struct sk_buff *)data);
2091 static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info)
2093 struct nlattr *dev_list;
2094 struct sk_buff *reply;
2100 if (info->attrs[NBD_ATTR_INDEX])
2101 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2103 mutex_lock(&nbd_index_mutex);
2105 msg_size = nla_total_size(nla_attr_size(sizeof(u32)) +
2106 nla_attr_size(sizeof(u8)));
2107 msg_size *= (index == -1) ? nbd_total_devices : 1;
2109 reply = genlmsg_new(msg_size, GFP_KERNEL);
2112 reply_head = genlmsg_put_reply(reply, info, &nbd_genl_family, 0,
2119 dev_list = nla_nest_start_noflag(reply, NBD_ATTR_DEVICE_LIST);
2121 ret = idr_for_each(&nbd_index_idr, &status_cb, reply);
2127 struct nbd_device *nbd;
2128 nbd = idr_find(&nbd_index_idr, index);
2130 ret = populate_nbd_status(nbd, reply);
2137 nla_nest_end(reply, dev_list);
2138 genlmsg_end(reply, reply_head);
2139 ret = genlmsg_reply(reply, info);
2141 mutex_unlock(&nbd_index_mutex);
2145 static void nbd_connect_reply(struct genl_info *info, int index)
2147 struct sk_buff *skb;
2151 skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2154 msg_head = genlmsg_put_reply(skb, info, &nbd_genl_family, 0,
2160 ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2165 genlmsg_end(skb, msg_head);
2166 genlmsg_reply(skb, info);
2169 static void nbd_mcast_index(int index)
2171 struct sk_buff *skb;
2175 skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2178 msg_head = genlmsg_put(skb, 0, 0, &nbd_genl_family, 0,
2184 ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2189 genlmsg_end(skb, msg_head);
2190 genlmsg_multicast(&nbd_genl_family, skb, 0, 0, GFP_KERNEL);
2193 static void nbd_dead_link_work(struct work_struct *work)
2195 struct link_dead_args *args = container_of(work, struct link_dead_args,
2197 nbd_mcast_index(args->index);
2201 static int __init nbd_init(void)
2205 BUILD_BUG_ON(sizeof(struct nbd_request) != 28);
2208 printk(KERN_ERR "nbd: max_part must be >= 0\n");
2214 part_shift = fls(max_part);
2217 * Adjust max_part according to part_shift as it is exported
2218 * to user space so that user can know the max number of
2219 * partition kernel should be able to manage.
2221 * Note that -1 is required because partition 0 is reserved
2222 * for the whole disk.
2224 max_part = (1UL << part_shift) - 1;
2227 if ((1UL << part_shift) > DISK_MAX_PARTS)
2230 if (nbds_max > 1UL << (MINORBITS - part_shift))
2232 recv_workqueue = alloc_workqueue("knbd-recv",
2233 WQ_MEM_RECLAIM | WQ_HIGHPRI |
2235 if (!recv_workqueue)
2238 if (register_blkdev(NBD_MAJOR, "nbd")) {
2239 destroy_workqueue(recv_workqueue);
2243 if (genl_register_family(&nbd_genl_family)) {
2244 unregister_blkdev(NBD_MAJOR, "nbd");
2245 destroy_workqueue(recv_workqueue);
2250 mutex_lock(&nbd_index_mutex);
2251 for (i = 0; i < nbds_max; i++)
2253 mutex_unlock(&nbd_index_mutex);
2257 static int nbd_exit_cb(int id, void *ptr, void *data)
2259 struct list_head *list = (struct list_head *)data;
2260 struct nbd_device *nbd = ptr;
2262 list_add_tail(&nbd->list, list);
2266 static void __exit nbd_cleanup(void)
2268 struct nbd_device *nbd;
2269 LIST_HEAD(del_list);
2273 mutex_lock(&nbd_index_mutex);
2274 idr_for_each(&nbd_index_idr, &nbd_exit_cb, &del_list);
2275 mutex_unlock(&nbd_index_mutex);
2277 while (!list_empty(&del_list)) {
2278 nbd = list_first_entry(&del_list, struct nbd_device, list);
2279 list_del_init(&nbd->list);
2280 if (refcount_read(&nbd->refs) != 1)
2281 printk(KERN_ERR "nbd: possibly leaking a device\n");
2285 idr_destroy(&nbd_index_idr);
2286 genl_unregister_family(&nbd_genl_family);
2287 destroy_workqueue(recv_workqueue);
2288 unregister_blkdev(NBD_MAJOR, "nbd");
2291 module_init(nbd_init);
2292 module_exit(nbd_cleanup);
2294 MODULE_DESCRIPTION("Network Block Device");
2295 MODULE_LICENSE("GPL");
2297 module_param(nbds_max, int, 0444);
2298 MODULE_PARM_DESC(nbds_max, "number of network block devices to initialize (default: 16)");
2299 module_param(max_part, int, 0444);
2300 MODULE_PARM_DESC(max_part, "number of partitions per device (default: 16)");