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/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>
85 #include <linux/uaccess.h>
87 #define LOOP_IDLE_WORKER_TIMEOUT (60 * HZ)
89 static DEFINE_IDR(loop_index_idr);
90 static DEFINE_MUTEX(loop_ctl_mutex);
91 static DEFINE_MUTEX(loop_validate_mutex);
94 * loop_global_lock_killable() - take locks for safe loop_validate_file() test
96 * @lo: struct loop_device
97 * @global: true if @lo is about to bind another "struct loop_device", false otherwise
99 * Returns 0 on success, -EINTR otherwise.
101 * Since loop_validate_file() traverses on other "struct loop_device" if
102 * is_loop_device() is true, we need a global lock for serializing concurrent
103 * loop_configure()/loop_change_fd()/__loop_clr_fd() calls.
105 static int loop_global_lock_killable(struct loop_device *lo, bool global)
110 err = mutex_lock_killable(&loop_validate_mutex);
114 err = mutex_lock_killable(&lo->lo_mutex);
116 mutex_unlock(&loop_validate_mutex);
121 * loop_global_unlock() - release locks taken by loop_global_lock_killable()
123 * @lo: struct loop_device
124 * @global: true if @lo was about to bind another "struct loop_device", false otherwise
126 static void loop_global_unlock(struct loop_device *lo, bool global)
128 mutex_unlock(&lo->lo_mutex);
130 mutex_unlock(&loop_validate_mutex);
134 static int part_shift;
136 static loff_t get_size(loff_t offset, loff_t sizelimit, struct file *file)
140 /* Compute loopsize in bytes */
141 loopsize = i_size_read(file->f_mapping->host);
144 /* offset is beyond i_size, weird but possible */
148 if (sizelimit > 0 && sizelimit < loopsize)
149 loopsize = sizelimit;
151 * Unfortunately, if we want to do I/O on the device,
152 * the number of 512-byte sectors has to fit into a sector_t.
154 return loopsize >> 9;
157 static loff_t get_loop_size(struct loop_device *lo, struct file *file)
159 return get_size(lo->lo_offset, lo->lo_sizelimit, file);
162 static void __loop_update_dio(struct loop_device *lo, bool dio)
164 struct file *file = lo->lo_backing_file;
165 struct address_space *mapping = file->f_mapping;
166 struct inode *inode = mapping->host;
167 unsigned short sb_bsize = 0;
168 unsigned dio_align = 0;
171 if (inode->i_sb->s_bdev) {
172 sb_bsize = bdev_logical_block_size(inode->i_sb->s_bdev);
173 dio_align = sb_bsize - 1;
177 * We support direct I/O only if lo_offset is aligned with the
178 * logical I/O size of backing device, and the logical block
179 * size of loop is bigger than the backing device's.
181 * TODO: the above condition may be loosed in the future, and
182 * direct I/O may be switched runtime at that time because most
183 * of requests in sane applications should be PAGE_SIZE aligned
186 if (queue_logical_block_size(lo->lo_queue) >= sb_bsize &&
187 !(lo->lo_offset & dio_align) &&
188 mapping->a_ops->direct_IO)
196 if (lo->use_dio == use_dio)
199 /* flush dirty pages before changing direct IO */
203 * The flag of LO_FLAGS_DIRECT_IO is handled similarly with
204 * LO_FLAGS_READ_ONLY, both are set from kernel, and losetup
205 * will get updated by ioctl(LOOP_GET_STATUS)
207 if (lo->lo_state == Lo_bound)
208 blk_mq_freeze_queue(lo->lo_queue);
209 lo->use_dio = use_dio;
211 blk_queue_flag_clear(QUEUE_FLAG_NOMERGES, lo->lo_queue);
212 lo->lo_flags |= LO_FLAGS_DIRECT_IO;
214 blk_queue_flag_set(QUEUE_FLAG_NOMERGES, lo->lo_queue);
215 lo->lo_flags &= ~LO_FLAGS_DIRECT_IO;
217 if (lo->lo_state == Lo_bound)
218 blk_mq_unfreeze_queue(lo->lo_queue);
222 * loop_set_size() - sets device size and notifies userspace
223 * @lo: struct loop_device to set the size for
224 * @size: new size of the loop device
226 * Callers must validate that the size passed into this function fits into
227 * a sector_t, eg using loop_validate_size()
229 static void loop_set_size(struct loop_device *lo, loff_t size)
231 if (!set_capacity_and_notify(lo->lo_disk, size))
232 kobject_uevent(&disk_to_dev(lo->lo_disk)->kobj, KOBJ_CHANGE);
235 static int lo_write_bvec(struct file *file, struct bio_vec *bvec, loff_t *ppos)
240 iov_iter_bvec(&i, WRITE, bvec, 1, bvec->bv_len);
242 file_start_write(file);
243 bw = vfs_iter_write(file, &i, ppos, 0);
244 file_end_write(file);
246 if (likely(bw == bvec->bv_len))
249 printk_ratelimited(KERN_ERR
250 "loop: Write error at byte offset %llu, length %i.\n",
251 (unsigned long long)*ppos, bvec->bv_len);
257 static int lo_write_simple(struct loop_device *lo, struct request *rq,
261 struct req_iterator iter;
264 rq_for_each_segment(bvec, rq, iter) {
265 ret = lo_write_bvec(lo->lo_backing_file, &bvec, &pos);
274 static int lo_read_simple(struct loop_device *lo, struct request *rq,
278 struct req_iterator iter;
282 rq_for_each_segment(bvec, rq, iter) {
283 iov_iter_bvec(&i, READ, &bvec, 1, bvec.bv_len);
284 len = vfs_iter_read(lo->lo_backing_file, &i, &pos, 0);
288 flush_dcache_page(bvec.bv_page);
290 if (len != bvec.bv_len) {
293 __rq_for_each_bio(bio, rq)
303 static int lo_fallocate(struct loop_device *lo, struct request *rq, loff_t pos,
307 * We use fallocate to manipulate the space mappings used by the image
308 * a.k.a. discard/zerorange.
310 struct file *file = lo->lo_backing_file;
311 struct request_queue *q = lo->lo_queue;
314 mode |= FALLOC_FL_KEEP_SIZE;
316 if (!blk_queue_discard(q)) {
321 ret = file->f_op->fallocate(file, mode, pos, blk_rq_bytes(rq));
322 if (unlikely(ret && ret != -EINVAL && ret != -EOPNOTSUPP))
328 static int lo_req_flush(struct loop_device *lo, struct request *rq)
330 struct file *file = lo->lo_backing_file;
331 int ret = vfs_fsync(file, 0);
332 if (unlikely(ret && ret != -EINVAL))
338 static void lo_complete_rq(struct request *rq)
340 struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
341 blk_status_t ret = BLK_STS_OK;
343 if (!cmd->use_aio || cmd->ret < 0 || cmd->ret == blk_rq_bytes(rq) ||
344 req_op(rq) != REQ_OP_READ) {
346 ret = errno_to_blk_status(cmd->ret);
351 * Short READ - if we got some data, advance our request and
352 * retry it. If we got no data, end the rest with EIO.
355 blk_update_request(rq, BLK_STS_OK, cmd->ret);
357 blk_mq_requeue_request(rq, true);
360 struct bio *bio = rq->bio;
369 blk_mq_end_request(rq, ret);
373 static void lo_rw_aio_do_completion(struct loop_cmd *cmd)
375 struct request *rq = blk_mq_rq_from_pdu(cmd);
377 if (!atomic_dec_and_test(&cmd->ref))
381 if (likely(!blk_should_fake_timeout(rq->q)))
382 blk_mq_complete_request(rq);
385 static void lo_rw_aio_complete(struct kiocb *iocb, long ret)
387 struct loop_cmd *cmd = container_of(iocb, struct loop_cmd, iocb);
390 lo_rw_aio_do_completion(cmd);
393 static int lo_rw_aio(struct loop_device *lo, struct loop_cmd *cmd,
396 struct iov_iter iter;
397 struct req_iterator rq_iter;
398 struct bio_vec *bvec;
399 struct request *rq = blk_mq_rq_from_pdu(cmd);
400 struct bio *bio = rq->bio;
401 struct file *file = lo->lo_backing_file;
407 rq_for_each_bvec(tmp, rq, rq_iter)
410 if (rq->bio != rq->biotail) {
412 bvec = kmalloc_array(nr_bvec, sizeof(struct bio_vec),
419 * The bios of the request may be started from the middle of
420 * the 'bvec' because of bio splitting, so we can't directly
421 * copy bio->bi_iov_vec to new bvec. The rq_for_each_bvec
422 * API will take care of all details for us.
424 rq_for_each_bvec(tmp, rq, rq_iter) {
432 * Same here, this bio may be started from the middle of the
433 * 'bvec' because of bio splitting, so offset from the bvec
434 * must be passed to iov iterator
436 offset = bio->bi_iter.bi_bvec_done;
437 bvec = __bvec_iter_bvec(bio->bi_io_vec, bio->bi_iter);
439 atomic_set(&cmd->ref, 2);
441 iov_iter_bvec(&iter, rw, bvec, nr_bvec, blk_rq_bytes(rq));
442 iter.iov_offset = offset;
444 cmd->iocb.ki_pos = pos;
445 cmd->iocb.ki_filp = file;
446 cmd->iocb.ki_complete = lo_rw_aio_complete;
447 cmd->iocb.ki_flags = IOCB_DIRECT;
448 cmd->iocb.ki_ioprio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_NONE, 0);
451 ret = call_write_iter(file, &cmd->iocb, &iter);
453 ret = call_read_iter(file, &cmd->iocb, &iter);
455 lo_rw_aio_do_completion(cmd);
457 if (ret != -EIOCBQUEUED)
458 lo_rw_aio_complete(&cmd->iocb, ret);
462 static int do_req_filebacked(struct loop_device *lo, struct request *rq)
464 struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
465 loff_t pos = ((loff_t) blk_rq_pos(rq) << 9) + lo->lo_offset;
468 * lo_write_simple and lo_read_simple should have been covered
469 * by io submit style function like lo_rw_aio(), one blocker
470 * is that lo_read_simple() need to call flush_dcache_page after
471 * the page is written from kernel, and it isn't easy to handle
472 * this in io submit style function which submits all segments
473 * of the req at one time. And direct read IO doesn't need to
474 * run flush_dcache_page().
476 switch (req_op(rq)) {
478 return lo_req_flush(lo, rq);
479 case REQ_OP_WRITE_ZEROES:
481 * If the caller doesn't want deallocation, call zeroout to
482 * write zeroes the range. Otherwise, punch them out.
484 return lo_fallocate(lo, rq, pos,
485 (rq->cmd_flags & REQ_NOUNMAP) ?
486 FALLOC_FL_ZERO_RANGE :
487 FALLOC_FL_PUNCH_HOLE);
489 return lo_fallocate(lo, rq, pos, FALLOC_FL_PUNCH_HOLE);
492 return lo_rw_aio(lo, cmd, pos, WRITE);
494 return lo_write_simple(lo, rq, pos);
497 return lo_rw_aio(lo, cmd, pos, READ);
499 return lo_read_simple(lo, rq, pos);
506 static inline void loop_update_dio(struct loop_device *lo)
508 __loop_update_dio(lo, (lo->lo_backing_file->f_flags & O_DIRECT) |
512 static void loop_reread_partitions(struct loop_device *lo)
516 mutex_lock(&lo->lo_disk->open_mutex);
517 rc = bdev_disk_changed(lo->lo_disk, false);
518 mutex_unlock(&lo->lo_disk->open_mutex);
520 pr_warn("%s: partition scan of loop%d (%s) failed (rc=%d)\n",
521 __func__, lo->lo_number, lo->lo_file_name, rc);
524 static inline int is_loop_device(struct file *file)
526 struct inode *i = file->f_mapping->host;
528 return i && S_ISBLK(i->i_mode) && imajor(i) == LOOP_MAJOR;
531 static int loop_validate_file(struct file *file, struct block_device *bdev)
533 struct inode *inode = file->f_mapping->host;
534 struct file *f = file;
536 /* Avoid recursion */
537 while (is_loop_device(f)) {
538 struct loop_device *l;
540 lockdep_assert_held(&loop_validate_mutex);
541 if (f->f_mapping->host->i_rdev == bdev->bd_dev)
544 l = I_BDEV(f->f_mapping->host)->bd_disk->private_data;
545 if (l->lo_state != Lo_bound)
547 /* Order wrt setting lo->lo_backing_file in loop_configure(). */
549 f = l->lo_backing_file;
551 if (!S_ISREG(inode->i_mode) && !S_ISBLK(inode->i_mode))
557 * loop_change_fd switched the backing store of a loopback device to
558 * a new file. This is useful for operating system installers to free up
559 * the original file and in High Availability environments to switch to
560 * an alternative location for the content in case of server meltdown.
561 * This can only work if the loop device is used read-only, and if the
562 * new backing store is the same size and type as the old backing store.
564 static int loop_change_fd(struct loop_device *lo, struct block_device *bdev,
567 struct file *file = fget(arg);
568 struct file *old_file;
575 is_loop = is_loop_device(file);
576 error = loop_global_lock_killable(lo, is_loop);
580 if (lo->lo_state != Lo_bound)
583 /* the loop device has to be read-only */
585 if (!(lo->lo_flags & LO_FLAGS_READ_ONLY))
588 error = loop_validate_file(file, bdev);
592 old_file = lo->lo_backing_file;
596 /* size of the new backing store needs to be the same */
597 if (get_loop_size(lo, file) != get_loop_size(lo, old_file))
601 disk_force_media_change(lo->lo_disk, DISK_EVENT_MEDIA_CHANGE);
602 blk_mq_freeze_queue(lo->lo_queue);
603 mapping_set_gfp_mask(old_file->f_mapping, lo->old_gfp_mask);
604 lo->lo_backing_file = file;
605 lo->old_gfp_mask = mapping_gfp_mask(file->f_mapping);
606 mapping_set_gfp_mask(file->f_mapping,
607 lo->old_gfp_mask & ~(__GFP_IO|__GFP_FS));
609 blk_mq_unfreeze_queue(lo->lo_queue);
610 partscan = lo->lo_flags & LO_FLAGS_PARTSCAN;
611 loop_global_unlock(lo, is_loop);
614 * Flush loop_validate_file() before fput(), for l->lo_backing_file
615 * might be pointing at old_file which might be the last reference.
618 mutex_lock(&loop_validate_mutex);
619 mutex_unlock(&loop_validate_mutex);
622 * We must drop file reference outside of lo_mutex as dropping
623 * the file ref can take open_mutex which creates circular locking
628 loop_reread_partitions(lo);
632 loop_global_unlock(lo, is_loop);
638 /* loop sysfs attributes */
640 static ssize_t loop_attr_show(struct device *dev, char *page,
641 ssize_t (*callback)(struct loop_device *, char *))
643 struct gendisk *disk = dev_to_disk(dev);
644 struct loop_device *lo = disk->private_data;
646 return callback(lo, page);
649 #define LOOP_ATTR_RO(_name) \
650 static ssize_t loop_attr_##_name##_show(struct loop_device *, char *); \
651 static ssize_t loop_attr_do_show_##_name(struct device *d, \
652 struct device_attribute *attr, char *b) \
654 return loop_attr_show(d, b, loop_attr_##_name##_show); \
656 static struct device_attribute loop_attr_##_name = \
657 __ATTR(_name, 0444, loop_attr_do_show_##_name, NULL);
659 static ssize_t loop_attr_backing_file_show(struct loop_device *lo, char *buf)
664 spin_lock_irq(&lo->lo_lock);
665 if (lo->lo_backing_file)
666 p = file_path(lo->lo_backing_file, buf, PAGE_SIZE - 1);
667 spin_unlock_irq(&lo->lo_lock);
669 if (IS_ERR_OR_NULL(p))
673 memmove(buf, p, ret);
681 static ssize_t loop_attr_offset_show(struct loop_device *lo, char *buf)
683 return sprintf(buf, "%llu\n", (unsigned long long)lo->lo_offset);
686 static ssize_t loop_attr_sizelimit_show(struct loop_device *lo, char *buf)
688 return sprintf(buf, "%llu\n", (unsigned long long)lo->lo_sizelimit);
691 static ssize_t loop_attr_autoclear_show(struct loop_device *lo, char *buf)
693 int autoclear = (lo->lo_flags & LO_FLAGS_AUTOCLEAR);
695 return sprintf(buf, "%s\n", autoclear ? "1" : "0");
698 static ssize_t loop_attr_partscan_show(struct loop_device *lo, char *buf)
700 int partscan = (lo->lo_flags & LO_FLAGS_PARTSCAN);
702 return sprintf(buf, "%s\n", partscan ? "1" : "0");
705 static ssize_t loop_attr_dio_show(struct loop_device *lo, char *buf)
707 int dio = (lo->lo_flags & LO_FLAGS_DIRECT_IO);
709 return sprintf(buf, "%s\n", dio ? "1" : "0");
712 LOOP_ATTR_RO(backing_file);
713 LOOP_ATTR_RO(offset);
714 LOOP_ATTR_RO(sizelimit);
715 LOOP_ATTR_RO(autoclear);
716 LOOP_ATTR_RO(partscan);
719 static struct attribute *loop_attrs[] = {
720 &loop_attr_backing_file.attr,
721 &loop_attr_offset.attr,
722 &loop_attr_sizelimit.attr,
723 &loop_attr_autoclear.attr,
724 &loop_attr_partscan.attr,
729 static struct attribute_group loop_attribute_group = {
734 static void loop_sysfs_init(struct loop_device *lo)
736 lo->sysfs_inited = !sysfs_create_group(&disk_to_dev(lo->lo_disk)->kobj,
737 &loop_attribute_group);
740 static void loop_sysfs_exit(struct loop_device *lo)
742 if (lo->sysfs_inited)
743 sysfs_remove_group(&disk_to_dev(lo->lo_disk)->kobj,
744 &loop_attribute_group);
747 static void loop_config_discard(struct loop_device *lo)
749 struct file *file = lo->lo_backing_file;
750 struct inode *inode = file->f_mapping->host;
751 struct request_queue *q = lo->lo_queue;
752 u32 granularity, max_discard_sectors;
755 * If the backing device is a block device, mirror its zeroing
756 * capability. Set the discard sectors to the block device's zeroing
757 * capabilities because loop discards result in blkdev_issue_zeroout(),
758 * not blkdev_issue_discard(). This maintains consistent behavior with
759 * file-backed loop devices: discarded regions read back as zero.
761 if (S_ISBLK(inode->i_mode)) {
762 struct request_queue *backingq = bdev_get_queue(I_BDEV(inode));
764 max_discard_sectors = backingq->limits.max_write_zeroes_sectors;
765 granularity = backingq->limits.discard_granularity ?:
766 queue_physical_block_size(backingq);
769 * We use punch hole to reclaim the free space used by the
770 * image a.k.a. discard.
772 } else if (!file->f_op->fallocate) {
773 max_discard_sectors = 0;
777 max_discard_sectors = UINT_MAX >> 9;
778 granularity = inode->i_sb->s_blocksize;
781 if (max_discard_sectors) {
782 q->limits.discard_granularity = granularity;
783 blk_queue_max_discard_sectors(q, max_discard_sectors);
784 blk_queue_max_write_zeroes_sectors(q, max_discard_sectors);
785 blk_queue_flag_set(QUEUE_FLAG_DISCARD, q);
787 q->limits.discard_granularity = 0;
788 blk_queue_max_discard_sectors(q, 0);
789 blk_queue_max_write_zeroes_sectors(q, 0);
790 blk_queue_flag_clear(QUEUE_FLAG_DISCARD, q);
792 q->limits.discard_alignment = 0;
796 struct rb_node rb_node;
797 struct work_struct work;
798 struct list_head cmd_list;
799 struct list_head idle_list;
800 struct loop_device *lo;
801 struct cgroup_subsys_state *blkcg_css;
802 unsigned long last_ran_at;
805 static void loop_workfn(struct work_struct *work);
806 static void loop_rootcg_workfn(struct work_struct *work);
807 static void loop_free_idle_workers(struct timer_list *timer);
809 #ifdef CONFIG_BLK_CGROUP
810 static inline int queue_on_root_worker(struct cgroup_subsys_state *css)
812 return !css || css == blkcg_root_css;
815 static inline int queue_on_root_worker(struct cgroup_subsys_state *css)
821 static void loop_queue_work(struct loop_device *lo, struct loop_cmd *cmd)
823 struct rb_node **node = &(lo->worker_tree.rb_node), *parent = NULL;
824 struct loop_worker *cur_worker, *worker = NULL;
825 struct work_struct *work;
826 struct list_head *cmd_list;
828 spin_lock_irq(&lo->lo_work_lock);
830 if (queue_on_root_worker(cmd->blkcg_css))
833 node = &lo->worker_tree.rb_node;
837 cur_worker = container_of(*node, struct loop_worker, rb_node);
838 if (cur_worker->blkcg_css == cmd->blkcg_css) {
841 } else if ((long)cur_worker->blkcg_css < (long)cmd->blkcg_css) {
842 node = &(*node)->rb_left;
844 node = &(*node)->rb_right;
850 worker = kzalloc(sizeof(struct loop_worker), GFP_NOWAIT | __GFP_NOWARN);
852 * In the event we cannot allocate a worker, just queue on the
853 * rootcg worker and issue the I/O as the rootcg
856 cmd->blkcg_css = NULL;
858 css_put(cmd->memcg_css);
859 cmd->memcg_css = NULL;
863 worker->blkcg_css = cmd->blkcg_css;
864 css_get(worker->blkcg_css);
865 INIT_WORK(&worker->work, loop_workfn);
866 INIT_LIST_HEAD(&worker->cmd_list);
867 INIT_LIST_HEAD(&worker->idle_list);
869 rb_link_node(&worker->rb_node, parent, node);
870 rb_insert_color(&worker->rb_node, &lo->worker_tree);
874 * We need to remove from the idle list here while
875 * holding the lock so that the idle timer doesn't
878 if (!list_empty(&worker->idle_list))
879 list_del_init(&worker->idle_list);
880 work = &worker->work;
881 cmd_list = &worker->cmd_list;
883 work = &lo->rootcg_work;
884 cmd_list = &lo->rootcg_cmd_list;
886 list_add_tail(&cmd->list_entry, cmd_list);
887 queue_work(lo->workqueue, work);
888 spin_unlock_irq(&lo->lo_work_lock);
891 static void loop_update_rotational(struct loop_device *lo)
893 struct file *file = lo->lo_backing_file;
894 struct inode *file_inode = file->f_mapping->host;
895 struct block_device *file_bdev = file_inode->i_sb->s_bdev;
896 struct request_queue *q = lo->lo_queue;
899 /* not all filesystems (e.g. tmpfs) have a sb->s_bdev */
901 nonrot = blk_queue_nonrot(bdev_get_queue(file_bdev));
904 blk_queue_flag_set(QUEUE_FLAG_NONROT, q);
906 blk_queue_flag_clear(QUEUE_FLAG_NONROT, q);
910 * loop_set_status_from_info - configure device from loop_info
911 * @lo: struct loop_device to configure
912 * @info: struct loop_info64 to configure the device with
914 * Configures the loop device parameters according to the passed
915 * in loop_info64 configuration.
918 loop_set_status_from_info(struct loop_device *lo,
919 const struct loop_info64 *info)
921 if ((unsigned int) info->lo_encrypt_key_size > LO_KEY_SIZE)
924 switch (info->lo_encrypt_type) {
928 pr_warn("support for the xor transformation has been removed.\n");
930 case LO_CRYPT_CRYPTOAPI:
931 pr_warn("support for cryptoloop has been removed. Use dm-crypt instead.\n");
937 lo->lo_offset = info->lo_offset;
938 lo->lo_sizelimit = info->lo_sizelimit;
939 memcpy(lo->lo_file_name, info->lo_file_name, LO_NAME_SIZE);
940 lo->lo_file_name[LO_NAME_SIZE-1] = 0;
941 lo->lo_flags = info->lo_flags;
945 static int loop_configure(struct loop_device *lo, fmode_t mode,
946 struct block_device *bdev,
947 const struct loop_config *config)
949 struct file *file = fget(config->fd);
951 struct address_space *mapping;
955 unsigned short bsize;
960 is_loop = is_loop_device(file);
962 /* This is safe, since we have a reference from open(). */
963 __module_get(THIS_MODULE);
966 * If we don't hold exclusive handle for the device, upgrade to it
967 * here to avoid changing device under exclusive owner.
969 if (!(mode & FMODE_EXCL)) {
970 error = bd_prepare_to_claim(bdev, loop_configure);
975 error = loop_global_lock_killable(lo, is_loop);
980 if (lo->lo_state != Lo_unbound)
983 error = loop_validate_file(file, bdev);
987 mapping = file->f_mapping;
988 inode = mapping->host;
990 if ((config->info.lo_flags & ~LOOP_CONFIGURE_SETTABLE_FLAGS) != 0) {
995 if (config->block_size) {
996 error = blk_validate_block_size(config->block_size);
1001 error = loop_set_status_from_info(lo, &config->info);
1005 if (!(file->f_mode & FMODE_WRITE) || !(mode & FMODE_WRITE) ||
1006 !file->f_op->write_iter)
1007 lo->lo_flags |= LO_FLAGS_READ_ONLY;
1009 lo->workqueue = alloc_workqueue("loop%d",
1010 WQ_UNBOUND | WQ_FREEZABLE,
1013 if (!lo->workqueue) {
1018 disk_force_media_change(lo->lo_disk, DISK_EVENT_MEDIA_CHANGE);
1019 set_disk_ro(lo->lo_disk, (lo->lo_flags & LO_FLAGS_READ_ONLY) != 0);
1021 INIT_WORK(&lo->rootcg_work, loop_rootcg_workfn);
1022 INIT_LIST_HEAD(&lo->rootcg_cmd_list);
1023 INIT_LIST_HEAD(&lo->idle_worker_list);
1024 lo->worker_tree = RB_ROOT;
1025 timer_setup(&lo->timer, loop_free_idle_workers,
1027 lo->use_dio = lo->lo_flags & LO_FLAGS_DIRECT_IO;
1028 lo->lo_device = bdev;
1029 lo->lo_backing_file = file;
1030 lo->old_gfp_mask = mapping_gfp_mask(mapping);
1031 mapping_set_gfp_mask(mapping, lo->old_gfp_mask & ~(__GFP_IO|__GFP_FS));
1033 if (!(lo->lo_flags & LO_FLAGS_READ_ONLY) && file->f_op->fsync)
1034 blk_queue_write_cache(lo->lo_queue, true, false);
1036 if (config->block_size)
1037 bsize = config->block_size;
1038 else if ((lo->lo_backing_file->f_flags & O_DIRECT) && inode->i_sb->s_bdev)
1039 /* In case of direct I/O, match underlying block size */
1040 bsize = bdev_logical_block_size(inode->i_sb->s_bdev);
1044 blk_queue_logical_block_size(lo->lo_queue, bsize);
1045 blk_queue_physical_block_size(lo->lo_queue, bsize);
1046 blk_queue_io_min(lo->lo_queue, bsize);
1048 loop_config_discard(lo);
1049 loop_update_rotational(lo);
1050 loop_update_dio(lo);
1051 loop_sysfs_init(lo);
1053 size = get_loop_size(lo, file);
1054 loop_set_size(lo, size);
1056 /* Order wrt reading lo_state in loop_validate_file(). */
1059 lo->lo_state = Lo_bound;
1061 lo->lo_flags |= LO_FLAGS_PARTSCAN;
1062 partscan = lo->lo_flags & LO_FLAGS_PARTSCAN;
1064 lo->lo_disk->flags &= ~GENHD_FL_NO_PART;
1066 loop_global_unlock(lo, is_loop);
1068 loop_reread_partitions(lo);
1069 if (!(mode & FMODE_EXCL))
1070 bd_abort_claiming(bdev, loop_configure);
1074 loop_global_unlock(lo, is_loop);
1076 if (!(mode & FMODE_EXCL))
1077 bd_abort_claiming(bdev, loop_configure);
1080 /* This is safe: open() is still holding a reference. */
1081 module_put(THIS_MODULE);
1085 static void __loop_clr_fd(struct loop_device *lo)
1088 gfp_t gfp = lo->old_gfp_mask;
1089 struct loop_worker *pos, *worker;
1092 * Flush loop_configure() and loop_change_fd(). It is acceptable for
1093 * loop_validate_file() to succeed, for actual clear operation has not
1096 mutex_lock(&loop_validate_mutex);
1097 mutex_unlock(&loop_validate_mutex);
1099 * loop_validate_file() now fails because l->lo_state != Lo_bound
1104 * Since this function is called upon "ioctl(LOOP_CLR_FD)" xor "close()
1105 * after ioctl(LOOP_CLR_FD)", it is a sign of something going wrong if
1106 * lo->lo_state has changed while waiting for lo->lo_mutex.
1108 mutex_lock(&lo->lo_mutex);
1109 BUG_ON(lo->lo_state != Lo_rundown);
1110 mutex_unlock(&lo->lo_mutex);
1112 if (test_bit(QUEUE_FLAG_WC, &lo->lo_queue->queue_flags))
1113 blk_queue_write_cache(lo->lo_queue, false, false);
1115 /* freeze request queue during the transition */
1116 blk_mq_freeze_queue(lo->lo_queue);
1118 destroy_workqueue(lo->workqueue);
1119 spin_lock_irq(&lo->lo_work_lock);
1120 list_for_each_entry_safe(worker, pos, &lo->idle_worker_list,
1122 list_del(&worker->idle_list);
1123 rb_erase(&worker->rb_node, &lo->worker_tree);
1124 css_put(worker->blkcg_css);
1127 spin_unlock_irq(&lo->lo_work_lock);
1128 del_timer_sync(&lo->timer);
1130 spin_lock_irq(&lo->lo_lock);
1131 filp = lo->lo_backing_file;
1132 lo->lo_backing_file = NULL;
1133 spin_unlock_irq(&lo->lo_lock);
1135 lo->lo_device = NULL;
1137 lo->lo_sizelimit = 0;
1138 memset(lo->lo_file_name, 0, LO_NAME_SIZE);
1139 blk_queue_logical_block_size(lo->lo_queue, 512);
1140 blk_queue_physical_block_size(lo->lo_queue, 512);
1141 blk_queue_io_min(lo->lo_queue, 512);
1142 invalidate_disk(lo->lo_disk);
1143 loop_sysfs_exit(lo);
1144 /* let user-space know about this change */
1145 kobject_uevent(&disk_to_dev(lo->lo_disk)->kobj, KOBJ_CHANGE);
1146 mapping_set_gfp_mask(filp->f_mapping, gfp);
1147 blk_mq_unfreeze_queue(lo->lo_queue);
1149 disk_force_media_change(lo->lo_disk, DISK_EVENT_MEDIA_CHANGE);
1151 if (lo->lo_flags & LO_FLAGS_PARTSCAN) {
1154 mutex_lock(&lo->lo_disk->open_mutex);
1155 err = bdev_disk_changed(lo->lo_disk, false);
1156 mutex_unlock(&lo->lo_disk->open_mutex);
1158 pr_warn("%s: partition scan of loop%d failed (rc=%d)\n",
1159 __func__, lo->lo_number, err);
1160 /* Device is gone, no point in returning error */
1165 lo->lo_disk->flags |= GENHD_FL_NO_PART;
1170 static void loop_rundown_completed(struct loop_device *lo)
1172 mutex_lock(&lo->lo_mutex);
1173 lo->lo_state = Lo_unbound;
1174 mutex_unlock(&lo->lo_mutex);
1175 module_put(THIS_MODULE);
1178 static void loop_rundown_workfn(struct work_struct *work)
1180 struct loop_device *lo = container_of(work, struct loop_device,
1182 struct block_device *bdev = lo->lo_device;
1183 struct gendisk *disk = lo->lo_disk;
1186 kobject_put(&bdev->bd_device.kobj);
1187 module_put(disk->fops->owner);
1188 loop_rundown_completed(lo);
1191 static void loop_schedule_rundown(struct loop_device *lo)
1193 struct block_device *bdev = lo->lo_device;
1194 struct gendisk *disk = lo->lo_disk;
1196 __module_get(disk->fops->owner);
1197 kobject_get(&bdev->bd_device.kobj);
1198 INIT_WORK(&lo->rundown_work, loop_rundown_workfn);
1199 queue_work(system_long_wq, &lo->rundown_work);
1202 static int loop_clr_fd(struct loop_device *lo)
1206 err = mutex_lock_killable(&lo->lo_mutex);
1209 if (lo->lo_state != Lo_bound) {
1210 mutex_unlock(&lo->lo_mutex);
1214 * If we've explicitly asked to tear down the loop device,
1215 * and it has an elevated reference count, set it for auto-teardown when
1216 * the last reference goes away. This stops $!~#$@ udev from
1217 * preventing teardown because it decided that it needs to run blkid on
1218 * the loopback device whenever they appear. xfstests is notorious for
1219 * failing tests because blkid via udev races with a losetup
1220 * <dev>/do something like mkfs/losetup -d <dev> causing the losetup -d
1221 * command to fail with EBUSY.
1223 if (atomic_read(&lo->lo_refcnt) > 1) {
1224 lo->lo_flags |= LO_FLAGS_AUTOCLEAR;
1225 mutex_unlock(&lo->lo_mutex);
1228 lo->lo_state = Lo_rundown;
1229 mutex_unlock(&lo->lo_mutex);
1232 loop_rundown_completed(lo);
1237 loop_set_status(struct loop_device *lo, const struct loop_info64 *info)
1241 bool partscan = false;
1242 bool size_changed = false;
1244 err = mutex_lock_killable(&lo->lo_mutex);
1247 if (lo->lo_state != Lo_bound) {
1252 if (lo->lo_offset != info->lo_offset ||
1253 lo->lo_sizelimit != info->lo_sizelimit) {
1254 size_changed = true;
1255 sync_blockdev(lo->lo_device);
1256 invalidate_bdev(lo->lo_device);
1259 /* I/O need to be drained during transfer transition */
1260 blk_mq_freeze_queue(lo->lo_queue);
1262 if (size_changed && lo->lo_device->bd_inode->i_mapping->nrpages) {
1263 /* If any pages were dirtied after invalidate_bdev(), try again */
1265 pr_warn("%s: loop%d (%s) has still dirty pages (nrpages=%lu)\n",
1266 __func__, lo->lo_number, lo->lo_file_name,
1267 lo->lo_device->bd_inode->i_mapping->nrpages);
1271 prev_lo_flags = lo->lo_flags;
1273 err = loop_set_status_from_info(lo, info);
1277 /* Mask out flags that can't be set using LOOP_SET_STATUS. */
1278 lo->lo_flags &= LOOP_SET_STATUS_SETTABLE_FLAGS;
1279 /* For those flags, use the previous values instead */
1280 lo->lo_flags |= prev_lo_flags & ~LOOP_SET_STATUS_SETTABLE_FLAGS;
1281 /* For flags that can't be cleared, use previous values too */
1282 lo->lo_flags |= prev_lo_flags & ~LOOP_SET_STATUS_CLEARABLE_FLAGS;
1285 loff_t new_size = get_size(lo->lo_offset, lo->lo_sizelimit,
1286 lo->lo_backing_file);
1287 loop_set_size(lo, new_size);
1290 loop_config_discard(lo);
1292 /* update dio if lo_offset or transfer is changed */
1293 __loop_update_dio(lo, lo->use_dio);
1296 blk_mq_unfreeze_queue(lo->lo_queue);
1298 if (!err && (lo->lo_flags & LO_FLAGS_PARTSCAN) &&
1299 !(prev_lo_flags & LO_FLAGS_PARTSCAN)) {
1300 lo->lo_disk->flags &= ~GENHD_FL_NO_PART;
1304 mutex_unlock(&lo->lo_mutex);
1306 loop_reread_partitions(lo);
1312 loop_get_status(struct loop_device *lo, struct loop_info64 *info)
1318 ret = mutex_lock_killable(&lo->lo_mutex);
1321 if (lo->lo_state != Lo_bound) {
1322 mutex_unlock(&lo->lo_mutex);
1326 memset(info, 0, sizeof(*info));
1327 info->lo_number = lo->lo_number;
1328 info->lo_offset = lo->lo_offset;
1329 info->lo_sizelimit = lo->lo_sizelimit;
1330 info->lo_flags = lo->lo_flags;
1331 memcpy(info->lo_file_name, lo->lo_file_name, LO_NAME_SIZE);
1333 /* Drop lo_mutex while we call into the filesystem. */
1334 path = lo->lo_backing_file->f_path;
1336 mutex_unlock(&lo->lo_mutex);
1337 ret = vfs_getattr(&path, &stat, STATX_INO, AT_STATX_SYNC_AS_STAT);
1339 info->lo_device = huge_encode_dev(stat.dev);
1340 info->lo_inode = stat.ino;
1341 info->lo_rdevice = huge_encode_dev(stat.rdev);
1348 loop_info64_from_old(const struct loop_info *info, struct loop_info64 *info64)
1350 memset(info64, 0, sizeof(*info64));
1351 info64->lo_number = info->lo_number;
1352 info64->lo_device = info->lo_device;
1353 info64->lo_inode = info->lo_inode;
1354 info64->lo_rdevice = info->lo_rdevice;
1355 info64->lo_offset = info->lo_offset;
1356 info64->lo_sizelimit = 0;
1357 info64->lo_flags = info->lo_flags;
1358 memcpy(info64->lo_file_name, info->lo_name, LO_NAME_SIZE);
1362 loop_info64_to_old(const struct loop_info64 *info64, struct loop_info *info)
1364 memset(info, 0, sizeof(*info));
1365 info->lo_number = info64->lo_number;
1366 info->lo_device = info64->lo_device;
1367 info->lo_inode = info64->lo_inode;
1368 info->lo_rdevice = info64->lo_rdevice;
1369 info->lo_offset = info64->lo_offset;
1370 info->lo_flags = info64->lo_flags;
1371 memcpy(info->lo_name, info64->lo_file_name, LO_NAME_SIZE);
1373 /* error in case values were truncated */
1374 if (info->lo_device != info64->lo_device ||
1375 info->lo_rdevice != info64->lo_rdevice ||
1376 info->lo_inode != info64->lo_inode ||
1377 info->lo_offset != info64->lo_offset)
1384 loop_set_status_old(struct loop_device *lo, const struct loop_info __user *arg)
1386 struct loop_info info;
1387 struct loop_info64 info64;
1389 if (copy_from_user(&info, arg, sizeof (struct loop_info)))
1391 loop_info64_from_old(&info, &info64);
1392 return loop_set_status(lo, &info64);
1396 loop_set_status64(struct loop_device *lo, const struct loop_info64 __user *arg)
1398 struct loop_info64 info64;
1400 if (copy_from_user(&info64, arg, sizeof (struct loop_info64)))
1402 return loop_set_status(lo, &info64);
1406 loop_get_status_old(struct loop_device *lo, struct loop_info __user *arg) {
1407 struct loop_info info;
1408 struct loop_info64 info64;
1413 err = loop_get_status(lo, &info64);
1415 err = loop_info64_to_old(&info64, &info);
1416 if (!err && copy_to_user(arg, &info, sizeof(info)))
1423 loop_get_status64(struct loop_device *lo, struct loop_info64 __user *arg) {
1424 struct loop_info64 info64;
1429 err = loop_get_status(lo, &info64);
1430 if (!err && copy_to_user(arg, &info64, sizeof(info64)))
1436 static int loop_set_capacity(struct loop_device *lo)
1440 if (unlikely(lo->lo_state != Lo_bound))
1443 size = get_loop_size(lo, lo->lo_backing_file);
1444 loop_set_size(lo, size);
1449 static int loop_set_dio(struct loop_device *lo, unsigned long arg)
1452 if (lo->lo_state != Lo_bound)
1455 __loop_update_dio(lo, !!arg);
1456 if (lo->use_dio == !!arg)
1463 static int loop_set_block_size(struct loop_device *lo, unsigned long arg)
1467 if (lo->lo_state != Lo_bound)
1470 err = blk_validate_block_size(arg);
1474 if (lo->lo_queue->limits.logical_block_size == arg)
1477 sync_blockdev(lo->lo_device);
1478 invalidate_bdev(lo->lo_device);
1480 blk_mq_freeze_queue(lo->lo_queue);
1482 /* invalidate_bdev should have truncated all the pages */
1483 if (lo->lo_device->bd_inode->i_mapping->nrpages) {
1485 pr_warn("%s: loop%d (%s) has still dirty pages (nrpages=%lu)\n",
1486 __func__, lo->lo_number, lo->lo_file_name,
1487 lo->lo_device->bd_inode->i_mapping->nrpages);
1491 blk_queue_logical_block_size(lo->lo_queue, arg);
1492 blk_queue_physical_block_size(lo->lo_queue, arg);
1493 blk_queue_io_min(lo->lo_queue, arg);
1494 loop_update_dio(lo);
1496 blk_mq_unfreeze_queue(lo->lo_queue);
1501 static int lo_simple_ioctl(struct loop_device *lo, unsigned int cmd,
1506 err = mutex_lock_killable(&lo->lo_mutex);
1510 case LOOP_SET_CAPACITY:
1511 err = loop_set_capacity(lo);
1513 case LOOP_SET_DIRECT_IO:
1514 err = loop_set_dio(lo, arg);
1516 case LOOP_SET_BLOCK_SIZE:
1517 err = loop_set_block_size(lo, arg);
1522 mutex_unlock(&lo->lo_mutex);
1526 static int lo_ioctl(struct block_device *bdev, fmode_t mode,
1527 unsigned int cmd, unsigned long arg)
1529 struct loop_device *lo = bdev->bd_disk->private_data;
1530 void __user *argp = (void __user *) arg;
1536 * Legacy case - pass in a zeroed out struct loop_config with
1537 * only the file descriptor set , which corresponds with the
1538 * default parameters we'd have used otherwise.
1540 struct loop_config config;
1542 memset(&config, 0, sizeof(config));
1545 return loop_configure(lo, mode, bdev, &config);
1547 case LOOP_CONFIGURE: {
1548 struct loop_config config;
1550 if (copy_from_user(&config, argp, sizeof(config)))
1553 return loop_configure(lo, mode, bdev, &config);
1555 case LOOP_CHANGE_FD:
1556 return loop_change_fd(lo, bdev, arg);
1558 return loop_clr_fd(lo);
1559 case LOOP_SET_STATUS:
1561 if ((mode & FMODE_WRITE) || capable(CAP_SYS_ADMIN)) {
1562 err = loop_set_status_old(lo, argp);
1565 case LOOP_GET_STATUS:
1566 return loop_get_status_old(lo, argp);
1567 case LOOP_SET_STATUS64:
1569 if ((mode & FMODE_WRITE) || capable(CAP_SYS_ADMIN)) {
1570 err = loop_set_status64(lo, argp);
1573 case LOOP_GET_STATUS64:
1574 return loop_get_status64(lo, argp);
1575 case LOOP_SET_CAPACITY:
1576 case LOOP_SET_DIRECT_IO:
1577 case LOOP_SET_BLOCK_SIZE:
1578 if (!(mode & FMODE_WRITE) && !capable(CAP_SYS_ADMIN))
1582 err = lo_simple_ioctl(lo, cmd, arg);
1589 #ifdef CONFIG_COMPAT
1590 struct compat_loop_info {
1591 compat_int_t lo_number; /* ioctl r/o */
1592 compat_dev_t lo_device; /* ioctl r/o */
1593 compat_ulong_t lo_inode; /* ioctl r/o */
1594 compat_dev_t lo_rdevice; /* ioctl r/o */
1595 compat_int_t lo_offset;
1596 compat_int_t lo_encrypt_key_size; /* ioctl w/o */
1597 compat_int_t lo_flags; /* ioctl r/o */
1598 char lo_name[LO_NAME_SIZE];
1599 unsigned char lo_encrypt_key[LO_KEY_SIZE]; /* ioctl w/o */
1600 compat_ulong_t lo_init[2];
1605 * Transfer 32-bit compatibility structure in userspace to 64-bit loop info
1606 * - noinlined to reduce stack space usage in main part of driver
1609 loop_info64_from_compat(const struct compat_loop_info __user *arg,
1610 struct loop_info64 *info64)
1612 struct compat_loop_info info;
1614 if (copy_from_user(&info, arg, sizeof(info)))
1617 memset(info64, 0, sizeof(*info64));
1618 info64->lo_number = info.lo_number;
1619 info64->lo_device = info.lo_device;
1620 info64->lo_inode = info.lo_inode;
1621 info64->lo_rdevice = info.lo_rdevice;
1622 info64->lo_offset = info.lo_offset;
1623 info64->lo_sizelimit = 0;
1624 info64->lo_flags = info.lo_flags;
1625 memcpy(info64->lo_file_name, info.lo_name, LO_NAME_SIZE);
1630 * Transfer 64-bit loop info to 32-bit compatibility structure in userspace
1631 * - noinlined to reduce stack space usage in main part of driver
1634 loop_info64_to_compat(const struct loop_info64 *info64,
1635 struct compat_loop_info __user *arg)
1637 struct compat_loop_info info;
1639 memset(&info, 0, sizeof(info));
1640 info.lo_number = info64->lo_number;
1641 info.lo_device = info64->lo_device;
1642 info.lo_inode = info64->lo_inode;
1643 info.lo_rdevice = info64->lo_rdevice;
1644 info.lo_offset = info64->lo_offset;
1645 info.lo_flags = info64->lo_flags;
1646 memcpy(info.lo_name, info64->lo_file_name, LO_NAME_SIZE);
1648 /* error in case values were truncated */
1649 if (info.lo_device != info64->lo_device ||
1650 info.lo_rdevice != info64->lo_rdevice ||
1651 info.lo_inode != info64->lo_inode ||
1652 info.lo_offset != info64->lo_offset)
1655 if (copy_to_user(arg, &info, sizeof(info)))
1661 loop_set_status_compat(struct loop_device *lo,
1662 const struct compat_loop_info __user *arg)
1664 struct loop_info64 info64;
1667 ret = loop_info64_from_compat(arg, &info64);
1670 return loop_set_status(lo, &info64);
1674 loop_get_status_compat(struct loop_device *lo,
1675 struct compat_loop_info __user *arg)
1677 struct loop_info64 info64;
1682 err = loop_get_status(lo, &info64);
1684 err = loop_info64_to_compat(&info64, arg);
1688 static int lo_compat_ioctl(struct block_device *bdev, fmode_t mode,
1689 unsigned int cmd, unsigned long arg)
1691 struct loop_device *lo = bdev->bd_disk->private_data;
1695 case LOOP_SET_STATUS:
1696 err = loop_set_status_compat(lo,
1697 (const struct compat_loop_info __user *)arg);
1699 case LOOP_GET_STATUS:
1700 err = loop_get_status_compat(lo,
1701 (struct compat_loop_info __user *)arg);
1703 case LOOP_SET_CAPACITY:
1705 case LOOP_GET_STATUS64:
1706 case LOOP_SET_STATUS64:
1707 case LOOP_CONFIGURE:
1708 arg = (unsigned long) compat_ptr(arg);
1711 case LOOP_CHANGE_FD:
1712 case LOOP_SET_BLOCK_SIZE:
1713 case LOOP_SET_DIRECT_IO:
1714 err = lo_ioctl(bdev, mode, cmd, arg);
1724 static int lo_open(struct block_device *bdev, fmode_t mode)
1726 struct loop_device *lo = bdev->bd_disk->private_data;
1729 err = mutex_lock_killable(&lo->lo_mutex);
1732 if (lo->lo_state == Lo_deleting)
1735 atomic_inc(&lo->lo_refcnt);
1736 mutex_unlock(&lo->lo_mutex);
1740 static void lo_release(struct gendisk *disk, fmode_t mode)
1742 struct loop_device *lo = disk->private_data;
1744 mutex_lock(&lo->lo_mutex);
1745 if (atomic_dec_return(&lo->lo_refcnt))
1748 if (lo->lo_flags & LO_FLAGS_AUTOCLEAR) {
1749 if (lo->lo_state != Lo_bound)
1751 lo->lo_state = Lo_rundown;
1752 mutex_unlock(&lo->lo_mutex);
1754 * In autoclear mode, stop the loop thread
1755 * and remove configuration after last close.
1757 loop_schedule_rundown(lo);
1759 } else if (lo->lo_state == Lo_bound) {
1761 * Otherwise keep thread (if running) and config,
1762 * but flush possible ongoing bios in thread.
1764 blk_mq_freeze_queue(lo->lo_queue);
1765 blk_mq_unfreeze_queue(lo->lo_queue);
1769 mutex_unlock(&lo->lo_mutex);
1772 static const struct block_device_operations lo_fops = {
1773 .owner = THIS_MODULE,
1775 .release = lo_release,
1777 #ifdef CONFIG_COMPAT
1778 .compat_ioctl = lo_compat_ioctl,
1783 * And now the modules code and kernel interface.
1785 static int max_loop;
1786 module_param(max_loop, int, 0444);
1787 MODULE_PARM_DESC(max_loop, "Maximum number of loop devices");
1788 module_param(max_part, int, 0444);
1789 MODULE_PARM_DESC(max_part, "Maximum number of partitions per loop device");
1790 MODULE_LICENSE("GPL");
1791 MODULE_ALIAS_BLOCKDEV_MAJOR(LOOP_MAJOR);
1793 static blk_status_t loop_queue_rq(struct blk_mq_hw_ctx *hctx,
1794 const struct blk_mq_queue_data *bd)
1796 struct request *rq = bd->rq;
1797 struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
1798 struct loop_device *lo = rq->q->queuedata;
1800 blk_mq_start_request(rq);
1802 if (lo->lo_state != Lo_bound)
1803 return BLK_STS_IOERR;
1805 switch (req_op(rq)) {
1807 case REQ_OP_DISCARD:
1808 case REQ_OP_WRITE_ZEROES:
1809 cmd->use_aio = false;
1812 cmd->use_aio = lo->use_dio;
1816 /* always use the first bio's css */
1817 cmd->blkcg_css = NULL;
1818 cmd->memcg_css = NULL;
1819 #ifdef CONFIG_BLK_CGROUP
1820 if (rq->bio && rq->bio->bi_blkg) {
1821 cmd->blkcg_css = &bio_blkcg(rq->bio)->css;
1824 cgroup_get_e_css(cmd->blkcg_css->cgroup,
1825 &memory_cgrp_subsys);
1829 loop_queue_work(lo, cmd);
1834 static void loop_handle_cmd(struct loop_cmd *cmd)
1836 struct request *rq = blk_mq_rq_from_pdu(cmd);
1837 const bool write = op_is_write(req_op(rq));
1838 struct loop_device *lo = rq->q->queuedata;
1840 struct mem_cgroup *old_memcg = NULL;
1842 if (write && (lo->lo_flags & LO_FLAGS_READ_ONLY)) {
1848 kthread_associate_blkcg(cmd->blkcg_css);
1850 old_memcg = set_active_memcg(
1851 mem_cgroup_from_css(cmd->memcg_css));
1853 ret = do_req_filebacked(lo, rq);
1856 kthread_associate_blkcg(NULL);
1858 if (cmd->memcg_css) {
1859 set_active_memcg(old_memcg);
1860 css_put(cmd->memcg_css);
1863 /* complete non-aio request */
1864 if (!cmd->use_aio || ret) {
1865 if (ret == -EOPNOTSUPP)
1868 cmd->ret = ret ? -EIO : 0;
1869 if (likely(!blk_should_fake_timeout(rq->q)))
1870 blk_mq_complete_request(rq);
1874 static void loop_set_timer(struct loop_device *lo)
1876 timer_reduce(&lo->timer, jiffies + LOOP_IDLE_WORKER_TIMEOUT);
1879 static void loop_process_work(struct loop_worker *worker,
1880 struct list_head *cmd_list, struct loop_device *lo)
1882 int orig_flags = current->flags;
1883 struct loop_cmd *cmd;
1885 current->flags |= PF_LOCAL_THROTTLE | PF_MEMALLOC_NOIO;
1886 spin_lock_irq(&lo->lo_work_lock);
1887 while (!list_empty(cmd_list)) {
1889 cmd_list->next, struct loop_cmd, list_entry);
1890 list_del(cmd_list->next);
1891 spin_unlock_irq(&lo->lo_work_lock);
1893 loop_handle_cmd(cmd);
1896 spin_lock_irq(&lo->lo_work_lock);
1900 * We only add to the idle list if there are no pending cmds
1901 * *and* the worker will not run again which ensures that it
1902 * is safe to free any worker on the idle list
1904 if (worker && !work_pending(&worker->work)) {
1905 worker->last_ran_at = jiffies;
1906 list_add_tail(&worker->idle_list, &lo->idle_worker_list);
1909 spin_unlock_irq(&lo->lo_work_lock);
1910 current->flags = orig_flags;
1913 static void loop_workfn(struct work_struct *work)
1915 struct loop_worker *worker =
1916 container_of(work, struct loop_worker, work);
1917 loop_process_work(worker, &worker->cmd_list, worker->lo);
1920 static void loop_rootcg_workfn(struct work_struct *work)
1922 struct loop_device *lo =
1923 container_of(work, struct loop_device, rootcg_work);
1924 loop_process_work(NULL, &lo->rootcg_cmd_list, lo);
1927 static void loop_free_idle_workers(struct timer_list *timer)
1929 struct loop_device *lo = container_of(timer, struct loop_device, timer);
1930 struct loop_worker *pos, *worker;
1932 spin_lock_irq(&lo->lo_work_lock);
1933 list_for_each_entry_safe(worker, pos, &lo->idle_worker_list,
1935 if (time_is_after_jiffies(worker->last_ran_at +
1936 LOOP_IDLE_WORKER_TIMEOUT))
1938 list_del(&worker->idle_list);
1939 rb_erase(&worker->rb_node, &lo->worker_tree);
1940 css_put(worker->blkcg_css);
1943 if (!list_empty(&lo->idle_worker_list))
1945 spin_unlock_irq(&lo->lo_work_lock);
1948 static const struct blk_mq_ops loop_mq_ops = {
1949 .queue_rq = loop_queue_rq,
1950 .complete = lo_complete_rq,
1953 static int loop_add(int i)
1955 struct loop_device *lo;
1956 struct gendisk *disk;
1960 lo = kzalloc(sizeof(*lo), GFP_KERNEL);
1963 lo->lo_state = Lo_unbound;
1965 err = mutex_lock_killable(&loop_ctl_mutex);
1969 /* allocate id, if @id >= 0, we're requesting that specific id */
1971 err = idr_alloc(&loop_index_idr, lo, i, i + 1, GFP_KERNEL);
1975 err = idr_alloc(&loop_index_idr, lo, 0, 0, GFP_KERNEL);
1977 mutex_unlock(&loop_ctl_mutex);
1982 lo->tag_set.ops = &loop_mq_ops;
1983 lo->tag_set.nr_hw_queues = 1;
1984 lo->tag_set.queue_depth = 128;
1985 lo->tag_set.numa_node = NUMA_NO_NODE;
1986 lo->tag_set.cmd_size = sizeof(struct loop_cmd);
1987 lo->tag_set.flags = BLK_MQ_F_SHOULD_MERGE | BLK_MQ_F_STACKING |
1988 BLK_MQ_F_NO_SCHED_BY_DEFAULT;
1989 lo->tag_set.driver_data = lo;
1991 err = blk_mq_alloc_tag_set(&lo->tag_set);
1995 disk = lo->lo_disk = blk_mq_alloc_disk(&lo->tag_set, lo);
1997 err = PTR_ERR(disk);
1998 goto out_cleanup_tags;
2000 lo->lo_queue = lo->lo_disk->queue;
2002 blk_queue_max_hw_sectors(lo->lo_queue, BLK_DEF_MAX_SECTORS);
2005 * By default, we do buffer IO, so it doesn't make sense to enable
2006 * merge because the I/O submitted to backing file is handled page by
2007 * page. For directio mode, merge does help to dispatch bigger request
2008 * to underlayer disk. We will enable merge once directio is enabled.
2010 blk_queue_flag_set(QUEUE_FLAG_NOMERGES, lo->lo_queue);
2013 * Disable partition scanning by default. The in-kernel partition
2014 * scanning can be requested individually per-device during its
2015 * setup. Userspace can always add and remove partitions from all
2016 * devices. The needed partition minors are allocated from the
2017 * extended minor space, the main loop device numbers will continue
2018 * to match the loop minors, regardless of the number of partitions
2021 * If max_part is given, partition scanning is globally enabled for
2022 * all loop devices. The minors for the main loop devices will be
2023 * multiples of max_part.
2025 * Note: Global-for-all-devices, set-only-at-init, read-only module
2026 * parameteters like 'max_loop' and 'max_part' make things needlessly
2027 * complicated, are too static, inflexible and may surprise
2028 * userspace tools. Parameters like this in general should be avoided.
2031 disk->flags |= GENHD_FL_NO_PART;
2032 atomic_set(&lo->lo_refcnt, 0);
2033 mutex_init(&lo->lo_mutex);
2035 spin_lock_init(&lo->lo_lock);
2036 spin_lock_init(&lo->lo_work_lock);
2037 disk->major = LOOP_MAJOR;
2038 disk->first_minor = i << part_shift;
2039 disk->minors = 1 << part_shift;
2040 disk->fops = &lo_fops;
2041 disk->private_data = lo;
2042 disk->queue = lo->lo_queue;
2043 disk->events = DISK_EVENT_MEDIA_CHANGE;
2044 disk->event_flags = DISK_EVENT_FLAG_UEVENT;
2045 sprintf(disk->disk_name, "loop%d", i);
2046 /* Make this loop device reachable from pathname. */
2047 err = add_disk(disk);
2049 goto out_cleanup_disk;
2051 /* Show this loop device. */
2052 mutex_lock(&loop_ctl_mutex);
2053 lo->idr_visible = true;
2054 mutex_unlock(&loop_ctl_mutex);
2059 blk_cleanup_disk(disk);
2061 blk_mq_free_tag_set(&lo->tag_set);
2063 mutex_lock(&loop_ctl_mutex);
2064 idr_remove(&loop_index_idr, i);
2065 mutex_unlock(&loop_ctl_mutex);
2072 static void loop_remove(struct loop_device *lo)
2074 /* Make this loop device unreachable from pathname. */
2075 del_gendisk(lo->lo_disk);
2076 blk_cleanup_disk(lo->lo_disk);
2077 blk_mq_free_tag_set(&lo->tag_set);
2078 mutex_lock(&loop_ctl_mutex);
2079 idr_remove(&loop_index_idr, lo->lo_number);
2080 mutex_unlock(&loop_ctl_mutex);
2081 /* There is no route which can find this loop device. */
2082 mutex_destroy(&lo->lo_mutex);
2086 static void loop_probe(dev_t dev)
2088 int idx = MINOR(dev) >> part_shift;
2090 if (max_loop && idx >= max_loop)
2095 static int loop_control_remove(int idx)
2097 struct loop_device *lo;
2101 pr_warn_once("deleting an unspecified loop device is not supported.\n");
2105 /* Hide this loop device for serialization. */
2106 ret = mutex_lock_killable(&loop_ctl_mutex);
2109 lo = idr_find(&loop_index_idr, idx);
2110 if (!lo || !lo->idr_visible)
2113 lo->idr_visible = false;
2114 mutex_unlock(&loop_ctl_mutex);
2118 /* Check whether this loop device can be removed. */
2119 ret = mutex_lock_killable(&lo->lo_mutex);
2122 if (lo->lo_state != Lo_unbound ||
2123 atomic_read(&lo->lo_refcnt) > 0) {
2124 mutex_unlock(&lo->lo_mutex);
2128 /* Mark this loop device no longer open()-able. */
2129 lo->lo_state = Lo_deleting;
2130 mutex_unlock(&lo->lo_mutex);
2136 /* Show this loop device again. */
2137 mutex_lock(&loop_ctl_mutex);
2138 lo->idr_visible = true;
2139 mutex_unlock(&loop_ctl_mutex);
2143 static int loop_control_get_free(int idx)
2145 struct loop_device *lo;
2148 ret = mutex_lock_killable(&loop_ctl_mutex);
2151 idr_for_each_entry(&loop_index_idr, lo, id) {
2152 /* Hitting a race results in creating a new loop device which is harmless. */
2153 if (lo->idr_visible && data_race(lo->lo_state) == Lo_unbound)
2156 mutex_unlock(&loop_ctl_mutex);
2157 return loop_add(-1);
2159 mutex_unlock(&loop_ctl_mutex);
2163 static long loop_control_ioctl(struct file *file, unsigned int cmd,
2168 return loop_add(parm);
2169 case LOOP_CTL_REMOVE:
2170 return loop_control_remove(parm);
2171 case LOOP_CTL_GET_FREE:
2172 return loop_control_get_free(parm);
2178 static const struct file_operations loop_ctl_fops = {
2179 .open = nonseekable_open,
2180 .unlocked_ioctl = loop_control_ioctl,
2181 .compat_ioctl = loop_control_ioctl,
2182 .owner = THIS_MODULE,
2183 .llseek = noop_llseek,
2186 static struct miscdevice loop_misc = {
2187 .minor = LOOP_CTRL_MINOR,
2188 .name = "loop-control",
2189 .fops = &loop_ctl_fops,
2192 MODULE_ALIAS_MISCDEV(LOOP_CTRL_MINOR);
2193 MODULE_ALIAS("devname:loop-control");
2195 static int __init loop_init(void)
2202 part_shift = fls(max_part);
2205 * Adjust max_part according to part_shift as it is exported
2206 * to user space so that user can decide correct minor number
2207 * if [s]he want to create more devices.
2209 * Note that -1 is required because partition 0 is reserved
2210 * for the whole disk.
2212 max_part = (1UL << part_shift) - 1;
2215 if ((1UL << part_shift) > DISK_MAX_PARTS) {
2220 if (max_loop > 1UL << (MINORBITS - part_shift)) {
2226 * If max_loop is specified, create that many devices upfront.
2227 * This also becomes a hard limit. If max_loop is not specified,
2228 * create CONFIG_BLK_DEV_LOOP_MIN_COUNT loop devices at module
2229 * init time. Loop devices can be requested on-demand with the
2230 * /dev/loop-control interface, or be instantiated by accessing
2231 * a 'dead' device node.
2236 nr = CONFIG_BLK_DEV_LOOP_MIN_COUNT;
2238 err = misc_register(&loop_misc);
2243 if (__register_blkdev(LOOP_MAJOR, "loop", loop_probe)) {
2248 /* pre-create number of devices given by config or max_loop */
2249 for (i = 0; i < nr; i++)
2252 printk(KERN_INFO "loop: module loaded\n");
2256 misc_deregister(&loop_misc);
2261 static void __exit loop_exit(void)
2263 struct loop_device *lo;
2266 unregister_blkdev(LOOP_MAJOR, "loop");
2267 misc_deregister(&loop_misc);
2270 * There is no need to use loop_ctl_mutex here, for nobody else can
2271 * access loop_index_idr when this module is unloading (unless forced
2272 * module unloading is requested). If this is not a clean unloading,
2273 * we have no means to avoid kernel crash.
2275 idr_for_each_entry(&loop_index_idr, lo, id)
2278 idr_destroy(&loop_index_idr);
2281 module_init(loop_init);
2282 module_exit(loop_exit);
2285 static int __init max_loop_setup(char *str)
2287 max_loop = simple_strtol(str, NULL, 0);
2291 __setup("max_loop=", max_loop_setup);