GNU Linux-libre 5.4.241-gnu1
[releases.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/uio.h>
79 #include <linux/ioprio.h>
80 #include <linux/blk-cgroup.h>
81
82 #include "loop.h"
83
84 #include <linux/uaccess.h>
85
86 static DEFINE_IDR(loop_index_idr);
87 static DEFINE_MUTEX(loop_ctl_mutex);
88
89 static int max_part;
90 static int part_shift;
91
92 static int transfer_xor(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         char *in, *out, *key;
100         int i, keysize;
101
102         if (cmd == READ) {
103                 in = raw_buf;
104                 out = loop_buf;
105         } else {
106                 in = loop_buf;
107                 out = raw_buf;
108         }
109
110         key = lo->lo_encrypt_key;
111         keysize = lo->lo_encrypt_key_size;
112         for (i = 0; i < size; i++)
113                 *out++ = *in++ ^ key[(i & 511) % keysize];
114
115         kunmap_atomic(loop_buf);
116         kunmap_atomic(raw_buf);
117         cond_resched();
118         return 0;
119 }
120
121 static int xor_init(struct loop_device *lo, const struct loop_info64 *info)
122 {
123         if (unlikely(info->lo_encrypt_key_size <= 0))
124                 return -EINVAL;
125         return 0;
126 }
127
128 static struct loop_func_table none_funcs = {
129         .number = LO_CRYPT_NONE,
130 }; 
131
132 static struct loop_func_table xor_funcs = {
133         .number = LO_CRYPT_XOR,
134         .transfer = transfer_xor,
135         .init = xor_init
136 }; 
137
138 /* xfer_funcs[0] is special - its release function is never called */
139 static struct loop_func_table *xfer_funcs[MAX_LO_CRYPT] = {
140         &none_funcs,
141         &xor_funcs
142 };
143
144 static loff_t get_size(loff_t offset, loff_t sizelimit, struct file *file)
145 {
146         loff_t loopsize;
147
148         /* Compute loopsize in bytes */
149         loopsize = i_size_read(file->f_mapping->host);
150         if (offset > 0)
151                 loopsize -= offset;
152         /* offset is beyond i_size, weird but possible */
153         if (loopsize < 0)
154                 return 0;
155
156         if (sizelimit > 0 && sizelimit < loopsize)
157                 loopsize = sizelimit;
158         /*
159          * Unfortunately, if we want to do I/O on the device,
160          * the number of 512-byte sectors has to fit into a sector_t.
161          */
162         return loopsize >> 9;
163 }
164
165 static loff_t get_loop_size(struct loop_device *lo, struct file *file)
166 {
167         return get_size(lo->lo_offset, lo->lo_sizelimit, file);
168 }
169
170 static void __loop_update_dio(struct loop_device *lo, bool dio)
171 {
172         struct file *file = lo->lo_backing_file;
173         struct address_space *mapping = file->f_mapping;
174         struct inode *inode = mapping->host;
175         unsigned short sb_bsize = 0;
176         unsigned dio_align = 0;
177         bool use_dio;
178
179         if (inode->i_sb->s_bdev) {
180                 sb_bsize = bdev_logical_block_size(inode->i_sb->s_bdev);
181                 dio_align = sb_bsize - 1;
182         }
183
184         /*
185          * We support direct I/O only if lo_offset is aligned with the
186          * logical I/O size of backing device, and the logical block
187          * size of loop is bigger than the backing device's and the loop
188          * needn't transform transfer.
189          *
190          * TODO: the above condition may be loosed in the future, and
191          * direct I/O may be switched runtime at that time because most
192          * of requests in sane applications should be PAGE_SIZE aligned
193          */
194         if (dio) {
195                 if (queue_logical_block_size(lo->lo_queue) >= sb_bsize &&
196                                 !(lo->lo_offset & dio_align) &&
197                                 mapping->a_ops->direct_IO &&
198                                 !lo->transfer)
199                         use_dio = true;
200                 else
201                         use_dio = false;
202         } else {
203                 use_dio = false;
204         }
205
206         if (lo->use_dio == use_dio)
207                 return;
208
209         /* flush dirty pages before changing direct IO */
210         vfs_fsync(file, 0);
211
212         /*
213          * The flag of LO_FLAGS_DIRECT_IO is handled similarly with
214          * LO_FLAGS_READ_ONLY, both are set from kernel, and losetup
215          * will get updated by ioctl(LOOP_GET_STATUS)
216          */
217         blk_mq_freeze_queue(lo->lo_queue);
218         lo->use_dio = use_dio;
219         if (use_dio) {
220                 blk_queue_flag_clear(QUEUE_FLAG_NOMERGES, lo->lo_queue);
221                 lo->lo_flags |= LO_FLAGS_DIRECT_IO;
222         } else {
223                 blk_queue_flag_set(QUEUE_FLAG_NOMERGES, lo->lo_queue);
224                 lo->lo_flags &= ~LO_FLAGS_DIRECT_IO;
225         }
226         blk_mq_unfreeze_queue(lo->lo_queue);
227 }
228
229 static int
230 figure_loop_size(struct loop_device *lo, loff_t offset, loff_t sizelimit)
231 {
232         loff_t size = get_size(offset, sizelimit, lo->lo_backing_file);
233         sector_t x = (sector_t)size;
234         struct block_device *bdev = lo->lo_device;
235
236         if (unlikely((loff_t)x != size))
237                 return -EFBIG;
238         if (lo->lo_offset != offset)
239                 lo->lo_offset = offset;
240         if (lo->lo_sizelimit != sizelimit)
241                 lo->lo_sizelimit = sizelimit;
242         set_capacity(lo->lo_disk, x);
243         bd_set_size(bdev, (loff_t)get_capacity(bdev->bd_disk) << 9);
244         /* let user-space know about the new size */
245         kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, KOBJ_CHANGE);
246         return 0;
247 }
248
249 static inline int
250 lo_do_transfer(struct loop_device *lo, int cmd,
251                struct page *rpage, unsigned roffs,
252                struct page *lpage, unsigned loffs,
253                int size, sector_t rblock)
254 {
255         int ret;
256
257         ret = lo->transfer(lo, cmd, rpage, roffs, lpage, loffs, size, rblock);
258         if (likely(!ret))
259                 return 0;
260
261         printk_ratelimited(KERN_ERR
262                 "loop: Transfer error at byte offset %llu, length %i.\n",
263                 (unsigned long long)rblock << 9, size);
264         return ret;
265 }
266
267 static int lo_write_bvec(struct file *file, struct bio_vec *bvec, loff_t *ppos)
268 {
269         struct iov_iter i;
270         ssize_t bw;
271
272         iov_iter_bvec(&i, WRITE, bvec, 1, bvec->bv_len);
273
274         file_start_write(file);
275         bw = vfs_iter_write(file, &i, ppos, 0);
276         file_end_write(file);
277
278         if (likely(bw ==  bvec->bv_len))
279                 return 0;
280
281         printk_ratelimited(KERN_ERR
282                 "loop: Write error at byte offset %llu, length %i.\n",
283                 (unsigned long long)*ppos, bvec->bv_len);
284         if (bw >= 0)
285                 bw = -EIO;
286         return bw;
287 }
288
289 static int lo_write_simple(struct loop_device *lo, struct request *rq,
290                 loff_t pos)
291 {
292         struct bio_vec bvec;
293         struct req_iterator iter;
294         int ret = 0;
295
296         rq_for_each_segment(bvec, rq, iter) {
297                 ret = lo_write_bvec(lo->lo_backing_file, &bvec, &pos);
298                 if (ret < 0)
299                         break;
300                 cond_resched();
301         }
302
303         return ret;
304 }
305
306 /*
307  * This is the slow, transforming version that needs to double buffer the
308  * data as it cannot do the transformations in place without having direct
309  * access to the destination pages of the backing file.
310  */
311 static int lo_write_transfer(struct loop_device *lo, struct request *rq,
312                 loff_t pos)
313 {
314         struct bio_vec bvec, b;
315         struct req_iterator iter;
316         struct page *page;
317         int ret = 0;
318
319         page = alloc_page(GFP_NOIO);
320         if (unlikely(!page))
321                 return -ENOMEM;
322
323         rq_for_each_segment(bvec, rq, iter) {
324                 ret = lo_do_transfer(lo, WRITE, page, 0, bvec.bv_page,
325                         bvec.bv_offset, bvec.bv_len, pos >> 9);
326                 if (unlikely(ret))
327                         break;
328
329                 b.bv_page = page;
330                 b.bv_offset = 0;
331                 b.bv_len = bvec.bv_len;
332                 ret = lo_write_bvec(lo->lo_backing_file, &b, &pos);
333                 if (ret < 0)
334                         break;
335         }
336
337         __free_page(page);
338         return ret;
339 }
340
341 static int lo_read_simple(struct loop_device *lo, struct request *rq,
342                 loff_t pos)
343 {
344         struct bio_vec bvec;
345         struct req_iterator iter;
346         struct iov_iter i;
347         ssize_t len;
348
349         rq_for_each_segment(bvec, rq, iter) {
350                 iov_iter_bvec(&i, READ, &bvec, 1, bvec.bv_len);
351                 len = vfs_iter_read(lo->lo_backing_file, &i, &pos, 0);
352                 if (len < 0)
353                         return len;
354
355                 flush_dcache_page(bvec.bv_page);
356
357                 if (len != bvec.bv_len) {
358                         struct bio *bio;
359
360                         __rq_for_each_bio(bio, rq)
361                                 zero_fill_bio(bio);
362                         break;
363                 }
364                 cond_resched();
365         }
366
367         return 0;
368 }
369
370 static int lo_read_transfer(struct loop_device *lo, struct request *rq,
371                 loff_t pos)
372 {
373         struct bio_vec bvec, b;
374         struct req_iterator iter;
375         struct iov_iter i;
376         struct page *page;
377         ssize_t len;
378         int ret = 0;
379
380         page = alloc_page(GFP_NOIO);
381         if (unlikely(!page))
382                 return -ENOMEM;
383
384         rq_for_each_segment(bvec, rq, iter) {
385                 loff_t offset = pos;
386
387                 b.bv_page = page;
388                 b.bv_offset = 0;
389                 b.bv_len = bvec.bv_len;
390
391                 iov_iter_bvec(&i, READ, &b, 1, b.bv_len);
392                 len = vfs_iter_read(lo->lo_backing_file, &i, &pos, 0);
393                 if (len < 0) {
394                         ret = len;
395                         goto out_free_page;
396                 }
397
398                 ret = lo_do_transfer(lo, READ, page, 0, bvec.bv_page,
399                         bvec.bv_offset, len, offset >> 9);
400                 if (ret)
401                         goto out_free_page;
402
403                 flush_dcache_page(bvec.bv_page);
404
405                 if (len != bvec.bv_len) {
406                         struct bio *bio;
407
408                         __rq_for_each_bio(bio, rq)
409                                 zero_fill_bio(bio);
410                         break;
411                 }
412         }
413
414         ret = 0;
415 out_free_page:
416         __free_page(page);
417         return ret;
418 }
419
420 static int lo_fallocate(struct loop_device *lo, struct request *rq, loff_t pos,
421                         int mode)
422 {
423         /*
424          * We use fallocate to manipulate the space mappings used by the image
425          * a.k.a. discard/zerorange. However we do not support this if
426          * encryption is enabled, because it may give an attacker useful
427          * information.
428          */
429         struct file *file = lo->lo_backing_file;
430         struct request_queue *q = lo->lo_queue;
431         int ret;
432
433         mode |= FALLOC_FL_KEEP_SIZE;
434
435         if (!blk_queue_discard(q)) {
436                 ret = -EOPNOTSUPP;
437                 goto out;
438         }
439
440         ret = file->f_op->fallocate(file, mode, pos, blk_rq_bytes(rq));
441         if (unlikely(ret && ret != -EINVAL && ret != -EOPNOTSUPP))
442                 ret = -EIO;
443  out:
444         return ret;
445 }
446
447 static int lo_req_flush(struct loop_device *lo, struct request *rq)
448 {
449         struct file *file = lo->lo_backing_file;
450         int ret = vfs_fsync(file, 0);
451         if (unlikely(ret && ret != -EINVAL))
452                 ret = -EIO;
453
454         return ret;
455 }
456
457 static void lo_complete_rq(struct request *rq)
458 {
459         struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
460         blk_status_t ret = BLK_STS_OK;
461
462         if (!cmd->use_aio || cmd->ret < 0 || cmd->ret == blk_rq_bytes(rq) ||
463             req_op(rq) != REQ_OP_READ) {
464                 if (cmd->ret < 0)
465                         ret = BLK_STS_IOERR;
466                 goto end_io;
467         }
468
469         /*
470          * Short READ - if we got some data, advance our request and
471          * retry it. If we got no data, end the rest with EIO.
472          */
473         if (cmd->ret) {
474                 blk_update_request(rq, BLK_STS_OK, cmd->ret);
475                 cmd->ret = 0;
476                 blk_mq_requeue_request(rq, true);
477         } else {
478                 if (cmd->use_aio) {
479                         struct bio *bio = rq->bio;
480
481                         while (bio) {
482                                 zero_fill_bio(bio);
483                                 bio = bio->bi_next;
484                         }
485                 }
486                 ret = BLK_STS_IOERR;
487 end_io:
488                 blk_mq_end_request(rq, ret);
489         }
490 }
491
492 static void lo_rw_aio_do_completion(struct loop_cmd *cmd)
493 {
494         struct request *rq = blk_mq_rq_from_pdu(cmd);
495
496         if (!atomic_dec_and_test(&cmd->ref))
497                 return;
498         kfree(cmd->bvec);
499         cmd->bvec = NULL;
500         blk_mq_complete_request(rq);
501 }
502
503 static void lo_rw_aio_complete(struct kiocb *iocb, long ret, long ret2)
504 {
505         struct loop_cmd *cmd = container_of(iocb, struct loop_cmd, iocb);
506
507         if (cmd->css)
508                 css_put(cmd->css);
509         cmd->ret = ret;
510         lo_rw_aio_do_completion(cmd);
511 }
512
513 static int lo_rw_aio(struct loop_device *lo, struct loop_cmd *cmd,
514                      loff_t pos, bool rw)
515 {
516         struct iov_iter iter;
517         struct req_iterator rq_iter;
518         struct bio_vec *bvec;
519         struct request *rq = blk_mq_rq_from_pdu(cmd);
520         struct bio *bio = rq->bio;
521         struct file *file = lo->lo_backing_file;
522         struct bio_vec tmp;
523         unsigned int offset;
524         int nr_bvec = 0;
525         int ret;
526
527         rq_for_each_bvec(tmp, rq, rq_iter)
528                 nr_bvec++;
529
530         if (rq->bio != rq->biotail) {
531
532                 bvec = kmalloc_array(nr_bvec, sizeof(struct bio_vec),
533                                      GFP_NOIO);
534                 if (!bvec)
535                         return -EIO;
536                 cmd->bvec = bvec;
537
538                 /*
539                  * The bios of the request may be started from the middle of
540                  * the 'bvec' because of bio splitting, so we can't directly
541                  * copy bio->bi_iov_vec to new bvec. The rq_for_each_bvec
542                  * API will take care of all details for us.
543                  */
544                 rq_for_each_bvec(tmp, rq, rq_iter) {
545                         *bvec = tmp;
546                         bvec++;
547                 }
548                 bvec = cmd->bvec;
549                 offset = 0;
550         } else {
551                 /*
552                  * Same here, this bio may be started from the middle of the
553                  * 'bvec' because of bio splitting, so offset from the bvec
554                  * must be passed to iov iterator
555                  */
556                 offset = bio->bi_iter.bi_bvec_done;
557                 bvec = __bvec_iter_bvec(bio->bi_io_vec, bio->bi_iter);
558         }
559         atomic_set(&cmd->ref, 2);
560
561         iov_iter_bvec(&iter, rw, bvec, nr_bvec, blk_rq_bytes(rq));
562         iter.iov_offset = offset;
563
564         cmd->iocb.ki_pos = pos;
565         cmd->iocb.ki_filp = file;
566         cmd->iocb.ki_complete = lo_rw_aio_complete;
567         cmd->iocb.ki_flags = IOCB_DIRECT;
568         cmd->iocb.ki_ioprio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_NONE, 0);
569         if (cmd->css)
570                 kthread_associate_blkcg(cmd->css);
571
572         if (rw == WRITE)
573                 ret = call_write_iter(file, &cmd->iocb, &iter);
574         else
575                 ret = call_read_iter(file, &cmd->iocb, &iter);
576
577         lo_rw_aio_do_completion(cmd);
578         kthread_associate_blkcg(NULL);
579
580         if (ret != -EIOCBQUEUED)
581                 cmd->iocb.ki_complete(&cmd->iocb, ret, 0);
582         return 0;
583 }
584
585 static int do_req_filebacked(struct loop_device *lo, struct request *rq)
586 {
587         struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
588         loff_t pos = ((loff_t) blk_rq_pos(rq) << 9) + lo->lo_offset;
589
590         /*
591          * lo_write_simple and lo_read_simple should have been covered
592          * by io submit style function like lo_rw_aio(), one blocker
593          * is that lo_read_simple() need to call flush_dcache_page after
594          * the page is written from kernel, and it isn't easy to handle
595          * this in io submit style function which submits all segments
596          * of the req at one time. And direct read IO doesn't need to
597          * run flush_dcache_page().
598          */
599         switch (req_op(rq)) {
600         case REQ_OP_FLUSH:
601                 return lo_req_flush(lo, rq);
602         case REQ_OP_WRITE_ZEROES:
603                 /*
604                  * If the caller doesn't want deallocation, call zeroout to
605                  * write zeroes the range.  Otherwise, punch them out.
606                  */
607                 return lo_fallocate(lo, rq, pos,
608                         (rq->cmd_flags & REQ_NOUNMAP) ?
609                                 FALLOC_FL_ZERO_RANGE :
610                                 FALLOC_FL_PUNCH_HOLE);
611         case REQ_OP_DISCARD:
612                 return lo_fallocate(lo, rq, pos, FALLOC_FL_PUNCH_HOLE);
613         case REQ_OP_WRITE:
614                 if (lo->transfer)
615                         return lo_write_transfer(lo, rq, pos);
616                 else if (cmd->use_aio)
617                         return lo_rw_aio(lo, cmd, pos, WRITE);
618                 else
619                         return lo_write_simple(lo, rq, pos);
620         case REQ_OP_READ:
621                 if (lo->transfer)
622                         return lo_read_transfer(lo, rq, pos);
623                 else if (cmd->use_aio)
624                         return lo_rw_aio(lo, cmd, pos, READ);
625                 else
626                         return lo_read_simple(lo, rq, pos);
627         default:
628                 WARN_ON_ONCE(1);
629                 return -EIO;
630         }
631 }
632
633 static inline void loop_update_dio(struct loop_device *lo)
634 {
635         __loop_update_dio(lo, io_is_direct(lo->lo_backing_file) |
636                         lo->use_dio);
637 }
638
639 static void loop_reread_partitions(struct loop_device *lo,
640                                    struct block_device *bdev)
641 {
642         int rc;
643
644         rc = blkdev_reread_part(bdev);
645         if (rc)
646                 pr_warn("%s: partition scan of loop%d (%s) failed (rc=%d)\n",
647                         __func__, lo->lo_number, lo->lo_file_name, rc);
648 }
649
650 static inline int is_loop_device(struct file *file)
651 {
652         struct inode *i = file->f_mapping->host;
653
654         return i && S_ISBLK(i->i_mode) && MAJOR(i->i_rdev) == LOOP_MAJOR;
655 }
656
657 static int loop_validate_file(struct file *file, struct block_device *bdev)
658 {
659         struct inode    *inode = file->f_mapping->host;
660         struct file     *f = file;
661
662         /* Avoid recursion */
663         while (is_loop_device(f)) {
664                 struct loop_device *l;
665
666                 if (f->f_mapping->host->i_bdev == bdev)
667                         return -EBADF;
668
669                 l = f->f_mapping->host->i_bdev->bd_disk->private_data;
670                 if (l->lo_state != Lo_bound) {
671                         return -EINVAL;
672                 }
673                 f = l->lo_backing_file;
674         }
675         if (!S_ISREG(inode->i_mode) && !S_ISBLK(inode->i_mode))
676                 return -EINVAL;
677         return 0;
678 }
679
680 /*
681  * loop_change_fd switched the backing store of a loopback device to
682  * a new file. This is useful for operating system installers to free up
683  * the original file and in High Availability environments to switch to
684  * an alternative location for the content in case of server meltdown.
685  * This can only work if the loop device is used read-only, and if the
686  * new backing store is the same size and type as the old backing store.
687  */
688 static int loop_change_fd(struct loop_device *lo, struct block_device *bdev,
689                           unsigned int arg)
690 {
691         struct file     *file = NULL, *old_file;
692         int             error;
693         bool            partscan;
694
695         error = mutex_lock_killable(&loop_ctl_mutex);
696         if (error)
697                 return error;
698         error = -ENXIO;
699         if (lo->lo_state != Lo_bound)
700                 goto out_err;
701
702         /* the loop device has to be read-only */
703         error = -EINVAL;
704         if (!(lo->lo_flags & LO_FLAGS_READ_ONLY))
705                 goto out_err;
706
707         error = -EBADF;
708         file = fget(arg);
709         if (!file)
710                 goto out_err;
711
712         error = loop_validate_file(file, bdev);
713         if (error)
714                 goto out_err;
715
716         old_file = lo->lo_backing_file;
717
718         error = -EINVAL;
719
720         /* size of the new backing store needs to be the same */
721         if (get_loop_size(lo, file) != get_loop_size(lo, old_file))
722                 goto out_err;
723
724         /* and ... switch */
725         blk_mq_freeze_queue(lo->lo_queue);
726         mapping_set_gfp_mask(old_file->f_mapping, lo->old_gfp_mask);
727         lo->lo_backing_file = file;
728         lo->old_gfp_mask = mapping_gfp_mask(file->f_mapping);
729         mapping_set_gfp_mask(file->f_mapping,
730                              lo->old_gfp_mask & ~(__GFP_IO|__GFP_FS));
731         loop_update_dio(lo);
732         blk_mq_unfreeze_queue(lo->lo_queue);
733         partscan = lo->lo_flags & LO_FLAGS_PARTSCAN;
734         mutex_unlock(&loop_ctl_mutex);
735         /*
736          * We must drop file reference outside of loop_ctl_mutex as dropping
737          * the file ref can take bd_mutex which creates circular locking
738          * dependency.
739          */
740         fput(old_file);
741         if (partscan)
742                 loop_reread_partitions(lo, bdev);
743         return 0;
744
745 out_err:
746         mutex_unlock(&loop_ctl_mutex);
747         if (file)
748                 fput(file);
749         return error;
750 }
751
752 /* loop sysfs attributes */
753
754 static ssize_t loop_attr_show(struct device *dev, char *page,
755                               ssize_t (*callback)(struct loop_device *, char *))
756 {
757         struct gendisk *disk = dev_to_disk(dev);
758         struct loop_device *lo = disk->private_data;
759
760         return callback(lo, page);
761 }
762
763 #define LOOP_ATTR_RO(_name)                                             \
764 static ssize_t loop_attr_##_name##_show(struct loop_device *, char *);  \
765 static ssize_t loop_attr_do_show_##_name(struct device *d,              \
766                                 struct device_attribute *attr, char *b) \
767 {                                                                       \
768         return loop_attr_show(d, b, loop_attr_##_name##_show);          \
769 }                                                                       \
770 static struct device_attribute loop_attr_##_name =                      \
771         __ATTR(_name, 0444, loop_attr_do_show_##_name, NULL);
772
773 static ssize_t loop_attr_backing_file_show(struct loop_device *lo, char *buf)
774 {
775         ssize_t ret;
776         char *p = NULL;
777
778         spin_lock_irq(&lo->lo_lock);
779         if (lo->lo_backing_file)
780                 p = file_path(lo->lo_backing_file, buf, PAGE_SIZE - 1);
781         spin_unlock_irq(&lo->lo_lock);
782
783         if (IS_ERR_OR_NULL(p))
784                 ret = PTR_ERR(p);
785         else {
786                 ret = strlen(p);
787                 memmove(buf, p, ret);
788                 buf[ret++] = '\n';
789                 buf[ret] = 0;
790         }
791
792         return ret;
793 }
794
795 static ssize_t loop_attr_offset_show(struct loop_device *lo, char *buf)
796 {
797         return sysfs_emit(buf, "%llu\n", (unsigned long long)lo->lo_offset);
798 }
799
800 static ssize_t loop_attr_sizelimit_show(struct loop_device *lo, char *buf)
801 {
802         return sysfs_emit(buf, "%llu\n", (unsigned long long)lo->lo_sizelimit);
803 }
804
805 static ssize_t loop_attr_autoclear_show(struct loop_device *lo, char *buf)
806 {
807         int autoclear = (lo->lo_flags & LO_FLAGS_AUTOCLEAR);
808
809         return sysfs_emit(buf, "%s\n", autoclear ? "1" : "0");
810 }
811
812 static ssize_t loop_attr_partscan_show(struct loop_device *lo, char *buf)
813 {
814         int partscan = (lo->lo_flags & LO_FLAGS_PARTSCAN);
815
816         return sysfs_emit(buf, "%s\n", partscan ? "1" : "0");
817 }
818
819 static ssize_t loop_attr_dio_show(struct loop_device *lo, char *buf)
820 {
821         int dio = (lo->lo_flags & LO_FLAGS_DIRECT_IO);
822
823         return sysfs_emit(buf, "%s\n", dio ? "1" : "0");
824 }
825
826 LOOP_ATTR_RO(backing_file);
827 LOOP_ATTR_RO(offset);
828 LOOP_ATTR_RO(sizelimit);
829 LOOP_ATTR_RO(autoclear);
830 LOOP_ATTR_RO(partscan);
831 LOOP_ATTR_RO(dio);
832
833 static struct attribute *loop_attrs[] = {
834         &loop_attr_backing_file.attr,
835         &loop_attr_offset.attr,
836         &loop_attr_sizelimit.attr,
837         &loop_attr_autoclear.attr,
838         &loop_attr_partscan.attr,
839         &loop_attr_dio.attr,
840         NULL,
841 };
842
843 static struct attribute_group loop_attribute_group = {
844         .name = "loop",
845         .attrs= loop_attrs,
846 };
847
848 static void loop_sysfs_init(struct loop_device *lo)
849 {
850         lo->sysfs_inited = !sysfs_create_group(&disk_to_dev(lo->lo_disk)->kobj,
851                                                 &loop_attribute_group);
852 }
853
854 static void loop_sysfs_exit(struct loop_device *lo)
855 {
856         if (lo->sysfs_inited)
857                 sysfs_remove_group(&disk_to_dev(lo->lo_disk)->kobj,
858                                    &loop_attribute_group);
859 }
860
861 static void loop_config_discard(struct loop_device *lo)
862 {
863         struct file *file = lo->lo_backing_file;
864         struct inode *inode = file->f_mapping->host;
865         struct request_queue *q = lo->lo_queue;
866         u32 granularity, max_discard_sectors;
867
868         /*
869          * If the backing device is a block device, mirror its zeroing
870          * capability. Set the discard sectors to the block device's zeroing
871          * capabilities because loop discards result in blkdev_issue_zeroout(),
872          * not blkdev_issue_discard(). This maintains consistent behavior with
873          * file-backed loop devices: discarded regions read back as zero.
874          */
875         if (S_ISBLK(inode->i_mode) && !lo->lo_encrypt_key_size) {
876                 struct request_queue *backingq;
877
878                 backingq = bdev_get_queue(inode->i_bdev);
879
880                 max_discard_sectors = backingq->limits.max_write_zeroes_sectors;
881                 granularity = backingq->limits.discard_granularity ?:
882                         queue_physical_block_size(backingq);
883
884         /*
885          * We use punch hole to reclaim the free space used by the
886          * image a.k.a. discard. However we do not support discard if
887          * encryption is enabled, because it may give an attacker
888          * useful information.
889          */
890         } else if (!file->f_op->fallocate || lo->lo_encrypt_key_size) {
891                 max_discard_sectors = 0;
892                 granularity = 0;
893
894         } else {
895                 max_discard_sectors = UINT_MAX >> 9;
896                 granularity = inode->i_sb->s_blocksize;
897         }
898
899         if (max_discard_sectors) {
900                 q->limits.discard_granularity = granularity;
901                 blk_queue_max_discard_sectors(q, max_discard_sectors);
902                 blk_queue_max_write_zeroes_sectors(q, max_discard_sectors);
903                 blk_queue_flag_set(QUEUE_FLAG_DISCARD, q);
904         } else {
905                 q->limits.discard_granularity = 0;
906                 blk_queue_max_discard_sectors(q, 0);
907                 blk_queue_max_write_zeroes_sectors(q, 0);
908                 blk_queue_flag_clear(QUEUE_FLAG_DISCARD, q);
909         }
910         q->limits.discard_alignment = 0;
911 }
912
913 static void loop_unprepare_queue(struct loop_device *lo)
914 {
915         kthread_flush_worker(&lo->worker);
916         kthread_stop(lo->worker_task);
917 }
918
919 static int loop_kthread_worker_fn(void *worker_ptr)
920 {
921         current->flags |= PF_LESS_THROTTLE | PF_MEMALLOC_NOIO;
922         return kthread_worker_fn(worker_ptr);
923 }
924
925 static int loop_prepare_queue(struct loop_device *lo)
926 {
927         kthread_init_worker(&lo->worker);
928         lo->worker_task = kthread_run(loop_kthread_worker_fn,
929                         &lo->worker, "loop%d", lo->lo_number);
930         if (IS_ERR(lo->worker_task))
931                 return -ENOMEM;
932         set_user_nice(lo->worker_task, MIN_NICE);
933         return 0;
934 }
935
936 static void loop_update_rotational(struct loop_device *lo)
937 {
938         struct file *file = lo->lo_backing_file;
939         struct inode *file_inode = file->f_mapping->host;
940         struct block_device *file_bdev = file_inode->i_sb->s_bdev;
941         struct request_queue *q = lo->lo_queue;
942         bool nonrot = true;
943
944         /* not all filesystems (e.g. tmpfs) have a sb->s_bdev */
945         if (file_bdev)
946                 nonrot = blk_queue_nonrot(bdev_get_queue(file_bdev));
947
948         if (nonrot)
949                 blk_queue_flag_set(QUEUE_FLAG_NONROT, q);
950         else
951                 blk_queue_flag_clear(QUEUE_FLAG_NONROT, q);
952 }
953
954 static int loop_set_fd(struct loop_device *lo, fmode_t mode,
955                        struct block_device *bdev, unsigned int arg)
956 {
957         struct file     *file;
958         struct inode    *inode;
959         struct address_space *mapping;
960         struct block_device *claimed_bdev = NULL;
961         int             lo_flags = 0;
962         int             error;
963         loff_t          size;
964         bool            partscan;
965
966         /* This is safe, since we have a reference from open(). */
967         __module_get(THIS_MODULE);
968
969         error = -EBADF;
970         file = fget(arg);
971         if (!file)
972                 goto out;
973
974         /*
975          * If we don't hold exclusive handle for the device, upgrade to it
976          * here to avoid changing device under exclusive owner.
977          */
978         if (!(mode & FMODE_EXCL)) {
979                 claimed_bdev = bd_start_claiming(bdev, loop_set_fd);
980                 if (IS_ERR(claimed_bdev)) {
981                         error = PTR_ERR(claimed_bdev);
982                         goto out_putf;
983                 }
984         }
985
986         error = mutex_lock_killable(&loop_ctl_mutex);
987         if (error)
988                 goto out_bdev;
989
990         error = -EBUSY;
991         if (lo->lo_state != Lo_unbound)
992                 goto out_unlock;
993
994         error = loop_validate_file(file, bdev);
995         if (error)
996                 goto out_unlock;
997
998         mapping = file->f_mapping;
999         inode = mapping->host;
1000
1001         if (!(file->f_mode & FMODE_WRITE) || !(mode & FMODE_WRITE) ||
1002             !file->f_op->write_iter)
1003                 lo_flags |= LO_FLAGS_READ_ONLY;
1004
1005         error = -EFBIG;
1006         size = get_loop_size(lo, file);
1007         if ((loff_t)(sector_t)size != size)
1008                 goto out_unlock;
1009         error = loop_prepare_queue(lo);
1010         if (error)
1011                 goto out_unlock;
1012
1013         error = 0;
1014
1015         set_device_ro(bdev, (lo_flags & LO_FLAGS_READ_ONLY) != 0);
1016
1017         lo->use_dio = false;
1018         lo->lo_device = bdev;
1019         lo->lo_flags = lo_flags;
1020         lo->lo_backing_file = file;
1021         lo->transfer = NULL;
1022         lo->ioctl = NULL;
1023         lo->lo_sizelimit = 0;
1024         lo->old_gfp_mask = mapping_gfp_mask(mapping);
1025         mapping_set_gfp_mask(mapping, lo->old_gfp_mask & ~(__GFP_IO|__GFP_FS));
1026
1027         if (!(lo_flags & LO_FLAGS_READ_ONLY) && file->f_op->fsync)
1028                 blk_queue_write_cache(lo->lo_queue, true, false);
1029
1030         if (io_is_direct(lo->lo_backing_file) && inode->i_sb->s_bdev) {
1031                 /* In case of direct I/O, match underlying block size */
1032                 unsigned short bsize = bdev_logical_block_size(
1033                         inode->i_sb->s_bdev);
1034
1035                 blk_queue_logical_block_size(lo->lo_queue, bsize);
1036                 blk_queue_physical_block_size(lo->lo_queue, bsize);
1037                 blk_queue_io_min(lo->lo_queue, bsize);
1038         }
1039
1040         loop_update_rotational(lo);
1041         loop_update_dio(lo);
1042         set_capacity(lo->lo_disk, size);
1043         bd_set_size(bdev, size << 9);
1044         loop_sysfs_init(lo);
1045         /* let user-space know about the new size */
1046         kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, KOBJ_CHANGE);
1047
1048         set_blocksize(bdev, S_ISBLK(inode->i_mode) ?
1049                       block_size(inode->i_bdev) : PAGE_SIZE);
1050
1051         lo->lo_state = Lo_bound;
1052         if (part_shift)
1053                 lo->lo_flags |= LO_FLAGS_PARTSCAN;
1054         partscan = lo->lo_flags & LO_FLAGS_PARTSCAN;
1055
1056         /* Grab the block_device to prevent its destruction after we
1057          * put /dev/loopXX inode. Later in __loop_clr_fd() we bdput(bdev).
1058          */
1059         bdgrab(bdev);
1060         mutex_unlock(&loop_ctl_mutex);
1061         if (partscan)
1062                 loop_reread_partitions(lo, bdev);
1063         if (claimed_bdev)
1064                 bd_abort_claiming(bdev, claimed_bdev, loop_set_fd);
1065         return 0;
1066
1067 out_unlock:
1068         mutex_unlock(&loop_ctl_mutex);
1069 out_bdev:
1070         if (claimed_bdev)
1071                 bd_abort_claiming(bdev, claimed_bdev, loop_set_fd);
1072 out_putf:
1073         fput(file);
1074 out:
1075         /* This is safe: open() is still holding a reference. */
1076         module_put(THIS_MODULE);
1077         return error;
1078 }
1079
1080 static int
1081 loop_release_xfer(struct loop_device *lo)
1082 {
1083         int err = 0;
1084         struct loop_func_table *xfer = lo->lo_encryption;
1085
1086         if (xfer) {
1087                 if (xfer->release)
1088                         err = xfer->release(lo);
1089                 lo->transfer = NULL;
1090                 lo->lo_encryption = NULL;
1091                 module_put(xfer->owner);
1092         }
1093         return err;
1094 }
1095
1096 static int
1097 loop_init_xfer(struct loop_device *lo, struct loop_func_table *xfer,
1098                const struct loop_info64 *i)
1099 {
1100         int err = 0;
1101
1102         if (xfer) {
1103                 struct module *owner = xfer->owner;
1104
1105                 if (!try_module_get(owner))
1106                         return -EINVAL;
1107                 if (xfer->init)
1108                         err = xfer->init(lo, i);
1109                 if (err)
1110                         module_put(owner);
1111                 else
1112                         lo->lo_encryption = xfer;
1113         }
1114         return err;
1115 }
1116
1117 static int __loop_clr_fd(struct loop_device *lo, bool release)
1118 {
1119         struct file *filp = NULL;
1120         gfp_t gfp = lo->old_gfp_mask;
1121         struct block_device *bdev = lo->lo_device;
1122         int err = 0;
1123         bool partscan = false;
1124         int lo_number;
1125
1126         mutex_lock(&loop_ctl_mutex);
1127         if (WARN_ON_ONCE(lo->lo_state != Lo_rundown)) {
1128                 err = -ENXIO;
1129                 goto out_unlock;
1130         }
1131
1132         filp = lo->lo_backing_file;
1133         if (filp == NULL) {
1134                 err = -EINVAL;
1135                 goto out_unlock;
1136         }
1137
1138         /* freeze request queue during the transition */
1139         blk_mq_freeze_queue(lo->lo_queue);
1140
1141         spin_lock_irq(&lo->lo_lock);
1142         lo->lo_backing_file = NULL;
1143         spin_unlock_irq(&lo->lo_lock);
1144
1145         loop_release_xfer(lo);
1146         lo->transfer = NULL;
1147         lo->ioctl = NULL;
1148         lo->lo_device = NULL;
1149         lo->lo_encryption = NULL;
1150         lo->lo_offset = 0;
1151         lo->lo_sizelimit = 0;
1152         lo->lo_encrypt_key_size = 0;
1153         memset(lo->lo_encrypt_key, 0, LO_KEY_SIZE);
1154         memset(lo->lo_crypt_name, 0, LO_NAME_SIZE);
1155         memset(lo->lo_file_name, 0, LO_NAME_SIZE);
1156         blk_queue_logical_block_size(lo->lo_queue, 512);
1157         blk_queue_physical_block_size(lo->lo_queue, 512);
1158         blk_queue_io_min(lo->lo_queue, 512);
1159         if (bdev) {
1160                 bdput(bdev);
1161                 invalidate_bdev(bdev);
1162                 bdev->bd_inode->i_mapping->wb_err = 0;
1163         }
1164         set_capacity(lo->lo_disk, 0);
1165         loop_sysfs_exit(lo);
1166         if (bdev) {
1167                 bd_set_size(bdev, 0);
1168                 /* let user-space know about this change */
1169                 kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, KOBJ_CHANGE);
1170         }
1171         mapping_set_gfp_mask(filp->f_mapping, gfp);
1172         /* This is safe: open() is still holding a reference. */
1173         module_put(THIS_MODULE);
1174         blk_mq_unfreeze_queue(lo->lo_queue);
1175
1176         partscan = lo->lo_flags & LO_FLAGS_PARTSCAN && bdev;
1177         lo_number = lo->lo_number;
1178         loop_unprepare_queue(lo);
1179 out_unlock:
1180         mutex_unlock(&loop_ctl_mutex);
1181         if (partscan) {
1182                 /*
1183                  * bd_mutex has been held already in release path, so don't
1184                  * acquire it if this function is called in such case.
1185                  *
1186                  * If the reread partition isn't from release path, lo_refcnt
1187                  * must be at least one and it can only become zero when the
1188                  * current holder is released.
1189                  */
1190                 if (release)
1191                         err = __blkdev_reread_part(bdev);
1192                 else
1193                         err = blkdev_reread_part(bdev);
1194                 if (err)
1195                         pr_warn("%s: partition scan of loop%d failed (rc=%d)\n",
1196                                 __func__, lo_number, err);
1197                 /* Device is gone, no point in returning error */
1198                 err = 0;
1199         }
1200
1201         /*
1202          * lo->lo_state is set to Lo_unbound here after above partscan has
1203          * finished.
1204          *
1205          * There cannot be anybody else entering __loop_clr_fd() as
1206          * lo->lo_backing_file is already cleared and Lo_rundown state
1207          * protects us from all the other places trying to change the 'lo'
1208          * device.
1209          */
1210         mutex_lock(&loop_ctl_mutex);
1211         lo->lo_flags = 0;
1212         if (!part_shift)
1213                 lo->lo_disk->flags |= GENHD_FL_NO_PART_SCAN;
1214         lo->lo_state = Lo_unbound;
1215         mutex_unlock(&loop_ctl_mutex);
1216
1217         /*
1218          * Need not hold loop_ctl_mutex to fput backing file.
1219          * Calling fput holding loop_ctl_mutex triggers a circular
1220          * lock dependency possibility warning as fput can take
1221          * bd_mutex which is usually taken before loop_ctl_mutex.
1222          */
1223         if (filp)
1224                 fput(filp);
1225         return err;
1226 }
1227
1228 static int loop_clr_fd(struct loop_device *lo)
1229 {
1230         int err;
1231
1232         err = mutex_lock_killable(&loop_ctl_mutex);
1233         if (err)
1234                 return err;
1235         if (lo->lo_state != Lo_bound) {
1236                 mutex_unlock(&loop_ctl_mutex);
1237                 return -ENXIO;
1238         }
1239         /*
1240          * If we've explicitly asked to tear down the loop device,
1241          * and it has an elevated reference count, set it for auto-teardown when
1242          * the last reference goes away. This stops $!~#$@ udev from
1243          * preventing teardown because it decided that it needs to run blkid on
1244          * the loopback device whenever they appear. xfstests is notorious for
1245          * failing tests because blkid via udev races with a losetup
1246          * <dev>/do something like mkfs/losetup -d <dev> causing the losetup -d
1247          * command to fail with EBUSY.
1248          */
1249         if (atomic_read(&lo->lo_refcnt) > 1) {
1250                 lo->lo_flags |= LO_FLAGS_AUTOCLEAR;
1251                 mutex_unlock(&loop_ctl_mutex);
1252                 return 0;
1253         }
1254         lo->lo_state = Lo_rundown;
1255         mutex_unlock(&loop_ctl_mutex);
1256
1257         return __loop_clr_fd(lo, false);
1258 }
1259
1260 static int
1261 loop_set_status(struct loop_device *lo, const struct loop_info64 *info)
1262 {
1263         int err;
1264         struct loop_func_table *xfer;
1265         kuid_t uid = current_uid();
1266         struct block_device *bdev;
1267         bool partscan = false;
1268
1269         err = mutex_lock_killable(&loop_ctl_mutex);
1270         if (err)
1271                 return err;
1272         if (lo->lo_encrypt_key_size &&
1273             !uid_eq(lo->lo_key_owner, uid) &&
1274             !capable(CAP_SYS_ADMIN)) {
1275                 err = -EPERM;
1276                 goto out_unlock;
1277         }
1278         if (lo->lo_state != Lo_bound) {
1279                 err = -ENXIO;
1280                 goto out_unlock;
1281         }
1282         if ((unsigned int) info->lo_encrypt_key_size > LO_KEY_SIZE) {
1283                 err = -EINVAL;
1284                 goto out_unlock;
1285         }
1286
1287         if (lo->lo_offset != info->lo_offset ||
1288             lo->lo_sizelimit != info->lo_sizelimit) {
1289                 sync_blockdev(lo->lo_device);
1290                 invalidate_bdev(lo->lo_device);
1291         }
1292
1293         /* I/O need to be drained during transfer transition */
1294         blk_mq_freeze_queue(lo->lo_queue);
1295
1296         err = loop_release_xfer(lo);
1297         if (err)
1298                 goto out_unfreeze;
1299
1300         if (info->lo_encrypt_type) {
1301                 unsigned int type = info->lo_encrypt_type;
1302
1303                 if (type >= MAX_LO_CRYPT) {
1304                         err = -EINVAL;
1305                         goto out_unfreeze;
1306                 }
1307                 xfer = xfer_funcs[type];
1308                 if (xfer == NULL) {
1309                         err = -EINVAL;
1310                         goto out_unfreeze;
1311                 }
1312         } else
1313                 xfer = NULL;
1314
1315         err = loop_init_xfer(lo, xfer, info);
1316         if (err)
1317                 goto out_unfreeze;
1318
1319         if (lo->lo_offset != info->lo_offset ||
1320             lo->lo_sizelimit != info->lo_sizelimit) {
1321                 /* kill_bdev should have truncated all the pages */
1322                 if (lo->lo_device->bd_inode->i_mapping->nrpages) {
1323                         err = -EAGAIN;
1324                         pr_warn("%s: loop%d (%s) has still dirty pages (nrpages=%lu)\n",
1325                                 __func__, lo->lo_number, lo->lo_file_name,
1326                                 lo->lo_device->bd_inode->i_mapping->nrpages);
1327                         goto out_unfreeze;
1328                 }
1329                 if (figure_loop_size(lo, info->lo_offset, info->lo_sizelimit)) {
1330                         err = -EFBIG;
1331                         goto out_unfreeze;
1332                 }
1333         }
1334
1335         loop_config_discard(lo);
1336
1337         memcpy(lo->lo_file_name, info->lo_file_name, LO_NAME_SIZE);
1338         memcpy(lo->lo_crypt_name, info->lo_crypt_name, LO_NAME_SIZE);
1339         lo->lo_file_name[LO_NAME_SIZE-1] = 0;
1340         lo->lo_crypt_name[LO_NAME_SIZE-1] = 0;
1341
1342         if (!xfer)
1343                 xfer = &none_funcs;
1344         lo->transfer = xfer->transfer;
1345         lo->ioctl = xfer->ioctl;
1346
1347         if ((lo->lo_flags & LO_FLAGS_AUTOCLEAR) !=
1348              (info->lo_flags & LO_FLAGS_AUTOCLEAR))
1349                 lo->lo_flags ^= LO_FLAGS_AUTOCLEAR;
1350
1351         lo->lo_encrypt_key_size = info->lo_encrypt_key_size;
1352         lo->lo_init[0] = info->lo_init[0];
1353         lo->lo_init[1] = info->lo_init[1];
1354         if (info->lo_encrypt_key_size) {
1355                 memcpy(lo->lo_encrypt_key, info->lo_encrypt_key,
1356                        info->lo_encrypt_key_size);
1357                 lo->lo_key_owner = uid;
1358         }
1359
1360         /* update dio if lo_offset or transfer is changed */
1361         __loop_update_dio(lo, lo->use_dio);
1362
1363 out_unfreeze:
1364         blk_mq_unfreeze_queue(lo->lo_queue);
1365
1366         if (!err && (info->lo_flags & LO_FLAGS_PARTSCAN) &&
1367              !(lo->lo_flags & LO_FLAGS_PARTSCAN)) {
1368                 lo->lo_flags |= LO_FLAGS_PARTSCAN;
1369                 lo->lo_disk->flags &= ~GENHD_FL_NO_PART_SCAN;
1370                 bdev = lo->lo_device;
1371                 partscan = true;
1372         }
1373 out_unlock:
1374         mutex_unlock(&loop_ctl_mutex);
1375         if (partscan)
1376                 loop_reread_partitions(lo, bdev);
1377
1378         return err;
1379 }
1380
1381 static int
1382 loop_get_status(struct loop_device *lo, struct loop_info64 *info)
1383 {
1384         struct path path;
1385         struct kstat stat;
1386         int ret;
1387
1388         ret = mutex_lock_killable(&loop_ctl_mutex);
1389         if (ret)
1390                 return ret;
1391         if (lo->lo_state != Lo_bound) {
1392                 mutex_unlock(&loop_ctl_mutex);
1393                 return -ENXIO;
1394         }
1395
1396         memset(info, 0, sizeof(*info));
1397         info->lo_number = lo->lo_number;
1398         info->lo_offset = lo->lo_offset;
1399         info->lo_sizelimit = lo->lo_sizelimit;
1400
1401         /* loff_t vars have been assigned __u64 */
1402         if (lo->lo_offset < 0 || lo->lo_sizelimit < 0)
1403                 return -EOVERFLOW;
1404
1405         info->lo_flags = lo->lo_flags;
1406         memcpy(info->lo_file_name, lo->lo_file_name, LO_NAME_SIZE);
1407         memcpy(info->lo_crypt_name, lo->lo_crypt_name, LO_NAME_SIZE);
1408         info->lo_encrypt_type =
1409                 lo->lo_encryption ? lo->lo_encryption->number : 0;
1410         if (lo->lo_encrypt_key_size && capable(CAP_SYS_ADMIN)) {
1411                 info->lo_encrypt_key_size = lo->lo_encrypt_key_size;
1412                 memcpy(info->lo_encrypt_key, lo->lo_encrypt_key,
1413                        lo->lo_encrypt_key_size);
1414         }
1415
1416         /* Drop loop_ctl_mutex while we call into the filesystem. */
1417         path = lo->lo_backing_file->f_path;
1418         path_get(&path);
1419         mutex_unlock(&loop_ctl_mutex);
1420         ret = vfs_getattr(&path, &stat, STATX_INO, AT_STATX_SYNC_AS_STAT);
1421         if (!ret) {
1422                 info->lo_device = huge_encode_dev(stat.dev);
1423                 info->lo_inode = stat.ino;
1424                 info->lo_rdevice = huge_encode_dev(stat.rdev);
1425         }
1426         path_put(&path);
1427         return ret;
1428 }
1429
1430 static void
1431 loop_info64_from_old(const struct loop_info *info, struct loop_info64 *info64)
1432 {
1433         memset(info64, 0, sizeof(*info64));
1434         info64->lo_number = info->lo_number;
1435         info64->lo_device = info->lo_device;
1436         info64->lo_inode = info->lo_inode;
1437         info64->lo_rdevice = info->lo_rdevice;
1438         info64->lo_offset = info->lo_offset;
1439         info64->lo_sizelimit = 0;
1440         info64->lo_encrypt_type = info->lo_encrypt_type;
1441         info64->lo_encrypt_key_size = info->lo_encrypt_key_size;
1442         info64->lo_flags = info->lo_flags;
1443         info64->lo_init[0] = info->lo_init[0];
1444         info64->lo_init[1] = info->lo_init[1];
1445         if (info->lo_encrypt_type == LO_CRYPT_CRYPTOAPI)
1446                 memcpy(info64->lo_crypt_name, info->lo_name, LO_NAME_SIZE);
1447         else
1448                 memcpy(info64->lo_file_name, info->lo_name, LO_NAME_SIZE);
1449         memcpy(info64->lo_encrypt_key, info->lo_encrypt_key, LO_KEY_SIZE);
1450 }
1451
1452 static int
1453 loop_info64_to_old(const struct loop_info64 *info64, struct loop_info *info)
1454 {
1455         memset(info, 0, sizeof(*info));
1456         info->lo_number = info64->lo_number;
1457         info->lo_device = info64->lo_device;
1458         info->lo_inode = info64->lo_inode;
1459         info->lo_rdevice = info64->lo_rdevice;
1460         info->lo_offset = info64->lo_offset;
1461         info->lo_encrypt_type = info64->lo_encrypt_type;
1462         info->lo_encrypt_key_size = info64->lo_encrypt_key_size;
1463         info->lo_flags = info64->lo_flags;
1464         info->lo_init[0] = info64->lo_init[0];
1465         info->lo_init[1] = info64->lo_init[1];
1466         if (info->lo_encrypt_type == LO_CRYPT_CRYPTOAPI)
1467                 memcpy(info->lo_name, info64->lo_crypt_name, LO_NAME_SIZE);
1468         else
1469                 memcpy(info->lo_name, info64->lo_file_name, LO_NAME_SIZE);
1470         memcpy(info->lo_encrypt_key, info64->lo_encrypt_key, LO_KEY_SIZE);
1471
1472         /* error in case values were truncated */
1473         if (info->lo_device != info64->lo_device ||
1474             info->lo_rdevice != info64->lo_rdevice ||
1475             info->lo_inode != info64->lo_inode ||
1476             info->lo_offset != info64->lo_offset)
1477                 return -EOVERFLOW;
1478
1479         return 0;
1480 }
1481
1482 static int
1483 loop_set_status_old(struct loop_device *lo, const struct loop_info __user *arg)
1484 {
1485         struct loop_info info;
1486         struct loop_info64 info64;
1487
1488         if (copy_from_user(&info, arg, sizeof (struct loop_info)))
1489                 return -EFAULT;
1490         loop_info64_from_old(&info, &info64);
1491         return loop_set_status(lo, &info64);
1492 }
1493
1494 static int
1495 loop_set_status64(struct loop_device *lo, const struct loop_info64 __user *arg)
1496 {
1497         struct loop_info64 info64;
1498
1499         if (copy_from_user(&info64, arg, sizeof (struct loop_info64)))
1500                 return -EFAULT;
1501         return loop_set_status(lo, &info64);
1502 }
1503
1504 static int
1505 loop_get_status_old(struct loop_device *lo, struct loop_info __user *arg) {
1506         struct loop_info info;
1507         struct loop_info64 info64;
1508         int err;
1509
1510         if (!arg)
1511                 return -EINVAL;
1512         err = loop_get_status(lo, &info64);
1513         if (!err)
1514                 err = loop_info64_to_old(&info64, &info);
1515         if (!err && copy_to_user(arg, &info, sizeof(info)))
1516                 err = -EFAULT;
1517
1518         return err;
1519 }
1520
1521 static int
1522 loop_get_status64(struct loop_device *lo, struct loop_info64 __user *arg) {
1523         struct loop_info64 info64;
1524         int err;
1525
1526         if (!arg)
1527                 return -EINVAL;
1528         err = loop_get_status(lo, &info64);
1529         if (!err && copy_to_user(arg, &info64, sizeof(info64)))
1530                 err = -EFAULT;
1531
1532         return err;
1533 }
1534
1535 static int loop_set_capacity(struct loop_device *lo)
1536 {
1537         if (unlikely(lo->lo_state != Lo_bound))
1538                 return -ENXIO;
1539
1540         return figure_loop_size(lo, lo->lo_offset, lo->lo_sizelimit);
1541 }
1542
1543 static int loop_set_dio(struct loop_device *lo, unsigned long arg)
1544 {
1545         int error = -ENXIO;
1546         if (lo->lo_state != Lo_bound)
1547                 goto out;
1548
1549         __loop_update_dio(lo, !!arg);
1550         if (lo->use_dio == !!arg)
1551                 return 0;
1552         error = -EINVAL;
1553  out:
1554         return error;
1555 }
1556
1557 static int loop_set_block_size(struct loop_device *lo, unsigned long arg)
1558 {
1559         int err = 0;
1560
1561         if (lo->lo_state != Lo_bound)
1562                 return -ENXIO;
1563
1564         if (arg < 512 || arg > PAGE_SIZE || !is_power_of_2(arg))
1565                 return -EINVAL;
1566
1567         if (lo->lo_queue->limits.logical_block_size != arg) {
1568                 sync_blockdev(lo->lo_device);
1569                 invalidate_bdev(lo->lo_device);
1570         }
1571
1572         blk_mq_freeze_queue(lo->lo_queue);
1573
1574         /* invalidate_bdev should have truncated all the pages */
1575         if (lo->lo_queue->limits.logical_block_size != arg &&
1576                         lo->lo_device->bd_inode->i_mapping->nrpages) {
1577                 err = -EAGAIN;
1578                 pr_warn("%s: loop%d (%s) has still dirty pages (nrpages=%lu)\n",
1579                         __func__, lo->lo_number, lo->lo_file_name,
1580                         lo->lo_device->bd_inode->i_mapping->nrpages);
1581                 goto out_unfreeze;
1582         }
1583
1584         blk_queue_logical_block_size(lo->lo_queue, arg);
1585         blk_queue_physical_block_size(lo->lo_queue, arg);
1586         blk_queue_io_min(lo->lo_queue, arg);
1587         loop_update_dio(lo);
1588 out_unfreeze:
1589         blk_mq_unfreeze_queue(lo->lo_queue);
1590
1591         return err;
1592 }
1593
1594 static int lo_simple_ioctl(struct loop_device *lo, unsigned int cmd,
1595                            unsigned long arg)
1596 {
1597         int err;
1598
1599         err = mutex_lock_killable(&loop_ctl_mutex);
1600         if (err)
1601                 return err;
1602         switch (cmd) {
1603         case LOOP_SET_CAPACITY:
1604                 err = loop_set_capacity(lo);
1605                 break;
1606         case LOOP_SET_DIRECT_IO:
1607                 err = loop_set_dio(lo, arg);
1608                 break;
1609         case LOOP_SET_BLOCK_SIZE:
1610                 err = loop_set_block_size(lo, arg);
1611                 break;
1612         default:
1613                 err = lo->ioctl ? lo->ioctl(lo, cmd, arg) : -EINVAL;
1614         }
1615         mutex_unlock(&loop_ctl_mutex);
1616         return err;
1617 }
1618
1619 static int lo_ioctl(struct block_device *bdev, fmode_t mode,
1620         unsigned int cmd, unsigned long arg)
1621 {
1622         struct loop_device *lo = bdev->bd_disk->private_data;
1623         int err;
1624
1625         switch (cmd) {
1626         case LOOP_SET_FD:
1627                 return loop_set_fd(lo, mode, bdev, arg);
1628         case LOOP_CHANGE_FD:
1629                 return loop_change_fd(lo, bdev, arg);
1630         case LOOP_CLR_FD:
1631                 return loop_clr_fd(lo);
1632         case LOOP_SET_STATUS:
1633                 err = -EPERM;
1634                 if ((mode & FMODE_WRITE) || capable(CAP_SYS_ADMIN)) {
1635                         err = loop_set_status_old(lo,
1636                                         (struct loop_info __user *)arg);
1637                 }
1638                 break;
1639         case LOOP_GET_STATUS:
1640                 return loop_get_status_old(lo, (struct loop_info __user *) arg);
1641         case LOOP_SET_STATUS64:
1642                 err = -EPERM;
1643                 if ((mode & FMODE_WRITE) || capable(CAP_SYS_ADMIN)) {
1644                         err = loop_set_status64(lo,
1645                                         (struct loop_info64 __user *) arg);
1646                 }
1647                 break;
1648         case LOOP_GET_STATUS64:
1649                 return loop_get_status64(lo, (struct loop_info64 __user *) arg);
1650         case LOOP_SET_CAPACITY:
1651         case LOOP_SET_DIRECT_IO:
1652         case LOOP_SET_BLOCK_SIZE:
1653                 if (!(mode & FMODE_WRITE) && !capable(CAP_SYS_ADMIN))
1654                         return -EPERM;
1655                 /* Fall through */
1656         default:
1657                 err = lo_simple_ioctl(lo, cmd, arg);
1658                 break;
1659         }
1660
1661         return err;
1662 }
1663
1664 #ifdef CONFIG_COMPAT
1665 struct compat_loop_info {
1666         compat_int_t    lo_number;      /* ioctl r/o */
1667         compat_dev_t    lo_device;      /* ioctl r/o */
1668         compat_ulong_t  lo_inode;       /* ioctl r/o */
1669         compat_dev_t    lo_rdevice;     /* ioctl r/o */
1670         compat_int_t    lo_offset;
1671         compat_int_t    lo_encrypt_type;
1672         compat_int_t    lo_encrypt_key_size;    /* ioctl w/o */
1673         compat_int_t    lo_flags;       /* ioctl r/o */
1674         char            lo_name[LO_NAME_SIZE];
1675         unsigned char   lo_encrypt_key[LO_KEY_SIZE]; /* ioctl w/o */
1676         compat_ulong_t  lo_init[2];
1677         char            reserved[4];
1678 };
1679
1680 /*
1681  * Transfer 32-bit compatibility structure in userspace to 64-bit loop info
1682  * - noinlined to reduce stack space usage in main part of driver
1683  */
1684 static noinline int
1685 loop_info64_from_compat(const struct compat_loop_info __user *arg,
1686                         struct loop_info64 *info64)
1687 {
1688         struct compat_loop_info info;
1689
1690         if (copy_from_user(&info, arg, sizeof(info)))
1691                 return -EFAULT;
1692
1693         memset(info64, 0, sizeof(*info64));
1694         info64->lo_number = info.lo_number;
1695         info64->lo_device = info.lo_device;
1696         info64->lo_inode = info.lo_inode;
1697         info64->lo_rdevice = info.lo_rdevice;
1698         info64->lo_offset = info.lo_offset;
1699         info64->lo_sizelimit = 0;
1700         info64->lo_encrypt_type = info.lo_encrypt_type;
1701         info64->lo_encrypt_key_size = info.lo_encrypt_key_size;
1702         info64->lo_flags = info.lo_flags;
1703         info64->lo_init[0] = info.lo_init[0];
1704         info64->lo_init[1] = info.lo_init[1];
1705         if (info.lo_encrypt_type == LO_CRYPT_CRYPTOAPI)
1706                 memcpy(info64->lo_crypt_name, info.lo_name, LO_NAME_SIZE);
1707         else
1708                 memcpy(info64->lo_file_name, info.lo_name, LO_NAME_SIZE);
1709         memcpy(info64->lo_encrypt_key, info.lo_encrypt_key, LO_KEY_SIZE);
1710         return 0;
1711 }
1712
1713 /*
1714  * Transfer 64-bit loop info to 32-bit compatibility structure in userspace
1715  * - noinlined to reduce stack space usage in main part of driver
1716  */
1717 static noinline int
1718 loop_info64_to_compat(const struct loop_info64 *info64,
1719                       struct compat_loop_info __user *arg)
1720 {
1721         struct compat_loop_info info;
1722
1723         memset(&info, 0, sizeof(info));
1724         info.lo_number = info64->lo_number;
1725         info.lo_device = info64->lo_device;
1726         info.lo_inode = info64->lo_inode;
1727         info.lo_rdevice = info64->lo_rdevice;
1728         info.lo_offset = info64->lo_offset;
1729         info.lo_encrypt_type = info64->lo_encrypt_type;
1730         info.lo_encrypt_key_size = info64->lo_encrypt_key_size;
1731         info.lo_flags = info64->lo_flags;
1732         info.lo_init[0] = info64->lo_init[0];
1733         info.lo_init[1] = info64->lo_init[1];
1734         if (info.lo_encrypt_type == LO_CRYPT_CRYPTOAPI)
1735                 memcpy(info.lo_name, info64->lo_crypt_name, LO_NAME_SIZE);
1736         else
1737                 memcpy(info.lo_name, info64->lo_file_name, LO_NAME_SIZE);
1738         memcpy(info.lo_encrypt_key, info64->lo_encrypt_key, LO_KEY_SIZE);
1739
1740         /* error in case values were truncated */
1741         if (info.lo_device != info64->lo_device ||
1742             info.lo_rdevice != info64->lo_rdevice ||
1743             info.lo_inode != info64->lo_inode ||
1744             info.lo_offset != info64->lo_offset ||
1745             info.lo_init[0] != info64->lo_init[0] ||
1746             info.lo_init[1] != info64->lo_init[1])
1747                 return -EOVERFLOW;
1748
1749         if (copy_to_user(arg, &info, sizeof(info)))
1750                 return -EFAULT;
1751         return 0;
1752 }
1753
1754 static int
1755 loop_set_status_compat(struct loop_device *lo,
1756                        const struct compat_loop_info __user *arg)
1757 {
1758         struct loop_info64 info64;
1759         int ret;
1760
1761         ret = loop_info64_from_compat(arg, &info64);
1762         if (ret < 0)
1763                 return ret;
1764         return loop_set_status(lo, &info64);
1765 }
1766
1767 static int
1768 loop_get_status_compat(struct loop_device *lo,
1769                        struct compat_loop_info __user *arg)
1770 {
1771         struct loop_info64 info64;
1772         int err;
1773
1774         if (!arg)
1775                 return -EINVAL;
1776         err = loop_get_status(lo, &info64);
1777         if (!err)
1778                 err = loop_info64_to_compat(&info64, arg);
1779         return err;
1780 }
1781
1782 static int lo_compat_ioctl(struct block_device *bdev, fmode_t mode,
1783                            unsigned int cmd, unsigned long arg)
1784 {
1785         struct loop_device *lo = bdev->bd_disk->private_data;
1786         int err;
1787
1788         switch(cmd) {
1789         case LOOP_SET_STATUS:
1790                 err = loop_set_status_compat(lo,
1791                              (const struct compat_loop_info __user *)arg);
1792                 break;
1793         case LOOP_GET_STATUS:
1794                 err = loop_get_status_compat(lo,
1795                                      (struct compat_loop_info __user *)arg);
1796                 break;
1797         case LOOP_SET_CAPACITY:
1798         case LOOP_CLR_FD:
1799         case LOOP_GET_STATUS64:
1800         case LOOP_SET_STATUS64:
1801                 arg = (unsigned long) compat_ptr(arg);
1802                 /* fall through */
1803         case LOOP_SET_FD:
1804         case LOOP_CHANGE_FD:
1805         case LOOP_SET_BLOCK_SIZE:
1806         case LOOP_SET_DIRECT_IO:
1807                 err = lo_ioctl(bdev, mode, cmd, arg);
1808                 break;
1809         default:
1810                 err = -ENOIOCTLCMD;
1811                 break;
1812         }
1813         return err;
1814 }
1815 #endif
1816
1817 static int lo_open(struct block_device *bdev, fmode_t mode)
1818 {
1819         struct loop_device *lo;
1820         int err;
1821
1822         err = mutex_lock_killable(&loop_ctl_mutex);
1823         if (err)
1824                 return err;
1825         lo = bdev->bd_disk->private_data;
1826         if (!lo) {
1827                 err = -ENXIO;
1828                 goto out;
1829         }
1830
1831         atomic_inc(&lo->lo_refcnt);
1832 out:
1833         mutex_unlock(&loop_ctl_mutex);
1834         return err;
1835 }
1836
1837 static void lo_release(struct gendisk *disk, fmode_t mode)
1838 {
1839         struct loop_device *lo;
1840
1841         mutex_lock(&loop_ctl_mutex);
1842         lo = disk->private_data;
1843         if (atomic_dec_return(&lo->lo_refcnt))
1844                 goto out_unlock;
1845
1846         if (lo->lo_flags & LO_FLAGS_AUTOCLEAR) {
1847                 if (lo->lo_state != Lo_bound)
1848                         goto out_unlock;
1849                 lo->lo_state = Lo_rundown;
1850                 mutex_unlock(&loop_ctl_mutex);
1851                 /*
1852                  * In autoclear mode, stop the loop thread
1853                  * and remove configuration after last close.
1854                  */
1855                 __loop_clr_fd(lo, true);
1856                 return;
1857         } else if (lo->lo_state == Lo_bound) {
1858                 /*
1859                  * Otherwise keep thread (if running) and config,
1860                  * but flush possible ongoing bios in thread.
1861                  */
1862                 blk_mq_freeze_queue(lo->lo_queue);
1863                 blk_mq_unfreeze_queue(lo->lo_queue);
1864         }
1865
1866 out_unlock:
1867         mutex_unlock(&loop_ctl_mutex);
1868 }
1869
1870 static const struct block_device_operations lo_fops = {
1871         .owner =        THIS_MODULE,
1872         .open =         lo_open,
1873         .release =      lo_release,
1874         .ioctl =        lo_ioctl,
1875 #ifdef CONFIG_COMPAT
1876         .compat_ioctl = lo_compat_ioctl,
1877 #endif
1878 };
1879
1880 /*
1881  * And now the modules code and kernel interface.
1882  */
1883 static int max_loop;
1884 module_param(max_loop, int, 0444);
1885 MODULE_PARM_DESC(max_loop, "Maximum number of loop devices");
1886 module_param(max_part, int, 0444);
1887 MODULE_PARM_DESC(max_part, "Maximum number of partitions per loop device");
1888 MODULE_LICENSE("GPL");
1889 MODULE_ALIAS_BLOCKDEV_MAJOR(LOOP_MAJOR);
1890
1891 int loop_register_transfer(struct loop_func_table *funcs)
1892 {
1893         unsigned int n = funcs->number;
1894
1895         if (n >= MAX_LO_CRYPT || xfer_funcs[n])
1896                 return -EINVAL;
1897         xfer_funcs[n] = funcs;
1898         return 0;
1899 }
1900
1901 static int unregister_transfer_cb(int id, void *ptr, void *data)
1902 {
1903         struct loop_device *lo = ptr;
1904         struct loop_func_table *xfer = data;
1905
1906         mutex_lock(&loop_ctl_mutex);
1907         if (lo->lo_encryption == xfer)
1908                 loop_release_xfer(lo);
1909         mutex_unlock(&loop_ctl_mutex);
1910         return 0;
1911 }
1912
1913 int loop_unregister_transfer(int number)
1914 {
1915         unsigned int n = number;
1916         struct loop_func_table *xfer;
1917
1918         if (n == 0 || n >= MAX_LO_CRYPT || (xfer = xfer_funcs[n]) == NULL)
1919                 return -EINVAL;
1920
1921         xfer_funcs[n] = NULL;
1922         idr_for_each(&loop_index_idr, &unregister_transfer_cb, xfer);
1923         return 0;
1924 }
1925
1926 EXPORT_SYMBOL(loop_register_transfer);
1927 EXPORT_SYMBOL(loop_unregister_transfer);
1928
1929 static blk_status_t loop_queue_rq(struct blk_mq_hw_ctx *hctx,
1930                 const struct blk_mq_queue_data *bd)
1931 {
1932         struct request *rq = bd->rq;
1933         struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
1934         struct loop_device *lo = rq->q->queuedata;
1935
1936         blk_mq_start_request(rq);
1937
1938         if (lo->lo_state != Lo_bound)
1939                 return BLK_STS_IOERR;
1940
1941         switch (req_op(rq)) {
1942         case REQ_OP_FLUSH:
1943         case REQ_OP_DISCARD:
1944         case REQ_OP_WRITE_ZEROES:
1945                 cmd->use_aio = false;
1946                 break;
1947         default:
1948                 cmd->use_aio = lo->use_dio;
1949                 break;
1950         }
1951
1952         /* always use the first bio's css */
1953 #ifdef CONFIG_BLK_CGROUP
1954         if (cmd->use_aio && rq->bio && rq->bio->bi_blkg) {
1955                 cmd->css = &bio_blkcg(rq->bio)->css;
1956                 css_get(cmd->css);
1957         } else
1958 #endif
1959                 cmd->css = NULL;
1960         kthread_queue_work(&lo->worker, &cmd->work);
1961
1962         return BLK_STS_OK;
1963 }
1964
1965 static void loop_handle_cmd(struct loop_cmd *cmd)
1966 {
1967         struct request *rq = blk_mq_rq_from_pdu(cmd);
1968         const bool write = op_is_write(req_op(rq));
1969         struct loop_device *lo = rq->q->queuedata;
1970         int ret = 0;
1971
1972         if (write && (lo->lo_flags & LO_FLAGS_READ_ONLY)) {
1973                 ret = -EIO;
1974                 goto failed;
1975         }
1976
1977         ret = do_req_filebacked(lo, rq);
1978  failed:
1979         /* complete non-aio request */
1980         if (!cmd->use_aio || ret) {
1981                 cmd->ret = ret ? -EIO : 0;
1982                 blk_mq_complete_request(rq);
1983         }
1984 }
1985
1986 static void loop_queue_work(struct kthread_work *work)
1987 {
1988         struct loop_cmd *cmd =
1989                 container_of(work, struct loop_cmd, work);
1990
1991         loop_handle_cmd(cmd);
1992 }
1993
1994 static int loop_init_request(struct blk_mq_tag_set *set, struct request *rq,
1995                 unsigned int hctx_idx, unsigned int numa_node)
1996 {
1997         struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
1998
1999         kthread_init_work(&cmd->work, loop_queue_work);
2000         return 0;
2001 }
2002
2003 static const struct blk_mq_ops loop_mq_ops = {
2004         .queue_rq       = loop_queue_rq,
2005         .init_request   = loop_init_request,
2006         .complete       = lo_complete_rq,
2007 };
2008
2009 static int loop_add(struct loop_device **l, int i)
2010 {
2011         struct loop_device *lo;
2012         struct gendisk *disk;
2013         int err;
2014
2015         err = -ENOMEM;
2016         lo = kzalloc(sizeof(*lo), GFP_KERNEL);
2017         if (!lo)
2018                 goto out;
2019
2020         lo->lo_state = Lo_unbound;
2021
2022         /* allocate id, if @id >= 0, we're requesting that specific id */
2023         if (i >= 0) {
2024                 err = idr_alloc(&loop_index_idr, lo, i, i + 1, GFP_KERNEL);
2025                 if (err == -ENOSPC)
2026                         err = -EEXIST;
2027         } else {
2028                 err = idr_alloc(&loop_index_idr, lo, 0, 0, GFP_KERNEL);
2029         }
2030         if (err < 0)
2031                 goto out_free_dev;
2032         i = err;
2033
2034         err = -ENOMEM;
2035         lo->tag_set.ops = &loop_mq_ops;
2036         lo->tag_set.nr_hw_queues = 1;
2037         lo->tag_set.queue_depth = 128;
2038         lo->tag_set.numa_node = NUMA_NO_NODE;
2039         lo->tag_set.cmd_size = sizeof(struct loop_cmd);
2040         lo->tag_set.flags = BLK_MQ_F_SHOULD_MERGE;
2041         lo->tag_set.driver_data = lo;
2042
2043         err = blk_mq_alloc_tag_set(&lo->tag_set);
2044         if (err)
2045                 goto out_free_idr;
2046
2047         lo->lo_queue = blk_mq_init_queue(&lo->tag_set);
2048         if (IS_ERR(lo->lo_queue)) {
2049                 err = PTR_ERR(lo->lo_queue);
2050                 goto out_cleanup_tags;
2051         }
2052         lo->lo_queue->queuedata = lo;
2053
2054         blk_queue_max_hw_sectors(lo->lo_queue, BLK_DEF_MAX_SECTORS);
2055
2056         /*
2057          * By default, we do buffer IO, so it doesn't make sense to enable
2058          * merge because the I/O submitted to backing file is handled page by
2059          * page. For directio mode, merge does help to dispatch bigger request
2060          * to underlayer disk. We will enable merge once directio is enabled.
2061          */
2062         blk_queue_flag_set(QUEUE_FLAG_NOMERGES, lo->lo_queue);
2063
2064         err = -ENOMEM;
2065         disk = lo->lo_disk = alloc_disk(1 << part_shift);
2066         if (!disk)
2067                 goto out_free_queue;
2068
2069         /*
2070          * Disable partition scanning by default. The in-kernel partition
2071          * scanning can be requested individually per-device during its
2072          * setup. Userspace can always add and remove partitions from all
2073          * devices. The needed partition minors are allocated from the
2074          * extended minor space, the main loop device numbers will continue
2075          * to match the loop minors, regardless of the number of partitions
2076          * used.
2077          *
2078          * If max_part is given, partition scanning is globally enabled for
2079          * all loop devices. The minors for the main loop devices will be
2080          * multiples of max_part.
2081          *
2082          * Note: Global-for-all-devices, set-only-at-init, read-only module
2083          * parameteters like 'max_loop' and 'max_part' make things needlessly
2084          * complicated, are too static, inflexible and may surprise
2085          * userspace tools. Parameters like this in general should be avoided.
2086          */
2087         if (!part_shift)
2088                 disk->flags |= GENHD_FL_NO_PART_SCAN;
2089         disk->flags |= GENHD_FL_EXT_DEVT;
2090         atomic_set(&lo->lo_refcnt, 0);
2091         lo->lo_number           = i;
2092         spin_lock_init(&lo->lo_lock);
2093         disk->major             = LOOP_MAJOR;
2094         disk->first_minor       = i << part_shift;
2095         disk->fops              = &lo_fops;
2096         disk->private_data      = lo;
2097         disk->queue             = lo->lo_queue;
2098         sprintf(disk->disk_name, "loop%d", i);
2099         add_disk(disk);
2100         *l = lo;
2101         return lo->lo_number;
2102
2103 out_free_queue:
2104         blk_cleanup_queue(lo->lo_queue);
2105 out_cleanup_tags:
2106         blk_mq_free_tag_set(&lo->tag_set);
2107 out_free_idr:
2108         idr_remove(&loop_index_idr, i);
2109 out_free_dev:
2110         kfree(lo);
2111 out:
2112         return err;
2113 }
2114
2115 static void loop_remove(struct loop_device *lo)
2116 {
2117         del_gendisk(lo->lo_disk);
2118         blk_cleanup_queue(lo->lo_queue);
2119         blk_mq_free_tag_set(&lo->tag_set);
2120         put_disk(lo->lo_disk);
2121         kfree(lo);
2122 }
2123
2124 static int find_free_cb(int id, void *ptr, void *data)
2125 {
2126         struct loop_device *lo = ptr;
2127         struct loop_device **l = data;
2128
2129         if (lo->lo_state == Lo_unbound) {
2130                 *l = lo;
2131                 return 1;
2132         }
2133         return 0;
2134 }
2135
2136 static int loop_lookup(struct loop_device **l, int i)
2137 {
2138         struct loop_device *lo;
2139         int ret = -ENODEV;
2140
2141         if (i < 0) {
2142                 int err;
2143
2144                 err = idr_for_each(&loop_index_idr, &find_free_cb, &lo);
2145                 if (err == 1) {
2146                         *l = lo;
2147                         ret = lo->lo_number;
2148                 }
2149                 goto out;
2150         }
2151
2152         /* lookup and return a specific i */
2153         lo = idr_find(&loop_index_idr, i);
2154         if (lo) {
2155                 *l = lo;
2156                 ret = lo->lo_number;
2157         }
2158 out:
2159         return ret;
2160 }
2161
2162 static struct kobject *loop_probe(dev_t dev, int *part, void *data)
2163 {
2164         struct loop_device *lo;
2165         struct kobject *kobj;
2166         int err;
2167
2168         mutex_lock(&loop_ctl_mutex);
2169         err = loop_lookup(&lo, MINOR(dev) >> part_shift);
2170         if (err < 0)
2171                 err = loop_add(&lo, MINOR(dev) >> part_shift);
2172         if (err < 0)
2173                 kobj = NULL;
2174         else
2175                 kobj = get_disk_and_module(lo->lo_disk);
2176         mutex_unlock(&loop_ctl_mutex);
2177
2178         *part = 0;
2179         return kobj;
2180 }
2181
2182 static long loop_control_ioctl(struct file *file, unsigned int cmd,
2183                                unsigned long parm)
2184 {
2185         struct loop_device *lo;
2186         int ret;
2187
2188         ret = mutex_lock_killable(&loop_ctl_mutex);
2189         if (ret)
2190                 return ret;
2191
2192         ret = -ENOSYS;
2193         switch (cmd) {
2194         case LOOP_CTL_ADD:
2195                 ret = loop_lookup(&lo, parm);
2196                 if (ret >= 0) {
2197                         ret = -EEXIST;
2198                         break;
2199                 }
2200                 ret = loop_add(&lo, parm);
2201                 break;
2202         case LOOP_CTL_REMOVE:
2203                 ret = loop_lookup(&lo, parm);
2204                 if (ret < 0)
2205                         break;
2206                 if (lo->lo_state != Lo_unbound) {
2207                         ret = -EBUSY;
2208                         break;
2209                 }
2210                 if (atomic_read(&lo->lo_refcnt) > 0) {
2211                         ret = -EBUSY;
2212                         break;
2213                 }
2214                 lo->lo_disk->private_data = NULL;
2215                 idr_remove(&loop_index_idr, lo->lo_number);
2216                 loop_remove(lo);
2217                 break;
2218         case LOOP_CTL_GET_FREE:
2219                 ret = loop_lookup(&lo, -1);
2220                 if (ret >= 0)
2221                         break;
2222                 ret = loop_add(&lo, -1);
2223         }
2224         mutex_unlock(&loop_ctl_mutex);
2225
2226         return ret;
2227 }
2228
2229 static const struct file_operations loop_ctl_fops = {
2230         .open           = nonseekable_open,
2231         .unlocked_ioctl = loop_control_ioctl,
2232         .compat_ioctl   = loop_control_ioctl,
2233         .owner          = THIS_MODULE,
2234         .llseek         = noop_llseek,
2235 };
2236
2237 static struct miscdevice loop_misc = {
2238         .minor          = LOOP_CTRL_MINOR,
2239         .name           = "loop-control",
2240         .fops           = &loop_ctl_fops,
2241 };
2242
2243 MODULE_ALIAS_MISCDEV(LOOP_CTRL_MINOR);
2244 MODULE_ALIAS("devname:loop-control");
2245
2246 static int __init loop_init(void)
2247 {
2248         int i, nr;
2249         unsigned long range;
2250         struct loop_device *lo;
2251         int err;
2252
2253         part_shift = 0;
2254         if (max_part > 0) {
2255                 part_shift = fls(max_part);
2256
2257                 /*
2258                  * Adjust max_part according to part_shift as it is exported
2259                  * to user space so that user can decide correct minor number
2260                  * if [s]he want to create more devices.
2261                  *
2262                  * Note that -1 is required because partition 0 is reserved
2263                  * for the whole disk.
2264                  */
2265                 max_part = (1UL << part_shift) - 1;
2266         }
2267
2268         if ((1UL << part_shift) > DISK_MAX_PARTS) {
2269                 err = -EINVAL;
2270                 goto err_out;
2271         }
2272
2273         if (max_loop > 1UL << (MINORBITS - part_shift)) {
2274                 err = -EINVAL;
2275                 goto err_out;
2276         }
2277
2278         /*
2279          * If max_loop is specified, create that many devices upfront.
2280          * This also becomes a hard limit. If max_loop is not specified,
2281          * create CONFIG_BLK_DEV_LOOP_MIN_COUNT loop devices at module
2282          * init time. Loop devices can be requested on-demand with the
2283          * /dev/loop-control interface, or be instantiated by accessing
2284          * a 'dead' device node.
2285          */
2286         if (max_loop) {
2287                 nr = max_loop;
2288                 range = max_loop << part_shift;
2289         } else {
2290                 nr = CONFIG_BLK_DEV_LOOP_MIN_COUNT;
2291                 range = 1UL << MINORBITS;
2292         }
2293
2294         err = misc_register(&loop_misc);
2295         if (err < 0)
2296                 goto err_out;
2297
2298
2299         if (register_blkdev(LOOP_MAJOR, "loop")) {
2300                 err = -EIO;
2301                 goto misc_out;
2302         }
2303
2304         blk_register_region(MKDEV(LOOP_MAJOR, 0), range,
2305                                   THIS_MODULE, loop_probe, NULL, NULL);
2306
2307         /* pre-create number of devices given by config or max_loop */
2308         mutex_lock(&loop_ctl_mutex);
2309         for (i = 0; i < nr; i++)
2310                 loop_add(&lo, i);
2311         mutex_unlock(&loop_ctl_mutex);
2312
2313         printk(KERN_INFO "loop: module loaded\n");
2314         return 0;
2315
2316 misc_out:
2317         misc_deregister(&loop_misc);
2318 err_out:
2319         return err;
2320 }
2321
2322 static int loop_exit_cb(int id, void *ptr, void *data)
2323 {
2324         struct loop_device *lo = ptr;
2325
2326         loop_remove(lo);
2327         return 0;
2328 }
2329
2330 static void __exit loop_exit(void)
2331 {
2332         unsigned long range;
2333
2334         range = max_loop ? max_loop << part_shift : 1UL << MINORBITS;
2335
2336         mutex_lock(&loop_ctl_mutex);
2337
2338         idr_for_each(&loop_index_idr, &loop_exit_cb, NULL);
2339         idr_destroy(&loop_index_idr);
2340
2341         blk_unregister_region(MKDEV(LOOP_MAJOR, 0), range);
2342         unregister_blkdev(LOOP_MAJOR, "loop");
2343
2344         misc_deregister(&loop_misc);
2345
2346         mutex_unlock(&loop_ctl_mutex);
2347 }
2348
2349 module_init(loop_init);
2350 module_exit(loop_exit);
2351
2352 #ifndef MODULE
2353 static int __init max_loop_setup(char *str)
2354 {
2355         max_loop = simple_strtol(str, NULL, 0);
2356         return 1;
2357 }
2358
2359 __setup("max_loop=", max_loop_setup);
2360 #endif