2 * Network block device - make block devices work over TCP
4 * Note that you can not swap over this thing, yet. Seems to work but
5 * deadlocks sometimes - you can not swap over TCP in general.
7 * Copyright 1997-2000, 2008 Pavel Machek <pavel@ucw.cz>
8 * Parts copyright 2001 Steven Whitehouse <steve@chygwyn.com>
10 * This file is released under GPLv2 or later.
12 * (part of code stolen from loop.c)
15 #include <linux/major.h>
17 #include <linux/blkdev.h>
18 #include <linux/module.h>
19 #include <linux/init.h>
20 #include <linux/sched.h>
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>
33 #include <linux/net.h>
34 #include <linux/kthread.h>
36 #include <asm/uaccess.h>
37 #include <asm/system.h>
38 #include <asm/types.h>
43 #include <linux/nbd.h>
46 #define LO_MAGIC 0x68797548
49 #define dprintk(flags, fmt...)
51 #define dprintk(flags, fmt...) do { \
52 if (debugflags & (flags)) printk(KERN_DEBUG fmt); \
54 #define DBG_IOCTL 0x0004
55 #define DBG_INIT 0x0010
56 #define DBG_EXIT 0x0020
57 #define DBG_BLKDEV 0x0100
60 static unsigned int debugflags;
63 static unsigned int nbds_max = 16;
64 static struct nbd_device *nbd_dev;
68 * Use just one lock (or at most 1 per NIC). Two arguments for this:
69 * 1. Each NIC is essentially a synchronization point for all servers
70 * accessed through that NIC so there's no need to have more locks
72 * 2. More locks lead to more "Dirty cache line bouncing" which will slow
73 * down each lock to the point where they're actually slower than just
75 * Thanks go to Jens Axboe and Al Viro for their LKML emails explaining this!
77 static DEFINE_SPINLOCK(nbd_lock);
80 static const char *ioctl_cmd_to_ascii(int cmd)
83 case NBD_SET_SOCK: return "set-sock";
84 case NBD_SET_BLKSIZE: return "set-blksize";
85 case NBD_SET_SIZE: return "set-size";
86 case NBD_DO_IT: return "do-it";
87 case NBD_CLEAR_SOCK: return "clear-sock";
88 case NBD_CLEAR_QUE: return "clear-que";
89 case NBD_PRINT_DEBUG: return "print-debug";
90 case NBD_SET_SIZE_BLOCKS: return "set-size-blocks";
91 case NBD_DISCONNECT: return "disconnect";
92 case NBD_SET_TIMEOUT: return "set-timeout";
93 case NBD_SET_FLAGS: return "set-flags";
94 case BLKROSET: return "set-read-only";
95 case BLKFLSBUF: return "flush-buffer-cache";
100 static const char *nbdcmd_to_ascii(int cmd)
103 case NBD_CMD_READ: return "read";
104 case NBD_CMD_WRITE: return "write";
105 case NBD_CMD_DISC: return "disconnect";
106 case NBD_CMD_FLUSH: return "flush";
112 static void nbd_end_request(struct request *req)
114 int error = req->errors ? -EIO : 0;
115 struct request_queue *q = req->q;
118 dprintk(DBG_BLKDEV, "%s: request %p: %s\n", req->rq_disk->disk_name,
119 req, error ? "failed" : "done");
121 spin_lock_irqsave(q->queue_lock, flags);
122 __blk_end_request_all(req, error);
123 spin_unlock_irqrestore(q->queue_lock, flags);
126 static void sock_shutdown(struct nbd_device *lo, int lock)
128 /* Forcibly shutdown the socket causing all listeners
131 * FIXME: This code is duplicated from sys_shutdown, but
132 * there should be a more generic interface rather than
133 * calling socket ops directly here */
135 mutex_lock(&lo->tx_lock);
137 printk(KERN_WARNING "%s: shutting down socket\n",
138 lo->disk->disk_name);
139 kernel_sock_shutdown(lo->sock, SHUT_RDWR);
143 mutex_unlock(&lo->tx_lock);
146 static void nbd_xmit_timeout(unsigned long arg)
148 struct task_struct *task = (struct task_struct *)arg;
150 printk(KERN_WARNING "nbd: killing hung xmit (%s, pid: %d)\n",
151 task->comm, task->pid);
152 force_sig(SIGKILL, task);
156 * Send or receive packet.
158 static int sock_xmit(struct nbd_device *lo, int send, void *buf, int size,
161 struct socket *sock = lo->sock;
165 sigset_t blocked, oldset;
167 if (unlikely(!sock)) {
168 printk(KERN_ERR "%s: Attempted %s on closed socket in sock_xmit\n",
169 lo->disk->disk_name, (send ? "send" : "recv"));
173 /* Allow interception of SIGKILL only
174 * Don't allow other signals to interrupt the transmission */
175 siginitsetinv(&blocked, sigmask(SIGKILL));
176 sigprocmask(SIG_SETMASK, &blocked, &oldset);
179 sock->sk->sk_allocation = GFP_NOIO;
184 msg.msg_control = NULL;
185 msg.msg_controllen = 0;
186 msg.msg_flags = msg_flags | MSG_NOSIGNAL;
189 struct timer_list ti;
191 if (lo->xmit_timeout) {
193 ti.function = nbd_xmit_timeout;
194 ti.data = (unsigned long)current;
195 ti.expires = jiffies + lo->xmit_timeout;
198 result = kernel_sendmsg(sock, &msg, &iov, 1, size);
199 if (lo->xmit_timeout)
202 result = kernel_recvmsg(sock, &msg, &iov, 1, size, 0);
204 if (signal_pending(current)) {
206 printk(KERN_WARNING "nbd (pid %d: %s) got signal %d\n",
207 task_pid_nr(current), current->comm,
208 dequeue_signal_lock(current, ¤t->blocked, &info));
210 sock_shutdown(lo, !send);
216 result = -EPIPE; /* short read */
223 sigprocmask(SIG_SETMASK, &oldset, NULL);
228 static inline int sock_send_bvec(struct nbd_device *lo, struct bio_vec *bvec,
232 void *kaddr = kmap(bvec->bv_page);
233 result = sock_xmit(lo, 1, kaddr + bvec->bv_offset, bvec->bv_len, flags);
234 kunmap(bvec->bv_page);
238 /* always call with the tx_lock held */
239 static int nbd_send_req(struct nbd_device *lo, struct request *req)
242 struct nbd_request request;
243 unsigned long size = blk_rq_bytes(req);
245 request.magic = htonl(NBD_REQUEST_MAGIC);
246 /* If FUA is set in the request, and we are told to send FUA, then OR in NBD_CMD_FLAG_FUA */
247 request.type = htonl(nbd_cmd(req) |
248 (( (req->cmd_flags & REQ_FUA) && (lo->flags & NBD_FLAG_SEND_FUA)) ?
249 NBD_CMD_FLAG_FUA : 0));
250 request.from = cpu_to_be64((u64)blk_rq_pos(req) << 9);
251 request.len = htonl(size);
252 memcpy(request.handle, &req, sizeof(req));
254 dprintk(DBG_TX, "%s: request %p: sending control (%s@%llu,%uB)\n",
255 lo->disk->disk_name, req,
256 nbdcmd_to_ascii(nbd_cmd(req)),
257 (unsigned long long)blk_rq_pos(req) << 9,
259 result = sock_xmit(lo, 1, &request, sizeof(request),
260 (nbd_cmd(req) == NBD_CMD_WRITE) ? MSG_MORE : 0);
262 printk(KERN_ERR "%s: Send control failed (result %d)\n",
263 lo->disk->disk_name, result);
267 if (nbd_cmd(req) == NBD_CMD_WRITE) {
268 struct req_iterator iter;
269 struct bio_vec *bvec;
271 * we are really probing at internals to determine
272 * whether to set MSG_MORE or not...
274 rq_for_each_segment(bvec, req, iter) {
276 if (!rq_iter_last(req, iter))
278 dprintk(DBG_TX, "%s: request %p: sending %d bytes data\n",
279 lo->disk->disk_name, req, bvec->bv_len);
280 result = sock_send_bvec(lo, bvec, flags);
282 printk(KERN_ERR "%s: Send data failed (result %d)\n",
283 lo->disk->disk_name, result);
294 static struct request *nbd_find_request(struct nbd_device *lo,
295 struct request *xreq)
297 struct request *req, *tmp;
300 err = wait_event_interruptible(lo->active_wq, lo->active_req != xreq);
304 spin_lock(&lo->queue_lock);
305 list_for_each_entry_safe(req, tmp, &lo->queue_head, queuelist) {
308 list_del_init(&req->queuelist);
309 spin_unlock(&lo->queue_lock);
312 spin_unlock(&lo->queue_lock);
320 static inline int sock_recv_bvec(struct nbd_device *lo, struct bio_vec *bvec)
323 void *kaddr = kmap(bvec->bv_page);
324 result = sock_xmit(lo, 0, kaddr + bvec->bv_offset, bvec->bv_len,
326 kunmap(bvec->bv_page);
330 /* NULL returned = something went wrong, inform userspace */
331 static struct request *nbd_read_stat(struct nbd_device *lo)
334 struct nbd_reply reply;
338 result = sock_xmit(lo, 0, &reply, sizeof(reply), MSG_WAITALL);
340 printk(KERN_ERR "%s: Receive control failed (result %d)\n",
341 lo->disk->disk_name, result);
345 if (ntohl(reply.magic) != NBD_REPLY_MAGIC) {
346 printk(KERN_ERR "%s: Wrong magic (0x%lx)\n",
348 (unsigned long)ntohl(reply.magic));
353 req = nbd_find_request(lo, *(struct request **)reply.handle);
355 result = PTR_ERR(req);
356 if (result != -ENOENT)
359 printk(KERN_ERR "%s: Unexpected reply (%p)\n",
360 lo->disk->disk_name, reply.handle);
365 if (ntohl(reply.error)) {
366 printk(KERN_ERR "%s: Other side returned error (%d)\n",
367 lo->disk->disk_name, ntohl(reply.error));
372 dprintk(DBG_RX, "%s: request %p: got reply\n",
373 lo->disk->disk_name, req);
374 if (nbd_cmd(req) == NBD_CMD_READ) {
375 struct req_iterator iter;
376 struct bio_vec *bvec;
378 rq_for_each_segment(bvec, req, iter) {
379 result = sock_recv_bvec(lo, bvec);
381 printk(KERN_ERR "%s: Receive data failed (result %d)\n",
382 lo->disk->disk_name, result);
386 dprintk(DBG_RX, "%s: request %p: got %d bytes data\n",
387 lo->disk->disk_name, req, bvec->bv_len);
392 lo->harderror = result;
396 static ssize_t pid_show(struct device *dev,
397 struct device_attribute *attr, char *buf)
399 struct gendisk *disk = dev_to_disk(dev);
401 return sprintf(buf, "%ld\n",
402 (long) ((struct nbd_device *)disk->private_data)->pid);
405 static struct device_attribute pid_attr = {
406 .attr = { .name = "pid", .mode = S_IRUGO},
410 static int nbd_do_it(struct nbd_device *lo)
415 BUG_ON(lo->magic != LO_MAGIC);
417 lo->pid = current->pid;
418 ret = sysfs_create_file(&disk_to_dev(lo->disk)->kobj, &pid_attr.attr);
420 printk(KERN_ERR "nbd: sysfs_create_file failed!");
425 while ((req = nbd_read_stat(lo)) != NULL)
426 nbd_end_request(req);
428 sysfs_remove_file(&disk_to_dev(lo->disk)->kobj, &pid_attr.attr);
433 static void nbd_clear_que(struct nbd_device *lo)
437 BUG_ON(lo->magic != LO_MAGIC);
440 * Because we have set lo->sock to NULL under the tx_lock, all
441 * modifications to the list must have completed by now. For
442 * the same reason, the active_req must be NULL.
444 * As a consequence, we don't need to take the spin lock while
445 * purging the list here.
448 BUG_ON(lo->active_req);
450 while (!list_empty(&lo->queue_head)) {
451 req = list_entry(lo->queue_head.next, struct request,
453 list_del_init(&req->queuelist);
455 nbd_end_request(req);
460 static void nbd_handle_req(struct nbd_device *lo, struct request *req)
462 if (req->cmd_type != REQ_TYPE_FS)
465 nbd_cmd(req) = NBD_CMD_READ;
466 if (rq_data_dir(req) == WRITE) {
467 nbd_cmd(req) = NBD_CMD_WRITE;
468 if (lo->flags & NBD_FLAG_READ_ONLY) {
469 printk(KERN_ERR "%s: Write on read-only\n",
470 lo->disk->disk_name);
475 if (req->cmd_flags & REQ_FLUSH) {
476 if (unlikely(blk_rq_sectors(req))) {
477 /* Elevator is meant to guarantee that a request with REQ_FLUSH
478 * set is broken into an empty request with REQ_FLUSH set then
479 * the rest of the content (if any). If this doesn't happen,
480 * whinge, then proceed to do the content without a flush.
482 printk(KERN_ERR "%s: nbd passed non-empty flush request\n",
483 lo->disk->disk_name);
486 if (lo->flags & NBD_FLAG_SEND_FLUSH)
487 nbd_cmd(req) = NBD_CMD_FLUSH;
489 /* Ignore flush that we don't need */
490 nbd_end_request(req);
498 mutex_lock(&lo->tx_lock);
499 if (unlikely(!lo->sock)) {
500 mutex_unlock(&lo->tx_lock);
501 printk(KERN_ERR "%s: Attempted send on closed socket\n",
502 lo->disk->disk_name);
506 lo->active_req = req;
508 if (nbd_send_req(lo, req) != 0) {
509 printk(KERN_ERR "%s: Request send failed\n",
510 lo->disk->disk_name);
512 nbd_end_request(req);
514 spin_lock(&lo->queue_lock);
515 list_add(&req->queuelist, &lo->queue_head);
516 spin_unlock(&lo->queue_lock);
519 lo->active_req = NULL;
520 mutex_unlock(&lo->tx_lock);
521 wake_up_all(&lo->active_wq);
527 nbd_end_request(req);
530 static int nbd_thread(void *data)
532 struct nbd_device *lo = data;
535 set_user_nice(current, -20);
536 while (!kthread_should_stop() || !list_empty(&lo->waiting_queue)) {
537 /* wait for something to do */
538 wait_event_interruptible(lo->waiting_wq,
539 kthread_should_stop() ||
540 !list_empty(&lo->waiting_queue));
542 /* extract request */
543 if (list_empty(&lo->waiting_queue))
546 spin_lock_irq(&lo->queue_lock);
547 req = list_entry(lo->waiting_queue.next, struct request,
549 list_del_init(&req->queuelist);
550 spin_unlock_irq(&lo->queue_lock);
553 nbd_handle_req(lo, req);
559 * We always wait for result of write, for now. It would be nice to make it optional
561 * if ((rq_data_dir(req) == WRITE) && (lo->flags & NBD_WRITE_NOCHK))
562 * { printk( "Warning: Ignoring result!\n"); nbd_end_request( req ); }
565 static void do_nbd_request(struct request_queue *q)
569 while ((req = blk_fetch_request(q)) != NULL) {
570 struct nbd_device *lo;
572 spin_unlock_irq(q->queue_lock);
574 dprintk(DBG_BLKDEV, "%s: request %p: dequeued (flags=%x)\n",
575 req->rq_disk->disk_name, req, req->cmd_type);
577 lo = req->rq_disk->private_data;
579 BUG_ON(lo->magic != LO_MAGIC);
581 if (unlikely(!lo->sock)) {
582 printk(KERN_ERR "%s: Attempted send on closed socket\n",
583 lo->disk->disk_name);
585 nbd_end_request(req);
586 spin_lock_irq(q->queue_lock);
590 spin_lock_irq(&lo->queue_lock);
591 list_add_tail(&req->queuelist, &lo->waiting_queue);
592 spin_unlock_irq(&lo->queue_lock);
594 wake_up(&lo->waiting_wq);
596 spin_lock_irq(q->queue_lock);
600 /* Must be called with tx_lock held */
602 static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *lo,
603 unsigned int cmd, unsigned long arg)
606 case NBD_DISCONNECT: {
609 printk(KERN_INFO "%s: NBD_DISCONNECT\n", lo->disk->disk_name);
611 blk_rq_init(NULL, &sreq);
612 sreq.cmd_type = REQ_TYPE_SPECIAL;
613 nbd_cmd(&sreq) = NBD_CMD_DISC;
616 nbd_send_req(lo, &sreq);
620 case NBD_CLEAR_SOCK: {
627 BUG_ON(!list_empty(&lo->queue_head));
639 struct inode *inode = file->f_path.dentry->d_inode;
640 if (S_ISSOCK(inode->i_mode)) {
642 lo->sock = SOCKET_I(inode);
644 bdev->bd_invalidated = 1;
653 case NBD_SET_BLKSIZE:
655 lo->bytesize &= ~(lo->blksize-1);
656 bdev->bd_inode->i_size = lo->bytesize;
657 set_blocksize(bdev, lo->blksize);
658 set_capacity(lo->disk, lo->bytesize >> 9);
662 lo->bytesize = arg & ~(lo->blksize-1);
663 bdev->bd_inode->i_size = lo->bytesize;
664 set_blocksize(bdev, lo->blksize);
665 set_capacity(lo->disk, lo->bytesize >> 9);
668 case NBD_SET_TIMEOUT:
669 lo->xmit_timeout = arg * HZ;
676 if (lo->flags & NBD_FLAG_ROTATIONAL)
677 queue_flag_clear_unlocked(QUEUE_FLAG_NONROT, lo->disk->queue);
679 queue_flag_set_unlocked(QUEUE_FLAG_NONROT, lo->disk->queue);
684 case NBD_SET_SIZE_BLOCKS:
685 lo->bytesize = ((u64) arg) * lo->blksize;
686 bdev->bd_inode->i_size = lo->bytesize;
687 set_blocksize(bdev, lo->blksize);
688 set_capacity(lo->disk, lo->bytesize >> 9);
692 struct task_struct *thread;
701 mutex_unlock(&lo->tx_lock);
703 thread = kthread_create(nbd_thread, lo, lo->disk->disk_name);
704 if (IS_ERR(thread)) {
705 mutex_lock(&lo->tx_lock);
706 return PTR_ERR(thread);
708 wake_up_process(thread);
709 error = nbd_do_it(lo);
710 kthread_stop(thread);
712 mutex_lock(&lo->tx_lock);
715 sock_shutdown(lo, 0);
719 printk(KERN_WARNING "%s: queue cleared\n", lo->disk->disk_name);
723 bdev->bd_inode->i_size = 0;
724 set_capacity(lo->disk, 0);
726 ioctl_by_bdev(bdev, BLKRRPART, 0);
727 return lo->harderror;
732 * This is for compatibility only. The queue is always cleared
733 * by NBD_DO_IT or NBD_CLEAR_SOCK.
735 BUG_ON(!lo->sock && !list_empty(&lo->queue_head));
738 case NBD_PRINT_DEBUG:
739 printk(KERN_INFO "%s: next = %p, prev = %p, head = %p\n",
740 bdev->bd_disk->disk_name,
741 lo->queue_head.next, lo->queue_head.prev,
748 static int nbd_ioctl(struct block_device *bdev, fmode_t mode,
749 unsigned int cmd, unsigned long arg)
751 struct nbd_device *lo = bdev->bd_disk->private_data;
754 if (!capable(CAP_SYS_ADMIN))
757 BUG_ON(lo->magic != LO_MAGIC);
759 /* Anyone capable of this syscall can do *real bad* things */
760 dprintk(DBG_IOCTL, "%s: nbd_ioctl cmd=%s(0x%x) arg=%lu\n",
761 lo->disk->disk_name, ioctl_cmd_to_ascii(cmd), cmd, arg);
763 mutex_lock(&lo->tx_lock);
764 error = __nbd_ioctl(bdev, lo, cmd, arg);
765 mutex_unlock(&lo->tx_lock);
770 static const struct block_device_operations nbd_fops =
772 .owner = THIS_MODULE,
777 * And here should be modules and kernel interface
778 * (Just smiley confuses emacs :-)
781 static int __init nbd_init(void)
787 BUILD_BUG_ON(sizeof(struct nbd_request) != 28);
790 printk(KERN_CRIT "nbd: max_part must be >= 0\n");
794 nbd_dev = kcalloc(nbds_max, sizeof(*nbd_dev), GFP_KERNEL);
800 part_shift = fls(max_part);
802 for (i = 0; i < nbds_max; i++) {
803 struct gendisk *disk = alloc_disk(1 << part_shift);
806 nbd_dev[i].disk = disk;
808 * The new linux 2.5 block layer implementation requires
809 * every gendisk to have its very own request_queue struct.
810 * These structs are big so we dynamically allocate them.
812 disk->queue = blk_init_queue(do_nbd_request, &nbd_lock);
817 /* In order not to confuse the elevator, say we always
818 * want FLUSH and FUA. We won't send them to the server
819 * unless the relevant flag bit is set
821 blk_queue_flush(disk->queue, REQ_FLUSH | REQ_FUA);
823 * Tell the block layer that we are not a rotational device
825 queue_flag_set_unlocked(QUEUE_FLAG_NONROT, disk->queue);
828 if (register_blkdev(NBD_MAJOR, "nbd")) {
833 printk(KERN_INFO "nbd: registered device at major %d\n", NBD_MAJOR);
834 dprintk(DBG_INIT, "nbd: debugflags=0x%x\n", debugflags);
836 for (i = 0; i < nbds_max; i++) {
837 struct gendisk *disk = nbd_dev[i].disk;
838 nbd_dev[i].file = NULL;
839 nbd_dev[i].magic = LO_MAGIC;
840 nbd_dev[i].flags = 0;
841 INIT_LIST_HEAD(&nbd_dev[i].waiting_queue);
842 spin_lock_init(&nbd_dev[i].queue_lock);
843 INIT_LIST_HEAD(&nbd_dev[i].queue_head);
844 mutex_init(&nbd_dev[i].tx_lock);
845 init_waitqueue_head(&nbd_dev[i].active_wq);
846 init_waitqueue_head(&nbd_dev[i].waiting_wq);
847 nbd_dev[i].blksize = 1024;
848 nbd_dev[i].bytesize = 0;
849 disk->major = NBD_MAJOR;
850 disk->first_minor = i << part_shift;
851 disk->fops = &nbd_fops;
852 disk->private_data = &nbd_dev[i];
853 sprintf(disk->disk_name, "nbd%d", i);
854 set_capacity(disk, 0);
861 blk_cleanup_queue(nbd_dev[i].disk->queue);
862 put_disk(nbd_dev[i].disk);
868 static void __exit nbd_cleanup(void)
871 for (i = 0; i < nbds_max; i++) {
872 struct gendisk *disk = nbd_dev[i].disk;
873 nbd_dev[i].magic = 0;
876 blk_cleanup_queue(disk->queue);
880 unregister_blkdev(NBD_MAJOR, "nbd");
882 printk(KERN_INFO "nbd: unregistered device at major %d\n", NBD_MAJOR);
885 module_init(nbd_init);
886 module_exit(nbd_cleanup);
888 MODULE_DESCRIPTION("Network Block Device");
889 MODULE_LICENSE("GPL");
891 module_param(nbds_max, int, 0444);
892 MODULE_PARM_DESC(nbds_max, "number of network block devices to initialize (default: 16)");
893 module_param(max_part, int, 0444);
894 MODULE_PARM_DESC(max_part, "number of partitions per device (default: 0)");
896 module_param(debugflags, int, 0644);
897 MODULE_PARM_DESC(debugflags, "flags for controlling debug output");