]> git.karo-electronics.de Git - karo-tx-linux.git/blob - drivers/block/loop.c
loop: use aio to perform io on the underlying file
[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         /*
966          * set queue make_request_fn, and add limits based on lower level
967          * device
968          */
969         blk_queue_make_request(lo->lo_queue, loop_make_request);
970         lo->lo_queue->queuedata = lo;
971
972         if (!(lo_flags & LO_FLAGS_READ_ONLY) && file->f_op->fsync)
973                 blk_queue_flush(lo->lo_queue, REQ_FLUSH);
974
975         set_capacity(lo->lo_disk, size);
976         bd_set_size(bdev, size << 9);
977         loop_sysfs_init(lo);
978         /* let user-space know about the new size */
979         kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, KOBJ_CHANGE);
980
981         set_blocksize(bdev, lo_blocksize);
982
983 #ifdef CONFIG_AIO
984         /*
985          * We must not send too-small direct-io requests, so we inherit
986          * the logical block size from the underlying device
987          */
988         if ((lo_flags & LO_FLAGS_USE_AIO) && inode->i_sb->s_bdev)
989                 blk_queue_logical_block_size(lo->lo_queue,
990                                 bdev_logical_block_size(inode->i_sb->s_bdev));
991 #endif
992
993         lo->lo_thread = kthread_create(loop_thread, lo, "loop%d",
994                                                 lo->lo_number);
995         if (IS_ERR(lo->lo_thread)) {
996                 error = PTR_ERR(lo->lo_thread);
997                 goto out_clr;
998         }
999         lo->lo_state = Lo_bound;
1000         wake_up_process(lo->lo_thread);
1001         if (part_shift)
1002                 lo->lo_flags |= LO_FLAGS_PARTSCAN;
1003         if (lo->lo_flags & LO_FLAGS_PARTSCAN)
1004                 ioctl_by_bdev(bdev, BLKRRPART, 0);
1005
1006         /* Grab the block_device to prevent its destruction after we
1007          * put /dev/loopXX inode. Later in loop_clr_fd() we bdput(bdev).
1008          */
1009         bdgrab(bdev);
1010         return 0;
1011
1012 out_clr:
1013         loop_sysfs_exit(lo);
1014         lo->lo_thread = NULL;
1015         lo->lo_device = NULL;
1016         lo->lo_backing_file = NULL;
1017         lo->lo_flags = 0;
1018         set_capacity(lo->lo_disk, 0);
1019         invalidate_bdev(bdev);
1020         bd_set_size(bdev, 0);
1021         kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, KOBJ_CHANGE);
1022         mapping_set_gfp_mask(mapping, lo->old_gfp_mask);
1023         lo->lo_state = Lo_unbound;
1024  out_putf:
1025         fput(file);
1026  out:
1027         /* This is safe: open() is still holding a reference. */
1028         module_put(THIS_MODULE);
1029         return error;
1030 }
1031
1032 static int
1033 loop_release_xfer(struct loop_device *lo)
1034 {
1035         int err = 0;
1036         struct loop_func_table *xfer = lo->lo_encryption;
1037
1038         if (xfer) {
1039                 if (xfer->release)
1040                         err = xfer->release(lo);
1041                 lo->transfer = NULL;
1042                 lo->lo_encryption = NULL;
1043                 module_put(xfer->owner);
1044         }
1045         return err;
1046 }
1047
1048 static int
1049 loop_init_xfer(struct loop_device *lo, struct loop_func_table *xfer,
1050                const struct loop_info64 *i)
1051 {
1052         int err = 0;
1053
1054         if (xfer) {
1055                 struct module *owner = xfer->owner;
1056
1057                 if (!try_module_get(owner))
1058                         return -EINVAL;
1059                 if (xfer->init)
1060                         err = xfer->init(lo, i);
1061                 if (err)
1062                         module_put(owner);
1063                 else
1064                         lo->lo_encryption = xfer;
1065         }
1066         return err;
1067 }
1068
1069 static int loop_clr_fd(struct loop_device *lo)
1070 {
1071         struct file *filp = lo->lo_backing_file;
1072         gfp_t gfp = lo->old_gfp_mask;
1073         struct block_device *bdev = lo->lo_device;
1074
1075         if (lo->lo_state != Lo_bound)
1076                 return -ENXIO;
1077
1078         /*
1079          * If we've explicitly asked to tear down the loop device,
1080          * and it has an elevated reference count, set it for auto-teardown when
1081          * the last reference goes away. This stops $!~#$@ udev from
1082          * preventing teardown because it decided that it needs to run blkid on
1083          * the loopback device whenever they appear. xfstests is notorious for
1084          * failing tests because blkid via udev races with a losetup
1085          * <dev>/do something like mkfs/losetup -d <dev> causing the losetup -d
1086          * command to fail with EBUSY.
1087          */
1088         if (lo->lo_refcnt > 1) {
1089                 lo->lo_flags |= LO_FLAGS_AUTOCLEAR;
1090                 mutex_unlock(&lo->lo_ctl_mutex);
1091                 return 0;
1092         }
1093
1094         if (filp == NULL)
1095                 return -EINVAL;
1096
1097         spin_lock_irq(&lo->lo_lock);
1098         lo->lo_state = Lo_rundown;
1099         spin_unlock_irq(&lo->lo_lock);
1100
1101         kthread_stop(lo->lo_thread);
1102
1103         spin_lock_irq(&lo->lo_lock);
1104         lo->lo_backing_file = NULL;
1105         spin_unlock_irq(&lo->lo_lock);
1106
1107         loop_release_xfer(lo);
1108         lo->transfer = NULL;
1109         lo->ioctl = NULL;
1110         lo->lo_device = NULL;
1111         lo->lo_encryption = NULL;
1112         lo->lo_offset = 0;
1113         lo->lo_sizelimit = 0;
1114         lo->lo_encrypt_key_size = 0;
1115         lo->lo_thread = NULL;
1116         memset(lo->lo_encrypt_key, 0, LO_KEY_SIZE);
1117         memset(lo->lo_crypt_name, 0, LO_NAME_SIZE);
1118         memset(lo->lo_file_name, 0, LO_NAME_SIZE);
1119         if (bdev) {
1120                 bdput(bdev);
1121                 invalidate_bdev(bdev);
1122         }
1123         set_capacity(lo->lo_disk, 0);
1124         loop_sysfs_exit(lo);
1125         if (bdev) {
1126                 bd_set_size(bdev, 0);
1127                 /* let user-space know about this change */
1128                 kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, KOBJ_CHANGE);
1129         }
1130         mapping_set_gfp_mask(filp->f_mapping, gfp);
1131         lo->lo_state = Lo_unbound;
1132         /* This is safe: open() is still holding a reference. */
1133         module_put(THIS_MODULE);
1134         if (lo->lo_flags & LO_FLAGS_PARTSCAN && bdev)
1135                 ioctl_by_bdev(bdev, BLKRRPART, 0);
1136         lo->lo_flags = 0;
1137         if (!part_shift)
1138                 lo->lo_disk->flags |= GENHD_FL_NO_PART_SCAN;
1139         mutex_unlock(&lo->lo_ctl_mutex);
1140         /*
1141          * Need not hold lo_ctl_mutex to fput backing file.
1142          * Calling fput holding lo_ctl_mutex triggers a circular
1143          * lock dependency possibility warning as fput can take
1144          * bd_mutex which is usually taken before lo_ctl_mutex.
1145          */
1146         fput(filp);
1147         return 0;
1148 }
1149
1150 static int
1151 loop_set_status(struct loop_device *lo, const struct loop_info64 *info)
1152 {
1153         int err;
1154         struct loop_func_table *xfer;
1155         kuid_t uid = current_uid();
1156
1157         if (lo->lo_encrypt_key_size &&
1158             !uid_eq(lo->lo_key_owner, uid) &&
1159             !capable(CAP_SYS_ADMIN))
1160                 return -EPERM;
1161         if (lo->lo_state != Lo_bound)
1162                 return -ENXIO;
1163         if ((unsigned int) info->lo_encrypt_key_size > LO_KEY_SIZE)
1164                 return -EINVAL;
1165
1166         err = loop_release_xfer(lo);
1167         if (err)
1168                 return err;
1169
1170         if (info->lo_encrypt_type) {
1171                 unsigned int type = info->lo_encrypt_type;
1172
1173                 if (type >= MAX_LO_CRYPT)
1174                         return -EINVAL;
1175                 xfer = xfer_funcs[type];
1176                 if (xfer == NULL)
1177                         return -EINVAL;
1178         } else
1179                 xfer = NULL;
1180
1181         err = loop_init_xfer(lo, xfer, info);
1182         if (err)
1183                 return err;
1184
1185         if (lo->lo_offset != info->lo_offset ||
1186             lo->lo_sizelimit != info->lo_sizelimit)
1187                 if (figure_loop_size(lo, info->lo_offset, info->lo_sizelimit))
1188                         return -EFBIG;
1189
1190         loop_config_discard(lo);
1191
1192         memcpy(lo->lo_file_name, info->lo_file_name, LO_NAME_SIZE);
1193         memcpy(lo->lo_crypt_name, info->lo_crypt_name, LO_NAME_SIZE);
1194         lo->lo_file_name[LO_NAME_SIZE-1] = 0;
1195         lo->lo_crypt_name[LO_NAME_SIZE-1] = 0;
1196
1197         if (!xfer)
1198                 xfer = &none_funcs;
1199         lo->transfer = xfer->transfer;
1200         lo->ioctl = xfer->ioctl;
1201
1202         if ((lo->lo_flags & LO_FLAGS_AUTOCLEAR) !=
1203              (info->lo_flags & LO_FLAGS_AUTOCLEAR))
1204                 lo->lo_flags ^= LO_FLAGS_AUTOCLEAR;
1205
1206         if ((info->lo_flags & LO_FLAGS_PARTSCAN) &&
1207              !(lo->lo_flags & LO_FLAGS_PARTSCAN)) {
1208                 lo->lo_flags |= LO_FLAGS_PARTSCAN;
1209                 lo->lo_disk->flags &= ~GENHD_FL_NO_PART_SCAN;
1210                 ioctl_by_bdev(lo->lo_device, BLKRRPART, 0);
1211         }
1212
1213         lo->lo_encrypt_key_size = info->lo_encrypt_key_size;
1214         lo->lo_init[0] = info->lo_init[0];
1215         lo->lo_init[1] = info->lo_init[1];
1216         if (info->lo_encrypt_key_size) {
1217                 memcpy(lo->lo_encrypt_key, info->lo_encrypt_key,
1218                        info->lo_encrypt_key_size);
1219                 lo->lo_key_owner = uid;
1220         }       
1221
1222         return 0;
1223 }
1224
1225 static int
1226 loop_get_status(struct loop_device *lo, struct loop_info64 *info)
1227 {
1228         struct file *file = lo->lo_backing_file;
1229         struct kstat stat;
1230         int error;
1231
1232         if (lo->lo_state != Lo_bound)
1233                 return -ENXIO;
1234         error = vfs_getattr(&file->f_path, &stat);
1235         if (error)
1236                 return error;
1237         memset(info, 0, sizeof(*info));
1238         info->lo_number = lo->lo_number;
1239         info->lo_device = huge_encode_dev(stat.dev);
1240         info->lo_inode = stat.ino;
1241         info->lo_rdevice = huge_encode_dev(lo->lo_device ? stat.rdev : stat.dev);
1242         info->lo_offset = lo->lo_offset;
1243         info->lo_sizelimit = lo->lo_sizelimit;
1244         info->lo_flags = lo->lo_flags;
1245         memcpy(info->lo_file_name, lo->lo_file_name, LO_NAME_SIZE);
1246         memcpy(info->lo_crypt_name, lo->lo_crypt_name, LO_NAME_SIZE);
1247         info->lo_encrypt_type =
1248                 lo->lo_encryption ? lo->lo_encryption->number : 0;
1249         if (lo->lo_encrypt_key_size && capable(CAP_SYS_ADMIN)) {
1250                 info->lo_encrypt_key_size = lo->lo_encrypt_key_size;
1251                 memcpy(info->lo_encrypt_key, lo->lo_encrypt_key,
1252                        lo->lo_encrypt_key_size);
1253         }
1254         return 0;
1255 }
1256
1257 static void
1258 loop_info64_from_old(const struct loop_info *info, struct loop_info64 *info64)
1259 {
1260         memset(info64, 0, sizeof(*info64));
1261         info64->lo_number = info->lo_number;
1262         info64->lo_device = info->lo_device;
1263         info64->lo_inode = info->lo_inode;
1264         info64->lo_rdevice = info->lo_rdevice;
1265         info64->lo_offset = info->lo_offset;
1266         info64->lo_sizelimit = 0;
1267         info64->lo_encrypt_type = info->lo_encrypt_type;
1268         info64->lo_encrypt_key_size = info->lo_encrypt_key_size;
1269         info64->lo_flags = info->lo_flags;
1270         info64->lo_init[0] = info->lo_init[0];
1271         info64->lo_init[1] = info->lo_init[1];
1272         if (info->lo_encrypt_type == LO_CRYPT_CRYPTOAPI)
1273                 memcpy(info64->lo_crypt_name, info->lo_name, LO_NAME_SIZE);
1274         else
1275                 memcpy(info64->lo_file_name, info->lo_name, LO_NAME_SIZE);
1276         memcpy(info64->lo_encrypt_key, info->lo_encrypt_key, LO_KEY_SIZE);
1277 }
1278
1279 static int
1280 loop_info64_to_old(const struct loop_info64 *info64, struct loop_info *info)
1281 {
1282         memset(info, 0, sizeof(*info));
1283         info->lo_number = info64->lo_number;
1284         info->lo_device = info64->lo_device;
1285         info->lo_inode = info64->lo_inode;
1286         info->lo_rdevice = info64->lo_rdevice;
1287         info->lo_offset = info64->lo_offset;
1288         info->lo_encrypt_type = info64->lo_encrypt_type;
1289         info->lo_encrypt_key_size = info64->lo_encrypt_key_size;
1290         info->lo_flags = info64->lo_flags;
1291         info->lo_init[0] = info64->lo_init[0];
1292         info->lo_init[1] = info64->lo_init[1];
1293         if (info->lo_encrypt_type == LO_CRYPT_CRYPTOAPI)
1294                 memcpy(info->lo_name, info64->lo_crypt_name, LO_NAME_SIZE);
1295         else
1296                 memcpy(info->lo_name, info64->lo_file_name, LO_NAME_SIZE);
1297         memcpy(info->lo_encrypt_key, info64->lo_encrypt_key, LO_KEY_SIZE);
1298
1299         /* error in case values were truncated */
1300         if (info->lo_device != info64->lo_device ||
1301             info->lo_rdevice != info64->lo_rdevice ||
1302             info->lo_inode != info64->lo_inode ||
1303             info->lo_offset != info64->lo_offset)
1304                 return -EOVERFLOW;
1305
1306         return 0;
1307 }
1308
1309 static int
1310 loop_set_status_old(struct loop_device *lo, const struct loop_info __user *arg)
1311 {
1312         struct loop_info info;
1313         struct loop_info64 info64;
1314
1315         if (copy_from_user(&info, arg, sizeof (struct loop_info)))
1316                 return -EFAULT;
1317         loop_info64_from_old(&info, &info64);
1318         return loop_set_status(lo, &info64);
1319 }
1320
1321 static int
1322 loop_set_status64(struct loop_device *lo, const struct loop_info64 __user *arg)
1323 {
1324         struct loop_info64 info64;
1325
1326         if (copy_from_user(&info64, arg, sizeof (struct loop_info64)))
1327                 return -EFAULT;
1328         return loop_set_status(lo, &info64);
1329 }
1330
1331 static int
1332 loop_get_status_old(struct loop_device *lo, struct loop_info __user *arg) {
1333         struct loop_info info;
1334         struct loop_info64 info64;
1335         int err = 0;
1336
1337         if (!arg)
1338                 err = -EINVAL;
1339         if (!err)
1340                 err = loop_get_status(lo, &info64);
1341         if (!err)
1342                 err = loop_info64_to_old(&info64, &info);
1343         if (!err && copy_to_user(arg, &info, sizeof(info)))
1344                 err = -EFAULT;
1345
1346         return err;
1347 }
1348
1349 static int
1350 loop_get_status64(struct loop_device *lo, struct loop_info64 __user *arg) {
1351         struct loop_info64 info64;
1352         int err = 0;
1353
1354         if (!arg)
1355                 err = -EINVAL;
1356         if (!err)
1357                 err = loop_get_status(lo, &info64);
1358         if (!err && copy_to_user(arg, &info64, sizeof(info64)))
1359                 err = -EFAULT;
1360
1361         return err;
1362 }
1363
1364 static int loop_set_capacity(struct loop_device *lo, struct block_device *bdev)
1365 {
1366         if (unlikely(lo->lo_state != Lo_bound))
1367                 return -ENXIO;
1368
1369         return figure_loop_size(lo, lo->lo_offset, lo->lo_sizelimit);
1370 }
1371
1372 static int lo_ioctl(struct block_device *bdev, fmode_t mode,
1373         unsigned int cmd, unsigned long arg)
1374 {
1375         struct loop_device *lo = bdev->bd_disk->private_data;
1376         int err;
1377
1378         mutex_lock_nested(&lo->lo_ctl_mutex, 1);
1379         switch (cmd) {
1380         case LOOP_SET_FD:
1381                 err = loop_set_fd(lo, mode, bdev, arg);
1382                 break;
1383         case LOOP_CHANGE_FD:
1384                 err = loop_change_fd(lo, bdev, arg);
1385                 break;
1386         case LOOP_CLR_FD:
1387                 /* loop_clr_fd would have unlocked lo_ctl_mutex on success */
1388                 err = loop_clr_fd(lo);
1389                 if (!err)
1390                         goto out_unlocked;
1391                 break;
1392         case LOOP_SET_STATUS:
1393                 err = -EPERM;
1394                 if ((mode & FMODE_WRITE) || capable(CAP_SYS_ADMIN))
1395                         err = loop_set_status_old(lo,
1396                                         (struct loop_info __user *)arg);
1397                 break;
1398         case LOOP_GET_STATUS:
1399                 err = loop_get_status_old(lo, (struct loop_info __user *) arg);
1400                 break;
1401         case LOOP_SET_STATUS64:
1402                 err = -EPERM;
1403                 if ((mode & FMODE_WRITE) || capable(CAP_SYS_ADMIN))
1404                         err = loop_set_status64(lo,
1405                                         (struct loop_info64 __user *) arg);
1406                 break;
1407         case LOOP_GET_STATUS64:
1408                 err = loop_get_status64(lo, (struct loop_info64 __user *) arg);
1409                 break;
1410         case LOOP_SET_CAPACITY:
1411                 err = -EPERM;
1412                 if ((mode & FMODE_WRITE) || capable(CAP_SYS_ADMIN))
1413                         err = loop_set_capacity(lo, bdev);
1414                 break;
1415         default:
1416                 err = lo->ioctl ? lo->ioctl(lo, cmd, arg) : -EINVAL;
1417         }
1418         mutex_unlock(&lo->lo_ctl_mutex);
1419
1420 out_unlocked:
1421         return err;
1422 }
1423
1424 #ifdef CONFIG_COMPAT
1425 struct compat_loop_info {
1426         compat_int_t    lo_number;      /* ioctl r/o */
1427         compat_dev_t    lo_device;      /* ioctl r/o */
1428         compat_ulong_t  lo_inode;       /* ioctl r/o */
1429         compat_dev_t    lo_rdevice;     /* ioctl r/o */
1430         compat_int_t    lo_offset;
1431         compat_int_t    lo_encrypt_type;
1432         compat_int_t    lo_encrypt_key_size;    /* ioctl w/o */
1433         compat_int_t    lo_flags;       /* ioctl r/o */
1434         char            lo_name[LO_NAME_SIZE];
1435         unsigned char   lo_encrypt_key[LO_KEY_SIZE]; /* ioctl w/o */
1436         compat_ulong_t  lo_init[2];
1437         char            reserved[4];
1438 };
1439
1440 /*
1441  * Transfer 32-bit compatibility structure in userspace to 64-bit loop info
1442  * - noinlined to reduce stack space usage in main part of driver
1443  */
1444 static noinline int
1445 loop_info64_from_compat(const struct compat_loop_info __user *arg,
1446                         struct loop_info64 *info64)
1447 {
1448         struct compat_loop_info info;
1449
1450         if (copy_from_user(&info, arg, sizeof(info)))
1451                 return -EFAULT;
1452
1453         memset(info64, 0, sizeof(*info64));
1454         info64->lo_number = info.lo_number;
1455         info64->lo_device = info.lo_device;
1456         info64->lo_inode = info.lo_inode;
1457         info64->lo_rdevice = info.lo_rdevice;
1458         info64->lo_offset = info.lo_offset;
1459         info64->lo_sizelimit = 0;
1460         info64->lo_encrypt_type = info.lo_encrypt_type;
1461         info64->lo_encrypt_key_size = info.lo_encrypt_key_size;
1462         info64->lo_flags = info.lo_flags;
1463         info64->lo_init[0] = info.lo_init[0];
1464         info64->lo_init[1] = info.lo_init[1];
1465         if (info.lo_encrypt_type == LO_CRYPT_CRYPTOAPI)
1466                 memcpy(info64->lo_crypt_name, info.lo_name, LO_NAME_SIZE);
1467         else
1468                 memcpy(info64->lo_file_name, info.lo_name, LO_NAME_SIZE);
1469         memcpy(info64->lo_encrypt_key, info.lo_encrypt_key, LO_KEY_SIZE);
1470         return 0;
1471 }
1472
1473 /*
1474  * Transfer 64-bit loop info to 32-bit compatibility structure in userspace
1475  * - noinlined to reduce stack space usage in main part of driver
1476  */
1477 static noinline int
1478 loop_info64_to_compat(const struct loop_info64 *info64,
1479                       struct compat_loop_info __user *arg)
1480 {
1481         struct compat_loop_info info;
1482
1483         memset(&info, 0, sizeof(info));
1484         info.lo_number = info64->lo_number;
1485         info.lo_device = info64->lo_device;
1486         info.lo_inode = info64->lo_inode;
1487         info.lo_rdevice = info64->lo_rdevice;
1488         info.lo_offset = info64->lo_offset;
1489         info.lo_encrypt_type = info64->lo_encrypt_type;
1490         info.lo_encrypt_key_size = info64->lo_encrypt_key_size;
1491         info.lo_flags = info64->lo_flags;
1492         info.lo_init[0] = info64->lo_init[0];
1493         info.lo_init[1] = info64->lo_init[1];
1494         if (info.lo_encrypt_type == LO_CRYPT_CRYPTOAPI)
1495                 memcpy(info.lo_name, info64->lo_crypt_name, LO_NAME_SIZE);
1496         else
1497                 memcpy(info.lo_name, info64->lo_file_name, LO_NAME_SIZE);
1498         memcpy(info.lo_encrypt_key, info64->lo_encrypt_key, LO_KEY_SIZE);
1499
1500         /* error in case values were truncated */
1501         if (info.lo_device != info64->lo_device ||
1502             info.lo_rdevice != info64->lo_rdevice ||
1503             info.lo_inode != info64->lo_inode ||
1504             info.lo_offset != info64->lo_offset ||
1505             info.lo_init[0] != info64->lo_init[0] ||
1506             info.lo_init[1] != info64->lo_init[1])
1507                 return -EOVERFLOW;
1508
1509         if (copy_to_user(arg, &info, sizeof(info)))
1510                 return -EFAULT;
1511         return 0;
1512 }
1513
1514 static int
1515 loop_set_status_compat(struct loop_device *lo,
1516                        const struct compat_loop_info __user *arg)
1517 {
1518         struct loop_info64 info64;
1519         int ret;
1520
1521         ret = loop_info64_from_compat(arg, &info64);
1522         if (ret < 0)
1523                 return ret;
1524         return loop_set_status(lo, &info64);
1525 }
1526
1527 static int
1528 loop_get_status_compat(struct loop_device *lo,
1529                        struct compat_loop_info __user *arg)
1530 {
1531         struct loop_info64 info64;
1532         int err = 0;
1533
1534         if (!arg)
1535                 err = -EINVAL;
1536         if (!err)
1537                 err = loop_get_status(lo, &info64);
1538         if (!err)
1539                 err = loop_info64_to_compat(&info64, arg);
1540         return err;
1541 }
1542
1543 static int lo_compat_ioctl(struct block_device *bdev, fmode_t mode,
1544                            unsigned int cmd, unsigned long arg)
1545 {
1546         struct loop_device *lo = bdev->bd_disk->private_data;
1547         int err;
1548
1549         switch(cmd) {
1550         case LOOP_SET_STATUS:
1551                 mutex_lock(&lo->lo_ctl_mutex);
1552                 err = loop_set_status_compat(
1553                         lo, (const struct compat_loop_info __user *) arg);
1554                 mutex_unlock(&lo->lo_ctl_mutex);
1555                 break;
1556         case LOOP_GET_STATUS:
1557                 mutex_lock(&lo->lo_ctl_mutex);
1558                 err = loop_get_status_compat(
1559                         lo, (struct compat_loop_info __user *) arg);
1560                 mutex_unlock(&lo->lo_ctl_mutex);
1561                 break;
1562         case LOOP_SET_CAPACITY:
1563         case LOOP_CLR_FD:
1564         case LOOP_GET_STATUS64:
1565         case LOOP_SET_STATUS64:
1566                 arg = (unsigned long) compat_ptr(arg);
1567         case LOOP_SET_FD:
1568         case LOOP_CHANGE_FD:
1569                 err = lo_ioctl(bdev, mode, cmd, arg);
1570                 break;
1571         default:
1572                 err = -ENOIOCTLCMD;
1573                 break;
1574         }
1575         return err;
1576 }
1577 #endif
1578
1579 static int lo_open(struct block_device *bdev, fmode_t mode)
1580 {
1581         struct loop_device *lo;
1582         int err = 0;
1583
1584         mutex_lock(&loop_index_mutex);
1585         lo = bdev->bd_disk->private_data;
1586         if (!lo) {
1587                 err = -ENXIO;
1588                 goto out;
1589         }
1590
1591         mutex_lock(&lo->lo_ctl_mutex);
1592         lo->lo_refcnt++;
1593         mutex_unlock(&lo->lo_ctl_mutex);
1594 out:
1595         mutex_unlock(&loop_index_mutex);
1596         return err;
1597 }
1598
1599 static void lo_release(struct gendisk *disk, fmode_t mode)
1600 {
1601         struct loop_device *lo = disk->private_data;
1602         int err;
1603
1604         mutex_lock(&lo->lo_ctl_mutex);
1605
1606         if (--lo->lo_refcnt)
1607                 goto out;
1608
1609         if (lo->lo_flags & LO_FLAGS_AUTOCLEAR) {
1610                 /*
1611                  * In autoclear mode, stop the loop thread
1612                  * and remove configuration after last close.
1613                  */
1614                 err = loop_clr_fd(lo);
1615                 if (!err)
1616                         return;
1617         } else {
1618                 /*
1619                  * Otherwise keep thread (if running) and config,
1620                  * but flush possible ongoing bios in thread.
1621                  */
1622                 loop_flush(lo);
1623         }
1624
1625 out:
1626         mutex_unlock(&lo->lo_ctl_mutex);
1627 }
1628
1629 static const struct block_device_operations lo_fops = {
1630         .owner =        THIS_MODULE,
1631         .open =         lo_open,
1632         .release =      lo_release,
1633         .ioctl =        lo_ioctl,
1634 #ifdef CONFIG_COMPAT
1635         .compat_ioctl = lo_compat_ioctl,
1636 #endif
1637 };
1638
1639 /*
1640  * And now the modules code and kernel interface.
1641  */
1642 static int max_loop;
1643 module_param(max_loop, int, S_IRUGO);
1644 MODULE_PARM_DESC(max_loop, "Maximum number of loop devices");
1645 module_param(max_part, int, S_IRUGO);
1646 MODULE_PARM_DESC(max_part, "Maximum number of partitions per loop device");
1647 MODULE_LICENSE("GPL");
1648 MODULE_ALIAS_BLOCKDEV_MAJOR(LOOP_MAJOR);
1649
1650 int loop_register_transfer(struct loop_func_table *funcs)
1651 {
1652         unsigned int n = funcs->number;
1653
1654         if (n >= MAX_LO_CRYPT || xfer_funcs[n])
1655                 return -EINVAL;
1656         xfer_funcs[n] = funcs;
1657         return 0;
1658 }
1659
1660 static int unregister_transfer_cb(int id, void *ptr, void *data)
1661 {
1662         struct loop_device *lo = ptr;
1663         struct loop_func_table *xfer = data;
1664
1665         mutex_lock(&lo->lo_ctl_mutex);
1666         if (lo->lo_encryption == xfer)
1667                 loop_release_xfer(lo);
1668         mutex_unlock(&lo->lo_ctl_mutex);
1669         return 0;
1670 }
1671
1672 int loop_unregister_transfer(int number)
1673 {
1674         unsigned int n = number;
1675         struct loop_func_table *xfer;
1676
1677         if (n == 0 || n >= MAX_LO_CRYPT || (xfer = xfer_funcs[n]) == NULL)
1678                 return -EINVAL;
1679
1680         xfer_funcs[n] = NULL;
1681         idr_for_each(&loop_index_idr, &unregister_transfer_cb, xfer);
1682         return 0;
1683 }
1684
1685 EXPORT_SYMBOL(loop_register_transfer);
1686 EXPORT_SYMBOL(loop_unregister_transfer);
1687
1688 static int loop_add(struct loop_device **l, int i)
1689 {
1690         struct loop_device *lo;
1691         struct gendisk *disk;
1692         int err;
1693
1694         err = -ENOMEM;
1695         lo = kzalloc(sizeof(*lo), GFP_KERNEL);
1696         if (!lo)
1697                 goto out;
1698
1699         /* allocate id, if @id >= 0, we're requesting that specific id */
1700         if (i >= 0) {
1701                 err = idr_alloc(&loop_index_idr, lo, i, i + 1, GFP_KERNEL);
1702                 if (err == -ENOSPC)
1703                         err = -EEXIST;
1704         } else {
1705                 err = idr_alloc(&loop_index_idr, lo, 0, 0, GFP_KERNEL);
1706         }
1707         if (err < 0)
1708                 goto out_free_dev;
1709         i = err;
1710
1711         err = -ENOMEM;
1712         lo->lo_queue = blk_alloc_queue(GFP_KERNEL);
1713         if (!lo->lo_queue)
1714                 goto out_free_dev;
1715
1716         disk = lo->lo_disk = alloc_disk(1 << part_shift);
1717         if (!disk)
1718                 goto out_free_queue;
1719
1720         /*
1721          * Disable partition scanning by default. The in-kernel partition
1722          * scanning can be requested individually per-device during its
1723          * setup. Userspace can always add and remove partitions from all
1724          * devices. The needed partition minors are allocated from the
1725          * extended minor space, the main loop device numbers will continue
1726          * to match the loop minors, regardless of the number of partitions
1727          * used.
1728          *
1729          * If max_part is given, partition scanning is globally enabled for
1730          * all loop devices. The minors for the main loop devices will be
1731          * multiples of max_part.
1732          *
1733          * Note: Global-for-all-devices, set-only-at-init, read-only module
1734          * parameteters like 'max_loop' and 'max_part' make things needlessly
1735          * complicated, are too static, inflexible and may surprise
1736          * userspace tools. Parameters like this in general should be avoided.
1737          */
1738         if (!part_shift)
1739                 disk->flags |= GENHD_FL_NO_PART_SCAN;
1740         disk->flags |= GENHD_FL_EXT_DEVT;
1741         mutex_init(&lo->lo_ctl_mutex);
1742         lo->lo_number           = i;
1743         lo->lo_thread           = NULL;
1744         init_waitqueue_head(&lo->lo_event);
1745         init_waitqueue_head(&lo->lo_req_wait);
1746         spin_lock_init(&lo->lo_lock);
1747         disk->major             = LOOP_MAJOR;
1748         disk->first_minor       = i << part_shift;
1749         disk->fops              = &lo_fops;
1750         disk->private_data      = lo;
1751         disk->queue             = lo->lo_queue;
1752         sprintf(disk->disk_name, "loop%d", i);
1753         add_disk(disk);
1754         *l = lo;
1755         return lo->lo_number;
1756
1757 out_free_queue:
1758         blk_cleanup_queue(lo->lo_queue);
1759 out_free_dev:
1760         kfree(lo);
1761 out:
1762         return err;
1763 }
1764
1765 static void loop_remove(struct loop_device *lo)
1766 {
1767         del_gendisk(lo->lo_disk);
1768         blk_cleanup_queue(lo->lo_queue);
1769         put_disk(lo->lo_disk);
1770         kfree(lo);
1771 }
1772
1773 static int find_free_cb(int id, void *ptr, void *data)
1774 {
1775         struct loop_device *lo = ptr;
1776         struct loop_device **l = data;
1777
1778         if (lo->lo_state == Lo_unbound) {
1779                 *l = lo;
1780                 return 1;
1781         }
1782         return 0;
1783 }
1784
1785 static int loop_lookup(struct loop_device **l, int i)
1786 {
1787         struct loop_device *lo;
1788         int ret = -ENODEV;
1789
1790         if (i < 0) {
1791                 int err;
1792
1793                 err = idr_for_each(&loop_index_idr, &find_free_cb, &lo);
1794                 if (err == 1) {
1795                         *l = lo;
1796                         ret = lo->lo_number;
1797                 }
1798                 goto out;
1799         }
1800
1801         /* lookup and return a specific i */
1802         lo = idr_find(&loop_index_idr, i);
1803         if (lo) {
1804                 *l = lo;
1805                 ret = lo->lo_number;
1806         }
1807 out:
1808         return ret;
1809 }
1810
1811 static struct kobject *loop_probe(dev_t dev, int *part, void *data)
1812 {
1813         struct loop_device *lo;
1814         struct kobject *kobj;
1815         int err;
1816
1817         mutex_lock(&loop_index_mutex);
1818         err = loop_lookup(&lo, MINOR(dev) >> part_shift);
1819         if (err < 0)
1820                 err = loop_add(&lo, MINOR(dev) >> part_shift);
1821         if (err < 0)
1822                 kobj = ERR_PTR(err);
1823         else
1824                 kobj = get_disk(lo->lo_disk);
1825         mutex_unlock(&loop_index_mutex);
1826
1827         *part = 0;
1828         return kobj;
1829 }
1830
1831 static long loop_control_ioctl(struct file *file, unsigned int cmd,
1832                                unsigned long parm)
1833 {
1834         struct loop_device *lo;
1835         int ret = -ENOSYS;
1836
1837         mutex_lock(&loop_index_mutex);
1838         switch (cmd) {
1839         case LOOP_CTL_ADD:
1840                 ret = loop_lookup(&lo, parm);
1841                 if (ret >= 0) {
1842                         ret = -EEXIST;
1843                         break;
1844                 }
1845                 ret = loop_add(&lo, parm);
1846                 break;
1847         case LOOP_CTL_REMOVE:
1848                 ret = loop_lookup(&lo, parm);
1849                 if (ret < 0)
1850                         break;
1851                 mutex_lock(&lo->lo_ctl_mutex);
1852                 if (lo->lo_state != Lo_unbound) {
1853                         ret = -EBUSY;
1854                         mutex_unlock(&lo->lo_ctl_mutex);
1855                         break;
1856                 }
1857                 if (lo->lo_refcnt > 0) {
1858                         ret = -EBUSY;
1859                         mutex_unlock(&lo->lo_ctl_mutex);
1860                         break;
1861                 }
1862                 lo->lo_disk->private_data = NULL;
1863                 mutex_unlock(&lo->lo_ctl_mutex);
1864                 idr_remove(&loop_index_idr, lo->lo_number);
1865                 loop_remove(lo);
1866                 break;
1867         case LOOP_CTL_GET_FREE:
1868                 ret = loop_lookup(&lo, -1);
1869                 if (ret >= 0)
1870                         break;
1871                 ret = loop_add(&lo, -1);
1872         }
1873         mutex_unlock(&loop_index_mutex);
1874
1875         return ret;
1876 }
1877
1878 static const struct file_operations loop_ctl_fops = {
1879         .open           = nonseekable_open,
1880         .unlocked_ioctl = loop_control_ioctl,
1881         .compat_ioctl   = loop_control_ioctl,
1882         .owner          = THIS_MODULE,
1883         .llseek         = noop_llseek,
1884 };
1885
1886 static struct miscdevice loop_misc = {
1887         .minor          = LOOP_CTRL_MINOR,
1888         .name           = "loop-control",
1889         .fops           = &loop_ctl_fops,
1890 };
1891
1892 MODULE_ALIAS_MISCDEV(LOOP_CTRL_MINOR);
1893 MODULE_ALIAS("devname:loop-control");
1894
1895 static int __init loop_init(void)
1896 {
1897         int i, nr;
1898         unsigned long range;
1899         struct loop_device *lo;
1900         int err;
1901
1902         err = misc_register(&loop_misc);
1903         if (err < 0)
1904                 return err;
1905
1906         part_shift = 0;
1907         if (max_part > 0) {
1908                 part_shift = fls(max_part);
1909
1910                 /*
1911                  * Adjust max_part according to part_shift as it is exported
1912                  * to user space so that user can decide correct minor number
1913                  * if [s]he want to create more devices.
1914                  *
1915                  * Note that -1 is required because partition 0 is reserved
1916                  * for the whole disk.
1917                  */
1918                 max_part = (1UL << part_shift) - 1;
1919         }
1920
1921         if ((1UL << part_shift) > DISK_MAX_PARTS) {
1922                 err = -EINVAL;
1923                 goto misc_out;
1924         }
1925
1926         if (max_loop > 1UL << (MINORBITS - part_shift)) {
1927                 err = -EINVAL;
1928                 goto misc_out;
1929         }
1930
1931         /*
1932          * If max_loop is specified, create that many devices upfront.
1933          * This also becomes a hard limit. If max_loop is not specified,
1934          * create CONFIG_BLK_DEV_LOOP_MIN_COUNT loop devices at module
1935          * init time. Loop devices can be requested on-demand with the
1936          * /dev/loop-control interface, or be instantiated by accessing
1937          * a 'dead' device node.
1938          */
1939         if (max_loop) {
1940                 nr = max_loop;
1941                 range = max_loop << part_shift;
1942         } else {
1943                 nr = CONFIG_BLK_DEV_LOOP_MIN_COUNT;
1944                 range = 1UL << MINORBITS;
1945         }
1946
1947         if (register_blkdev(LOOP_MAJOR, "loop")) {
1948                 err = -EIO;
1949                 goto misc_out;
1950         }
1951
1952         blk_register_region(MKDEV(LOOP_MAJOR, 0), range,
1953                                   THIS_MODULE, loop_probe, NULL, NULL);
1954
1955         /* pre-create number of devices given by config or max_loop */
1956         mutex_lock(&loop_index_mutex);
1957         for (i = 0; i < nr; i++)
1958                 loop_add(&lo, i);
1959         mutex_unlock(&loop_index_mutex);
1960
1961         printk(KERN_INFO "loop: module loaded\n");
1962         return 0;
1963
1964 misc_out:
1965         misc_deregister(&loop_misc);
1966         return err;
1967 }
1968
1969 static int loop_exit_cb(int id, void *ptr, void *data)
1970 {
1971         struct loop_device *lo = ptr;
1972
1973         loop_remove(lo);
1974         return 0;
1975 }
1976
1977 static void __exit loop_exit(void)
1978 {
1979         unsigned long range;
1980
1981         range = max_loop ? max_loop << part_shift : 1UL << MINORBITS;
1982
1983         idr_for_each(&loop_index_idr, &loop_exit_cb, NULL);
1984         idr_destroy(&loop_index_idr);
1985
1986         blk_unregister_region(MKDEV(LOOP_MAJOR, 0), range);
1987         unregister_blkdev(LOOP_MAJOR, "loop");
1988
1989         misc_deregister(&loop_misc);
1990 }
1991
1992 module_init(loop_init);
1993 module_exit(loop_exit);
1994
1995 #ifndef MODULE
1996 static int __init max_loop_setup(char *str)
1997 {
1998         max_loop = simple_strtol(str, NULL, 0);
1999         return 1;
2000 }
2001
2002 __setup("max_loop=", max_loop_setup);
2003 #endif