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