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