1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Network block device - make block devices work over TCP
4 *
5 * Note that you can not swap over this thing, yet. Seems to work but
6 * deadlocks sometimes - you can not swap over TCP in general.
7 *
8 * Copyright 1997-2000, 2008 Pavel Machek <pavel@ucw.cz>
9 * Parts copyright 2001 Steven Whitehouse <steve@chygwyn.com>
10 *
11 * (part of code stolen from loop.c)
12 */
13
14 #include <linux/major.h>
15
16 #include <linux/blkdev.h>
17 #include <linux/module.h>
18 #include <linux/init.h>
19 #include <linux/sched.h>
20 #include <linux/sched/mm.h>
21 #include <linux/fs.h>
22 #include <linux/bio.h>
23 #include <linux/stat.h>
24 #include <linux/errno.h>
25 #include <linux/file.h>
26 #include <linux/ioctl.h>
27 #include <linux/mutex.h>
28 #include <linux/compiler.h>
29 #include <linux/completion.h>
30 #include <linux/err.h>
31 #include <linux/kernel.h>
32 #include <linux/slab.h>
33 #include <net/sock.h>
34 #include <linux/net.h>
35 #include <linux/kthread.h>
36 #include <linux/types.h>
37 #include <linux/debugfs.h>
38 #include <linux/blk-mq.h>
39
40 #include <linux/uaccess.h>
41 #include <asm/types.h>
42
43 #include <linux/nbd.h>
44 #include <linux/nbd-netlink.h>
45 #include <net/genetlink.h>
46
47 #define CREATE_TRACE_POINTS
48 #include <trace/events/nbd.h>
49
50 static DEFINE_IDR(nbd_index_idr);
51 static DEFINE_MUTEX(nbd_index_mutex);
52 static int nbd_total_devices = 0;
53
54 struct nbd_sock {
55 struct socket *sock;
56 struct mutex tx_lock;
57 struct request *pending;
58 int sent;
59 bool dead;
60 int fallback_index;
61 int cookie;
62 };
63
64 struct recv_thread_args {
65 struct work_struct work;
66 struct nbd_device *nbd;
67 int index;
68 };
69
70 struct link_dead_args {
71 struct work_struct work;
72 int index;
73 };
74
75 #define NBD_RT_TIMEDOUT 0
76 #define NBD_RT_DISCONNECT_REQUESTED 1
77 #define NBD_RT_DISCONNECTED 2
78 #define NBD_RT_HAS_PID_FILE 3
79 #define NBD_RT_HAS_CONFIG_REF 4
80 #define NBD_RT_BOUND 5
81 #define NBD_RT_DESTROY_ON_DISCONNECT 6
82 #define NBD_RT_DISCONNECT_ON_CLOSE 7
83
84 #define NBD_DESTROY_ON_DISCONNECT 0
85 #define NBD_DISCONNECT_REQUESTED 1
86
87 struct nbd_config {
88 u32 flags;
89 unsigned long runtime_flags;
90 u64 dead_conn_timeout;
91
92 struct nbd_sock **socks;
93 int num_connections;
94 atomic_t live_connections;
95 wait_queue_head_t conn_wait;
96
97 atomic_t recv_threads;
98 wait_queue_head_t recv_wq;
99 loff_t blksize;
100 loff_t bytesize;
101 #if IS_ENABLED(CONFIG_DEBUG_FS)
102 struct dentry *dbg_dir;
103 #endif
104 };
105
106 struct nbd_device {
107 struct blk_mq_tag_set tag_set;
108
109 int index;
110 refcount_t config_refs;
111 refcount_t refs;
112 struct nbd_config *config;
113 struct mutex config_lock;
114 struct gendisk *disk;
115 struct workqueue_struct *recv_workq;
116
117 struct list_head list;
118 struct task_struct *task_recv;
119 struct task_struct *task_setup;
120
121 struct completion *destroy_complete;
122 unsigned long flags;
123 };
124
125 #define NBD_CMD_REQUEUED 1
126
127 struct nbd_cmd {
128 struct nbd_device *nbd;
129 struct mutex lock;
130 int index;
131 int cookie;
132 int retries;
133 blk_status_t status;
134 unsigned long flags;
135 u32 cmd_cookie;
136 };
137
138 #if IS_ENABLED(CONFIG_DEBUG_FS)
139 static struct dentry *nbd_dbg_dir;
140 #endif
141
142 #define nbd_name(nbd) ((nbd)->disk->disk_name)
143
144 #define NBD_MAGIC 0x68797548
145
146 #define NBD_DEF_BLKSIZE 1024
147
148 static unsigned int nbds_max = 16;
149 static int max_part = 16;
150 static int part_shift;
151
152 static int nbd_dev_dbg_init(struct nbd_device *nbd);
153 static void nbd_dev_dbg_close(struct nbd_device *nbd);
154 static void nbd_config_put(struct nbd_device *nbd);
155 static void nbd_connect_reply(struct genl_info *info, int index);
156 static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info);
157 static void nbd_dead_link_work(struct work_struct *work);
158 static void nbd_disconnect_and_put(struct nbd_device *nbd);
159
nbd_to_dev(struct nbd_device * nbd)160 static inline struct device *nbd_to_dev(struct nbd_device *nbd)
161 {
162 return disk_to_dev(nbd->disk);
163 }
164
nbd_requeue_cmd(struct nbd_cmd * cmd)165 static void nbd_requeue_cmd(struct nbd_cmd *cmd)
166 {
167 struct request *req = blk_mq_rq_from_pdu(cmd);
168
169 if (!test_and_set_bit(NBD_CMD_REQUEUED, &cmd->flags))
170 blk_mq_requeue_request(req, true);
171 }
172
173 #define NBD_COOKIE_BITS 32
174
nbd_cmd_handle(struct nbd_cmd * cmd)175 static u64 nbd_cmd_handle(struct nbd_cmd *cmd)
176 {
177 struct request *req = blk_mq_rq_from_pdu(cmd);
178 u32 tag = blk_mq_unique_tag(req);
179 u64 cookie = cmd->cmd_cookie;
180
181 return (cookie << NBD_COOKIE_BITS) | tag;
182 }
183
nbd_handle_to_tag(u64 handle)184 static u32 nbd_handle_to_tag(u64 handle)
185 {
186 return (u32)handle;
187 }
188
nbd_handle_to_cookie(u64 handle)189 static u32 nbd_handle_to_cookie(u64 handle)
190 {
191 return (u32)(handle >> NBD_COOKIE_BITS);
192 }
193
nbdcmd_to_ascii(int cmd)194 static const char *nbdcmd_to_ascii(int cmd)
195 {
196 switch (cmd) {
197 case NBD_CMD_READ: return "read";
198 case NBD_CMD_WRITE: return "write";
199 case NBD_CMD_DISC: return "disconnect";
200 case NBD_CMD_FLUSH: return "flush";
201 case NBD_CMD_TRIM: return "trim/discard";
202 }
203 return "invalid";
204 }
205
pid_show(struct device * dev,struct device_attribute * attr,char * buf)206 static ssize_t pid_show(struct device *dev,
207 struct device_attribute *attr, char *buf)
208 {
209 struct gendisk *disk = dev_to_disk(dev);
210 struct nbd_device *nbd = (struct nbd_device *)disk->private_data;
211
212 return sprintf(buf, "%d\n", task_pid_nr(nbd->task_recv));
213 }
214
215 static const struct device_attribute pid_attr = {
216 .attr = { .name = "pid", .mode = 0444},
217 .show = pid_show,
218 };
219
nbd_dev_remove(struct nbd_device * nbd)220 static void nbd_dev_remove(struct nbd_device *nbd)
221 {
222 struct gendisk *disk = nbd->disk;
223 struct request_queue *q;
224
225 if (disk) {
226 q = disk->queue;
227 del_gendisk(disk);
228 blk_cleanup_queue(q);
229 blk_mq_free_tag_set(&nbd->tag_set);
230 disk->private_data = NULL;
231 put_disk(disk);
232 }
233
234 /*
235 * Place this in the last just before the nbd is freed to
236 * make sure that the disk and the related kobject are also
237 * totally removed to avoid duplicate creation of the same
238 * one.
239 */
240 if (test_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags) && nbd->destroy_complete)
241 complete(nbd->destroy_complete);
242
243 kfree(nbd);
244 }
245
nbd_put(struct nbd_device * nbd)246 static void nbd_put(struct nbd_device *nbd)
247 {
248 if (refcount_dec_and_mutex_lock(&nbd->refs,
249 &nbd_index_mutex)) {
250 idr_remove(&nbd_index_idr, nbd->index);
251 nbd_dev_remove(nbd);
252 mutex_unlock(&nbd_index_mutex);
253 }
254 }
255
nbd_disconnected(struct nbd_config * config)256 static int nbd_disconnected(struct nbd_config *config)
257 {
258 return test_bit(NBD_RT_DISCONNECTED, &config->runtime_flags) ||
259 test_bit(NBD_RT_DISCONNECT_REQUESTED, &config->runtime_flags);
260 }
261
nbd_mark_nsock_dead(struct nbd_device * nbd,struct nbd_sock * nsock,int notify)262 static void nbd_mark_nsock_dead(struct nbd_device *nbd, struct nbd_sock *nsock,
263 int notify)
264 {
265 if (!nsock->dead && notify && !nbd_disconnected(nbd->config)) {
266 struct link_dead_args *args;
267 args = kmalloc(sizeof(struct link_dead_args), GFP_NOIO);
268 if (args) {
269 INIT_WORK(&args->work, nbd_dead_link_work);
270 args->index = nbd->index;
271 queue_work(system_wq, &args->work);
272 }
273 }
274 if (!nsock->dead) {
275 kernel_sock_shutdown(nsock->sock, SHUT_RDWR);
276 if (atomic_dec_return(&nbd->config->live_connections) == 0) {
277 if (test_and_clear_bit(NBD_RT_DISCONNECT_REQUESTED,
278 &nbd->config->runtime_flags)) {
279 set_bit(NBD_RT_DISCONNECTED,
280 &nbd->config->runtime_flags);
281 dev_info(nbd_to_dev(nbd),
282 "Disconnected due to user request.\n");
283 }
284 }
285 }
286 nsock->dead = true;
287 nsock->pending = NULL;
288 nsock->sent = 0;
289 }
290
nbd_size_clear(struct nbd_device * nbd)291 static void nbd_size_clear(struct nbd_device *nbd)
292 {
293 if (nbd->config->bytesize) {
294 set_capacity(nbd->disk, 0);
295 kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
296 }
297 }
298
nbd_size_update(struct nbd_device * nbd,bool start)299 static void nbd_size_update(struct nbd_device *nbd, bool start)
300 {
301 struct nbd_config *config = nbd->config;
302 struct block_device *bdev = bdget_disk(nbd->disk, 0);
303 sector_t nr_sectors = config->bytesize >> 9;
304
305 if (config->flags & NBD_FLAG_SEND_TRIM) {
306 nbd->disk->queue->limits.discard_granularity = config->blksize;
307 nbd->disk->queue->limits.discard_alignment = config->blksize;
308 blk_queue_max_discard_sectors(nbd->disk->queue, UINT_MAX);
309 }
310 blk_queue_logical_block_size(nbd->disk->queue, config->blksize);
311 blk_queue_physical_block_size(nbd->disk->queue, config->blksize);
312 set_capacity(nbd->disk, nr_sectors);
313 if (bdev) {
314 if (bdev->bd_disk) {
315 bd_set_nr_sectors(bdev, nr_sectors);
316 if (start)
317 set_blocksize(bdev, config->blksize);
318 } else
319 set_bit(GD_NEED_PART_SCAN, &nbd->disk->state);
320 bdput(bdev);
321 }
322 kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
323 }
324
nbd_size_set(struct nbd_device * nbd,loff_t blocksize,loff_t nr_blocks)325 static void nbd_size_set(struct nbd_device *nbd, loff_t blocksize,
326 loff_t nr_blocks)
327 {
328 struct nbd_config *config = nbd->config;
329 config->blksize = blocksize;
330 config->bytesize = blocksize * nr_blocks;
331 if (nbd->task_recv != NULL)
332 nbd_size_update(nbd, false);
333 }
334
nbd_complete_rq(struct request * req)335 static void nbd_complete_rq(struct request *req)
336 {
337 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
338
339 dev_dbg(nbd_to_dev(cmd->nbd), "request %p: %s\n", req,
340 cmd->status ? "failed" : "done");
341
342 blk_mq_end_request(req, cmd->status);
343 }
344
345 /*
346 * Forcibly shutdown the socket causing all listeners to error
347 */
sock_shutdown(struct nbd_device * nbd)348 static void sock_shutdown(struct nbd_device *nbd)
349 {
350 struct nbd_config *config = nbd->config;
351 int i;
352
353 if (config->num_connections == 0)
354 return;
355 if (test_and_set_bit(NBD_RT_DISCONNECTED, &config->runtime_flags))
356 return;
357
358 for (i = 0; i < config->num_connections; i++) {
359 struct nbd_sock *nsock = config->socks[i];
360 mutex_lock(&nsock->tx_lock);
361 nbd_mark_nsock_dead(nbd, nsock, 0);
362 mutex_unlock(&nsock->tx_lock);
363 }
364 dev_warn(disk_to_dev(nbd->disk), "shutting down sockets\n");
365 }
366
req_to_nbd_cmd_type(struct request * req)367 static u32 req_to_nbd_cmd_type(struct request *req)
368 {
369 switch (req_op(req)) {
370 case REQ_OP_DISCARD:
371 return NBD_CMD_TRIM;
372 case REQ_OP_FLUSH:
373 return NBD_CMD_FLUSH;
374 case REQ_OP_WRITE:
375 return NBD_CMD_WRITE;
376 case REQ_OP_READ:
377 return NBD_CMD_READ;
378 default:
379 return U32_MAX;
380 }
381 }
382
nbd_xmit_timeout(struct request * req,bool reserved)383 static enum blk_eh_timer_return nbd_xmit_timeout(struct request *req,
384 bool reserved)
385 {
386 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
387 struct nbd_device *nbd = cmd->nbd;
388 struct nbd_config *config;
389
390 if (!mutex_trylock(&cmd->lock))
391 return BLK_EH_RESET_TIMER;
392
393 if (!refcount_inc_not_zero(&nbd->config_refs)) {
394 cmd->status = BLK_STS_TIMEOUT;
395 mutex_unlock(&cmd->lock);
396 goto done;
397 }
398 config = nbd->config;
399
400 if (config->num_connections > 1 ||
401 (config->num_connections == 1 && nbd->tag_set.timeout)) {
402 dev_err_ratelimited(nbd_to_dev(nbd),
403 "Connection timed out, retrying (%d/%d alive)\n",
404 atomic_read(&config->live_connections),
405 config->num_connections);
406 /*
407 * Hooray we have more connections, requeue this IO, the submit
408 * path will put it on a real connection. Or if only one
409 * connection is configured, the submit path will wait util
410 * a new connection is reconfigured or util dead timeout.
411 */
412 if (config->socks) {
413 if (cmd->index < config->num_connections) {
414 struct nbd_sock *nsock =
415 config->socks[cmd->index];
416 mutex_lock(&nsock->tx_lock);
417 /* We can have multiple outstanding requests, so
418 * we don't want to mark the nsock dead if we've
419 * already reconnected with a new socket, so
420 * only mark it dead if its the same socket we
421 * were sent out on.
422 */
423 if (cmd->cookie == nsock->cookie)
424 nbd_mark_nsock_dead(nbd, nsock, 1);
425 mutex_unlock(&nsock->tx_lock);
426 }
427 mutex_unlock(&cmd->lock);
428 nbd_requeue_cmd(cmd);
429 nbd_config_put(nbd);
430 return BLK_EH_DONE;
431 }
432 }
433
434 if (!nbd->tag_set.timeout) {
435 /*
436 * Userspace sets timeout=0 to disable socket disconnection,
437 * so just warn and reset the timer.
438 */
439 struct nbd_sock *nsock = config->socks[cmd->index];
440 cmd->retries++;
441 dev_info(nbd_to_dev(nbd), "Possible stuck request %p: control (%s@%llu,%uB). Runtime %u seconds\n",
442 req, nbdcmd_to_ascii(req_to_nbd_cmd_type(req)),
443 (unsigned long long)blk_rq_pos(req) << 9,
444 blk_rq_bytes(req), (req->timeout / HZ) * cmd->retries);
445
446 mutex_lock(&nsock->tx_lock);
447 if (cmd->cookie != nsock->cookie) {
448 nbd_requeue_cmd(cmd);
449 mutex_unlock(&nsock->tx_lock);
450 mutex_unlock(&cmd->lock);
451 nbd_config_put(nbd);
452 return BLK_EH_DONE;
453 }
454 mutex_unlock(&nsock->tx_lock);
455 mutex_unlock(&cmd->lock);
456 nbd_config_put(nbd);
457 return BLK_EH_RESET_TIMER;
458 }
459
460 dev_err_ratelimited(nbd_to_dev(nbd), "Connection timed out\n");
461 set_bit(NBD_RT_TIMEDOUT, &config->runtime_flags);
462 cmd->status = BLK_STS_IOERR;
463 mutex_unlock(&cmd->lock);
464 sock_shutdown(nbd);
465 nbd_config_put(nbd);
466 done:
467 blk_mq_complete_request(req);
468 return BLK_EH_DONE;
469 }
470
471 /*
472 * Send or receive packet.
473 */
sock_xmit(struct nbd_device * nbd,int index,int send,struct iov_iter * iter,int msg_flags,int * sent)474 static int sock_xmit(struct nbd_device *nbd, int index, int send,
475 struct iov_iter *iter, int msg_flags, int *sent)
476 {
477 struct nbd_config *config = nbd->config;
478 struct socket *sock = config->socks[index]->sock;
479 int result;
480 struct msghdr msg;
481 unsigned int noreclaim_flag;
482
483 if (unlikely(!sock)) {
484 dev_err_ratelimited(disk_to_dev(nbd->disk),
485 "Attempted %s on closed socket in sock_xmit\n",
486 (send ? "send" : "recv"));
487 return -EINVAL;
488 }
489
490 msg.msg_iter = *iter;
491
492 noreclaim_flag = memalloc_noreclaim_save();
493 do {
494 sock->sk->sk_allocation = GFP_NOIO | __GFP_MEMALLOC;
495 msg.msg_name = NULL;
496 msg.msg_namelen = 0;
497 msg.msg_control = NULL;
498 msg.msg_controllen = 0;
499 msg.msg_flags = msg_flags | MSG_NOSIGNAL;
500
501 if (send)
502 result = sock_sendmsg(sock, &msg);
503 else
504 result = sock_recvmsg(sock, &msg, msg.msg_flags);
505
506 if (result <= 0) {
507 if (result == 0)
508 result = -EPIPE; /* short read */
509 break;
510 }
511 if (sent)
512 *sent += result;
513 } while (msg_data_left(&msg));
514
515 memalloc_noreclaim_restore(noreclaim_flag);
516
517 return result;
518 }
519
520 /*
521 * Different settings for sk->sk_sndtimeo can result in different return values
522 * if there is a signal pending when we enter sendmsg, because reasons?
523 */
was_interrupted(int result)524 static inline int was_interrupted(int result)
525 {
526 return result == -ERESTARTSYS || result == -EINTR;
527 }
528
529 /* always call with the tx_lock held */
nbd_send_cmd(struct nbd_device * nbd,struct nbd_cmd * cmd,int index)530 static int nbd_send_cmd(struct nbd_device *nbd, struct nbd_cmd *cmd, int index)
531 {
532 struct request *req = blk_mq_rq_from_pdu(cmd);
533 struct nbd_config *config = nbd->config;
534 struct nbd_sock *nsock = config->socks[index];
535 int result;
536 struct nbd_request request = {.magic = htonl(NBD_REQUEST_MAGIC)};
537 struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
538 struct iov_iter from;
539 unsigned long size = blk_rq_bytes(req);
540 struct bio *bio;
541 u64 handle;
542 u32 type;
543 u32 nbd_cmd_flags = 0;
544 int sent = nsock->sent, skip = 0;
545
546 iov_iter_kvec(&from, WRITE, &iov, 1, sizeof(request));
547
548 type = req_to_nbd_cmd_type(req);
549 if (type == U32_MAX)
550 return -EIO;
551
552 if (rq_data_dir(req) == WRITE &&
553 (config->flags & NBD_FLAG_READ_ONLY)) {
554 dev_err_ratelimited(disk_to_dev(nbd->disk),
555 "Write on read-only\n");
556 return -EIO;
557 }
558
559 if (req->cmd_flags & REQ_FUA)
560 nbd_cmd_flags |= NBD_CMD_FLAG_FUA;
561
562 /* We did a partial send previously, and we at least sent the whole
563 * request struct, so just go and send the rest of the pages in the
564 * request.
565 */
566 if (sent) {
567 if (sent >= sizeof(request)) {
568 skip = sent - sizeof(request);
569
570 /* initialize handle for tracing purposes */
571 handle = nbd_cmd_handle(cmd);
572
573 goto send_pages;
574 }
575 iov_iter_advance(&from, sent);
576 } else {
577 cmd->cmd_cookie++;
578 }
579 cmd->index = index;
580 cmd->cookie = nsock->cookie;
581 cmd->retries = 0;
582 request.type = htonl(type | nbd_cmd_flags);
583 if (type != NBD_CMD_FLUSH) {
584 request.from = cpu_to_be64((u64)blk_rq_pos(req) << 9);
585 request.len = htonl(size);
586 }
587 handle = nbd_cmd_handle(cmd);
588 memcpy(request.handle, &handle, sizeof(handle));
589
590 trace_nbd_send_request(&request, nbd->index, blk_mq_rq_from_pdu(cmd));
591
592 dev_dbg(nbd_to_dev(nbd), "request %p: sending control (%s@%llu,%uB)\n",
593 req, nbdcmd_to_ascii(type),
594 (unsigned long long)blk_rq_pos(req) << 9, blk_rq_bytes(req));
595 result = sock_xmit(nbd, index, 1, &from,
596 (type == NBD_CMD_WRITE) ? MSG_MORE : 0, &sent);
597 trace_nbd_header_sent(req, handle);
598 if (result <= 0) {
599 if (was_interrupted(result)) {
600 /* If we havne't sent anything we can just return BUSY,
601 * however if we have sent something we need to make
602 * sure we only allow this req to be sent until we are
603 * completely done.
604 */
605 if (sent) {
606 nsock->pending = req;
607 nsock->sent = sent;
608 }
609 set_bit(NBD_CMD_REQUEUED, &cmd->flags);
610 return BLK_STS_RESOURCE;
611 }
612 dev_err_ratelimited(disk_to_dev(nbd->disk),
613 "Send control failed (result %d)\n", result);
614 return -EAGAIN;
615 }
616 send_pages:
617 if (type != NBD_CMD_WRITE)
618 goto out;
619
620 bio = req->bio;
621 while (bio) {
622 struct bio *next = bio->bi_next;
623 struct bvec_iter iter;
624 struct bio_vec bvec;
625
626 bio_for_each_segment(bvec, bio, iter) {
627 bool is_last = !next && bio_iter_last(bvec, iter);
628 int flags = is_last ? 0 : MSG_MORE;
629
630 dev_dbg(nbd_to_dev(nbd), "request %p: sending %d bytes data\n",
631 req, bvec.bv_len);
632 iov_iter_bvec(&from, WRITE, &bvec, 1, bvec.bv_len);
633 if (skip) {
634 if (skip >= iov_iter_count(&from)) {
635 skip -= iov_iter_count(&from);
636 continue;
637 }
638 iov_iter_advance(&from, skip);
639 skip = 0;
640 }
641 result = sock_xmit(nbd, index, 1, &from, flags, &sent);
642 if (result <= 0) {
643 if (was_interrupted(result)) {
644 /* We've already sent the header, we
645 * have no choice but to set pending and
646 * return BUSY.
647 */
648 nsock->pending = req;
649 nsock->sent = sent;
650 set_bit(NBD_CMD_REQUEUED, &cmd->flags);
651 return BLK_STS_RESOURCE;
652 }
653 dev_err(disk_to_dev(nbd->disk),
654 "Send data failed (result %d)\n",
655 result);
656 return -EAGAIN;
657 }
658 /*
659 * The completion might already have come in,
660 * so break for the last one instead of letting
661 * the iterator do it. This prevents use-after-free
662 * of the bio.
663 */
664 if (is_last)
665 break;
666 }
667 bio = next;
668 }
669 out:
670 trace_nbd_payload_sent(req, handle);
671 nsock->pending = NULL;
672 nsock->sent = 0;
673 return 0;
674 }
675
676 /* NULL returned = something went wrong, inform userspace */
nbd_read_stat(struct nbd_device * nbd,int index)677 static struct nbd_cmd *nbd_read_stat(struct nbd_device *nbd, int index)
678 {
679 struct nbd_config *config = nbd->config;
680 int result;
681 struct nbd_reply reply;
682 struct nbd_cmd *cmd;
683 struct request *req = NULL;
684 u64 handle;
685 u16 hwq;
686 u32 tag;
687 struct kvec iov = {.iov_base = &reply, .iov_len = sizeof(reply)};
688 struct iov_iter to;
689 int ret = 0;
690
691 reply.magic = 0;
692 iov_iter_kvec(&to, READ, &iov, 1, sizeof(reply));
693 result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
694 if (result <= 0) {
695 if (!nbd_disconnected(config))
696 dev_err(disk_to_dev(nbd->disk),
697 "Receive control failed (result %d)\n", result);
698 return ERR_PTR(result);
699 }
700
701 if (ntohl(reply.magic) != NBD_REPLY_MAGIC) {
702 dev_err(disk_to_dev(nbd->disk), "Wrong magic (0x%lx)\n",
703 (unsigned long)ntohl(reply.magic));
704 return ERR_PTR(-EPROTO);
705 }
706
707 memcpy(&handle, reply.handle, sizeof(handle));
708 tag = nbd_handle_to_tag(handle);
709 hwq = blk_mq_unique_tag_to_hwq(tag);
710 if (hwq < nbd->tag_set.nr_hw_queues)
711 req = blk_mq_tag_to_rq(nbd->tag_set.tags[hwq],
712 blk_mq_unique_tag_to_tag(tag));
713 if (!req || !blk_mq_request_started(req)) {
714 dev_err(disk_to_dev(nbd->disk), "Unexpected reply (%d) %p\n",
715 tag, req);
716 return ERR_PTR(-ENOENT);
717 }
718 trace_nbd_header_received(req, handle);
719 cmd = blk_mq_rq_to_pdu(req);
720
721 mutex_lock(&cmd->lock);
722 if (cmd->cmd_cookie != nbd_handle_to_cookie(handle)) {
723 dev_err(disk_to_dev(nbd->disk), "Double reply on req %p, cmd_cookie %u, handle cookie %u\n",
724 req, cmd->cmd_cookie, nbd_handle_to_cookie(handle));
725 ret = -ENOENT;
726 goto out;
727 }
728 if (cmd->status != BLK_STS_OK) {
729 dev_err(disk_to_dev(nbd->disk), "Command already handled %p\n",
730 req);
731 ret = -ENOENT;
732 goto out;
733 }
734 if (test_bit(NBD_CMD_REQUEUED, &cmd->flags)) {
735 dev_err(disk_to_dev(nbd->disk), "Raced with timeout on req %p\n",
736 req);
737 ret = -ENOENT;
738 goto out;
739 }
740 if (ntohl(reply.error)) {
741 dev_err(disk_to_dev(nbd->disk), "Other side returned error (%d)\n",
742 ntohl(reply.error));
743 cmd->status = BLK_STS_IOERR;
744 goto out;
745 }
746
747 dev_dbg(nbd_to_dev(nbd), "request %p: got reply\n", req);
748 if (rq_data_dir(req) != WRITE) {
749 struct req_iterator iter;
750 struct bio_vec bvec;
751
752 rq_for_each_segment(bvec, req, iter) {
753 iov_iter_bvec(&to, READ, &bvec, 1, bvec.bv_len);
754 result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
755 if (result <= 0) {
756 dev_err(disk_to_dev(nbd->disk), "Receive data failed (result %d)\n",
757 result);
758 /*
759 * If we've disconnected, we need to make sure we
760 * complete this request, otherwise error out
761 * and let the timeout stuff handle resubmitting
762 * this request onto another connection.
763 */
764 if (nbd_disconnected(config)) {
765 cmd->status = BLK_STS_IOERR;
766 goto out;
767 }
768 ret = -EIO;
769 goto out;
770 }
771 dev_dbg(nbd_to_dev(nbd), "request %p: got %d bytes data\n",
772 req, bvec.bv_len);
773 }
774 }
775 out:
776 trace_nbd_payload_received(req, handle);
777 mutex_unlock(&cmd->lock);
778 return ret ? ERR_PTR(ret) : cmd;
779 }
780
recv_work(struct work_struct * work)781 static void recv_work(struct work_struct *work)
782 {
783 struct recv_thread_args *args = container_of(work,
784 struct recv_thread_args,
785 work);
786 struct nbd_device *nbd = args->nbd;
787 struct nbd_config *config = nbd->config;
788 struct nbd_cmd *cmd;
789 struct request *rq;
790
791 while (1) {
792 cmd = nbd_read_stat(nbd, args->index);
793 if (IS_ERR(cmd)) {
794 struct nbd_sock *nsock = config->socks[args->index];
795
796 mutex_lock(&nsock->tx_lock);
797 nbd_mark_nsock_dead(nbd, nsock, 1);
798 mutex_unlock(&nsock->tx_lock);
799 break;
800 }
801
802 rq = blk_mq_rq_from_pdu(cmd);
803 if (likely(!blk_should_fake_timeout(rq->q)))
804 blk_mq_complete_request(rq);
805 }
806 nbd_config_put(nbd);
807 atomic_dec(&config->recv_threads);
808 wake_up(&config->recv_wq);
809 kfree(args);
810 }
811
nbd_clear_req(struct request * req,void * data,bool reserved)812 static bool nbd_clear_req(struct request *req, void *data, bool reserved)
813 {
814 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
815
816 mutex_lock(&cmd->lock);
817 cmd->status = BLK_STS_IOERR;
818 mutex_unlock(&cmd->lock);
819
820 blk_mq_complete_request(req);
821 return true;
822 }
823
nbd_clear_que(struct nbd_device * nbd)824 static void nbd_clear_que(struct nbd_device *nbd)
825 {
826 blk_mq_quiesce_queue(nbd->disk->queue);
827 blk_mq_tagset_busy_iter(&nbd->tag_set, nbd_clear_req, NULL);
828 blk_mq_unquiesce_queue(nbd->disk->queue);
829 dev_dbg(disk_to_dev(nbd->disk), "queue cleared\n");
830 }
831
find_fallback(struct nbd_device * nbd,int index)832 static int find_fallback(struct nbd_device *nbd, int index)
833 {
834 struct nbd_config *config = nbd->config;
835 int new_index = -1;
836 struct nbd_sock *nsock = config->socks[index];
837 int fallback = nsock->fallback_index;
838
839 if (test_bit(NBD_RT_DISCONNECTED, &config->runtime_flags))
840 return new_index;
841
842 if (config->num_connections <= 1) {
843 dev_err_ratelimited(disk_to_dev(nbd->disk),
844 "Dead connection, failed to find a fallback\n");
845 return new_index;
846 }
847
848 if (fallback >= 0 && fallback < config->num_connections &&
849 !config->socks[fallback]->dead)
850 return fallback;
851
852 if (nsock->fallback_index < 0 ||
853 nsock->fallback_index >= config->num_connections ||
854 config->socks[nsock->fallback_index]->dead) {
855 int i;
856 for (i = 0; i < config->num_connections; i++) {
857 if (i == index)
858 continue;
859 if (!config->socks[i]->dead) {
860 new_index = i;
861 break;
862 }
863 }
864 nsock->fallback_index = new_index;
865 if (new_index < 0) {
866 dev_err_ratelimited(disk_to_dev(nbd->disk),
867 "Dead connection, failed to find a fallback\n");
868 return new_index;
869 }
870 }
871 new_index = nsock->fallback_index;
872 return new_index;
873 }
874
wait_for_reconnect(struct nbd_device * nbd)875 static int wait_for_reconnect(struct nbd_device *nbd)
876 {
877 struct nbd_config *config = nbd->config;
878 if (!config->dead_conn_timeout)
879 return 0;
880 if (test_bit(NBD_RT_DISCONNECTED, &config->runtime_flags))
881 return 0;
882 return wait_event_timeout(config->conn_wait,
883 atomic_read(&config->live_connections) > 0,
884 config->dead_conn_timeout) > 0;
885 }
886
nbd_handle_cmd(struct nbd_cmd * cmd,int index)887 static int nbd_handle_cmd(struct nbd_cmd *cmd, int index)
888 {
889 struct request *req = blk_mq_rq_from_pdu(cmd);
890 struct nbd_device *nbd = cmd->nbd;
891 struct nbd_config *config;
892 struct nbd_sock *nsock;
893 int ret;
894
895 if (!refcount_inc_not_zero(&nbd->config_refs)) {
896 dev_err_ratelimited(disk_to_dev(nbd->disk),
897 "Socks array is empty\n");
898 blk_mq_start_request(req);
899 return -EINVAL;
900 }
901 config = nbd->config;
902
903 if (index >= config->num_connections) {
904 dev_err_ratelimited(disk_to_dev(nbd->disk),
905 "Attempted send on invalid socket\n");
906 nbd_config_put(nbd);
907 blk_mq_start_request(req);
908 return -EINVAL;
909 }
910 cmd->status = BLK_STS_OK;
911 again:
912 nsock = config->socks[index];
913 mutex_lock(&nsock->tx_lock);
914 if (nsock->dead) {
915 int old_index = index;
916 index = find_fallback(nbd, index);
917 mutex_unlock(&nsock->tx_lock);
918 if (index < 0) {
919 if (wait_for_reconnect(nbd)) {
920 index = old_index;
921 goto again;
922 }
923 /* All the sockets should already be down at this point,
924 * we just want to make sure that DISCONNECTED is set so
925 * any requests that come in that were queue'ed waiting
926 * for the reconnect timer don't trigger the timer again
927 * and instead just error out.
928 */
929 sock_shutdown(nbd);
930 nbd_config_put(nbd);
931 blk_mq_start_request(req);
932 return -EIO;
933 }
934 goto again;
935 }
936
937 /* Handle the case that we have a pending request that was partially
938 * transmitted that _has_ to be serviced first. We need to call requeue
939 * here so that it gets put _after_ the request that is already on the
940 * dispatch list.
941 */
942 blk_mq_start_request(req);
943 if (unlikely(nsock->pending && nsock->pending != req)) {
944 nbd_requeue_cmd(cmd);
945 ret = 0;
946 goto out;
947 }
948 /*
949 * Some failures are related to the link going down, so anything that
950 * returns EAGAIN can be retried on a different socket.
951 */
952 ret = nbd_send_cmd(nbd, cmd, index);
953 if (ret == -EAGAIN) {
954 dev_err_ratelimited(disk_to_dev(nbd->disk),
955 "Request send failed, requeueing\n");
956 nbd_mark_nsock_dead(nbd, nsock, 1);
957 nbd_requeue_cmd(cmd);
958 ret = 0;
959 }
960 out:
961 mutex_unlock(&nsock->tx_lock);
962 nbd_config_put(nbd);
963 return ret;
964 }
965
nbd_queue_rq(struct blk_mq_hw_ctx * hctx,const struct blk_mq_queue_data * bd)966 static blk_status_t nbd_queue_rq(struct blk_mq_hw_ctx *hctx,
967 const struct blk_mq_queue_data *bd)
968 {
969 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(bd->rq);
970 int ret;
971
972 /*
973 * Since we look at the bio's to send the request over the network we
974 * need to make sure the completion work doesn't mark this request done
975 * before we are done doing our send. This keeps us from dereferencing
976 * freed data if we have particularly fast completions (ie we get the
977 * completion before we exit sock_xmit on the last bvec) or in the case
978 * that the server is misbehaving (or there was an error) before we're
979 * done sending everything over the wire.
980 */
981 mutex_lock(&cmd->lock);
982 clear_bit(NBD_CMD_REQUEUED, &cmd->flags);
983
984 /* We can be called directly from the user space process, which means we
985 * could possibly have signals pending so our sendmsg will fail. In
986 * this case we need to return that we are busy, otherwise error out as
987 * appropriate.
988 */
989 ret = nbd_handle_cmd(cmd, hctx->queue_num);
990 if (ret < 0)
991 ret = BLK_STS_IOERR;
992 else if (!ret)
993 ret = BLK_STS_OK;
994 mutex_unlock(&cmd->lock);
995
996 return ret;
997 }
998
nbd_get_socket(struct nbd_device * nbd,unsigned long fd,int * err)999 static struct socket *nbd_get_socket(struct nbd_device *nbd, unsigned long fd,
1000 int *err)
1001 {
1002 struct socket *sock;
1003
1004 *err = 0;
1005 sock = sockfd_lookup(fd, err);
1006 if (!sock)
1007 return NULL;
1008
1009 if (sock->ops->shutdown == sock_no_shutdown) {
1010 dev_err(disk_to_dev(nbd->disk), "Unsupported socket: shutdown callout must be supported.\n");
1011 *err = -EINVAL;
1012 sockfd_put(sock);
1013 return NULL;
1014 }
1015
1016 return sock;
1017 }
1018
nbd_add_socket(struct nbd_device * nbd,unsigned long arg,bool netlink)1019 static int nbd_add_socket(struct nbd_device *nbd, unsigned long arg,
1020 bool netlink)
1021 {
1022 struct nbd_config *config = nbd->config;
1023 struct socket *sock;
1024 struct nbd_sock **socks;
1025 struct nbd_sock *nsock;
1026 int err;
1027
1028 sock = nbd_get_socket(nbd, arg, &err);
1029 if (!sock)
1030 return err;
1031
1032 if (!netlink && !nbd->task_setup &&
1033 !test_bit(NBD_RT_BOUND, &config->runtime_flags))
1034 nbd->task_setup = current;
1035
1036 if (!netlink &&
1037 (nbd->task_setup != current ||
1038 test_bit(NBD_RT_BOUND, &config->runtime_flags))) {
1039 dev_err(disk_to_dev(nbd->disk),
1040 "Device being setup by another task");
1041 err = -EBUSY;
1042 goto put_socket;
1043 }
1044
1045 nsock = kzalloc(sizeof(*nsock), GFP_KERNEL);
1046 if (!nsock) {
1047 err = -ENOMEM;
1048 goto put_socket;
1049 }
1050
1051 socks = krealloc(config->socks, (config->num_connections + 1) *
1052 sizeof(struct nbd_sock *), GFP_KERNEL);
1053 if (!socks) {
1054 kfree(nsock);
1055 err = -ENOMEM;
1056 goto put_socket;
1057 }
1058
1059 config->socks = socks;
1060
1061 nsock->fallback_index = -1;
1062 nsock->dead = false;
1063 mutex_init(&nsock->tx_lock);
1064 nsock->sock = sock;
1065 nsock->pending = NULL;
1066 nsock->sent = 0;
1067 nsock->cookie = 0;
1068 socks[config->num_connections++] = nsock;
1069 atomic_inc(&config->live_connections);
1070
1071 return 0;
1072
1073 put_socket:
1074 sockfd_put(sock);
1075 return err;
1076 }
1077
nbd_reconnect_socket(struct nbd_device * nbd,unsigned long arg)1078 static int nbd_reconnect_socket(struct nbd_device *nbd, unsigned long arg)
1079 {
1080 struct nbd_config *config = nbd->config;
1081 struct socket *sock, *old;
1082 struct recv_thread_args *args;
1083 int i;
1084 int err;
1085
1086 sock = nbd_get_socket(nbd, arg, &err);
1087 if (!sock)
1088 return err;
1089
1090 args = kzalloc(sizeof(*args), GFP_KERNEL);
1091 if (!args) {
1092 sockfd_put(sock);
1093 return -ENOMEM;
1094 }
1095
1096 for (i = 0; i < config->num_connections; i++) {
1097 struct nbd_sock *nsock = config->socks[i];
1098
1099 if (!nsock->dead)
1100 continue;
1101
1102 mutex_lock(&nsock->tx_lock);
1103 if (!nsock->dead) {
1104 mutex_unlock(&nsock->tx_lock);
1105 continue;
1106 }
1107 sk_set_memalloc(sock->sk);
1108 if (nbd->tag_set.timeout)
1109 sock->sk->sk_sndtimeo = nbd->tag_set.timeout;
1110 atomic_inc(&config->recv_threads);
1111 refcount_inc(&nbd->config_refs);
1112 old = nsock->sock;
1113 nsock->fallback_index = -1;
1114 nsock->sock = sock;
1115 nsock->dead = false;
1116 INIT_WORK(&args->work, recv_work);
1117 args->index = i;
1118 args->nbd = nbd;
1119 nsock->cookie++;
1120 mutex_unlock(&nsock->tx_lock);
1121 sockfd_put(old);
1122
1123 clear_bit(NBD_RT_DISCONNECTED, &config->runtime_flags);
1124
1125 /* We take the tx_mutex in an error path in the recv_work, so we
1126 * need to queue_work outside of the tx_mutex.
1127 */
1128 queue_work(nbd->recv_workq, &args->work);
1129
1130 atomic_inc(&config->live_connections);
1131 wake_up(&config->conn_wait);
1132 return 0;
1133 }
1134 sockfd_put(sock);
1135 kfree(args);
1136 return -ENOSPC;
1137 }
1138
nbd_bdev_reset(struct block_device * bdev)1139 static void nbd_bdev_reset(struct block_device *bdev)
1140 {
1141 if (bdev->bd_openers > 1)
1142 return;
1143 bd_set_nr_sectors(bdev, 0);
1144 }
1145
nbd_parse_flags(struct nbd_device * nbd)1146 static void nbd_parse_flags(struct nbd_device *nbd)
1147 {
1148 struct nbd_config *config = nbd->config;
1149 if (config->flags & NBD_FLAG_READ_ONLY)
1150 set_disk_ro(nbd->disk, true);
1151 else
1152 set_disk_ro(nbd->disk, false);
1153 if (config->flags & NBD_FLAG_SEND_TRIM)
1154 blk_queue_flag_set(QUEUE_FLAG_DISCARD, nbd->disk->queue);
1155 if (config->flags & NBD_FLAG_SEND_FLUSH) {
1156 if (config->flags & NBD_FLAG_SEND_FUA)
1157 blk_queue_write_cache(nbd->disk->queue, true, true);
1158 else
1159 blk_queue_write_cache(nbd->disk->queue, true, false);
1160 }
1161 else
1162 blk_queue_write_cache(nbd->disk->queue, false, false);
1163 }
1164
send_disconnects(struct nbd_device * nbd)1165 static void send_disconnects(struct nbd_device *nbd)
1166 {
1167 struct nbd_config *config = nbd->config;
1168 struct nbd_request request = {
1169 .magic = htonl(NBD_REQUEST_MAGIC),
1170 .type = htonl(NBD_CMD_DISC),
1171 };
1172 struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
1173 struct iov_iter from;
1174 int i, ret;
1175
1176 for (i = 0; i < config->num_connections; i++) {
1177 struct nbd_sock *nsock = config->socks[i];
1178
1179 iov_iter_kvec(&from, WRITE, &iov, 1, sizeof(request));
1180 mutex_lock(&nsock->tx_lock);
1181 ret = sock_xmit(nbd, i, 1, &from, 0, NULL);
1182 if (ret <= 0)
1183 dev_err(disk_to_dev(nbd->disk),
1184 "Send disconnect failed %d\n", ret);
1185 mutex_unlock(&nsock->tx_lock);
1186 }
1187 }
1188
nbd_disconnect(struct nbd_device * nbd)1189 static int nbd_disconnect(struct nbd_device *nbd)
1190 {
1191 struct nbd_config *config = nbd->config;
1192
1193 dev_info(disk_to_dev(nbd->disk), "NBD_DISCONNECT\n");
1194 set_bit(NBD_RT_DISCONNECT_REQUESTED, &config->runtime_flags);
1195 set_bit(NBD_DISCONNECT_REQUESTED, &nbd->flags);
1196 send_disconnects(nbd);
1197 return 0;
1198 }
1199
nbd_clear_sock(struct nbd_device * nbd)1200 static void nbd_clear_sock(struct nbd_device *nbd)
1201 {
1202 sock_shutdown(nbd);
1203 nbd_clear_que(nbd);
1204 nbd->task_setup = NULL;
1205 }
1206
nbd_config_put(struct nbd_device * nbd)1207 static void nbd_config_put(struct nbd_device *nbd)
1208 {
1209 if (refcount_dec_and_mutex_lock(&nbd->config_refs,
1210 &nbd->config_lock)) {
1211 struct nbd_config *config = nbd->config;
1212 nbd_dev_dbg_close(nbd);
1213 nbd_size_clear(nbd);
1214 if (test_and_clear_bit(NBD_RT_HAS_PID_FILE,
1215 &config->runtime_flags))
1216 device_remove_file(disk_to_dev(nbd->disk), &pid_attr);
1217 nbd->task_recv = NULL;
1218 nbd_clear_sock(nbd);
1219 if (config->num_connections) {
1220 int i;
1221 for (i = 0; i < config->num_connections; i++) {
1222 sockfd_put(config->socks[i]->sock);
1223 kfree(config->socks[i]);
1224 }
1225 kfree(config->socks);
1226 }
1227 kfree(nbd->config);
1228 nbd->config = NULL;
1229
1230 if (nbd->recv_workq)
1231 destroy_workqueue(nbd->recv_workq);
1232 nbd->recv_workq = NULL;
1233
1234 nbd->tag_set.timeout = 0;
1235 nbd->disk->queue->limits.discard_granularity = 0;
1236 nbd->disk->queue->limits.discard_alignment = 0;
1237 blk_queue_max_discard_sectors(nbd->disk->queue, UINT_MAX);
1238 blk_queue_flag_clear(QUEUE_FLAG_DISCARD, nbd->disk->queue);
1239
1240 mutex_unlock(&nbd->config_lock);
1241 nbd_put(nbd);
1242 module_put(THIS_MODULE);
1243 }
1244 }
1245
nbd_start_device(struct nbd_device * nbd)1246 static int nbd_start_device(struct nbd_device *nbd)
1247 {
1248 struct nbd_config *config = nbd->config;
1249 int num_connections = config->num_connections;
1250 int error = 0, i;
1251
1252 if (nbd->task_recv)
1253 return -EBUSY;
1254 if (!config->socks)
1255 return -EINVAL;
1256 if (num_connections > 1 &&
1257 !(config->flags & NBD_FLAG_CAN_MULTI_CONN)) {
1258 dev_err(disk_to_dev(nbd->disk), "server does not support multiple connections per device.\n");
1259 return -EINVAL;
1260 }
1261
1262 nbd->recv_workq = alloc_workqueue("knbd%d-recv",
1263 WQ_MEM_RECLAIM | WQ_HIGHPRI |
1264 WQ_UNBOUND, 0, nbd->index);
1265 if (!nbd->recv_workq) {
1266 dev_err(disk_to_dev(nbd->disk), "Could not allocate knbd recv work queue.\n");
1267 return -ENOMEM;
1268 }
1269
1270 blk_mq_update_nr_hw_queues(&nbd->tag_set, config->num_connections);
1271 nbd->task_recv = current;
1272
1273 nbd_parse_flags(nbd);
1274
1275 error = device_create_file(disk_to_dev(nbd->disk), &pid_attr);
1276 if (error) {
1277 dev_err(disk_to_dev(nbd->disk), "device_create_file failed!\n");
1278 return error;
1279 }
1280 set_bit(NBD_RT_HAS_PID_FILE, &config->runtime_flags);
1281
1282 nbd_dev_dbg_init(nbd);
1283 for (i = 0; i < num_connections; i++) {
1284 struct recv_thread_args *args;
1285
1286 args = kzalloc(sizeof(*args), GFP_KERNEL);
1287 if (!args) {
1288 sock_shutdown(nbd);
1289 /*
1290 * If num_connections is m (2 < m),
1291 * and NO.1 ~ NO.n(1 < n < m) kzallocs are successful.
1292 * But NO.(n + 1) failed. We still have n recv threads.
1293 * So, add flush_workqueue here to prevent recv threads
1294 * dropping the last config_refs and trying to destroy
1295 * the workqueue from inside the workqueue.
1296 */
1297 if (i)
1298 flush_workqueue(nbd->recv_workq);
1299 return -ENOMEM;
1300 }
1301 sk_set_memalloc(config->socks[i]->sock->sk);
1302 if (nbd->tag_set.timeout)
1303 config->socks[i]->sock->sk->sk_sndtimeo =
1304 nbd->tag_set.timeout;
1305 atomic_inc(&config->recv_threads);
1306 refcount_inc(&nbd->config_refs);
1307 INIT_WORK(&args->work, recv_work);
1308 args->nbd = nbd;
1309 args->index = i;
1310 queue_work(nbd->recv_workq, &args->work);
1311 }
1312 nbd_size_update(nbd, true);
1313 return error;
1314 }
1315
nbd_start_device_ioctl(struct nbd_device * nbd,struct block_device * bdev)1316 static int nbd_start_device_ioctl(struct nbd_device *nbd, struct block_device *bdev)
1317 {
1318 struct nbd_config *config = nbd->config;
1319 int ret;
1320
1321 ret = nbd_start_device(nbd);
1322 if (ret)
1323 return ret;
1324
1325 if (max_part)
1326 set_bit(GD_NEED_PART_SCAN, &nbd->disk->state);
1327 mutex_unlock(&nbd->config_lock);
1328 ret = wait_event_interruptible(config->recv_wq,
1329 atomic_read(&config->recv_threads) == 0);
1330 if (ret)
1331 sock_shutdown(nbd);
1332 flush_workqueue(nbd->recv_workq);
1333
1334 mutex_lock(&nbd->config_lock);
1335 nbd_bdev_reset(bdev);
1336 /* user requested, ignore socket errors */
1337 if (test_bit(NBD_RT_DISCONNECT_REQUESTED, &config->runtime_flags))
1338 ret = 0;
1339 if (test_bit(NBD_RT_TIMEDOUT, &config->runtime_flags))
1340 ret = -ETIMEDOUT;
1341 return ret;
1342 }
1343
nbd_clear_sock_ioctl(struct nbd_device * nbd,struct block_device * bdev)1344 static void nbd_clear_sock_ioctl(struct nbd_device *nbd,
1345 struct block_device *bdev)
1346 {
1347 sock_shutdown(nbd);
1348 __invalidate_device(bdev, true);
1349 nbd_bdev_reset(bdev);
1350 if (test_and_clear_bit(NBD_RT_HAS_CONFIG_REF,
1351 &nbd->config->runtime_flags))
1352 nbd_config_put(nbd);
1353 }
1354
nbd_is_valid_blksize(unsigned long blksize)1355 static bool nbd_is_valid_blksize(unsigned long blksize)
1356 {
1357 if (!blksize || !is_power_of_2(blksize) || blksize < 512 ||
1358 blksize > PAGE_SIZE)
1359 return false;
1360 return true;
1361 }
1362
nbd_set_cmd_timeout(struct nbd_device * nbd,u64 timeout)1363 static void nbd_set_cmd_timeout(struct nbd_device *nbd, u64 timeout)
1364 {
1365 nbd->tag_set.timeout = timeout * HZ;
1366 if (timeout)
1367 blk_queue_rq_timeout(nbd->disk->queue, timeout * HZ);
1368 else
1369 blk_queue_rq_timeout(nbd->disk->queue, 30 * HZ);
1370 }
1371
1372 /* Must be called with config_lock held */
__nbd_ioctl(struct block_device * bdev,struct nbd_device * nbd,unsigned int cmd,unsigned long arg)1373 static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
1374 unsigned int cmd, unsigned long arg)
1375 {
1376 struct nbd_config *config = nbd->config;
1377
1378 switch (cmd) {
1379 case NBD_DISCONNECT:
1380 return nbd_disconnect(nbd);
1381 case NBD_CLEAR_SOCK:
1382 nbd_clear_sock_ioctl(nbd, bdev);
1383 return 0;
1384 case NBD_SET_SOCK:
1385 return nbd_add_socket(nbd, arg, false);
1386 case NBD_SET_BLKSIZE:
1387 if (!arg)
1388 arg = NBD_DEF_BLKSIZE;
1389 if (!nbd_is_valid_blksize(arg))
1390 return -EINVAL;
1391 nbd_size_set(nbd, arg,
1392 div_s64(config->bytesize, arg));
1393 return 0;
1394 case NBD_SET_SIZE:
1395 nbd_size_set(nbd, config->blksize,
1396 div_s64(arg, config->blksize));
1397 return 0;
1398 case NBD_SET_SIZE_BLOCKS:
1399 nbd_size_set(nbd, config->blksize, arg);
1400 return 0;
1401 case NBD_SET_TIMEOUT:
1402 nbd_set_cmd_timeout(nbd, arg);
1403 return 0;
1404
1405 case NBD_SET_FLAGS:
1406 config->flags = arg;
1407 return 0;
1408 case NBD_DO_IT:
1409 return nbd_start_device_ioctl(nbd, bdev);
1410 case NBD_CLEAR_QUE:
1411 /*
1412 * This is for compatibility only. The queue is always cleared
1413 * by NBD_DO_IT or NBD_CLEAR_SOCK.
1414 */
1415 return 0;
1416 case NBD_PRINT_DEBUG:
1417 /*
1418 * For compatibility only, we no longer keep a list of
1419 * outstanding requests.
1420 */
1421 return 0;
1422 }
1423 return -ENOTTY;
1424 }
1425
nbd_ioctl(struct block_device * bdev,fmode_t mode,unsigned int cmd,unsigned long arg)1426 static int nbd_ioctl(struct block_device *bdev, fmode_t mode,
1427 unsigned int cmd, unsigned long arg)
1428 {
1429 struct nbd_device *nbd = bdev->bd_disk->private_data;
1430 struct nbd_config *config = nbd->config;
1431 int error = -EINVAL;
1432
1433 if (!capable(CAP_SYS_ADMIN))
1434 return -EPERM;
1435
1436 /* The block layer will pass back some non-nbd ioctls in case we have
1437 * special handling for them, but we don't so just return an error.
1438 */
1439 if (_IOC_TYPE(cmd) != 0xab)
1440 return -EINVAL;
1441
1442 mutex_lock(&nbd->config_lock);
1443
1444 /* Don't allow ioctl operations on a nbd device that was created with
1445 * netlink, unless it's DISCONNECT or CLEAR_SOCK, which are fine.
1446 */
1447 if (!test_bit(NBD_RT_BOUND, &config->runtime_flags) ||
1448 (cmd == NBD_DISCONNECT || cmd == NBD_CLEAR_SOCK))
1449 error = __nbd_ioctl(bdev, nbd, cmd, arg);
1450 else
1451 dev_err(nbd_to_dev(nbd), "Cannot use ioctl interface on a netlink controlled device.\n");
1452 mutex_unlock(&nbd->config_lock);
1453 return error;
1454 }
1455
nbd_alloc_config(void)1456 static struct nbd_config *nbd_alloc_config(void)
1457 {
1458 struct nbd_config *config;
1459
1460 config = kzalloc(sizeof(struct nbd_config), GFP_NOFS);
1461 if (!config)
1462 return NULL;
1463 atomic_set(&config->recv_threads, 0);
1464 init_waitqueue_head(&config->recv_wq);
1465 init_waitqueue_head(&config->conn_wait);
1466 config->blksize = NBD_DEF_BLKSIZE;
1467 atomic_set(&config->live_connections, 0);
1468 try_module_get(THIS_MODULE);
1469 return config;
1470 }
1471
nbd_open(struct block_device * bdev,fmode_t mode)1472 static int nbd_open(struct block_device *bdev, fmode_t mode)
1473 {
1474 struct nbd_device *nbd;
1475 int ret = 0;
1476
1477 mutex_lock(&nbd_index_mutex);
1478 nbd = bdev->bd_disk->private_data;
1479 if (!nbd) {
1480 ret = -ENXIO;
1481 goto out;
1482 }
1483 if (!refcount_inc_not_zero(&nbd->refs)) {
1484 ret = -ENXIO;
1485 goto out;
1486 }
1487 if (!refcount_inc_not_zero(&nbd->config_refs)) {
1488 struct nbd_config *config;
1489
1490 mutex_lock(&nbd->config_lock);
1491 if (refcount_inc_not_zero(&nbd->config_refs)) {
1492 mutex_unlock(&nbd->config_lock);
1493 goto out;
1494 }
1495 config = nbd->config = nbd_alloc_config();
1496 if (!config) {
1497 ret = -ENOMEM;
1498 mutex_unlock(&nbd->config_lock);
1499 goto out;
1500 }
1501 refcount_set(&nbd->config_refs, 1);
1502 refcount_inc(&nbd->refs);
1503 mutex_unlock(&nbd->config_lock);
1504 set_bit(GD_NEED_PART_SCAN, &bdev->bd_disk->state);
1505 } else if (nbd_disconnected(nbd->config)) {
1506 set_bit(GD_NEED_PART_SCAN, &bdev->bd_disk->state);
1507 }
1508 out:
1509 mutex_unlock(&nbd_index_mutex);
1510 return ret;
1511 }
1512
nbd_release(struct gendisk * disk,fmode_t mode)1513 static void nbd_release(struct gendisk *disk, fmode_t mode)
1514 {
1515 struct nbd_device *nbd = disk->private_data;
1516 struct block_device *bdev = bdget_disk(disk, 0);
1517
1518 if (test_bit(NBD_RT_DISCONNECT_ON_CLOSE, &nbd->config->runtime_flags) &&
1519 bdev->bd_openers == 0)
1520 nbd_disconnect_and_put(nbd);
1521 bdput(bdev);
1522
1523 nbd_config_put(nbd);
1524 nbd_put(nbd);
1525 }
1526
1527 static const struct block_device_operations nbd_fops =
1528 {
1529 .owner = THIS_MODULE,
1530 .open = nbd_open,
1531 .release = nbd_release,
1532 .ioctl = nbd_ioctl,
1533 .compat_ioctl = nbd_ioctl,
1534 };
1535
1536 #if IS_ENABLED(CONFIG_DEBUG_FS)
1537
nbd_dbg_tasks_show(struct seq_file * s,void * unused)1538 static int nbd_dbg_tasks_show(struct seq_file *s, void *unused)
1539 {
1540 struct nbd_device *nbd = s->private;
1541
1542 if (nbd->task_recv)
1543 seq_printf(s, "recv: %d\n", task_pid_nr(nbd->task_recv));
1544
1545 return 0;
1546 }
1547
nbd_dbg_tasks_open(struct inode * inode,struct file * file)1548 static int nbd_dbg_tasks_open(struct inode *inode, struct file *file)
1549 {
1550 return single_open(file, nbd_dbg_tasks_show, inode->i_private);
1551 }
1552
1553 static const struct file_operations nbd_dbg_tasks_ops = {
1554 .open = nbd_dbg_tasks_open,
1555 .read = seq_read,
1556 .llseek = seq_lseek,
1557 .release = single_release,
1558 };
1559
nbd_dbg_flags_show(struct seq_file * s,void * unused)1560 static int nbd_dbg_flags_show(struct seq_file *s, void *unused)
1561 {
1562 struct nbd_device *nbd = s->private;
1563 u32 flags = nbd->config->flags;
1564
1565 seq_printf(s, "Hex: 0x%08x\n\n", flags);
1566
1567 seq_puts(s, "Known flags:\n");
1568
1569 if (flags & NBD_FLAG_HAS_FLAGS)
1570 seq_puts(s, "NBD_FLAG_HAS_FLAGS\n");
1571 if (flags & NBD_FLAG_READ_ONLY)
1572 seq_puts(s, "NBD_FLAG_READ_ONLY\n");
1573 if (flags & NBD_FLAG_SEND_FLUSH)
1574 seq_puts(s, "NBD_FLAG_SEND_FLUSH\n");
1575 if (flags & NBD_FLAG_SEND_FUA)
1576 seq_puts(s, "NBD_FLAG_SEND_FUA\n");
1577 if (flags & NBD_FLAG_SEND_TRIM)
1578 seq_puts(s, "NBD_FLAG_SEND_TRIM\n");
1579
1580 return 0;
1581 }
1582
nbd_dbg_flags_open(struct inode * inode,struct file * file)1583 static int nbd_dbg_flags_open(struct inode *inode, struct file *file)
1584 {
1585 return single_open(file, nbd_dbg_flags_show, inode->i_private);
1586 }
1587
1588 static const struct file_operations nbd_dbg_flags_ops = {
1589 .open = nbd_dbg_flags_open,
1590 .read = seq_read,
1591 .llseek = seq_lseek,
1592 .release = single_release,
1593 };
1594
nbd_dev_dbg_init(struct nbd_device * nbd)1595 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1596 {
1597 struct dentry *dir;
1598 struct nbd_config *config = nbd->config;
1599
1600 if (!nbd_dbg_dir)
1601 return -EIO;
1602
1603 dir = debugfs_create_dir(nbd_name(nbd), nbd_dbg_dir);
1604 if (!dir) {
1605 dev_err(nbd_to_dev(nbd), "Failed to create debugfs dir for '%s'\n",
1606 nbd_name(nbd));
1607 return -EIO;
1608 }
1609 config->dbg_dir = dir;
1610
1611 debugfs_create_file("tasks", 0444, dir, nbd, &nbd_dbg_tasks_ops);
1612 debugfs_create_u64("size_bytes", 0444, dir, &config->bytesize);
1613 debugfs_create_u32("timeout", 0444, dir, &nbd->tag_set.timeout);
1614 debugfs_create_u64("blocksize", 0444, dir, &config->blksize);
1615 debugfs_create_file("flags", 0444, dir, nbd, &nbd_dbg_flags_ops);
1616
1617 return 0;
1618 }
1619
nbd_dev_dbg_close(struct nbd_device * nbd)1620 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1621 {
1622 debugfs_remove_recursive(nbd->config->dbg_dir);
1623 }
1624
nbd_dbg_init(void)1625 static int nbd_dbg_init(void)
1626 {
1627 struct dentry *dbg_dir;
1628
1629 dbg_dir = debugfs_create_dir("nbd", NULL);
1630 if (!dbg_dir)
1631 return -EIO;
1632
1633 nbd_dbg_dir = dbg_dir;
1634
1635 return 0;
1636 }
1637
nbd_dbg_close(void)1638 static void nbd_dbg_close(void)
1639 {
1640 debugfs_remove_recursive(nbd_dbg_dir);
1641 }
1642
1643 #else /* IS_ENABLED(CONFIG_DEBUG_FS) */
1644
nbd_dev_dbg_init(struct nbd_device * nbd)1645 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1646 {
1647 return 0;
1648 }
1649
nbd_dev_dbg_close(struct nbd_device * nbd)1650 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1651 {
1652 }
1653
nbd_dbg_init(void)1654 static int nbd_dbg_init(void)
1655 {
1656 return 0;
1657 }
1658
nbd_dbg_close(void)1659 static void nbd_dbg_close(void)
1660 {
1661 }
1662
1663 #endif
1664
nbd_init_request(struct blk_mq_tag_set * set,struct request * rq,unsigned int hctx_idx,unsigned int numa_node)1665 static int nbd_init_request(struct blk_mq_tag_set *set, struct request *rq,
1666 unsigned int hctx_idx, unsigned int numa_node)
1667 {
1668 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(rq);
1669 cmd->nbd = set->driver_data;
1670 cmd->flags = 0;
1671 mutex_init(&cmd->lock);
1672 return 0;
1673 }
1674
1675 static const struct blk_mq_ops nbd_mq_ops = {
1676 .queue_rq = nbd_queue_rq,
1677 .complete = nbd_complete_rq,
1678 .init_request = nbd_init_request,
1679 .timeout = nbd_xmit_timeout,
1680 };
1681
nbd_dev_add(int index)1682 static int nbd_dev_add(int index)
1683 {
1684 struct nbd_device *nbd;
1685 struct gendisk *disk;
1686 struct request_queue *q;
1687 int err = -ENOMEM;
1688
1689 nbd = kzalloc(sizeof(struct nbd_device), GFP_KERNEL);
1690 if (!nbd)
1691 goto out;
1692
1693 disk = alloc_disk(1 << part_shift);
1694 if (!disk)
1695 goto out_free_nbd;
1696
1697 if (index >= 0) {
1698 err = idr_alloc(&nbd_index_idr, nbd, index, index + 1,
1699 GFP_KERNEL);
1700 if (err == -ENOSPC)
1701 err = -EEXIST;
1702 } else {
1703 err = idr_alloc(&nbd_index_idr, nbd, 0, 0, GFP_KERNEL);
1704 if (err >= 0)
1705 index = err;
1706 }
1707 if (err < 0)
1708 goto out_free_disk;
1709
1710 nbd->index = index;
1711 nbd->disk = disk;
1712 nbd->tag_set.ops = &nbd_mq_ops;
1713 nbd->tag_set.nr_hw_queues = 1;
1714 nbd->tag_set.queue_depth = 128;
1715 nbd->tag_set.numa_node = NUMA_NO_NODE;
1716 nbd->tag_set.cmd_size = sizeof(struct nbd_cmd);
1717 nbd->tag_set.flags = BLK_MQ_F_SHOULD_MERGE |
1718 BLK_MQ_F_BLOCKING;
1719 nbd->tag_set.driver_data = nbd;
1720 nbd->destroy_complete = NULL;
1721
1722 err = blk_mq_alloc_tag_set(&nbd->tag_set);
1723 if (err)
1724 goto out_free_idr;
1725
1726 q = blk_mq_init_queue(&nbd->tag_set);
1727 if (IS_ERR(q)) {
1728 err = PTR_ERR(q);
1729 goto out_free_tags;
1730 }
1731 disk->queue = q;
1732
1733 /*
1734 * Tell the block layer that we are not a rotational device
1735 */
1736 blk_queue_flag_set(QUEUE_FLAG_NONROT, disk->queue);
1737 blk_queue_flag_clear(QUEUE_FLAG_ADD_RANDOM, disk->queue);
1738 disk->queue->limits.discard_granularity = 0;
1739 disk->queue->limits.discard_alignment = 0;
1740 blk_queue_max_discard_sectors(disk->queue, 0);
1741 blk_queue_max_segment_size(disk->queue, UINT_MAX);
1742 blk_queue_max_segments(disk->queue, USHRT_MAX);
1743 blk_queue_max_hw_sectors(disk->queue, 65536);
1744 disk->queue->limits.max_sectors = 256;
1745
1746 mutex_init(&nbd->config_lock);
1747 refcount_set(&nbd->config_refs, 0);
1748 refcount_set(&nbd->refs, 1);
1749 INIT_LIST_HEAD(&nbd->list);
1750 disk->major = NBD_MAJOR;
1751 disk->first_minor = index << part_shift;
1752 disk->fops = &nbd_fops;
1753 disk->private_data = nbd;
1754 sprintf(disk->disk_name, "nbd%d", index);
1755 add_disk(disk);
1756 nbd_total_devices++;
1757 return index;
1758
1759 out_free_tags:
1760 blk_mq_free_tag_set(&nbd->tag_set);
1761 out_free_idr:
1762 idr_remove(&nbd_index_idr, index);
1763 out_free_disk:
1764 put_disk(disk);
1765 out_free_nbd:
1766 kfree(nbd);
1767 out:
1768 return err;
1769 }
1770
find_free_cb(int id,void * ptr,void * data)1771 static int find_free_cb(int id, void *ptr, void *data)
1772 {
1773 struct nbd_device *nbd = ptr;
1774 struct nbd_device **found = data;
1775
1776 if (!refcount_read(&nbd->config_refs)) {
1777 *found = nbd;
1778 return 1;
1779 }
1780 return 0;
1781 }
1782
1783 /* Netlink interface. */
1784 static const struct nla_policy nbd_attr_policy[NBD_ATTR_MAX + 1] = {
1785 [NBD_ATTR_INDEX] = { .type = NLA_U32 },
1786 [NBD_ATTR_SIZE_BYTES] = { .type = NLA_U64 },
1787 [NBD_ATTR_BLOCK_SIZE_BYTES] = { .type = NLA_U64 },
1788 [NBD_ATTR_TIMEOUT] = { .type = NLA_U64 },
1789 [NBD_ATTR_SERVER_FLAGS] = { .type = NLA_U64 },
1790 [NBD_ATTR_CLIENT_FLAGS] = { .type = NLA_U64 },
1791 [NBD_ATTR_SOCKETS] = { .type = NLA_NESTED},
1792 [NBD_ATTR_DEAD_CONN_TIMEOUT] = { .type = NLA_U64 },
1793 [NBD_ATTR_DEVICE_LIST] = { .type = NLA_NESTED},
1794 };
1795
1796 static const struct nla_policy nbd_sock_policy[NBD_SOCK_MAX + 1] = {
1797 [NBD_SOCK_FD] = { .type = NLA_U32 },
1798 };
1799
1800 /* We don't use this right now since we don't parse the incoming list, but we
1801 * still want it here so userspace knows what to expect.
1802 */
1803 static const struct nla_policy __attribute__((unused))
1804 nbd_device_policy[NBD_DEVICE_ATTR_MAX + 1] = {
1805 [NBD_DEVICE_INDEX] = { .type = NLA_U32 },
1806 [NBD_DEVICE_CONNECTED] = { .type = NLA_U8 },
1807 };
1808
nbd_genl_size_set(struct genl_info * info,struct nbd_device * nbd)1809 static int nbd_genl_size_set(struct genl_info *info, struct nbd_device *nbd)
1810 {
1811 struct nbd_config *config = nbd->config;
1812 u64 bsize = config->blksize;
1813 u64 bytes = config->bytesize;
1814
1815 if (info->attrs[NBD_ATTR_SIZE_BYTES])
1816 bytes = nla_get_u64(info->attrs[NBD_ATTR_SIZE_BYTES]);
1817
1818 if (info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]) {
1819 bsize = nla_get_u64(info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]);
1820 if (!bsize)
1821 bsize = NBD_DEF_BLKSIZE;
1822 if (!nbd_is_valid_blksize(bsize)) {
1823 printk(KERN_ERR "Invalid block size %llu\n", bsize);
1824 return -EINVAL;
1825 }
1826 }
1827
1828 if (bytes != config->bytesize || bsize != config->blksize)
1829 nbd_size_set(nbd, bsize, div64_u64(bytes, bsize));
1830 return 0;
1831 }
1832
nbd_genl_connect(struct sk_buff * skb,struct genl_info * info)1833 static int nbd_genl_connect(struct sk_buff *skb, struct genl_info *info)
1834 {
1835 DECLARE_COMPLETION_ONSTACK(destroy_complete);
1836 struct nbd_device *nbd = NULL;
1837 struct nbd_config *config;
1838 int index = -1;
1839 int ret;
1840 bool put_dev = false;
1841
1842 if (!netlink_capable(skb, CAP_SYS_ADMIN))
1843 return -EPERM;
1844
1845 if (info->attrs[NBD_ATTR_INDEX])
1846 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1847 if (!info->attrs[NBD_ATTR_SOCKETS]) {
1848 printk(KERN_ERR "nbd: must specify at least one socket\n");
1849 return -EINVAL;
1850 }
1851 if (!info->attrs[NBD_ATTR_SIZE_BYTES]) {
1852 printk(KERN_ERR "nbd: must specify a size in bytes for the device\n");
1853 return -EINVAL;
1854 }
1855 again:
1856 mutex_lock(&nbd_index_mutex);
1857 if (index == -1) {
1858 ret = idr_for_each(&nbd_index_idr, &find_free_cb, &nbd);
1859 if (ret == 0) {
1860 int new_index;
1861 new_index = nbd_dev_add(-1);
1862 if (new_index < 0) {
1863 mutex_unlock(&nbd_index_mutex);
1864 printk(KERN_ERR "nbd: failed to add new device\n");
1865 return new_index;
1866 }
1867 nbd = idr_find(&nbd_index_idr, new_index);
1868 }
1869 } else {
1870 nbd = idr_find(&nbd_index_idr, index);
1871 if (!nbd) {
1872 ret = nbd_dev_add(index);
1873 if (ret < 0) {
1874 mutex_unlock(&nbd_index_mutex);
1875 printk(KERN_ERR "nbd: failed to add new device\n");
1876 return ret;
1877 }
1878 nbd = idr_find(&nbd_index_idr, index);
1879 }
1880 }
1881 if (!nbd) {
1882 printk(KERN_ERR "nbd: couldn't find device at index %d\n",
1883 index);
1884 mutex_unlock(&nbd_index_mutex);
1885 return -EINVAL;
1886 }
1887
1888 if (test_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags) &&
1889 test_bit(NBD_DISCONNECT_REQUESTED, &nbd->flags)) {
1890 nbd->destroy_complete = &destroy_complete;
1891 mutex_unlock(&nbd_index_mutex);
1892
1893 /* Wait untill the the nbd stuff is totally destroyed */
1894 wait_for_completion(&destroy_complete);
1895 goto again;
1896 }
1897
1898 if (!refcount_inc_not_zero(&nbd->refs)) {
1899 mutex_unlock(&nbd_index_mutex);
1900 if (index == -1)
1901 goto again;
1902 printk(KERN_ERR "nbd: device at index %d is going down\n",
1903 index);
1904 return -EINVAL;
1905 }
1906 mutex_unlock(&nbd_index_mutex);
1907
1908 mutex_lock(&nbd->config_lock);
1909 if (refcount_read(&nbd->config_refs)) {
1910 mutex_unlock(&nbd->config_lock);
1911 nbd_put(nbd);
1912 if (index == -1)
1913 goto again;
1914 printk(KERN_ERR "nbd: nbd%d already in use\n", index);
1915 return -EBUSY;
1916 }
1917 if (WARN_ON(nbd->config)) {
1918 mutex_unlock(&nbd->config_lock);
1919 nbd_put(nbd);
1920 return -EINVAL;
1921 }
1922 config = nbd->config = nbd_alloc_config();
1923 if (!nbd->config) {
1924 mutex_unlock(&nbd->config_lock);
1925 nbd_put(nbd);
1926 printk(KERN_ERR "nbd: couldn't allocate config\n");
1927 return -ENOMEM;
1928 }
1929 refcount_set(&nbd->config_refs, 1);
1930 set_bit(NBD_RT_BOUND, &config->runtime_flags);
1931
1932 ret = nbd_genl_size_set(info, nbd);
1933 if (ret)
1934 goto out;
1935
1936 if (info->attrs[NBD_ATTR_TIMEOUT])
1937 nbd_set_cmd_timeout(nbd,
1938 nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]));
1939 if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
1940 config->dead_conn_timeout =
1941 nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
1942 config->dead_conn_timeout *= HZ;
1943 }
1944 if (info->attrs[NBD_ATTR_SERVER_FLAGS])
1945 config->flags =
1946 nla_get_u64(info->attrs[NBD_ATTR_SERVER_FLAGS]);
1947 if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
1948 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
1949 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
1950 set_bit(NBD_RT_DESTROY_ON_DISCONNECT,
1951 &config->runtime_flags);
1952 set_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags);
1953 put_dev = true;
1954 } else {
1955 clear_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags);
1956 }
1957 if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
1958 set_bit(NBD_RT_DISCONNECT_ON_CLOSE,
1959 &config->runtime_flags);
1960 }
1961 }
1962
1963 if (info->attrs[NBD_ATTR_SOCKETS]) {
1964 struct nlattr *attr;
1965 int rem, fd;
1966
1967 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
1968 rem) {
1969 struct nlattr *socks[NBD_SOCK_MAX+1];
1970
1971 if (nla_type(attr) != NBD_SOCK_ITEM) {
1972 printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
1973 ret = -EINVAL;
1974 goto out;
1975 }
1976 ret = nla_parse_nested_deprecated(socks, NBD_SOCK_MAX,
1977 attr,
1978 nbd_sock_policy,
1979 info->extack);
1980 if (ret != 0) {
1981 printk(KERN_ERR "nbd: error processing sock list\n");
1982 ret = -EINVAL;
1983 goto out;
1984 }
1985 if (!socks[NBD_SOCK_FD])
1986 continue;
1987 fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
1988 ret = nbd_add_socket(nbd, fd, true);
1989 if (ret)
1990 goto out;
1991 }
1992 }
1993 ret = nbd_start_device(nbd);
1994 out:
1995 mutex_unlock(&nbd->config_lock);
1996 if (!ret) {
1997 set_bit(NBD_RT_HAS_CONFIG_REF, &config->runtime_flags);
1998 refcount_inc(&nbd->config_refs);
1999 nbd_connect_reply(info, nbd->index);
2000 }
2001 nbd_config_put(nbd);
2002 if (put_dev)
2003 nbd_put(nbd);
2004 return ret;
2005 }
2006
nbd_disconnect_and_put(struct nbd_device * nbd)2007 static void nbd_disconnect_and_put(struct nbd_device *nbd)
2008 {
2009 mutex_lock(&nbd->config_lock);
2010 nbd_disconnect(nbd);
2011 nbd_clear_sock(nbd);
2012 mutex_unlock(&nbd->config_lock);
2013 /*
2014 * Make sure recv thread has finished, so it does not drop the last
2015 * config ref and try to destroy the workqueue from inside the work
2016 * queue.
2017 */
2018 flush_workqueue(nbd->recv_workq);
2019 if (test_and_clear_bit(NBD_RT_HAS_CONFIG_REF,
2020 &nbd->config->runtime_flags))
2021 nbd_config_put(nbd);
2022 }
2023
nbd_genl_disconnect(struct sk_buff * skb,struct genl_info * info)2024 static int nbd_genl_disconnect(struct sk_buff *skb, struct genl_info *info)
2025 {
2026 struct nbd_device *nbd;
2027 int index;
2028
2029 if (!netlink_capable(skb, CAP_SYS_ADMIN))
2030 return -EPERM;
2031
2032 if (!info->attrs[NBD_ATTR_INDEX]) {
2033 printk(KERN_ERR "nbd: must specify an index to disconnect\n");
2034 return -EINVAL;
2035 }
2036 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2037 mutex_lock(&nbd_index_mutex);
2038 nbd = idr_find(&nbd_index_idr, index);
2039 if (!nbd) {
2040 mutex_unlock(&nbd_index_mutex);
2041 printk(KERN_ERR "nbd: couldn't find device at index %d\n",
2042 index);
2043 return -EINVAL;
2044 }
2045 if (!refcount_inc_not_zero(&nbd->refs)) {
2046 mutex_unlock(&nbd_index_mutex);
2047 printk(KERN_ERR "nbd: device at index %d is going down\n",
2048 index);
2049 return -EINVAL;
2050 }
2051 mutex_unlock(&nbd_index_mutex);
2052 if (!refcount_inc_not_zero(&nbd->config_refs)) {
2053 nbd_put(nbd);
2054 return 0;
2055 }
2056 nbd_disconnect_and_put(nbd);
2057 nbd_config_put(nbd);
2058 nbd_put(nbd);
2059 return 0;
2060 }
2061
nbd_genl_reconfigure(struct sk_buff * skb,struct genl_info * info)2062 static int nbd_genl_reconfigure(struct sk_buff *skb, struct genl_info *info)
2063 {
2064 struct nbd_device *nbd = NULL;
2065 struct nbd_config *config;
2066 int index;
2067 int ret = 0;
2068 bool put_dev = false;
2069
2070 if (!netlink_capable(skb, CAP_SYS_ADMIN))
2071 return -EPERM;
2072
2073 if (!info->attrs[NBD_ATTR_INDEX]) {
2074 printk(KERN_ERR "nbd: must specify a device to reconfigure\n");
2075 return -EINVAL;
2076 }
2077 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2078 mutex_lock(&nbd_index_mutex);
2079 nbd = idr_find(&nbd_index_idr, index);
2080 if (!nbd) {
2081 mutex_unlock(&nbd_index_mutex);
2082 printk(KERN_ERR "nbd: couldn't find a device at index %d\n",
2083 index);
2084 return -EINVAL;
2085 }
2086 if (!refcount_inc_not_zero(&nbd->refs)) {
2087 mutex_unlock(&nbd_index_mutex);
2088 printk(KERN_ERR "nbd: device at index %d is going down\n",
2089 index);
2090 return -EINVAL;
2091 }
2092 mutex_unlock(&nbd_index_mutex);
2093
2094 if (!refcount_inc_not_zero(&nbd->config_refs)) {
2095 dev_err(nbd_to_dev(nbd),
2096 "not configured, cannot reconfigure\n");
2097 nbd_put(nbd);
2098 return -EINVAL;
2099 }
2100
2101 mutex_lock(&nbd->config_lock);
2102 config = nbd->config;
2103 if (!test_bit(NBD_RT_BOUND, &config->runtime_flags) ||
2104 !nbd->task_recv) {
2105 dev_err(nbd_to_dev(nbd),
2106 "not configured, cannot reconfigure\n");
2107 ret = -EINVAL;
2108 goto out;
2109 }
2110
2111 ret = nbd_genl_size_set(info, nbd);
2112 if (ret)
2113 goto out;
2114
2115 if (info->attrs[NBD_ATTR_TIMEOUT])
2116 nbd_set_cmd_timeout(nbd,
2117 nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]));
2118 if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
2119 config->dead_conn_timeout =
2120 nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
2121 config->dead_conn_timeout *= HZ;
2122 }
2123 if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
2124 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
2125 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
2126 if (!test_and_set_bit(NBD_RT_DESTROY_ON_DISCONNECT,
2127 &config->runtime_flags))
2128 put_dev = true;
2129 set_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags);
2130 } else {
2131 if (test_and_clear_bit(NBD_RT_DESTROY_ON_DISCONNECT,
2132 &config->runtime_flags))
2133 refcount_inc(&nbd->refs);
2134 clear_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags);
2135 }
2136
2137 if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
2138 set_bit(NBD_RT_DISCONNECT_ON_CLOSE,
2139 &config->runtime_flags);
2140 } else {
2141 clear_bit(NBD_RT_DISCONNECT_ON_CLOSE,
2142 &config->runtime_flags);
2143 }
2144 }
2145
2146 if (info->attrs[NBD_ATTR_SOCKETS]) {
2147 struct nlattr *attr;
2148 int rem, fd;
2149
2150 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
2151 rem) {
2152 struct nlattr *socks[NBD_SOCK_MAX+1];
2153
2154 if (nla_type(attr) != NBD_SOCK_ITEM) {
2155 printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
2156 ret = -EINVAL;
2157 goto out;
2158 }
2159 ret = nla_parse_nested_deprecated(socks, NBD_SOCK_MAX,
2160 attr,
2161 nbd_sock_policy,
2162 info->extack);
2163 if (ret != 0) {
2164 printk(KERN_ERR "nbd: error processing sock list\n");
2165 ret = -EINVAL;
2166 goto out;
2167 }
2168 if (!socks[NBD_SOCK_FD])
2169 continue;
2170 fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
2171 ret = nbd_reconnect_socket(nbd, fd);
2172 if (ret) {
2173 if (ret == -ENOSPC)
2174 ret = 0;
2175 goto out;
2176 }
2177 dev_info(nbd_to_dev(nbd), "reconnected socket\n");
2178 }
2179 }
2180 out:
2181 mutex_unlock(&nbd->config_lock);
2182 nbd_config_put(nbd);
2183 nbd_put(nbd);
2184 if (put_dev)
2185 nbd_put(nbd);
2186 return ret;
2187 }
2188
2189 static const struct genl_small_ops nbd_connect_genl_ops[] = {
2190 {
2191 .cmd = NBD_CMD_CONNECT,
2192 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2193 .doit = nbd_genl_connect,
2194 },
2195 {
2196 .cmd = NBD_CMD_DISCONNECT,
2197 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2198 .doit = nbd_genl_disconnect,
2199 },
2200 {
2201 .cmd = NBD_CMD_RECONFIGURE,
2202 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2203 .doit = nbd_genl_reconfigure,
2204 },
2205 {
2206 .cmd = NBD_CMD_STATUS,
2207 .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2208 .doit = nbd_genl_status,
2209 },
2210 };
2211
2212 static const struct genl_multicast_group nbd_mcast_grps[] = {
2213 { .name = NBD_GENL_MCAST_GROUP_NAME, },
2214 };
2215
2216 static struct genl_family nbd_genl_family __ro_after_init = {
2217 .hdrsize = 0,
2218 .name = NBD_GENL_FAMILY_NAME,
2219 .version = NBD_GENL_VERSION,
2220 .module = THIS_MODULE,
2221 .small_ops = nbd_connect_genl_ops,
2222 .n_small_ops = ARRAY_SIZE(nbd_connect_genl_ops),
2223 .maxattr = NBD_ATTR_MAX,
2224 .policy = nbd_attr_policy,
2225 .mcgrps = nbd_mcast_grps,
2226 .n_mcgrps = ARRAY_SIZE(nbd_mcast_grps),
2227 };
2228
populate_nbd_status(struct nbd_device * nbd,struct sk_buff * reply)2229 static int populate_nbd_status(struct nbd_device *nbd, struct sk_buff *reply)
2230 {
2231 struct nlattr *dev_opt;
2232 u8 connected = 0;
2233 int ret;
2234
2235 /* This is a little racey, but for status it's ok. The
2236 * reason we don't take a ref here is because we can't
2237 * take a ref in the index == -1 case as we would need
2238 * to put under the nbd_index_mutex, which could
2239 * deadlock if we are configured to remove ourselves
2240 * once we're disconnected.
2241 */
2242 if (refcount_read(&nbd->config_refs))
2243 connected = 1;
2244 dev_opt = nla_nest_start_noflag(reply, NBD_DEVICE_ITEM);
2245 if (!dev_opt)
2246 return -EMSGSIZE;
2247 ret = nla_put_u32(reply, NBD_DEVICE_INDEX, nbd->index);
2248 if (ret)
2249 return -EMSGSIZE;
2250 ret = nla_put_u8(reply, NBD_DEVICE_CONNECTED,
2251 connected);
2252 if (ret)
2253 return -EMSGSIZE;
2254 nla_nest_end(reply, dev_opt);
2255 return 0;
2256 }
2257
status_cb(int id,void * ptr,void * data)2258 static int status_cb(int id, void *ptr, void *data)
2259 {
2260 struct nbd_device *nbd = ptr;
2261 return populate_nbd_status(nbd, (struct sk_buff *)data);
2262 }
2263
nbd_genl_status(struct sk_buff * skb,struct genl_info * info)2264 static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info)
2265 {
2266 struct nlattr *dev_list;
2267 struct sk_buff *reply;
2268 void *reply_head;
2269 size_t msg_size;
2270 int index = -1;
2271 int ret = -ENOMEM;
2272
2273 if (info->attrs[NBD_ATTR_INDEX])
2274 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2275
2276 mutex_lock(&nbd_index_mutex);
2277
2278 msg_size = nla_total_size(nla_attr_size(sizeof(u32)) +
2279 nla_attr_size(sizeof(u8)));
2280 msg_size *= (index == -1) ? nbd_total_devices : 1;
2281
2282 reply = genlmsg_new(msg_size, GFP_KERNEL);
2283 if (!reply)
2284 goto out;
2285 reply_head = genlmsg_put_reply(reply, info, &nbd_genl_family, 0,
2286 NBD_CMD_STATUS);
2287 if (!reply_head) {
2288 nlmsg_free(reply);
2289 goto out;
2290 }
2291
2292 dev_list = nla_nest_start_noflag(reply, NBD_ATTR_DEVICE_LIST);
2293 if (index == -1) {
2294 ret = idr_for_each(&nbd_index_idr, &status_cb, reply);
2295 if (ret) {
2296 nlmsg_free(reply);
2297 goto out;
2298 }
2299 } else {
2300 struct nbd_device *nbd;
2301 nbd = idr_find(&nbd_index_idr, index);
2302 if (nbd) {
2303 ret = populate_nbd_status(nbd, reply);
2304 if (ret) {
2305 nlmsg_free(reply);
2306 goto out;
2307 }
2308 }
2309 }
2310 nla_nest_end(reply, dev_list);
2311 genlmsg_end(reply, reply_head);
2312 ret = genlmsg_reply(reply, info);
2313 out:
2314 mutex_unlock(&nbd_index_mutex);
2315 return ret;
2316 }
2317
nbd_connect_reply(struct genl_info * info,int index)2318 static void nbd_connect_reply(struct genl_info *info, int index)
2319 {
2320 struct sk_buff *skb;
2321 void *msg_head;
2322 int ret;
2323
2324 skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2325 if (!skb)
2326 return;
2327 msg_head = genlmsg_put_reply(skb, info, &nbd_genl_family, 0,
2328 NBD_CMD_CONNECT);
2329 if (!msg_head) {
2330 nlmsg_free(skb);
2331 return;
2332 }
2333 ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2334 if (ret) {
2335 nlmsg_free(skb);
2336 return;
2337 }
2338 genlmsg_end(skb, msg_head);
2339 genlmsg_reply(skb, info);
2340 }
2341
nbd_mcast_index(int index)2342 static void nbd_mcast_index(int index)
2343 {
2344 struct sk_buff *skb;
2345 void *msg_head;
2346 int ret;
2347
2348 skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2349 if (!skb)
2350 return;
2351 msg_head = genlmsg_put(skb, 0, 0, &nbd_genl_family, 0,
2352 NBD_CMD_LINK_DEAD);
2353 if (!msg_head) {
2354 nlmsg_free(skb);
2355 return;
2356 }
2357 ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2358 if (ret) {
2359 nlmsg_free(skb);
2360 return;
2361 }
2362 genlmsg_end(skb, msg_head);
2363 genlmsg_multicast(&nbd_genl_family, skb, 0, 0, GFP_KERNEL);
2364 }
2365
nbd_dead_link_work(struct work_struct * work)2366 static void nbd_dead_link_work(struct work_struct *work)
2367 {
2368 struct link_dead_args *args = container_of(work, struct link_dead_args,
2369 work);
2370 nbd_mcast_index(args->index);
2371 kfree(args);
2372 }
2373
nbd_init(void)2374 static int __init nbd_init(void)
2375 {
2376 int i;
2377
2378 BUILD_BUG_ON(sizeof(struct nbd_request) != 28);
2379
2380 if (max_part < 0) {
2381 printk(KERN_ERR "nbd: max_part must be >= 0\n");
2382 return -EINVAL;
2383 }
2384
2385 part_shift = 0;
2386 if (max_part > 0) {
2387 part_shift = fls(max_part);
2388
2389 /*
2390 * Adjust max_part according to part_shift as it is exported
2391 * to user space so that user can know the max number of
2392 * partition kernel should be able to manage.
2393 *
2394 * Note that -1 is required because partition 0 is reserved
2395 * for the whole disk.
2396 */
2397 max_part = (1UL << part_shift) - 1;
2398 }
2399
2400 if ((1UL << part_shift) > DISK_MAX_PARTS)
2401 return -EINVAL;
2402
2403 if (nbds_max > 1UL << (MINORBITS - part_shift))
2404 return -EINVAL;
2405
2406 if (register_blkdev(NBD_MAJOR, "nbd"))
2407 return -EIO;
2408
2409 if (genl_register_family(&nbd_genl_family)) {
2410 unregister_blkdev(NBD_MAJOR, "nbd");
2411 return -EINVAL;
2412 }
2413 nbd_dbg_init();
2414
2415 mutex_lock(&nbd_index_mutex);
2416 for (i = 0; i < nbds_max; i++)
2417 nbd_dev_add(i);
2418 mutex_unlock(&nbd_index_mutex);
2419 return 0;
2420 }
2421
nbd_exit_cb(int id,void * ptr,void * data)2422 static int nbd_exit_cb(int id, void *ptr, void *data)
2423 {
2424 struct list_head *list = (struct list_head *)data;
2425 struct nbd_device *nbd = ptr;
2426
2427 list_add_tail(&nbd->list, list);
2428 return 0;
2429 }
2430
nbd_cleanup(void)2431 static void __exit nbd_cleanup(void)
2432 {
2433 struct nbd_device *nbd;
2434 LIST_HEAD(del_list);
2435
2436 nbd_dbg_close();
2437
2438 mutex_lock(&nbd_index_mutex);
2439 idr_for_each(&nbd_index_idr, &nbd_exit_cb, &del_list);
2440 mutex_unlock(&nbd_index_mutex);
2441
2442 while (!list_empty(&del_list)) {
2443 nbd = list_first_entry(&del_list, struct nbd_device, list);
2444 list_del_init(&nbd->list);
2445 if (refcount_read(&nbd->refs) != 1)
2446 printk(KERN_ERR "nbd: possibly leaking a device\n");
2447 nbd_put(nbd);
2448 }
2449
2450 idr_destroy(&nbd_index_idr);
2451 genl_unregister_family(&nbd_genl_family);
2452 unregister_blkdev(NBD_MAJOR, "nbd");
2453 }
2454
2455 module_init(nbd_init);
2456 module_exit(nbd_cleanup);
2457
2458 MODULE_DESCRIPTION("Network Block Device");
2459 MODULE_LICENSE("GPL");
2460
2461 module_param(nbds_max, int, 0444);
2462 MODULE_PARM_DESC(nbds_max, "number of network block devices to initialize (default: 16)");
2463 module_param(max_part, int, 0444);
2464 MODULE_PARM_DESC(max_part, "number of partitions per device (default: 16)");
2465