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 struct socket * sock; /* If == NULL, device is not ready, yet */
47 spinlock_t queue_lock;
48 struct list_head queue_head; /* Requests waiting result */
49 struct request *active_req;
50 wait_queue_head_t active_wq;
51 struct list_head waiting_queue; /* Requests to be sent */
52 wait_queue_head_t waiting_wq;
58 pid_t pid; /* pid of nbd-client, if attached */
60 int disconnect; /* a disconnect has been requested by user */
62 struct timer_list timeout_timer;
63 struct task_struct *task_recv;
64 struct task_struct *task_send;
67 #define NBD_MAGIC 0x68797548
69 static unsigned int nbds_max = 16;
70 static struct nbd_device *nbd_dev;
74 * Use just one lock (or at most 1 per NIC). Two arguments for this:
75 * 1. Each NIC is essentially a synchronization point for all servers
76 * accessed through that NIC so there's no need to have more locks
78 * 2. More locks lead to more "Dirty cache line bouncing" which will slow
79 * down each lock to the point where they're actually slower than just
81 * Thanks go to Jens Axboe and Al Viro for their LKML emails explaining this!
83 static DEFINE_SPINLOCK(nbd_lock);
85 static inline struct device *nbd_to_dev(struct nbd_device *nbd)
87 return disk_to_dev(nbd->disk);
90 static const char *nbdcmd_to_ascii(int cmd)
93 case NBD_CMD_READ: return "read";
94 case NBD_CMD_WRITE: return "write";
95 case NBD_CMD_DISC: return "disconnect";
96 case NBD_CMD_FLUSH: return "flush";
97 case NBD_CMD_TRIM: return "trim/discard";
102 static void nbd_end_request(struct nbd_device *nbd, struct request *req)
104 int error = req->errors ? -EIO : 0;
105 struct request_queue *q = req->q;
108 dev_dbg(nbd_to_dev(nbd), "request %p: %s\n", req,
109 error ? "failed" : "done");
111 spin_lock_irqsave(q->queue_lock, flags);
112 __blk_end_request_all(req, error);
113 spin_unlock_irqrestore(q->queue_lock, flags);
117 * Forcibly shutdown the socket causing all listeners to error
119 static void sock_shutdown(struct nbd_device *nbd)
124 dev_warn(disk_to_dev(nbd->disk), "shutting down socket\n");
125 kernel_sock_shutdown(nbd->sock, SHUT_RDWR);
127 del_timer_sync(&nbd->timeout_timer);
130 static void nbd_xmit_timeout(unsigned long arg)
132 struct nbd_device *nbd = (struct nbd_device *)arg;
133 struct task_struct *task;
135 if (list_empty(&nbd->queue_head))
140 task = READ_ONCE(nbd->task_recv);
142 force_sig(SIGKILL, task);
144 task = READ_ONCE(nbd->task_send);
146 force_sig(SIGKILL, nbd->task_send);
148 dev_err(nbd_to_dev(nbd), "Connection timed out, killed receiver and sender, shutting down connection\n");
152 * Send or receive packet.
154 static int sock_xmit(struct nbd_device *nbd, int send, void *buf, int size,
157 struct socket *sock = nbd->sock;
161 sigset_t blocked, oldset;
162 unsigned long pflags = current->flags;
164 if (unlikely(!sock)) {
165 dev_err(disk_to_dev(nbd->disk),
166 "Attempted %s on closed socket in sock_xmit\n",
167 (send ? "send" : "recv"));
171 /* Allow interception of SIGKILL only
172 * Don't allow other signals to interrupt the transmission */
173 siginitsetinv(&blocked, sigmask(SIGKILL));
174 sigprocmask(SIG_SETMASK, &blocked, &oldset);
176 current->flags |= PF_MEMALLOC;
178 sock->sk->sk_allocation = GFP_NOIO | __GFP_MEMALLOC;
183 msg.msg_control = NULL;
184 msg.msg_controllen = 0;
185 msg.msg_flags = msg_flags | MSG_NOSIGNAL;
188 result = kernel_sendmsg(sock, &msg, &iov, 1, size);
190 result = kernel_recvmsg(sock, &msg, &iov, 1, size,
195 result = -EPIPE; /* short read */
202 sigprocmask(SIG_SETMASK, &oldset, NULL);
203 tsk_restore_flags(current, pflags, PF_MEMALLOC);
205 if (!send && nbd->xmit_timeout)
206 mod_timer(&nbd->timeout_timer, jiffies + nbd->xmit_timeout);
211 static inline int sock_send_bvec(struct nbd_device *nbd, struct bio_vec *bvec,
215 void *kaddr = kmap(bvec->bv_page);
216 result = sock_xmit(nbd, 1, kaddr + bvec->bv_offset,
217 bvec->bv_len, flags);
218 kunmap(bvec->bv_page);
222 /* always call with the tx_lock held */
223 static int nbd_send_req(struct nbd_device *nbd, struct request *req)
226 struct nbd_request request;
227 unsigned long size = blk_rq_bytes(req);
230 if (req->cmd_type == REQ_TYPE_DRV_PRIV)
232 else if (req->cmd_flags & REQ_DISCARD)
234 else if (req->cmd_flags & REQ_FLUSH)
235 type = NBD_CMD_FLUSH;
236 else if (rq_data_dir(req) == WRITE)
237 type = NBD_CMD_WRITE;
241 memset(&request, 0, sizeof(request));
242 request.magic = htonl(NBD_REQUEST_MAGIC);
243 request.type = htonl(type);
244 if (type != NBD_CMD_FLUSH && type != NBD_CMD_DISC) {
245 request.from = cpu_to_be64((u64)blk_rq_pos(req) << 9);
246 request.len = htonl(size);
248 memcpy(request.handle, &req, sizeof(req));
250 dev_dbg(nbd_to_dev(nbd), "request %p: sending control (%s@%llu,%uB)\n",
251 req, nbdcmd_to_ascii(type),
252 (unsigned long long)blk_rq_pos(req) << 9, blk_rq_bytes(req));
253 result = sock_xmit(nbd, 1, &request, sizeof(request),
254 (type == NBD_CMD_WRITE) ? MSG_MORE : 0);
256 dev_err(disk_to_dev(nbd->disk),
257 "Send control failed (result %d)\n", result);
261 if (type == NBD_CMD_WRITE) {
262 struct req_iterator iter;
265 * we are really probing at internals to determine
266 * whether to set MSG_MORE or not...
268 rq_for_each_segment(bvec, req, iter) {
270 if (!rq_iter_last(bvec, iter))
272 dev_dbg(nbd_to_dev(nbd), "request %p: sending %d bytes data\n",
274 result = sock_send_bvec(nbd, &bvec, flags);
276 dev_err(disk_to_dev(nbd->disk),
277 "Send data failed (result %d)\n",
286 static struct request *nbd_find_request(struct nbd_device *nbd,
287 struct request *xreq)
289 struct request *req, *tmp;
292 err = wait_event_interruptible(nbd->active_wq, nbd->active_req != xreq);
296 spin_lock(&nbd->queue_lock);
297 list_for_each_entry_safe(req, tmp, &nbd->queue_head, queuelist) {
300 list_del_init(&req->queuelist);
301 spin_unlock(&nbd->queue_lock);
304 spin_unlock(&nbd->queue_lock);
306 return ERR_PTR(-ENOENT);
309 static inline int sock_recv_bvec(struct nbd_device *nbd, struct bio_vec *bvec)
312 void *kaddr = kmap(bvec->bv_page);
313 result = sock_xmit(nbd, 0, kaddr + bvec->bv_offset, bvec->bv_len,
315 kunmap(bvec->bv_page);
319 /* NULL returned = something went wrong, inform userspace */
320 static struct request *nbd_read_stat(struct nbd_device *nbd)
323 struct nbd_reply reply;
327 result = sock_xmit(nbd, 0, &reply, sizeof(reply), MSG_WAITALL);
329 dev_err(disk_to_dev(nbd->disk),
330 "Receive control failed (result %d)\n", result);
331 return ERR_PTR(result);
334 if (ntohl(reply.magic) != NBD_REPLY_MAGIC) {
335 dev_err(disk_to_dev(nbd->disk), "Wrong magic (0x%lx)\n",
336 (unsigned long)ntohl(reply.magic));
337 return ERR_PTR(-EPROTO);
340 req = nbd_find_request(nbd, *(struct request **)reply.handle);
342 result = PTR_ERR(req);
343 if (result != -ENOENT)
344 return ERR_PTR(result);
346 dev_err(disk_to_dev(nbd->disk), "Unexpected reply (%p)\n",
348 return ERR_PTR(-EBADR);
351 if (ntohl(reply.error)) {
352 dev_err(disk_to_dev(nbd->disk), "Other side returned error (%d)\n",
358 dev_dbg(nbd_to_dev(nbd), "request %p: got reply\n", req);
359 if (rq_data_dir(req) != WRITE) {
360 struct req_iterator iter;
363 rq_for_each_segment(bvec, req, iter) {
364 result = sock_recv_bvec(nbd, &bvec);
366 dev_err(disk_to_dev(nbd->disk), "Receive data failed (result %d)\n",
371 dev_dbg(nbd_to_dev(nbd), "request %p: got %d bytes data\n",
378 static ssize_t pid_show(struct device *dev,
379 struct device_attribute *attr, char *buf)
381 struct gendisk *disk = dev_to_disk(dev);
383 return sprintf(buf, "%ld\n",
384 (long) ((struct nbd_device *)disk->private_data)->pid);
387 static struct device_attribute pid_attr = {
388 .attr = { .name = "pid", .mode = S_IRUGO},
392 static int nbd_do_it(struct nbd_device *nbd)
397 BUG_ON(nbd->magic != NBD_MAGIC);
399 sk_set_memalloc(nbd->sock->sk);
400 nbd->pid = task_pid_nr(current);
401 ret = device_create_file(disk_to_dev(nbd->disk), &pid_attr);
403 dev_err(disk_to_dev(nbd->disk), "device_create_file failed!\n");
408 nbd->task_recv = current;
411 req = nbd_read_stat(nbd);
417 nbd_end_request(nbd, req);
420 nbd->task_recv = NULL;
422 if (signal_pending(current)) {
425 ret = dequeue_signal_lock(current, ¤t->blocked, &info);
426 dev_warn(nbd_to_dev(nbd), "pid %d, %s, got signal %d\n",
427 task_pid_nr(current), current->comm, ret);
428 mutex_lock(&nbd->tx_lock);
430 mutex_unlock(&nbd->tx_lock);
434 device_remove_file(disk_to_dev(nbd->disk), &pid_attr);
439 static void nbd_clear_que(struct nbd_device *nbd)
443 BUG_ON(nbd->magic != NBD_MAGIC);
446 * Because we have set nbd->sock to NULL under the tx_lock, all
447 * modifications to the list must have completed by now. For
448 * the same reason, the active_req must be NULL.
450 * As a consequence, we don't need to take the spin lock while
451 * purging the list here.
454 BUG_ON(nbd->active_req);
456 while (!list_empty(&nbd->queue_head)) {
457 req = list_entry(nbd->queue_head.next, struct request,
459 list_del_init(&req->queuelist);
461 nbd_end_request(nbd, req);
464 while (!list_empty(&nbd->waiting_queue)) {
465 req = list_entry(nbd->waiting_queue.next, struct request,
467 list_del_init(&req->queuelist);
469 nbd_end_request(nbd, req);
471 dev_dbg(disk_to_dev(nbd->disk), "queue cleared\n");
475 static void nbd_handle_req(struct nbd_device *nbd, struct request *req)
477 if (req->cmd_type != REQ_TYPE_FS)
480 if (rq_data_dir(req) == WRITE &&
481 (nbd->flags & NBD_FLAG_READ_ONLY)) {
482 dev_err(disk_to_dev(nbd->disk),
483 "Write on read-only\n");
489 mutex_lock(&nbd->tx_lock);
490 if (unlikely(!nbd->sock)) {
491 mutex_unlock(&nbd->tx_lock);
492 dev_err(disk_to_dev(nbd->disk),
493 "Attempted send on closed socket\n");
497 nbd->active_req = req;
499 if (nbd->xmit_timeout && list_empty_careful(&nbd->queue_head))
500 mod_timer(&nbd->timeout_timer, jiffies + nbd->xmit_timeout);
502 if (nbd_send_req(nbd, req) != 0) {
503 dev_err(disk_to_dev(nbd->disk), "Request send failed\n");
505 nbd_end_request(nbd, req);
507 spin_lock(&nbd->queue_lock);
508 list_add_tail(&req->queuelist, &nbd->queue_head);
509 spin_unlock(&nbd->queue_lock);
512 nbd->active_req = NULL;
513 mutex_unlock(&nbd->tx_lock);
514 wake_up_all(&nbd->active_wq);
520 nbd_end_request(nbd, req);
523 static int nbd_thread(void *data)
525 struct nbd_device *nbd = data;
528 nbd->task_send = current;
530 set_user_nice(current, MIN_NICE);
531 while (!kthread_should_stop() || !list_empty(&nbd->waiting_queue)) {
532 /* wait for something to do */
533 wait_event_interruptible(nbd->waiting_wq,
534 kthread_should_stop() ||
535 !list_empty(&nbd->waiting_queue));
537 if (signal_pending(current)) {
541 ret = dequeue_signal_lock(current, ¤t->blocked,
543 dev_warn(nbd_to_dev(nbd), "pid %d, %s, got signal %d\n",
544 task_pid_nr(current), current->comm, ret);
545 mutex_lock(&nbd->tx_lock);
547 mutex_unlock(&nbd->tx_lock);
551 /* extract request */
552 if (list_empty(&nbd->waiting_queue))
555 spin_lock_irq(&nbd->queue_lock);
556 req = list_entry(nbd->waiting_queue.next, struct request,
558 list_del_init(&req->queuelist);
559 spin_unlock_irq(&nbd->queue_lock);
562 nbd_handle_req(nbd, req);
565 nbd->task_send = NULL;
571 * We always wait for result of write, for now. It would be nice to make it optional
573 * if ((rq_data_dir(req) == WRITE) && (nbd->flags & NBD_WRITE_NOCHK))
574 * { printk( "Warning: Ignoring result!\n"); nbd_end_request( req ); }
577 static void do_nbd_request(struct request_queue *q)
578 __releases(q->queue_lock) __acquires(q->queue_lock)
582 while ((req = blk_fetch_request(q)) != NULL) {
583 struct nbd_device *nbd;
585 spin_unlock_irq(q->queue_lock);
587 nbd = req->rq_disk->private_data;
589 BUG_ON(nbd->magic != NBD_MAGIC);
591 dev_dbg(nbd_to_dev(nbd), "request %p: dequeued (flags=%x)\n",
594 if (unlikely(!nbd->sock)) {
595 dev_err(disk_to_dev(nbd->disk),
596 "Attempted send on closed socket\n");
598 nbd_end_request(nbd, req);
599 spin_lock_irq(q->queue_lock);
603 spin_lock_irq(&nbd->queue_lock);
604 list_add_tail(&req->queuelist, &nbd->waiting_queue);
605 spin_unlock_irq(&nbd->queue_lock);
607 wake_up(&nbd->waiting_wq);
609 spin_lock_irq(q->queue_lock);
613 /* Must be called with tx_lock held */
615 static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
616 unsigned int cmd, unsigned long arg)
619 case NBD_DISCONNECT: {
622 dev_info(disk_to_dev(nbd->disk), "NBD_DISCONNECT\n");
626 mutex_unlock(&nbd->tx_lock);
628 mutex_lock(&nbd->tx_lock);
629 blk_rq_init(NULL, &sreq);
630 sreq.cmd_type = REQ_TYPE_DRV_PRIV;
632 /* Check again after getting mutex back. */
638 nbd_send_req(nbd, &sreq);
642 case NBD_CLEAR_SOCK: {
643 struct socket *sock = nbd->sock;
646 BUG_ON(!list_empty(&nbd->queue_head));
647 BUG_ON(!list_empty(&nbd->waiting_queue));
659 sock = sockfd_lookup(arg, &err);
663 bdev->bd_invalidated = 1;
664 nbd->disconnect = 0; /* we're connected now */
670 case NBD_SET_BLKSIZE:
672 nbd->bytesize &= ~(nbd->blksize-1);
673 bdev->bd_inode->i_size = nbd->bytesize;
674 set_blocksize(bdev, nbd->blksize);
675 set_capacity(nbd->disk, nbd->bytesize >> 9);
679 nbd->bytesize = arg & ~(nbd->blksize-1);
680 bdev->bd_inode->i_size = nbd->bytesize;
681 set_blocksize(bdev, nbd->blksize);
682 set_capacity(nbd->disk, nbd->bytesize >> 9);
685 case NBD_SET_TIMEOUT:
686 nbd->xmit_timeout = arg * HZ;
688 mod_timer(&nbd->timeout_timer,
689 jiffies + nbd->xmit_timeout);
691 del_timer_sync(&nbd->timeout_timer);
699 case NBD_SET_SIZE_BLOCKS:
700 nbd->bytesize = ((u64) arg) * nbd->blksize;
701 bdev->bd_inode->i_size = nbd->bytesize;
702 set_blocksize(bdev, nbd->blksize);
703 set_capacity(nbd->disk, nbd->bytesize >> 9);
707 struct task_struct *thread;
716 mutex_unlock(&nbd->tx_lock);
718 if (nbd->flags & NBD_FLAG_READ_ONLY)
719 set_device_ro(bdev, true);
720 if (nbd->flags & NBD_FLAG_SEND_TRIM)
721 queue_flag_set_unlocked(QUEUE_FLAG_DISCARD,
723 if (nbd->flags & NBD_FLAG_SEND_FLUSH)
724 blk_queue_flush(nbd->disk->queue, REQ_FLUSH);
726 blk_queue_flush(nbd->disk->queue, 0);
728 thread = kthread_run(nbd_thread, nbd, "%s",
729 nbd->disk->disk_name);
730 if (IS_ERR(thread)) {
731 mutex_lock(&nbd->tx_lock);
732 return PTR_ERR(thread);
735 error = nbd_do_it(nbd);
736 kthread_stop(thread);
738 mutex_lock(&nbd->tx_lock);
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 */
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)");