fedora core 6 1.2949 + vserver 2.2.0
[linux-2.6.git] / drivers / block / loop.c
1 /*
2  *  linux/drivers/block/loop.c
3  *
4  *  Written by Theodore Ts'o, 3/29/93
5  *
6  * Copyright 1993 by Theodore Ts'o.  Redistribution of this file is
7  * permitted under the GNU General Public License.
8  *
9  * DES encryption plus some minor changes by Werner Almesberger, 30-MAY-1993
10  * more DES encryption plus IDEA encryption by Nicholas J. Leon, June 20, 1996
11  *
12  * Modularized and updated for 1.1.16 kernel - Mitch Dsouza 28th May 1994
13  * Adapted for 1.3.59 kernel - Andries Brouwer, 1 Feb 1996
14  *
15  * Fixed do_loop_request() re-entrancy - Vincent.Renardias@waw.com Mar 20, 1997
16  *
17  * Added devfs support - Richard Gooch <rgooch@atnf.csiro.au> 16-Jan-1998
18  *
19  * Handle sparse backing files correctly - Kenn Humborg, Jun 28, 1998
20  *
21  * Loadable modules and other fixes by AK, 1998
22  *
23  * Make real block number available to downstream transfer functions, enables
24  * CBC (and relatives) mode encryption requiring unique IVs per data block.
25  * Reed H. Petty, rhp@draper.net
26  *
27  * Maximum number of loop devices now dynamic via max_loop module parameter.
28  * Russell Kroll <rkroll@exploits.org> 19990701
29  *
30  * Maximum number of loop devices when compiled-in now selectable by passing
31  * max_loop=<1-255> to the kernel on boot.
32  * Erik I. Bolsø, <eriki@himolde.no>, Oct 31, 1999
33  *
34  * Completely rewrite request handling to be make_request_fn style and
35  * non blocking, pushing work to a helper thread. Lots of fixes from
36  * Al Viro too.
37  * Jens Axboe <axboe@suse.de>, Nov 2000
38  *
39  * Support up to 256 loop devices
40  * Heinz Mauelshagen <mge@sistina.com>, Feb 2002
41  *
42  * Support for falling back on the write file operation when the address space
43  * operations prepare_write and/or commit_write are not available on the
44  * backing filesystem.
45  * Anton Altaparmakov, 16 Feb 2005
46  *
47  * Still To Fix:
48  * - Advisory locking is ignored here.
49  * - Should use an own CAP_* category instead of CAP_SYS_ADMIN
50  *
51  */
52
53 #include <linux/module.h>
54 #include <linux/moduleparam.h>
55 #include <linux/sched.h>
56 #include <linux/fs.h>
57 #include <linux/file.h>
58 #include <linux/stat.h>
59 #include <linux/errno.h>
60 #include <linux/major.h>
61 #include <linux/wait.h>
62 #include <linux/blkdev.h>
63 #include <linux/blkpg.h>
64 #include <linux/init.h>
65 #include <linux/smp_lock.h>
66 #include <linux/swap.h>
67 #include <linux/slab.h>
68 #include <linux/loop.h>
69 #include <linux/compat.h>
70 #include <linux/suspend.h>
71 #include <linux/writeback.h>
72 #include <linux/buffer_head.h>          /* for invalidate_bdev() */
73 #include <linux/completion.h>
74 #include <linux/highmem.h>
75 #include <linux/gfp.h>
76 #include <linux/kthread.h>
77 #include <linux/vs_context.h>
78
79 #include <asm/uaccess.h>
80
81 static int max_loop = 8;
82 static struct loop_device *loop_dev;
83 static struct gendisk **disks;
84
85 /*
86  * Transfer functions
87  */
88 static int transfer_none(struct loop_device *lo, int cmd,
89                          struct page *raw_page, unsigned raw_off,
90                          struct page *loop_page, unsigned loop_off,
91                          int size, sector_t real_block)
92 {
93         char *raw_buf = kmap_atomic(raw_page, KM_USER0) + raw_off;
94         char *loop_buf = kmap_atomic(loop_page, KM_USER1) + loop_off;
95
96         if (cmd == READ)
97                 memcpy(loop_buf, raw_buf, size);
98         else
99                 memcpy(raw_buf, loop_buf, size);
100
101         kunmap_atomic(raw_buf, KM_USER0);
102         kunmap_atomic(loop_buf, KM_USER1);
103         cond_resched();
104         return 0;
105 }
106
107 static int transfer_xor(struct loop_device *lo, int cmd,
108                         struct page *raw_page, unsigned raw_off,
109                         struct page *loop_page, unsigned loop_off,
110                         int size, sector_t real_block)
111 {
112         char *raw_buf = kmap_atomic(raw_page, KM_USER0) + raw_off;
113         char *loop_buf = kmap_atomic(loop_page, KM_USER1) + loop_off;
114         char *in, *out, *key;
115         int i, keysize;
116
117         if (cmd == READ) {
118                 in = raw_buf;
119                 out = loop_buf;
120         } else {
121                 in = loop_buf;
122                 out = raw_buf;
123         }
124
125         key = lo->lo_encrypt_key;
126         keysize = lo->lo_encrypt_key_size;
127         for (i = 0; i < size; i++)
128                 *out++ = *in++ ^ key[(i & 511) % keysize];
129
130         kunmap_atomic(raw_buf, KM_USER0);
131         kunmap_atomic(loop_buf, KM_USER1);
132         cond_resched();
133         return 0;
134 }
135
136 static int xor_init(struct loop_device *lo, const struct loop_info64 *info)
137 {
138         if (unlikely(info->lo_encrypt_key_size <= 0))
139                 return -EINVAL;
140         return 0;
141 }
142
143 static struct loop_func_table none_funcs = {
144         .number = LO_CRYPT_NONE,
145         .transfer = transfer_none,
146 };      
147
148 static struct loop_func_table xor_funcs = {
149         .number = LO_CRYPT_XOR,
150         .transfer = transfer_xor,
151         .init = xor_init
152 };      
153
154 /* xfer_funcs[0] is special - its release function is never called */
155 static struct loop_func_table *xfer_funcs[MAX_LO_CRYPT] = {
156         &none_funcs,
157         &xor_funcs
158 };
159
160 static loff_t get_loop_size(struct loop_device *lo, struct file *file)
161 {
162         loff_t size, offset, loopsize;
163
164         /* Compute loopsize in bytes */
165         size = i_size_read(file->f_mapping->host);
166         offset = lo->lo_offset;
167         loopsize = size - offset;
168         if (lo->lo_sizelimit > 0 && lo->lo_sizelimit < loopsize)
169                 loopsize = lo->lo_sizelimit;
170
171         /*
172          * Unfortunately, if we want to do I/O on the device,
173          * the number of 512-byte sectors has to fit into a sector_t.
174          */
175         return loopsize >> 9;
176 }
177
178 static int
179 figure_loop_size(struct loop_device *lo)
180 {
181         loff_t size = get_loop_size(lo, lo->lo_backing_file);
182         sector_t x = (sector_t)size;
183
184         if (unlikely((loff_t)x != size))
185                 return -EFBIG;
186
187         set_capacity(disks[lo->lo_number], x);
188         return 0;                                       
189 }
190
191 static inline int
192 lo_do_transfer(struct loop_device *lo, int cmd,
193                struct page *rpage, unsigned roffs,
194                struct page *lpage, unsigned loffs,
195                int size, sector_t rblock)
196 {
197         if (unlikely(!lo->transfer))
198                 return 0;
199
200         return lo->transfer(lo, cmd, rpage, roffs, lpage, loffs, size, rblock);
201 }
202
203 /**
204  * do_lo_send_aops - helper for writing data to a loop device
205  *
206  * This is the fast version for backing filesystems which implement the address
207  * space operations prepare_write and commit_write.
208  */
209 static int do_lo_send_aops(struct loop_device *lo, struct bio_vec *bvec,
210                 int bsize, loff_t pos, struct page *page)
211 {
212         struct file *file = lo->lo_backing_file; /* kudos to NFsckingS */
213         struct address_space *mapping = file->f_mapping;
214         const struct address_space_operations *aops = mapping->a_ops;
215         pgoff_t index;
216         unsigned offset, bv_offs;
217         int len, ret;
218
219         mutex_lock(&mapping->host->i_mutex);
220         index = pos >> PAGE_CACHE_SHIFT;
221         offset = pos & ((pgoff_t)PAGE_CACHE_SIZE - 1);
222         bv_offs = bvec->bv_offset;
223         len = bvec->bv_len;
224         while (len > 0) {
225                 sector_t IV;
226                 unsigned size;
227                 int transfer_result;
228
229                 IV = ((sector_t)index << (PAGE_CACHE_SHIFT - 9))+(offset >> 9);
230                 size = PAGE_CACHE_SIZE - offset;
231                 if (size > len)
232                         size = len;
233                 page = grab_cache_page(mapping, index);
234                 if (unlikely(!page))
235                         goto fail;
236                 ret = aops->prepare_write(file, page, offset,
237                                           offset + size);
238                 if (unlikely(ret)) {
239                         if (ret == AOP_TRUNCATED_PAGE) {
240                                 page_cache_release(page);
241                                 continue;
242                         }
243                         goto unlock;
244                 }
245                 transfer_result = lo_do_transfer(lo, WRITE, page, offset,
246                                 bvec->bv_page, bv_offs, size, IV);
247                 if (unlikely(transfer_result)) {
248                         char *kaddr;
249
250                         /*
251                          * The transfer failed, but we still write the data to
252                          * keep prepare/commit calls balanced.
253                          */
254                         printk(KERN_ERR "loop: transfer error block %llu\n",
255                                (unsigned long long)index);
256                         kaddr = kmap_atomic(page, KM_USER0);
257                         memset(kaddr + offset, 0, size);
258                         kunmap_atomic(kaddr, KM_USER0);
259                 }
260                 flush_dcache_page(page);
261                 ret = aops->commit_write(file, page, offset,
262                                          offset + size);
263                 if (unlikely(ret)) {
264                         if (ret == AOP_TRUNCATED_PAGE) {
265                                 page_cache_release(page);
266                                 continue;
267                         }
268                         goto unlock;
269                 }
270                 if (unlikely(transfer_result))
271                         goto unlock;
272                 bv_offs += size;
273                 len -= size;
274                 offset = 0;
275                 index++;
276                 pos += size;
277                 unlock_page(page);
278                 page_cache_release(page);
279         }
280         ret = 0;
281 out:
282         mutex_unlock(&mapping->host->i_mutex);
283         return ret;
284 unlock:
285         unlock_page(page);
286         page_cache_release(page);
287 fail:
288         ret = -1;
289         goto out;
290 }
291
292 /**
293  * __do_lo_send_write - helper for writing data to a loop device
294  *
295  * This helper just factors out common code between do_lo_send_direct_write()
296  * and do_lo_send_write().
297  */
298 static int __do_lo_send_write(struct file *file,
299                 u8 *buf, const int len, loff_t pos)
300 {
301         ssize_t bw;
302         mm_segment_t old_fs = get_fs();
303
304         set_fs(get_ds());
305         bw = file->f_op->write(file, buf, len, &pos);
306         set_fs(old_fs);
307         if (likely(bw == len))
308                 return 0;
309         printk(KERN_ERR "loop: Write error at byte offset %llu, length %i.\n",
310                         (unsigned long long)pos, len);
311         if (bw >= 0)
312                 bw = -EIO;
313         return bw;
314 }
315
316 /**
317  * do_lo_send_direct_write - helper for writing data to a loop device
318  *
319  * This is the fast, non-transforming version for backing filesystems which do
320  * not implement the address space operations prepare_write and commit_write.
321  * It uses the write file operation which should be present on all writeable
322  * filesystems.
323  */
324 static int do_lo_send_direct_write(struct loop_device *lo,
325                 struct bio_vec *bvec, int bsize, loff_t pos, struct page *page)
326 {
327         ssize_t bw = __do_lo_send_write(lo->lo_backing_file,
328                         kmap(bvec->bv_page) + bvec->bv_offset,
329                         bvec->bv_len, pos);
330         kunmap(bvec->bv_page);
331         cond_resched();
332         return bw;
333 }
334
335 /**
336  * do_lo_send_write - helper for writing data to a loop device
337  *
338  * This is the slow, transforming version for filesystems which do not
339  * implement the address space operations prepare_write and commit_write.  It
340  * uses the write file operation which should be present on all writeable
341  * filesystems.
342  *
343  * Using fops->write is slower than using aops->{prepare,commit}_write in the
344  * transforming case because we need to double buffer the data as we cannot do
345  * the transformations in place as we do not have direct access to the
346  * destination pages of the backing file.
347  */
348 static int do_lo_send_write(struct loop_device *lo, struct bio_vec *bvec,
349                 int bsize, loff_t pos, struct page *page)
350 {
351         int ret = lo_do_transfer(lo, WRITE, page, 0, bvec->bv_page,
352                         bvec->bv_offset, bvec->bv_len, pos >> 9);
353         if (likely(!ret))
354                 return __do_lo_send_write(lo->lo_backing_file,
355                                 page_address(page), bvec->bv_len,
356                                 pos);
357         printk(KERN_ERR "loop: Transfer error at byte offset %llu, "
358                         "length %i.\n", (unsigned long long)pos, bvec->bv_len);
359         if (ret > 0)
360                 ret = -EIO;
361         return ret;
362 }
363
364 static int lo_send(struct loop_device *lo, struct bio *bio, int bsize,
365                 loff_t pos)
366 {
367         int (*do_lo_send)(struct loop_device *, struct bio_vec *, int, loff_t,
368                         struct page *page);
369         struct bio_vec *bvec;
370         struct page *page = NULL;
371         int i, ret = 0;
372
373         do_lo_send = do_lo_send_aops;
374         if (!(lo->lo_flags & LO_FLAGS_USE_AOPS)) {
375                 do_lo_send = do_lo_send_direct_write;
376                 if (lo->transfer != transfer_none) {
377                         page = alloc_page(GFP_NOIO | __GFP_HIGHMEM);
378                         if (unlikely(!page))
379                                 goto fail;
380                         kmap(page);
381                         do_lo_send = do_lo_send_write;
382                 }
383         }
384         bio_for_each_segment(bvec, bio, i) {
385                 ret = do_lo_send(lo, bvec, bsize, pos, page);
386                 if (ret < 0)
387                         break;
388                 pos += bvec->bv_len;
389         }
390         if (page) {
391                 kunmap(page);
392                 __free_page(page);
393         }
394 out:
395         return ret;
396 fail:
397         printk(KERN_ERR "loop: Failed to allocate temporary page for write.\n");
398         ret = -ENOMEM;
399         goto out;
400 }
401
402 struct lo_read_data {
403         struct loop_device *lo;
404         struct page *page;
405         unsigned offset;
406         int bsize;
407 };
408
409 static int
410 lo_read_actor(read_descriptor_t *desc, struct page *page,
411               unsigned long offset, unsigned long size)
412 {
413         unsigned long count = desc->count;
414         struct lo_read_data *p = desc->arg.data;
415         struct loop_device *lo = p->lo;
416         sector_t IV;
417
418         IV = ((sector_t) page->index << (PAGE_CACHE_SHIFT - 9))+(offset >> 9);
419
420         if (size > count)
421                 size = count;
422
423         if (lo_do_transfer(lo, READ, page, offset, p->page, p->offset, size, IV)) {
424                 size = 0;
425                 printk(KERN_ERR "loop: transfer error block %ld\n",
426                        page->index);
427                 desc->error = -EINVAL;
428         }
429
430         flush_dcache_page(p->page);
431
432         desc->count = count - size;
433         desc->written += size;
434         p->offset += size;
435         return size;
436 }
437
438 static int
439 do_lo_receive(struct loop_device *lo,
440               struct bio_vec *bvec, int bsize, loff_t pos)
441 {
442         struct lo_read_data cookie;
443         struct file *file;
444         int retval;
445
446         cookie.lo = lo;
447         cookie.page = bvec->bv_page;
448         cookie.offset = bvec->bv_offset;
449         cookie.bsize = bsize;
450         file = lo->lo_backing_file;
451         retval = file->f_op->sendfile(file, &pos, bvec->bv_len,
452                         lo_read_actor, &cookie);
453         return (retval < 0)? retval: 0;
454 }
455
456 static int
457 lo_receive(struct loop_device *lo, struct bio *bio, int bsize, loff_t pos)
458 {
459         struct bio_vec *bvec;
460         int i, ret = 0;
461
462         bio_for_each_segment(bvec, bio, i) {
463                 ret = do_lo_receive(lo, bvec, bsize, pos);
464                 if (ret < 0)
465                         break;
466                 pos += bvec->bv_len;
467         }
468         return ret;
469 }
470
471 static int do_bio_filebacked(struct loop_device *lo, struct bio *bio)
472 {
473         loff_t pos;
474         int ret;
475
476         pos = ((loff_t) bio->bi_sector << 9) + lo->lo_offset;
477         if (bio_rw(bio) == WRITE)
478                 ret = lo_send(lo, bio, lo->lo_blocksize, pos);
479         else
480                 ret = lo_receive(lo, bio, lo->lo_blocksize, pos);
481         return ret;
482 }
483
484 /*
485  * Add bio to back of pending list
486  */
487 static void loop_add_bio(struct loop_device *lo, struct bio *bio)
488 {
489         if (lo->lo_biotail) {
490                 lo->lo_biotail->bi_next = bio;
491                 lo->lo_biotail = bio;
492         } else
493                 lo->lo_bio = lo->lo_biotail = bio;
494 }
495
496 /*
497  * Grab first pending buffer
498  */
499 static struct bio *loop_get_bio(struct loop_device *lo)
500 {
501         struct bio *bio;
502
503         if ((bio = lo->lo_bio)) {
504                 if (bio == lo->lo_biotail)
505                         lo->lo_biotail = NULL;
506                 lo->lo_bio = bio->bi_next;
507                 bio->bi_next = NULL;
508         }
509
510         return bio;
511 }
512
513 static int loop_make_request(request_queue_t *q, struct bio *old_bio)
514 {
515         struct loop_device *lo = q->queuedata;
516         int rw = bio_rw(old_bio);
517
518         if (rw == READA)
519                 rw = READ;
520
521         BUG_ON(!lo || (rw != READ && rw != WRITE));
522
523         spin_lock_irq(&lo->lo_lock);
524         if (lo->lo_state != Lo_bound)
525                 goto out;
526         if (unlikely(rw == WRITE && (lo->lo_flags & LO_FLAGS_READ_ONLY)))
527                 goto out;
528         loop_add_bio(lo, old_bio);
529         wake_up(&lo->lo_event);
530         spin_unlock_irq(&lo->lo_lock);
531         return 0;
532
533 out:
534         spin_unlock_irq(&lo->lo_lock);
535         bio_io_error(old_bio, old_bio->bi_size);
536         return 0;
537 }
538
539 /*
540  * kick off io on the underlying address space
541  */
542 static void loop_unplug(request_queue_t *q)
543 {
544         struct loop_device *lo = q->queuedata;
545
546         clear_bit(QUEUE_FLAG_PLUGGED, &q->queue_flags);
547         blk_run_address_space(lo->lo_backing_file->f_mapping);
548 }
549
550 struct switch_request {
551         struct file *file;
552         struct completion wait;
553 };
554
555 static void do_loop_switch(struct loop_device *, struct switch_request *);
556
557 static inline void loop_handle_bio(struct loop_device *lo, struct bio *bio)
558 {
559         if (unlikely(!bio->bi_bdev)) {
560                 do_loop_switch(lo, bio->bi_private);
561                 bio_put(bio);
562         } else {
563                 int ret = do_bio_filebacked(lo, bio);
564                 bio_endio(bio, bio->bi_size, ret);
565         }
566 }
567
568 /*
569  * worker thread that handles reads/writes to file backed loop devices,
570  * to avoid blocking in our make_request_fn. it also does loop decrypting
571  * on reads for block backed loop, as that is too heavy to do from
572  * b_end_io context where irqs may be disabled.
573  *
574  * Loop explanation:  loop_clr_fd() sets lo_state to Lo_rundown before
575  * calling kthread_stop().  Therefore once kthread_should_stop() is
576  * true, make_request will not place any more requests.  Therefore
577  * once kthread_should_stop() is true and lo_bio is NULL, we are
578  * done with the loop.
579  */
580 static int loop_thread(void *data)
581 {
582         struct loop_device *lo = data;
583         struct bio *bio;
584
585         /*
586          * loop can be used in an encrypted device,
587          * hence, it mustn't be stopped at all
588          * because it could be indirectly used during suspension
589          */
590         current->flags |= PF_NOFREEZE;
591
592         set_user_nice(current, -20);
593
594         while (!kthread_should_stop() || lo->lo_bio) {
595
596                 wait_event_interruptible(lo->lo_event,
597                                 lo->lo_bio || kthread_should_stop());
598
599                 if (!lo->lo_bio)
600                         continue;
601                 spin_lock_irq(&lo->lo_lock);
602                 bio = loop_get_bio(lo);
603                 spin_unlock_irq(&lo->lo_lock);
604
605                 BUG_ON(!bio);
606                 loop_handle_bio(lo, bio);
607         }
608
609         return 0;
610 }
611
612 /*
613  * loop_switch performs the hard work of switching a backing store.
614  * First it needs to flush existing IO, it does this by sending a magic
615  * BIO down the pipe. The completion of this BIO does the actual switch.
616  */
617 static int loop_switch(struct loop_device *lo, struct file *file)
618 {
619         struct switch_request w;
620         struct bio *bio = bio_alloc(GFP_KERNEL, 1);
621         if (!bio)
622                 return -ENOMEM;
623         init_completion(&w.wait);
624         w.file = file;
625         bio->bi_private = &w;
626         bio->bi_bdev = NULL;
627         loop_make_request(lo->lo_queue, bio);
628         wait_for_completion(&w.wait);
629         return 0;
630 }
631
632 /*
633  * Do the actual switch; called from the BIO completion routine
634  */
635 static void do_loop_switch(struct loop_device *lo, struct switch_request *p)
636 {
637         struct file *file = p->file;
638         struct file *old_file = lo->lo_backing_file;
639         struct address_space *mapping = file->f_mapping;
640
641         mapping_set_gfp_mask(old_file->f_mapping, lo->old_gfp_mask);
642         lo->lo_backing_file = file;
643         lo->lo_blocksize = S_ISBLK(mapping->host->i_mode) ?
644                 mapping->host->i_bdev->bd_block_size : PAGE_SIZE;
645         lo->old_gfp_mask = mapping_gfp_mask(mapping);
646         mapping_set_gfp_mask(mapping, lo->old_gfp_mask & ~(__GFP_IO|__GFP_FS));
647         complete(&p->wait);
648 }
649
650
651 /*
652  * loop_change_fd switched the backing store of a loopback device to
653  * a new file. This is useful for operating system installers to free up
654  * the original file and in High Availability environments to switch to
655  * an alternative location for the content in case of server meltdown.
656  * This can only work if the loop device is used read-only, and if the
657  * new backing store is the same size and type as the old backing store.
658  */
659 static int loop_change_fd(struct loop_device *lo, struct file *lo_file,
660                        struct block_device *bdev, unsigned int arg)
661 {
662         struct file     *file, *old_file;
663         struct inode    *inode;
664         int             error;
665
666         error = -ENXIO;
667         if (lo->lo_state != Lo_bound)
668                 goto out;
669
670         /* the loop device has to be read-only */
671         error = -EINVAL;
672         if (!(lo->lo_flags & LO_FLAGS_READ_ONLY))
673                 goto out;
674
675         error = -EBADF;
676         file = fget(arg);
677         if (!file)
678                 goto out;
679
680         inode = file->f_mapping->host;
681         old_file = lo->lo_backing_file;
682
683         error = -EINVAL;
684
685         if (!S_ISREG(inode->i_mode) && !S_ISBLK(inode->i_mode))
686                 goto out_putf;
687
688         /* new backing store needs to support loop (eg sendfile) */
689         if (!inode->i_fop->sendfile)
690                 goto out_putf;
691
692         /* size of the new backing store needs to be the same */
693         if (get_loop_size(lo, file) != get_loop_size(lo, old_file))
694                 goto out_putf;
695
696         /* and ... switch */
697         error = loop_switch(lo, file);
698         if (error)
699                 goto out_putf;
700
701         fput(old_file);
702         return 0;
703
704  out_putf:
705         fput(file);
706  out:
707         return error;
708 }
709
710 static inline int is_loop_device(struct file *file)
711 {
712         struct inode *i = file->f_mapping->host;
713
714         return i && S_ISBLK(i->i_mode) && MAJOR(i->i_rdev) == LOOP_MAJOR;
715 }
716
717 static int loop_set_fd(struct loop_device *lo, struct file *lo_file,
718                        struct block_device *bdev, unsigned int arg)
719 {
720         struct file     *file, *f;
721         struct inode    *inode;
722         struct address_space *mapping;
723         unsigned lo_blocksize;
724         int             lo_flags = 0;
725         int             error;
726         loff_t          size;
727
728         /* This is safe, since we have a reference from open(). */
729         __module_get(THIS_MODULE);
730
731         error = -EBADF;
732         file = fget(arg);
733         if (!file)
734                 goto out;
735
736         error = -EBUSY;
737         if (lo->lo_state != Lo_unbound)
738                 goto out_putf;
739
740         /* Avoid recursion */
741         f = file;
742         while (is_loop_device(f)) {
743                 struct loop_device *l;
744
745                 if (f->f_mapping->host->i_rdev == lo_file->f_mapping->host->i_rdev)
746                         goto out_putf;
747
748                 l = f->f_mapping->host->i_bdev->bd_disk->private_data;
749                 if (l->lo_state == Lo_unbound) {
750                         error = -EINVAL;
751                         goto out_putf;
752                 }
753                 f = l->lo_backing_file;
754         }
755
756         mapping = file->f_mapping;
757         inode = mapping->host;
758
759         if (!(file->f_mode & FMODE_WRITE))
760                 lo_flags |= LO_FLAGS_READ_ONLY;
761
762         error = -EINVAL;
763         if (S_ISREG(inode->i_mode) || S_ISBLK(inode->i_mode)) {
764                 const struct address_space_operations *aops = mapping->a_ops;
765                 /*
766                  * If we can't read - sorry. If we only can't write - well,
767                  * it's going to be read-only.
768                  */
769                 if (!file->f_op->sendfile)
770                         goto out_putf;
771                 if (aops->prepare_write && aops->commit_write)
772                         lo_flags |= LO_FLAGS_USE_AOPS;
773                 if (!(lo_flags & LO_FLAGS_USE_AOPS) && !file->f_op->write)
774                         lo_flags |= LO_FLAGS_READ_ONLY;
775
776                 lo_blocksize = S_ISBLK(inode->i_mode) ?
777                         inode->i_bdev->bd_block_size : PAGE_SIZE;
778
779                 error = 0;
780         } else {
781                 goto out_putf;
782         }
783
784         size = get_loop_size(lo, file);
785
786         if ((loff_t)(sector_t)size != size) {
787                 error = -EFBIG;
788                 goto out_putf;
789         }
790
791         if (!(lo_file->f_mode & FMODE_WRITE))
792                 lo_flags |= LO_FLAGS_READ_ONLY;
793
794         set_device_ro(bdev, (lo_flags & LO_FLAGS_READ_ONLY) != 0);
795
796         lo->lo_blocksize = lo_blocksize;
797         lo->lo_device = bdev;
798         lo->lo_flags = lo_flags;
799         lo->lo_xid = vx_current_xid();
800         lo->lo_backing_file = file;
801         lo->transfer = transfer_none;
802         lo->ioctl = NULL;
803         lo->lo_sizelimit = 0;
804         lo->old_gfp_mask = mapping_gfp_mask(mapping);
805         mapping_set_gfp_mask(mapping, lo->old_gfp_mask & ~(__GFP_IO|__GFP_FS));
806
807         lo->lo_bio = lo->lo_biotail = NULL;
808
809         /*
810          * set queue make_request_fn, and add limits based on lower level
811          * device
812          */
813         blk_queue_make_request(lo->lo_queue, loop_make_request);
814         lo->lo_queue->queuedata = lo;
815         lo->lo_queue->unplug_fn = loop_unplug;
816
817         set_capacity(disks[lo->lo_number], size);
818         bd_set_size(bdev, size << 9);
819
820         set_blocksize(bdev, lo_blocksize);
821
822         lo->lo_thread = kthread_create(loop_thread, lo, "loop%d",
823                                                 lo->lo_number);
824         if (IS_ERR(lo->lo_thread)) {
825                 error = PTR_ERR(lo->lo_thread);
826                 goto out_clr;
827         }
828         lo->lo_state = Lo_bound;
829         wake_up_process(lo->lo_thread);
830         return 0;
831
832 out_clr:
833         lo->lo_thread = NULL;
834         lo->lo_device = NULL;
835         lo->lo_backing_file = NULL;
836         lo->lo_flags = 0;
837         set_capacity(disks[lo->lo_number], 0);
838         invalidate_bdev(bdev, 0);
839         bd_set_size(bdev, 0);
840         mapping_set_gfp_mask(mapping, lo->old_gfp_mask);
841         lo->lo_state = Lo_unbound;
842  out_putf:
843         fput(file);
844  out:
845         /* This is safe: open() is still holding a reference. */
846         module_put(THIS_MODULE);
847         return error;
848 }
849
850 static int
851 loop_release_xfer(struct loop_device *lo)
852 {
853         int err = 0;
854         struct loop_func_table *xfer = lo->lo_encryption;
855
856         if (xfer) {
857                 if (xfer->release)
858                         err = xfer->release(lo);
859                 lo->transfer = NULL;
860                 lo->lo_encryption = NULL;
861                 module_put(xfer->owner);
862         }
863         return err;
864 }
865
866 static int
867 loop_init_xfer(struct loop_device *lo, struct loop_func_table *xfer,
868                const struct loop_info64 *i)
869 {
870         int err = 0;
871
872         if (xfer) {
873                 struct module *owner = xfer->owner;
874
875                 if (!try_module_get(owner))
876                         return -EINVAL;
877                 if (xfer->init)
878                         err = xfer->init(lo, i);
879                 if (err)
880                         module_put(owner);
881                 else
882                         lo->lo_encryption = xfer;
883         }
884         return err;
885 }
886
887 static int loop_clr_fd(struct loop_device *lo, struct block_device *bdev)
888 {
889         struct file *filp = lo->lo_backing_file;
890         gfp_t gfp = lo->old_gfp_mask;
891
892         if (lo->lo_state != Lo_bound)
893                 return -ENXIO;
894
895         if (lo->lo_refcnt > 1)  /* we needed one fd for the ioctl */
896                 return -EBUSY;
897
898         if (filp == NULL)
899                 return -EINVAL;
900
901         spin_lock_irq(&lo->lo_lock);
902         lo->lo_state = Lo_rundown;
903         spin_unlock_irq(&lo->lo_lock);
904
905         kthread_stop(lo->lo_thread);
906
907         lo->lo_backing_file = NULL;
908
909         loop_release_xfer(lo);
910         lo->transfer = NULL;
911         lo->ioctl = NULL;
912         lo->lo_device = NULL;
913         lo->lo_encryption = NULL;
914         lo->lo_offset = 0;
915         lo->lo_sizelimit = 0;
916         lo->lo_encrypt_key_size = 0;
917         lo->lo_flags = 0;
918         lo->lo_thread = NULL;
919         memset(lo->lo_encrypt_key, 0, LO_KEY_SIZE);
920         memset(lo->lo_crypt_name, 0, LO_NAME_SIZE);
921         memset(lo->lo_file_name, 0, LO_NAME_SIZE);
922         invalidate_bdev(bdev, 0);
923         set_capacity(disks[lo->lo_number], 0);
924         bd_set_size(bdev, 0);
925         mapping_set_gfp_mask(filp->f_mapping, gfp);
926         lo->lo_state = Lo_unbound;
927         fput(filp);
928         /* This is safe: open() is still holding a reference. */
929         module_put(THIS_MODULE);
930         return 0;
931 }
932
933 static int
934 loop_set_status(struct loop_device *lo, const struct loop_info64 *info)
935 {
936         int err;
937         struct loop_func_table *xfer;
938
939         if (lo->lo_encrypt_key_size && lo->lo_key_owner != current->uid &&
940             !vx_capable(CAP_SYS_ADMIN, VXC_ADMIN_CLOOP))
941                 return -EPERM;
942         if (lo->lo_state != Lo_bound)
943                 return -ENXIO;
944         if ((unsigned int) info->lo_encrypt_key_size > LO_KEY_SIZE)
945                 return -EINVAL;
946
947         err = loop_release_xfer(lo);
948         if (err)
949                 return err;
950
951         if (info->lo_encrypt_type) {
952                 unsigned int type = info->lo_encrypt_type;
953
954                 if (type >= MAX_LO_CRYPT)
955                         return -EINVAL;
956                 xfer = xfer_funcs[type];
957                 if (xfer == NULL)
958                         return -EINVAL;
959         } else
960                 xfer = NULL;
961
962         err = loop_init_xfer(lo, xfer, info);
963         if (err)
964                 return err;
965
966         if (lo->lo_offset != info->lo_offset ||
967             lo->lo_sizelimit != info->lo_sizelimit) {
968                 lo->lo_offset = info->lo_offset;
969                 lo->lo_sizelimit = info->lo_sizelimit;
970                 if (figure_loop_size(lo))
971                         return -EFBIG;
972         }
973
974         memcpy(lo->lo_file_name, info->lo_file_name, LO_NAME_SIZE);
975         memcpy(lo->lo_crypt_name, info->lo_crypt_name, LO_NAME_SIZE);
976         lo->lo_file_name[LO_NAME_SIZE-1] = 0;
977         lo->lo_crypt_name[LO_NAME_SIZE-1] = 0;
978
979         if (!xfer)
980                 xfer = &none_funcs;
981         lo->transfer = xfer->transfer;
982         lo->ioctl = xfer->ioctl;
983
984         lo->lo_encrypt_key_size = info->lo_encrypt_key_size;
985         lo->lo_init[0] = info->lo_init[0];
986         lo->lo_init[1] = info->lo_init[1];
987         if (info->lo_encrypt_key_size) {
988                 memcpy(lo->lo_encrypt_key, info->lo_encrypt_key,
989                        info->lo_encrypt_key_size);
990                 lo->lo_key_owner = current->uid;
991         }       
992
993         return 0;
994 }
995
996 static int
997 loop_get_status(struct loop_device *lo, struct loop_info64 *info)
998 {
999         struct file *file = lo->lo_backing_file;
1000         struct kstat stat;
1001         int error;
1002
1003         if (lo->lo_state != Lo_bound)
1004                 return -ENXIO;
1005         error = vfs_getattr(file->f_path.mnt, file->f_path.dentry, &stat);
1006         if (error)
1007                 return error;
1008         memset(info, 0, sizeof(*info));
1009         info->lo_number = lo->lo_number;
1010         info->lo_device = huge_encode_dev(stat.dev);
1011         info->lo_inode = stat.ino;
1012         info->lo_rdevice = huge_encode_dev(lo->lo_device ? stat.rdev : stat.dev);
1013         info->lo_offset = lo->lo_offset;
1014         info->lo_sizelimit = lo->lo_sizelimit;
1015         info->lo_flags = lo->lo_flags;
1016         memcpy(info->lo_file_name, lo->lo_file_name, LO_NAME_SIZE);
1017         memcpy(info->lo_crypt_name, lo->lo_crypt_name, LO_NAME_SIZE);
1018         info->lo_encrypt_type =
1019                 lo->lo_encryption ? lo->lo_encryption->number : 0;
1020         if (lo->lo_encrypt_key_size &&
1021                 vx_capable(CAP_SYS_ADMIN, VXC_ADMIN_CLOOP)) {
1022                 info->lo_encrypt_key_size = lo->lo_encrypt_key_size;
1023                 memcpy(info->lo_encrypt_key, lo->lo_encrypt_key,
1024                        lo->lo_encrypt_key_size);
1025         }
1026         return 0;
1027 }
1028
1029 static void
1030 loop_info64_from_old(const struct loop_info *info, struct loop_info64 *info64)
1031 {
1032         memset(info64, 0, sizeof(*info64));
1033         info64->lo_number = info->lo_number;
1034         info64->lo_device = info->lo_device;
1035         info64->lo_inode = info->lo_inode;
1036         info64->lo_rdevice = info->lo_rdevice;
1037         info64->lo_offset = info->lo_offset;
1038         info64->lo_sizelimit = 0;
1039         info64->lo_encrypt_type = info->lo_encrypt_type;
1040         info64->lo_encrypt_key_size = info->lo_encrypt_key_size;
1041         info64->lo_flags = info->lo_flags;
1042         info64->lo_init[0] = info->lo_init[0];
1043         info64->lo_init[1] = info->lo_init[1];
1044         if (info->lo_encrypt_type == LO_CRYPT_CRYPTOAPI)
1045                 memcpy(info64->lo_crypt_name, info->lo_name, LO_NAME_SIZE);
1046         else
1047                 memcpy(info64->lo_file_name, info->lo_name, LO_NAME_SIZE);
1048         memcpy(info64->lo_encrypt_key, info->lo_encrypt_key, LO_KEY_SIZE);
1049 }
1050
1051 static int
1052 loop_info64_to_old(const struct loop_info64 *info64, struct loop_info *info)
1053 {
1054         memset(info, 0, sizeof(*info));
1055         info->lo_number = info64->lo_number;
1056         info->lo_device = info64->lo_device;
1057         info->lo_inode = info64->lo_inode;
1058         info->lo_rdevice = info64->lo_rdevice;
1059         info->lo_offset = info64->lo_offset;
1060         info->lo_encrypt_type = info64->lo_encrypt_type;
1061         info->lo_encrypt_key_size = info64->lo_encrypt_key_size;
1062         info->lo_flags = info64->lo_flags;
1063         info->lo_init[0] = info64->lo_init[0];
1064         info->lo_init[1] = info64->lo_init[1];
1065         if (info->lo_encrypt_type == LO_CRYPT_CRYPTOAPI)
1066                 memcpy(info->lo_name, info64->lo_crypt_name, LO_NAME_SIZE);
1067         else
1068                 memcpy(info->lo_name, info64->lo_file_name, LO_NAME_SIZE);
1069         memcpy(info->lo_encrypt_key, info64->lo_encrypt_key, LO_KEY_SIZE);
1070
1071         /* error in case values were truncated */
1072         if (info->lo_device != info64->lo_device ||
1073             info->lo_rdevice != info64->lo_rdevice ||
1074             info->lo_inode != info64->lo_inode ||
1075             info->lo_offset != info64->lo_offset)
1076                 return -EOVERFLOW;
1077
1078         return 0;
1079 }
1080
1081 static int
1082 loop_set_status_old(struct loop_device *lo, const struct loop_info __user *arg)
1083 {
1084         struct loop_info info;
1085         struct loop_info64 info64;
1086
1087         if (copy_from_user(&info, arg, sizeof (struct loop_info)))
1088                 return -EFAULT;
1089         loop_info64_from_old(&info, &info64);
1090         return loop_set_status(lo, &info64);
1091 }
1092
1093 static int
1094 loop_set_status64(struct loop_device *lo, const struct loop_info64 __user *arg)
1095 {
1096         struct loop_info64 info64;
1097
1098         if (copy_from_user(&info64, arg, sizeof (struct loop_info64)))
1099                 return -EFAULT;
1100         return loop_set_status(lo, &info64);
1101 }
1102
1103 static int
1104 loop_get_status_old(struct loop_device *lo, struct loop_info __user *arg) {
1105         struct loop_info info;
1106         struct loop_info64 info64;
1107         int err = 0;
1108
1109         if (!arg)
1110                 err = -EINVAL;
1111         if (!err)
1112                 err = loop_get_status(lo, &info64);
1113         if (!err)
1114                 err = loop_info64_to_old(&info64, &info);
1115         if (!err && copy_to_user(arg, &info, sizeof(info)))
1116                 err = -EFAULT;
1117
1118         return err;
1119 }
1120
1121 static int
1122 loop_get_status64(struct loop_device *lo, struct loop_info64 __user *arg) {
1123         struct loop_info64 info64;
1124         int err = 0;
1125
1126         if (!arg)
1127                 err = -EINVAL;
1128         if (!err)
1129                 err = loop_get_status(lo, &info64);
1130         if (!err && copy_to_user(arg, &info64, sizeof(info64)))
1131                 err = -EFAULT;
1132
1133         return err;
1134 }
1135
1136 static int lo_ioctl(struct inode * inode, struct file * file,
1137         unsigned int cmd, unsigned long arg)
1138 {
1139         struct loop_device *lo = inode->i_bdev->bd_disk->private_data;
1140         int err;
1141
1142         mutex_lock(&lo->lo_ctl_mutex);
1143         switch (cmd) {
1144         case LOOP_SET_FD:
1145                 err = loop_set_fd(lo, file, inode->i_bdev, arg);
1146                 break;
1147         case LOOP_CHANGE_FD:
1148                 err = loop_change_fd(lo, file, inode->i_bdev, arg);
1149                 break;
1150         case LOOP_CLR_FD:
1151                 err = loop_clr_fd(lo, inode->i_bdev);
1152                 break;
1153         case LOOP_SET_STATUS:
1154                 err = loop_set_status_old(lo, (struct loop_info __user *) arg);
1155                 break;
1156         case LOOP_GET_STATUS:
1157                 err = loop_get_status_old(lo, (struct loop_info __user *) arg);
1158                 break;
1159         case LOOP_SET_STATUS64:
1160                 err = loop_set_status64(lo, (struct loop_info64 __user *) arg);
1161                 break;
1162         case LOOP_GET_STATUS64:
1163                 err = loop_get_status64(lo, (struct loop_info64 __user *) arg);
1164                 break;
1165         default:
1166                 err = lo->ioctl ? lo->ioctl(lo, cmd, arg) : -EINVAL;
1167         }
1168         mutex_unlock(&lo->lo_ctl_mutex);
1169         return err;
1170 }
1171
1172 #ifdef CONFIG_COMPAT
1173 struct compat_loop_info {
1174         compat_int_t    lo_number;      /* ioctl r/o */
1175         compat_dev_t    lo_device;      /* ioctl r/o */
1176         compat_ulong_t  lo_inode;       /* ioctl r/o */
1177         compat_dev_t    lo_rdevice;     /* ioctl r/o */
1178         compat_int_t    lo_offset;
1179         compat_int_t    lo_encrypt_type;
1180         compat_int_t    lo_encrypt_key_size;    /* ioctl w/o */
1181         compat_int_t    lo_flags;       /* ioctl r/o */
1182         char            lo_name[LO_NAME_SIZE];
1183         unsigned char   lo_encrypt_key[LO_KEY_SIZE]; /* ioctl w/o */
1184         compat_ulong_t  lo_init[2];
1185         char            reserved[4];
1186 };
1187
1188 /*
1189  * Transfer 32-bit compatibility structure in userspace to 64-bit loop info
1190  * - noinlined to reduce stack space usage in main part of driver
1191  */
1192 static noinline int
1193 loop_info64_from_compat(const struct compat_loop_info __user *arg,
1194                         struct loop_info64 *info64)
1195 {
1196         struct compat_loop_info info;
1197
1198         if (copy_from_user(&info, arg, sizeof(info)))
1199                 return -EFAULT;
1200
1201         memset(info64, 0, sizeof(*info64));
1202         info64->lo_number = info.lo_number;
1203         info64->lo_device = info.lo_device;
1204         info64->lo_inode = info.lo_inode;
1205         info64->lo_rdevice = info.lo_rdevice;
1206         info64->lo_offset = info.lo_offset;
1207         info64->lo_sizelimit = 0;
1208         info64->lo_encrypt_type = info.lo_encrypt_type;
1209         info64->lo_encrypt_key_size = info.lo_encrypt_key_size;
1210         info64->lo_flags = info.lo_flags;
1211         info64->lo_init[0] = info.lo_init[0];
1212         info64->lo_init[1] = info.lo_init[1];
1213         if (info.lo_encrypt_type == LO_CRYPT_CRYPTOAPI)
1214                 memcpy(info64->lo_crypt_name, info.lo_name, LO_NAME_SIZE);
1215         else
1216                 memcpy(info64->lo_file_name, info.lo_name, LO_NAME_SIZE);
1217         memcpy(info64->lo_encrypt_key, info.lo_encrypt_key, LO_KEY_SIZE);
1218         return 0;
1219 }
1220
1221 /*
1222  * Transfer 64-bit loop info to 32-bit compatibility structure in userspace
1223  * - noinlined to reduce stack space usage in main part of driver
1224  */
1225 static noinline int
1226 loop_info64_to_compat(const struct loop_info64 *info64,
1227                       struct compat_loop_info __user *arg)
1228 {
1229         struct compat_loop_info info;
1230
1231         memset(&info, 0, sizeof(info));
1232         info.lo_number = info64->lo_number;
1233         info.lo_device = info64->lo_device;
1234         info.lo_inode = info64->lo_inode;
1235         info.lo_rdevice = info64->lo_rdevice;
1236         info.lo_offset = info64->lo_offset;
1237         info.lo_encrypt_type = info64->lo_encrypt_type;
1238         info.lo_encrypt_key_size = info64->lo_encrypt_key_size;
1239         info.lo_flags = info64->lo_flags;
1240         info.lo_init[0] = info64->lo_init[0];
1241         info.lo_init[1] = info64->lo_init[1];
1242         if (info.lo_encrypt_type == LO_CRYPT_CRYPTOAPI)
1243                 memcpy(info.lo_name, info64->lo_crypt_name, LO_NAME_SIZE);
1244         else
1245                 memcpy(info.lo_name, info64->lo_file_name, LO_NAME_SIZE);
1246         memcpy(info.lo_encrypt_key, info64->lo_encrypt_key, LO_KEY_SIZE);
1247
1248         /* error in case values were truncated */
1249         if (info.lo_device != info64->lo_device ||
1250             info.lo_rdevice != info64->lo_rdevice ||
1251             info.lo_inode != info64->lo_inode ||
1252             info.lo_offset != info64->lo_offset ||
1253             info.lo_init[0] != info64->lo_init[0] ||
1254             info.lo_init[1] != info64->lo_init[1])
1255                 return -EOVERFLOW;
1256
1257         if (copy_to_user(arg, &info, sizeof(info)))
1258                 return -EFAULT;
1259         return 0;
1260 }
1261
1262 static int
1263 loop_set_status_compat(struct loop_device *lo,
1264                        const struct compat_loop_info __user *arg)
1265 {
1266         struct loop_info64 info64;
1267         int ret;
1268
1269         ret = loop_info64_from_compat(arg, &info64);
1270         if (ret < 0)
1271                 return ret;
1272         return loop_set_status(lo, &info64);
1273 }
1274
1275 static int
1276 loop_get_status_compat(struct loop_device *lo,
1277                        struct compat_loop_info __user *arg)
1278 {
1279         struct loop_info64 info64;
1280         int err = 0;
1281
1282         if (!arg)
1283                 err = -EINVAL;
1284         if (!err)
1285                 err = loop_get_status(lo, &info64);
1286         if (!err)
1287                 err = loop_info64_to_compat(&info64, arg);
1288         return err;
1289 }
1290
1291 static long lo_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
1292 {
1293         struct inode *inode = file->f_path.dentry->d_inode;
1294         struct loop_device *lo = inode->i_bdev->bd_disk->private_data;
1295         int err;
1296
1297         lock_kernel();
1298         switch(cmd) {
1299         case LOOP_SET_STATUS:
1300                 mutex_lock(&lo->lo_ctl_mutex);
1301                 err = loop_set_status_compat(
1302                         lo, (const struct compat_loop_info __user *) arg);
1303                 mutex_unlock(&lo->lo_ctl_mutex);
1304                 break;
1305         case LOOP_GET_STATUS:
1306                 mutex_lock(&lo->lo_ctl_mutex);
1307                 err = loop_get_status_compat(
1308                         lo, (struct compat_loop_info __user *) arg);
1309                 mutex_unlock(&lo->lo_ctl_mutex);
1310                 break;
1311         case LOOP_CLR_FD:
1312         case LOOP_GET_STATUS64:
1313         case LOOP_SET_STATUS64:
1314                 arg = (unsigned long) compat_ptr(arg);
1315         case LOOP_SET_FD:
1316         case LOOP_CHANGE_FD:
1317                 err = lo_ioctl(inode, file, cmd, arg);
1318                 break;
1319         default:
1320                 err = -ENOIOCTLCMD;
1321                 break;
1322         }
1323         unlock_kernel();
1324         return err;
1325 }
1326 #endif
1327
1328 static int lo_open(struct inode *inode, struct file *file)
1329 {
1330         struct loop_device *lo = inode->i_bdev->bd_disk->private_data;
1331
1332         if (!vx_check(lo->lo_xid, VS_IDENT|VS_HOSTID))
1333                 return -EACCES;
1334
1335         mutex_lock(&lo->lo_ctl_mutex);
1336         lo->lo_refcnt++;
1337         mutex_unlock(&lo->lo_ctl_mutex);
1338
1339         return 0;
1340 }
1341
1342 static int lo_release(struct inode *inode, struct file *file)
1343 {
1344         struct loop_device *lo = inode->i_bdev->bd_disk->private_data;
1345
1346         mutex_lock(&lo->lo_ctl_mutex);
1347         --lo->lo_refcnt;
1348         mutex_unlock(&lo->lo_ctl_mutex);
1349
1350         return 0;
1351 }
1352
1353 static struct block_device_operations lo_fops = {
1354         .owner =        THIS_MODULE,
1355         .open =         lo_open,
1356         .release =      lo_release,
1357         .ioctl =        lo_ioctl,
1358 #ifdef CONFIG_COMPAT
1359         .compat_ioctl = lo_compat_ioctl,
1360 #endif
1361 };
1362
1363 /*
1364  * And now the modules code and kernel interface.
1365  */
1366 module_param(max_loop, int, 0);
1367 MODULE_PARM_DESC(max_loop, "Maximum number of loop devices (1-256)");
1368 MODULE_LICENSE("GPL");
1369 MODULE_ALIAS_BLOCKDEV_MAJOR(LOOP_MAJOR);
1370
1371 int loop_register_transfer(struct loop_func_table *funcs)
1372 {
1373         unsigned int n = funcs->number;
1374
1375         if (n >= MAX_LO_CRYPT || xfer_funcs[n])
1376                 return -EINVAL;
1377         xfer_funcs[n] = funcs;
1378         return 0;
1379 }
1380
1381 int loop_unregister_transfer(int number)
1382 {
1383         unsigned int n = number;
1384         struct loop_device *lo;
1385         struct loop_func_table *xfer;
1386
1387         if (n == 0 || n >= MAX_LO_CRYPT || (xfer = xfer_funcs[n]) == NULL)
1388                 return -EINVAL;
1389
1390         xfer_funcs[n] = NULL;
1391
1392         for (lo = &loop_dev[0]; lo < &loop_dev[max_loop]; lo++) {
1393                 mutex_lock(&lo->lo_ctl_mutex);
1394
1395                 if (lo->lo_encryption == xfer)
1396                         loop_release_xfer(lo);
1397
1398                 mutex_unlock(&lo->lo_ctl_mutex);
1399         }
1400
1401         return 0;
1402 }
1403
1404 EXPORT_SYMBOL(loop_register_transfer);
1405 EXPORT_SYMBOL(loop_unregister_transfer);
1406
1407 static int __init loop_init(void)
1408 {
1409         int     i;
1410
1411         if (max_loop < 1 || max_loop > 256) {
1412                 printk(KERN_WARNING "loop: invalid max_loop (must be between"
1413                                     " 1 and 256), using default (8)\n");
1414                 max_loop = 8;
1415         }
1416
1417         if (register_blkdev(LOOP_MAJOR, "loop"))
1418                 return -EIO;
1419
1420         loop_dev = kmalloc(max_loop * sizeof(struct loop_device), GFP_KERNEL);
1421         if (!loop_dev)
1422                 goto out_mem1;
1423         memset(loop_dev, 0, max_loop * sizeof(struct loop_device));
1424
1425         disks = kmalloc(max_loop * sizeof(struct gendisk *), GFP_KERNEL);
1426         if (!disks)
1427                 goto out_mem2;
1428
1429         for (i = 0; i < max_loop; i++) {
1430                 disks[i] = alloc_disk(1);
1431                 if (!disks[i])
1432                         goto out_mem3;
1433         }
1434
1435         for (i = 0; i < max_loop; i++) {
1436                 struct loop_device *lo = &loop_dev[i];
1437                 struct gendisk *disk = disks[i];
1438
1439                 memset(lo, 0, sizeof(*lo));
1440                 lo->lo_queue = blk_alloc_queue(GFP_KERNEL);
1441                 if (!lo->lo_queue)
1442                         goto out_mem4;
1443                 mutex_init(&lo->lo_ctl_mutex);
1444                 lo->lo_number = i;
1445                 lo->lo_thread = NULL;
1446                 init_waitqueue_head(&lo->lo_event);
1447                 spin_lock_init(&lo->lo_lock);
1448                 disk->major = LOOP_MAJOR;
1449                 disk->first_minor = i;
1450                 disk->fops = &lo_fops;
1451                 sprintf(disk->disk_name, "loop%d", i);
1452                 disk->private_data = lo;
1453                 disk->queue = lo->lo_queue;
1454         }
1455
1456         /* We cannot fail after we call this, so another loop!*/
1457         for (i = 0; i < max_loop; i++)
1458                 add_disk(disks[i]);
1459         printk(KERN_INFO "loop: loaded (max %d devices)\n", max_loop);
1460         return 0;
1461
1462 out_mem4:
1463         while (i--)
1464                 blk_cleanup_queue(loop_dev[i].lo_queue);
1465         i = max_loop;
1466 out_mem3:
1467         while (i--)
1468                 put_disk(disks[i]);
1469         kfree(disks);
1470 out_mem2:
1471         kfree(loop_dev);
1472 out_mem1:
1473         unregister_blkdev(LOOP_MAJOR, "loop");
1474         printk(KERN_ERR "loop: ran out of memory\n");
1475         return -ENOMEM;
1476 }
1477
1478 static void loop_exit(void)
1479 {
1480         int i;
1481
1482         for (i = 0; i < max_loop; i++) {
1483                 del_gendisk(disks[i]);
1484                 blk_cleanup_queue(loop_dev[i].lo_queue);
1485                 put_disk(disks[i]);
1486         }
1487         if (unregister_blkdev(LOOP_MAJOR, "loop"))
1488                 printk(KERN_WARNING "loop: cannot unregister blkdev\n");
1489
1490         kfree(disks);
1491         kfree(loop_dev);
1492 }
1493
1494 module_init(loop_init);
1495 module_exit(loop_exit);
1496
1497 #ifndef MODULE
1498 static int __init max_loop_setup(char *str)
1499 {
1500         max_loop = simple_strtol(str, NULL, 0);
1501         return 1;
1502 }
1503
1504 __setup("max_loop=", max_loop_setup);
1505 #endif