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