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>
35 #include <linux/types.h>
37 #include <asm/uaccess.h>
38 #include <asm/types.h>
40 #include <linux/nbd.h>
44 int harderror; /* Code of hard error */
45 struct socket * sock; /* If == NULL, device is not ready, yet */
48 spinlock_t queue_lock;
49 struct list_head queue_head; /* Requests waiting result */
50 struct request *active_req;
51 wait_queue_head_t active_wq;
52 struct list_head waiting_queue; /* Requests to be sent */
53 wait_queue_head_t waiting_wq;
59 pid_t pid; /* pid of nbd-client, if attached */
61 int disconnect; /* a disconnect has been requested by user */
63 struct timer_list timeout_timer;
64 struct task_struct *task_recv;
65 struct task_struct *task_send;
68 #define NBD_MAGIC 0x68797548
70 static unsigned int nbds_max = 16;
71 static struct nbd_device *nbd_dev;
75 * Use just one lock (or at most 1 per NIC). Two arguments for this:
76 * 1. Each NIC is essentially a synchronization point for all servers
77 * accessed through that NIC so there's no need to have more locks
79 * 2. More locks lead to more "Dirty cache line bouncing" which will slow
80 * down each lock to the point where they're actually slower than just
82 * Thanks go to Jens Axboe and Al Viro for their LKML emails explaining this!
84 static DEFINE_SPINLOCK(nbd_lock);
86 static inline struct device *nbd_to_dev(struct nbd_device *nbd)
88 return disk_to_dev(nbd->disk);
91 static const char *nbdcmd_to_ascii(int cmd)
94 case NBD_CMD_READ: return "read";
95 case NBD_CMD_WRITE: return "write";
96 case NBD_CMD_DISC: return "disconnect";
97 case NBD_CMD_FLUSH: return "flush";
98 case NBD_CMD_TRIM: return "trim/discard";
103 static void nbd_end_request(struct nbd_device *nbd, struct request *req)
105 int error = req->errors ? -EIO : 0;
106 struct request_queue *q = req->q;
109 dev_dbg(nbd_to_dev(nbd), "request %p: %s\n", req,
110 error ? "failed" : "done");
112 spin_lock_irqsave(q->queue_lock, flags);
113 __blk_end_request_all(req, error);
114 spin_unlock_irqrestore(q->queue_lock, flags);
118 * Forcibly shutdown the socket causing all listeners to error
120 static void sock_shutdown(struct nbd_device *nbd)
125 dev_warn(disk_to_dev(nbd->disk), "shutting down socket\n");
126 kernel_sock_shutdown(nbd->sock, SHUT_RDWR);
128 del_timer_sync(&nbd->timeout_timer);
131 static void nbd_xmit_timeout(unsigned long arg)
133 struct nbd_device *nbd = (struct nbd_device *)arg;
134 struct task_struct *task;
136 if (list_empty(&nbd->queue_head))
141 task = READ_ONCE(nbd->task_recv);
143 force_sig(SIGKILL, task);
145 task = READ_ONCE(nbd->task_send);
147 force_sig(SIGKILL, nbd->task_send);
149 dev_err(nbd_to_dev(nbd), "Connection timed out, killed receiver and sender, shutting down connection\n");
153 * Send or receive packet.
155 static int sock_xmit(struct nbd_device *nbd, int send, void *buf, int size,
158 struct socket *sock = nbd->sock;
162 sigset_t blocked, oldset;
163 unsigned long pflags = current->flags;
165 if (unlikely(!sock)) {
166 dev_err(disk_to_dev(nbd->disk),
167 "Attempted %s on closed socket in sock_xmit\n",
168 (send ? "send" : "recv"));
172 /* Allow interception of SIGKILL only
173 * Don't allow other signals to interrupt the transmission */
174 siginitsetinv(&blocked, sigmask(SIGKILL));
175 sigprocmask(SIG_SETMASK, &blocked, &oldset);
177 current->flags |= PF_MEMALLOC;
179 sock->sk->sk_allocation = GFP_NOIO | __GFP_MEMALLOC;
184 msg.msg_control = NULL;
185 msg.msg_controllen = 0;
186 msg.msg_flags = msg_flags | MSG_NOSIGNAL;
189 result = kernel_sendmsg(sock, &msg, &iov, 1, size);
191 result = kernel_recvmsg(sock, &msg, &iov, 1, size,
196 result = -EPIPE; /* short read */
203 sigprocmask(SIG_SETMASK, &oldset, NULL);
204 tsk_restore_flags(current, pflags, PF_MEMALLOC);
206 if (!send && nbd->xmit_timeout)
207 mod_timer(&nbd->timeout_timer, jiffies + nbd->xmit_timeout);
212 static inline int sock_send_bvec(struct nbd_device *nbd, struct bio_vec *bvec,
216 void *kaddr = kmap(bvec->bv_page);
217 result = sock_xmit(nbd, 1, kaddr + bvec->bv_offset,
218 bvec->bv_len, flags);
219 kunmap(bvec->bv_page);
223 /* always call with the tx_lock held */
224 static int nbd_send_req(struct nbd_device *nbd, struct request *req)
227 struct nbd_request request;
228 unsigned long size = blk_rq_bytes(req);
231 if (req->cmd_type == REQ_TYPE_DRV_PRIV)
233 else if (req->cmd_flags & REQ_DISCARD)
235 else if (req->cmd_flags & REQ_FLUSH)
236 type = NBD_CMD_FLUSH;
237 else if (rq_data_dir(req) == WRITE)
238 type = NBD_CMD_WRITE;
242 memset(&request, 0, sizeof(request));
243 request.magic = htonl(NBD_REQUEST_MAGIC);
244 request.type = htonl(type);
245 if (type != NBD_CMD_FLUSH && type != NBD_CMD_DISC) {
246 request.from = cpu_to_be64((u64)blk_rq_pos(req) << 9);
247 request.len = htonl(size);
249 memcpy(request.handle, &req, sizeof(req));
251 dev_dbg(nbd_to_dev(nbd), "request %p: sending control (%s@%llu,%uB)\n",
252 req, nbdcmd_to_ascii(type),
253 (unsigned long long)blk_rq_pos(req) << 9, blk_rq_bytes(req));
254 result = sock_xmit(nbd, 1, &request, sizeof(request),
255 (type == NBD_CMD_WRITE) ? MSG_MORE : 0);
257 dev_err(disk_to_dev(nbd->disk),
258 "Send control failed (result %d)\n", result);
262 if (type == NBD_CMD_WRITE) {
263 struct req_iterator iter;
266 * we are really probing at internals to determine
267 * whether to set MSG_MORE or not...
269 rq_for_each_segment(bvec, req, iter) {
271 if (!rq_iter_last(bvec, iter))
273 dev_dbg(nbd_to_dev(nbd), "request %p: sending %d bytes data\n",
275 result = sock_send_bvec(nbd, &bvec, flags);
277 dev_err(disk_to_dev(nbd->disk),
278 "Send data failed (result %d)\n",
287 static struct request *nbd_find_request(struct nbd_device *nbd,
288 struct request *xreq)
290 struct request *req, *tmp;
293 err = wait_event_interruptible(nbd->active_wq, nbd->active_req != xreq);
297 spin_lock(&nbd->queue_lock);
298 list_for_each_entry_safe(req, tmp, &nbd->queue_head, queuelist) {
301 list_del_init(&req->queuelist);
302 spin_unlock(&nbd->queue_lock);
305 spin_unlock(&nbd->queue_lock);
307 return ERR_PTR(-ENOENT);
310 static inline int sock_recv_bvec(struct nbd_device *nbd, struct bio_vec *bvec)
313 void *kaddr = kmap(bvec->bv_page);
314 result = sock_xmit(nbd, 0, kaddr + bvec->bv_offset, bvec->bv_len,
316 kunmap(bvec->bv_page);
320 /* NULL returned = something went wrong, inform userspace */
321 static struct request *nbd_read_stat(struct nbd_device *nbd)
324 struct nbd_reply reply;
328 result = sock_xmit(nbd, 0, &reply, sizeof(reply), MSG_WAITALL);
330 dev_err(disk_to_dev(nbd->disk),
331 "Receive control failed (result %d)\n", result);
335 if (ntohl(reply.magic) != NBD_REPLY_MAGIC) {
336 dev_err(disk_to_dev(nbd->disk), "Wrong magic (0x%lx)\n",
337 (unsigned long)ntohl(reply.magic));
342 req = nbd_find_request(nbd, *(struct request **)reply.handle);
344 result = PTR_ERR(req);
345 if (result != -ENOENT)
348 dev_err(disk_to_dev(nbd->disk), "Unexpected reply (%p)\n",
354 if (ntohl(reply.error)) {
355 dev_err(disk_to_dev(nbd->disk), "Other side returned error (%d)\n",
361 dev_dbg(nbd_to_dev(nbd), "request %p: got reply\n", req);
362 if (rq_data_dir(req) != WRITE) {
363 struct req_iterator iter;
366 rq_for_each_segment(bvec, req, iter) {
367 result = sock_recv_bvec(nbd, &bvec);
369 dev_err(disk_to_dev(nbd->disk), "Receive data failed (result %d)\n",
374 dev_dbg(nbd_to_dev(nbd), "request %p: got %d bytes data\n",
380 nbd->harderror = result;
384 static ssize_t pid_show(struct device *dev,
385 struct device_attribute *attr, char *buf)
387 struct gendisk *disk = dev_to_disk(dev);
389 return sprintf(buf, "%ld\n",
390 (long) ((struct nbd_device *)disk->private_data)->pid);
393 static struct device_attribute pid_attr = {
394 .attr = { .name = "pid", .mode = S_IRUGO},
398 static int nbd_do_it(struct nbd_device *nbd)
403 BUG_ON(nbd->magic != NBD_MAGIC);
405 sk_set_memalloc(nbd->sock->sk);
406 nbd->pid = task_pid_nr(current);
407 ret = device_create_file(disk_to_dev(nbd->disk), &pid_attr);
409 dev_err(disk_to_dev(nbd->disk), "device_create_file failed!\n");
414 nbd->task_recv = current;
416 while ((req = nbd_read_stat(nbd)) != NULL)
417 nbd_end_request(nbd, req);
419 nbd->task_recv = NULL;
421 if (signal_pending(current)) {
424 ret = dequeue_signal_lock(current, ¤t->blocked, &info);
425 dev_warn(nbd_to_dev(nbd), "pid %d, %s, got signal %d\n",
426 task_pid_nr(current), current->comm, ret);
427 mutex_lock(&nbd->tx_lock);
429 mutex_unlock(&nbd->tx_lock);
433 device_remove_file(disk_to_dev(nbd->disk), &pid_attr);
438 static void nbd_clear_que(struct nbd_device *nbd)
442 BUG_ON(nbd->magic != NBD_MAGIC);
445 * Because we have set nbd->sock to NULL under the tx_lock, all
446 * modifications to the list must have completed by now. For
447 * the same reason, the active_req must be NULL.
449 * As a consequence, we don't need to take the spin lock while
450 * purging the list here.
453 BUG_ON(nbd->active_req);
455 while (!list_empty(&nbd->queue_head)) {
456 req = list_entry(nbd->queue_head.next, struct request,
458 list_del_init(&req->queuelist);
460 nbd_end_request(nbd, req);
463 while (!list_empty(&nbd->waiting_queue)) {
464 req = list_entry(nbd->waiting_queue.next, struct request,
466 list_del_init(&req->queuelist);
468 nbd_end_request(nbd, req);
473 static void nbd_handle_req(struct nbd_device *nbd, struct request *req)
475 if (req->cmd_type != REQ_TYPE_FS)
478 if (rq_data_dir(req) == WRITE &&
479 (nbd->flags & NBD_FLAG_READ_ONLY)) {
480 dev_err(disk_to_dev(nbd->disk),
481 "Write on read-only\n");
487 mutex_lock(&nbd->tx_lock);
488 if (unlikely(!nbd->sock)) {
489 mutex_unlock(&nbd->tx_lock);
490 dev_err(disk_to_dev(nbd->disk),
491 "Attempted send on closed socket\n");
495 nbd->active_req = req;
497 if (nbd->xmit_timeout && list_empty_careful(&nbd->queue_head))
498 mod_timer(&nbd->timeout_timer, jiffies + nbd->xmit_timeout);
500 if (nbd_send_req(nbd, req) != 0) {
501 dev_err(disk_to_dev(nbd->disk), "Request send failed\n");
503 nbd_end_request(nbd, req);
505 spin_lock(&nbd->queue_lock);
506 list_add_tail(&req->queuelist, &nbd->queue_head);
507 spin_unlock(&nbd->queue_lock);
510 nbd->active_req = NULL;
511 mutex_unlock(&nbd->tx_lock);
512 wake_up_all(&nbd->active_wq);
518 nbd_end_request(nbd, req);
521 static int nbd_thread(void *data)
523 struct nbd_device *nbd = data;
526 nbd->task_send = current;
528 set_user_nice(current, MIN_NICE);
529 while (!kthread_should_stop() || !list_empty(&nbd->waiting_queue)) {
530 /* wait for something to do */
531 wait_event_interruptible(nbd->waiting_wq,
532 kthread_should_stop() ||
533 !list_empty(&nbd->waiting_queue));
535 if (signal_pending(current)) {
539 ret = dequeue_signal_lock(current, ¤t->blocked,
541 dev_warn(nbd_to_dev(nbd), "pid %d, %s, got signal %d\n",
542 task_pid_nr(current), current->comm, ret);
543 mutex_lock(&nbd->tx_lock);
545 mutex_unlock(&nbd->tx_lock);
549 /* extract request */
550 if (list_empty(&nbd->waiting_queue))
553 spin_lock_irq(&nbd->queue_lock);
554 req = list_entry(nbd->waiting_queue.next, struct request,
556 list_del_init(&req->queuelist);
557 spin_unlock_irq(&nbd->queue_lock);
560 nbd_handle_req(nbd, req);
563 nbd->task_send = NULL;
569 * We always wait for result of write, for now. It would be nice to make it optional
571 * if ((rq_data_dir(req) == WRITE) && (nbd->flags & NBD_WRITE_NOCHK))
572 * { printk( "Warning: Ignoring result!\n"); nbd_end_request( req ); }
575 static void do_nbd_request(struct request_queue *q)
576 __releases(q->queue_lock) __acquires(q->queue_lock)
580 while ((req = blk_fetch_request(q)) != NULL) {
581 struct nbd_device *nbd;
583 spin_unlock_irq(q->queue_lock);
585 nbd = req->rq_disk->private_data;
587 BUG_ON(nbd->magic != NBD_MAGIC);
589 dev_dbg(nbd_to_dev(nbd), "request %p: dequeued (flags=%x)\n",
592 if (unlikely(!nbd->sock)) {
593 dev_err(disk_to_dev(nbd->disk),
594 "Attempted send on closed socket\n");
596 nbd_end_request(nbd, req);
597 spin_lock_irq(q->queue_lock);
601 spin_lock_irq(&nbd->queue_lock);
602 list_add_tail(&req->queuelist, &nbd->waiting_queue);
603 spin_unlock_irq(&nbd->queue_lock);
605 wake_up(&nbd->waiting_wq);
607 spin_lock_irq(q->queue_lock);
611 /* Must be called with tx_lock held */
613 static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
614 unsigned int cmd, unsigned long arg)
617 case NBD_DISCONNECT: {
620 dev_info(disk_to_dev(nbd->disk), "NBD_DISCONNECT\n");
624 mutex_unlock(&nbd->tx_lock);
626 mutex_lock(&nbd->tx_lock);
627 blk_rq_init(NULL, &sreq);
628 sreq.cmd_type = REQ_TYPE_DRV_PRIV;
630 /* Check again after getting mutex back. */
636 nbd_send_req(nbd, &sreq);
640 case NBD_CLEAR_SOCK: {
641 struct socket *sock = nbd->sock;
644 BUG_ON(!list_empty(&nbd->queue_head));
645 BUG_ON(!list_empty(&nbd->waiting_queue));
657 sock = sockfd_lookup(arg, &err);
661 bdev->bd_invalidated = 1;
662 nbd->disconnect = 0; /* we're connected now */
668 case NBD_SET_BLKSIZE:
670 nbd->bytesize &= ~(nbd->blksize-1);
671 bdev->bd_inode->i_size = nbd->bytesize;
672 set_blocksize(bdev, nbd->blksize);
673 set_capacity(nbd->disk, nbd->bytesize >> 9);
677 nbd->bytesize = arg & ~(nbd->blksize-1);
678 bdev->bd_inode->i_size = nbd->bytesize;
679 set_blocksize(bdev, nbd->blksize);
680 set_capacity(nbd->disk, nbd->bytesize >> 9);
683 case NBD_SET_TIMEOUT:
684 nbd->xmit_timeout = arg * HZ;
686 mod_timer(&nbd->timeout_timer,
687 jiffies + nbd->xmit_timeout);
689 del_timer_sync(&nbd->timeout_timer);
697 case NBD_SET_SIZE_BLOCKS:
698 nbd->bytesize = ((u64) arg) * nbd->blksize;
699 bdev->bd_inode->i_size = nbd->bytesize;
700 set_blocksize(bdev, nbd->blksize);
701 set_capacity(nbd->disk, nbd->bytesize >> 9);
705 struct task_struct *thread;
714 mutex_unlock(&nbd->tx_lock);
716 if (nbd->flags & NBD_FLAG_READ_ONLY)
717 set_device_ro(bdev, true);
718 if (nbd->flags & NBD_FLAG_SEND_TRIM)
719 queue_flag_set_unlocked(QUEUE_FLAG_DISCARD,
721 if (nbd->flags & NBD_FLAG_SEND_FLUSH)
722 blk_queue_flush(nbd->disk->queue, REQ_FLUSH);
724 blk_queue_flush(nbd->disk->queue, 0);
726 thread = kthread_run(nbd_thread, nbd, "%s",
727 nbd->disk->disk_name);
728 if (IS_ERR(thread)) {
729 mutex_lock(&nbd->tx_lock);
730 return PTR_ERR(thread);
733 error = nbd_do_it(nbd);
734 kthread_stop(thread);
736 mutex_lock(&nbd->tx_lock);
743 dev_warn(disk_to_dev(nbd->disk), "queue cleared\n");
745 queue_flag_clear_unlocked(QUEUE_FLAG_DISCARD, nbd->disk->queue);
746 set_device_ro(bdev, false);
751 bdev->bd_inode->i_size = 0;
752 set_capacity(nbd->disk, 0);
754 blkdev_reread_part(bdev);
755 if (nbd->disconnect) /* user requested, ignore socket errors */
757 return nbd->harderror;
762 * This is for compatibility only. The queue is always cleared
763 * by NBD_DO_IT or NBD_CLEAR_SOCK.
767 case NBD_PRINT_DEBUG:
768 dev_info(disk_to_dev(nbd->disk),
769 "next = %p, prev = %p, head = %p\n",
770 nbd->queue_head.next, nbd->queue_head.prev,
777 static int nbd_ioctl(struct block_device *bdev, fmode_t mode,
778 unsigned int cmd, unsigned long arg)
780 struct nbd_device *nbd = bdev->bd_disk->private_data;
783 if (!capable(CAP_SYS_ADMIN))
786 BUG_ON(nbd->magic != NBD_MAGIC);
788 mutex_lock(&nbd->tx_lock);
789 error = __nbd_ioctl(bdev, nbd, cmd, arg);
790 mutex_unlock(&nbd->tx_lock);
795 static const struct block_device_operations nbd_fops =
797 .owner = THIS_MODULE,
802 * And here should be modules and kernel interface
803 * (Just smiley confuses emacs :-)
806 static int __init nbd_init(void)
812 BUILD_BUG_ON(sizeof(struct nbd_request) != 28);
815 printk(KERN_ERR "nbd: max_part must be >= 0\n");
821 part_shift = fls(max_part);
824 * Adjust max_part according to part_shift as it is exported
825 * to user space so that user can know the max number of
826 * partition kernel should be able to manage.
828 * Note that -1 is required because partition 0 is reserved
829 * for the whole disk.
831 max_part = (1UL << part_shift) - 1;
834 if ((1UL << part_shift) > DISK_MAX_PARTS)
837 if (nbds_max > 1UL << (MINORBITS - part_shift))
840 nbd_dev = kcalloc(nbds_max, sizeof(*nbd_dev), GFP_KERNEL);
844 for (i = 0; i < nbds_max; i++) {
845 struct gendisk *disk = alloc_disk(1 << part_shift);
848 nbd_dev[i].disk = disk;
850 * The new linux 2.5 block layer implementation requires
851 * every gendisk to have its very own request_queue struct.
852 * These structs are big so we dynamically allocate them.
854 disk->queue = blk_init_queue(do_nbd_request, &nbd_lock);
860 * Tell the block layer that we are not a rotational device
862 queue_flag_set_unlocked(QUEUE_FLAG_NONROT, disk->queue);
863 queue_flag_clear_unlocked(QUEUE_FLAG_ADD_RANDOM, disk->queue);
864 disk->queue->limits.discard_granularity = 512;
865 blk_queue_max_discard_sectors(disk->queue, UINT_MAX);
866 disk->queue->limits.discard_zeroes_data = 0;
867 blk_queue_max_hw_sectors(disk->queue, 65536);
868 disk->queue->limits.max_sectors = 256;
871 if (register_blkdev(NBD_MAJOR, "nbd")) {
876 printk(KERN_INFO "nbd: registered device at major %d\n", NBD_MAJOR);
878 for (i = 0; i < nbds_max; i++) {
879 struct gendisk *disk = nbd_dev[i].disk;
880 nbd_dev[i].magic = NBD_MAGIC;
881 INIT_LIST_HEAD(&nbd_dev[i].waiting_queue);
882 spin_lock_init(&nbd_dev[i].queue_lock);
883 INIT_LIST_HEAD(&nbd_dev[i].queue_head);
884 mutex_init(&nbd_dev[i].tx_lock);
885 init_timer(&nbd_dev[i].timeout_timer);
886 nbd_dev[i].timeout_timer.function = nbd_xmit_timeout;
887 nbd_dev[i].timeout_timer.data = (unsigned long)&nbd_dev[i];
888 init_waitqueue_head(&nbd_dev[i].active_wq);
889 init_waitqueue_head(&nbd_dev[i].waiting_wq);
890 nbd_dev[i].blksize = 1024;
891 nbd_dev[i].bytesize = 0;
892 disk->major = NBD_MAJOR;
893 disk->first_minor = i << part_shift;
894 disk->fops = &nbd_fops;
895 disk->private_data = &nbd_dev[i];
896 sprintf(disk->disk_name, "nbd%d", i);
897 set_capacity(disk, 0);
904 blk_cleanup_queue(nbd_dev[i].disk->queue);
905 put_disk(nbd_dev[i].disk);
911 static void __exit nbd_cleanup(void)
914 for (i = 0; i < nbds_max; i++) {
915 struct gendisk *disk = nbd_dev[i].disk;
916 nbd_dev[i].magic = 0;
919 blk_cleanup_queue(disk->queue);
923 unregister_blkdev(NBD_MAJOR, "nbd");
925 printk(KERN_INFO "nbd: unregistered device at major %d\n", NBD_MAJOR);
928 module_init(nbd_init);
929 module_exit(nbd_cleanup);
931 MODULE_DESCRIPTION("Network Block Device");
932 MODULE_LICENSE("GPL");
934 module_param(nbds_max, int, 0444);
935 MODULE_PARM_DESC(nbds_max, "number of network block devices to initialize (default: 16)");
936 module_param(max_part, int, 0444);
937 MODULE_PARM_DESC(max_part, "number of partitions per device (default: 0)");