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