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