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