Out of tree builds use local include file
[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 BLKROSET: return "set-read-only";
93         case BLKFLSBUF: return "flush-buffer-cache";
94         }
95         return "unknown";
96 }
97
98 static const char *nbdcmd_to_ascii(int cmd)
99 {
100         switch (cmd) {
101         case  NBD_CMD_READ: return "read";
102         case NBD_CMD_WRITE: return "write";
103         case  NBD_CMD_DISC: return "disconnect";
104         }
105         return "invalid";
106 }
107 #endif /* NDEBUG */
108
109 static void nbd_end_request(struct request *req)
110 {
111         int error = req->errors ? -EIO : 0;
112         struct request_queue *q = req->q;
113         unsigned long flags;
114
115         dprintk(DBG_BLKDEV, "%s: request %p: %s\n", req->rq_disk->disk_name,
116                         req, error ? "failed" : "done");
117
118         spin_lock_irqsave(q->queue_lock, flags);
119         __blk_end_request_all(req, error);
120         spin_unlock_irqrestore(q->queue_lock, flags);
121 }
122
123 static void sock_shutdown(struct nbd_device *lo, int lock)
124 {
125         /* Forcibly shutdown the socket causing all listeners
126          * to error
127          *
128          * FIXME: This code is duplicated from sys_shutdown, but
129          * there should be a more generic interface rather than
130          * calling socket ops directly here */
131         if (lock)
132                 mutex_lock(&lo->tx_lock);
133         if (lo->sock) {
134                 printk(KERN_WARNING "%s: shutting down socket\n",
135                         lo->disk->disk_name);
136                 kernel_sock_shutdown(lo->sock, SHUT_RDWR);
137                 lo->sock = NULL;
138         }
139         if (lock)
140                 mutex_unlock(&lo->tx_lock);
141 }
142
143 static void nbd_xmit_timeout(unsigned long arg)
144 {
145         struct task_struct *task = (struct task_struct *)arg;
146
147         printk(KERN_WARNING "nbd: killing hung xmit (%s, pid: %d)\n",
148                 task->comm, task->pid);
149         force_sig(SIGKILL, task);
150 }
151
152 /*
153  *  Send or receive packet.
154  */
155 static int sock_xmit(struct nbd_device *lo, int send, void *buf, int size,
156                 int msg_flags)
157 {
158         struct socket *sock = lo->sock;
159         int result;
160         struct msghdr msg;
161         struct kvec iov;
162         sigset_t blocked, oldset;
163
164         if (unlikely(!sock)) {
165                 printk(KERN_ERR "%s: Attempted %s on closed socket in sock_xmit\n",
166                        lo->disk->disk_name, (send ? "send" : "recv"));
167                 return -EINVAL;
168         }
169
170         /* Allow interception of SIGKILL only
171          * Don't allow other signals to interrupt the transmission */
172         siginitsetinv(&blocked, sigmask(SIGKILL));
173         sigprocmask(SIG_SETMASK, &blocked, &oldset);
174
175         do {
176                 sock->sk->sk_allocation = GFP_NOIO;
177                 iov.iov_base = buf;
178                 iov.iov_len = size;
179                 msg.msg_name = NULL;
180                 msg.msg_namelen = 0;
181                 msg.msg_control = NULL;
182                 msg.msg_controllen = 0;
183                 msg.msg_flags = msg_flags | MSG_NOSIGNAL;
184
185                 if (send) {
186                         struct timer_list ti;
187
188                         if (lo->xmit_timeout) {
189                                 init_timer(&ti);
190                                 ti.function = nbd_xmit_timeout;
191                                 ti.data = (unsigned long)current;
192                                 ti.expires = jiffies + lo->xmit_timeout;
193                                 add_timer(&ti);
194                         }
195                         result = kernel_sendmsg(sock, &msg, &iov, 1, size);
196                         if (lo->xmit_timeout)
197                                 del_timer_sync(&ti);
198                 } else
199                         result = kernel_recvmsg(sock, &msg, &iov, 1, size, 0);
200
201                 if (signal_pending(current)) {
202                         siginfo_t info;
203                         printk(KERN_WARNING "nbd (pid %d: %s) got signal %d\n",
204                                 task_pid_nr(current), current->comm,
205                                 dequeue_signal_lock(current, &current->blocked, &info));
206                         result = -EINTR;
207                         sock_shutdown(lo, !send);
208                         break;
209                 }
210
211                 if (result <= 0) {
212                         if (result == 0)
213                                 result = -EPIPE; /* short read */
214                         break;
215                 }
216                 size -= result;
217                 buf += result;
218         } while (size > 0);
219
220         sigprocmask(SIG_SETMASK, &oldset, NULL);
221
222         return result;
223 }
224
225 static inline int sock_send_bvec(struct nbd_device *lo, struct bio_vec *bvec,
226                 int flags)
227 {
228         int result;
229         void *kaddr = kmap(bvec->bv_page);
230         result = sock_xmit(lo, 1, kaddr + bvec->bv_offset, bvec->bv_len, flags);
231         kunmap(bvec->bv_page);
232         return result;
233 }
234
235 /* always call with the tx_lock held */
236 static int nbd_send_req(struct nbd_device *lo, struct request *req)
237 {
238         int result, flags;
239         struct nbd_request request;
240         unsigned long size = blk_rq_bytes(req);
241
242         request.magic = htonl(NBD_REQUEST_MAGIC);
243         request.type = htonl(nbd_cmd(req));
244         request.from = cpu_to_be64((u64)blk_rq_pos(req) << 9);
245         request.len = htonl(size);
246         memcpy(request.handle, &req, sizeof(req));
247
248         dprintk(DBG_TX, "%s: request %p: sending control (%s@%llu,%uB)\n",
249                         lo->disk->disk_name, req,
250                         nbdcmd_to_ascii(nbd_cmd(req)),
251                         (unsigned long long)blk_rq_pos(req) << 9,
252                         blk_rq_bytes(req));
253         result = sock_xmit(lo, 1, &request, sizeof(request),
254                         (nbd_cmd(req) == NBD_CMD_WRITE) ? MSG_MORE : 0);
255         if (result <= 0) {
256                 printk(KERN_ERR "%s: Send control failed (result %d)\n",
257                                 lo->disk->disk_name, result);
258                 goto error_out;
259         }
260
261         if (nbd_cmd(req) == NBD_CMD_WRITE) {
262                 struct req_iterator iter;
263                 struct bio_vec *bvec;
264                 /*
265                  * we are really probing at internals to determine
266                  * whether to set MSG_MORE or not...
267                  */
268                 rq_for_each_segment(bvec, req, iter) {
269                         flags = 0;
270                         if (!rq_iter_last(req, iter))
271                                 flags = MSG_MORE;
272                         dprintk(DBG_TX, "%s: request %p: sending %d bytes data\n",
273                                         lo->disk->disk_name, req, bvec->bv_len);
274                         result = sock_send_bvec(lo, bvec, flags);
275                         if (result <= 0) {
276                                 printk(KERN_ERR "%s: Send data failed (result %d)\n",
277                                                 lo->disk->disk_name, result);
278                                 goto error_out;
279                         }
280                 }
281         }
282         return 0;
283
284 error_out:
285         return -EIO;
286 }
287
288 static struct request *nbd_find_request(struct nbd_device *lo,
289                                         struct request *xreq)
290 {
291         struct request *req, *tmp;
292         int err;
293
294         err = wait_event_interruptible(lo->active_wq, lo->active_req != xreq);
295         if (unlikely(err))
296                 goto out;
297
298         spin_lock(&lo->queue_lock);
299         list_for_each_entry_safe(req, tmp, &lo->queue_head, queuelist) {
300                 if (req != xreq)
301                         continue;
302                 list_del_init(&req->queuelist);
303                 spin_unlock(&lo->queue_lock);
304                 return req;
305         }
306         spin_unlock(&lo->queue_lock);
307
308         err = -ENOENT;
309
310 out:
311         return ERR_PTR(err);
312 }
313
314 static inline int sock_recv_bvec(struct nbd_device *lo, struct bio_vec *bvec)
315 {
316         int result;
317         void *kaddr = kmap(bvec->bv_page);
318         result = sock_xmit(lo, 0, kaddr + bvec->bv_offset, bvec->bv_len,
319                         MSG_WAITALL);
320         kunmap(bvec->bv_page);
321         return result;
322 }
323
324 /* NULL returned = something went wrong, inform userspace */
325 static struct request *nbd_read_stat(struct nbd_device *lo)
326 {
327         int result;
328         struct nbd_reply reply;
329         struct request *req;
330
331         reply.magic = 0;
332         result = sock_xmit(lo, 0, &reply, sizeof(reply), MSG_WAITALL);
333         if (result <= 0) {
334                 printk(KERN_ERR "%s: Receive control failed (result %d)\n",
335                                 lo->disk->disk_name, result);
336                 goto harderror;
337         }
338
339         if (ntohl(reply.magic) != NBD_REPLY_MAGIC) {
340                 printk(KERN_ERR "%s: Wrong magic (0x%lx)\n",
341                                 lo->disk->disk_name,
342                                 (unsigned long)ntohl(reply.magic));
343                 result = -EPROTO;
344                 goto harderror;
345         }
346
347         req = nbd_find_request(lo, *(struct request **)reply.handle);
348         if (IS_ERR(req)) {
349                 result = PTR_ERR(req);
350                 if (result != -ENOENT)
351                         goto harderror;
352
353                 printk(KERN_ERR "%s: Unexpected reply (%p)\n",
354                                 lo->disk->disk_name, reply.handle);
355                 result = -EBADR;
356                 goto harderror;
357         }
358
359         if (ntohl(reply.error)) {
360                 printk(KERN_ERR "%s: Other side returned error (%d)\n",
361                                 lo->disk->disk_name, ntohl(reply.error));
362                 req->errors++;
363                 return req;
364         }
365
366         dprintk(DBG_RX, "%s: request %p: got reply\n",
367                         lo->disk->disk_name, req);
368         if (nbd_cmd(req) == NBD_CMD_READ) {
369                 struct req_iterator iter;
370                 struct bio_vec *bvec;
371
372                 rq_for_each_segment(bvec, req, iter) {
373                         result = sock_recv_bvec(lo, bvec);
374                         if (result <= 0) {
375                                 printk(KERN_ERR "%s: Receive data failed (result %d)\n",
376                                                 lo->disk->disk_name, result);
377                                 req->errors++;
378                                 return req;
379                         }
380                         dprintk(DBG_RX, "%s: request %p: got %d bytes data\n",
381                                 lo->disk->disk_name, req, bvec->bv_len);
382                 }
383         }
384         return req;
385 harderror:
386         lo->harderror = result;
387         return NULL;
388 }
389
390 static ssize_t pid_show(struct device *dev,
391                         struct device_attribute *attr, char *buf)
392 {
393         struct gendisk *disk = dev_to_disk(dev);
394
395         return sprintf(buf, "%ld\n",
396                 (long) ((struct nbd_device *)disk->private_data)->pid);
397 }
398
399 static struct device_attribute pid_attr = {
400         .attr = { .name = "pid", .mode = S_IRUGO},
401         .show = pid_show,
402 };
403
404 static int nbd_do_it(struct nbd_device *lo)
405 {
406         struct request *req;
407         int ret;
408
409         BUG_ON(lo->magic != LO_MAGIC);
410
411         lo->pid = current->pid;
412         ret = sysfs_create_file(&disk_to_dev(lo->disk)->kobj, &pid_attr.attr);
413         if (ret) {
414                 printk(KERN_ERR "nbd: sysfs_create_file failed!");
415                 lo->pid = 0;
416                 return ret;
417         }
418
419         while ((req = nbd_read_stat(lo)) != NULL)
420                 nbd_end_request(req);
421
422         sysfs_remove_file(&disk_to_dev(lo->disk)->kobj, &pid_attr.attr);
423         lo->pid = 0;
424         return 0;
425 }
426
427 static void nbd_clear_que(struct nbd_device *lo)
428 {
429         struct request *req;
430
431         BUG_ON(lo->magic != LO_MAGIC);
432
433         /*
434          * Because we have set lo->sock to NULL under the tx_lock, all
435          * modifications to the list must have completed by now.  For
436          * the same reason, the active_req must be NULL.
437          *
438          * As a consequence, we don't need to take the spin lock while
439          * purging the list here.
440          */
441         BUG_ON(lo->sock);
442         BUG_ON(lo->active_req);
443
444         while (!list_empty(&lo->queue_head)) {
445                 req = list_entry(lo->queue_head.next, struct request,
446                                  queuelist);
447                 list_del_init(&req->queuelist);
448                 req->errors++;
449                 nbd_end_request(req);
450         }
451 }
452
453
454 static void nbd_handle_req(struct nbd_device *lo, struct request *req)
455 {
456         if (req->cmd_type != REQ_TYPE_FS)
457                 goto error_out;
458
459         nbd_cmd(req) = NBD_CMD_READ;
460         if (rq_data_dir(req) == WRITE) {
461                 nbd_cmd(req) = NBD_CMD_WRITE;
462                 if (lo->flags & NBD_READ_ONLY) {
463                         printk(KERN_ERR "%s: Write on read-only\n",
464                                         lo->disk->disk_name);
465                         goto error_out;
466                 }
467         }
468
469         req->errors = 0;
470
471         mutex_lock(&lo->tx_lock);
472         if (unlikely(!lo->sock)) {
473                 mutex_unlock(&lo->tx_lock);
474                 printk(KERN_ERR "%s: Attempted send on closed socket\n",
475                        lo->disk->disk_name);
476                 goto error_out;
477         }
478
479         lo->active_req = req;
480
481         if (nbd_send_req(lo, req) != 0) {
482                 printk(KERN_ERR "%s: Request send failed\n",
483                                 lo->disk->disk_name);
484                 req->errors++;
485                 nbd_end_request(req);
486         } else {
487                 spin_lock(&lo->queue_lock);
488                 list_add(&req->queuelist, &lo->queue_head);
489                 spin_unlock(&lo->queue_lock);
490         }
491
492         lo->active_req = NULL;
493         mutex_unlock(&lo->tx_lock);
494         wake_up_all(&lo->active_wq);
495
496         return;
497
498 error_out:
499         req->errors++;
500         nbd_end_request(req);
501 }
502
503 static int nbd_thread(void *data)
504 {
505         struct nbd_device *lo = data;
506         struct request *req;
507
508         set_user_nice(current, -20);
509         while (!kthread_should_stop() || !list_empty(&lo->waiting_queue)) {
510                 /* wait for something to do */
511                 wait_event_interruptible(lo->waiting_wq,
512                                          kthread_should_stop() ||
513                                          !list_empty(&lo->waiting_queue));
514
515                 /* extract request */
516                 if (list_empty(&lo->waiting_queue))
517                         continue;
518
519                 spin_lock_irq(&lo->queue_lock);
520                 req = list_entry(lo->waiting_queue.next, struct request,
521                                  queuelist);
522                 list_del_init(&req->queuelist);
523                 spin_unlock_irq(&lo->queue_lock);
524
525                 /* handle request */
526                 nbd_handle_req(lo, req);
527         }
528         return 0;
529 }
530
531 /*
532  * We always wait for result of write, for now. It would be nice to make it optional
533  * in future
534  * if ((rq_data_dir(req) == WRITE) && (lo->flags & NBD_WRITE_NOCHK))
535  *   { printk( "Warning: Ignoring result!\n"); nbd_end_request( req ); }
536  */
537
538 static void do_nbd_request(struct request_queue *q)
539 {
540         struct request *req;
541         
542         while ((req = blk_fetch_request(q)) != NULL) {
543                 struct nbd_device *lo;
544
545                 spin_unlock_irq(q->queue_lock);
546
547                 dprintk(DBG_BLKDEV, "%s: request %p: dequeued (flags=%x)\n",
548                                 req->rq_disk->disk_name, req, req->cmd_type);
549
550                 lo = req->rq_disk->private_data;
551
552                 BUG_ON(lo->magic != LO_MAGIC);
553
554                 if (unlikely(!lo->sock)) {
555                         printk(KERN_ERR "%s: Attempted send on closed socket\n",
556                                 lo->disk->disk_name);
557                         req->errors++;
558                         nbd_end_request(req);
559                         spin_lock_irq(q->queue_lock);
560                         continue;
561                 }
562
563                 spin_lock_irq(&lo->queue_lock);
564                 list_add_tail(&req->queuelist, &lo->waiting_queue);
565                 spin_unlock_irq(&lo->queue_lock);
566
567                 wake_up(&lo->waiting_wq);
568
569                 spin_lock_irq(q->queue_lock);
570         }
571 }
572
573 /* Must be called with tx_lock held */
574
575 static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *lo,
576                        unsigned int cmd, unsigned long arg)
577 {
578         switch (cmd) {
579         case NBD_DISCONNECT: {
580                 struct request sreq;
581
582                 printk(KERN_INFO "%s: NBD_DISCONNECT\n", lo->disk->disk_name);
583
584                 blk_rq_init(NULL, &sreq);
585                 sreq.cmd_type = REQ_TYPE_SPECIAL;
586                 nbd_cmd(&sreq) = NBD_CMD_DISC;
587                 if (!lo->sock)
588                         return -EINVAL;
589                 nbd_send_req(lo, &sreq);
590                 return 0;
591         }
592  
593         case NBD_CLEAR_SOCK: {
594                 struct file *file;
595
596                 lo->sock = NULL;
597                 file = lo->file;
598                 lo->file = NULL;
599                 nbd_clear_que(lo);
600                 BUG_ON(!list_empty(&lo->queue_head));
601                 if (file)
602                         fput(file);
603                 return 0;
604         }
605
606         case NBD_SET_SOCK: {
607                 struct file *file;
608                 if (lo->file)
609                         return -EBUSY;
610                 file = fget(arg);
611                 if (file) {
612                         struct inode *inode = file->f_path.dentry->d_inode;
613                         if (S_ISSOCK(inode->i_mode)) {
614                                 lo->file = file;
615                                 lo->sock = SOCKET_I(inode);
616                                 if (max_part > 0)
617                                         bdev->bd_invalidated = 1;
618                                 return 0;
619                         } else {
620                                 fput(file);
621                         }
622                 }
623                 return -EINVAL;
624         }
625
626         case NBD_SET_BLKSIZE:
627                 lo->blksize = arg;
628                 lo->bytesize &= ~(lo->blksize-1);
629                 bdev->bd_inode->i_size = lo->bytesize;
630                 set_blocksize(bdev, lo->blksize);
631                 set_capacity(lo->disk, lo->bytesize >> 9);
632                 return 0;
633
634         case NBD_SET_SIZE:
635                 lo->bytesize = arg & ~(lo->blksize-1);
636                 bdev->bd_inode->i_size = lo->bytesize;
637                 set_blocksize(bdev, lo->blksize);
638                 set_capacity(lo->disk, lo->bytesize >> 9);
639                 return 0;
640
641         case NBD_SET_TIMEOUT:
642                 lo->xmit_timeout = arg * HZ;
643                 return 0;
644
645         case NBD_SET_SIZE_BLOCKS:
646                 lo->bytesize = ((u64) arg) * lo->blksize;
647                 bdev->bd_inode->i_size = lo->bytesize;
648                 set_blocksize(bdev, lo->blksize);
649                 set_capacity(lo->disk, lo->bytesize >> 9);
650                 return 0;
651
652         case NBD_DO_IT: {
653                 struct task_struct *thread;
654                 struct file *file;
655                 int error;
656
657                 if (lo->pid)
658                         return -EBUSY;
659                 if (!lo->file)
660                         return -EINVAL;
661
662                 mutex_unlock(&lo->tx_lock);
663
664                 thread = kthread_create(nbd_thread, lo, lo->disk->disk_name);
665                 if (IS_ERR(thread)) {
666                         mutex_lock(&lo->tx_lock);
667                         return PTR_ERR(thread);
668                 }
669                 wake_up_process(thread);
670                 error = nbd_do_it(lo);
671                 kthread_stop(thread);
672
673                 mutex_lock(&lo->tx_lock);
674                 if (error)
675                         return error;
676                 sock_shutdown(lo, 0);
677                 file = lo->file;
678                 lo->file = NULL;
679                 nbd_clear_que(lo);
680                 printk(KERN_WARNING "%s: queue cleared\n", lo->disk->disk_name);
681                 if (file)
682                         fput(file);
683                 lo->bytesize = 0;
684                 bdev->bd_inode->i_size = 0;
685                 set_capacity(lo->disk, 0);
686                 if (max_part > 0)
687                         ioctl_by_bdev(bdev, BLKRRPART, 0);
688                 return lo->harderror;
689         }
690
691         case NBD_CLEAR_QUE:
692                 /*
693                  * This is for compatibility only.  The queue is always cleared
694                  * by NBD_DO_IT or NBD_CLEAR_SOCK.
695                  */
696                 BUG_ON(!lo->sock && !list_empty(&lo->queue_head));
697                 return 0;
698
699         case NBD_PRINT_DEBUG:
700                 printk(KERN_INFO "%s: next = %p, prev = %p, head = %p\n",
701                         bdev->bd_disk->disk_name,
702                         lo->queue_head.next, lo->queue_head.prev,
703                         &lo->queue_head);
704                 return 0;
705         }
706         return -ENOTTY;
707 }
708
709 static int nbd_ioctl(struct block_device *bdev, fmode_t mode,
710                      unsigned int cmd, unsigned long arg)
711 {
712         struct nbd_device *lo = bdev->bd_disk->private_data;
713         int error;
714
715         if (!capable(CAP_SYS_ADMIN))
716                 return -EPERM;
717
718         BUG_ON(lo->magic != LO_MAGIC);
719
720         /* Anyone capable of this syscall can do *real bad* things */
721         dprintk(DBG_IOCTL, "%s: nbd_ioctl cmd=%s(0x%x) arg=%lu\n",
722                         lo->disk->disk_name, ioctl_cmd_to_ascii(cmd), cmd, arg);
723
724         mutex_lock(&lo->tx_lock);
725         error = __nbd_ioctl(bdev, lo, cmd, arg);
726         mutex_unlock(&lo->tx_lock);
727
728         return error;
729 }
730
731 static const struct block_device_operations nbd_fops =
732 {
733         .owner =        THIS_MODULE,
734         .ioctl =        nbd_ioctl,
735 };
736
737 /*
738  * And here should be modules and kernel interface 
739  *  (Just smiley confuses emacs :-)
740  */
741
742 static int __init nbd_init(void)
743 {
744         int err = -ENOMEM;
745         int i;
746         int part_shift;
747
748         BUILD_BUG_ON(sizeof(struct nbd_request) != 28);
749
750         if (max_part < 0) {
751                 printk(KERN_CRIT "nbd: max_part must be >= 0\n");
752                 return -EINVAL;
753         }
754
755         nbd_dev = kcalloc(nbds_max, sizeof(*nbd_dev), GFP_KERNEL);
756         if (!nbd_dev)
757                 return -ENOMEM;
758
759         part_shift = 0;
760         if (max_part > 0)
761                 part_shift = fls(max_part);
762
763         for (i = 0; i < nbds_max; i++) {
764                 struct gendisk *disk = alloc_disk(1 << part_shift);
765                 if (!disk)
766                         goto out;
767                 nbd_dev[i].disk = disk;
768                 /*
769                  * The new linux 2.5 block layer implementation requires
770                  * every gendisk to have its very own request_queue struct.
771                  * These structs are big so we dynamically allocate them.
772                  */
773                 disk->queue = blk_init_queue(do_nbd_request, &nbd_lock);
774                 if (!disk->queue) {
775                         put_disk(disk);
776                         goto out;
777                 }
778                 /*
779                  * Tell the block layer that we are not a rotational device
780                  */
781                 queue_flag_set_unlocked(QUEUE_FLAG_NONROT, disk->queue);
782         }
783
784         if (register_blkdev(NBD_MAJOR, "nbd")) {
785                 err = -EIO;
786                 goto out;
787         }
788
789         printk(KERN_INFO "nbd: registered device at major %d\n", NBD_MAJOR);
790         dprintk(DBG_INIT, "nbd: debugflags=0x%x\n", debugflags);
791
792         for (i = 0; i < nbds_max; i++) {
793                 struct gendisk *disk = nbd_dev[i].disk;
794                 nbd_dev[i].file = NULL;
795                 nbd_dev[i].magic = LO_MAGIC;
796                 nbd_dev[i].flags = 0;
797                 INIT_LIST_HEAD(&nbd_dev[i].waiting_queue);
798                 spin_lock_init(&nbd_dev[i].queue_lock);
799                 INIT_LIST_HEAD(&nbd_dev[i].queue_head);
800                 mutex_init(&nbd_dev[i].tx_lock);
801                 init_waitqueue_head(&nbd_dev[i].active_wq);
802                 init_waitqueue_head(&nbd_dev[i].waiting_wq);
803                 nbd_dev[i].blksize = 1024;
804                 nbd_dev[i].bytesize = 0;
805                 disk->major = NBD_MAJOR;
806                 disk->first_minor = i << part_shift;
807                 disk->fops = &nbd_fops;
808                 disk->private_data = &nbd_dev[i];
809                 sprintf(disk->disk_name, "nbd%d", i);
810                 set_capacity(disk, 0);
811                 add_disk(disk);
812         }
813
814         return 0;
815 out:
816         while (i--) {
817                 blk_cleanup_queue(nbd_dev[i].disk->queue);
818                 put_disk(nbd_dev[i].disk);
819         }
820         kfree(nbd_dev);
821         return err;
822 }
823
824 static void __exit nbd_cleanup(void)
825 {
826         int i;
827         for (i = 0; i < nbds_max; i++) {
828                 struct gendisk *disk = nbd_dev[i].disk;
829                 nbd_dev[i].magic = 0;
830                 if (disk) {
831                         del_gendisk(disk);
832                         blk_cleanup_queue(disk->queue);
833                         put_disk(disk);
834                 }
835         }
836         unregister_blkdev(NBD_MAJOR, "nbd");
837         kfree(nbd_dev);
838         printk(KERN_INFO "nbd: unregistered device at major %d\n", NBD_MAJOR);
839 }
840
841 module_init(nbd_init);
842 module_exit(nbd_cleanup);
843
844 MODULE_DESCRIPTION("Network Block Device");
845 MODULE_LICENSE("GPL");
846
847 module_param(nbds_max, int, 0444);
848 MODULE_PARM_DESC(nbds_max, "number of network block devices to initialize (default: 16)");
849 module_param(max_part, int, 0444);
850 MODULE_PARM_DESC(max_part, "number of partitions per device (default: 0)");
851 #ifndef NDEBUG
852 module_param(debugflags, int, 0644);
853 MODULE_PARM_DESC(debugflags, "flags for controlling debug output");
854 #endif