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
);
169 * We support direct I/O only if lo_offset is aligned with the logical I/O size
170 * of backing device, and the logical block size of loop is bigger than that of
171 * the backing device.
173 static bool lo_bdev_can_use_dio(struct loop_device
*lo
,
174 struct block_device
*backing_bdev
)
176 unsigned short sb_bsize
= bdev_logical_block_size(backing_bdev
);
178 if (queue_logical_block_size(lo
->lo_queue
) < sb_bsize
)
180 if (lo
->lo_offset
& (sb_bsize
- 1))
185 static void __loop_update_dio(struct loop_device
*lo
, bool dio
)
187 struct file
*file
= lo
->lo_backing_file
;
188 struct inode
*inode
= file
->f_mapping
->host
;
189 struct block_device
*backing_bdev
= NULL
;
192 if (S_ISBLK(inode
->i_mode
))
193 backing_bdev
= I_BDEV(inode
);
194 else if (inode
->i_sb
->s_bdev
)
195 backing_bdev
= inode
->i_sb
->s_bdev
;
197 use_dio
= dio
&& (file
->f_mode
& FMODE_CAN_ODIRECT
) &&
198 (!backing_bdev
|| lo_bdev_can_use_dio(lo
, backing_bdev
));
200 if (lo
->use_dio
== use_dio
)
203 /* flush dirty pages before changing direct IO */
207 * The flag of LO_FLAGS_DIRECT_IO is handled similarly with
208 * LO_FLAGS_READ_ONLY, both are set from kernel, and losetup
209 * will get updated by ioctl(LOOP_GET_STATUS)
211 if (lo
->lo_state
== Lo_bound
)
212 blk_mq_freeze_queue(lo
->lo_queue
);
213 lo
->use_dio
= use_dio
;
215 blk_queue_flag_clear(QUEUE_FLAG_NOMERGES
, lo
->lo_queue
);
216 lo
->lo_flags
|= LO_FLAGS_DIRECT_IO
;
218 blk_queue_flag_set(QUEUE_FLAG_NOMERGES
, lo
->lo_queue
);
219 lo
->lo_flags
&= ~LO_FLAGS_DIRECT_IO
;
221 if (lo
->lo_state
== Lo_bound
)
222 blk_mq_unfreeze_queue(lo
->lo_queue
);
226 * loop_set_size() - sets device size and notifies userspace
227 * @lo: struct loop_device to set the size for
228 * @size: new size of the loop device
230 * Callers must validate that the size passed into this function fits into
231 * a sector_t, eg using loop_validate_size()
233 static void loop_set_size(struct loop_device
*lo
, loff_t size
)
235 if (!set_capacity_and_notify(lo
->lo_disk
, size
))
236 kobject_uevent(&disk_to_dev(lo
->lo_disk
)->kobj
, KOBJ_CHANGE
);
239 static int lo_write_bvec(struct file
*file
, struct bio_vec
*bvec
, loff_t
*ppos
)
244 iov_iter_bvec(&i
, ITER_SOURCE
, bvec
, 1, bvec
->bv_len
);
246 bw
= vfs_iter_write(file
, &i
, ppos
, 0);
248 if (likely(bw
== bvec
->bv_len
))
251 printk_ratelimited(KERN_ERR
252 "loop: Write error at byte offset %llu, length %i.\n",
253 (unsigned long long)*ppos
, bvec
->bv_len
);
259 static int lo_write_simple(struct loop_device
*lo
, struct request
*rq
,
263 struct req_iterator iter
;
266 rq_for_each_segment(bvec
, rq
, iter
) {
267 ret
= lo_write_bvec(lo
->lo_backing_file
, &bvec
, &pos
);
276 static int lo_read_simple(struct loop_device
*lo
, struct request
*rq
,
280 struct req_iterator iter
;
284 rq_for_each_segment(bvec
, rq
, iter
) {
285 iov_iter_bvec(&i
, ITER_DEST
, &bvec
, 1, bvec
.bv_len
);
286 len
= vfs_iter_read(lo
->lo_backing_file
, &i
, &pos
, 0);
290 flush_dcache_page(bvec
.bv_page
);
292 if (len
!= bvec
.bv_len
) {
295 __rq_for_each_bio(bio
, rq
)
305 static int lo_fallocate(struct loop_device
*lo
, struct request
*rq
, loff_t pos
,
309 * We use fallocate to manipulate the space mappings used by the image
310 * a.k.a. discard/zerorange.
312 struct file
*file
= lo
->lo_backing_file
;
315 mode
|= FALLOC_FL_KEEP_SIZE
;
317 if (!bdev_max_discard_sectors(lo
->lo_device
))
320 ret
= file
->f_op
->fallocate(file
, mode
, pos
, blk_rq_bytes(rq
));
321 if (unlikely(ret
&& ret
!= -EINVAL
&& ret
!= -EOPNOTSUPP
))
326 static int lo_req_flush(struct loop_device
*lo
, struct request
*rq
)
328 int ret
= vfs_fsync(lo
->lo_backing_file
, 0);
329 if (unlikely(ret
&& ret
!= -EINVAL
))
335 static void lo_complete_rq(struct request
*rq
)
337 struct loop_cmd
*cmd
= blk_mq_rq_to_pdu(rq
);
338 blk_status_t ret
= BLK_STS_OK
;
340 if (!cmd
->use_aio
|| cmd
->ret
< 0 || cmd
->ret
== blk_rq_bytes(rq
) ||
341 req_op(rq
) != REQ_OP_READ
) {
343 ret
= errno_to_blk_status(cmd
->ret
);
348 * Short READ - if we got some data, advance our request and
349 * retry it. If we got no data, end the rest with EIO.
352 blk_update_request(rq
, BLK_STS_OK
, cmd
->ret
);
354 blk_mq_requeue_request(rq
, true);
357 struct bio
*bio
= rq
->bio
;
366 blk_mq_end_request(rq
, ret
);
370 static void lo_rw_aio_do_completion(struct loop_cmd
*cmd
)
372 struct request
*rq
= blk_mq_rq_from_pdu(cmd
);
374 if (!atomic_dec_and_test(&cmd
->ref
))
378 if (likely(!blk_should_fake_timeout(rq
->q
)))
379 blk_mq_complete_request(rq
);
382 static void lo_rw_aio_complete(struct kiocb
*iocb
, long ret
)
384 struct loop_cmd
*cmd
= container_of(iocb
, struct loop_cmd
, iocb
);
387 lo_rw_aio_do_completion(cmd
);
390 static int lo_rw_aio(struct loop_device
*lo
, struct loop_cmd
*cmd
,
393 struct iov_iter iter
;
394 struct req_iterator rq_iter
;
395 struct bio_vec
*bvec
;
396 struct request
*rq
= blk_mq_rq_from_pdu(cmd
);
397 struct bio
*bio
= rq
->bio
;
398 struct file
*file
= lo
->lo_backing_file
;
404 rq_for_each_bvec(tmp
, rq
, rq_iter
)
407 if (rq
->bio
!= rq
->biotail
) {
409 bvec
= kmalloc_array(nr_bvec
, sizeof(struct bio_vec
),
416 * The bios of the request may be started from the middle of
417 * the 'bvec' because of bio splitting, so we can't directly
418 * copy bio->bi_iov_vec to new bvec. The rq_for_each_bvec
419 * API will take care of all details for us.
421 rq_for_each_bvec(tmp
, rq
, rq_iter
) {
429 * Same here, this bio may be started from the middle of the
430 * 'bvec' because of bio splitting, so offset from the bvec
431 * must be passed to iov iterator
433 offset
= bio
->bi_iter
.bi_bvec_done
;
434 bvec
= __bvec_iter_bvec(bio
->bi_io_vec
, bio
->bi_iter
);
436 atomic_set(&cmd
->ref
, 2);
438 iov_iter_bvec(&iter
, rw
, bvec
, nr_bvec
, blk_rq_bytes(rq
));
439 iter
.iov_offset
= offset
;
441 cmd
->iocb
.ki_pos
= pos
;
442 cmd
->iocb
.ki_filp
= file
;
443 cmd
->iocb
.ki_complete
= lo_rw_aio_complete
;
444 cmd
->iocb
.ki_flags
= IOCB_DIRECT
;
445 cmd
->iocb
.ki_ioprio
= IOPRIO_PRIO_VALUE(IOPRIO_CLASS_NONE
, 0);
447 if (rw
== ITER_SOURCE
)
448 ret
= call_write_iter(file
, &cmd
->iocb
, &iter
);
450 ret
= call_read_iter(file
, &cmd
->iocb
, &iter
);
452 lo_rw_aio_do_completion(cmd
);
454 if (ret
!= -EIOCBQUEUED
)
455 lo_rw_aio_complete(&cmd
->iocb
, ret
);
459 static int do_req_filebacked(struct loop_device
*lo
, struct request
*rq
)
461 struct loop_cmd
*cmd
= blk_mq_rq_to_pdu(rq
);
462 loff_t pos
= ((loff_t
) blk_rq_pos(rq
) << 9) + lo
->lo_offset
;
465 * lo_write_simple and lo_read_simple should have been covered
466 * by io submit style function like lo_rw_aio(), one blocker
467 * is that lo_read_simple() need to call flush_dcache_page after
468 * the page is written from kernel, and it isn't easy to handle
469 * this in io submit style function which submits all segments
470 * of the req at one time. And direct read IO doesn't need to
471 * run flush_dcache_page().
473 switch (req_op(rq
)) {
475 return lo_req_flush(lo
, rq
);
476 case REQ_OP_WRITE_ZEROES
:
478 * If the caller doesn't want deallocation, call zeroout to
479 * write zeroes the range. Otherwise, punch them out.
481 return lo_fallocate(lo
, rq
, pos
,
482 (rq
->cmd_flags
& REQ_NOUNMAP
) ?
483 FALLOC_FL_ZERO_RANGE
:
484 FALLOC_FL_PUNCH_HOLE
);
486 return lo_fallocate(lo
, rq
, pos
, FALLOC_FL_PUNCH_HOLE
);
489 return lo_rw_aio(lo
, cmd
, pos
, ITER_SOURCE
);
491 return lo_write_simple(lo
, rq
, pos
);
494 return lo_rw_aio(lo
, cmd
, pos
, ITER_DEST
);
496 return lo_read_simple(lo
, rq
, pos
);
503 static inline void loop_update_dio(struct loop_device
*lo
)
505 __loop_update_dio(lo
, (lo
->lo_backing_file
->f_flags
& O_DIRECT
) |
509 static void loop_reread_partitions(struct loop_device
*lo
)
513 mutex_lock(&lo
->lo_disk
->open_mutex
);
514 rc
= bdev_disk_changed(lo
->lo_disk
, false);
515 mutex_unlock(&lo
->lo_disk
->open_mutex
);
517 pr_warn("%s: partition scan of loop%d (%s) failed (rc=%d)\n",
518 __func__
, lo
->lo_number
, lo
->lo_file_name
, rc
);
521 static inline int is_loop_device(struct file
*file
)
523 struct inode
*i
= file
->f_mapping
->host
;
525 return i
&& S_ISBLK(i
->i_mode
) && imajor(i
) == LOOP_MAJOR
;
528 static int loop_validate_file(struct file
*file
, struct block_device
*bdev
)
530 struct inode
*inode
= file
->f_mapping
->host
;
531 struct file
*f
= file
;
533 /* Avoid recursion */
534 while (is_loop_device(f
)) {
535 struct loop_device
*l
;
537 lockdep_assert_held(&loop_validate_mutex
);
538 if (f
->f_mapping
->host
->i_rdev
== bdev
->bd_dev
)
541 l
= I_BDEV(f
->f_mapping
->host
)->bd_disk
->private_data
;
542 if (l
->lo_state
!= Lo_bound
)
544 /* Order wrt setting lo->lo_backing_file in loop_configure(). */
546 f
= l
->lo_backing_file
;
548 if (!S_ISREG(inode
->i_mode
) && !S_ISBLK(inode
->i_mode
))
554 * loop_change_fd switched the backing store of a loopback device to
555 * a new file. This is useful for operating system installers to free up
556 * the original file and in High Availability environments to switch to
557 * an alternative location for the content in case of server meltdown.
558 * This can only work if the loop device is used read-only, and if the
559 * new backing store is the same size and type as the old backing store.
561 static int loop_change_fd(struct loop_device
*lo
, struct block_device
*bdev
,
564 struct file
*file
= fget(arg
);
565 struct file
*old_file
;
573 /* suppress uevents while reconfiguring the device */
574 dev_set_uevent_suppress(disk_to_dev(lo
->lo_disk
), 1);
576 is_loop
= is_loop_device(file
);
577 error
= loop_global_lock_killable(lo
, is_loop
);
581 if (lo
->lo_state
!= Lo_bound
)
584 /* the loop device has to be read-only */
586 if (!(lo
->lo_flags
& LO_FLAGS_READ_ONLY
))
589 error
= loop_validate_file(file
, bdev
);
593 old_file
= lo
->lo_backing_file
;
597 /* size of the new backing store needs to be the same */
598 if (get_loop_size(lo
, file
) != get_loop_size(lo
, old_file
))
602 disk_force_media_change(lo
->lo_disk
);
603 blk_mq_freeze_queue(lo
->lo_queue
);
604 mapping_set_gfp_mask(old_file
->f_mapping
, lo
->old_gfp_mask
);
605 lo
->lo_backing_file
= file
;
606 lo
->old_gfp_mask
= mapping_gfp_mask(file
->f_mapping
);
607 mapping_set_gfp_mask(file
->f_mapping
,
608 lo
->old_gfp_mask
& ~(__GFP_IO
|__GFP_FS
));
610 blk_mq_unfreeze_queue(lo
->lo_queue
);
611 partscan
= lo
->lo_flags
& LO_FLAGS_PARTSCAN
;
612 loop_global_unlock(lo
, is_loop
);
615 * Flush loop_validate_file() before fput(), for l->lo_backing_file
616 * might be pointing at old_file which might be the last reference.
619 mutex_lock(&loop_validate_mutex
);
620 mutex_unlock(&loop_validate_mutex
);
623 * We must drop file reference outside of lo_mutex as dropping
624 * the file ref can take open_mutex which creates circular locking
629 loop_reread_partitions(lo
);
633 /* enable and uncork uevent now that we are done */
634 dev_set_uevent_suppress(disk_to_dev(lo
->lo_disk
), 0);
638 loop_global_unlock(lo
, is_loop
);
644 /* loop sysfs attributes */
646 static ssize_t
loop_attr_show(struct device
*dev
, char *page
,
647 ssize_t (*callback
)(struct loop_device
*, char *))
649 struct gendisk
*disk
= dev_to_disk(dev
);
650 struct loop_device
*lo
= disk
->private_data
;
652 return callback(lo
, page
);
655 #define LOOP_ATTR_RO(_name) \
656 static ssize_t loop_attr_##_name##_show(struct loop_device *, char *); \
657 static ssize_t loop_attr_do_show_##_name(struct device *d, \
658 struct device_attribute *attr, char *b) \
660 return loop_attr_show(d, b, loop_attr_##_name##_show); \
662 static struct device_attribute loop_attr_##_name = \
663 __ATTR(_name, 0444, loop_attr_do_show_##_name, NULL);
665 static ssize_t
loop_attr_backing_file_show(struct loop_device
*lo
, char *buf
)
670 spin_lock_irq(&lo
->lo_lock
);
671 if (lo
->lo_backing_file
)
672 p
= file_path(lo
->lo_backing_file
, buf
, PAGE_SIZE
- 1);
673 spin_unlock_irq(&lo
->lo_lock
);
675 if (IS_ERR_OR_NULL(p
))
679 memmove(buf
, p
, ret
);
687 static ssize_t
loop_attr_offset_show(struct loop_device
*lo
, char *buf
)
689 return sysfs_emit(buf
, "%llu\n", (unsigned long long)lo
->lo_offset
);
692 static ssize_t
loop_attr_sizelimit_show(struct loop_device
*lo
, char *buf
)
694 return sysfs_emit(buf
, "%llu\n", (unsigned long long)lo
->lo_sizelimit
);
697 static ssize_t
loop_attr_autoclear_show(struct loop_device
*lo
, char *buf
)
699 int autoclear
= (lo
->lo_flags
& LO_FLAGS_AUTOCLEAR
);
701 return sysfs_emit(buf
, "%s\n", autoclear
? "1" : "0");
704 static ssize_t
loop_attr_partscan_show(struct loop_device
*lo
, char *buf
)
706 int partscan
= (lo
->lo_flags
& LO_FLAGS_PARTSCAN
);
708 return sysfs_emit(buf
, "%s\n", partscan
? "1" : "0");
711 static ssize_t
loop_attr_dio_show(struct loop_device
*lo
, char *buf
)
713 int dio
= (lo
->lo_flags
& LO_FLAGS_DIRECT_IO
);
715 return sysfs_emit(buf
, "%s\n", dio
? "1" : "0");
718 LOOP_ATTR_RO(backing_file
);
719 LOOP_ATTR_RO(offset
);
720 LOOP_ATTR_RO(sizelimit
);
721 LOOP_ATTR_RO(autoclear
);
722 LOOP_ATTR_RO(partscan
);
725 static struct attribute
*loop_attrs
[] = {
726 &loop_attr_backing_file
.attr
,
727 &loop_attr_offset
.attr
,
728 &loop_attr_sizelimit
.attr
,
729 &loop_attr_autoclear
.attr
,
730 &loop_attr_partscan
.attr
,
735 static struct attribute_group loop_attribute_group
= {
740 static void loop_sysfs_init(struct loop_device
*lo
)
742 lo
->sysfs_inited
= !sysfs_create_group(&disk_to_dev(lo
->lo_disk
)->kobj
,
743 &loop_attribute_group
);
746 static void loop_sysfs_exit(struct loop_device
*lo
)
748 if (lo
->sysfs_inited
)
749 sysfs_remove_group(&disk_to_dev(lo
->lo_disk
)->kobj
,
750 &loop_attribute_group
);
753 static void loop_config_discard(struct loop_device
*lo
,
754 struct queue_limits
*lim
)
756 struct file
*file
= lo
->lo_backing_file
;
757 struct inode
*inode
= file
->f_mapping
->host
;
758 u32 granularity
= 0, max_discard_sectors
= 0;
762 * If the backing device is a block device, mirror its zeroing
763 * capability. Set the discard sectors to the block device's zeroing
764 * capabilities because loop discards result in blkdev_issue_zeroout(),
765 * not blkdev_issue_discard(). This maintains consistent behavior with
766 * file-backed loop devices: discarded regions read back as zero.
768 if (S_ISBLK(inode
->i_mode
)) {
769 struct request_queue
*backingq
= bdev_get_queue(I_BDEV(inode
));
771 max_discard_sectors
= backingq
->limits
.max_write_zeroes_sectors
;
772 granularity
= bdev_discard_granularity(I_BDEV(inode
)) ?:
773 queue_physical_block_size(backingq
);
776 * We use punch hole to reclaim the free space used by the
777 * image a.k.a. discard.
779 } else if (file
->f_op
->fallocate
&& !vfs_statfs(&file
->f_path
, &sbuf
)) {
780 max_discard_sectors
= UINT_MAX
>> 9;
781 granularity
= sbuf
.f_bsize
;
784 lim
->max_hw_discard_sectors
= max_discard_sectors
;
785 lim
->max_write_zeroes_sectors
= max_discard_sectors
;
786 if (max_discard_sectors
)
787 lim
->discard_granularity
= granularity
;
789 lim
->discard_granularity
= 0;
793 struct rb_node rb_node
;
794 struct work_struct work
;
795 struct list_head cmd_list
;
796 struct list_head idle_list
;
797 struct loop_device
*lo
;
798 struct cgroup_subsys_state
*blkcg_css
;
799 unsigned long last_ran_at
;
802 static void loop_workfn(struct work_struct
*work
);
804 #ifdef CONFIG_BLK_CGROUP
805 static inline int queue_on_root_worker(struct cgroup_subsys_state
*css
)
807 return !css
|| css
== blkcg_root_css
;
810 static inline int queue_on_root_worker(struct cgroup_subsys_state
*css
)
816 static void loop_queue_work(struct loop_device
*lo
, struct loop_cmd
*cmd
)
818 struct rb_node
**node
, *parent
= NULL
;
819 struct loop_worker
*cur_worker
, *worker
= NULL
;
820 struct work_struct
*work
;
821 struct list_head
*cmd_list
;
823 spin_lock_irq(&lo
->lo_work_lock
);
825 if (queue_on_root_worker(cmd
->blkcg_css
))
828 node
= &lo
->worker_tree
.rb_node
;
832 cur_worker
= container_of(*node
, struct loop_worker
, rb_node
);
833 if (cur_worker
->blkcg_css
== cmd
->blkcg_css
) {
836 } else if ((long)cur_worker
->blkcg_css
< (long)cmd
->blkcg_css
) {
837 node
= &(*node
)->rb_left
;
839 node
= &(*node
)->rb_right
;
845 worker
= kzalloc(sizeof(struct loop_worker
), GFP_NOWAIT
| __GFP_NOWARN
);
847 * In the event we cannot allocate a worker, just queue on the
848 * rootcg worker and issue the I/O as the rootcg
851 cmd
->blkcg_css
= NULL
;
853 css_put(cmd
->memcg_css
);
854 cmd
->memcg_css
= NULL
;
858 worker
->blkcg_css
= cmd
->blkcg_css
;
859 css_get(worker
->blkcg_css
);
860 INIT_WORK(&worker
->work
, loop_workfn
);
861 INIT_LIST_HEAD(&worker
->cmd_list
);
862 INIT_LIST_HEAD(&worker
->idle_list
);
864 rb_link_node(&worker
->rb_node
, parent
, node
);
865 rb_insert_color(&worker
->rb_node
, &lo
->worker_tree
);
869 * We need to remove from the idle list here while
870 * holding the lock so that the idle timer doesn't
873 if (!list_empty(&worker
->idle_list
))
874 list_del_init(&worker
->idle_list
);
875 work
= &worker
->work
;
876 cmd_list
= &worker
->cmd_list
;
878 work
= &lo
->rootcg_work
;
879 cmd_list
= &lo
->rootcg_cmd_list
;
881 list_add_tail(&cmd
->list_entry
, cmd_list
);
882 queue_work(lo
->workqueue
, work
);
883 spin_unlock_irq(&lo
->lo_work_lock
);
886 static void loop_set_timer(struct loop_device
*lo
)
888 timer_reduce(&lo
->timer
, jiffies
+ LOOP_IDLE_WORKER_TIMEOUT
);
891 static void loop_free_idle_workers(struct loop_device
*lo
, bool delete_all
)
893 struct loop_worker
*pos
, *worker
;
895 spin_lock_irq(&lo
->lo_work_lock
);
896 list_for_each_entry_safe(worker
, pos
, &lo
->idle_worker_list
,
899 time_is_after_jiffies(worker
->last_ran_at
+
900 LOOP_IDLE_WORKER_TIMEOUT
))
902 list_del(&worker
->idle_list
);
903 rb_erase(&worker
->rb_node
, &lo
->worker_tree
);
904 css_put(worker
->blkcg_css
);
907 if (!list_empty(&lo
->idle_worker_list
))
909 spin_unlock_irq(&lo
->lo_work_lock
);
912 static void loop_free_idle_workers_timer(struct timer_list
*timer
)
914 struct loop_device
*lo
= container_of(timer
, struct loop_device
, timer
);
916 return loop_free_idle_workers(lo
, false);
919 static void loop_update_rotational(struct loop_device
*lo
)
921 struct file
*file
= lo
->lo_backing_file
;
922 struct inode
*file_inode
= file
->f_mapping
->host
;
923 struct block_device
*file_bdev
= file_inode
->i_sb
->s_bdev
;
924 struct request_queue
*q
= lo
->lo_queue
;
927 /* not all filesystems (e.g. tmpfs) have a sb->s_bdev */
929 nonrot
= bdev_nonrot(file_bdev
);
932 blk_queue_flag_set(QUEUE_FLAG_NONROT
, q
);
934 blk_queue_flag_clear(QUEUE_FLAG_NONROT
, q
);
938 * loop_set_status_from_info - configure device from loop_info
939 * @lo: struct loop_device to configure
940 * @info: struct loop_info64 to configure the device with
942 * Configures the loop device parameters according to the passed
943 * in loop_info64 configuration.
946 loop_set_status_from_info(struct loop_device
*lo
,
947 const struct loop_info64
*info
)
949 if ((unsigned int) info
->lo_encrypt_key_size
> LO_KEY_SIZE
)
952 switch (info
->lo_encrypt_type
) {
956 pr_warn("support for the xor transformation has been removed.\n");
958 case LO_CRYPT_CRYPTOAPI
:
959 pr_warn("support for cryptoloop has been removed. Use dm-crypt instead.\n");
965 /* Avoid assigning overflow values */
966 if (info
->lo_offset
> LLONG_MAX
|| info
->lo_sizelimit
> LLONG_MAX
)
969 lo
->lo_offset
= info
->lo_offset
;
970 lo
->lo_sizelimit
= info
->lo_sizelimit
;
972 memcpy(lo
->lo_file_name
, info
->lo_file_name
, LO_NAME_SIZE
);
973 lo
->lo_file_name
[LO_NAME_SIZE
-1] = 0;
974 lo
->lo_flags
= info
->lo_flags
;
978 static int loop_reconfigure_limits(struct loop_device
*lo
, unsigned short bsize
,
979 bool update_discard_settings
)
981 struct queue_limits lim
;
983 lim
= queue_limits_start_update(lo
->lo_queue
);
984 lim
.logical_block_size
= bsize
;
985 lim
.physical_block_size
= bsize
;
987 if (update_discard_settings
)
988 loop_config_discard(lo
, &lim
);
989 return queue_limits_commit_update(lo
->lo_queue
, &lim
);
992 static int loop_configure(struct loop_device
*lo
, blk_mode_t mode
,
993 struct block_device
*bdev
,
994 const struct loop_config
*config
)
996 struct file
*file
= fget(config
->fd
);
998 struct address_space
*mapping
;
1002 unsigned short bsize
;
1007 is_loop
= is_loop_device(file
);
1009 /* This is safe, since we have a reference from open(). */
1010 __module_get(THIS_MODULE
);
1013 * If we don't hold exclusive handle for the device, upgrade to it
1014 * here to avoid changing device under exclusive owner.
1016 if (!(mode
& BLK_OPEN_EXCL
)) {
1017 error
= bd_prepare_to_claim(bdev
, loop_configure
, NULL
);
1022 error
= loop_global_lock_killable(lo
, is_loop
);
1027 if (lo
->lo_state
!= Lo_unbound
)
1030 error
= loop_validate_file(file
, bdev
);
1034 mapping
= file
->f_mapping
;
1035 inode
= mapping
->host
;
1037 if ((config
->info
.lo_flags
& ~LOOP_CONFIGURE_SETTABLE_FLAGS
) != 0) {
1042 if (config
->block_size
) {
1043 error
= blk_validate_block_size(config
->block_size
);
1048 error
= loop_set_status_from_info(lo
, &config
->info
);
1052 if (!(file
->f_mode
& FMODE_WRITE
) || !(mode
& BLK_OPEN_WRITE
) ||
1053 !file
->f_op
->write_iter
)
1054 lo
->lo_flags
|= LO_FLAGS_READ_ONLY
;
1056 if (!lo
->workqueue
) {
1057 lo
->workqueue
= alloc_workqueue("loop%d",
1058 WQ_UNBOUND
| WQ_FREEZABLE
,
1060 if (!lo
->workqueue
) {
1066 /* suppress uevents while reconfiguring the device */
1067 dev_set_uevent_suppress(disk_to_dev(lo
->lo_disk
), 1);
1069 disk_force_media_change(lo
->lo_disk
);
1070 set_disk_ro(lo
->lo_disk
, (lo
->lo_flags
& LO_FLAGS_READ_ONLY
) != 0);
1072 lo
->use_dio
= lo
->lo_flags
& LO_FLAGS_DIRECT_IO
;
1073 lo
->lo_device
= bdev
;
1074 lo
->lo_backing_file
= file
;
1075 lo
->old_gfp_mask
= mapping_gfp_mask(mapping
);
1076 mapping_set_gfp_mask(mapping
, lo
->old_gfp_mask
& ~(__GFP_IO
|__GFP_FS
));
1078 if (!(lo
->lo_flags
& LO_FLAGS_READ_ONLY
) && file
->f_op
->fsync
)
1079 blk_queue_write_cache(lo
->lo_queue
, true, false);
1081 if (config
->block_size
)
1082 bsize
= config
->block_size
;
1083 else if ((lo
->lo_backing_file
->f_flags
& O_DIRECT
) && inode
->i_sb
->s_bdev
)
1084 /* In case of direct I/O, match underlying block size */
1085 bsize
= bdev_logical_block_size(inode
->i_sb
->s_bdev
);
1089 error
= loop_reconfigure_limits(lo
, bsize
, true);
1090 if (WARN_ON_ONCE(error
))
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 loop_reconfigure_limits(lo
, 512, false);
1160 invalidate_disk(lo
->lo_disk
);
1161 loop_sysfs_exit(lo
);
1162 /* let user-space know about this change */
1163 kobject_uevent(&disk_to_dev(lo
->lo_disk
)->kobj
, KOBJ_CHANGE
);
1164 mapping_set_gfp_mask(filp
->f_mapping
, gfp
);
1165 /* This is safe: open() is still holding a reference. */
1166 module_put(THIS_MODULE
);
1168 blk_mq_unfreeze_queue(lo
->lo_queue
);
1170 disk_force_media_change(lo
->lo_disk
);
1172 if (lo
->lo_flags
& LO_FLAGS_PARTSCAN
) {
1176 * open_mutex has been held already in release path, so don't
1177 * acquire it if this function is called in such case.
1179 * If the reread partition isn't from release path, lo_refcnt
1180 * must be at least one and it can only become zero when the
1181 * current holder is released.
1184 mutex_lock(&lo
->lo_disk
->open_mutex
);
1185 err
= bdev_disk_changed(lo
->lo_disk
, false);
1187 mutex_unlock(&lo
->lo_disk
->open_mutex
);
1189 pr_warn("%s: partition scan of loop%d failed (rc=%d)\n",
1190 __func__
, lo
->lo_number
, err
);
1191 /* Device is gone, no point in returning error */
1195 * lo->lo_state is set to Lo_unbound here after above partscan has
1196 * finished. There cannot be anybody else entering __loop_clr_fd() as
1197 * Lo_rundown state protects us from all the other places trying to
1198 * change the 'lo' device.
1202 set_bit(GD_SUPPRESS_PART_SCAN
, &lo
->lo_disk
->state
);
1203 mutex_lock(&lo
->lo_mutex
);
1204 lo
->lo_state
= Lo_unbound
;
1205 mutex_unlock(&lo
->lo_mutex
);
1208 * Need not hold lo_mutex to fput backing file. Calling fput holding
1209 * lo_mutex triggers a circular lock dependency possibility warning as
1210 * fput can take open_mutex which is usually taken before lo_mutex.
1215 static int loop_clr_fd(struct loop_device
*lo
)
1220 * Since lo_ioctl() is called without locks held, it is possible that
1221 * loop_configure()/loop_change_fd() and loop_clr_fd() run in parallel.
1223 * Therefore, use global lock when setting Lo_rundown state in order to
1224 * make sure that loop_validate_file() will fail if the "struct file"
1225 * which loop_configure()/loop_change_fd() found via fget() was this
1228 err
= loop_global_lock_killable(lo
, true);
1231 if (lo
->lo_state
!= Lo_bound
) {
1232 loop_global_unlock(lo
, true);
1236 * If we've explicitly asked to tear down the loop device,
1237 * and it has an elevated reference count, set it for auto-teardown when
1238 * the last reference goes away. This stops $!~#$@ udev from
1239 * preventing teardown because it decided that it needs to run blkid on
1240 * the loopback device whenever they appear. xfstests is notorious for
1241 * failing tests because blkid via udev races with a losetup
1242 * <dev>/do something like mkfs/losetup -d <dev> causing the losetup -d
1243 * command to fail with EBUSY.
1245 if (disk_openers(lo
->lo_disk
) > 1) {
1246 lo
->lo_flags
|= LO_FLAGS_AUTOCLEAR
;
1247 loop_global_unlock(lo
, true);
1250 lo
->lo_state
= Lo_rundown
;
1251 loop_global_unlock(lo
, true);
1253 __loop_clr_fd(lo
, false);
1258 loop_set_status(struct loop_device
*lo
, const struct loop_info64
*info
)
1262 bool partscan
= false;
1263 bool size_changed
= false;
1265 err
= mutex_lock_killable(&lo
->lo_mutex
);
1268 if (lo
->lo_state
!= Lo_bound
) {
1273 if (lo
->lo_offset
!= info
->lo_offset
||
1274 lo
->lo_sizelimit
!= info
->lo_sizelimit
) {
1275 size_changed
= true;
1276 sync_blockdev(lo
->lo_device
);
1277 invalidate_bdev(lo
->lo_device
);
1280 /* I/O need to be drained during transfer transition */
1281 blk_mq_freeze_queue(lo
->lo_queue
);
1283 prev_lo_flags
= lo
->lo_flags
;
1285 err
= loop_set_status_from_info(lo
, info
);
1289 /* Mask out flags that can't be set using LOOP_SET_STATUS. */
1290 lo
->lo_flags
&= LOOP_SET_STATUS_SETTABLE_FLAGS
;
1291 /* For those flags, use the previous values instead */
1292 lo
->lo_flags
|= prev_lo_flags
& ~LOOP_SET_STATUS_SETTABLE_FLAGS
;
1293 /* For flags that can't be cleared, use previous values too */
1294 lo
->lo_flags
|= prev_lo_flags
& ~LOOP_SET_STATUS_CLEARABLE_FLAGS
;
1297 loff_t new_size
= get_size(lo
->lo_offset
, lo
->lo_sizelimit
,
1298 lo
->lo_backing_file
);
1299 loop_set_size(lo
, new_size
);
1302 /* update dio if lo_offset or transfer is changed */
1303 __loop_update_dio(lo
, lo
->use_dio
);
1306 blk_mq_unfreeze_queue(lo
->lo_queue
);
1308 if (!err
&& (lo
->lo_flags
& LO_FLAGS_PARTSCAN
) &&
1309 !(prev_lo_flags
& LO_FLAGS_PARTSCAN
)) {
1310 clear_bit(GD_SUPPRESS_PART_SCAN
, &lo
->lo_disk
->state
);
1314 mutex_unlock(&lo
->lo_mutex
);
1316 loop_reread_partitions(lo
);
1322 loop_get_status(struct loop_device
*lo
, struct loop_info64
*info
)
1328 ret
= mutex_lock_killable(&lo
->lo_mutex
);
1331 if (lo
->lo_state
!= Lo_bound
) {
1332 mutex_unlock(&lo
->lo_mutex
);
1336 memset(info
, 0, sizeof(*info
));
1337 info
->lo_number
= lo
->lo_number
;
1338 info
->lo_offset
= lo
->lo_offset
;
1339 info
->lo_sizelimit
= lo
->lo_sizelimit
;
1340 info
->lo_flags
= lo
->lo_flags
;
1341 memcpy(info
->lo_file_name
, lo
->lo_file_name
, LO_NAME_SIZE
);
1343 /* Drop lo_mutex while we call into the filesystem. */
1344 path
= lo
->lo_backing_file
->f_path
;
1346 mutex_unlock(&lo
->lo_mutex
);
1347 ret
= vfs_getattr(&path
, &stat
, STATX_INO
, AT_STATX_SYNC_AS_STAT
);
1349 info
->lo_device
= huge_encode_dev(stat
.dev
);
1350 info
->lo_inode
= stat
.ino
;
1351 info
->lo_rdevice
= huge_encode_dev(stat
.rdev
);
1358 loop_info64_from_old(const struct loop_info
*info
, struct loop_info64
*info64
)
1360 memset(info64
, 0, sizeof(*info64
));
1361 info64
->lo_number
= info
->lo_number
;
1362 info64
->lo_device
= info
->lo_device
;
1363 info64
->lo_inode
= info
->lo_inode
;
1364 info64
->lo_rdevice
= info
->lo_rdevice
;
1365 info64
->lo_offset
= info
->lo_offset
;
1366 info64
->lo_sizelimit
= 0;
1367 info64
->lo_flags
= info
->lo_flags
;
1368 memcpy(info64
->lo_file_name
, info
->lo_name
, LO_NAME_SIZE
);
1372 loop_info64_to_old(const struct loop_info64
*info64
, struct loop_info
*info
)
1374 memset(info
, 0, sizeof(*info
));
1375 info
->lo_number
= info64
->lo_number
;
1376 info
->lo_device
= info64
->lo_device
;
1377 info
->lo_inode
= info64
->lo_inode
;
1378 info
->lo_rdevice
= info64
->lo_rdevice
;
1379 info
->lo_offset
= info64
->lo_offset
;
1380 info
->lo_flags
= info64
->lo_flags
;
1381 memcpy(info
->lo_name
, info64
->lo_file_name
, LO_NAME_SIZE
);
1383 /* error in case values were truncated */
1384 if (info
->lo_device
!= info64
->lo_device
||
1385 info
->lo_rdevice
!= info64
->lo_rdevice
||
1386 info
->lo_inode
!= info64
->lo_inode
||
1387 info
->lo_offset
!= info64
->lo_offset
)
1394 loop_set_status_old(struct loop_device
*lo
, const struct loop_info __user
*arg
)
1396 struct loop_info info
;
1397 struct loop_info64 info64
;
1399 if (copy_from_user(&info
, arg
, sizeof (struct loop_info
)))
1401 loop_info64_from_old(&info
, &info64
);
1402 return loop_set_status(lo
, &info64
);
1406 loop_set_status64(struct loop_device
*lo
, const struct loop_info64 __user
*arg
)
1408 struct loop_info64 info64
;
1410 if (copy_from_user(&info64
, arg
, sizeof (struct loop_info64
)))
1412 return loop_set_status(lo
, &info64
);
1416 loop_get_status_old(struct loop_device
*lo
, struct loop_info __user
*arg
) {
1417 struct loop_info info
;
1418 struct loop_info64 info64
;
1423 err
= loop_get_status(lo
, &info64
);
1425 err
= loop_info64_to_old(&info64
, &info
);
1426 if (!err
&& copy_to_user(arg
, &info
, sizeof(info
)))
1433 loop_get_status64(struct loop_device
*lo
, struct loop_info64 __user
*arg
) {
1434 struct loop_info64 info64
;
1439 err
= loop_get_status(lo
, &info64
);
1440 if (!err
&& copy_to_user(arg
, &info64
, sizeof(info64
)))
1446 static int loop_set_capacity(struct loop_device
*lo
)
1450 if (unlikely(lo
->lo_state
!= Lo_bound
))
1453 size
= get_loop_size(lo
, lo
->lo_backing_file
);
1454 loop_set_size(lo
, size
);
1459 static int loop_set_dio(struct loop_device
*lo
, unsigned long arg
)
1462 if (lo
->lo_state
!= Lo_bound
)
1465 __loop_update_dio(lo
, !!arg
);
1466 if (lo
->use_dio
== !!arg
)
1473 static int loop_set_block_size(struct loop_device
*lo
, unsigned long arg
)
1477 if (lo
->lo_state
!= Lo_bound
)
1480 err
= blk_validate_block_size(arg
);
1484 if (lo
->lo_queue
->limits
.logical_block_size
== arg
)
1487 sync_blockdev(lo
->lo_device
);
1488 invalidate_bdev(lo
->lo_device
);
1490 blk_mq_freeze_queue(lo
->lo_queue
);
1491 err
= loop_reconfigure_limits(lo
, arg
, false);
1492 loop_update_dio(lo
);
1493 blk_mq_unfreeze_queue(lo
->lo_queue
);
1498 static int lo_simple_ioctl(struct loop_device
*lo
, unsigned int cmd
,
1503 err
= mutex_lock_killable(&lo
->lo_mutex
);
1507 case LOOP_SET_CAPACITY
:
1508 err
= loop_set_capacity(lo
);
1510 case LOOP_SET_DIRECT_IO
:
1511 err
= loop_set_dio(lo
, arg
);
1513 case LOOP_SET_BLOCK_SIZE
:
1514 err
= loop_set_block_size(lo
, arg
);
1519 mutex_unlock(&lo
->lo_mutex
);
1523 static int lo_ioctl(struct block_device
*bdev
, blk_mode_t mode
,
1524 unsigned int cmd
, unsigned long arg
)
1526 struct loop_device
*lo
= bdev
->bd_disk
->private_data
;
1527 void __user
*argp
= (void __user
*) arg
;
1533 * Legacy case - pass in a zeroed out struct loop_config with
1534 * only the file descriptor set , which corresponds with the
1535 * default parameters we'd have used otherwise.
1537 struct loop_config config
;
1539 memset(&config
, 0, sizeof(config
));
1542 return loop_configure(lo
, mode
, bdev
, &config
);
1544 case LOOP_CONFIGURE
: {
1545 struct loop_config config
;
1547 if (copy_from_user(&config
, argp
, sizeof(config
)))
1550 return loop_configure(lo
, mode
, bdev
, &config
);
1552 case LOOP_CHANGE_FD
:
1553 return loop_change_fd(lo
, bdev
, arg
);
1555 return loop_clr_fd(lo
);
1556 case LOOP_SET_STATUS
:
1558 if ((mode
& BLK_OPEN_WRITE
) || capable(CAP_SYS_ADMIN
))
1559 err
= loop_set_status_old(lo
, argp
);
1561 case LOOP_GET_STATUS
:
1562 return loop_get_status_old(lo
, argp
);
1563 case LOOP_SET_STATUS64
:
1565 if ((mode
& BLK_OPEN_WRITE
) || capable(CAP_SYS_ADMIN
))
1566 err
= loop_set_status64(lo
, argp
);
1568 case LOOP_GET_STATUS64
:
1569 return loop_get_status64(lo
, argp
);
1570 case LOOP_SET_CAPACITY
:
1571 case LOOP_SET_DIRECT_IO
:
1572 case LOOP_SET_BLOCK_SIZE
:
1573 if (!(mode
& BLK_OPEN_WRITE
) && !capable(CAP_SYS_ADMIN
))
1577 err
= lo_simple_ioctl(lo
, cmd
, arg
);
1584 #ifdef CONFIG_COMPAT
1585 struct compat_loop_info
{
1586 compat_int_t lo_number
; /* ioctl r/o */
1587 compat_dev_t lo_device
; /* ioctl r/o */
1588 compat_ulong_t lo_inode
; /* ioctl r/o */
1589 compat_dev_t lo_rdevice
; /* ioctl r/o */
1590 compat_int_t lo_offset
;
1591 compat_int_t lo_encrypt_type
; /* obsolete, ignored */
1592 compat_int_t lo_encrypt_key_size
; /* ioctl w/o */
1593 compat_int_t lo_flags
; /* ioctl r/o */
1594 char lo_name
[LO_NAME_SIZE
];
1595 unsigned char lo_encrypt_key
[LO_KEY_SIZE
]; /* ioctl w/o */
1596 compat_ulong_t lo_init
[2];
1601 * Transfer 32-bit compatibility structure in userspace to 64-bit loop info
1602 * - noinlined to reduce stack space usage in main part of driver
1605 loop_info64_from_compat(const struct compat_loop_info __user
*arg
,
1606 struct loop_info64
*info64
)
1608 struct compat_loop_info info
;
1610 if (copy_from_user(&info
, arg
, sizeof(info
)))
1613 memset(info64
, 0, sizeof(*info64
));
1614 info64
->lo_number
= info
.lo_number
;
1615 info64
->lo_device
= info
.lo_device
;
1616 info64
->lo_inode
= info
.lo_inode
;
1617 info64
->lo_rdevice
= info
.lo_rdevice
;
1618 info64
->lo_offset
= info
.lo_offset
;
1619 info64
->lo_sizelimit
= 0;
1620 info64
->lo_flags
= info
.lo_flags
;
1621 memcpy(info64
->lo_file_name
, info
.lo_name
, LO_NAME_SIZE
);
1626 * Transfer 64-bit loop info to 32-bit compatibility structure in userspace
1627 * - noinlined to reduce stack space usage in main part of driver
1630 loop_info64_to_compat(const struct loop_info64
*info64
,
1631 struct compat_loop_info __user
*arg
)
1633 struct compat_loop_info info
;
1635 memset(&info
, 0, sizeof(info
));
1636 info
.lo_number
= info64
->lo_number
;
1637 info
.lo_device
= info64
->lo_device
;
1638 info
.lo_inode
= info64
->lo_inode
;
1639 info
.lo_rdevice
= info64
->lo_rdevice
;
1640 info
.lo_offset
= info64
->lo_offset
;
1641 info
.lo_flags
= info64
->lo_flags
;
1642 memcpy(info
.lo_name
, info64
->lo_file_name
, LO_NAME_SIZE
);
1644 /* error in case values were truncated */
1645 if (info
.lo_device
!= info64
->lo_device
||
1646 info
.lo_rdevice
!= info64
->lo_rdevice
||
1647 info
.lo_inode
!= info64
->lo_inode
||
1648 info
.lo_offset
!= info64
->lo_offset
)
1651 if (copy_to_user(arg
, &info
, sizeof(info
)))
1657 loop_set_status_compat(struct loop_device
*lo
,
1658 const struct compat_loop_info __user
*arg
)
1660 struct loop_info64 info64
;
1663 ret
= loop_info64_from_compat(arg
, &info64
);
1666 return loop_set_status(lo
, &info64
);
1670 loop_get_status_compat(struct loop_device
*lo
,
1671 struct compat_loop_info __user
*arg
)
1673 struct loop_info64 info64
;
1678 err
= loop_get_status(lo
, &info64
);
1680 err
= loop_info64_to_compat(&info64
, arg
);
1684 static int lo_compat_ioctl(struct block_device
*bdev
, blk_mode_t mode
,
1685 unsigned int cmd
, unsigned long arg
)
1687 struct loop_device
*lo
= bdev
->bd_disk
->private_data
;
1691 case LOOP_SET_STATUS
:
1692 err
= loop_set_status_compat(lo
,
1693 (const struct compat_loop_info __user
*)arg
);
1695 case LOOP_GET_STATUS
:
1696 err
= loop_get_status_compat(lo
,
1697 (struct compat_loop_info __user
*)arg
);
1699 case LOOP_SET_CAPACITY
:
1701 case LOOP_GET_STATUS64
:
1702 case LOOP_SET_STATUS64
:
1703 case LOOP_CONFIGURE
:
1704 arg
= (unsigned long) compat_ptr(arg
);
1707 case LOOP_CHANGE_FD
:
1708 case LOOP_SET_BLOCK_SIZE
:
1709 case LOOP_SET_DIRECT_IO
:
1710 err
= lo_ioctl(bdev
, mode
, cmd
, arg
);
1720 static void lo_release(struct gendisk
*disk
)
1722 struct loop_device
*lo
= disk
->private_data
;
1724 if (disk_openers(disk
) > 0)
1727 mutex_lock(&lo
->lo_mutex
);
1728 if (lo
->lo_state
== Lo_bound
&& (lo
->lo_flags
& LO_FLAGS_AUTOCLEAR
)) {
1729 lo
->lo_state
= Lo_rundown
;
1730 mutex_unlock(&lo
->lo_mutex
);
1732 * In autoclear mode, stop the loop thread
1733 * and remove configuration after last close.
1735 __loop_clr_fd(lo
, true);
1738 mutex_unlock(&lo
->lo_mutex
);
1741 static void lo_free_disk(struct gendisk
*disk
)
1743 struct loop_device
*lo
= disk
->private_data
;
1746 destroy_workqueue(lo
->workqueue
);
1747 loop_free_idle_workers(lo
, true);
1748 timer_shutdown_sync(&lo
->timer
);
1749 mutex_destroy(&lo
->lo_mutex
);
1753 static const struct block_device_operations lo_fops
= {
1754 .owner
= THIS_MODULE
,
1755 .release
= lo_release
,
1757 #ifdef CONFIG_COMPAT
1758 .compat_ioctl
= lo_compat_ioctl
,
1760 .free_disk
= lo_free_disk
,
1764 * And now the modules code and kernel interface.
1768 * If max_loop is specified, create that many devices upfront.
1769 * This also becomes a hard limit. If max_loop is not specified,
1770 * the default isn't a hard limit (as before commit 85c50197716c
1771 * changed the default value from 0 for max_loop=0 reasons), just
1772 * create CONFIG_BLK_DEV_LOOP_MIN_COUNT loop devices at module
1773 * init time. Loop devices can be requested on-demand with the
1774 * /dev/loop-control interface, or be instantiated by accessing
1775 * a 'dead' device node.
1777 static int max_loop
= CONFIG_BLK_DEV_LOOP_MIN_COUNT
;
1779 #ifdef CONFIG_BLOCK_LEGACY_AUTOLOAD
1780 static bool max_loop_specified
;
1782 static int max_loop_param_set_int(const char *val
,
1783 const struct kernel_param
*kp
)
1787 ret
= param_set_int(val
, kp
);
1791 max_loop_specified
= true;
1795 static const struct kernel_param_ops max_loop_param_ops
= {
1796 .set
= max_loop_param_set_int
,
1797 .get
= param_get_int
,
1800 module_param_cb(max_loop
, &max_loop_param_ops
, &max_loop
, 0444);
1801 MODULE_PARM_DESC(max_loop
, "Maximum number of loop devices");
1803 module_param(max_loop
, int, 0444);
1804 MODULE_PARM_DESC(max_loop
, "Initial number of loop devices");
1807 module_param(max_part
, int, 0444);
1808 MODULE_PARM_DESC(max_part
, "Maximum number of partitions per loop device");
1810 static int hw_queue_depth
= LOOP_DEFAULT_HW_Q_DEPTH
;
1812 static int loop_set_hw_queue_depth(const char *s
, const struct kernel_param
*p
)
1816 ret
= kstrtoint(s
, 0, &qd
);
1821 hw_queue_depth
= qd
;
1825 static const struct kernel_param_ops loop_hw_qdepth_param_ops
= {
1826 .set
= loop_set_hw_queue_depth
,
1827 .get
= param_get_int
,
1830 device_param_cb(hw_queue_depth
, &loop_hw_qdepth_param_ops
, &hw_queue_depth
, 0444);
1831 MODULE_PARM_DESC(hw_queue_depth
, "Queue depth for each hardware queue. Default: " __stringify(LOOP_DEFAULT_HW_Q_DEPTH
));
1833 MODULE_LICENSE("GPL");
1834 MODULE_ALIAS_BLOCKDEV_MAJOR(LOOP_MAJOR
);
1836 static blk_status_t
loop_queue_rq(struct blk_mq_hw_ctx
*hctx
,
1837 const struct blk_mq_queue_data
*bd
)
1839 struct request
*rq
= bd
->rq
;
1840 struct loop_cmd
*cmd
= blk_mq_rq_to_pdu(rq
);
1841 struct loop_device
*lo
= rq
->q
->queuedata
;
1843 blk_mq_start_request(rq
);
1845 if (lo
->lo_state
!= Lo_bound
)
1846 return BLK_STS_IOERR
;
1848 switch (req_op(rq
)) {
1850 case REQ_OP_DISCARD
:
1851 case REQ_OP_WRITE_ZEROES
:
1852 cmd
->use_aio
= false;
1855 cmd
->use_aio
= lo
->use_dio
;
1859 /* always use the first bio's css */
1860 cmd
->blkcg_css
= NULL
;
1861 cmd
->memcg_css
= NULL
;
1862 #ifdef CONFIG_BLK_CGROUP
1864 cmd
->blkcg_css
= bio_blkcg_css(rq
->bio
);
1866 if (cmd
->blkcg_css
) {
1868 cgroup_get_e_css(cmd
->blkcg_css
->cgroup
,
1869 &memory_cgrp_subsys
);
1874 loop_queue_work(lo
, cmd
);
1879 static void loop_handle_cmd(struct loop_cmd
*cmd
)
1881 struct cgroup_subsys_state
*cmd_blkcg_css
= cmd
->blkcg_css
;
1882 struct cgroup_subsys_state
*cmd_memcg_css
= cmd
->memcg_css
;
1883 struct request
*rq
= blk_mq_rq_from_pdu(cmd
);
1884 const bool write
= op_is_write(req_op(rq
));
1885 struct loop_device
*lo
= rq
->q
->queuedata
;
1887 struct mem_cgroup
*old_memcg
= NULL
;
1888 const bool use_aio
= cmd
->use_aio
;
1890 if (write
&& (lo
->lo_flags
& LO_FLAGS_READ_ONLY
)) {
1896 kthread_associate_blkcg(cmd_blkcg_css
);
1898 old_memcg
= set_active_memcg(
1899 mem_cgroup_from_css(cmd_memcg_css
));
1902 * do_req_filebacked() may call blk_mq_complete_request() synchronously
1903 * or asynchronously if using aio. Hence, do not touch 'cmd' after
1904 * do_req_filebacked() has returned unless we are sure that 'cmd' has
1905 * not yet been completed.
1907 ret
= do_req_filebacked(lo
, rq
);
1910 kthread_associate_blkcg(NULL
);
1912 if (cmd_memcg_css
) {
1913 set_active_memcg(old_memcg
);
1914 css_put(cmd_memcg_css
);
1917 /* complete non-aio request */
1918 if (!use_aio
|| ret
) {
1919 if (ret
== -EOPNOTSUPP
)
1922 cmd
->ret
= ret
? -EIO
: 0;
1923 if (likely(!blk_should_fake_timeout(rq
->q
)))
1924 blk_mq_complete_request(rq
);
1928 static void loop_process_work(struct loop_worker
*worker
,
1929 struct list_head
*cmd_list
, struct loop_device
*lo
)
1931 int orig_flags
= current
->flags
;
1932 struct loop_cmd
*cmd
;
1934 current
->flags
|= PF_LOCAL_THROTTLE
| PF_MEMALLOC_NOIO
;
1935 spin_lock_irq(&lo
->lo_work_lock
);
1936 while (!list_empty(cmd_list
)) {
1938 cmd_list
->next
, struct loop_cmd
, list_entry
);
1939 list_del(cmd_list
->next
);
1940 spin_unlock_irq(&lo
->lo_work_lock
);
1942 loop_handle_cmd(cmd
);
1945 spin_lock_irq(&lo
->lo_work_lock
);
1949 * We only add to the idle list if there are no pending cmds
1950 * *and* the worker will not run again which ensures that it
1951 * is safe to free any worker on the idle list
1953 if (worker
&& !work_pending(&worker
->work
)) {
1954 worker
->last_ran_at
= jiffies
;
1955 list_add_tail(&worker
->idle_list
, &lo
->idle_worker_list
);
1958 spin_unlock_irq(&lo
->lo_work_lock
);
1959 current
->flags
= orig_flags
;
1962 static void loop_workfn(struct work_struct
*work
)
1964 struct loop_worker
*worker
=
1965 container_of(work
, struct loop_worker
, work
);
1966 loop_process_work(worker
, &worker
->cmd_list
, worker
->lo
);
1969 static void loop_rootcg_workfn(struct work_struct
*work
)
1971 struct loop_device
*lo
=
1972 container_of(work
, struct loop_device
, rootcg_work
);
1973 loop_process_work(NULL
, &lo
->rootcg_cmd_list
, lo
);
1976 static const struct blk_mq_ops loop_mq_ops
= {
1977 .queue_rq
= loop_queue_rq
,
1978 .complete
= lo_complete_rq
,
1981 static int loop_add(int i
)
1983 struct queue_limits lim
= {
1985 * Random number picked from the historic block max_sectors cap.
1987 .max_hw_sectors
= 2560u,
1989 struct loop_device
*lo
;
1990 struct gendisk
*disk
;
1994 lo
= kzalloc(sizeof(*lo
), GFP_KERNEL
);
1997 lo
->worker_tree
= RB_ROOT
;
1998 INIT_LIST_HEAD(&lo
->idle_worker_list
);
1999 timer_setup(&lo
->timer
, loop_free_idle_workers_timer
, TIMER_DEFERRABLE
);
2000 lo
->lo_state
= Lo_unbound
;
2002 err
= mutex_lock_killable(&loop_ctl_mutex
);
2006 /* allocate id, if @id >= 0, we're requesting that specific id */
2008 err
= idr_alloc(&loop_index_idr
, lo
, i
, i
+ 1, GFP_KERNEL
);
2012 err
= idr_alloc(&loop_index_idr
, lo
, 0, 0, GFP_KERNEL
);
2014 mutex_unlock(&loop_ctl_mutex
);
2019 lo
->tag_set
.ops
= &loop_mq_ops
;
2020 lo
->tag_set
.nr_hw_queues
= 1;
2021 lo
->tag_set
.queue_depth
= hw_queue_depth
;
2022 lo
->tag_set
.numa_node
= NUMA_NO_NODE
;
2023 lo
->tag_set
.cmd_size
= sizeof(struct loop_cmd
);
2024 lo
->tag_set
.flags
= BLK_MQ_F_SHOULD_MERGE
| BLK_MQ_F_STACKING
|
2025 BLK_MQ_F_NO_SCHED_BY_DEFAULT
;
2026 lo
->tag_set
.driver_data
= lo
;
2028 err
= blk_mq_alloc_tag_set(&lo
->tag_set
);
2032 disk
= lo
->lo_disk
= blk_mq_alloc_disk(&lo
->tag_set
, &lim
, lo
);
2034 err
= PTR_ERR(disk
);
2035 goto out_cleanup_tags
;
2037 lo
->lo_queue
= lo
->lo_disk
->queue
;
2040 * By default, we do buffer IO, so it doesn't make sense to enable
2041 * merge because the I/O submitted to backing file is handled page by
2042 * page. For directio mode, merge does help to dispatch bigger request
2043 * to underlayer disk. We will enable merge once directio is enabled.
2045 blk_queue_flag_set(QUEUE_FLAG_NOMERGES
, lo
->lo_queue
);
2048 * Disable partition scanning by default. The in-kernel partition
2049 * scanning can be requested individually per-device during its
2050 * setup. Userspace can always add and remove partitions from all
2051 * devices. The needed partition minors are allocated from the
2052 * extended minor space, the main loop device numbers will continue
2053 * to match the loop minors, regardless of the number of partitions
2056 * If max_part is given, partition scanning is globally enabled for
2057 * all loop devices. The minors for the main loop devices will be
2058 * multiples of max_part.
2060 * Note: Global-for-all-devices, set-only-at-init, read-only module
2061 * parameteters like 'max_loop' and 'max_part' make things needlessly
2062 * complicated, are too static, inflexible and may surprise
2063 * userspace tools. Parameters like this in general should be avoided.
2066 set_bit(GD_SUPPRESS_PART_SCAN
, &disk
->state
);
2067 mutex_init(&lo
->lo_mutex
);
2069 spin_lock_init(&lo
->lo_lock
);
2070 spin_lock_init(&lo
->lo_work_lock
);
2071 INIT_WORK(&lo
->rootcg_work
, loop_rootcg_workfn
);
2072 INIT_LIST_HEAD(&lo
->rootcg_cmd_list
);
2073 disk
->major
= LOOP_MAJOR
;
2074 disk
->first_minor
= i
<< part_shift
;
2075 disk
->minors
= 1 << part_shift
;
2076 disk
->fops
= &lo_fops
;
2077 disk
->private_data
= lo
;
2078 disk
->queue
= lo
->lo_queue
;
2079 disk
->events
= DISK_EVENT_MEDIA_CHANGE
;
2080 disk
->event_flags
= DISK_EVENT_FLAG_UEVENT
;
2081 sprintf(disk
->disk_name
, "loop%d", i
);
2082 /* Make this loop device reachable from pathname. */
2083 err
= add_disk(disk
);
2085 goto out_cleanup_disk
;
2087 /* Show this loop device. */
2088 mutex_lock(&loop_ctl_mutex
);
2089 lo
->idr_visible
= true;
2090 mutex_unlock(&loop_ctl_mutex
);
2097 blk_mq_free_tag_set(&lo
->tag_set
);
2099 mutex_lock(&loop_ctl_mutex
);
2100 idr_remove(&loop_index_idr
, i
);
2101 mutex_unlock(&loop_ctl_mutex
);
2108 static void loop_remove(struct loop_device
*lo
)
2110 /* Make this loop device unreachable from pathname. */
2111 del_gendisk(lo
->lo_disk
);
2112 blk_mq_free_tag_set(&lo
->tag_set
);
2114 mutex_lock(&loop_ctl_mutex
);
2115 idr_remove(&loop_index_idr
, lo
->lo_number
);
2116 mutex_unlock(&loop_ctl_mutex
);
2118 put_disk(lo
->lo_disk
);
2121 #ifdef CONFIG_BLOCK_LEGACY_AUTOLOAD
2122 static void loop_probe(dev_t dev
)
2124 int idx
= MINOR(dev
) >> part_shift
;
2126 if (max_loop_specified
&& max_loop
&& idx
>= max_loop
)
2131 #define loop_probe NULL
2132 #endif /* !CONFIG_BLOCK_LEGACY_AUTOLOAD */
2134 static int loop_control_remove(int idx
)
2136 struct loop_device
*lo
;
2140 pr_warn_once("deleting an unspecified loop device is not supported.\n");
2144 /* Hide this loop device for serialization. */
2145 ret
= mutex_lock_killable(&loop_ctl_mutex
);
2148 lo
= idr_find(&loop_index_idr
, idx
);
2149 if (!lo
|| !lo
->idr_visible
)
2152 lo
->idr_visible
= false;
2153 mutex_unlock(&loop_ctl_mutex
);
2157 /* Check whether this loop device can be removed. */
2158 ret
= mutex_lock_killable(&lo
->lo_mutex
);
2161 if (lo
->lo_state
!= Lo_unbound
|| disk_openers(lo
->lo_disk
) > 0) {
2162 mutex_unlock(&lo
->lo_mutex
);
2166 /* Mark this loop device as no more bound, but not quite unbound yet */
2167 lo
->lo_state
= Lo_deleting
;
2168 mutex_unlock(&lo
->lo_mutex
);
2174 /* Show this loop device again. */
2175 mutex_lock(&loop_ctl_mutex
);
2176 lo
->idr_visible
= true;
2177 mutex_unlock(&loop_ctl_mutex
);
2181 static int loop_control_get_free(int idx
)
2183 struct loop_device
*lo
;
2186 ret
= mutex_lock_killable(&loop_ctl_mutex
);
2189 idr_for_each_entry(&loop_index_idr
, lo
, id
) {
2190 /* Hitting a race results in creating a new loop device which is harmless. */
2191 if (lo
->idr_visible
&& data_race(lo
->lo_state
) == Lo_unbound
)
2194 mutex_unlock(&loop_ctl_mutex
);
2195 return loop_add(-1);
2197 mutex_unlock(&loop_ctl_mutex
);
2201 static long loop_control_ioctl(struct file
*file
, unsigned int cmd
,
2206 return loop_add(parm
);
2207 case LOOP_CTL_REMOVE
:
2208 return loop_control_remove(parm
);
2209 case LOOP_CTL_GET_FREE
:
2210 return loop_control_get_free(parm
);
2216 static const struct file_operations loop_ctl_fops
= {
2217 .open
= nonseekable_open
,
2218 .unlocked_ioctl
= loop_control_ioctl
,
2219 .compat_ioctl
= loop_control_ioctl
,
2220 .owner
= THIS_MODULE
,
2221 .llseek
= noop_llseek
,
2224 static struct miscdevice loop_misc
= {
2225 .minor
= LOOP_CTRL_MINOR
,
2226 .name
= "loop-control",
2227 .fops
= &loop_ctl_fops
,
2230 MODULE_ALIAS_MISCDEV(LOOP_CTRL_MINOR
);
2231 MODULE_ALIAS("devname:loop-control");
2233 static int __init
loop_init(void)
2240 part_shift
= fls(max_part
);
2243 * Adjust max_part according to part_shift as it is exported
2244 * to user space so that user can decide correct minor number
2245 * if [s]he want to create more devices.
2247 * Note that -1 is required because partition 0 is reserved
2248 * for the whole disk.
2250 max_part
= (1UL << part_shift
) - 1;
2253 if ((1UL << part_shift
) > DISK_MAX_PARTS
) {
2258 if (max_loop
> 1UL << (MINORBITS
- part_shift
)) {
2263 err
= misc_register(&loop_misc
);
2268 if (__register_blkdev(LOOP_MAJOR
, "loop", loop_probe
)) {
2273 /* pre-create number of devices given by config or max_loop */
2274 for (i
= 0; i
< max_loop
; i
++)
2277 printk(KERN_INFO
"loop: module loaded\n");
2281 misc_deregister(&loop_misc
);
2286 static void __exit
loop_exit(void)
2288 struct loop_device
*lo
;
2291 unregister_blkdev(LOOP_MAJOR
, "loop");
2292 misc_deregister(&loop_misc
);
2295 * There is no need to use loop_ctl_mutex here, for nobody else can
2296 * access loop_index_idr when this module is unloading (unless forced
2297 * module unloading is requested). If this is not a clean unloading,
2298 * we have no means to avoid kernel crash.
2300 idr_for_each_entry(&loop_index_idr
, lo
, id
)
2303 idr_destroy(&loop_index_idr
);
2306 module_init(loop_init
);
2307 module_exit(loop_exit
);
2310 static int __init
max_loop_setup(char *str
)
2312 max_loop
= simple_strtol(str
, NULL
, 0);
2313 #ifdef CONFIG_BLOCK_LEGACY_AUTOLOAD
2314 max_loop_specified
= true;
2319 __setup("max_loop=", max_loop_setup
);