1 // SPDX-License-Identifier: GPL-2.0-only
3 * Copyright 1993 by Theodore Ts'o.
5 #include <linux/module.h>
6 #include <linux/moduleparam.h>
7 #include <linux/sched.h>
9 #include <linux/pagemap.h>
10 #include <linux/file.h>
11 #include <linux/stat.h>
12 #include <linux/errno.h>
13 #include <linux/major.h>
14 #include <linux/wait.h>
15 #include <linux/blkpg.h>
16 #include <linux/init.h>
17 #include <linux/swap.h>
18 #include <linux/slab.h>
19 #include <linux/compat.h>
20 #include <linux/suspend.h>
21 #include <linux/freezer.h>
22 #include <linux/mutex.h>
23 #include <linux/writeback.h>
24 #include <linux/completion.h>
25 #include <linux/highmem.h>
26 #include <linux/splice.h>
27 #include <linux/sysfs.h>
28 #include <linux/miscdevice.h>
29 #include <linux/falloc.h>
30 #include <linux/uio.h>
31 #include <linux/ioprio.h>
32 #include <linux/blk-cgroup.h>
33 #include <linux/sched/mm.h>
34 #include <linux/statfs.h>
35 #include <linux/uaccess.h>
36 #include <linux/blk-mq.h>
37 #include <linux/spinlock.h>
38 #include <uapi/linux/loop.h>
40 /* Possible states of device */
48 struct loop_func_table;
55 char lo_file_name[LO_NAME_SIZE];
57 struct file * lo_backing_file;
58 struct block_device *lo_device;
64 spinlock_t lo_work_lock;
65 struct workqueue_struct *workqueue;
66 struct work_struct rootcg_work;
67 struct list_head rootcg_cmd_list;
68 struct list_head idle_worker_list;
69 struct rb_root worker_tree;
70 struct timer_list timer;
74 struct request_queue *lo_queue;
75 struct blk_mq_tag_set tag_set;
76 struct gendisk *lo_disk;
77 struct mutex lo_mutex;
82 struct list_head list_entry;
83 bool use_aio; /* use AIO interface to handle I/O */
84 atomic_t ref; /* only for aio */
88 struct cgroup_subsys_state *blkcg_css;
89 struct cgroup_subsys_state *memcg_css;
92 #define LOOP_IDLE_WORKER_TIMEOUT (60 * HZ)
93 #define LOOP_DEFAULT_HW_Q_DEPTH 128
95 static DEFINE_IDR(loop_index_idr);
96 static DEFINE_MUTEX(loop_ctl_mutex);
97 static DEFINE_MUTEX(loop_validate_mutex);
100 * loop_global_lock_killable() - take locks for safe loop_validate_file() test
102 * @lo: struct loop_device
103 * @global: true if @lo is about to bind another "struct loop_device", false otherwise
105 * Returns 0 on success, -EINTR otherwise.
107 * Since loop_validate_file() traverses on other "struct loop_device" if
108 * is_loop_device() is true, we need a global lock for serializing concurrent
109 * loop_configure()/loop_change_fd()/__loop_clr_fd() calls.
111 static int loop_global_lock_killable(struct loop_device *lo, bool global)
116 err = mutex_lock_killable(&loop_validate_mutex);
120 err = mutex_lock_killable(&lo->lo_mutex);
122 mutex_unlock(&loop_validate_mutex);
127 * loop_global_unlock() - release locks taken by loop_global_lock_killable()
129 * @lo: struct loop_device
130 * @global: true if @lo was about to bind another "struct loop_device", false otherwise
132 static void loop_global_unlock(struct loop_device *lo, bool global)
134 mutex_unlock(&lo->lo_mutex);
136 mutex_unlock(&loop_validate_mutex);
140 static int part_shift;
142 static loff_t get_size(loff_t offset, loff_t sizelimit, struct file *file)
146 /* Compute loopsize in bytes */
147 loopsize = i_size_read(file->f_mapping->host);
150 /* offset is beyond i_size, weird but possible */
154 if (sizelimit > 0 && sizelimit < loopsize)
155 loopsize = sizelimit;
157 * Unfortunately, if we want to do I/O on the device,
158 * the number of 512-byte sectors has to fit into a sector_t.
160 return loopsize >> 9;
163 static loff_t get_loop_size(struct loop_device *lo, struct file *file)
165 return get_size(lo->lo_offset, lo->lo_sizelimit, file);
168 static void __loop_update_dio(struct loop_device *lo, bool dio)
170 struct file *file = lo->lo_backing_file;
171 struct address_space *mapping = file->f_mapping;
172 struct inode *inode = mapping->host;
173 unsigned short sb_bsize = 0;
174 unsigned dio_align = 0;
177 if (inode->i_sb->s_bdev) {
178 sb_bsize = bdev_logical_block_size(inode->i_sb->s_bdev);
179 dio_align = sb_bsize - 1;
183 * We support direct I/O only if lo_offset is aligned with the
184 * logical I/O size of backing device, and the logical block
185 * size of loop is bigger than the backing device's.
187 * TODO: the above condition may be loosed in the future, and
188 * direct I/O may be switched runtime at that time because most
189 * of requests in sane applications should be PAGE_SIZE aligned
192 if (queue_logical_block_size(lo->lo_queue) >= sb_bsize &&
193 !(lo->lo_offset & dio_align) &&
194 (file->f_mode & FMODE_CAN_ODIRECT))
202 if (lo->use_dio == use_dio)
205 /* flush dirty pages before changing direct IO */
209 * The flag of LO_FLAGS_DIRECT_IO is handled similarly with
210 * LO_FLAGS_READ_ONLY, both are set from kernel, and losetup
211 * will get updated by ioctl(LOOP_GET_STATUS)
213 if (lo->lo_state == Lo_bound)
214 blk_mq_freeze_queue(lo->lo_queue);
215 lo->use_dio = use_dio;
217 blk_queue_flag_clear(QUEUE_FLAG_NOMERGES, lo->lo_queue);
218 lo->lo_flags |= LO_FLAGS_DIRECT_IO;
220 blk_queue_flag_set(QUEUE_FLAG_NOMERGES, lo->lo_queue);
221 lo->lo_flags &= ~LO_FLAGS_DIRECT_IO;
223 if (lo->lo_state == Lo_bound)
224 blk_mq_unfreeze_queue(lo->lo_queue);
228 * loop_set_size() - sets device size and notifies userspace
229 * @lo: struct loop_device to set the size for
230 * @size: new size of the loop device
232 * Callers must validate that the size passed into this function fits into
233 * a sector_t, eg using loop_validate_size()
235 static void loop_set_size(struct loop_device *lo, loff_t size)
237 if (!set_capacity_and_notify(lo->lo_disk, size))
238 kobject_uevent(&disk_to_dev(lo->lo_disk)->kobj, KOBJ_CHANGE);
241 static int lo_write_bvec(struct file *file, struct bio_vec *bvec, loff_t *ppos)
246 iov_iter_bvec(&i, ITER_SOURCE, bvec, 1, bvec->bv_len);
248 bw = vfs_iter_write(file, &i, ppos, 0);
250 if (likely(bw == bvec->bv_len))
253 printk_ratelimited(KERN_ERR
254 "loop: Write error at byte offset %llu, length %i.\n",
255 (unsigned long long)*ppos, bvec->bv_len);
261 static int lo_write_simple(struct loop_device *lo, struct request *rq,
265 struct req_iterator iter;
268 rq_for_each_segment(bvec, rq, iter) {
269 ret = lo_write_bvec(lo->lo_backing_file, &bvec, &pos);
278 static int lo_read_simple(struct loop_device *lo, struct request *rq,
282 struct req_iterator iter;
286 rq_for_each_segment(bvec, rq, iter) {
287 iov_iter_bvec(&i, ITER_DEST, &bvec, 1, bvec.bv_len);
288 len = vfs_iter_read(lo->lo_backing_file, &i, &pos, 0);
292 flush_dcache_page(bvec.bv_page);
294 if (len != bvec.bv_len) {
297 __rq_for_each_bio(bio, rq)
307 static int lo_fallocate(struct loop_device *lo, struct request *rq, loff_t pos,
311 * We use fallocate to manipulate the space mappings used by the image
312 * a.k.a. discard/zerorange.
314 struct file *file = lo->lo_backing_file;
317 mode |= FALLOC_FL_KEEP_SIZE;
319 if (!bdev_max_discard_sectors(lo->lo_device))
322 ret = file->f_op->fallocate(file, mode, pos, blk_rq_bytes(rq));
323 if (unlikely(ret && ret != -EINVAL && ret != -EOPNOTSUPP))
328 static int lo_req_flush(struct loop_device *lo, struct request *rq)
330 int ret = vfs_fsync(lo->lo_backing_file, 0);
331 if (unlikely(ret && ret != -EINVAL))
337 static void lo_complete_rq(struct request *rq)
339 struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
340 blk_status_t ret = BLK_STS_OK;
342 if (!cmd->use_aio || cmd->ret < 0 || cmd->ret == blk_rq_bytes(rq) ||
343 req_op(rq) != REQ_OP_READ) {
345 ret = errno_to_blk_status(cmd->ret);
350 * Short READ - if we got some data, advance our request and
351 * retry it. If we got no data, end the rest with EIO.
354 blk_update_request(rq, BLK_STS_OK, cmd->ret);
356 blk_mq_requeue_request(rq, true);
359 struct bio *bio = rq->bio;
368 blk_mq_end_request(rq, ret);
372 static void lo_rw_aio_do_completion(struct loop_cmd *cmd)
374 struct request *rq = blk_mq_rq_from_pdu(cmd);
376 if (!atomic_dec_and_test(&cmd->ref))
380 if (likely(!blk_should_fake_timeout(rq->q)))
381 blk_mq_complete_request(rq);
384 static void lo_rw_aio_complete(struct kiocb *iocb, long ret)
386 struct loop_cmd *cmd = container_of(iocb, struct loop_cmd, iocb);
389 lo_rw_aio_do_completion(cmd);
392 static int lo_rw_aio(struct loop_device *lo, struct loop_cmd *cmd,
395 struct iov_iter iter;
396 struct req_iterator rq_iter;
397 struct bio_vec *bvec;
398 struct request *rq = blk_mq_rq_from_pdu(cmd);
399 struct bio *bio = rq->bio;
400 struct file *file = lo->lo_backing_file;
406 rq_for_each_bvec(tmp, rq, rq_iter)
409 if (rq->bio != rq->biotail) {
411 bvec = kmalloc_array(nr_bvec, sizeof(struct bio_vec),
418 * The bios of the request may be started from the middle of
419 * the 'bvec' because of bio splitting, so we can't directly
420 * copy bio->bi_iov_vec to new bvec. The rq_for_each_bvec
421 * API will take care of all details for us.
423 rq_for_each_bvec(tmp, rq, rq_iter) {
431 * Same here, this bio may be started from the middle of the
432 * 'bvec' because of bio splitting, so offset from the bvec
433 * must be passed to iov iterator
435 offset = bio->bi_iter.bi_bvec_done;
436 bvec = __bvec_iter_bvec(bio->bi_io_vec, bio->bi_iter);
438 atomic_set(&cmd->ref, 2);
440 iov_iter_bvec(&iter, rw, bvec, nr_bvec, blk_rq_bytes(rq));
441 iter.iov_offset = offset;
443 cmd->iocb.ki_pos = pos;
444 cmd->iocb.ki_filp = file;
445 cmd->iocb.ki_complete = lo_rw_aio_complete;
446 cmd->iocb.ki_flags = IOCB_DIRECT;
447 cmd->iocb.ki_ioprio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_NONE, 0);
449 if (rw == ITER_SOURCE)
450 ret = call_write_iter(file, &cmd->iocb, &iter);
452 ret = call_read_iter(file, &cmd->iocb, &iter);
454 lo_rw_aio_do_completion(cmd);
456 if (ret != -EIOCBQUEUED)
457 lo_rw_aio_complete(&cmd->iocb, ret);
461 static int do_req_filebacked(struct loop_device *lo, struct request *rq)
463 struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
464 loff_t pos = ((loff_t) blk_rq_pos(rq) << 9) + lo->lo_offset;
467 * lo_write_simple and lo_read_simple should have been covered
468 * by io submit style function like lo_rw_aio(), one blocker
469 * is that lo_read_simple() need to call flush_dcache_page after
470 * the page is written from kernel, and it isn't easy to handle
471 * this in io submit style function which submits all segments
472 * of the req at one time. And direct read IO doesn't need to
473 * run flush_dcache_page().
475 switch (req_op(rq)) {
477 return lo_req_flush(lo, rq);
478 case REQ_OP_WRITE_ZEROES:
480 * If the caller doesn't want deallocation, call zeroout to
481 * write zeroes the range. Otherwise, punch them out.
483 return lo_fallocate(lo, rq, pos,
484 (rq->cmd_flags & REQ_NOUNMAP) ?
485 FALLOC_FL_ZERO_RANGE :
486 FALLOC_FL_PUNCH_HOLE);
488 return lo_fallocate(lo, rq, pos, FALLOC_FL_PUNCH_HOLE);
491 return lo_rw_aio(lo, cmd, pos, ITER_SOURCE);
493 return lo_write_simple(lo, rq, pos);
496 return lo_rw_aio(lo, cmd, pos, ITER_DEST);
498 return lo_read_simple(lo, rq, pos);
505 static inline void loop_update_dio(struct loop_device *lo)
507 __loop_update_dio(lo, (lo->lo_backing_file->f_flags & O_DIRECT) |
511 static void loop_reread_partitions(struct loop_device *lo)
515 mutex_lock(&lo->lo_disk->open_mutex);
516 rc = bdev_disk_changed(lo->lo_disk, false);
517 mutex_unlock(&lo->lo_disk->open_mutex);
519 pr_warn("%s: partition scan of loop%d (%s) failed (rc=%d)\n",
520 __func__, lo->lo_number, lo->lo_file_name, rc);
523 static inline int is_loop_device(struct file *file)
525 struct inode *i = file->f_mapping->host;
527 return i && S_ISBLK(i->i_mode) && imajor(i) == LOOP_MAJOR;
530 static int loop_validate_file(struct file *file, struct block_device *bdev)
532 struct inode *inode = file->f_mapping->host;
533 struct file *f = file;
535 /* Avoid recursion */
536 while (is_loop_device(f)) {
537 struct loop_device *l;
539 lockdep_assert_held(&loop_validate_mutex);
540 if (f->f_mapping->host->i_rdev == bdev->bd_dev)
543 l = I_BDEV(f->f_mapping->host)->bd_disk->private_data;
544 if (l->lo_state != Lo_bound)
546 /* Order wrt setting lo->lo_backing_file in loop_configure(). */
548 f = l->lo_backing_file;
550 if (!S_ISREG(inode->i_mode) && !S_ISBLK(inode->i_mode))
556 * loop_change_fd switched the backing store of a loopback device to
557 * a new file. This is useful for operating system installers to free up
558 * the original file and in High Availability environments to switch to
559 * an alternative location for the content in case of server meltdown.
560 * This can only work if the loop device is used read-only, and if the
561 * new backing store is the same size and type as the old backing store.
563 static int loop_change_fd(struct loop_device *lo, struct block_device *bdev,
566 struct file *file = fget(arg);
567 struct file *old_file;
575 /* suppress uevents while reconfiguring the device */
576 dev_set_uevent_suppress(disk_to_dev(lo->lo_disk), 1);
578 is_loop = is_loop_device(file);
579 error = loop_global_lock_killable(lo, is_loop);
583 if (lo->lo_state != Lo_bound)
586 /* the loop device has to be read-only */
588 if (!(lo->lo_flags & LO_FLAGS_READ_ONLY))
591 error = loop_validate_file(file, bdev);
595 old_file = lo->lo_backing_file;
599 /* size of the new backing store needs to be the same */
600 if (get_loop_size(lo, file) != get_loop_size(lo, old_file))
604 disk_force_media_change(lo->lo_disk);
605 blk_mq_freeze_queue(lo->lo_queue);
606 mapping_set_gfp_mask(old_file->f_mapping, lo->old_gfp_mask);
607 lo->lo_backing_file = file;
608 lo->old_gfp_mask = mapping_gfp_mask(file->f_mapping);
609 mapping_set_gfp_mask(file->f_mapping,
610 lo->old_gfp_mask & ~(__GFP_IO|__GFP_FS));
612 blk_mq_unfreeze_queue(lo->lo_queue);
613 partscan = lo->lo_flags & LO_FLAGS_PARTSCAN;
614 loop_global_unlock(lo, is_loop);
617 * Flush loop_validate_file() before fput(), for l->lo_backing_file
618 * might be pointing at old_file which might be the last reference.
621 mutex_lock(&loop_validate_mutex);
622 mutex_unlock(&loop_validate_mutex);
625 * We must drop file reference outside of lo_mutex as dropping
626 * the file ref can take open_mutex which creates circular locking
631 loop_reread_partitions(lo);
635 /* enable and uncork uevent now that we are done */
636 dev_set_uevent_suppress(disk_to_dev(lo->lo_disk), 0);
640 loop_global_unlock(lo, is_loop);
646 /* loop sysfs attributes */
648 static ssize_t loop_attr_show(struct device *dev, char *page,
649 ssize_t (*callback)(struct loop_device *, char *))
651 struct gendisk *disk = dev_to_disk(dev);
652 struct loop_device *lo = disk->private_data;
654 return callback(lo, page);
657 #define LOOP_ATTR_RO(_name) \
658 static ssize_t loop_attr_##_name##_show(struct loop_device *, char *); \
659 static ssize_t loop_attr_do_show_##_name(struct device *d, \
660 struct device_attribute *attr, char *b) \
662 return loop_attr_show(d, b, loop_attr_##_name##_show); \
664 static struct device_attribute loop_attr_##_name = \
665 __ATTR(_name, 0444, loop_attr_do_show_##_name, NULL);
667 static ssize_t loop_attr_backing_file_show(struct loop_device *lo, char *buf)
672 spin_lock_irq(&lo->lo_lock);
673 if (lo->lo_backing_file)
674 p = file_path(lo->lo_backing_file, buf, PAGE_SIZE - 1);
675 spin_unlock_irq(&lo->lo_lock);
677 if (IS_ERR_OR_NULL(p))
681 memmove(buf, p, ret);
689 static ssize_t loop_attr_offset_show(struct loop_device *lo, char *buf)
691 return sysfs_emit(buf, "%llu\n", (unsigned long long)lo->lo_offset);
694 static ssize_t loop_attr_sizelimit_show(struct loop_device *lo, char *buf)
696 return sysfs_emit(buf, "%llu\n", (unsigned long long)lo->lo_sizelimit);
699 static ssize_t loop_attr_autoclear_show(struct loop_device *lo, char *buf)
701 int autoclear = (lo->lo_flags & LO_FLAGS_AUTOCLEAR);
703 return sysfs_emit(buf, "%s\n", autoclear ? "1" : "0");
706 static ssize_t loop_attr_partscan_show(struct loop_device *lo, char *buf)
708 int partscan = (lo->lo_flags & LO_FLAGS_PARTSCAN);
710 return sysfs_emit(buf, "%s\n", partscan ? "1" : "0");
713 static ssize_t loop_attr_dio_show(struct loop_device *lo, char *buf)
715 int dio = (lo->lo_flags & LO_FLAGS_DIRECT_IO);
717 return sysfs_emit(buf, "%s\n", dio ? "1" : "0");
720 LOOP_ATTR_RO(backing_file);
721 LOOP_ATTR_RO(offset);
722 LOOP_ATTR_RO(sizelimit);
723 LOOP_ATTR_RO(autoclear);
724 LOOP_ATTR_RO(partscan);
727 static struct attribute *loop_attrs[] = {
728 &loop_attr_backing_file.attr,
729 &loop_attr_offset.attr,
730 &loop_attr_sizelimit.attr,
731 &loop_attr_autoclear.attr,
732 &loop_attr_partscan.attr,
737 static struct attribute_group loop_attribute_group = {
742 static void loop_sysfs_init(struct loop_device *lo)
744 lo->sysfs_inited = !sysfs_create_group(&disk_to_dev(lo->lo_disk)->kobj,
745 &loop_attribute_group);
748 static void loop_sysfs_exit(struct loop_device *lo)
750 if (lo->sysfs_inited)
751 sysfs_remove_group(&disk_to_dev(lo->lo_disk)->kobj,
752 &loop_attribute_group);
755 static void loop_config_discard(struct loop_device *lo)
757 struct file *file = lo->lo_backing_file;
758 struct inode *inode = file->f_mapping->host;
759 struct request_queue *q = lo->lo_queue;
760 u32 granularity, max_discard_sectors;
763 * If the backing device is a block device, mirror its zeroing
764 * capability. Set the discard sectors to the block device's zeroing
765 * capabilities because loop discards result in blkdev_issue_zeroout(),
766 * not blkdev_issue_discard(). This maintains consistent behavior with
767 * file-backed loop devices: discarded regions read back as zero.
769 if (S_ISBLK(inode->i_mode)) {
770 struct request_queue *backingq = bdev_get_queue(I_BDEV(inode));
772 max_discard_sectors = backingq->limits.max_write_zeroes_sectors;
773 granularity = bdev_discard_granularity(I_BDEV(inode)) ?:
774 queue_physical_block_size(backingq);
777 * We use punch hole to reclaim the free space used by the
778 * image a.k.a. discard.
780 } else if (!file->f_op->fallocate) {
781 max_discard_sectors = 0;
787 max_discard_sectors = UINT_MAX >> 9;
788 if (!vfs_statfs(&file->f_path, &sbuf))
789 granularity = sbuf.f_bsize;
791 max_discard_sectors = 0;
794 if (max_discard_sectors) {
795 q->limits.discard_granularity = granularity;
796 blk_queue_max_discard_sectors(q, max_discard_sectors);
797 blk_queue_max_write_zeroes_sectors(q, max_discard_sectors);
799 q->limits.discard_granularity = 0;
800 blk_queue_max_discard_sectors(q, 0);
801 blk_queue_max_write_zeroes_sectors(q, 0);
806 struct rb_node rb_node;
807 struct work_struct work;
808 struct list_head cmd_list;
809 struct list_head idle_list;
810 struct loop_device *lo;
811 struct cgroup_subsys_state *blkcg_css;
812 unsigned long last_ran_at;
815 static void loop_workfn(struct work_struct *work);
817 #ifdef CONFIG_BLK_CGROUP
818 static inline int queue_on_root_worker(struct cgroup_subsys_state *css)
820 return !css || css == blkcg_root_css;
823 static inline int queue_on_root_worker(struct cgroup_subsys_state *css)
829 static void loop_queue_work(struct loop_device *lo, struct loop_cmd *cmd)
831 struct rb_node **node, *parent = NULL;
832 struct loop_worker *cur_worker, *worker = NULL;
833 struct work_struct *work;
834 struct list_head *cmd_list;
836 spin_lock_irq(&lo->lo_work_lock);
838 if (queue_on_root_worker(cmd->blkcg_css))
841 node = &lo->worker_tree.rb_node;
845 cur_worker = container_of(*node, struct loop_worker, rb_node);
846 if (cur_worker->blkcg_css == cmd->blkcg_css) {
849 } else if ((long)cur_worker->blkcg_css < (long)cmd->blkcg_css) {
850 node = &(*node)->rb_left;
852 node = &(*node)->rb_right;
858 worker = kzalloc(sizeof(struct loop_worker), GFP_NOWAIT | __GFP_NOWARN);
860 * In the event we cannot allocate a worker, just queue on the
861 * rootcg worker and issue the I/O as the rootcg
864 cmd->blkcg_css = NULL;
866 css_put(cmd->memcg_css);
867 cmd->memcg_css = NULL;
871 worker->blkcg_css = cmd->blkcg_css;
872 css_get(worker->blkcg_css);
873 INIT_WORK(&worker->work, loop_workfn);
874 INIT_LIST_HEAD(&worker->cmd_list);
875 INIT_LIST_HEAD(&worker->idle_list);
877 rb_link_node(&worker->rb_node, parent, node);
878 rb_insert_color(&worker->rb_node, &lo->worker_tree);
882 * We need to remove from the idle list here while
883 * holding the lock so that the idle timer doesn't
886 if (!list_empty(&worker->idle_list))
887 list_del_init(&worker->idle_list);
888 work = &worker->work;
889 cmd_list = &worker->cmd_list;
891 work = &lo->rootcg_work;
892 cmd_list = &lo->rootcg_cmd_list;
894 list_add_tail(&cmd->list_entry, cmd_list);
895 queue_work(lo->workqueue, work);
896 spin_unlock_irq(&lo->lo_work_lock);
899 static void loop_set_timer(struct loop_device *lo)
901 timer_reduce(&lo->timer, jiffies + LOOP_IDLE_WORKER_TIMEOUT);
904 static void loop_free_idle_workers(struct loop_device *lo, bool delete_all)
906 struct loop_worker *pos, *worker;
908 spin_lock_irq(&lo->lo_work_lock);
909 list_for_each_entry_safe(worker, pos, &lo->idle_worker_list,
912 time_is_after_jiffies(worker->last_ran_at +
913 LOOP_IDLE_WORKER_TIMEOUT))
915 list_del(&worker->idle_list);
916 rb_erase(&worker->rb_node, &lo->worker_tree);
917 css_put(worker->blkcg_css);
920 if (!list_empty(&lo->idle_worker_list))
922 spin_unlock_irq(&lo->lo_work_lock);
925 static void loop_free_idle_workers_timer(struct timer_list *timer)
927 struct loop_device *lo = container_of(timer, struct loop_device, timer);
929 return loop_free_idle_workers(lo, false);
932 static void loop_update_rotational(struct loop_device *lo)
934 struct file *file = lo->lo_backing_file;
935 struct inode *file_inode = file->f_mapping->host;
936 struct block_device *file_bdev = file_inode->i_sb->s_bdev;
937 struct request_queue *q = lo->lo_queue;
940 /* not all filesystems (e.g. tmpfs) have a sb->s_bdev */
942 nonrot = bdev_nonrot(file_bdev);
945 blk_queue_flag_set(QUEUE_FLAG_NONROT, q);
947 blk_queue_flag_clear(QUEUE_FLAG_NONROT, q);
951 * loop_set_status_from_info - configure device from loop_info
952 * @lo: struct loop_device to configure
953 * @info: struct loop_info64 to configure the device with
955 * Configures the loop device parameters according to the passed
956 * in loop_info64 configuration.
959 loop_set_status_from_info(struct loop_device *lo,
960 const struct loop_info64 *info)
962 if ((unsigned int) info->lo_encrypt_key_size > LO_KEY_SIZE)
965 switch (info->lo_encrypt_type) {
969 pr_warn("support for the xor transformation has been removed.\n");
971 case LO_CRYPT_CRYPTOAPI:
972 pr_warn("support for cryptoloop has been removed. Use dm-crypt instead.\n");
978 /* Avoid assigning overflow values */
979 if (info->lo_offset > LLONG_MAX || info->lo_sizelimit > LLONG_MAX)
982 lo->lo_offset = info->lo_offset;
983 lo->lo_sizelimit = info->lo_sizelimit;
985 memcpy(lo->lo_file_name, info->lo_file_name, LO_NAME_SIZE);
986 lo->lo_file_name[LO_NAME_SIZE-1] = 0;
987 lo->lo_flags = info->lo_flags;
991 static int loop_configure(struct loop_device *lo, blk_mode_t mode,
992 struct block_device *bdev,
993 const struct loop_config *config)
995 struct file *file = fget(config->fd);
997 struct address_space *mapping;
1001 unsigned short bsize;
1006 is_loop = is_loop_device(file);
1008 /* This is safe, since we have a reference from open(). */
1009 __module_get(THIS_MODULE);
1012 * If we don't hold exclusive handle for the device, upgrade to it
1013 * here to avoid changing device under exclusive owner.
1015 if (!(mode & BLK_OPEN_EXCL)) {
1016 error = bd_prepare_to_claim(bdev, loop_configure, NULL);
1021 error = loop_global_lock_killable(lo, is_loop);
1026 if (lo->lo_state != Lo_unbound)
1029 error = loop_validate_file(file, bdev);
1033 mapping = file->f_mapping;
1034 inode = mapping->host;
1036 if ((config->info.lo_flags & ~LOOP_CONFIGURE_SETTABLE_FLAGS) != 0) {
1041 if (config->block_size) {
1042 error = blk_validate_block_size(config->block_size);
1047 error = loop_set_status_from_info(lo, &config->info);
1051 if (!(file->f_mode & FMODE_WRITE) || !(mode & BLK_OPEN_WRITE) ||
1052 !file->f_op->write_iter)
1053 lo->lo_flags |= LO_FLAGS_READ_ONLY;
1055 if (!lo->workqueue) {
1056 lo->workqueue = alloc_workqueue("loop%d",
1057 WQ_UNBOUND | WQ_FREEZABLE,
1059 if (!lo->workqueue) {
1065 /* suppress uevents while reconfiguring the device */
1066 dev_set_uevent_suppress(disk_to_dev(lo->lo_disk), 1);
1068 disk_force_media_change(lo->lo_disk);
1069 set_disk_ro(lo->lo_disk, (lo->lo_flags & LO_FLAGS_READ_ONLY) != 0);
1071 lo->use_dio = lo->lo_flags & LO_FLAGS_DIRECT_IO;
1072 lo->lo_device = bdev;
1073 lo->lo_backing_file = file;
1074 lo->old_gfp_mask = mapping_gfp_mask(mapping);
1075 mapping_set_gfp_mask(mapping, lo->old_gfp_mask & ~(__GFP_IO|__GFP_FS));
1077 if (!(lo->lo_flags & LO_FLAGS_READ_ONLY) && file->f_op->fsync)
1078 blk_queue_write_cache(lo->lo_queue, true, false);
1080 if (config->block_size)
1081 bsize = config->block_size;
1082 else if ((lo->lo_backing_file->f_flags & O_DIRECT) && inode->i_sb->s_bdev)
1083 /* In case of direct I/O, match underlying block size */
1084 bsize = bdev_logical_block_size(inode->i_sb->s_bdev);
1088 blk_queue_logical_block_size(lo->lo_queue, bsize);
1089 blk_queue_physical_block_size(lo->lo_queue, bsize);
1090 blk_queue_io_min(lo->lo_queue, bsize);
1092 loop_config_discard(lo);
1093 loop_update_rotational(lo);
1094 loop_update_dio(lo);
1095 loop_sysfs_init(lo);
1097 size = get_loop_size(lo, file);
1098 loop_set_size(lo, size);
1100 /* Order wrt reading lo_state in loop_validate_file(). */
1103 lo->lo_state = Lo_bound;
1105 lo->lo_flags |= LO_FLAGS_PARTSCAN;
1106 partscan = lo->lo_flags & LO_FLAGS_PARTSCAN;
1108 clear_bit(GD_SUPPRESS_PART_SCAN, &lo->lo_disk->state);
1110 /* enable and uncork uevent now that we are done */
1111 dev_set_uevent_suppress(disk_to_dev(lo->lo_disk), 0);
1113 loop_global_unlock(lo, is_loop);
1115 loop_reread_partitions(lo);
1117 if (!(mode & BLK_OPEN_EXCL))
1118 bd_abort_claiming(bdev, loop_configure);
1123 loop_global_unlock(lo, is_loop);
1125 if (!(mode & BLK_OPEN_EXCL))
1126 bd_abort_claiming(bdev, loop_configure);
1129 /* This is safe: open() is still holding a reference. */
1130 module_put(THIS_MODULE);
1134 static void __loop_clr_fd(struct loop_device *lo, bool release)
1137 gfp_t gfp = lo->old_gfp_mask;
1139 if (test_bit(QUEUE_FLAG_WC, &lo->lo_queue->queue_flags))
1140 blk_queue_write_cache(lo->lo_queue, false, false);
1143 * Freeze the request queue when unbinding on a live file descriptor and
1144 * thus an open device. When called from ->release we are guaranteed
1145 * that there is no I/O in progress already.
1148 blk_mq_freeze_queue(lo->lo_queue);
1150 spin_lock_irq(&lo->lo_lock);
1151 filp = lo->lo_backing_file;
1152 lo->lo_backing_file = NULL;
1153 spin_unlock_irq(&lo->lo_lock);
1155 lo->lo_device = NULL;
1157 lo->lo_sizelimit = 0;
1158 memset(lo->lo_file_name, 0, LO_NAME_SIZE);
1159 blk_queue_logical_block_size(lo->lo_queue, 512);
1160 blk_queue_physical_block_size(lo->lo_queue, 512);
1161 blk_queue_io_min(lo->lo_queue, 512);
1162 invalidate_disk(lo->lo_disk);
1163 loop_sysfs_exit(lo);
1164 /* let user-space know about this change */
1165 kobject_uevent(&disk_to_dev(lo->lo_disk)->kobj, KOBJ_CHANGE);
1166 mapping_set_gfp_mask(filp->f_mapping, gfp);
1167 /* This is safe: open() is still holding a reference. */
1168 module_put(THIS_MODULE);
1170 blk_mq_unfreeze_queue(lo->lo_queue);
1172 disk_force_media_change(lo->lo_disk);
1174 if (lo->lo_flags & LO_FLAGS_PARTSCAN) {
1178 * open_mutex has been held already in release path, so don't
1179 * acquire it if this function is called in such case.
1181 * If the reread partition isn't from release path, lo_refcnt
1182 * must be at least one and it can only become zero when the
1183 * current holder is released.
1186 mutex_lock(&lo->lo_disk->open_mutex);
1187 err = bdev_disk_changed(lo->lo_disk, false);
1189 mutex_unlock(&lo->lo_disk->open_mutex);
1191 pr_warn("%s: partition scan of loop%d failed (rc=%d)\n",
1192 __func__, lo->lo_number, err);
1193 /* Device is gone, no point in returning error */
1197 * lo->lo_state is set to Lo_unbound here after above partscan has
1198 * finished. There cannot be anybody else entering __loop_clr_fd() as
1199 * Lo_rundown state protects us from all the other places trying to
1200 * change the 'lo' device.
1204 set_bit(GD_SUPPRESS_PART_SCAN, &lo->lo_disk->state);
1205 mutex_lock(&lo->lo_mutex);
1206 lo->lo_state = Lo_unbound;
1207 mutex_unlock(&lo->lo_mutex);
1210 * Need not hold lo_mutex to fput backing file. Calling fput holding
1211 * lo_mutex triggers a circular lock dependency possibility warning as
1212 * fput can take open_mutex which is usually taken before lo_mutex.
1217 static int loop_clr_fd(struct loop_device *lo)
1222 * Since lo_ioctl() is called without locks held, it is possible that
1223 * loop_configure()/loop_change_fd() and loop_clr_fd() run in parallel.
1225 * Therefore, use global lock when setting Lo_rundown state in order to
1226 * make sure that loop_validate_file() will fail if the "struct file"
1227 * which loop_configure()/loop_change_fd() found via fget() was this
1230 err = loop_global_lock_killable(lo, true);
1233 if (lo->lo_state != Lo_bound) {
1234 loop_global_unlock(lo, true);
1238 * If we've explicitly asked to tear down the loop device,
1239 * and it has an elevated reference count, set it for auto-teardown when
1240 * the last reference goes away. This stops $!~#$@ udev from
1241 * preventing teardown because it decided that it needs to run blkid on
1242 * the loopback device whenever they appear. xfstests is notorious for
1243 * failing tests because blkid via udev races with a losetup
1244 * <dev>/do something like mkfs/losetup -d <dev> causing the losetup -d
1245 * command to fail with EBUSY.
1247 if (disk_openers(lo->lo_disk) > 1) {
1248 lo->lo_flags |= LO_FLAGS_AUTOCLEAR;
1249 loop_global_unlock(lo, true);
1252 lo->lo_state = Lo_rundown;
1253 loop_global_unlock(lo, true);
1255 __loop_clr_fd(lo, false);
1260 loop_set_status(struct loop_device *lo, const struct loop_info64 *info)
1264 bool partscan = false;
1265 bool size_changed = false;
1267 err = mutex_lock_killable(&lo->lo_mutex);
1270 if (lo->lo_state != Lo_bound) {
1275 if (lo->lo_offset != info->lo_offset ||
1276 lo->lo_sizelimit != info->lo_sizelimit) {
1277 size_changed = true;
1278 sync_blockdev(lo->lo_device);
1279 invalidate_bdev(lo->lo_device);
1282 /* I/O need to be drained during transfer transition */
1283 blk_mq_freeze_queue(lo->lo_queue);
1285 prev_lo_flags = lo->lo_flags;
1287 err = loop_set_status_from_info(lo, info);
1291 /* Mask out flags that can't be set using LOOP_SET_STATUS. */
1292 lo->lo_flags &= LOOP_SET_STATUS_SETTABLE_FLAGS;
1293 /* For those flags, use the previous values instead */
1294 lo->lo_flags |= prev_lo_flags & ~LOOP_SET_STATUS_SETTABLE_FLAGS;
1295 /* For flags that can't be cleared, use previous values too */
1296 lo->lo_flags |= prev_lo_flags & ~LOOP_SET_STATUS_CLEARABLE_FLAGS;
1299 loff_t new_size = get_size(lo->lo_offset, lo->lo_sizelimit,
1300 lo->lo_backing_file);
1301 loop_set_size(lo, new_size);
1304 /* update dio if lo_offset or transfer is changed */
1305 __loop_update_dio(lo, lo->use_dio);
1308 blk_mq_unfreeze_queue(lo->lo_queue);
1310 if (!err && (lo->lo_flags & LO_FLAGS_PARTSCAN) &&
1311 !(prev_lo_flags & LO_FLAGS_PARTSCAN)) {
1312 clear_bit(GD_SUPPRESS_PART_SCAN, &lo->lo_disk->state);
1316 mutex_unlock(&lo->lo_mutex);
1318 loop_reread_partitions(lo);
1324 loop_get_status(struct loop_device *lo, struct loop_info64 *info)
1330 ret = mutex_lock_killable(&lo->lo_mutex);
1333 if (lo->lo_state != Lo_bound) {
1334 mutex_unlock(&lo->lo_mutex);
1338 memset(info, 0, sizeof(*info));
1339 info->lo_number = lo->lo_number;
1340 info->lo_offset = lo->lo_offset;
1341 info->lo_sizelimit = lo->lo_sizelimit;
1342 info->lo_flags = lo->lo_flags;
1343 memcpy(info->lo_file_name, lo->lo_file_name, LO_NAME_SIZE);
1345 /* Drop lo_mutex while we call into the filesystem. */
1346 path = lo->lo_backing_file->f_path;
1348 mutex_unlock(&lo->lo_mutex);
1349 ret = vfs_getattr(&path, &stat, STATX_INO, AT_STATX_SYNC_AS_STAT);
1351 info->lo_device = huge_encode_dev(stat.dev);
1352 info->lo_inode = stat.ino;
1353 info->lo_rdevice = huge_encode_dev(stat.rdev);
1360 loop_info64_from_old(const struct loop_info *info, struct loop_info64 *info64)
1362 memset(info64, 0, sizeof(*info64));
1363 info64->lo_number = info->lo_number;
1364 info64->lo_device = info->lo_device;
1365 info64->lo_inode = info->lo_inode;
1366 info64->lo_rdevice = info->lo_rdevice;
1367 info64->lo_offset = info->lo_offset;
1368 info64->lo_sizelimit = 0;
1369 info64->lo_flags = info->lo_flags;
1370 memcpy(info64->lo_file_name, info->lo_name, LO_NAME_SIZE);
1374 loop_info64_to_old(const struct loop_info64 *info64, struct loop_info *info)
1376 memset(info, 0, sizeof(*info));
1377 info->lo_number = info64->lo_number;
1378 info->lo_device = info64->lo_device;
1379 info->lo_inode = info64->lo_inode;
1380 info->lo_rdevice = info64->lo_rdevice;
1381 info->lo_offset = info64->lo_offset;
1382 info->lo_flags = info64->lo_flags;
1383 memcpy(info->lo_name, info64->lo_file_name, LO_NAME_SIZE);
1385 /* error in case values were truncated */
1386 if (info->lo_device != info64->lo_device ||
1387 info->lo_rdevice != info64->lo_rdevice ||
1388 info->lo_inode != info64->lo_inode ||
1389 info->lo_offset != info64->lo_offset)
1396 loop_set_status_old(struct loop_device *lo, const struct loop_info __user *arg)
1398 struct loop_info info;
1399 struct loop_info64 info64;
1401 if (copy_from_user(&info, arg, sizeof (struct loop_info)))
1403 loop_info64_from_old(&info, &info64);
1404 return loop_set_status(lo, &info64);
1408 loop_set_status64(struct loop_device *lo, const struct loop_info64 __user *arg)
1410 struct loop_info64 info64;
1412 if (copy_from_user(&info64, arg, sizeof (struct loop_info64)))
1414 return loop_set_status(lo, &info64);
1418 loop_get_status_old(struct loop_device *lo, struct loop_info __user *arg) {
1419 struct loop_info info;
1420 struct loop_info64 info64;
1425 err = loop_get_status(lo, &info64);
1427 err = loop_info64_to_old(&info64, &info);
1428 if (!err && copy_to_user(arg, &info, sizeof(info)))
1435 loop_get_status64(struct loop_device *lo, struct loop_info64 __user *arg) {
1436 struct loop_info64 info64;
1441 err = loop_get_status(lo, &info64);
1442 if (!err && copy_to_user(arg, &info64, sizeof(info64)))
1448 static int loop_set_capacity(struct loop_device *lo)
1452 if (unlikely(lo->lo_state != Lo_bound))
1455 size = get_loop_size(lo, lo->lo_backing_file);
1456 loop_set_size(lo, size);
1461 static int loop_set_dio(struct loop_device *lo, unsigned long arg)
1464 if (lo->lo_state != Lo_bound)
1467 __loop_update_dio(lo, !!arg);
1468 if (lo->use_dio == !!arg)
1475 static int loop_set_block_size(struct loop_device *lo, unsigned long arg)
1479 if (lo->lo_state != Lo_bound)
1482 err = blk_validate_block_size(arg);
1486 if (lo->lo_queue->limits.logical_block_size == arg)
1489 sync_blockdev(lo->lo_device);
1490 invalidate_bdev(lo->lo_device);
1492 blk_mq_freeze_queue(lo->lo_queue);
1493 blk_queue_logical_block_size(lo->lo_queue, arg);
1494 blk_queue_physical_block_size(lo->lo_queue, arg);
1495 blk_queue_io_min(lo->lo_queue, arg);
1496 loop_update_dio(lo);
1497 blk_mq_unfreeze_queue(lo->lo_queue);
1502 static int lo_simple_ioctl(struct loop_device *lo, unsigned int cmd,
1507 err = mutex_lock_killable(&lo->lo_mutex);
1511 case LOOP_SET_CAPACITY:
1512 err = loop_set_capacity(lo);
1514 case LOOP_SET_DIRECT_IO:
1515 err = loop_set_dio(lo, arg);
1517 case LOOP_SET_BLOCK_SIZE:
1518 err = loop_set_block_size(lo, arg);
1523 mutex_unlock(&lo->lo_mutex);
1527 static int lo_ioctl(struct block_device *bdev, blk_mode_t mode,
1528 unsigned int cmd, unsigned long arg)
1530 struct loop_device *lo = bdev->bd_disk->private_data;
1531 void __user *argp = (void __user *) arg;
1537 * Legacy case - pass in a zeroed out struct loop_config with
1538 * only the file descriptor set , which corresponds with the
1539 * default parameters we'd have used otherwise.
1541 struct loop_config config;
1543 memset(&config, 0, sizeof(config));
1546 return loop_configure(lo, mode, bdev, &config);
1548 case LOOP_CONFIGURE: {
1549 struct loop_config config;
1551 if (copy_from_user(&config, argp, sizeof(config)))
1554 return loop_configure(lo, mode, bdev, &config);
1556 case LOOP_CHANGE_FD:
1557 return loop_change_fd(lo, bdev, arg);
1559 return loop_clr_fd(lo);
1560 case LOOP_SET_STATUS:
1562 if ((mode & BLK_OPEN_WRITE) || capable(CAP_SYS_ADMIN))
1563 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 & BLK_OPEN_WRITE) || capable(CAP_SYS_ADMIN))
1570 err = loop_set_status64(lo, argp);
1572 case LOOP_GET_STATUS64:
1573 return loop_get_status64(lo, argp);
1574 case LOOP_SET_CAPACITY:
1575 case LOOP_SET_DIRECT_IO:
1576 case LOOP_SET_BLOCK_SIZE:
1577 if (!(mode & BLK_OPEN_WRITE) && !capable(CAP_SYS_ADMIN))
1581 err = lo_simple_ioctl(lo, cmd, arg);
1588 #ifdef CONFIG_COMPAT
1589 struct compat_loop_info {
1590 compat_int_t lo_number; /* ioctl r/o */
1591 compat_dev_t lo_device; /* ioctl r/o */
1592 compat_ulong_t lo_inode; /* ioctl r/o */
1593 compat_dev_t lo_rdevice; /* ioctl r/o */
1594 compat_int_t lo_offset;
1595 compat_int_t lo_encrypt_type; /* obsolete, ignored */
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, blk_mode_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 void lo_release(struct gendisk *disk)
1726 struct loop_device *lo = disk->private_data;
1728 if (disk_openers(disk) > 0)
1731 mutex_lock(&lo->lo_mutex);
1732 if (lo->lo_state == Lo_bound && (lo->lo_flags & LO_FLAGS_AUTOCLEAR)) {
1733 lo->lo_state = Lo_rundown;
1734 mutex_unlock(&lo->lo_mutex);
1736 * In autoclear mode, stop the loop thread
1737 * and remove configuration after last close.
1739 __loop_clr_fd(lo, true);
1742 mutex_unlock(&lo->lo_mutex);
1745 static void lo_free_disk(struct gendisk *disk)
1747 struct loop_device *lo = disk->private_data;
1750 destroy_workqueue(lo->workqueue);
1751 loop_free_idle_workers(lo, true);
1752 timer_shutdown_sync(&lo->timer);
1753 mutex_destroy(&lo->lo_mutex);
1757 static const struct block_device_operations lo_fops = {
1758 .owner = THIS_MODULE,
1759 .release = lo_release,
1761 #ifdef CONFIG_COMPAT
1762 .compat_ioctl = lo_compat_ioctl,
1764 .free_disk = lo_free_disk,
1768 * And now the modules code and kernel interface.
1772 * If max_loop is specified, create that many devices upfront.
1773 * This also becomes a hard limit. If max_loop is not specified,
1774 * the default isn't a hard limit (as before commit 85c50197716c
1775 * changed the default value from 0 for max_loop=0 reasons), just
1776 * create CONFIG_BLK_DEV_LOOP_MIN_COUNT loop devices at module
1777 * init time. Loop devices can be requested on-demand with the
1778 * /dev/loop-control interface, or be instantiated by accessing
1779 * a 'dead' device node.
1781 static int max_loop = CONFIG_BLK_DEV_LOOP_MIN_COUNT;
1783 #ifdef CONFIG_BLOCK_LEGACY_AUTOLOAD
1784 static bool max_loop_specified;
1786 static int max_loop_param_set_int(const char *val,
1787 const struct kernel_param *kp)
1791 ret = param_set_int(val, kp);
1795 max_loop_specified = true;
1799 static const struct kernel_param_ops max_loop_param_ops = {
1800 .set = max_loop_param_set_int,
1801 .get = param_get_int,
1804 module_param_cb(max_loop, &max_loop_param_ops, &max_loop, 0444);
1805 MODULE_PARM_DESC(max_loop, "Maximum number of loop devices");
1807 module_param(max_loop, int, 0444);
1808 MODULE_PARM_DESC(max_loop, "Initial number of loop devices");
1811 module_param(max_part, int, 0444);
1812 MODULE_PARM_DESC(max_part, "Maximum number of partitions per loop device");
1814 static int hw_queue_depth = LOOP_DEFAULT_HW_Q_DEPTH;
1816 static int loop_set_hw_queue_depth(const char *s, const struct kernel_param *p)
1820 ret = kstrtoint(s, 0, &qd);
1825 hw_queue_depth = qd;
1829 static const struct kernel_param_ops loop_hw_qdepth_param_ops = {
1830 .set = loop_set_hw_queue_depth,
1831 .get = param_get_int,
1834 device_param_cb(hw_queue_depth, &loop_hw_qdepth_param_ops, &hw_queue_depth, 0444);
1835 MODULE_PARM_DESC(hw_queue_depth, "Queue depth for each hardware queue. Default: " __stringify(LOOP_DEFAULT_HW_Q_DEPTH));
1837 MODULE_LICENSE("GPL");
1838 MODULE_ALIAS_BLOCKDEV_MAJOR(LOOP_MAJOR);
1840 static blk_status_t loop_queue_rq(struct blk_mq_hw_ctx *hctx,
1841 const struct blk_mq_queue_data *bd)
1843 struct request *rq = bd->rq;
1844 struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
1845 struct loop_device *lo = rq->q->queuedata;
1847 blk_mq_start_request(rq);
1849 if (lo->lo_state != Lo_bound)
1850 return BLK_STS_IOERR;
1852 switch (req_op(rq)) {
1854 case REQ_OP_DISCARD:
1855 case REQ_OP_WRITE_ZEROES:
1856 cmd->use_aio = false;
1859 cmd->use_aio = lo->use_dio;
1863 /* always use the first bio's css */
1864 cmd->blkcg_css = NULL;
1865 cmd->memcg_css = NULL;
1866 #ifdef CONFIG_BLK_CGROUP
1868 cmd->blkcg_css = bio_blkcg_css(rq->bio);
1870 if (cmd->blkcg_css) {
1872 cgroup_get_e_css(cmd->blkcg_css->cgroup,
1873 &memory_cgrp_subsys);
1878 loop_queue_work(lo, cmd);
1883 static void loop_handle_cmd(struct loop_cmd *cmd)
1885 struct cgroup_subsys_state *cmd_blkcg_css = cmd->blkcg_css;
1886 struct cgroup_subsys_state *cmd_memcg_css = cmd->memcg_css;
1887 struct request *rq = blk_mq_rq_from_pdu(cmd);
1888 const bool write = op_is_write(req_op(rq));
1889 struct loop_device *lo = rq->q->queuedata;
1891 struct mem_cgroup *old_memcg = NULL;
1892 const bool use_aio = cmd->use_aio;
1894 if (write && (lo->lo_flags & LO_FLAGS_READ_ONLY)) {
1900 kthread_associate_blkcg(cmd_blkcg_css);
1902 old_memcg = set_active_memcg(
1903 mem_cgroup_from_css(cmd_memcg_css));
1906 * do_req_filebacked() may call blk_mq_complete_request() synchronously
1907 * or asynchronously if using aio. Hence, do not touch 'cmd' after
1908 * do_req_filebacked() has returned unless we are sure that 'cmd' has
1909 * not yet been completed.
1911 ret = do_req_filebacked(lo, rq);
1914 kthread_associate_blkcg(NULL);
1916 if (cmd_memcg_css) {
1917 set_active_memcg(old_memcg);
1918 css_put(cmd_memcg_css);
1921 /* complete non-aio request */
1922 if (!use_aio || ret) {
1923 if (ret == -EOPNOTSUPP)
1926 cmd->ret = ret ? -EIO : 0;
1927 if (likely(!blk_should_fake_timeout(rq->q)))
1928 blk_mq_complete_request(rq);
1932 static void loop_process_work(struct loop_worker *worker,
1933 struct list_head *cmd_list, struct loop_device *lo)
1935 int orig_flags = current->flags;
1936 struct loop_cmd *cmd;
1938 current->flags |= PF_LOCAL_THROTTLE | PF_MEMALLOC_NOIO;
1939 spin_lock_irq(&lo->lo_work_lock);
1940 while (!list_empty(cmd_list)) {
1942 cmd_list->next, struct loop_cmd, list_entry);
1943 list_del(cmd_list->next);
1944 spin_unlock_irq(&lo->lo_work_lock);
1946 loop_handle_cmd(cmd);
1949 spin_lock_irq(&lo->lo_work_lock);
1953 * We only add to the idle list if there are no pending cmds
1954 * *and* the worker will not run again which ensures that it
1955 * is safe to free any worker on the idle list
1957 if (worker && !work_pending(&worker->work)) {
1958 worker->last_ran_at = jiffies;
1959 list_add_tail(&worker->idle_list, &lo->idle_worker_list);
1962 spin_unlock_irq(&lo->lo_work_lock);
1963 current->flags = orig_flags;
1966 static void loop_workfn(struct work_struct *work)
1968 struct loop_worker *worker =
1969 container_of(work, struct loop_worker, work);
1970 loop_process_work(worker, &worker->cmd_list, worker->lo);
1973 static void loop_rootcg_workfn(struct work_struct *work)
1975 struct loop_device *lo =
1976 container_of(work, struct loop_device, rootcg_work);
1977 loop_process_work(NULL, &lo->rootcg_cmd_list, lo);
1980 static const struct blk_mq_ops loop_mq_ops = {
1981 .queue_rq = loop_queue_rq,
1982 .complete = lo_complete_rq,
1985 static int loop_add(int i)
1987 struct loop_device *lo;
1988 struct gendisk *disk;
1992 lo = kzalloc(sizeof(*lo), GFP_KERNEL);
1995 lo->worker_tree = RB_ROOT;
1996 INIT_LIST_HEAD(&lo->idle_worker_list);
1997 timer_setup(&lo->timer, loop_free_idle_workers_timer, TIMER_DEFERRABLE);
1998 lo->lo_state = Lo_unbound;
2000 err = mutex_lock_killable(&loop_ctl_mutex);
2004 /* allocate id, if @id >= 0, we're requesting that specific id */
2006 err = idr_alloc(&loop_index_idr, lo, i, i + 1, GFP_KERNEL);
2010 err = idr_alloc(&loop_index_idr, lo, 0, 0, GFP_KERNEL);
2012 mutex_unlock(&loop_ctl_mutex);
2017 lo->tag_set.ops = &loop_mq_ops;
2018 lo->tag_set.nr_hw_queues = 1;
2019 lo->tag_set.queue_depth = hw_queue_depth;
2020 lo->tag_set.numa_node = NUMA_NO_NODE;
2021 lo->tag_set.cmd_size = sizeof(struct loop_cmd);
2022 lo->tag_set.flags = BLK_MQ_F_SHOULD_MERGE | BLK_MQ_F_STACKING |
2023 BLK_MQ_F_NO_SCHED_BY_DEFAULT;
2024 lo->tag_set.driver_data = lo;
2026 err = blk_mq_alloc_tag_set(&lo->tag_set);
2030 disk = lo->lo_disk = blk_mq_alloc_disk(&lo->tag_set, lo);
2032 err = PTR_ERR(disk);
2033 goto out_cleanup_tags;
2035 lo->lo_queue = lo->lo_disk->queue;
2037 /* random number picked from the history block max_sectors cap */
2038 blk_queue_max_hw_sectors(lo->lo_queue, 2560u);
2041 * By default, we do buffer IO, so it doesn't make sense to enable
2042 * merge because the I/O submitted to backing file is handled page by
2043 * page. For directio mode, merge does help to dispatch bigger request
2044 * to underlayer disk. We will enable merge once directio is enabled.
2046 blk_queue_flag_set(QUEUE_FLAG_NOMERGES, lo->lo_queue);
2049 * Disable partition scanning by default. The in-kernel partition
2050 * scanning can be requested individually per-device during its
2051 * setup. Userspace can always add and remove partitions from all
2052 * devices. The needed partition minors are allocated from the
2053 * extended minor space, the main loop device numbers will continue
2054 * to match the loop minors, regardless of the number of partitions
2057 * If max_part is given, partition scanning is globally enabled for
2058 * all loop devices. The minors for the main loop devices will be
2059 * multiples of max_part.
2061 * Note: Global-for-all-devices, set-only-at-init, read-only module
2062 * parameteters like 'max_loop' and 'max_part' make things needlessly
2063 * complicated, are too static, inflexible and may surprise
2064 * userspace tools. Parameters like this in general should be avoided.
2067 set_bit(GD_SUPPRESS_PART_SCAN, &disk->state);
2068 mutex_init(&lo->lo_mutex);
2070 spin_lock_init(&lo->lo_lock);
2071 spin_lock_init(&lo->lo_work_lock);
2072 INIT_WORK(&lo->rootcg_work, loop_rootcg_workfn);
2073 INIT_LIST_HEAD(&lo->rootcg_cmd_list);
2074 disk->major = LOOP_MAJOR;
2075 disk->first_minor = i << part_shift;
2076 disk->minors = 1 << part_shift;
2077 disk->fops = &lo_fops;
2078 disk->private_data = lo;
2079 disk->queue = lo->lo_queue;
2080 disk->events = DISK_EVENT_MEDIA_CHANGE;
2081 disk->event_flags = DISK_EVENT_FLAG_UEVENT;
2082 sprintf(disk->disk_name, "loop%d", i);
2083 /* Make this loop device reachable from pathname. */
2084 err = add_disk(disk);
2086 goto out_cleanup_disk;
2088 /* Show this loop device. */
2089 mutex_lock(&loop_ctl_mutex);
2090 lo->idr_visible = true;
2091 mutex_unlock(&loop_ctl_mutex);
2098 blk_mq_free_tag_set(&lo->tag_set);
2100 mutex_lock(&loop_ctl_mutex);
2101 idr_remove(&loop_index_idr, i);
2102 mutex_unlock(&loop_ctl_mutex);
2109 static void loop_remove(struct loop_device *lo)
2111 /* Make this loop device unreachable from pathname. */
2112 del_gendisk(lo->lo_disk);
2113 blk_mq_free_tag_set(&lo->tag_set);
2115 mutex_lock(&loop_ctl_mutex);
2116 idr_remove(&loop_index_idr, lo->lo_number);
2117 mutex_unlock(&loop_ctl_mutex);
2119 put_disk(lo->lo_disk);
2122 #ifdef CONFIG_BLOCK_LEGACY_AUTOLOAD
2123 static void loop_probe(dev_t dev)
2125 int idx = MINOR(dev) >> part_shift;
2127 if (max_loop_specified && max_loop && idx >= max_loop)
2132 #define loop_probe NULL
2133 #endif /* !CONFIG_BLOCK_LEGACY_AUTOLOAD */
2135 static int loop_control_remove(int idx)
2137 struct loop_device *lo;
2141 pr_warn_once("deleting an unspecified loop device is not supported.\n");
2145 /* Hide this loop device for serialization. */
2146 ret = mutex_lock_killable(&loop_ctl_mutex);
2149 lo = idr_find(&loop_index_idr, idx);
2150 if (!lo || !lo->idr_visible)
2153 lo->idr_visible = false;
2154 mutex_unlock(&loop_ctl_mutex);
2158 /* Check whether this loop device can be removed. */
2159 ret = mutex_lock_killable(&lo->lo_mutex);
2162 if (lo->lo_state != Lo_unbound || disk_openers(lo->lo_disk) > 0) {
2163 mutex_unlock(&lo->lo_mutex);
2167 /* Mark this loop device as no more bound, but not quite unbound yet */
2168 lo->lo_state = Lo_deleting;
2169 mutex_unlock(&lo->lo_mutex);
2175 /* Show this loop device again. */
2176 mutex_lock(&loop_ctl_mutex);
2177 lo->idr_visible = true;
2178 mutex_unlock(&loop_ctl_mutex);
2182 static int loop_control_get_free(int idx)
2184 struct loop_device *lo;
2187 ret = mutex_lock_killable(&loop_ctl_mutex);
2190 idr_for_each_entry(&loop_index_idr, lo, id) {
2191 /* Hitting a race results in creating a new loop device which is harmless. */
2192 if (lo->idr_visible && data_race(lo->lo_state) == Lo_unbound)
2195 mutex_unlock(&loop_ctl_mutex);
2196 return loop_add(-1);
2198 mutex_unlock(&loop_ctl_mutex);
2202 static long loop_control_ioctl(struct file *file, unsigned int cmd,
2207 return loop_add(parm);
2208 case LOOP_CTL_REMOVE:
2209 return loop_control_remove(parm);
2210 case LOOP_CTL_GET_FREE:
2211 return loop_control_get_free(parm);
2217 static const struct file_operations loop_ctl_fops = {
2218 .open = nonseekable_open,
2219 .unlocked_ioctl = loop_control_ioctl,
2220 .compat_ioctl = loop_control_ioctl,
2221 .owner = THIS_MODULE,
2222 .llseek = noop_llseek,
2225 static struct miscdevice loop_misc = {
2226 .minor = LOOP_CTRL_MINOR,
2227 .name = "loop-control",
2228 .fops = &loop_ctl_fops,
2231 MODULE_ALIAS_MISCDEV(LOOP_CTRL_MINOR);
2232 MODULE_ALIAS("devname:loop-control");
2234 static int __init loop_init(void)
2241 part_shift = fls(max_part);
2244 * Adjust max_part according to part_shift as it is exported
2245 * to user space so that user can decide correct minor number
2246 * if [s]he want to create more devices.
2248 * Note that -1 is required because partition 0 is reserved
2249 * for the whole disk.
2251 max_part = (1UL << part_shift) - 1;
2254 if ((1UL << part_shift) > DISK_MAX_PARTS) {
2259 if (max_loop > 1UL << (MINORBITS - part_shift)) {
2264 err = misc_register(&loop_misc);
2269 if (__register_blkdev(LOOP_MAJOR, "loop", loop_probe)) {
2274 /* pre-create number of devices given by config or max_loop */
2275 for (i = 0; i < max_loop; i++)
2278 printk(KERN_INFO "loop: module loaded\n");
2282 misc_deregister(&loop_misc);
2287 static void __exit loop_exit(void)
2289 struct loop_device *lo;
2292 unregister_blkdev(LOOP_MAJOR, "loop");
2293 misc_deregister(&loop_misc);
2296 * There is no need to use loop_ctl_mutex here, for nobody else can
2297 * access loop_index_idr when this module is unloading (unless forced
2298 * module unloading is requested). If this is not a clean unloading,
2299 * we have no means to avoid kernel crash.
2301 idr_for_each_entry(&loop_index_idr, lo, id)
2304 idr_destroy(&loop_index_idr);
2307 module_init(loop_init);
2308 module_exit(loop_exit);
2311 static int __init max_loop_setup(char *str)
2313 max_loop = simple_strtol(str, NULL, 0);
2314 #ifdef CONFIG_BLOCK_LEGACY_AUTOLOAD
2315 max_loop_specified = true;
2320 __setup("max_loop=", max_loop_setup);