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