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