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