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