2 * linux/drivers/block/loop.c
4 * Written by Theodore Ts'o, 3/29/93
6 * Copyright 1993 by Theodore Ts'o. Redistribution of this file is
7 * permitted under the GNU General Public License.
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
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
15 * Fixed do_loop_request() re-entrancy - Vincent.Renardias@waw.com Mar 20, 1997
17 * Added devfs support - Richard Gooch <rgooch@atnf.csiro.au> 16-Jan-1998
19 * Handle sparse backing files correctly - Kenn Humborg, Jun 28, 1998
21 * Loadable modules and other fixes by AK, 1998
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
27 * Maximum number of loop devices now dynamic via max_loop module parameter.
28 * Russell Kroll <rkroll@exploits.org> 19990701
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
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
37 * Jens Axboe <axboe@suse.de>, Nov 2000
39 * Support up to 256 loop devices
40 * Heinz Mauelshagen <mge@sistina.com>, Feb 2002
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
47 * - Advisory locking is ignored here.
48 * - Should use an own CAP_* category instead of CAP_SYS_ADMIN
52 #include <linux/module.h>
53 #include <linux/moduleparam.h>
54 #include <linux/sched.h>
56 #include <linux/file.h>
57 #include <linux/stat.h>
58 #include <linux/errno.h>
59 #include <linux/major.h>
60 #include <linux/wait.h>
61 #include <linux/blkdev.h>
62 #include <linux/blkpg.h>
63 #include <linux/init.h>
64 #include <linux/swap.h>
65 #include <linux/slab.h>
66 #include <linux/compat.h>
67 #include <linux/suspend.h>
68 #include <linux/freezer.h>
69 #include <linux/mutex.h>
70 #include <linux/writeback.h>
71 #include <linux/completion.h>
72 #include <linux/highmem.h>
73 #include <linux/kthread.h>
74 #include <linux/splice.h>
75 #include <linux/sysfs.h>
76 #include <linux/miscdevice.h>
77 #include <linux/falloc.h>
78 #include <linux/uio.h>
79 #include <linux/ioprio.h>
83 #include <linux/uaccess.h>
85 static DEFINE_IDR(loop_index_idr);
86 static DEFINE_MUTEX(loop_ctl_mutex);
89 static int part_shift;
91 static int transfer_xor(struct loop_device *lo, int cmd,
92 struct page *raw_page, unsigned raw_off,
93 struct page *loop_page, unsigned loop_off,
94 int size, sector_t real_block)
96 char *raw_buf = kmap_atomic(raw_page) + raw_off;
97 char *loop_buf = kmap_atomic(loop_page) + loop_off;
109 key = lo->lo_encrypt_key;
110 keysize = lo->lo_encrypt_key_size;
111 for (i = 0; i < size; i++)
112 *out++ = *in++ ^ key[(i & 511) % keysize];
114 kunmap_atomic(loop_buf);
115 kunmap_atomic(raw_buf);
120 static int xor_init(struct loop_device *lo, const struct loop_info64 *info)
122 if (unlikely(info->lo_encrypt_key_size <= 0))
127 static struct loop_func_table none_funcs = {
128 .number = LO_CRYPT_NONE,
131 static struct loop_func_table xor_funcs = {
132 .number = LO_CRYPT_XOR,
133 .transfer = transfer_xor,
137 /* xfer_funcs[0] is special - its release function is never called */
138 static struct loop_func_table *xfer_funcs[MAX_LO_CRYPT] = {
143 static loff_t get_size(loff_t offset, loff_t sizelimit, struct file *file)
147 /* Compute loopsize in bytes */
148 loopsize = i_size_read(file->f_mapping->host);
151 /* offset is beyond i_size, weird but possible */
155 if (sizelimit > 0 && sizelimit < loopsize)
156 loopsize = sizelimit;
158 * Unfortunately, if we want to do I/O on the device,
159 * the number of 512-byte sectors has to fit into a sector_t.
161 return loopsize >> 9;
164 static loff_t get_loop_size(struct loop_device *lo, struct file *file)
166 return get_size(lo->lo_offset, lo->lo_sizelimit, file);
169 static void __loop_update_dio(struct loop_device *lo, bool dio)
171 struct file *file = lo->lo_backing_file;
172 struct address_space *mapping = file->f_mapping;
173 struct inode *inode = mapping->host;
174 unsigned short sb_bsize = 0;
175 unsigned dio_align = 0;
178 if (inode->i_sb->s_bdev) {
179 sb_bsize = bdev_logical_block_size(inode->i_sb->s_bdev);
180 dio_align = sb_bsize - 1;
184 * We support direct I/O only if lo_offset is aligned with the
185 * logical I/O size of backing device, and the logical block
186 * size of loop is bigger than the backing device's and the loop
187 * needn't transform transfer.
189 * TODO: the above condition may be loosed in the future, and
190 * direct I/O may be switched runtime at that time because most
191 * of requests in sane applications should be PAGE_SIZE aligned
194 if (queue_logical_block_size(lo->lo_queue) >= sb_bsize &&
195 !(lo->lo_offset & dio_align) &&
196 mapping->a_ops->direct_IO &&
205 if (lo->use_dio == use_dio)
208 /* flush dirty pages before changing direct IO */
212 * The flag of LO_FLAGS_DIRECT_IO is handled similarly with
213 * LO_FLAGS_READ_ONLY, both are set from kernel, and losetup
214 * will get updated by ioctl(LOOP_GET_STATUS)
216 blk_mq_freeze_queue(lo->lo_queue);
217 lo->use_dio = use_dio;
219 blk_queue_flag_clear(QUEUE_FLAG_NOMERGES, lo->lo_queue);
220 lo->lo_flags |= LO_FLAGS_DIRECT_IO;
222 blk_queue_flag_set(QUEUE_FLAG_NOMERGES, lo->lo_queue);
223 lo->lo_flags &= ~LO_FLAGS_DIRECT_IO;
225 blk_mq_unfreeze_queue(lo->lo_queue);
229 * loop_set_size() - sets device size and notifies userspace
230 * @lo: struct loop_device to set the size for
231 * @size: new size of the loop device
233 * Callers must validate that the size passed into this function fits into
234 * a sector_t, eg using loop_validate_size()
236 static void loop_set_size(struct loop_device *lo, loff_t size)
238 struct block_device *bdev = lo->lo_device;
240 set_capacity(lo->lo_disk, size);
241 bd_set_size(bdev, size << SECTOR_SHIFT);
242 /* let user-space know about the new size */
243 kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, KOBJ_CHANGE);
247 figure_loop_size(struct loop_device *lo, loff_t offset, loff_t sizelimit)
249 loff_t size = get_size(offset, sizelimit, lo->lo_backing_file);
250 sector_t x = (sector_t)size;
252 if (unlikely((loff_t)x != size))
254 loop_set_size(lo, size);
259 lo_do_transfer(struct loop_device *lo, int cmd,
260 struct page *rpage, unsigned roffs,
261 struct page *lpage, unsigned loffs,
262 int size, sector_t rblock)
266 ret = lo->transfer(lo, cmd, rpage, roffs, lpage, loffs, size, rblock);
270 printk_ratelimited(KERN_ERR
271 "loop: Transfer error at byte offset %llu, length %i.\n",
272 (unsigned long long)rblock << 9, size);
276 static int lo_write_bvec(struct file *file, struct bio_vec *bvec, loff_t *ppos)
281 iov_iter_bvec(&i, ITER_BVEC | WRITE, bvec, 1, bvec->bv_len);
283 file_start_write(file);
284 bw = vfs_iter_write(file, &i, ppos, 0);
285 file_end_write(file);
287 if (likely(bw == bvec->bv_len))
290 printk_ratelimited(KERN_ERR
291 "loop: Write error at byte offset %llu, length %i.\n",
292 (unsigned long long)*ppos, bvec->bv_len);
298 static int lo_write_simple(struct loop_device *lo, struct request *rq,
302 struct req_iterator iter;
305 rq_for_each_segment(bvec, rq, iter) {
306 ret = lo_write_bvec(lo->lo_backing_file, &bvec, &pos);
316 * This is the slow, transforming version that needs to double buffer the
317 * data as it cannot do the transformations in place without having direct
318 * access to the destination pages of the backing file.
320 static int lo_write_transfer(struct loop_device *lo, struct request *rq,
323 struct bio_vec bvec, b;
324 struct req_iterator iter;
328 page = alloc_page(GFP_NOIO);
332 rq_for_each_segment(bvec, rq, iter) {
333 ret = lo_do_transfer(lo, WRITE, page, 0, bvec.bv_page,
334 bvec.bv_offset, bvec.bv_len, pos >> 9);
340 b.bv_len = bvec.bv_len;
341 ret = lo_write_bvec(lo->lo_backing_file, &b, &pos);
350 static int lo_read_simple(struct loop_device *lo, struct request *rq,
354 struct req_iterator iter;
358 rq_for_each_segment(bvec, rq, iter) {
359 iov_iter_bvec(&i, ITER_BVEC, &bvec, 1, bvec.bv_len);
360 len = vfs_iter_read(lo->lo_backing_file, &i, &pos, 0);
364 flush_dcache_page(bvec.bv_page);
366 if (len != bvec.bv_len) {
369 __rq_for_each_bio(bio, rq)
379 static int lo_read_transfer(struct loop_device *lo, struct request *rq,
382 struct bio_vec bvec, b;
383 struct req_iterator iter;
389 page = alloc_page(GFP_NOIO);
393 rq_for_each_segment(bvec, rq, iter) {
398 b.bv_len = bvec.bv_len;
400 iov_iter_bvec(&i, ITER_BVEC, &b, 1, b.bv_len);
401 len = vfs_iter_read(lo->lo_backing_file, &i, &pos, 0);
407 ret = lo_do_transfer(lo, READ, page, 0, bvec.bv_page,
408 bvec.bv_offset, len, offset >> 9);
412 flush_dcache_page(bvec.bv_page);
414 if (len != bvec.bv_len) {
417 __rq_for_each_bio(bio, rq)
429 static int lo_fallocate(struct loop_device *lo, struct request *rq, loff_t pos,
433 * We use fallocate to manipulate the space mappings used by the image
434 * a.k.a. discard/zerorange. However we do not support this if
435 * encryption is enabled, because it may give an attacker useful
438 struct file *file = lo->lo_backing_file;
439 struct request_queue *q = lo->lo_queue;
442 mode |= FALLOC_FL_KEEP_SIZE;
444 if (!blk_queue_discard(q)) {
449 ret = file->f_op->fallocate(file, mode, pos, blk_rq_bytes(rq));
450 if (unlikely(ret && ret != -EINVAL && ret != -EOPNOTSUPP))
456 static int lo_req_flush(struct loop_device *lo, struct request *rq)
458 struct file *file = lo->lo_backing_file;
459 int ret = vfs_fsync(file, 0);
460 if (unlikely(ret && ret != -EINVAL))
466 static void lo_complete_rq(struct request *rq)
468 struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
469 blk_status_t ret = BLK_STS_OK;
471 if (!cmd->use_aio || cmd->ret < 0 || cmd->ret == blk_rq_bytes(rq) ||
472 req_op(rq) != REQ_OP_READ) {
479 * Short READ - if we got some data, advance our request and
480 * retry it. If we got no data, end the rest with EIO.
483 blk_update_request(rq, BLK_STS_OK, cmd->ret);
485 blk_mq_requeue_request(rq, true);
488 struct bio *bio = rq->bio;
497 blk_mq_end_request(rq, ret);
501 static void lo_rw_aio_do_completion(struct loop_cmd *cmd)
503 struct request *rq = blk_mq_rq_from_pdu(cmd);
505 if (!atomic_dec_and_test(&cmd->ref))
509 blk_mq_complete_request(rq);
512 static void lo_rw_aio_complete(struct kiocb *iocb, long ret, long ret2)
514 struct loop_cmd *cmd = container_of(iocb, struct loop_cmd, iocb);
519 lo_rw_aio_do_completion(cmd);
522 static int lo_rw_aio(struct loop_device *lo, struct loop_cmd *cmd,
525 struct iov_iter iter;
526 struct bio_vec *bvec;
527 struct request *rq = blk_mq_rq_from_pdu(cmd);
528 struct bio *bio = rq->bio;
529 struct file *file = lo->lo_backing_file;
534 if (rq->bio != rq->biotail) {
535 struct req_iterator iter;
538 __rq_for_each_bio(bio, rq)
539 segments += bio_segments(bio);
540 bvec = kmalloc_array(segments, sizeof(struct bio_vec),
547 * The bios of the request may be started from the middle of
548 * the 'bvec' because of bio splitting, so we can't directly
549 * copy bio->bi_iov_vec to new bvec. The rq_for_each_segment
550 * API will take care of all details for us.
552 rq_for_each_segment(tmp, rq, iter) {
560 * Same here, this bio may be started from the middle of the
561 * 'bvec' because of bio splitting, so offset from the bvec
562 * must be passed to iov iterator
564 offset = bio->bi_iter.bi_bvec_done;
565 bvec = __bvec_iter_bvec(bio->bi_io_vec, bio->bi_iter);
566 segments = bio_segments(bio);
568 atomic_set(&cmd->ref, 2);
570 iov_iter_bvec(&iter, ITER_BVEC | rw, bvec,
571 segments, blk_rq_bytes(rq));
572 iter.iov_offset = offset;
574 cmd->iocb.ki_pos = pos;
575 cmd->iocb.ki_filp = file;
576 cmd->iocb.ki_complete = lo_rw_aio_complete;
577 cmd->iocb.ki_flags = IOCB_DIRECT;
578 cmd->iocb.ki_ioprio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_NONE, 0);
580 kthread_associate_blkcg(cmd->css);
583 ret = call_write_iter(file, &cmd->iocb, &iter);
585 ret = call_read_iter(file, &cmd->iocb, &iter);
587 lo_rw_aio_do_completion(cmd);
588 kthread_associate_blkcg(NULL);
590 if (ret != -EIOCBQUEUED)
591 cmd->iocb.ki_complete(&cmd->iocb, ret, 0);
595 static int do_req_filebacked(struct loop_device *lo, struct request *rq)
597 struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
598 loff_t pos = ((loff_t) blk_rq_pos(rq) << 9) + lo->lo_offset;
601 * lo_write_simple and lo_read_simple should have been covered
602 * by io submit style function like lo_rw_aio(), one blocker
603 * is that lo_read_simple() need to call flush_dcache_page after
604 * the page is written from kernel, and it isn't easy to handle
605 * this in io submit style function which submits all segments
606 * of the req at one time. And direct read IO doesn't need to
607 * run flush_dcache_page().
609 switch (req_op(rq)) {
611 return lo_req_flush(lo, rq);
612 case REQ_OP_WRITE_ZEROES:
614 * If the caller doesn't want deallocation, call zeroout to
615 * write zeroes the range. Otherwise, punch them out.
617 return lo_fallocate(lo, rq, pos,
618 (rq->cmd_flags & REQ_NOUNMAP) ?
619 FALLOC_FL_ZERO_RANGE :
620 FALLOC_FL_PUNCH_HOLE);
622 return lo_fallocate(lo, rq, pos, FALLOC_FL_PUNCH_HOLE);
625 return lo_write_transfer(lo, rq, pos);
626 else if (cmd->use_aio)
627 return lo_rw_aio(lo, cmd, pos, WRITE);
629 return lo_write_simple(lo, rq, pos);
632 return lo_read_transfer(lo, rq, pos);
633 else if (cmd->use_aio)
634 return lo_rw_aio(lo, cmd, pos, READ);
636 return lo_read_simple(lo, rq, pos);
644 static inline void loop_update_dio(struct loop_device *lo)
646 __loop_update_dio(lo, io_is_direct(lo->lo_backing_file) |
650 static void loop_reread_partitions(struct loop_device *lo,
651 struct block_device *bdev)
655 rc = blkdev_reread_part(bdev);
657 pr_warn("%s: partition scan of loop%d (%s) failed (rc=%d)\n",
658 __func__, lo->lo_number, lo->lo_file_name, rc);
661 static inline int is_loop_device(struct file *file)
663 struct inode *i = file->f_mapping->host;
665 return i && S_ISBLK(i->i_mode) && MAJOR(i->i_rdev) == LOOP_MAJOR;
668 static int loop_validate_file(struct file *file, struct block_device *bdev)
670 struct inode *inode = file->f_mapping->host;
671 struct file *f = file;
673 /* Avoid recursion */
674 while (is_loop_device(f)) {
675 struct loop_device *l;
677 if (f->f_mapping->host->i_bdev == bdev)
680 l = f->f_mapping->host->i_bdev->bd_disk->private_data;
681 if (l->lo_state != Lo_bound) {
684 f = l->lo_backing_file;
686 if (!S_ISREG(inode->i_mode) && !S_ISBLK(inode->i_mode))
692 * loop_change_fd switched the backing store of a loopback device to
693 * a new file. This is useful for operating system installers to free up
694 * the original file and in High Availability environments to switch to
695 * an alternative location for the content in case of server meltdown.
696 * This can only work if the loop device is used read-only, and if the
697 * new backing store is the same size and type as the old backing store.
699 static int loop_change_fd(struct loop_device *lo, struct block_device *bdev,
702 struct file *file = NULL, *old_file;
706 error = mutex_lock_killable(&loop_ctl_mutex);
710 if (lo->lo_state != Lo_bound)
713 /* the loop device has to be read-only */
715 if (!(lo->lo_flags & LO_FLAGS_READ_ONLY))
723 error = loop_validate_file(file, bdev);
727 old_file = lo->lo_backing_file;
731 /* size of the new backing store needs to be the same */
732 if (get_loop_size(lo, file) != get_loop_size(lo, old_file))
736 blk_mq_freeze_queue(lo->lo_queue);
737 mapping_set_gfp_mask(old_file->f_mapping, lo->old_gfp_mask);
738 lo->lo_backing_file = file;
739 lo->old_gfp_mask = mapping_gfp_mask(file->f_mapping);
740 mapping_set_gfp_mask(file->f_mapping,
741 lo->old_gfp_mask & ~(__GFP_IO|__GFP_FS));
743 blk_mq_unfreeze_queue(lo->lo_queue);
744 partscan = lo->lo_flags & LO_FLAGS_PARTSCAN;
745 mutex_unlock(&loop_ctl_mutex);
747 * We must drop file reference outside of loop_ctl_mutex as dropping
748 * the file ref can take bd_mutex which creates circular locking
753 loop_reread_partitions(lo, bdev);
757 mutex_unlock(&loop_ctl_mutex);
763 /* loop sysfs attributes */
765 static ssize_t loop_attr_show(struct device *dev, char *page,
766 ssize_t (*callback)(struct loop_device *, char *))
768 struct gendisk *disk = dev_to_disk(dev);
769 struct loop_device *lo = disk->private_data;
771 return callback(lo, page);
774 #define LOOP_ATTR_RO(_name) \
775 static ssize_t loop_attr_##_name##_show(struct loop_device *, char *); \
776 static ssize_t loop_attr_do_show_##_name(struct device *d, \
777 struct device_attribute *attr, char *b) \
779 return loop_attr_show(d, b, loop_attr_##_name##_show); \
781 static struct device_attribute loop_attr_##_name = \
782 __ATTR(_name, 0444, loop_attr_do_show_##_name, NULL);
784 static ssize_t loop_attr_backing_file_show(struct loop_device *lo, char *buf)
789 spin_lock_irq(&lo->lo_lock);
790 if (lo->lo_backing_file)
791 p = file_path(lo->lo_backing_file, buf, PAGE_SIZE - 1);
792 spin_unlock_irq(&lo->lo_lock);
794 if (IS_ERR_OR_NULL(p))
798 memmove(buf, p, ret);
806 static ssize_t loop_attr_offset_show(struct loop_device *lo, char *buf)
808 return sysfs_emit(buf, "%llu\n", (unsigned long long)lo->lo_offset);
811 static ssize_t loop_attr_sizelimit_show(struct loop_device *lo, char *buf)
813 return sysfs_emit(buf, "%llu\n", (unsigned long long)lo->lo_sizelimit);
816 static ssize_t loop_attr_autoclear_show(struct loop_device *lo, char *buf)
818 int autoclear = (lo->lo_flags & LO_FLAGS_AUTOCLEAR);
820 return sysfs_emit(buf, "%s\n", autoclear ? "1" : "0");
823 static ssize_t loop_attr_partscan_show(struct loop_device *lo, char *buf)
825 int partscan = (lo->lo_flags & LO_FLAGS_PARTSCAN);
827 return sysfs_emit(buf, "%s\n", partscan ? "1" : "0");
830 static ssize_t loop_attr_dio_show(struct loop_device *lo, char *buf)
832 int dio = (lo->lo_flags & LO_FLAGS_DIRECT_IO);
834 return sysfs_emit(buf, "%s\n", dio ? "1" : "0");
837 LOOP_ATTR_RO(backing_file);
838 LOOP_ATTR_RO(offset);
839 LOOP_ATTR_RO(sizelimit);
840 LOOP_ATTR_RO(autoclear);
841 LOOP_ATTR_RO(partscan);
844 static struct attribute *loop_attrs[] = {
845 &loop_attr_backing_file.attr,
846 &loop_attr_offset.attr,
847 &loop_attr_sizelimit.attr,
848 &loop_attr_autoclear.attr,
849 &loop_attr_partscan.attr,
854 static struct attribute_group loop_attribute_group = {
859 static void loop_sysfs_init(struct loop_device *lo)
861 lo->sysfs_inited = !sysfs_create_group(&disk_to_dev(lo->lo_disk)->kobj,
862 &loop_attribute_group);
865 static void loop_sysfs_exit(struct loop_device *lo)
867 if (lo->sysfs_inited)
868 sysfs_remove_group(&disk_to_dev(lo->lo_disk)->kobj,
869 &loop_attribute_group);
872 static void loop_config_discard(struct loop_device *lo)
874 struct file *file = lo->lo_backing_file;
875 struct inode *inode = file->f_mapping->host;
876 struct request_queue *q = lo->lo_queue;
877 u32 granularity, max_discard_sectors;
880 * If the backing device is a block device, mirror its zeroing
881 * capability. Set the discard sectors to the block device's zeroing
882 * capabilities because loop discards result in blkdev_issue_zeroout(),
883 * not blkdev_issue_discard(). This maintains consistent behavior with
884 * file-backed loop devices: discarded regions read back as zero.
886 if (S_ISBLK(inode->i_mode) && !lo->lo_encrypt_key_size) {
887 struct request_queue *backingq;
889 backingq = bdev_get_queue(inode->i_bdev);
891 max_discard_sectors = backingq->limits.max_write_zeroes_sectors;
892 granularity = backingq->limits.discard_granularity ?:
893 queue_physical_block_size(backingq);
896 * We use punch hole to reclaim the free space used by the
897 * image a.k.a. discard. However we do not support discard if
898 * encryption is enabled, because it may give an attacker
899 * useful information.
901 } else if (!file->f_op->fallocate || lo->lo_encrypt_key_size) {
902 max_discard_sectors = 0;
906 max_discard_sectors = UINT_MAX >> 9;
907 granularity = inode->i_sb->s_blocksize;
910 if (max_discard_sectors) {
911 q->limits.discard_granularity = granularity;
912 blk_queue_max_discard_sectors(q, max_discard_sectors);
913 blk_queue_max_write_zeroes_sectors(q, max_discard_sectors);
914 blk_queue_flag_set(QUEUE_FLAG_DISCARD, q);
916 q->limits.discard_granularity = 0;
917 blk_queue_max_discard_sectors(q, 0);
918 blk_queue_max_write_zeroes_sectors(q, 0);
919 blk_queue_flag_clear(QUEUE_FLAG_DISCARD, q);
921 q->limits.discard_alignment = 0;
924 static void loop_unprepare_queue(struct loop_device *lo)
926 kthread_flush_worker(&lo->worker);
927 kthread_stop(lo->worker_task);
930 static int loop_kthread_worker_fn(void *worker_ptr)
932 current->flags |= PF_LESS_THROTTLE | PF_MEMALLOC_NOIO;
933 return kthread_worker_fn(worker_ptr);
936 static int loop_prepare_queue(struct loop_device *lo)
938 kthread_init_worker(&lo->worker);
939 lo->worker_task = kthread_run(loop_kthread_worker_fn,
940 &lo->worker, "loop%d", lo->lo_number);
941 if (IS_ERR(lo->worker_task))
943 set_user_nice(lo->worker_task, MIN_NICE);
947 static void loop_update_rotational(struct loop_device *lo)
949 struct file *file = lo->lo_backing_file;
950 struct inode *file_inode = file->f_mapping->host;
951 struct block_device *file_bdev = file_inode->i_sb->s_bdev;
952 struct request_queue *q = lo->lo_queue;
955 /* not all filesystems (e.g. tmpfs) have a sb->s_bdev */
957 nonrot = blk_queue_nonrot(bdev_get_queue(file_bdev));
960 blk_queue_flag_set(QUEUE_FLAG_NONROT, q);
962 blk_queue_flag_clear(QUEUE_FLAG_NONROT, q);
965 static int loop_set_fd(struct loop_device *lo, fmode_t mode,
966 struct block_device *bdev, unsigned int arg)
970 struct address_space *mapping;
976 /* This is safe, since we have a reference from open(). */
977 __module_get(THIS_MODULE);
984 error = mutex_lock_killable(&loop_ctl_mutex);
989 if (lo->lo_state != Lo_unbound)
992 error = loop_validate_file(file, bdev);
996 mapping = file->f_mapping;
997 inode = mapping->host;
999 if (!(file->f_mode & FMODE_WRITE) || !(mode & FMODE_WRITE) ||
1000 !file->f_op->write_iter)
1001 lo_flags |= LO_FLAGS_READ_ONLY;
1004 size = get_loop_size(lo, file);
1005 if ((loff_t)(sector_t)size != size)
1008 error = loop_prepare_queue(lo);
1014 set_device_ro(bdev, (lo_flags & LO_FLAGS_READ_ONLY) != 0);
1016 lo->use_dio = false;
1017 lo->lo_device = bdev;
1018 lo->lo_flags = lo_flags;
1019 lo->lo_backing_file = file;
1020 lo->transfer = NULL;
1022 lo->lo_sizelimit = 0;
1023 lo->old_gfp_mask = mapping_gfp_mask(mapping);
1024 mapping_set_gfp_mask(mapping, lo->old_gfp_mask & ~(__GFP_IO|__GFP_FS));
1026 if (!(lo_flags & LO_FLAGS_READ_ONLY) && file->f_op->fsync)
1027 blk_queue_write_cache(lo->lo_queue, true, false);
1029 loop_update_rotational(lo);
1030 loop_update_dio(lo);
1031 loop_sysfs_init(lo);
1032 loop_set_size(lo, size);
1034 set_blocksize(bdev, S_ISBLK(inode->i_mode) ?
1035 block_size(inode->i_bdev) : PAGE_SIZE);
1037 lo->lo_state = Lo_bound;
1039 lo->lo_flags |= LO_FLAGS_PARTSCAN;
1040 partscan = lo->lo_flags & LO_FLAGS_PARTSCAN;
1042 /* Grab the block_device to prevent its destruction after we
1043 * put /dev/loopXX inode. Later in __loop_clr_fd() we bdput(bdev).
1046 mutex_unlock(&loop_ctl_mutex);
1048 loop_reread_partitions(lo, bdev);
1052 mutex_unlock(&loop_ctl_mutex);
1056 /* This is safe: open() is still holding a reference. */
1057 module_put(THIS_MODULE);
1062 loop_release_xfer(struct loop_device *lo)
1065 struct loop_func_table *xfer = lo->lo_encryption;
1069 err = xfer->release(lo);
1070 lo->transfer = NULL;
1071 lo->lo_encryption = NULL;
1072 module_put(xfer->owner);
1078 loop_init_xfer(struct loop_device *lo, struct loop_func_table *xfer,
1079 const struct loop_info64 *i)
1084 struct module *owner = xfer->owner;
1086 if (!try_module_get(owner))
1089 err = xfer->init(lo, i);
1093 lo->lo_encryption = xfer;
1098 static int __loop_clr_fd(struct loop_device *lo, bool release)
1100 struct file *filp = NULL;
1101 gfp_t gfp = lo->old_gfp_mask;
1102 struct block_device *bdev = lo->lo_device;
1104 bool partscan = false;
1107 mutex_lock(&loop_ctl_mutex);
1108 if (WARN_ON_ONCE(lo->lo_state != Lo_rundown)) {
1113 filp = lo->lo_backing_file;
1119 /* freeze request queue during the transition */
1120 blk_mq_freeze_queue(lo->lo_queue);
1122 spin_lock_irq(&lo->lo_lock);
1123 lo->lo_backing_file = NULL;
1124 spin_unlock_irq(&lo->lo_lock);
1126 loop_release_xfer(lo);
1127 lo->transfer = NULL;
1129 lo->lo_device = NULL;
1130 lo->lo_encryption = NULL;
1132 lo->lo_sizelimit = 0;
1133 lo->lo_encrypt_key_size = 0;
1134 memset(lo->lo_encrypt_key, 0, LO_KEY_SIZE);
1135 memset(lo->lo_crypt_name, 0, LO_NAME_SIZE);
1136 memset(lo->lo_file_name, 0, LO_NAME_SIZE);
1137 blk_queue_logical_block_size(lo->lo_queue, 512);
1138 blk_queue_physical_block_size(lo->lo_queue, 512);
1139 blk_queue_io_min(lo->lo_queue, 512);
1142 invalidate_bdev(bdev);
1143 bdev->bd_inode->i_mapping->wb_err = 0;
1145 set_capacity(lo->lo_disk, 0);
1146 loop_sysfs_exit(lo);
1148 bd_set_size(bdev, 0);
1149 /* let user-space know about this change */
1150 kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, KOBJ_CHANGE);
1152 mapping_set_gfp_mask(filp->f_mapping, gfp);
1153 /* This is safe: open() is still holding a reference. */
1154 module_put(THIS_MODULE);
1155 blk_mq_unfreeze_queue(lo->lo_queue);
1157 partscan = lo->lo_flags & LO_FLAGS_PARTSCAN && bdev;
1158 lo_number = lo->lo_number;
1159 loop_unprepare_queue(lo);
1161 mutex_unlock(&loop_ctl_mutex);
1164 * bd_mutex has been held already in release path, so don't
1165 * acquire it if this function is called in such case.
1167 * If the reread partition isn't from release path, lo_refcnt
1168 * must be at least one and it can only become zero when the
1169 * current holder is released.
1172 err = __blkdev_reread_part(bdev);
1174 err = blkdev_reread_part(bdev);
1176 pr_warn("%s: partition scan of loop%d failed (rc=%d)\n",
1177 __func__, lo_number, err);
1178 /* Device is gone, no point in returning error */
1183 * lo->lo_state is set to Lo_unbound here after above partscan has
1186 * There cannot be anybody else entering __loop_clr_fd() as
1187 * lo->lo_backing_file is already cleared and Lo_rundown state
1188 * protects us from all the other places trying to change the 'lo'
1191 mutex_lock(&loop_ctl_mutex);
1194 lo->lo_disk->flags |= GENHD_FL_NO_PART_SCAN;
1195 lo->lo_state = Lo_unbound;
1196 mutex_unlock(&loop_ctl_mutex);
1199 * Need not hold loop_ctl_mutex to fput backing file.
1200 * Calling fput holding loop_ctl_mutex triggers a circular
1201 * lock dependency possibility warning as fput can take
1202 * bd_mutex which is usually taken before loop_ctl_mutex.
1209 static int loop_clr_fd(struct loop_device *lo)
1213 err = mutex_lock_killable(&loop_ctl_mutex);
1216 if (lo->lo_state != Lo_bound) {
1217 mutex_unlock(&loop_ctl_mutex);
1221 * If we've explicitly asked to tear down the loop device,
1222 * and it has an elevated reference count, set it for auto-teardown when
1223 * the last reference goes away. This stops $!~#$@ udev from
1224 * preventing teardown because it decided that it needs to run blkid on
1225 * the loopback device whenever they appear. xfstests is notorious for
1226 * failing tests because blkid via udev races with a losetup
1227 * <dev>/do something like mkfs/losetup -d <dev> causing the losetup -d
1228 * command to fail with EBUSY.
1230 if (atomic_read(&lo->lo_refcnt) > 1) {
1231 lo->lo_flags |= LO_FLAGS_AUTOCLEAR;
1232 mutex_unlock(&loop_ctl_mutex);
1235 lo->lo_state = Lo_rundown;
1236 mutex_unlock(&loop_ctl_mutex);
1238 return __loop_clr_fd(lo, false);
1242 * loop_set_status_from_info - configure device from loop_info
1243 * @lo: struct loop_device to configure
1244 * @info: struct loop_info64 to configure the device with
1246 * Configures the loop device parameters according to the passed
1247 * in loop_info64 configuration.
1250 loop_set_status_from_info(struct loop_device *lo,
1251 const struct loop_info64 *info)
1254 struct loop_func_table *xfer;
1255 kuid_t uid = current_uid();
1258 if ((unsigned int) info->lo_encrypt_key_size > LO_KEY_SIZE)
1261 err = loop_release_xfer(lo);
1265 if (info->lo_encrypt_type) {
1266 unsigned int type = info->lo_encrypt_type;
1268 if (type >= MAX_LO_CRYPT)
1270 xfer = xfer_funcs[type];
1276 err = loop_init_xfer(lo, xfer, info);
1280 /* Avoid assigning overflow values */
1281 if (info->lo_offset > LLONG_MAX || info->lo_sizelimit > LLONG_MAX)
1284 new_size = get_size(info->lo_offset, info->lo_sizelimit,
1285 lo->lo_backing_file);
1286 if ((loff_t)(sector_t)new_size != new_size)
1289 lo->lo_offset = info->lo_offset;
1290 lo->lo_sizelimit = info->lo_sizelimit;
1292 memcpy(lo->lo_file_name, info->lo_file_name, LO_NAME_SIZE);
1293 memcpy(lo->lo_crypt_name, info->lo_crypt_name, LO_NAME_SIZE);
1294 lo->lo_file_name[LO_NAME_SIZE-1] = 0;
1295 lo->lo_crypt_name[LO_NAME_SIZE-1] = 0;
1299 lo->transfer = xfer->transfer;
1300 lo->ioctl = xfer->ioctl;
1302 if ((lo->lo_flags & LO_FLAGS_AUTOCLEAR) !=
1303 (info->lo_flags & LO_FLAGS_AUTOCLEAR))
1304 lo->lo_flags ^= LO_FLAGS_AUTOCLEAR;
1306 lo->lo_encrypt_key_size = info->lo_encrypt_key_size;
1307 lo->lo_init[0] = info->lo_init[0];
1308 lo->lo_init[1] = info->lo_init[1];
1309 if (info->lo_encrypt_key_size) {
1310 memcpy(lo->lo_encrypt_key, info->lo_encrypt_key,
1311 info->lo_encrypt_key_size);
1312 lo->lo_key_owner = uid;
1319 loop_set_status(struct loop_device *lo, const struct loop_info64 *info)
1322 struct block_device *bdev;
1323 kuid_t uid = current_uid();
1324 bool partscan = false;
1325 bool size_changed = false;
1327 err = mutex_lock_killable(&loop_ctl_mutex);
1330 if (lo->lo_encrypt_key_size &&
1331 !uid_eq(lo->lo_key_owner, uid) &&
1332 !capable(CAP_SYS_ADMIN)) {
1336 if (lo->lo_state != Lo_bound) {
1341 if (lo->lo_offset != info->lo_offset ||
1342 lo->lo_sizelimit != info->lo_sizelimit) {
1343 size_changed = true;
1344 sync_blockdev(lo->lo_device);
1345 invalidate_bdev(lo->lo_device);
1348 /* I/O need to be drained during transfer transition */
1349 blk_mq_freeze_queue(lo->lo_queue);
1351 if (size_changed && lo->lo_device->bd_inode->i_mapping->nrpages) {
1352 /* If any pages were dirtied after invalidate_bdev(), try again */
1354 pr_warn("%s: loop%d (%s) has still dirty pages (nrpages=%lu)\n",
1355 __func__, lo->lo_number, lo->lo_file_name,
1356 lo->lo_device->bd_inode->i_mapping->nrpages);
1360 err = loop_set_status_from_info(lo, info);
1365 loff_t new_size = get_size(lo->lo_offset, lo->lo_sizelimit,
1366 lo->lo_backing_file);
1367 loop_set_size(lo, new_size);
1370 loop_config_discard(lo);
1372 /* update dio if lo_offset or transfer is changed */
1373 __loop_update_dio(lo, lo->use_dio);
1376 blk_mq_unfreeze_queue(lo->lo_queue);
1378 if (!err && (info->lo_flags & LO_FLAGS_PARTSCAN) &&
1379 !(lo->lo_flags & LO_FLAGS_PARTSCAN)) {
1380 lo->lo_flags |= LO_FLAGS_PARTSCAN;
1381 lo->lo_disk->flags &= ~GENHD_FL_NO_PART_SCAN;
1382 bdev = lo->lo_device;
1386 mutex_unlock(&loop_ctl_mutex);
1388 loop_reread_partitions(lo, bdev);
1394 loop_get_status(struct loop_device *lo, struct loop_info64 *info)
1400 ret = mutex_lock_killable(&loop_ctl_mutex);
1403 if (lo->lo_state != Lo_bound) {
1404 mutex_unlock(&loop_ctl_mutex);
1408 memset(info, 0, sizeof(*info));
1409 info->lo_number = lo->lo_number;
1410 info->lo_offset = lo->lo_offset;
1411 info->lo_sizelimit = lo->lo_sizelimit;
1412 info->lo_flags = lo->lo_flags;
1413 memcpy(info->lo_file_name, lo->lo_file_name, LO_NAME_SIZE);
1414 memcpy(info->lo_crypt_name, lo->lo_crypt_name, LO_NAME_SIZE);
1415 info->lo_encrypt_type =
1416 lo->lo_encryption ? lo->lo_encryption->number : 0;
1417 if (lo->lo_encrypt_key_size && capable(CAP_SYS_ADMIN)) {
1418 info->lo_encrypt_key_size = lo->lo_encrypt_key_size;
1419 memcpy(info->lo_encrypt_key, lo->lo_encrypt_key,
1420 lo->lo_encrypt_key_size);
1423 /* Drop loop_ctl_mutex while we call into the filesystem. */
1424 path = lo->lo_backing_file->f_path;
1426 mutex_unlock(&loop_ctl_mutex);
1427 ret = vfs_getattr(&path, &stat, STATX_INO, AT_STATX_SYNC_AS_STAT);
1429 info->lo_device = huge_encode_dev(stat.dev);
1430 info->lo_inode = stat.ino;
1431 info->lo_rdevice = huge_encode_dev(stat.rdev);
1438 loop_info64_from_old(const struct loop_info *info, struct loop_info64 *info64)
1440 memset(info64, 0, sizeof(*info64));
1441 info64->lo_number = info->lo_number;
1442 info64->lo_device = info->lo_device;
1443 info64->lo_inode = info->lo_inode;
1444 info64->lo_rdevice = info->lo_rdevice;
1445 info64->lo_offset = info->lo_offset;
1446 info64->lo_sizelimit = 0;
1447 info64->lo_encrypt_type = info->lo_encrypt_type;
1448 info64->lo_encrypt_key_size = info->lo_encrypt_key_size;
1449 info64->lo_flags = info->lo_flags;
1450 info64->lo_init[0] = info->lo_init[0];
1451 info64->lo_init[1] = info->lo_init[1];
1452 if (info->lo_encrypt_type == LO_CRYPT_CRYPTOAPI)
1453 memcpy(info64->lo_crypt_name, info->lo_name, LO_NAME_SIZE);
1455 memcpy(info64->lo_file_name, info->lo_name, LO_NAME_SIZE);
1456 memcpy(info64->lo_encrypt_key, info->lo_encrypt_key, LO_KEY_SIZE);
1460 loop_info64_to_old(const struct loop_info64 *info64, struct loop_info *info)
1462 memset(info, 0, sizeof(*info));
1463 info->lo_number = info64->lo_number;
1464 info->lo_device = info64->lo_device;
1465 info->lo_inode = info64->lo_inode;
1466 info->lo_rdevice = info64->lo_rdevice;
1467 info->lo_offset = info64->lo_offset;
1468 info->lo_encrypt_type = info64->lo_encrypt_type;
1469 info->lo_encrypt_key_size = info64->lo_encrypt_key_size;
1470 info->lo_flags = info64->lo_flags;
1471 info->lo_init[0] = info64->lo_init[0];
1472 info->lo_init[1] = info64->lo_init[1];
1473 if (info->lo_encrypt_type == LO_CRYPT_CRYPTOAPI)
1474 memcpy(info->lo_name, info64->lo_crypt_name, LO_NAME_SIZE);
1476 memcpy(info->lo_name, info64->lo_file_name, LO_NAME_SIZE);
1477 memcpy(info->lo_encrypt_key, info64->lo_encrypt_key, LO_KEY_SIZE);
1479 /* error in case values were truncated */
1480 if (info->lo_device != info64->lo_device ||
1481 info->lo_rdevice != info64->lo_rdevice ||
1482 info->lo_inode != info64->lo_inode ||
1483 info->lo_offset != info64->lo_offset)
1490 loop_set_status_old(struct loop_device *lo, const struct loop_info __user *arg)
1492 struct loop_info info;
1493 struct loop_info64 info64;
1495 if (copy_from_user(&info, arg, sizeof (struct loop_info)))
1497 loop_info64_from_old(&info, &info64);
1498 return loop_set_status(lo, &info64);
1502 loop_set_status64(struct loop_device *lo, const struct loop_info64 __user *arg)
1504 struct loop_info64 info64;
1506 if (copy_from_user(&info64, arg, sizeof (struct loop_info64)))
1508 return loop_set_status(lo, &info64);
1512 loop_get_status_old(struct loop_device *lo, struct loop_info __user *arg) {
1513 struct loop_info info;
1514 struct loop_info64 info64;
1519 err = loop_get_status(lo, &info64);
1521 err = loop_info64_to_old(&info64, &info);
1522 if (!err && copy_to_user(arg, &info, sizeof(info)))
1529 loop_get_status64(struct loop_device *lo, struct loop_info64 __user *arg) {
1530 struct loop_info64 info64;
1535 err = loop_get_status(lo, &info64);
1536 if (!err && copy_to_user(arg, &info64, sizeof(info64)))
1542 static int loop_set_capacity(struct loop_device *lo)
1544 if (unlikely(lo->lo_state != Lo_bound))
1547 return figure_loop_size(lo, lo->lo_offset, lo->lo_sizelimit);
1550 static int loop_set_dio(struct loop_device *lo, unsigned long arg)
1553 if (lo->lo_state != Lo_bound)
1556 __loop_update_dio(lo, !!arg);
1557 if (lo->use_dio == !!arg)
1564 static int loop_set_block_size(struct loop_device *lo, unsigned long arg)
1568 if (lo->lo_state != Lo_bound)
1571 if (arg < 512 || arg > PAGE_SIZE || !is_power_of_2(arg))
1574 if (lo->lo_queue->limits.logical_block_size != arg) {
1575 sync_blockdev(lo->lo_device);
1576 invalidate_bdev(lo->lo_device);
1579 blk_mq_freeze_queue(lo->lo_queue);
1581 /* invalidate_bdev should have truncated all the pages */
1582 if (lo->lo_queue->limits.logical_block_size != arg &&
1583 lo->lo_device->bd_inode->i_mapping->nrpages) {
1585 pr_warn("%s: loop%d (%s) has still dirty pages (nrpages=%lu)\n",
1586 __func__, lo->lo_number, lo->lo_file_name,
1587 lo->lo_device->bd_inode->i_mapping->nrpages);
1591 blk_queue_logical_block_size(lo->lo_queue, arg);
1592 blk_queue_physical_block_size(lo->lo_queue, arg);
1593 blk_queue_io_min(lo->lo_queue, arg);
1594 loop_update_dio(lo);
1596 blk_mq_unfreeze_queue(lo->lo_queue);
1601 static int lo_simple_ioctl(struct loop_device *lo, unsigned int cmd,
1606 err = mutex_lock_killable(&loop_ctl_mutex);
1610 case LOOP_SET_CAPACITY:
1611 err = loop_set_capacity(lo);
1613 case LOOP_SET_DIRECT_IO:
1614 err = loop_set_dio(lo, arg);
1616 case LOOP_SET_BLOCK_SIZE:
1617 err = loop_set_block_size(lo, arg);
1620 err = lo->ioctl ? lo->ioctl(lo, cmd, arg) : -EINVAL;
1622 mutex_unlock(&loop_ctl_mutex);
1626 static int lo_ioctl(struct block_device *bdev, fmode_t mode,
1627 unsigned int cmd, unsigned long arg)
1629 struct loop_device *lo = bdev->bd_disk->private_data;
1634 return loop_set_fd(lo, mode, bdev, arg);
1635 case LOOP_CHANGE_FD:
1636 return loop_change_fd(lo, bdev, arg);
1638 return loop_clr_fd(lo);
1639 case LOOP_SET_STATUS:
1641 if ((mode & FMODE_WRITE) || capable(CAP_SYS_ADMIN)) {
1642 err = loop_set_status_old(lo,
1643 (struct loop_info __user *)arg);
1646 case LOOP_GET_STATUS:
1647 return loop_get_status_old(lo, (struct loop_info __user *) arg);
1648 case LOOP_SET_STATUS64:
1650 if ((mode & FMODE_WRITE) || capable(CAP_SYS_ADMIN)) {
1651 err = loop_set_status64(lo,
1652 (struct loop_info64 __user *) arg);
1655 case LOOP_GET_STATUS64:
1656 return loop_get_status64(lo, (struct loop_info64 __user *) arg);
1657 case LOOP_SET_CAPACITY:
1658 case LOOP_SET_DIRECT_IO:
1659 case LOOP_SET_BLOCK_SIZE:
1660 if (!(mode & FMODE_WRITE) && !capable(CAP_SYS_ADMIN))
1664 err = lo_simple_ioctl(lo, cmd, arg);
1671 #ifdef CONFIG_COMPAT
1672 struct compat_loop_info {
1673 compat_int_t lo_number; /* ioctl r/o */
1674 compat_dev_t lo_device; /* ioctl r/o */
1675 compat_ulong_t lo_inode; /* ioctl r/o */
1676 compat_dev_t lo_rdevice; /* ioctl r/o */
1677 compat_int_t lo_offset;
1678 compat_int_t lo_encrypt_type;
1679 compat_int_t lo_encrypt_key_size; /* ioctl w/o */
1680 compat_int_t lo_flags; /* ioctl r/o */
1681 char lo_name[LO_NAME_SIZE];
1682 unsigned char lo_encrypt_key[LO_KEY_SIZE]; /* ioctl w/o */
1683 compat_ulong_t lo_init[2];
1688 * Transfer 32-bit compatibility structure in userspace to 64-bit loop info
1689 * - noinlined to reduce stack space usage in main part of driver
1692 loop_info64_from_compat(const struct compat_loop_info __user *arg,
1693 struct loop_info64 *info64)
1695 struct compat_loop_info info;
1697 if (copy_from_user(&info, arg, sizeof(info)))
1700 memset(info64, 0, sizeof(*info64));
1701 info64->lo_number = info.lo_number;
1702 info64->lo_device = info.lo_device;
1703 info64->lo_inode = info.lo_inode;
1704 info64->lo_rdevice = info.lo_rdevice;
1705 info64->lo_offset = info.lo_offset;
1706 info64->lo_sizelimit = 0;
1707 info64->lo_encrypt_type = info.lo_encrypt_type;
1708 info64->lo_encrypt_key_size = info.lo_encrypt_key_size;
1709 info64->lo_flags = info.lo_flags;
1710 info64->lo_init[0] = info.lo_init[0];
1711 info64->lo_init[1] = info.lo_init[1];
1712 if (info.lo_encrypt_type == LO_CRYPT_CRYPTOAPI)
1713 memcpy(info64->lo_crypt_name, info.lo_name, LO_NAME_SIZE);
1715 memcpy(info64->lo_file_name, info.lo_name, LO_NAME_SIZE);
1716 memcpy(info64->lo_encrypt_key, info.lo_encrypt_key, LO_KEY_SIZE);
1721 * Transfer 64-bit loop info to 32-bit compatibility structure in userspace
1722 * - noinlined to reduce stack space usage in main part of driver
1725 loop_info64_to_compat(const struct loop_info64 *info64,
1726 struct compat_loop_info __user *arg)
1728 struct compat_loop_info info;
1730 memset(&info, 0, sizeof(info));
1731 info.lo_number = info64->lo_number;
1732 info.lo_device = info64->lo_device;
1733 info.lo_inode = info64->lo_inode;
1734 info.lo_rdevice = info64->lo_rdevice;
1735 info.lo_offset = info64->lo_offset;
1736 info.lo_encrypt_type = info64->lo_encrypt_type;
1737 info.lo_encrypt_key_size = info64->lo_encrypt_key_size;
1738 info.lo_flags = info64->lo_flags;
1739 info.lo_init[0] = info64->lo_init[0];
1740 info.lo_init[1] = info64->lo_init[1];
1741 if (info.lo_encrypt_type == LO_CRYPT_CRYPTOAPI)
1742 memcpy(info.lo_name, info64->lo_crypt_name, LO_NAME_SIZE);
1744 memcpy(info.lo_name, info64->lo_file_name, LO_NAME_SIZE);
1745 memcpy(info.lo_encrypt_key, info64->lo_encrypt_key, LO_KEY_SIZE);
1747 /* error in case values were truncated */
1748 if (info.lo_device != info64->lo_device ||
1749 info.lo_rdevice != info64->lo_rdevice ||
1750 info.lo_inode != info64->lo_inode ||
1751 info.lo_offset != info64->lo_offset ||
1752 info.lo_init[0] != info64->lo_init[0] ||
1753 info.lo_init[1] != info64->lo_init[1])
1756 if (copy_to_user(arg, &info, sizeof(info)))
1762 loop_set_status_compat(struct loop_device *lo,
1763 const struct compat_loop_info __user *arg)
1765 struct loop_info64 info64;
1768 ret = loop_info64_from_compat(arg, &info64);
1771 return loop_set_status(lo, &info64);
1775 loop_get_status_compat(struct loop_device *lo,
1776 struct compat_loop_info __user *arg)
1778 struct loop_info64 info64;
1783 err = loop_get_status(lo, &info64);
1785 err = loop_info64_to_compat(&info64, arg);
1789 static int lo_compat_ioctl(struct block_device *bdev, fmode_t mode,
1790 unsigned int cmd, unsigned long arg)
1792 struct loop_device *lo = bdev->bd_disk->private_data;
1796 case LOOP_SET_STATUS:
1797 err = loop_set_status_compat(lo,
1798 (const struct compat_loop_info __user *)arg);
1800 case LOOP_GET_STATUS:
1801 err = loop_get_status_compat(lo,
1802 (struct compat_loop_info __user *)arg);
1804 case LOOP_SET_CAPACITY:
1806 case LOOP_GET_STATUS64:
1807 case LOOP_SET_STATUS64:
1808 arg = (unsigned long) compat_ptr(arg);
1811 case LOOP_CHANGE_FD:
1812 case LOOP_SET_BLOCK_SIZE:
1813 case LOOP_SET_DIRECT_IO:
1814 err = lo_ioctl(bdev, mode, cmd, arg);
1824 static int lo_open(struct block_device *bdev, fmode_t mode)
1826 struct loop_device *lo;
1829 err = mutex_lock_killable(&loop_ctl_mutex);
1832 lo = bdev->bd_disk->private_data;
1838 atomic_inc(&lo->lo_refcnt);
1840 mutex_unlock(&loop_ctl_mutex);
1844 static void lo_release(struct gendisk *disk, fmode_t mode)
1846 struct loop_device *lo;
1848 mutex_lock(&loop_ctl_mutex);
1849 lo = disk->private_data;
1850 if (atomic_dec_return(&lo->lo_refcnt))
1853 if (lo->lo_flags & LO_FLAGS_AUTOCLEAR) {
1854 if (lo->lo_state != Lo_bound)
1856 lo->lo_state = Lo_rundown;
1857 mutex_unlock(&loop_ctl_mutex);
1859 * In autoclear mode, stop the loop thread
1860 * and remove configuration after last close.
1862 __loop_clr_fd(lo, true);
1864 } else if (lo->lo_state == Lo_bound) {
1866 * Otherwise keep thread (if running) and config,
1867 * but flush possible ongoing bios in thread.
1869 blk_mq_freeze_queue(lo->lo_queue);
1870 blk_mq_unfreeze_queue(lo->lo_queue);
1874 mutex_unlock(&loop_ctl_mutex);
1877 static const struct block_device_operations lo_fops = {
1878 .owner = THIS_MODULE,
1880 .release = lo_release,
1882 #ifdef CONFIG_COMPAT
1883 .compat_ioctl = lo_compat_ioctl,
1888 * And now the modules code and kernel interface.
1890 static int max_loop;
1891 module_param(max_loop, int, 0444);
1892 MODULE_PARM_DESC(max_loop, "Maximum number of loop devices");
1893 module_param(max_part, int, 0444);
1894 MODULE_PARM_DESC(max_part, "Maximum number of partitions per loop device");
1895 MODULE_LICENSE("GPL");
1896 MODULE_ALIAS_BLOCKDEV_MAJOR(LOOP_MAJOR);
1898 int loop_register_transfer(struct loop_func_table *funcs)
1900 unsigned int n = funcs->number;
1902 if (n >= MAX_LO_CRYPT || xfer_funcs[n])
1904 xfer_funcs[n] = funcs;
1908 static int unregister_transfer_cb(int id, void *ptr, void *data)
1910 struct loop_device *lo = ptr;
1911 struct loop_func_table *xfer = data;
1913 mutex_lock(&loop_ctl_mutex);
1914 if (lo->lo_encryption == xfer)
1915 loop_release_xfer(lo);
1916 mutex_unlock(&loop_ctl_mutex);
1920 int loop_unregister_transfer(int number)
1922 unsigned int n = number;
1923 struct loop_func_table *xfer;
1925 if (n == 0 || n >= MAX_LO_CRYPT || (xfer = xfer_funcs[n]) == NULL)
1928 xfer_funcs[n] = NULL;
1929 idr_for_each(&loop_index_idr, &unregister_transfer_cb, xfer);
1933 EXPORT_SYMBOL(loop_register_transfer);
1934 EXPORT_SYMBOL(loop_unregister_transfer);
1936 static blk_status_t loop_queue_rq(struct blk_mq_hw_ctx *hctx,
1937 const struct blk_mq_queue_data *bd)
1939 struct request *rq = bd->rq;
1940 struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
1941 struct loop_device *lo = rq->q->queuedata;
1943 blk_mq_start_request(rq);
1945 if (lo->lo_state != Lo_bound)
1946 return BLK_STS_IOERR;
1948 switch (req_op(rq)) {
1950 case REQ_OP_DISCARD:
1951 case REQ_OP_WRITE_ZEROES:
1952 cmd->use_aio = false;
1955 cmd->use_aio = lo->use_dio;
1959 /* always use the first bio's css */
1960 #ifdef CONFIG_BLK_CGROUP
1961 if (cmd->use_aio && rq->bio && rq->bio->bi_css) {
1962 cmd->css = rq->bio->bi_css;
1967 kthread_queue_work(&lo->worker, &cmd->work);
1972 static void loop_handle_cmd(struct loop_cmd *cmd)
1974 struct request *rq = blk_mq_rq_from_pdu(cmd);
1975 const bool write = op_is_write(req_op(rq));
1976 struct loop_device *lo = rq->q->queuedata;
1979 if (write && (lo->lo_flags & LO_FLAGS_READ_ONLY)) {
1984 ret = do_req_filebacked(lo, rq);
1986 /* complete non-aio request */
1987 if (!cmd->use_aio || ret) {
1988 cmd->ret = ret ? -EIO : 0;
1989 blk_mq_complete_request(rq);
1993 static void loop_queue_work(struct kthread_work *work)
1995 struct loop_cmd *cmd =
1996 container_of(work, struct loop_cmd, work);
1998 loop_handle_cmd(cmd);
2001 static int loop_init_request(struct blk_mq_tag_set *set, struct request *rq,
2002 unsigned int hctx_idx, unsigned int numa_node)
2004 struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
2006 kthread_init_work(&cmd->work, loop_queue_work);
2010 static const struct blk_mq_ops loop_mq_ops = {
2011 .queue_rq = loop_queue_rq,
2012 .init_request = loop_init_request,
2013 .complete = lo_complete_rq,
2016 static int loop_add(struct loop_device **l, int i)
2018 struct loop_device *lo;
2019 struct gendisk *disk;
2023 lo = kzalloc(sizeof(*lo), GFP_KERNEL);
2027 lo->lo_state = Lo_unbound;
2029 /* allocate id, if @id >= 0, we're requesting that specific id */
2031 err = idr_alloc(&loop_index_idr, lo, i, i + 1, GFP_KERNEL);
2035 err = idr_alloc(&loop_index_idr, lo, 0, 0, GFP_KERNEL);
2042 lo->tag_set.ops = &loop_mq_ops;
2043 lo->tag_set.nr_hw_queues = 1;
2044 lo->tag_set.queue_depth = 128;
2045 lo->tag_set.numa_node = NUMA_NO_NODE;
2046 lo->tag_set.cmd_size = sizeof(struct loop_cmd);
2047 lo->tag_set.flags = BLK_MQ_F_SHOULD_MERGE | BLK_MQ_F_SG_MERGE |
2049 lo->tag_set.driver_data = lo;
2051 err = blk_mq_alloc_tag_set(&lo->tag_set);
2055 lo->lo_queue = blk_mq_init_queue(&lo->tag_set);
2056 if (IS_ERR_OR_NULL(lo->lo_queue)) {
2057 err = PTR_ERR(lo->lo_queue);
2058 goto out_cleanup_tags;
2060 lo->lo_queue->queuedata = lo;
2062 blk_queue_max_hw_sectors(lo->lo_queue, BLK_DEF_MAX_SECTORS);
2065 * By default, we do buffer IO, so it doesn't make sense to enable
2066 * merge because the I/O submitted to backing file is handled page by
2067 * page. For directio mode, merge does help to dispatch bigger request
2068 * to underlayer disk. We will enable merge once directio is enabled.
2070 blk_queue_flag_set(QUEUE_FLAG_NOMERGES, lo->lo_queue);
2073 disk = lo->lo_disk = alloc_disk(1 << part_shift);
2075 goto out_free_queue;
2078 * Disable partition scanning by default. The in-kernel partition
2079 * scanning can be requested individually per-device during its
2080 * setup. Userspace can always add and remove partitions from all
2081 * devices. The needed partition minors are allocated from the
2082 * extended minor space, the main loop device numbers will continue
2083 * to match the loop minors, regardless of the number of partitions
2086 * If max_part is given, partition scanning is globally enabled for
2087 * all loop devices. The minors for the main loop devices will be
2088 * multiples of max_part.
2090 * Note: Global-for-all-devices, set-only-at-init, read-only module
2091 * parameteters like 'max_loop' and 'max_part' make things needlessly
2092 * complicated, are too static, inflexible and may surprise
2093 * userspace tools. Parameters like this in general should be avoided.
2096 disk->flags |= GENHD_FL_NO_PART_SCAN;
2097 disk->flags |= GENHD_FL_EXT_DEVT;
2098 atomic_set(&lo->lo_refcnt, 0);
2100 spin_lock_init(&lo->lo_lock);
2101 disk->major = LOOP_MAJOR;
2102 disk->first_minor = i << part_shift;
2103 disk->fops = &lo_fops;
2104 disk->private_data = lo;
2105 disk->queue = lo->lo_queue;
2106 sprintf(disk->disk_name, "loop%d", i);
2109 return lo->lo_number;
2112 blk_cleanup_queue(lo->lo_queue);
2114 blk_mq_free_tag_set(&lo->tag_set);
2116 idr_remove(&loop_index_idr, i);
2123 static void loop_remove(struct loop_device *lo)
2125 del_gendisk(lo->lo_disk);
2126 blk_cleanup_queue(lo->lo_queue);
2127 blk_mq_free_tag_set(&lo->tag_set);
2128 put_disk(lo->lo_disk);
2132 static int find_free_cb(int id, void *ptr, void *data)
2134 struct loop_device *lo = ptr;
2135 struct loop_device **l = data;
2137 if (lo->lo_state == Lo_unbound) {
2144 static int loop_lookup(struct loop_device **l, int i)
2146 struct loop_device *lo;
2152 err = idr_for_each(&loop_index_idr, &find_free_cb, &lo);
2155 ret = lo->lo_number;
2160 /* lookup and return a specific i */
2161 lo = idr_find(&loop_index_idr, i);
2164 ret = lo->lo_number;
2170 static struct kobject *loop_probe(dev_t dev, int *part, void *data)
2172 struct loop_device *lo;
2173 struct kobject *kobj;
2176 mutex_lock(&loop_ctl_mutex);
2177 err = loop_lookup(&lo, MINOR(dev) >> part_shift);
2179 err = loop_add(&lo, MINOR(dev) >> part_shift);
2183 kobj = get_disk_and_module(lo->lo_disk);
2184 mutex_unlock(&loop_ctl_mutex);
2190 static long loop_control_ioctl(struct file *file, unsigned int cmd,
2193 struct loop_device *lo;
2196 ret = mutex_lock_killable(&loop_ctl_mutex);
2203 ret = loop_lookup(&lo, parm);
2208 ret = loop_add(&lo, parm);
2210 case LOOP_CTL_REMOVE:
2211 ret = loop_lookup(&lo, parm);
2214 if (lo->lo_state != Lo_unbound) {
2218 if (atomic_read(&lo->lo_refcnt) > 0) {
2222 lo->lo_disk->private_data = NULL;
2223 idr_remove(&loop_index_idr, lo->lo_number);
2226 case LOOP_CTL_GET_FREE:
2227 ret = loop_lookup(&lo, -1);
2230 ret = loop_add(&lo, -1);
2232 mutex_unlock(&loop_ctl_mutex);
2237 static const struct file_operations loop_ctl_fops = {
2238 .open = nonseekable_open,
2239 .unlocked_ioctl = loop_control_ioctl,
2240 .compat_ioctl = loop_control_ioctl,
2241 .owner = THIS_MODULE,
2242 .llseek = noop_llseek,
2245 static struct miscdevice loop_misc = {
2246 .minor = LOOP_CTRL_MINOR,
2247 .name = "loop-control",
2248 .fops = &loop_ctl_fops,
2251 MODULE_ALIAS_MISCDEV(LOOP_CTRL_MINOR);
2252 MODULE_ALIAS("devname:loop-control");
2254 static int __init loop_init(void)
2257 unsigned long range;
2258 struct loop_device *lo;
2263 part_shift = fls(max_part);
2266 * Adjust max_part according to part_shift as it is exported
2267 * to user space so that user can decide correct minor number
2268 * if [s]he want to create more devices.
2270 * Note that -1 is required because partition 0 is reserved
2271 * for the whole disk.
2273 max_part = (1UL << part_shift) - 1;
2276 if ((1UL << part_shift) > DISK_MAX_PARTS) {
2281 if (max_loop > 1UL << (MINORBITS - part_shift)) {
2287 * If max_loop is specified, create that many devices upfront.
2288 * This also becomes a hard limit. If max_loop is not specified,
2289 * create CONFIG_BLK_DEV_LOOP_MIN_COUNT loop devices at module
2290 * init time. Loop devices can be requested on-demand with the
2291 * /dev/loop-control interface, or be instantiated by accessing
2292 * a 'dead' device node.
2296 range = max_loop << part_shift;
2298 nr = CONFIG_BLK_DEV_LOOP_MIN_COUNT;
2299 range = 1UL << MINORBITS;
2302 err = misc_register(&loop_misc);
2307 if (register_blkdev(LOOP_MAJOR, "loop")) {
2312 blk_register_region(MKDEV(LOOP_MAJOR, 0), range,
2313 THIS_MODULE, loop_probe, NULL, NULL);
2315 /* pre-create number of devices given by config or max_loop */
2316 mutex_lock(&loop_ctl_mutex);
2317 for (i = 0; i < nr; i++)
2319 mutex_unlock(&loop_ctl_mutex);
2321 printk(KERN_INFO "loop: module loaded\n");
2325 misc_deregister(&loop_misc);
2330 static int loop_exit_cb(int id, void *ptr, void *data)
2332 struct loop_device *lo = ptr;
2338 static void __exit loop_exit(void)
2340 unsigned long range;
2342 range = max_loop ? max_loop << part_shift : 1UL << MINORBITS;
2344 mutex_lock(&loop_ctl_mutex);
2346 idr_for_each(&loop_index_idr, &loop_exit_cb, NULL);
2347 idr_destroy(&loop_index_idr);
2349 blk_unregister_region(MKDEV(LOOP_MAJOR, 0), range);
2350 unregister_blkdev(LOOP_MAJOR, "loop");
2352 misc_deregister(&loop_misc);
2354 mutex_unlock(&loop_ctl_mutex);
2357 module_init(loop_init);
2358 module_exit(loop_exit);
2361 static int __init max_loop_setup(char *str)
2363 max_loop = simple_strtol(str, NULL, 0);
2367 __setup("max_loop=", max_loop_setup);