]> git.karo-electronics.de Git - karo-tx-linux.git/blob - drivers/block/loop.c
Merge remote-tracking branch 'block/for-next'
[karo-tx-linux.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 write_begin is not available on the backing filesystem.
44  * Anton Altaparmakov, 16 Feb 2005
45  *
46  * Still To Fix:
47  * - Advisory locking is ignored here.
48  * - Should use an own CAP_* category instead of CAP_SYS_ADMIN
49  *
50  */
51
52 #include <linux/module.h>
53 #include <linux/moduleparam.h>
54 #include <linux/sched.h>
55 #include <linux/fs.h>
56 #include <linux/file.h>
57 #include <linux/stat.h>
58 #include <linux/errno.h>
59 #include <linux/major.h>
60 #include <linux/wait.h>
61 #include <linux/blkdev.h>
62 #include <linux/blkpg.h>
63 #include <linux/init.h>
64 #include <linux/swap.h>
65 #include <linux/slab.h>
66 #include <linux/compat.h>
67 #include <linux/suspend.h>
68 #include <linux/freezer.h>
69 #include <linux/mutex.h>
70 #include <linux/writeback.h>
71 #include <linux/completion.h>
72 #include <linux/highmem.h>
73 #include <linux/kthread.h>
74 #include <linux/splice.h>
75 #include <linux/sysfs.h>
76 #include <linux/miscdevice.h>
77 #include <linux/falloc.h>
78 #include <linux/aio.h>
79 #include "loop.h"
80
81 #include <asm/uaccess.h>
82
83 static DEFINE_IDR(loop_index_idr);
84 static DEFINE_MUTEX(loop_index_mutex);
85
86 static int max_part;
87 static int part_shift;
88
89 /*
90  * Transfer functions
91  */
92 static int transfer_none(struct loop_device *lo, int cmd,
93                          struct page *raw_page, unsigned raw_off,
94                          struct page *loop_page, unsigned loop_off,
95                          int size, sector_t real_block)
96 {
97         char *raw_buf = kmap_atomic(raw_page) + raw_off;
98         char *loop_buf = kmap_atomic(loop_page) + loop_off;
99
100         if (cmd == READ)
101                 memcpy(loop_buf, raw_buf, size);
102         else
103                 memcpy(raw_buf, loop_buf, size);
104
105         kunmap_atomic(loop_buf);
106         kunmap_atomic(raw_buf);
107         cond_resched();
108         return 0;
109 }
110
111 static int transfer_xor(struct loop_device *lo, int cmd,
112                         struct page *raw_page, unsigned raw_off,
113                         struct page *loop_page, unsigned loop_off,
114                         int size, sector_t real_block)
115 {
116         char *raw_buf = kmap_atomic(raw_page) + raw_off;
117         char *loop_buf = kmap_atomic(loop_page) + loop_off;
118         char *in, *out, *key;
119         int i, keysize;
120
121         if (cmd == READ) {
122                 in = raw_buf;
123                 out = loop_buf;
124         } else {
125                 in = loop_buf;
126                 out = raw_buf;
127         }
128
129         key = lo->lo_encrypt_key;
130         keysize = lo->lo_encrypt_key_size;
131         for (i = 0; i < size; i++)
132                 *out++ = *in++ ^ key[(i & 511) % keysize];
133
134         kunmap_atomic(loop_buf);
135         kunmap_atomic(raw_buf);
136         cond_resched();
137         return 0;
138 }
139
140 static int xor_init(struct loop_device *lo, const struct loop_info64 *info)
141 {
142         if (unlikely(info->lo_encrypt_key_size <= 0))
143                 return -EINVAL;
144         return 0;
145 }
146
147 static struct loop_func_table none_funcs = {
148         .number = LO_CRYPT_NONE,
149         .transfer = transfer_none,
150 };      
151
152 static struct loop_func_table xor_funcs = {
153         .number = LO_CRYPT_XOR,
154         .transfer = transfer_xor,
155         .init = xor_init
156 };      
157
158 /* xfer_funcs[0] is special - its release function is never called */
159 static struct loop_func_table *xfer_funcs[MAX_LO_CRYPT] = {
160         &none_funcs,
161         &xor_funcs
162 };
163
164 static loff_t get_size(loff_t offset, loff_t sizelimit, struct file *file)
165 {
166         loff_t loopsize;
167
168         /* Compute loopsize in bytes */
169         loopsize = i_size_read(file->f_mapping->host);
170         if (offset > 0)
171                 loopsize -= offset;
172         /* offset is beyond i_size, weird but possible */
173         if (loopsize < 0)
174                 return 0;
175
176         if (sizelimit > 0 && sizelimit < loopsize)
177                 loopsize = sizelimit;
178         /*
179          * Unfortunately, if we want to do I/O on the device,
180          * the number of 512-byte sectors has to fit into a sector_t.
181          */
182         return loopsize >> 9;
183 }
184
185 static loff_t get_loop_size(struct loop_device *lo, struct file *file)
186 {
187         return get_size(lo->lo_offset, lo->lo_sizelimit, file);
188 }
189
190 static int
191 figure_loop_size(struct loop_device *lo, loff_t offset, loff_t sizelimit)
192 {
193         loff_t size = get_size(offset, sizelimit, lo->lo_backing_file);
194         sector_t x = (sector_t)size;
195         struct block_device *bdev = lo->lo_device;
196
197         if (unlikely((loff_t)x != size))
198                 return -EFBIG;
199         if (lo->lo_offset != offset)
200                 lo->lo_offset = offset;
201         if (lo->lo_sizelimit != sizelimit)
202                 lo->lo_sizelimit = sizelimit;
203         set_capacity(lo->lo_disk, x);
204         bd_set_size(bdev, (loff_t)get_capacity(bdev->bd_disk) << 9);
205         /* let user-space know about the new size */
206         kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, KOBJ_CHANGE);
207         return 0;
208 }
209
210 static inline int
211 lo_do_transfer(struct loop_device *lo, int cmd,
212                struct page *rpage, unsigned roffs,
213                struct page *lpage, unsigned loffs,
214                int size, sector_t rblock)
215 {
216         if (unlikely(!lo->transfer))
217                 return 0;
218
219         return lo->transfer(lo, cmd, rpage, roffs, lpage, loffs, size, rblock);
220 }
221
222 #ifdef CONFIG_AIO
223 static void lo_rw_aio_complete(u64 data, long res)
224 {
225         struct bio *bio = (struct bio *)(uintptr_t)data;
226
227         if (res > 0)
228                 res = 0;
229         else if (res < 0)
230                 res = -EIO;
231
232         bio_endio(bio, res);
233 }
234
235 static int lo_rw_aio(struct loop_device *lo, struct bio *bio)
236 {
237         struct file *file = lo->lo_backing_file;
238         struct kiocb *iocb;
239         unsigned int op;
240         struct iov_iter iter;
241         struct bio_vec *bvec;
242         size_t nr_segs;
243         loff_t pos = ((loff_t) bio->bi_sector << 9) + lo->lo_offset;
244
245         iocb = aio_kernel_alloc(GFP_NOIO);
246         if (!iocb)
247                 return -ENOMEM;
248
249         if (bio_rw(bio) & WRITE)
250                 op = IOCB_CMD_WRITE_ITER;
251         else
252                 op = IOCB_CMD_READ_ITER;
253
254         bvec = bio_iovec_idx(bio, bio->bi_idx);
255         nr_segs = bio_segments(bio);
256         iov_iter_init_bvec(&iter, bvec, nr_segs, bvec_length(bvec, nr_segs), 0);
257         aio_kernel_init_rw(iocb, file, iov_iter_count(&iter), pos);
258         aio_kernel_init_callback(iocb, lo_rw_aio_complete, (u64)(uintptr_t)bio);
259
260         return aio_kernel_submit(iocb, op, &iter);
261 }
262 #endif /* CONFIG_AIO */
263
264 /**
265  * __do_lo_send_write - helper for writing data to a loop device
266  *
267  * This helper just factors out common code between do_lo_send_direct_write()
268  * and do_lo_send_write().
269  */
270 static int __do_lo_send_write(struct file *file,
271                 u8 *buf, const int len, loff_t pos)
272 {
273         ssize_t bw;
274         mm_segment_t old_fs = get_fs();
275
276         file_start_write(file);
277         set_fs(get_ds());
278         bw = file->f_op->write(file, buf, len, &pos);
279         set_fs(old_fs);
280         file_end_write(file);
281         if (likely(bw == len))
282                 return 0;
283         printk(KERN_ERR "loop: Write error at byte offset %llu, length %i.\n",
284                         (unsigned long long)pos, len);
285         if (bw >= 0)
286                 bw = -EIO;
287         return bw;
288 }
289
290 /**
291  * do_lo_send_direct_write - helper for writing data to a loop device
292  *
293  * This is the fast, non-transforming version that does not need double
294  * buffering.
295  */
296 static int do_lo_send_direct_write(struct loop_device *lo,
297                 struct bio_vec *bvec, loff_t pos, struct page *page)
298 {
299         ssize_t bw = __do_lo_send_write(lo->lo_backing_file,
300                         kmap(bvec->bv_page) + bvec->bv_offset,
301                         bvec->bv_len, pos);
302         kunmap(bvec->bv_page);
303         cond_resched();
304         return bw;
305 }
306
307 /**
308  * do_lo_send_write - helper for writing data to a loop device
309  *
310  * This is the slow, transforming version that needs to double buffer the
311  * data as it cannot do the transformations in place without having direct
312  * access to the destination pages of the backing file.
313  */
314 static int do_lo_send_write(struct loop_device *lo, struct bio_vec *bvec,
315                 loff_t pos, struct page *page)
316 {
317         int ret = lo_do_transfer(lo, WRITE, page, 0, bvec->bv_page,
318                         bvec->bv_offset, bvec->bv_len, pos >> 9);
319         if (likely(!ret))
320                 return __do_lo_send_write(lo->lo_backing_file,
321                                 page_address(page), bvec->bv_len,
322                                 pos);
323         printk(KERN_ERR "loop: Transfer error at byte offset %llu, "
324                         "length %i.\n", (unsigned long long)pos, bvec->bv_len);
325         if (ret > 0)
326                 ret = -EIO;
327         return ret;
328 }
329
330 static int lo_send(struct loop_device *lo, struct bio *bio, loff_t pos)
331 {
332         int (*do_lo_send)(struct loop_device *, struct bio_vec *, loff_t,
333                         struct page *page);
334         struct bio_vec *bvec;
335         struct page *page = NULL;
336         int i, ret = 0;
337
338         if (lo->transfer != transfer_none) {
339                 page = alloc_page(GFP_NOIO | __GFP_HIGHMEM);
340                 if (unlikely(!page))
341                         goto fail;
342                 kmap(page);
343                 do_lo_send = do_lo_send_write;
344         } else {
345                 do_lo_send = do_lo_send_direct_write;
346         }
347
348         bio_for_each_segment(bvec, bio, i) {
349                 ret = do_lo_send(lo, bvec, pos, page);
350                 if (ret < 0)
351                         break;
352                 pos += bvec->bv_len;
353         }
354         if (page) {
355                 kunmap(page);
356                 __free_page(page);
357         }
358 out:
359         return ret;
360 fail:
361         printk(KERN_ERR "loop: Failed to allocate temporary page for write.\n");
362         ret = -ENOMEM;
363         goto out;
364 }
365
366 struct lo_read_data {
367         struct loop_device *lo;
368         struct page *page;
369         unsigned offset;
370         int bsize;
371 };
372
373 static int
374 lo_splice_actor(struct pipe_inode_info *pipe, struct pipe_buffer *buf,
375                 struct splice_desc *sd)
376 {
377         struct lo_read_data *p = sd->u.data;
378         struct loop_device *lo = p->lo;
379         struct page *page = buf->page;
380         sector_t IV;
381         int size;
382
383         IV = ((sector_t) page->index << (PAGE_CACHE_SHIFT - 9)) +
384                                                         (buf->offset >> 9);
385         size = sd->len;
386         if (size > p->bsize)
387                 size = p->bsize;
388
389         if (lo_do_transfer(lo, READ, page, buf->offset, p->page, p->offset, size, IV)) {
390                 printk(KERN_ERR "loop: transfer error block %ld\n",
391                        page->index);
392                 size = -EINVAL;
393         }
394
395         flush_dcache_page(p->page);
396
397         if (size > 0)
398                 p->offset += size;
399
400         return size;
401 }
402
403 static int
404 lo_direct_splice_actor(struct pipe_inode_info *pipe, struct splice_desc *sd)
405 {
406         return __splice_from_pipe(pipe, sd, lo_splice_actor);
407 }
408
409 static ssize_t
410 do_lo_receive(struct loop_device *lo,
411               struct bio_vec *bvec, int bsize, loff_t pos)
412 {
413         struct lo_read_data cookie;
414         struct splice_desc sd;
415         struct file *file;
416         ssize_t retval;
417
418         cookie.lo = lo;
419         cookie.page = bvec->bv_page;
420         cookie.offset = bvec->bv_offset;
421         cookie.bsize = bsize;
422
423         sd.len = 0;
424         sd.total_len = bvec->bv_len;
425         sd.flags = 0;
426         sd.pos = pos;
427         sd.u.data = &cookie;
428
429         file = lo->lo_backing_file;
430         retval = splice_direct_to_actor(file, &sd, lo_direct_splice_actor);
431
432         return retval;
433 }
434
435 static int
436 lo_receive(struct loop_device *lo, struct bio *bio, int bsize, loff_t pos)
437 {
438         struct bio_vec *bvec;
439         ssize_t s;
440         int i;
441
442         bio_for_each_segment(bvec, bio, i) {
443                 s = do_lo_receive(lo, bvec, bsize, pos);
444                 if (s < 0)
445                         return s;
446
447                 if (s != bvec->bv_len) {
448                         zero_fill_bio(bio);
449                         break;
450                 }
451                 pos += bvec->bv_len;
452         }
453         return 0;
454 }
455
456 static int do_bio_filebacked(struct loop_device *lo, struct bio *bio)
457 {
458         loff_t pos;
459         int ret;
460
461         pos = ((loff_t) bio->bi_sector << 9) + lo->lo_offset;
462
463         if (bio_rw(bio) == WRITE) {
464                 ret = lo_send(lo, bio, pos);
465         } else
466                 ret = lo_receive(lo, bio, lo->lo_blocksize, pos);
467
468         return ret;
469 }
470
471 static int lo_discard(struct loop_device *lo, struct bio *bio)
472 {
473         struct file *file = lo->lo_backing_file;
474         int mode = FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE;
475         loff_t pos = ((loff_t) bio->bi_sector << 9) + lo->lo_offset;
476         int ret;
477
478         /*
479          * We use punch hole to reclaim the free space used by the
480          * image a.k.a. discard. However we do not support discard if
481          * encryption is enabled, because it may give an attacker
482          * useful information.
483          */
484
485         if ((!file->f_op->fallocate) || lo->lo_encrypt_key_size)
486                 return -EOPNOTSUPP;
487
488         ret = file->f_op->fallocate(file, mode, pos, bio->bi_size);
489         if (unlikely(ret && ret != -EINVAL && ret != -EOPNOTSUPP))
490                 ret = -EIO;
491         return ret;
492 }
493
494 /*
495  * Add bio to back of pending list
496  */
497 static void loop_add_bio(struct loop_device *lo, struct bio *bio)
498 {
499         lo->lo_bio_count++;
500         bio_list_add(&lo->lo_bio_list, bio);
501 }
502
503 /*
504  * Grab first pending buffer
505  */
506 static struct bio *loop_get_bio(struct loop_device *lo)
507 {
508         lo->lo_bio_count--;
509         return bio_list_pop(&lo->lo_bio_list);
510 }
511
512 static void loop_make_request(struct request_queue *q, struct bio *old_bio)
513 {
514         struct loop_device *lo = q->queuedata;
515         int rw = bio_rw(old_bio);
516
517         if (rw == READA)
518                 rw = READ;
519
520         BUG_ON(!lo || (rw != READ && rw != WRITE));
521
522         spin_lock_irq(&lo->lo_lock);
523         if (lo->lo_state != Lo_bound)
524                 goto out;
525         if (unlikely(rw == WRITE && (lo->lo_flags & LO_FLAGS_READ_ONLY)))
526                 goto out;
527         if (lo->lo_bio_count >= q->nr_congestion_on)
528                 wait_event_lock_irq(lo->lo_req_wait,
529                                     lo->lo_bio_count < q->nr_congestion_off,
530                                     lo->lo_lock);
531         loop_add_bio(lo, old_bio);
532         wake_up(&lo->lo_event);
533         spin_unlock_irq(&lo->lo_lock);
534         return;
535
536 out:
537         spin_unlock_irq(&lo->lo_lock);
538         bio_io_error(old_bio);
539 }
540
541 struct switch_request {
542         struct file *file;
543         struct completion wait;
544 };
545
546 static void do_loop_switch(struct loop_device *, struct switch_request *);
547
548 static inline void loop_handle_bio(struct loop_device *lo, struct bio *bio)
549 {
550         if (unlikely(!bio->bi_bdev)) {
551                 do_loop_switch(lo, bio->bi_private);
552                 bio_put(bio);
553         } else {
554                 int ret;
555
556                 if (bio_rw(bio) == WRITE) {
557                         if (bio->bi_rw & REQ_FLUSH) {
558                                 ret = vfs_fsync(lo->lo_backing_file, 1);
559                                 if (unlikely(ret && ret != -EINVAL))
560                                         goto out;
561                         }
562                         if (bio->bi_rw & REQ_DISCARD) {
563                                 ret = lo_discard(lo, bio);
564                                 goto out;
565                         }
566                 }
567 #ifdef CONFIG_AIO
568                 if (lo->lo_flags & LO_FLAGS_USE_AIO &&
569                     lo->transfer == transfer_none) {
570                         ret = lo_rw_aio(lo, bio);
571                         if (ret == 0)
572                                 return;
573                 } else
574 #endif
575                         ret = do_bio_filebacked(lo, bio);
576
577                 if ((bio_rw(bio) == WRITE) && bio->bi_rw & REQ_FUA && !ret) {
578                         ret = vfs_fsync(lo->lo_backing_file, 0);
579                         if (unlikely(ret && ret != -EINVAL))
580                                 ret = -EIO;
581                 }
582 out:
583                 bio_endio(bio, ret);
584         }
585 }
586
587 /*
588  * worker thread that handles reads/writes to file backed loop devices,
589  * to avoid blocking in our make_request_fn. it also does loop decrypting
590  * on reads for block backed loop, as that is too heavy to do from
591  * b_end_io context where irqs may be disabled.
592  *
593  * Loop explanation:  loop_clr_fd() sets lo_state to Lo_rundown before
594  * calling kthread_stop().  Therefore once kthread_should_stop() is
595  * true, make_request will not place any more requests.  Therefore
596  * once kthread_should_stop() is true and lo_bio is NULL, we are
597  * done with the loop.
598  */
599 static int loop_thread(void *data)
600 {
601         struct loop_device *lo = data;
602         struct bio *bio;
603
604         /*
605          * In cases where the underlying filesystem calls balance_dirty_pages()
606          * we want less throttling to avoid lock ups trying to write dirty
607          * pages through the loop device
608          */
609         current->flags |= PF_LESS_THROTTLE;
610         set_user_nice(current, -20);
611
612         while (!kthread_should_stop() || !bio_list_empty(&lo->lo_bio_list)) {
613
614                 wait_event_interruptible(lo->lo_event,
615                                 !bio_list_empty(&lo->lo_bio_list) ||
616                                 kthread_should_stop());
617
618                 if (bio_list_empty(&lo->lo_bio_list))
619                         continue;
620                 spin_lock_irq(&lo->lo_lock);
621                 bio = loop_get_bio(lo);
622                 if (lo->lo_bio_count < lo->lo_queue->nr_congestion_off)
623                         wake_up(&lo->lo_req_wait);
624                 spin_unlock_irq(&lo->lo_lock);
625
626                 BUG_ON(!bio);
627                 loop_handle_bio(lo, bio);
628         }
629
630         return 0;
631 }
632
633 /*
634  * loop_switch performs the hard work of switching a backing store.
635  * First it needs to flush existing IO, it does this by sending a magic
636  * BIO down the pipe. The completion of this BIO does the actual switch.
637  */
638 static int loop_switch(struct loop_device *lo, struct file *file)
639 {
640         struct switch_request w;
641         struct bio *bio = bio_alloc(GFP_KERNEL, 0);
642         if (!bio)
643                 return -ENOMEM;
644         init_completion(&w.wait);
645         w.file = file;
646         bio->bi_private = &w;
647         bio->bi_bdev = NULL;
648         loop_make_request(lo->lo_queue, bio);
649         wait_for_completion(&w.wait);
650         return 0;
651 }
652
653 /*
654  * Helper to flush the IOs in loop, but keeping loop thread running
655  */
656 static int loop_flush(struct loop_device *lo)
657 {
658         /* loop not yet configured, no running thread, nothing to flush */
659         if (!lo->lo_thread)
660                 return 0;
661
662         return loop_switch(lo, NULL);
663 }
664
665 /*
666  * Do the actual switch; called from the BIO completion routine
667  */
668 static void do_loop_switch(struct loop_device *lo, struct switch_request *p)
669 {
670         struct file *file = p->file;
671         struct file *old_file = lo->lo_backing_file;
672         struct address_space *mapping;
673
674         /* if no new file, only flush of queued bios requested */
675         if (!file)
676                 goto out;
677
678         mapping = file->f_mapping;
679         mapping_set_gfp_mask(old_file->f_mapping, lo->old_gfp_mask);
680         lo->lo_backing_file = file;
681         lo->lo_blocksize = S_ISBLK(mapping->host->i_mode) ?
682                 mapping->host->i_bdev->bd_block_size : PAGE_SIZE;
683         lo->old_gfp_mask = mapping_gfp_mask(mapping);
684         mapping_set_gfp_mask(mapping, lo->old_gfp_mask & ~(__GFP_IO|__GFP_FS));
685 out:
686         complete(&p->wait);
687 }
688
689
690 /*
691  * loop_change_fd switched the backing store of a loopback device to
692  * a new file. This is useful for operating system installers to free up
693  * the original file and in High Availability environments to switch to
694  * an alternative location for the content in case of server meltdown.
695  * This can only work if the loop device is used read-only, and if the
696  * new backing store is the same size and type as the old backing store.
697  */
698 static int loop_change_fd(struct loop_device *lo, struct block_device *bdev,
699                           unsigned int arg)
700 {
701         struct file     *file, *old_file;
702         struct inode    *inode;
703         int             error;
704
705         error = -ENXIO;
706         if (lo->lo_state != Lo_bound)
707                 goto out;
708
709         /* the loop device has to be read-only */
710         error = -EINVAL;
711         if (!(lo->lo_flags & LO_FLAGS_READ_ONLY))
712                 goto out;
713
714         error = -EBADF;
715         file = fget(arg);
716         if (!file)
717                 goto out;
718
719         inode = file->f_mapping->host;
720         old_file = lo->lo_backing_file;
721
722         error = -EINVAL;
723
724         if (!S_ISREG(inode->i_mode) && !S_ISBLK(inode->i_mode))
725                 goto out_putf;
726
727         /* size of the new backing store needs to be the same */
728         if (get_loop_size(lo, file) != get_loop_size(lo, old_file))
729                 goto out_putf;
730
731         /* and ... switch */
732         error = loop_switch(lo, file);
733         if (error)
734                 goto out_putf;
735
736         fput(old_file);
737         if (lo->lo_flags & LO_FLAGS_PARTSCAN)
738                 ioctl_by_bdev(bdev, BLKRRPART, 0);
739         return 0;
740
741  out_putf:
742         fput(file);
743  out:
744         return error;
745 }
746
747 static inline int is_loop_device(struct file *file)
748 {
749         struct inode *i = file->f_mapping->host;
750
751         return i && S_ISBLK(i->i_mode) && MAJOR(i->i_rdev) == LOOP_MAJOR;
752 }
753
754 /* loop sysfs attributes */
755
756 static ssize_t loop_attr_show(struct device *dev, char *page,
757                               ssize_t (*callback)(struct loop_device *, char *))
758 {
759         struct gendisk *disk = dev_to_disk(dev);
760         struct loop_device *lo = disk->private_data;
761
762         return callback(lo, page);
763 }
764
765 #define LOOP_ATTR_RO(_name)                                             \
766 static ssize_t loop_attr_##_name##_show(struct loop_device *, char *);  \
767 static ssize_t loop_attr_do_show_##_name(struct device *d,              \
768                                 struct device_attribute *attr, char *b) \
769 {                                                                       \
770         return loop_attr_show(d, b, loop_attr_##_name##_show);          \
771 }                                                                       \
772 static struct device_attribute loop_attr_##_name =                      \
773         __ATTR(_name, S_IRUGO, loop_attr_do_show_##_name, NULL);
774
775 static ssize_t loop_attr_backing_file_show(struct loop_device *lo, char *buf)
776 {
777         ssize_t ret;
778         char *p = NULL;
779
780         spin_lock_irq(&lo->lo_lock);
781         if (lo->lo_backing_file)
782                 p = d_path(&lo->lo_backing_file->f_path, buf, PAGE_SIZE - 1);
783         spin_unlock_irq(&lo->lo_lock);
784
785         if (IS_ERR_OR_NULL(p))
786                 ret = PTR_ERR(p);
787         else {
788                 ret = strlen(p);
789                 memmove(buf, p, ret);
790                 buf[ret++] = '\n';
791                 buf[ret] = 0;
792         }
793
794         return ret;
795 }
796
797 static ssize_t loop_attr_offset_show(struct loop_device *lo, char *buf)
798 {
799         return sprintf(buf, "%llu\n", (unsigned long long)lo->lo_offset);
800 }
801
802 static ssize_t loop_attr_sizelimit_show(struct loop_device *lo, char *buf)
803 {
804         return sprintf(buf, "%llu\n", (unsigned long long)lo->lo_sizelimit);
805 }
806
807 static ssize_t loop_attr_autoclear_show(struct loop_device *lo, char *buf)
808 {
809         int autoclear = (lo->lo_flags & LO_FLAGS_AUTOCLEAR);
810
811         return sprintf(buf, "%s\n", autoclear ? "1" : "0");
812 }
813
814 static ssize_t loop_attr_partscan_show(struct loop_device *lo, char *buf)
815 {
816         int partscan = (lo->lo_flags & LO_FLAGS_PARTSCAN);
817
818         return sprintf(buf, "%s\n", partscan ? "1" : "0");
819 }
820
821 LOOP_ATTR_RO(backing_file);
822 LOOP_ATTR_RO(offset);
823 LOOP_ATTR_RO(sizelimit);
824 LOOP_ATTR_RO(autoclear);
825 LOOP_ATTR_RO(partscan);
826
827 static struct attribute *loop_attrs[] = {
828         &loop_attr_backing_file.attr,
829         &loop_attr_offset.attr,
830         &loop_attr_sizelimit.attr,
831         &loop_attr_autoclear.attr,
832         &loop_attr_partscan.attr,
833         NULL,
834 };
835
836 static struct attribute_group loop_attribute_group = {
837         .name = "loop",
838         .attrs= loop_attrs,
839 };
840
841 static int loop_sysfs_init(struct loop_device *lo)
842 {
843         return sysfs_create_group(&disk_to_dev(lo->lo_disk)->kobj,
844                                   &loop_attribute_group);
845 }
846
847 static void loop_sysfs_exit(struct loop_device *lo)
848 {
849         sysfs_remove_group(&disk_to_dev(lo->lo_disk)->kobj,
850                            &loop_attribute_group);
851 }
852
853 static void loop_config_discard(struct loop_device *lo)
854 {
855         struct file *file = lo->lo_backing_file;
856         struct inode *inode = file->f_mapping->host;
857         struct request_queue *q = lo->lo_queue;
858
859         /*
860          * We use punch hole to reclaim the free space used by the
861          * image a.k.a. discard. However we do support discard if
862          * encryption is enabled, because it may give an attacker
863          * useful information.
864          */
865         if ((!file->f_op->fallocate) ||
866             lo->lo_encrypt_key_size) {
867                 q->limits.discard_granularity = 0;
868                 q->limits.discard_alignment = 0;
869                 q->limits.max_discard_sectors = 0;
870                 q->limits.discard_zeroes_data = 0;
871                 queue_flag_clear_unlocked(QUEUE_FLAG_DISCARD, q);
872                 return;
873         }
874
875         q->limits.discard_granularity = inode->i_sb->s_blocksize;
876         q->limits.discard_alignment = 0;
877         q->limits.max_discard_sectors = UINT_MAX >> 9;
878         q->limits.discard_zeroes_data = 1;
879         queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, q);
880 }
881
882 static int loop_set_fd(struct loop_device *lo, fmode_t mode,
883                        struct block_device *bdev, unsigned int arg)
884 {
885         struct file     *file, *f;
886         struct inode    *inode;
887         struct address_space *mapping;
888         unsigned lo_blocksize;
889         int             lo_flags = 0;
890         int             error;
891         loff_t          size;
892
893         /* This is safe, since we have a reference from open(). */
894         __module_get(THIS_MODULE);
895
896         error = -EBADF;
897         file = fget(arg);
898         if (!file)
899                 goto out;
900
901         error = -EBUSY;
902         if (lo->lo_state != Lo_unbound)
903                 goto out_putf;
904
905         /* Avoid recursion */
906         f = file;
907         while (is_loop_device(f)) {
908                 struct loop_device *l;
909
910                 if (f->f_mapping->host->i_bdev == bdev)
911                         goto out_putf;
912
913                 l = f->f_mapping->host->i_bdev->bd_disk->private_data;
914                 if (l->lo_state == Lo_unbound) {
915                         error = -EINVAL;
916                         goto out_putf;
917                 }
918                 f = l->lo_backing_file;
919         }
920
921         mapping = file->f_mapping;
922         inode = mapping->host;
923
924         error = -EINVAL;
925         if (!S_ISREG(inode->i_mode) && !S_ISBLK(inode->i_mode))
926                 goto out_putf;
927
928         if (!(file->f_mode & FMODE_WRITE) || !(mode & FMODE_WRITE) ||
929             !file->f_op->write)
930                 lo_flags |= LO_FLAGS_READ_ONLY;
931
932 #ifdef CONFIG_AIO
933         if (file->f_op->write_iter && file->f_op->read_iter &&
934             mapping->a_ops->direct_IO) {
935                 file->f_flags |= O_DIRECT;
936                 lo_flags |= LO_FLAGS_USE_AIO;
937         }
938 #endif
939
940         lo_blocksize = S_ISBLK(inode->i_mode) ?
941                 inode->i_bdev->bd_block_size : PAGE_SIZE;
942
943         error = -EFBIG;
944         size = get_loop_size(lo, file);
945         if ((loff_t)(sector_t)size != size)
946                 goto out_putf;
947
948         error = 0;
949
950         set_device_ro(bdev, (lo_flags & LO_FLAGS_READ_ONLY) != 0);
951
952         lo->lo_blocksize = lo_blocksize;
953         lo->lo_device = bdev;
954         lo->lo_flags = lo_flags;
955         lo->lo_backing_file = file;
956         lo->transfer = transfer_none;
957         lo->ioctl = NULL;
958         lo->lo_sizelimit = 0;
959         lo->lo_bio_count = 0;
960         lo->old_gfp_mask = mapping_gfp_mask(mapping);
961         mapping_set_gfp_mask(mapping, lo->old_gfp_mask & ~(__GFP_IO|__GFP_FS));
962
963         bio_list_init(&lo->lo_bio_list);
964
965         if (!(lo_flags & LO_FLAGS_READ_ONLY) && file->f_op->fsync)
966                 blk_queue_flush(lo->lo_queue, REQ_FLUSH);
967
968         set_capacity(lo->lo_disk, size);
969         bd_set_size(bdev, size << 9);
970         loop_sysfs_init(lo);
971         /* let user-space know about the new size */
972         kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, KOBJ_CHANGE);
973
974         set_blocksize(bdev, lo_blocksize);
975
976 #ifdef CONFIG_AIO
977         /*
978          * We must not send too-small direct-io requests, so we inherit
979          * the logical block size from the underlying device
980          */
981         if ((lo_flags & LO_FLAGS_USE_AIO) && inode->i_sb->s_bdev)
982                 blk_queue_logical_block_size(lo->lo_queue,
983                                 bdev_logical_block_size(inode->i_sb->s_bdev));
984 #endif
985
986         lo->lo_thread = kthread_create(loop_thread, lo, "loop%d",
987                                                 lo->lo_number);
988         if (IS_ERR(lo->lo_thread)) {
989                 error = PTR_ERR(lo->lo_thread);
990                 goto out_clr;
991         }
992         lo->lo_state = Lo_bound;
993         wake_up_process(lo->lo_thread);
994         if (part_shift)
995                 lo->lo_flags |= LO_FLAGS_PARTSCAN;
996         if (lo->lo_flags & LO_FLAGS_PARTSCAN)
997                 ioctl_by_bdev(bdev, BLKRRPART, 0);
998
999         /* Grab the block_device to prevent its destruction after we
1000          * put /dev/loopXX inode. Later in loop_clr_fd() we bdput(bdev).
1001          */
1002         bdgrab(bdev);
1003         return 0;
1004
1005 out_clr:
1006         loop_sysfs_exit(lo);
1007         lo->lo_thread = NULL;
1008         lo->lo_device = NULL;
1009         lo->lo_backing_file = NULL;
1010         lo->lo_flags = 0;
1011         set_capacity(lo->lo_disk, 0);
1012         invalidate_bdev(bdev);
1013         bd_set_size(bdev, 0);
1014         kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, KOBJ_CHANGE);
1015         mapping_set_gfp_mask(mapping, lo->old_gfp_mask);
1016         lo->lo_state = Lo_unbound;
1017  out_putf:
1018         fput(file);
1019  out:
1020         /* This is safe: open() is still holding a reference. */
1021         module_put(THIS_MODULE);
1022         return error;
1023 }
1024
1025 static int
1026 loop_release_xfer(struct loop_device *lo)
1027 {
1028         int err = 0;
1029         struct loop_func_table *xfer = lo->lo_encryption;
1030
1031         if (xfer) {
1032                 if (xfer->release)
1033                         err = xfer->release(lo);
1034                 lo->transfer = NULL;
1035                 lo->lo_encryption = NULL;
1036                 module_put(xfer->owner);
1037         }
1038         return err;
1039 }
1040
1041 static int
1042 loop_init_xfer(struct loop_device *lo, struct loop_func_table *xfer,
1043                const struct loop_info64 *i)
1044 {
1045         int err = 0;
1046
1047         if (xfer) {
1048                 struct module *owner = xfer->owner;
1049
1050                 if (!try_module_get(owner))
1051                         return -EINVAL;
1052                 if (xfer->init)
1053                         err = xfer->init(lo, i);
1054                 if (err)
1055                         module_put(owner);
1056                 else
1057                         lo->lo_encryption = xfer;
1058         }
1059         return err;
1060 }
1061
1062 static int loop_clr_fd(struct loop_device *lo)
1063 {
1064         struct file *filp = lo->lo_backing_file;
1065         gfp_t gfp = lo->old_gfp_mask;
1066         struct block_device *bdev = lo->lo_device;
1067
1068         if (lo->lo_state != Lo_bound)
1069                 return -ENXIO;
1070
1071         /*
1072          * If we've explicitly asked to tear down the loop device,
1073          * and it has an elevated reference count, set it for auto-teardown when
1074          * the last reference goes away. This stops $!~#$@ udev from
1075          * preventing teardown because it decided that it needs to run blkid on
1076          * the loopback device whenever they appear. xfstests is notorious for
1077          * failing tests because blkid via udev races with a losetup
1078          * <dev>/do something like mkfs/losetup -d <dev> causing the losetup -d
1079          * command to fail with EBUSY.
1080          */
1081         if (lo->lo_refcnt > 1) {
1082                 lo->lo_flags |= LO_FLAGS_AUTOCLEAR;
1083                 mutex_unlock(&lo->lo_ctl_mutex);
1084                 return 0;
1085         }
1086
1087         if (filp == NULL)
1088                 return -EINVAL;
1089
1090         spin_lock_irq(&lo->lo_lock);
1091         lo->lo_state = Lo_rundown;
1092         spin_unlock_irq(&lo->lo_lock);
1093
1094         kthread_stop(lo->lo_thread);
1095
1096         spin_lock_irq(&lo->lo_lock);
1097         lo->lo_backing_file = NULL;
1098         spin_unlock_irq(&lo->lo_lock);
1099
1100         loop_release_xfer(lo);
1101         lo->transfer = NULL;
1102         lo->ioctl = NULL;
1103         lo->lo_device = NULL;
1104         lo->lo_encryption = NULL;
1105         lo->lo_offset = 0;
1106         lo->lo_sizelimit = 0;
1107         lo->lo_encrypt_key_size = 0;
1108         lo->lo_thread = NULL;
1109         memset(lo->lo_encrypt_key, 0, LO_KEY_SIZE);
1110         memset(lo->lo_crypt_name, 0, LO_NAME_SIZE);
1111         memset(lo->lo_file_name, 0, LO_NAME_SIZE);
1112         if (bdev) {
1113                 bdput(bdev);
1114                 invalidate_bdev(bdev);
1115         }
1116         set_capacity(lo->lo_disk, 0);
1117         loop_sysfs_exit(lo);
1118         if (bdev) {
1119                 bd_set_size(bdev, 0);
1120                 /* let user-space know about this change */
1121                 kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, KOBJ_CHANGE);
1122         }
1123         mapping_set_gfp_mask(filp->f_mapping, gfp);
1124         lo->lo_state = Lo_unbound;
1125         /* This is safe: open() is still holding a reference. */
1126         module_put(THIS_MODULE);
1127         if (lo->lo_flags & LO_FLAGS_PARTSCAN && bdev)
1128                 ioctl_by_bdev(bdev, BLKRRPART, 0);
1129         lo->lo_flags = 0;
1130         if (!part_shift)
1131                 lo->lo_disk->flags |= GENHD_FL_NO_PART_SCAN;
1132         mutex_unlock(&lo->lo_ctl_mutex);
1133         /*
1134          * Need not hold lo_ctl_mutex to fput backing file.
1135          * Calling fput holding lo_ctl_mutex triggers a circular
1136          * lock dependency possibility warning as fput can take
1137          * bd_mutex which is usually taken before lo_ctl_mutex.
1138          */
1139         fput(filp);
1140         return 0;
1141 }
1142
1143 static int
1144 loop_set_status(struct loop_device *lo, const struct loop_info64 *info)
1145 {
1146         int err;
1147         struct loop_func_table *xfer;
1148         kuid_t uid = current_uid();
1149
1150         if (lo->lo_encrypt_key_size &&
1151             !uid_eq(lo->lo_key_owner, uid) &&
1152             !capable(CAP_SYS_ADMIN))
1153                 return -EPERM;
1154         if (lo->lo_state != Lo_bound)
1155                 return -ENXIO;
1156         if ((unsigned int) info->lo_encrypt_key_size > LO_KEY_SIZE)
1157                 return -EINVAL;
1158
1159         err = loop_release_xfer(lo);
1160         if (err)
1161                 return err;
1162
1163         if (info->lo_encrypt_type) {
1164                 unsigned int type = info->lo_encrypt_type;
1165
1166                 if (type >= MAX_LO_CRYPT)
1167                         return -EINVAL;
1168                 xfer = xfer_funcs[type];
1169                 if (xfer == NULL)
1170                         return -EINVAL;
1171         } else
1172                 xfer = NULL;
1173
1174         err = loop_init_xfer(lo, xfer, info);
1175         if (err)
1176                 return err;
1177
1178         if (lo->lo_offset != info->lo_offset ||
1179             lo->lo_sizelimit != info->lo_sizelimit)
1180                 if (figure_loop_size(lo, info->lo_offset, info->lo_sizelimit))
1181                         return -EFBIG;
1182
1183         loop_config_discard(lo);
1184
1185         memcpy(lo->lo_file_name, info->lo_file_name, LO_NAME_SIZE);
1186         memcpy(lo->lo_crypt_name, info->lo_crypt_name, LO_NAME_SIZE);
1187         lo->lo_file_name[LO_NAME_SIZE-1] = 0;
1188         lo->lo_crypt_name[LO_NAME_SIZE-1] = 0;
1189
1190         if (!xfer)
1191                 xfer = &none_funcs;
1192         lo->transfer = xfer->transfer;
1193         lo->ioctl = xfer->ioctl;
1194
1195         if ((lo->lo_flags & LO_FLAGS_AUTOCLEAR) !=
1196              (info->lo_flags & LO_FLAGS_AUTOCLEAR))
1197                 lo->lo_flags ^= LO_FLAGS_AUTOCLEAR;
1198
1199         if ((info->lo_flags & LO_FLAGS_PARTSCAN) &&
1200              !(lo->lo_flags & LO_FLAGS_PARTSCAN)) {
1201                 lo->lo_flags |= LO_FLAGS_PARTSCAN;
1202                 lo->lo_disk->flags &= ~GENHD_FL_NO_PART_SCAN;
1203                 ioctl_by_bdev(lo->lo_device, BLKRRPART, 0);
1204         }
1205
1206         lo->lo_encrypt_key_size = info->lo_encrypt_key_size;
1207         lo->lo_init[0] = info->lo_init[0];
1208         lo->lo_init[1] = info->lo_init[1];
1209         if (info->lo_encrypt_key_size) {
1210                 memcpy(lo->lo_encrypt_key, info->lo_encrypt_key,
1211                        info->lo_encrypt_key_size);
1212                 lo->lo_key_owner = uid;
1213         }       
1214
1215         return 0;
1216 }
1217
1218 static int
1219 loop_get_status(struct loop_device *lo, struct loop_info64 *info)
1220 {
1221         struct file *file = lo->lo_backing_file;
1222         struct kstat stat;
1223         int error;
1224
1225         if (lo->lo_state != Lo_bound)
1226                 return -ENXIO;
1227         error = vfs_getattr(&file->f_path, &stat);
1228         if (error)
1229                 return error;
1230         memset(info, 0, sizeof(*info));
1231         info->lo_number = lo->lo_number;
1232         info->lo_device = huge_encode_dev(stat.dev);
1233         info->lo_inode = stat.ino;
1234         info->lo_rdevice = huge_encode_dev(lo->lo_device ? stat.rdev : stat.dev);
1235         info->lo_offset = lo->lo_offset;
1236         info->lo_sizelimit = lo->lo_sizelimit;
1237         info->lo_flags = lo->lo_flags;
1238         memcpy(info->lo_file_name, lo->lo_file_name, LO_NAME_SIZE);
1239         memcpy(info->lo_crypt_name, lo->lo_crypt_name, LO_NAME_SIZE);
1240         info->lo_encrypt_type =
1241                 lo->lo_encryption ? lo->lo_encryption->number : 0;
1242         if (lo->lo_encrypt_key_size && capable(CAP_SYS_ADMIN)) {
1243                 info->lo_encrypt_key_size = lo->lo_encrypt_key_size;
1244                 memcpy(info->lo_encrypt_key, lo->lo_encrypt_key,
1245                        lo->lo_encrypt_key_size);
1246         }
1247         return 0;
1248 }
1249
1250 static void
1251 loop_info64_from_old(const struct loop_info *info, struct loop_info64 *info64)
1252 {
1253         memset(info64, 0, sizeof(*info64));
1254         info64->lo_number = info->lo_number;
1255         info64->lo_device = info->lo_device;
1256         info64->lo_inode = info->lo_inode;
1257         info64->lo_rdevice = info->lo_rdevice;
1258         info64->lo_offset = info->lo_offset;
1259         info64->lo_sizelimit = 0;
1260         info64->lo_encrypt_type = info->lo_encrypt_type;
1261         info64->lo_encrypt_key_size = info->lo_encrypt_key_size;
1262         info64->lo_flags = info->lo_flags;
1263         info64->lo_init[0] = info->lo_init[0];
1264         info64->lo_init[1] = info->lo_init[1];
1265         if (info->lo_encrypt_type == LO_CRYPT_CRYPTOAPI)
1266                 memcpy(info64->lo_crypt_name, info->lo_name, LO_NAME_SIZE);
1267         else
1268                 memcpy(info64->lo_file_name, info->lo_name, LO_NAME_SIZE);
1269         memcpy(info64->lo_encrypt_key, info->lo_encrypt_key, LO_KEY_SIZE);
1270 }
1271
1272 static int
1273 loop_info64_to_old(const struct loop_info64 *info64, struct loop_info *info)
1274 {
1275         memset(info, 0, sizeof(*info));
1276         info->lo_number = info64->lo_number;
1277         info->lo_device = info64->lo_device;
1278         info->lo_inode = info64->lo_inode;
1279         info->lo_rdevice = info64->lo_rdevice;
1280         info->lo_offset = info64->lo_offset;
1281         info->lo_encrypt_type = info64->lo_encrypt_type;
1282         info->lo_encrypt_key_size = info64->lo_encrypt_key_size;
1283         info->lo_flags = info64->lo_flags;
1284         info->lo_init[0] = info64->lo_init[0];
1285         info->lo_init[1] = info64->lo_init[1];
1286         if (info->lo_encrypt_type == LO_CRYPT_CRYPTOAPI)
1287                 memcpy(info->lo_name, info64->lo_crypt_name, LO_NAME_SIZE);
1288         else
1289                 memcpy(info->lo_name, info64->lo_file_name, LO_NAME_SIZE);
1290         memcpy(info->lo_encrypt_key, info64->lo_encrypt_key, LO_KEY_SIZE);
1291
1292         /* error in case values were truncated */
1293         if (info->lo_device != info64->lo_device ||
1294             info->lo_rdevice != info64->lo_rdevice ||
1295             info->lo_inode != info64->lo_inode ||
1296             info->lo_offset != info64->lo_offset)
1297                 return -EOVERFLOW;
1298
1299         return 0;
1300 }
1301
1302 static int
1303 loop_set_status_old(struct loop_device *lo, const struct loop_info __user *arg)
1304 {
1305         struct loop_info info;
1306         struct loop_info64 info64;
1307
1308         if (copy_from_user(&info, arg, sizeof (struct loop_info)))
1309                 return -EFAULT;
1310         loop_info64_from_old(&info, &info64);
1311         return loop_set_status(lo, &info64);
1312 }
1313
1314 static int
1315 loop_set_status64(struct loop_device *lo, const struct loop_info64 __user *arg)
1316 {
1317         struct loop_info64 info64;
1318
1319         if (copy_from_user(&info64, arg, sizeof (struct loop_info64)))
1320                 return -EFAULT;
1321         return loop_set_status(lo, &info64);
1322 }
1323
1324 static int
1325 loop_get_status_old(struct loop_device *lo, struct loop_info __user *arg) {
1326         struct loop_info info;
1327         struct loop_info64 info64;
1328         int err = 0;
1329
1330         if (!arg)
1331                 err = -EINVAL;
1332         if (!err)
1333                 err = loop_get_status(lo, &info64);
1334         if (!err)
1335                 err = loop_info64_to_old(&info64, &info);
1336         if (!err && copy_to_user(arg, &info, sizeof(info)))
1337                 err = -EFAULT;
1338
1339         return err;
1340 }
1341
1342 static int
1343 loop_get_status64(struct loop_device *lo, struct loop_info64 __user *arg) {
1344         struct loop_info64 info64;
1345         int err = 0;
1346
1347         if (!arg)
1348                 err = -EINVAL;
1349         if (!err)
1350                 err = loop_get_status(lo, &info64);
1351         if (!err && copy_to_user(arg, &info64, sizeof(info64)))
1352                 err = -EFAULT;
1353
1354         return err;
1355 }
1356
1357 static int loop_set_capacity(struct loop_device *lo, struct block_device *bdev)
1358 {
1359         if (unlikely(lo->lo_state != Lo_bound))
1360                 return -ENXIO;
1361
1362         return figure_loop_size(lo, lo->lo_offset, lo->lo_sizelimit);
1363 }
1364
1365 static int lo_ioctl(struct block_device *bdev, fmode_t mode,
1366         unsigned int cmd, unsigned long arg)
1367 {
1368         struct loop_device *lo = bdev->bd_disk->private_data;
1369         int err;
1370
1371         mutex_lock_nested(&lo->lo_ctl_mutex, 1);
1372         switch (cmd) {
1373         case LOOP_SET_FD:
1374                 err = loop_set_fd(lo, mode, bdev, arg);
1375                 break;
1376         case LOOP_CHANGE_FD:
1377                 err = loop_change_fd(lo, bdev, arg);
1378                 break;
1379         case LOOP_CLR_FD:
1380                 /* loop_clr_fd would have unlocked lo_ctl_mutex on success */
1381                 err = loop_clr_fd(lo);
1382                 if (!err)
1383                         goto out_unlocked;
1384                 break;
1385         case LOOP_SET_STATUS:
1386                 err = -EPERM;
1387                 if ((mode & FMODE_WRITE) || capable(CAP_SYS_ADMIN))
1388                         err = loop_set_status_old(lo,
1389                                         (struct loop_info __user *)arg);
1390                 break;
1391         case LOOP_GET_STATUS:
1392                 err = loop_get_status_old(lo, (struct loop_info __user *) arg);
1393                 break;
1394         case LOOP_SET_STATUS64:
1395                 err = -EPERM;
1396                 if ((mode & FMODE_WRITE) || capable(CAP_SYS_ADMIN))
1397                         err = loop_set_status64(lo,
1398                                         (struct loop_info64 __user *) arg);
1399                 break;
1400         case LOOP_GET_STATUS64:
1401                 err = loop_get_status64(lo, (struct loop_info64 __user *) arg);
1402                 break;
1403         case LOOP_SET_CAPACITY:
1404                 err = -EPERM;
1405                 if ((mode & FMODE_WRITE) || capable(CAP_SYS_ADMIN))
1406                         err = loop_set_capacity(lo, bdev);
1407                 break;
1408         default:
1409                 err = lo->ioctl ? lo->ioctl(lo, cmd, arg) : -EINVAL;
1410         }
1411         mutex_unlock(&lo->lo_ctl_mutex);
1412
1413 out_unlocked:
1414         return err;
1415 }
1416
1417 #ifdef CONFIG_COMPAT
1418 struct compat_loop_info {
1419         compat_int_t    lo_number;      /* ioctl r/o */
1420         compat_dev_t    lo_device;      /* ioctl r/o */
1421         compat_ulong_t  lo_inode;       /* ioctl r/o */
1422         compat_dev_t    lo_rdevice;     /* ioctl r/o */
1423         compat_int_t    lo_offset;
1424         compat_int_t    lo_encrypt_type;
1425         compat_int_t    lo_encrypt_key_size;    /* ioctl w/o */
1426         compat_int_t    lo_flags;       /* ioctl r/o */
1427         char            lo_name[LO_NAME_SIZE];
1428         unsigned char   lo_encrypt_key[LO_KEY_SIZE]; /* ioctl w/o */
1429         compat_ulong_t  lo_init[2];
1430         char            reserved[4];
1431 };
1432
1433 /*
1434  * Transfer 32-bit compatibility structure in userspace to 64-bit loop info
1435  * - noinlined to reduce stack space usage in main part of driver
1436  */
1437 static noinline int
1438 loop_info64_from_compat(const struct compat_loop_info __user *arg,
1439                         struct loop_info64 *info64)
1440 {
1441         struct compat_loop_info info;
1442
1443         if (copy_from_user(&info, arg, sizeof(info)))
1444                 return -EFAULT;
1445
1446         memset(info64, 0, sizeof(*info64));
1447         info64->lo_number = info.lo_number;
1448         info64->lo_device = info.lo_device;
1449         info64->lo_inode = info.lo_inode;
1450         info64->lo_rdevice = info.lo_rdevice;
1451         info64->lo_offset = info.lo_offset;
1452         info64->lo_sizelimit = 0;
1453         info64->lo_encrypt_type = info.lo_encrypt_type;
1454         info64->lo_encrypt_key_size = info.lo_encrypt_key_size;
1455         info64->lo_flags = info.lo_flags;
1456         info64->lo_init[0] = info.lo_init[0];
1457         info64->lo_init[1] = info.lo_init[1];
1458         if (info.lo_encrypt_type == LO_CRYPT_CRYPTOAPI)
1459                 memcpy(info64->lo_crypt_name, info.lo_name, LO_NAME_SIZE);
1460         else
1461                 memcpy(info64->lo_file_name, info.lo_name, LO_NAME_SIZE);
1462         memcpy(info64->lo_encrypt_key, info.lo_encrypt_key, LO_KEY_SIZE);
1463         return 0;
1464 }
1465
1466 /*
1467  * Transfer 64-bit loop info to 32-bit compatibility structure in userspace
1468  * - noinlined to reduce stack space usage in main part of driver
1469  */
1470 static noinline int
1471 loop_info64_to_compat(const struct loop_info64 *info64,
1472                       struct compat_loop_info __user *arg)
1473 {
1474         struct compat_loop_info info;
1475
1476         memset(&info, 0, sizeof(info));
1477         info.lo_number = info64->lo_number;
1478         info.lo_device = info64->lo_device;
1479         info.lo_inode = info64->lo_inode;
1480         info.lo_rdevice = info64->lo_rdevice;
1481         info.lo_offset = info64->lo_offset;
1482         info.lo_encrypt_type = info64->lo_encrypt_type;
1483         info.lo_encrypt_key_size = info64->lo_encrypt_key_size;
1484         info.lo_flags = info64->lo_flags;
1485         info.lo_init[0] = info64->lo_init[0];
1486         info.lo_init[1] = info64->lo_init[1];
1487         if (info.lo_encrypt_type == LO_CRYPT_CRYPTOAPI)
1488                 memcpy(info.lo_name, info64->lo_crypt_name, LO_NAME_SIZE);
1489         else
1490                 memcpy(info.lo_name, info64->lo_file_name, LO_NAME_SIZE);
1491         memcpy(info.lo_encrypt_key, info64->lo_encrypt_key, LO_KEY_SIZE);
1492
1493         /* error in case values were truncated */
1494         if (info.lo_device != info64->lo_device ||
1495             info.lo_rdevice != info64->lo_rdevice ||
1496             info.lo_inode != info64->lo_inode ||
1497             info.lo_offset != info64->lo_offset ||
1498             info.lo_init[0] != info64->lo_init[0] ||
1499             info.lo_init[1] != info64->lo_init[1])
1500                 return -EOVERFLOW;
1501
1502         if (copy_to_user(arg, &info, sizeof(info)))
1503                 return -EFAULT;
1504         return 0;
1505 }
1506
1507 static int
1508 loop_set_status_compat(struct loop_device *lo,
1509                        const struct compat_loop_info __user *arg)
1510 {
1511         struct loop_info64 info64;
1512         int ret;
1513
1514         ret = loop_info64_from_compat(arg, &info64);
1515         if (ret < 0)
1516                 return ret;
1517         return loop_set_status(lo, &info64);
1518 }
1519
1520 static int
1521 loop_get_status_compat(struct loop_device *lo,
1522                        struct compat_loop_info __user *arg)
1523 {
1524         struct loop_info64 info64;
1525         int err = 0;
1526
1527         if (!arg)
1528                 err = -EINVAL;
1529         if (!err)
1530                 err = loop_get_status(lo, &info64);
1531         if (!err)
1532                 err = loop_info64_to_compat(&info64, arg);
1533         return err;
1534 }
1535
1536 static int lo_compat_ioctl(struct block_device *bdev, fmode_t mode,
1537                            unsigned int cmd, unsigned long arg)
1538 {
1539         struct loop_device *lo = bdev->bd_disk->private_data;
1540         int err;
1541
1542         switch(cmd) {
1543         case LOOP_SET_STATUS:
1544                 mutex_lock(&lo->lo_ctl_mutex);
1545                 err = loop_set_status_compat(
1546                         lo, (const struct compat_loop_info __user *) arg);
1547                 mutex_unlock(&lo->lo_ctl_mutex);
1548                 break;
1549         case LOOP_GET_STATUS:
1550                 mutex_lock(&lo->lo_ctl_mutex);
1551                 err = loop_get_status_compat(
1552                         lo, (struct compat_loop_info __user *) arg);
1553                 mutex_unlock(&lo->lo_ctl_mutex);
1554                 break;
1555         case LOOP_SET_CAPACITY:
1556         case LOOP_CLR_FD:
1557         case LOOP_GET_STATUS64:
1558         case LOOP_SET_STATUS64:
1559                 arg = (unsigned long) compat_ptr(arg);
1560         case LOOP_SET_FD:
1561         case LOOP_CHANGE_FD:
1562                 err = lo_ioctl(bdev, mode, cmd, arg);
1563                 break;
1564         default:
1565                 err = -ENOIOCTLCMD;
1566                 break;
1567         }
1568         return err;
1569 }
1570 #endif
1571
1572 static int lo_open(struct block_device *bdev, fmode_t mode)
1573 {
1574         struct loop_device *lo;
1575         int err = 0;
1576
1577         mutex_lock(&loop_index_mutex);
1578         lo = bdev->bd_disk->private_data;
1579         if (!lo) {
1580                 err = -ENXIO;
1581                 goto out;
1582         }
1583
1584         mutex_lock(&lo->lo_ctl_mutex);
1585         lo->lo_refcnt++;
1586         mutex_unlock(&lo->lo_ctl_mutex);
1587 out:
1588         mutex_unlock(&loop_index_mutex);
1589         return err;
1590 }
1591
1592 static void lo_release(struct gendisk *disk, fmode_t mode)
1593 {
1594         struct loop_device *lo = disk->private_data;
1595         int err;
1596
1597         mutex_lock(&lo->lo_ctl_mutex);
1598
1599         if (--lo->lo_refcnt)
1600                 goto out;
1601
1602         if (lo->lo_flags & LO_FLAGS_AUTOCLEAR) {
1603                 /*
1604                  * In autoclear mode, stop the loop thread
1605                  * and remove configuration after last close.
1606                  */
1607                 err = loop_clr_fd(lo);
1608                 if (!err)
1609                         return;
1610         } else {
1611                 /*
1612                  * Otherwise keep thread (if running) and config,
1613                  * but flush possible ongoing bios in thread.
1614                  */
1615                 loop_flush(lo);
1616         }
1617
1618 out:
1619         mutex_unlock(&lo->lo_ctl_mutex);
1620 }
1621
1622 static const struct block_device_operations lo_fops = {
1623         .owner =        THIS_MODULE,
1624         .open =         lo_open,
1625         .release =      lo_release,
1626         .ioctl =        lo_ioctl,
1627 #ifdef CONFIG_COMPAT
1628         .compat_ioctl = lo_compat_ioctl,
1629 #endif
1630 };
1631
1632 /*
1633  * And now the modules code and kernel interface.
1634  */
1635 static int max_loop;
1636 module_param(max_loop, int, S_IRUGO);
1637 MODULE_PARM_DESC(max_loop, "Maximum number of loop devices");
1638 module_param(max_part, int, S_IRUGO);
1639 MODULE_PARM_DESC(max_part, "Maximum number of partitions per loop device");
1640 MODULE_LICENSE("GPL");
1641 MODULE_ALIAS_BLOCKDEV_MAJOR(LOOP_MAJOR);
1642
1643 int loop_register_transfer(struct loop_func_table *funcs)
1644 {
1645         unsigned int n = funcs->number;
1646
1647         if (n >= MAX_LO_CRYPT || xfer_funcs[n])
1648                 return -EINVAL;
1649         xfer_funcs[n] = funcs;
1650         return 0;
1651 }
1652
1653 static int unregister_transfer_cb(int id, void *ptr, void *data)
1654 {
1655         struct loop_device *lo = ptr;
1656         struct loop_func_table *xfer = data;
1657
1658         mutex_lock(&lo->lo_ctl_mutex);
1659         if (lo->lo_encryption == xfer)
1660                 loop_release_xfer(lo);
1661         mutex_unlock(&lo->lo_ctl_mutex);
1662         return 0;
1663 }
1664
1665 int loop_unregister_transfer(int number)
1666 {
1667         unsigned int n = number;
1668         struct loop_func_table *xfer;
1669
1670         if (n == 0 || n >= MAX_LO_CRYPT || (xfer = xfer_funcs[n]) == NULL)
1671                 return -EINVAL;
1672
1673         xfer_funcs[n] = NULL;
1674         idr_for_each(&loop_index_idr, &unregister_transfer_cb, xfer);
1675         return 0;
1676 }
1677
1678 EXPORT_SYMBOL(loop_register_transfer);
1679 EXPORT_SYMBOL(loop_unregister_transfer);
1680
1681 static int loop_add(struct loop_device **l, int i)
1682 {
1683         struct loop_device *lo;
1684         struct gendisk *disk;
1685         int err;
1686
1687         err = -ENOMEM;
1688         lo = kzalloc(sizeof(*lo), GFP_KERNEL);
1689         if (!lo)
1690                 goto out;
1691
1692         lo->lo_state = Lo_unbound;
1693
1694         /* allocate id, if @id >= 0, we're requesting that specific id */
1695         if (i >= 0) {
1696                 err = idr_alloc(&loop_index_idr, lo, i, i + 1, GFP_KERNEL);
1697                 if (err == -ENOSPC)
1698                         err = -EEXIST;
1699         } else {
1700                 err = idr_alloc(&loop_index_idr, lo, 0, 0, GFP_KERNEL);
1701         }
1702         if (err < 0)
1703                 goto out_free_dev;
1704         i = err;
1705
1706         err = -ENOMEM;
1707         lo->lo_queue = blk_alloc_queue(GFP_KERNEL);
1708         if (!lo->lo_queue)
1709                 goto out_free_idr;
1710
1711         /*
1712          * set queue make_request_fn
1713          */
1714         blk_queue_make_request(lo->lo_queue, loop_make_request);
1715         lo->lo_queue->queuedata = lo;
1716
1717         disk = lo->lo_disk = alloc_disk(1 << part_shift);
1718         if (!disk)
1719                 goto out_free_queue;
1720
1721         /*
1722          * Disable partition scanning by default. The in-kernel partition
1723          * scanning can be requested individually per-device during its
1724          * setup. Userspace can always add and remove partitions from all
1725          * devices. The needed partition minors are allocated from the
1726          * extended minor space, the main loop device numbers will continue
1727          * to match the loop minors, regardless of the number of partitions
1728          * used.
1729          *
1730          * If max_part is given, partition scanning is globally enabled for
1731          * all loop devices. The minors for the main loop devices will be
1732          * multiples of max_part.
1733          *
1734          * Note: Global-for-all-devices, set-only-at-init, read-only module
1735          * parameteters like 'max_loop' and 'max_part' make things needlessly
1736          * complicated, are too static, inflexible and may surprise
1737          * userspace tools. Parameters like this in general should be avoided.
1738          */
1739         if (!part_shift)
1740                 disk->flags |= GENHD_FL_NO_PART_SCAN;
1741         disk->flags |= GENHD_FL_EXT_DEVT;
1742         mutex_init(&lo->lo_ctl_mutex);
1743         lo->lo_number           = i;
1744         lo->lo_thread           = NULL;
1745         init_waitqueue_head(&lo->lo_event);
1746         init_waitqueue_head(&lo->lo_req_wait);
1747         spin_lock_init(&lo->lo_lock);
1748         disk->major             = LOOP_MAJOR;
1749         disk->first_minor       = i << part_shift;
1750         disk->fops              = &lo_fops;
1751         disk->private_data      = lo;
1752         disk->queue             = lo->lo_queue;
1753         sprintf(disk->disk_name, "loop%d", i);
1754         add_disk(disk);
1755         *l = lo;
1756         return lo->lo_number;
1757
1758 out_free_queue:
1759         blk_cleanup_queue(lo->lo_queue);
1760 out_free_idr:
1761         idr_remove(&loop_index_idr, i);
1762 out_free_dev:
1763         kfree(lo);
1764 out:
1765         return err;
1766 }
1767
1768 static void loop_remove(struct loop_device *lo)
1769 {
1770         del_gendisk(lo->lo_disk);
1771         blk_cleanup_queue(lo->lo_queue);
1772         put_disk(lo->lo_disk);
1773         kfree(lo);
1774 }
1775
1776 static int find_free_cb(int id, void *ptr, void *data)
1777 {
1778         struct loop_device *lo = ptr;
1779         struct loop_device **l = data;
1780
1781         if (lo->lo_state == Lo_unbound) {
1782                 *l = lo;
1783                 return 1;
1784         }
1785         return 0;
1786 }
1787
1788 static int loop_lookup(struct loop_device **l, int i)
1789 {
1790         struct loop_device *lo;
1791         int ret = -ENODEV;
1792
1793         if (i < 0) {
1794                 int err;
1795
1796                 err = idr_for_each(&loop_index_idr, &find_free_cb, &lo);
1797                 if (err == 1) {
1798                         *l = lo;
1799                         ret = lo->lo_number;
1800                 }
1801                 goto out;
1802         }
1803
1804         /* lookup and return a specific i */
1805         lo = idr_find(&loop_index_idr, i);
1806         if (lo) {
1807                 *l = lo;
1808                 ret = lo->lo_number;
1809         }
1810 out:
1811         return ret;
1812 }
1813
1814 static struct kobject *loop_probe(dev_t dev, int *part, void *data)
1815 {
1816         struct loop_device *lo;
1817         struct kobject *kobj;
1818         int err;
1819
1820         mutex_lock(&loop_index_mutex);
1821         err = loop_lookup(&lo, MINOR(dev) >> part_shift);
1822         if (err < 0)
1823                 err = loop_add(&lo, MINOR(dev) >> part_shift);
1824         if (err < 0)
1825                 kobj = NULL;
1826         else
1827                 kobj = get_disk(lo->lo_disk);
1828         mutex_unlock(&loop_index_mutex);
1829
1830         *part = 0;
1831         return kobj;
1832 }
1833
1834 static long loop_control_ioctl(struct file *file, unsigned int cmd,
1835                                unsigned long parm)
1836 {
1837         struct loop_device *lo;
1838         int ret = -ENOSYS;
1839
1840         mutex_lock(&loop_index_mutex);
1841         switch (cmd) {
1842         case LOOP_CTL_ADD:
1843                 ret = loop_lookup(&lo, parm);
1844                 if (ret >= 0) {
1845                         ret = -EEXIST;
1846                         break;
1847                 }
1848                 ret = loop_add(&lo, parm);
1849                 break;
1850         case LOOP_CTL_REMOVE:
1851                 ret = loop_lookup(&lo, parm);
1852                 if (ret < 0)
1853                         break;
1854                 mutex_lock(&lo->lo_ctl_mutex);
1855                 if (lo->lo_state != Lo_unbound) {
1856                         ret = -EBUSY;
1857                         mutex_unlock(&lo->lo_ctl_mutex);
1858                         break;
1859                 }
1860                 if (lo->lo_refcnt > 0) {
1861                         ret = -EBUSY;
1862                         mutex_unlock(&lo->lo_ctl_mutex);
1863                         break;
1864                 }
1865                 lo->lo_disk->private_data = NULL;
1866                 mutex_unlock(&lo->lo_ctl_mutex);
1867                 idr_remove(&loop_index_idr, lo->lo_number);
1868                 loop_remove(lo);
1869                 break;
1870         case LOOP_CTL_GET_FREE:
1871                 ret = loop_lookup(&lo, -1);
1872                 if (ret >= 0)
1873                         break;
1874                 ret = loop_add(&lo, -1);
1875         }
1876         mutex_unlock(&loop_index_mutex);
1877
1878         return ret;
1879 }
1880
1881 static const struct file_operations loop_ctl_fops = {
1882         .open           = nonseekable_open,
1883         .unlocked_ioctl = loop_control_ioctl,
1884         .compat_ioctl   = loop_control_ioctl,
1885         .owner          = THIS_MODULE,
1886         .llseek         = noop_llseek,
1887 };
1888
1889 static struct miscdevice loop_misc = {
1890         .minor          = LOOP_CTRL_MINOR,
1891         .name           = "loop-control",
1892         .fops           = &loop_ctl_fops,
1893 };
1894
1895 MODULE_ALIAS_MISCDEV(LOOP_CTRL_MINOR);
1896 MODULE_ALIAS("devname:loop-control");
1897
1898 static int __init loop_init(void)
1899 {
1900         int i, nr;
1901         unsigned long range;
1902         struct loop_device *lo;
1903         int err;
1904
1905         err = misc_register(&loop_misc);
1906         if (err < 0)
1907                 return err;
1908
1909         part_shift = 0;
1910         if (max_part > 0) {
1911                 part_shift = fls(max_part);
1912
1913                 /*
1914                  * Adjust max_part according to part_shift as it is exported
1915                  * to user space so that user can decide correct minor number
1916                  * if [s]he want to create more devices.
1917                  *
1918                  * Note that -1 is required because partition 0 is reserved
1919                  * for the whole disk.
1920                  */
1921                 max_part = (1UL << part_shift) - 1;
1922         }
1923
1924         if ((1UL << part_shift) > DISK_MAX_PARTS) {
1925                 err = -EINVAL;
1926                 goto misc_out;
1927         }
1928
1929         if (max_loop > 1UL << (MINORBITS - part_shift)) {
1930                 err = -EINVAL;
1931                 goto misc_out;
1932         }
1933
1934         /*
1935          * If max_loop is specified, create that many devices upfront.
1936          * This also becomes a hard limit. If max_loop is not specified,
1937          * create CONFIG_BLK_DEV_LOOP_MIN_COUNT loop devices at module
1938          * init time. Loop devices can be requested on-demand with the
1939          * /dev/loop-control interface, or be instantiated by accessing
1940          * a 'dead' device node.
1941          */
1942         if (max_loop) {
1943                 nr = max_loop;
1944                 range = max_loop << part_shift;
1945         } else {
1946                 nr = CONFIG_BLK_DEV_LOOP_MIN_COUNT;
1947                 range = 1UL << MINORBITS;
1948         }
1949
1950         if (register_blkdev(LOOP_MAJOR, "loop")) {
1951                 err = -EIO;
1952                 goto misc_out;
1953         }
1954
1955         blk_register_region(MKDEV(LOOP_MAJOR, 0), range,
1956                                   THIS_MODULE, loop_probe, NULL, NULL);
1957
1958         /* pre-create number of devices given by config or max_loop */
1959         mutex_lock(&loop_index_mutex);
1960         for (i = 0; i < nr; i++)
1961                 loop_add(&lo, i);
1962         mutex_unlock(&loop_index_mutex);
1963
1964         printk(KERN_INFO "loop: module loaded\n");
1965         return 0;
1966
1967 misc_out:
1968         misc_deregister(&loop_misc);
1969         return err;
1970 }
1971
1972 static int loop_exit_cb(int id, void *ptr, void *data)
1973 {
1974         struct loop_device *lo = ptr;
1975
1976         loop_remove(lo);
1977         return 0;
1978 }
1979
1980 static void __exit loop_exit(void)
1981 {
1982         unsigned long range;
1983
1984         range = max_loop ? max_loop << part_shift : 1UL << MINORBITS;
1985
1986         idr_for_each(&loop_index_idr, &loop_exit_cb, NULL);
1987         idr_destroy(&loop_index_idr);
1988
1989         blk_unregister_region(MKDEV(LOOP_MAJOR, 0), range);
1990         unregister_blkdev(LOOP_MAJOR, "loop");
1991
1992         misc_deregister(&loop_misc);
1993 }
1994
1995 module_init(loop_init);
1996 module_exit(loop_exit);
1997
1998 #ifndef MODULE
1999 static int __init max_loop_setup(char *str)
2000 {
2001         max_loop = simple_strtol(str, NULL, 0);
2002         return 1;
2003 }
2004
2005 __setup("max_loop=", max_loop_setup);
2006 #endif