First patch to support FUA, FLUSH and ROTATIONAL
[nbd-module.git] / nbd.c
1 /*
2  * Network block device - make block devices work over TCP
3  *
4  * Note that you can not swap over this thing, yet. Seems to work but
5  * deadlocks sometimes - you can not swap over TCP in general.
6  * 
7  * Copyright 1997-2000, 2008 Pavel Machek <pavel@ucw.cz>
8  * Parts copyright 2001 Steven Whitehouse <steve@chygwyn.com>
9  *
10  * This file is released under GPLv2 or later.
11  *
12  * (part of code stolen from loop.c)
13  */
14
15 #include <linux/major.h>
16
17 #include <linux/blkdev.h>
18 #include <linux/module.h>
19 #include <linux/init.h>
20 #include <linux/sched.h>
21 #include <linux/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 #ifdef NBD_OUTOFTREE
41 #include "nbd.h"
42 #else
43 #include <linux/nbd.h>
44 #endif
45
46 #define LO_MAGIC 0x68797548
47
48 #ifdef NDEBUG
49 #define dprintk(flags, fmt...)
50 #else /* NDEBUG */
51 #define dprintk(flags, fmt...) do { \
52         if (debugflags & (flags)) printk(KERN_DEBUG fmt); \
53 } while (0)
54 #define DBG_IOCTL       0x0004
55 #define DBG_INIT        0x0010
56 #define DBG_EXIT        0x0020
57 #define DBG_BLKDEV      0x0100
58 #define DBG_RX          0x0200
59 #define DBG_TX          0x0400
60 static unsigned int debugflags;
61 #endif /* NDEBUG */
62
63 static unsigned int nbds_max = 16;
64 static struct nbd_device *nbd_dev;
65 static int max_part;
66
67 /*
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
71  *    than NICs anyway.
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
74  *    a single lock.
75  * Thanks go to Jens Axboe and Al Viro for their LKML emails explaining this!
76  */
77 static DEFINE_SPINLOCK(nbd_lock);
78
79 #ifndef NDEBUG
80 static const char *ioctl_cmd_to_ascii(int cmd)
81 {
82         switch (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";
96         }
97         return "unknown";
98 }
99
100 static const char *nbdcmd_to_ascii(int cmd)
101 {
102         switch (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";
107         }
108         return "invalid";
109 }
110 #endif /* NDEBUG */
111
112 static void nbd_end_request(struct request *req)
113 {
114         int error = req->errors ? -EIO : 0;
115         struct request_queue *q = req->q;
116         unsigned long flags;
117
118         dprintk(DBG_BLKDEV, "%s: request %p: %s\n", req->rq_disk->disk_name,
119                         req, error ? "failed" : "done");
120
121         spin_lock_irqsave(q->queue_lock, flags);
122         __blk_end_request_all(req, error);
123         spin_unlock_irqrestore(q->queue_lock, flags);
124 }
125
126 static void sock_shutdown(struct nbd_device *lo, int lock)
127 {
128         /* Forcibly shutdown the socket causing all listeners
129          * to error
130          *
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 */
134         if (lock)
135                 mutex_lock(&lo->tx_lock);
136         if (lo->sock) {
137                 printk(KERN_WARNING "%s: shutting down socket\n",
138                         lo->disk->disk_name);
139                 kernel_sock_shutdown(lo->sock, SHUT_RDWR);
140                 lo->sock = NULL;
141         }
142         if (lock)
143                 mutex_unlock(&lo->tx_lock);
144 }
145
146 static void nbd_xmit_timeout(unsigned long arg)
147 {
148         struct task_struct *task = (struct task_struct *)arg;
149
150         printk(KERN_WARNING "nbd: killing hung xmit (%s, pid: %d)\n",
151                 task->comm, task->pid);
152         force_sig(SIGKILL, task);
153 }
154
155 /*
156  *  Send or receive packet.
157  */
158 static int sock_xmit(struct nbd_device *lo, int send, void *buf, int size,
159                 int msg_flags)
160 {
161         struct socket *sock = lo->sock;
162         int result;
163         struct msghdr msg;
164         struct kvec iov;
165         sigset_t blocked, oldset;
166
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"));
170                 return -EINVAL;
171         }
172
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);
177
178         do {
179                 sock->sk->sk_allocation = GFP_NOIO;
180                 iov.iov_base = buf;
181                 iov.iov_len = size;
182                 msg.msg_name = NULL;
183                 msg.msg_namelen = 0;
184                 msg.msg_control = NULL;
185                 msg.msg_controllen = 0;
186                 msg.msg_flags = msg_flags | MSG_NOSIGNAL;
187
188                 if (send) {
189                         struct timer_list ti;
190
191                         if (lo->xmit_timeout) {
192                                 init_timer(&ti);
193                                 ti.function = nbd_xmit_timeout;
194                                 ti.data = (unsigned long)current;
195                                 ti.expires = jiffies + lo->xmit_timeout;
196                                 add_timer(&ti);
197                         }
198                         result = kernel_sendmsg(sock, &msg, &iov, 1, size);
199                         if (lo->xmit_timeout)
200                                 del_timer_sync(&ti);
201                 } else
202                         result = kernel_recvmsg(sock, &msg, &iov, 1, size, 0);
203
204                 if (signal_pending(current)) {
205                         siginfo_t info;
206                         printk(KERN_WARNING "nbd (pid %d: %s) got signal %d\n",
207                                 task_pid_nr(current), current->comm,
208                                 dequeue_signal_lock(current, &current->blocked, &info));
209                         result = -EINTR;
210                         sock_shutdown(lo, !send);
211                         break;
212                 }
213
214                 if (result <= 0) {
215                         if (result == 0)
216                                 result = -EPIPE; /* short read */
217                         break;
218                 }
219                 size -= result;
220                 buf += result;
221         } while (size > 0);
222
223         sigprocmask(SIG_SETMASK, &oldset, NULL);
224
225         return result;
226 }
227
228 static inline int sock_send_bvec(struct nbd_device *lo, struct bio_vec *bvec,
229                 int flags)
230 {
231         int result;
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);
235         return result;
236 }
237
238 /* always call with the tx_lock held */
239 static int nbd_send_req(struct nbd_device *lo, struct request *req)
240 {
241         int result, flags;
242         struct nbd_request request;
243         unsigned long size = blk_rq_bytes(req);
244
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));
253
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,
258                         blk_rq_bytes(req));
259         result = sock_xmit(lo, 1, &request, sizeof(request),
260                         (nbd_cmd(req) == NBD_CMD_WRITE) ? MSG_MORE : 0);
261         if (result <= 0) {
262                 printk(KERN_ERR "%s: Send control failed (result %d)\n",
263                                 lo->disk->disk_name, result);
264                 goto error_out;
265         }
266
267         if (nbd_cmd(req) == NBD_CMD_WRITE) {
268                 struct req_iterator iter;
269                 struct bio_vec *bvec;
270                 /*
271                  * we are really probing at internals to determine
272                  * whether to set MSG_MORE or not...
273                  */
274                 rq_for_each_segment(bvec, req, iter) {
275                         flags = 0;
276                         if (!rq_iter_last(req, iter))
277                                 flags = MSG_MORE;
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);
281                         if (result <= 0) {
282                                 printk(KERN_ERR "%s: Send data failed (result %d)\n",
283                                                 lo->disk->disk_name, result);
284                                 goto error_out;
285                         }
286                 }
287         }
288         return 0;
289
290 error_out:
291         return -EIO;
292 }
293
294 static struct request *nbd_find_request(struct nbd_device *lo,
295                                         struct request *xreq)
296 {
297         struct request *req, *tmp;
298         int err;
299
300         err = wait_event_interruptible(lo->active_wq, lo->active_req != xreq);
301         if (unlikely(err))
302                 goto out;
303
304         spin_lock(&lo->queue_lock);
305         list_for_each_entry_safe(req, tmp, &lo->queue_head, queuelist) {
306                 if (req != xreq)
307                         continue;
308                 list_del_init(&req->queuelist);
309                 spin_unlock(&lo->queue_lock);
310                 return req;
311         }
312         spin_unlock(&lo->queue_lock);
313
314         err = -ENOENT;
315
316 out:
317         return ERR_PTR(err);
318 }
319
320 static inline int sock_recv_bvec(struct nbd_device *lo, struct bio_vec *bvec)
321 {
322         int result;
323         void *kaddr = kmap(bvec->bv_page);
324         result = sock_xmit(lo, 0, kaddr + bvec->bv_offset, bvec->bv_len,
325                         MSG_WAITALL);
326         kunmap(bvec->bv_page);
327         return result;
328 }
329
330 /* NULL returned = something went wrong, inform userspace */
331 static struct request *nbd_read_stat(struct nbd_device *lo)
332 {
333         int result;
334         struct nbd_reply reply;
335         struct request *req;
336
337         reply.magic = 0;
338         result = sock_xmit(lo, 0, &reply, sizeof(reply), MSG_WAITALL);
339         if (result <= 0) {
340                 printk(KERN_ERR "%s: Receive control failed (result %d)\n",
341                                 lo->disk->disk_name, result);
342                 goto harderror;
343         }
344
345         if (ntohl(reply.magic) != NBD_REPLY_MAGIC) {
346                 printk(KERN_ERR "%s: Wrong magic (0x%lx)\n",
347                                 lo->disk->disk_name,
348                                 (unsigned long)ntohl(reply.magic));
349                 result = -EPROTO;
350                 goto harderror;
351         }
352
353         req = nbd_find_request(lo, *(struct request **)reply.handle);
354         if (IS_ERR(req)) {
355                 result = PTR_ERR(req);
356                 if (result != -ENOENT)
357                         goto harderror;
358
359                 printk(KERN_ERR "%s: Unexpected reply (%p)\n",
360                                 lo->disk->disk_name, reply.handle);
361                 result = -EBADR;
362                 goto harderror;
363         }
364
365         if (ntohl(reply.error)) {
366                 printk(KERN_ERR "%s: Other side returned error (%d)\n",
367                                 lo->disk->disk_name, ntohl(reply.error));
368                 req->errors++;
369                 return req;
370         }
371
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;
377
378                 rq_for_each_segment(bvec, req, iter) {
379                         result = sock_recv_bvec(lo, bvec);
380                         if (result <= 0) {
381                                 printk(KERN_ERR "%s: Receive data failed (result %d)\n",
382                                                 lo->disk->disk_name, result);
383                                 req->errors++;
384                                 return req;
385                         }
386                         dprintk(DBG_RX, "%s: request %p: got %d bytes data\n",
387                                 lo->disk->disk_name, req, bvec->bv_len);
388                 }
389         }
390         return req;
391 harderror:
392         lo->harderror = result;
393         return NULL;
394 }
395
396 static ssize_t pid_show(struct device *dev,
397                         struct device_attribute *attr, char *buf)
398 {
399         struct gendisk *disk = dev_to_disk(dev);
400
401         return sprintf(buf, "%ld\n",
402                 (long) ((struct nbd_device *)disk->private_data)->pid);
403 }
404
405 static struct device_attribute pid_attr = {
406         .attr = { .name = "pid", .mode = S_IRUGO},
407         .show = pid_show,
408 };
409
410 static int nbd_do_it(struct nbd_device *lo)
411 {
412         struct request *req;
413         int ret;
414
415         BUG_ON(lo->magic != LO_MAGIC);
416
417         lo->pid = current->pid;
418         ret = sysfs_create_file(&disk_to_dev(lo->disk)->kobj, &pid_attr.attr);
419         if (ret) {
420                 printk(KERN_ERR "nbd: sysfs_create_file failed!");
421                 lo->pid = 0;
422                 return ret;
423         }
424
425         while ((req = nbd_read_stat(lo)) != NULL)
426                 nbd_end_request(req);
427
428         sysfs_remove_file(&disk_to_dev(lo->disk)->kobj, &pid_attr.attr);
429         lo->pid = 0;
430         return 0;
431 }
432
433 static void nbd_clear_que(struct nbd_device *lo)
434 {
435         struct request *req;
436
437         BUG_ON(lo->magic != LO_MAGIC);
438
439         /*
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.
443          *
444          * As a consequence, we don't need to take the spin lock while
445          * purging the list here.
446          */
447         BUG_ON(lo->sock);
448         BUG_ON(lo->active_req);
449
450         while (!list_empty(&lo->queue_head)) {
451                 req = list_entry(lo->queue_head.next, struct request,
452                                  queuelist);
453                 list_del_init(&req->queuelist);
454                 req->errors++;
455                 nbd_end_request(req);
456         }
457 }
458
459
460 static void nbd_handle_req(struct nbd_device *lo, struct request *req)
461 {
462         if (req->cmd_type != REQ_TYPE_FS)
463                 goto error_out;
464
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);
471                         goto error_out;
472                 }
473         }
474
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.
481                          */
482                         printk(KERN_ERR "%s: nbd passed non-empty flush request\n",
483                                lo->disk->disk_name);
484
485                 } else {
486                         if (lo->flags & NBD_FLAG_SEND_FLUSH)
487                                 nbd_cmd(req) = NBD_CMD_FLUSH;
488                         else {
489                                 /* Ignore flush that we don't need */
490                                 nbd_end_request(req);
491                                 return;
492                         }
493                 }
494         }
495
496         req->errors = 0;
497
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);
503                 goto error_out;
504         }
505
506         lo->active_req = req;
507
508         if (nbd_send_req(lo, req) != 0) {
509                 printk(KERN_ERR "%s: Request send failed\n",
510                                 lo->disk->disk_name);
511                 req->errors++;
512                 nbd_end_request(req);
513         } else {
514                 spin_lock(&lo->queue_lock);
515                 list_add(&req->queuelist, &lo->queue_head);
516                 spin_unlock(&lo->queue_lock);
517         }
518
519         lo->active_req = NULL;
520         mutex_unlock(&lo->tx_lock);
521         wake_up_all(&lo->active_wq);
522
523         return;
524
525 error_out:
526         req->errors++;
527         nbd_end_request(req);
528 }
529
530 static int nbd_thread(void *data)
531 {
532         struct nbd_device *lo = data;
533         struct request *req;
534
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));
541
542                 /* extract request */
543                 if (list_empty(&lo->waiting_queue))
544                         continue;
545
546                 spin_lock_irq(&lo->queue_lock);
547                 req = list_entry(lo->waiting_queue.next, struct request,
548                                  queuelist);
549                 list_del_init(&req->queuelist);
550                 spin_unlock_irq(&lo->queue_lock);
551
552                 /* handle request */
553                 nbd_handle_req(lo, req);
554         }
555         return 0;
556 }
557
558 /*
559  * We always wait for result of write, for now. It would be nice to make it optional
560  * in future
561  * if ((rq_data_dir(req) == WRITE) && (lo->flags & NBD_WRITE_NOCHK))
562  *   { printk( "Warning: Ignoring result!\n"); nbd_end_request( req ); }
563  */
564
565 static void do_nbd_request(struct request_queue *q)
566 {
567         struct request *req;
568         
569         while ((req = blk_fetch_request(q)) != NULL) {
570                 struct nbd_device *lo;
571
572                 spin_unlock_irq(q->queue_lock);
573
574                 dprintk(DBG_BLKDEV, "%s: request %p: dequeued (flags=%x)\n",
575                                 req->rq_disk->disk_name, req, req->cmd_type);
576
577                 lo = req->rq_disk->private_data;
578
579                 BUG_ON(lo->magic != LO_MAGIC);
580
581                 if (unlikely(!lo->sock)) {
582                         printk(KERN_ERR "%s: Attempted send on closed socket\n",
583                                 lo->disk->disk_name);
584                         req->errors++;
585                         nbd_end_request(req);
586                         spin_lock_irq(q->queue_lock);
587                         continue;
588                 }
589
590                 spin_lock_irq(&lo->queue_lock);
591                 list_add_tail(&req->queuelist, &lo->waiting_queue);
592                 spin_unlock_irq(&lo->queue_lock);
593
594                 wake_up(&lo->waiting_wq);
595
596                 spin_lock_irq(q->queue_lock);
597         }
598 }
599
600 /* Must be called with tx_lock held */
601
602 static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *lo,
603                        unsigned int cmd, unsigned long arg)
604 {
605         switch (cmd) {
606         case NBD_DISCONNECT: {
607                 struct request sreq;
608
609                 printk(KERN_INFO "%s: NBD_DISCONNECT\n", lo->disk->disk_name);
610
611                 blk_rq_init(NULL, &sreq);
612                 sreq.cmd_type = REQ_TYPE_SPECIAL;
613                 nbd_cmd(&sreq) = NBD_CMD_DISC;
614                 if (!lo->sock)
615                         return -EINVAL;
616                 nbd_send_req(lo, &sreq);
617                 return 0;
618         }
619  
620         case NBD_CLEAR_SOCK: {
621                 struct file *file;
622
623                 lo->sock = NULL;
624                 file = lo->file;
625                 lo->file = NULL;
626                 nbd_clear_que(lo);
627                 BUG_ON(!list_empty(&lo->queue_head));
628                 if (file)
629                         fput(file);
630                 return 0;
631         }
632
633         case NBD_SET_SOCK: {
634                 struct file *file;
635                 if (lo->file)
636                         return -EBUSY;
637                 file = fget(arg);
638                 if (file) {
639                         struct inode *inode = file->f_path.dentry->d_inode;
640                         if (S_ISSOCK(inode->i_mode)) {
641                                 lo->file = file;
642                                 lo->sock = SOCKET_I(inode);
643                                 if (max_part > 0)
644                                         bdev->bd_invalidated = 1;
645                                 return 0;
646                         } else {
647                                 fput(file);
648                         }
649                 }
650                 return -EINVAL;
651         }
652
653         case NBD_SET_BLKSIZE:
654                 lo->blksize = arg;
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);
659                 return 0;
660
661         case NBD_SET_SIZE:
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);
666                 return 0;
667
668         case NBD_SET_TIMEOUT:
669                 lo->xmit_timeout = arg * HZ;
670                 return 0;
671
672         case NBD_SET_FLAGS:
673                 lo->flags = arg;
674                 if (lo->disk)
675                 {
676                         if (lo->flags & NBD_FLAG_ROTATIONAL)
677                                 queue_flag_clear_unlocked(QUEUE_FLAG_NONROT, lo->disk->queue);
678                         else
679                                 queue_flag_set_unlocked(QUEUE_FLAG_NONROT, lo->disk->queue);
680
681                 }
682                 return 0;
683
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);
689                 return 0;
690
691         case NBD_DO_IT: {
692                 struct task_struct *thread;
693                 struct file *file;
694                 int error;
695
696                 if (lo->pid)
697                         return -EBUSY;
698                 if (!lo->file)
699                         return -EINVAL;
700
701                 mutex_unlock(&lo->tx_lock);
702
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);
707                 }
708                 wake_up_process(thread);
709                 error = nbd_do_it(lo);
710                 kthread_stop(thread);
711
712                 mutex_lock(&lo->tx_lock);
713                 if (error)
714                         return error;
715                 sock_shutdown(lo, 0);
716                 file = lo->file;
717                 lo->file = NULL;
718                 nbd_clear_que(lo);
719                 printk(KERN_WARNING "%s: queue cleared\n", lo->disk->disk_name);
720                 if (file)
721                         fput(file);
722                 lo->bytesize = 0;
723                 bdev->bd_inode->i_size = 0;
724                 set_capacity(lo->disk, 0);
725                 if (max_part > 0)
726                         ioctl_by_bdev(bdev, BLKRRPART, 0);
727                 return lo->harderror;
728         }
729
730         case NBD_CLEAR_QUE:
731                 /*
732                  * This is for compatibility only.  The queue is always cleared
733                  * by NBD_DO_IT or NBD_CLEAR_SOCK.
734                  */
735                 BUG_ON(!lo->sock && !list_empty(&lo->queue_head));
736                 return 0;
737
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,
742                         &lo->queue_head);
743                 return 0;
744         }
745         return -ENOTTY;
746 }
747
748 static int nbd_ioctl(struct block_device *bdev, fmode_t mode,
749                      unsigned int cmd, unsigned long arg)
750 {
751         struct nbd_device *lo = bdev->bd_disk->private_data;
752         int error;
753
754         if (!capable(CAP_SYS_ADMIN))
755                 return -EPERM;
756
757         BUG_ON(lo->magic != LO_MAGIC);
758
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);
762
763         mutex_lock(&lo->tx_lock);
764         error = __nbd_ioctl(bdev, lo, cmd, arg);
765         mutex_unlock(&lo->tx_lock);
766
767         return error;
768 }
769
770 static const struct block_device_operations nbd_fops =
771 {
772         .owner =        THIS_MODULE,
773         .ioctl =        nbd_ioctl,
774 };
775
776 /*
777  * And here should be modules and kernel interface 
778  *  (Just smiley confuses emacs :-)
779  */
780
781 static int __init nbd_init(void)
782 {
783         int err = -ENOMEM;
784         int i;
785         int part_shift;
786
787         BUILD_BUG_ON(sizeof(struct nbd_request) != 28);
788
789         if (max_part < 0) {
790                 printk(KERN_CRIT "nbd: max_part must be >= 0\n");
791                 return -EINVAL;
792         }
793
794         nbd_dev = kcalloc(nbds_max, sizeof(*nbd_dev), GFP_KERNEL);
795         if (!nbd_dev)
796                 return -ENOMEM;
797
798         part_shift = 0;
799         if (max_part > 0)
800                 part_shift = fls(max_part);
801
802         for (i = 0; i < nbds_max; i++) {
803                 struct gendisk *disk = alloc_disk(1 << part_shift);
804                 if (!disk)
805                         goto out;
806                 nbd_dev[i].disk = disk;
807                 /*
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.
811                  */
812                 disk->queue = blk_init_queue(do_nbd_request, &nbd_lock);
813                 if (!disk->queue) {
814                         put_disk(disk);
815                         goto out;
816                 }
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
820                  */
821                 blk_queue_flush(disk->queue, REQ_FLUSH | REQ_FUA);
822                 /*
823                  * Tell the block layer that we are not a rotational device
824                  */
825                 queue_flag_set_unlocked(QUEUE_FLAG_NONROT, disk->queue);
826         }
827
828         if (register_blkdev(NBD_MAJOR, "nbd")) {
829                 err = -EIO;
830                 goto out;
831         }
832
833         printk(KERN_INFO "nbd: registered device at major %d\n", NBD_MAJOR);
834         dprintk(DBG_INIT, "nbd: debugflags=0x%x\n", debugflags);
835
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);
855                 add_disk(disk);
856         }
857
858         return 0;
859 out:
860         while (i--) {
861                 blk_cleanup_queue(nbd_dev[i].disk->queue);
862                 put_disk(nbd_dev[i].disk);
863         }
864         kfree(nbd_dev);
865         return err;
866 }
867
868 static void __exit nbd_cleanup(void)
869 {
870         int i;
871         for (i = 0; i < nbds_max; i++) {
872                 struct gendisk *disk = nbd_dev[i].disk;
873                 nbd_dev[i].magic = 0;
874                 if (disk) {
875                         del_gendisk(disk);
876                         blk_cleanup_queue(disk->queue);
877                         put_disk(disk);
878                 }
879         }
880         unregister_blkdev(NBD_MAJOR, "nbd");
881         kfree(nbd_dev);
882         printk(KERN_INFO "nbd: unregistered device at major %d\n", NBD_MAJOR);
883 }
884
885 module_init(nbd_init);
886 module_exit(nbd_cleanup);
887
888 MODULE_DESCRIPTION("Network Block Device");
889 MODULE_LICENSE("GPL");
890
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)");
895 #ifndef NDEBUG
896 module_param(debugflags, int, 0644);
897 MODULE_PARM_DESC(debugflags, "flags for controlling debug output");
898 #endif