1// SPDX-License-Identifier: GPL-2.0-only
2/*
3 * Copyright 1993 by Theodore Ts'o.
4 */
5#include <linux/module.h>
6#include <linux/moduleparam.h>
7#include <linux/sched.h>
8#include <linux/fs.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>
39
40/* Possible states of device */
41enum {
42	Lo_unbound,
43	Lo_bound,
44	Lo_rundown,
45	Lo_deleting,
46};
47
48struct loop_func_table;
49
50struct loop_device {
51	int		lo_number;
52	loff_t		lo_offset;
53	loff_t		lo_sizelimit;
54	int		lo_flags;
55	char		lo_file_name[LO_NAME_SIZE];
56
57	struct file *	lo_backing_file;
58	struct block_device *lo_device;
59
60	gfp_t		old_gfp_mask;
61
62	spinlock_t		lo_lock;
63	int			lo_state;
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;
71	bool			use_dio;
72	bool			sysfs_inited;
73
74	struct request_queue	*lo_queue;
75	struct blk_mq_tag_set	tag_set;
76	struct gendisk		*lo_disk;
77	struct mutex		lo_mutex;
78	bool			idr_visible;
79};
80
81struct loop_cmd {
82	struct list_head list_entry;
83	bool use_aio; /* use AIO interface to handle I/O */
84	atomic_t ref; /* only for aio */
85	long ret;
86	struct kiocb iocb;
87	struct bio_vec *bvec;
88	struct cgroup_subsys_state *blkcg_css;
89	struct cgroup_subsys_state *memcg_css;
90};
91
92#define LOOP_IDLE_WORKER_TIMEOUT (60 * HZ)
93#define LOOP_DEFAULT_HW_Q_DEPTH 128
94
95static DEFINE_IDR(loop_index_idr);
96static DEFINE_MUTEX(loop_ctl_mutex);
97static DEFINE_MUTEX(loop_validate_mutex);
98
99/**
100 * loop_global_lock_killable() - take locks for safe loop_validate_file() test
101 *
102 * @lo: struct loop_device
103 * @global: true if @lo is about to bind another "struct loop_device", false otherwise
104 *
105 * Returns 0 on success, -EINTR otherwise.
106 *
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.
110 */
111static int loop_global_lock_killable(struct loop_device *lo, bool global)
112{
113	int err;
114
115	if (global) {
116		err = mutex_lock_killable(&loop_validate_mutex);
117		if (err)
118			return err;
119	}
120	err = mutex_lock_killable(&lo->lo_mutex);
121	if (err && global)
122		mutex_unlock(&loop_validate_mutex);
123	return err;
124}
125
126/**
127 * loop_global_unlock() - release locks taken by loop_global_lock_killable()
128 *
129 * @lo: struct loop_device
130 * @global: true if @lo was about to bind another "struct loop_device", false otherwise
131 */
132static void loop_global_unlock(struct loop_device *lo, bool global)
133{
134	mutex_unlock(&lo->lo_mutex);
135	if (global)
136		mutex_unlock(&loop_validate_mutex);
137}
138
139static int max_part;
140static int part_shift;
141
142static loff_t get_size(loff_t offset, loff_t sizelimit, struct file *file)
143{
144	loff_t loopsize;
145
146	/* Compute loopsize in bytes */
147	loopsize = i_size_read(file->f_mapping->host);
148	if (offset > 0)
149		loopsize -= offset;
150	/* offset is beyond i_size, weird but possible */
151	if (loopsize < 0)
152		return 0;
153
154	if (sizelimit > 0 && sizelimit < loopsize)
155		loopsize = sizelimit;
156	/*
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.
159	 */
160	return loopsize >> 9;
161}
162
163static loff_t get_loop_size(struct loop_device *lo, struct file *file)
164{
165	return get_size(lo->lo_offset, lo->lo_sizelimit, file);
166}
167
168/*
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.
172 */
173static bool lo_bdev_can_use_dio(struct loop_device *lo,
174		struct block_device *backing_bdev)
175{
176	unsigned short sb_bsize = bdev_logical_block_size(backing_bdev);
177
178	if (queue_logical_block_size(lo->lo_queue) < sb_bsize)
179		return false;
180	if (lo->lo_offset & (sb_bsize - 1))
181		return false;
182	return true;
183}
184
185static void __loop_update_dio(struct loop_device *lo, bool dio)
186{
187	struct file *file = lo->lo_backing_file;
188	struct inode *inode = file->f_mapping->host;
189	struct block_device *backing_bdev = NULL;
190	bool use_dio;
191
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;
196
197	use_dio = dio && (file->f_mode & FMODE_CAN_ODIRECT) &&
198		(!backing_bdev || lo_bdev_can_use_dio(lo, backing_bdev));
199
200	if (lo->use_dio == use_dio)
201		return;
202
203	/* flush dirty pages before changing direct IO */
204	vfs_fsync(file, 0);
205
206	/*
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)
210	 */
211	if (lo->lo_state == Lo_bound)
212		blk_mq_freeze_queue(lo->lo_queue);
213	lo->use_dio = use_dio;
214	if (use_dio) {
215		blk_queue_flag_clear(QUEUE_FLAG_NOMERGES, lo->lo_queue);
216		lo->lo_flags |= LO_FLAGS_DIRECT_IO;
217	} else {
218		blk_queue_flag_set(QUEUE_FLAG_NOMERGES, lo->lo_queue);
219		lo->lo_flags &= ~LO_FLAGS_DIRECT_IO;
220	}
221	if (lo->lo_state == Lo_bound)
222		blk_mq_unfreeze_queue(lo->lo_queue);
223}
224
225/**
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
229 *
230 * Callers must validate that the size passed into this function fits into
231 * a sector_t, eg using loop_validate_size()
232 */
233static void loop_set_size(struct loop_device *lo, loff_t size)
234{
235	if (!set_capacity_and_notify(lo->lo_disk, size))
236		kobject_uevent(&disk_to_dev(lo->lo_disk)->kobj, KOBJ_CHANGE);
237}
238
239static int lo_write_bvec(struct file *file, struct bio_vec *bvec, loff_t *ppos)
240{
241	struct iov_iter i;
242	ssize_t bw;
243
244	iov_iter_bvec(&i, ITER_SOURCE, bvec, 1, bvec->bv_len);
245
246	bw = vfs_iter_write(file, &i, ppos, 0);
247
248	if (likely(bw ==  bvec->bv_len))
249		return 0;
250
251	printk_ratelimited(KERN_ERR
252		"loop: Write error at byte offset %llu, length %i.\n",
253		(unsigned long long)*ppos, bvec->bv_len);
254	if (bw >= 0)
255		bw = -EIO;
256	return bw;
257}
258
259static int lo_write_simple(struct loop_device *lo, struct request *rq,
260		loff_t pos)
261{
262	struct bio_vec bvec;
263	struct req_iterator iter;
264	int ret = 0;
265
266	rq_for_each_segment(bvec, rq, iter) {
267		ret = lo_write_bvec(lo->lo_backing_file, &bvec, &pos);
268		if (ret < 0)
269			break;
270		cond_resched();
271	}
272
273	return ret;
274}
275
276static int lo_read_simple(struct loop_device *lo, struct request *rq,
277		loff_t pos)
278{
279	struct bio_vec bvec;
280	struct req_iterator iter;
281	struct iov_iter i;
282	ssize_t len;
283
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);
287		if (len < 0)
288			return len;
289
290		flush_dcache_page(bvec.bv_page);
291
292		if (len != bvec.bv_len) {
293			struct bio *bio;
294
295			__rq_for_each_bio(bio, rq)
296				zero_fill_bio(bio);
297			break;
298		}
299		cond_resched();
300	}
301
302	return 0;
303}
304
305static int lo_fallocate(struct loop_device *lo, struct request *rq, loff_t pos,
306			int mode)
307{
308	/*
309	 * We use fallocate to manipulate the space mappings used by the image
310	 * a.k.a. discard/zerorange.
311	 */
312	struct file *file = lo->lo_backing_file;
313	int ret;
314
315	mode |= FALLOC_FL_KEEP_SIZE;
316
317	if (!bdev_max_discard_sectors(lo->lo_device))
318		return -EOPNOTSUPP;
319
320	ret = file->f_op->fallocate(file, mode, pos, blk_rq_bytes(rq));
321	if (unlikely(ret && ret != -EINVAL && ret != -EOPNOTSUPP))
322		return -EIO;
323	return ret;
324}
325
326static int lo_req_flush(struct loop_device *lo, struct request *rq)
327{
328	int ret = vfs_fsync(lo->lo_backing_file, 0);
329	if (unlikely(ret && ret != -EINVAL))
330		ret = -EIO;
331
332	return ret;
333}
334
335static void lo_complete_rq(struct request *rq)
336{
337	struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
338	blk_status_t ret = BLK_STS_OK;
339
340	if (!cmd->use_aio || cmd->ret < 0 || cmd->ret == blk_rq_bytes(rq) ||
341	    req_op(rq) != REQ_OP_READ) {
342		if (cmd->ret < 0)
343			ret = errno_to_blk_status(cmd->ret);
344		goto end_io;
345	}
346
347	/*
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.
350	 */
351	if (cmd->ret) {
352		blk_update_request(rq, BLK_STS_OK, cmd->ret);
353		cmd->ret = 0;
354		blk_mq_requeue_request(rq, true);
355	} else {
356		if (cmd->use_aio) {
357			struct bio *bio = rq->bio;
358
359			while (bio) {
360				zero_fill_bio(bio);
361				bio = bio->bi_next;
362			}
363		}
364		ret = BLK_STS_IOERR;
365end_io:
366		blk_mq_end_request(rq, ret);
367	}
368}
369
370static void lo_rw_aio_do_completion(struct loop_cmd *cmd)
371{
372	struct request *rq = blk_mq_rq_from_pdu(cmd);
373
374	if (!atomic_dec_and_test(&cmd->ref))
375		return;
376	kfree(cmd->bvec);
377	cmd->bvec = NULL;
378	if (likely(!blk_should_fake_timeout(rq->q)))
379		blk_mq_complete_request(rq);
380}
381
382static void lo_rw_aio_complete(struct kiocb *iocb, long ret)
383{
384	struct loop_cmd *cmd = container_of(iocb, struct loop_cmd, iocb);
385
386	cmd->ret = ret;
387	lo_rw_aio_do_completion(cmd);
388}
389
390static int lo_rw_aio(struct loop_device *lo, struct loop_cmd *cmd,
391		     loff_t pos, int rw)
392{
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;
399	struct bio_vec tmp;
400	unsigned int offset;
401	int nr_bvec = 0;
402	int ret;
403
404	rq_for_each_bvec(tmp, rq, rq_iter)
405		nr_bvec++;
406
407	if (rq->bio != rq->biotail) {
408
409		bvec = kmalloc_array(nr_bvec, sizeof(struct bio_vec),
410				     GFP_NOIO);
411		if (!bvec)
412			return -EIO;
413		cmd->bvec = bvec;
414
415		/*
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.
420		 */
421		rq_for_each_bvec(tmp, rq, rq_iter) {
422			*bvec = tmp;
423			bvec++;
424		}
425		bvec = cmd->bvec;
426		offset = 0;
427	} else {
428		/*
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
432		 */
433		offset = bio->bi_iter.bi_bvec_done;
434		bvec = __bvec_iter_bvec(bio->bi_io_vec, bio->bi_iter);
435	}
436	atomic_set(&cmd->ref, 2);
437
438	iov_iter_bvec(&iter, rw, bvec, nr_bvec, blk_rq_bytes(rq));
439	iter.iov_offset = offset;
440
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);
446
447	if (rw == ITER_SOURCE)
448		ret = call_write_iter(file, &cmd->iocb, &iter);
449	else
450		ret = call_read_iter(file, &cmd->iocb, &iter);
451
452	lo_rw_aio_do_completion(cmd);
453
454	if (ret != -EIOCBQUEUED)
455		lo_rw_aio_complete(&cmd->iocb, ret);
456	return 0;
457}
458
459static int do_req_filebacked(struct loop_device *lo, struct request *rq)
460{
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;
463
464	/*
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().
472	 */
473	switch (req_op(rq)) {
474	case REQ_OP_FLUSH:
475		return lo_req_flush(lo, rq);
476	case REQ_OP_WRITE_ZEROES:
477		/*
478		 * If the caller doesn't want deallocation, call zeroout to
479		 * write zeroes the range.  Otherwise, punch them out.
480		 */
481		return lo_fallocate(lo, rq, pos,
482			(rq->cmd_flags & REQ_NOUNMAP) ?
483				FALLOC_FL_ZERO_RANGE :
484				FALLOC_FL_PUNCH_HOLE);
485	case REQ_OP_DISCARD:
486		return lo_fallocate(lo, rq, pos, FALLOC_FL_PUNCH_HOLE);
487	case REQ_OP_WRITE:
488		if (cmd->use_aio)
489			return lo_rw_aio(lo, cmd, pos, ITER_SOURCE);
490		else
491			return lo_write_simple(lo, rq, pos);
492	case REQ_OP_READ:
493		if (cmd->use_aio)
494			return lo_rw_aio(lo, cmd, pos, ITER_DEST);
495		else
496			return lo_read_simple(lo, rq, pos);
497	default:
498		WARN_ON_ONCE(1);
499		return -EIO;
500	}
501}
502
503static inline void loop_update_dio(struct loop_device *lo)
504{
505	__loop_update_dio(lo, (lo->lo_backing_file->f_flags & O_DIRECT) |
506				lo->use_dio);
507}
508
509static void loop_reread_partitions(struct loop_device *lo)
510{
511	int rc;
512
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);
516	if (rc)
517		pr_warn("%s: partition scan of loop%d (%s) failed (rc=%d)\n",
518			__func__, lo->lo_number, lo->lo_file_name, rc);
519}
520
521static inline int is_loop_device(struct file *file)
522{
523	struct inode *i = file->f_mapping->host;
524
525	return i && S_ISBLK(i->i_mode) && imajor(i) == LOOP_MAJOR;
526}
527
528static int loop_validate_file(struct file *file, struct block_device *bdev)
529{
530	struct inode	*inode = file->f_mapping->host;
531	struct file	*f = file;
532
533	/* Avoid recursion */
534	while (is_loop_device(f)) {
535		struct loop_device *l;
536
537		lockdep_assert_held(&loop_validate_mutex);
538		if (f->f_mapping->host->i_rdev == bdev->bd_dev)
539			return -EBADF;
540
541		l = I_BDEV(f->f_mapping->host)->bd_disk->private_data;
542		if (l->lo_state != Lo_bound)
543			return -EINVAL;
544		/* Order wrt setting lo->lo_backing_file in loop_configure(). */
545		rmb();
546		f = l->lo_backing_file;
547	}
548	if (!S_ISREG(inode->i_mode) && !S_ISBLK(inode->i_mode))
549		return -EINVAL;
550	return 0;
551}
552
553/*
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.
560 */
561static int loop_change_fd(struct loop_device *lo, struct block_device *bdev,
562			  unsigned int arg)
563{
564	struct file *file = fget(arg);
565	struct file *old_file;
566	int error;
567	bool partscan;
568	bool is_loop;
569
570	if (!file)
571		return -EBADF;
572
573	/* suppress uevents while reconfiguring the device */
574	dev_set_uevent_suppress(disk_to_dev(lo->lo_disk), 1);
575
576	is_loop = is_loop_device(file);
577	error = loop_global_lock_killable(lo, is_loop);
578	if (error)
579		goto out_putf;
580	error = -ENXIO;
581	if (lo->lo_state != Lo_bound)
582		goto out_err;
583
584	/* the loop device has to be read-only */
585	error = -EINVAL;
586	if (!(lo->lo_flags & LO_FLAGS_READ_ONLY))
587		goto out_err;
588
589	error = loop_validate_file(file, bdev);
590	if (error)
591		goto out_err;
592
593	old_file = lo->lo_backing_file;
594
595	error = -EINVAL;
596
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))
599		goto out_err;
600
601	/* and ... switch */
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));
609	loop_update_dio(lo);
610	blk_mq_unfreeze_queue(lo->lo_queue);
611	partscan = lo->lo_flags & LO_FLAGS_PARTSCAN;
612	loop_global_unlock(lo, is_loop);
613
614	/*
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.
617	 */
618	if (!is_loop) {
619		mutex_lock(&loop_validate_mutex);
620		mutex_unlock(&loop_validate_mutex);
621	}
622	/*
623	 * We must drop file reference outside of lo_mutex as dropping
624	 * the file ref can take open_mutex which creates circular locking
625	 * dependency.
626	 */
627	fput(old_file);
628	if (partscan)
629		loop_reread_partitions(lo);
630
631	error = 0;
632done:
633	/* enable and uncork uevent now that we are done */
634	dev_set_uevent_suppress(disk_to_dev(lo->lo_disk), 0);
635	return error;
636
637out_err:
638	loop_global_unlock(lo, is_loop);
639out_putf:
640	fput(file);
641	goto done;
642}
643
644/* loop sysfs attributes */
645
646static ssize_t loop_attr_show(struct device *dev, char *page,
647			      ssize_t (*callback)(struct loop_device *, char *))
648{
649	struct gendisk *disk = dev_to_disk(dev);
650	struct loop_device *lo = disk->private_data;
651
652	return callback(lo, page);
653}
654
655#define LOOP_ATTR_RO(_name)						\
656static ssize_t loop_attr_##_name##_show(struct loop_device *, char *);	\
657static ssize_t loop_attr_do_show_##_name(struct device *d,		\
658				struct device_attribute *attr, char *b)	\
659{									\
660	return loop_attr_show(d, b, loop_attr_##_name##_show);		\
661}									\
662static struct device_attribute loop_attr_##_name =			\
663	__ATTR(_name, 0444, loop_attr_do_show_##_name, NULL);
664
665static ssize_t loop_attr_backing_file_show(struct loop_device *lo, char *buf)
666{
667	ssize_t ret;
668	char *p = NULL;
669
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);
674
675	if (IS_ERR_OR_NULL(p))
676		ret = PTR_ERR(p);
677	else {
678		ret = strlen(p);
679		memmove(buf, p, ret);
680		buf[ret++] = '\n';
681		buf[ret] = 0;
682	}
683
684	return ret;
685}
686
687static ssize_t loop_attr_offset_show(struct loop_device *lo, char *buf)
688{
689	return sysfs_emit(buf, "%llu\n", (unsigned long long)lo->lo_offset);
690}
691
692static ssize_t loop_attr_sizelimit_show(struct loop_device *lo, char *buf)
693{
694	return sysfs_emit(buf, "%llu\n", (unsigned long long)lo->lo_sizelimit);
695}
696
697static ssize_t loop_attr_autoclear_show(struct loop_device *lo, char *buf)
698{
699	int autoclear = (lo->lo_flags & LO_FLAGS_AUTOCLEAR);
700
701	return sysfs_emit(buf, "%s\n", autoclear ? "1" : "0");
702}
703
704static ssize_t loop_attr_partscan_show(struct loop_device *lo, char *buf)
705{
706	int partscan = (lo->lo_flags & LO_FLAGS_PARTSCAN);
707
708	return sysfs_emit(buf, "%s\n", partscan ? "1" : "0");
709}
710
711static ssize_t loop_attr_dio_show(struct loop_device *lo, char *buf)
712{
713	int dio = (lo->lo_flags & LO_FLAGS_DIRECT_IO);
714
715	return sysfs_emit(buf, "%s\n", dio ? "1" : "0");
716}
717
718LOOP_ATTR_RO(backing_file);
719LOOP_ATTR_RO(offset);
720LOOP_ATTR_RO(sizelimit);
721LOOP_ATTR_RO(autoclear);
722LOOP_ATTR_RO(partscan);
723LOOP_ATTR_RO(dio);
724
725static 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,
731	&loop_attr_dio.attr,
732	NULL,
733};
734
735static struct attribute_group loop_attribute_group = {
736	.name = "loop",
737	.attrs= loop_attrs,
738};
739
740static void loop_sysfs_init(struct loop_device *lo)
741{
742	lo->sysfs_inited = !sysfs_create_group(&disk_to_dev(lo->lo_disk)->kobj,
743						&loop_attribute_group);
744}
745
746static void loop_sysfs_exit(struct loop_device *lo)
747{
748	if (lo->sysfs_inited)
749		sysfs_remove_group(&disk_to_dev(lo->lo_disk)->kobj,
750				   &loop_attribute_group);
751}
752
753static void loop_config_discard(struct loop_device *lo,
754		struct queue_limits *lim)
755{
756	struct file *file = lo->lo_backing_file;
757	struct inode *inode = file->f_mapping->host;
758	u32 granularity = 0, max_discard_sectors = 0;
759	struct kstatfs sbuf;
760
761	/*
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.
767	 */
768	if (S_ISBLK(inode->i_mode)) {
769		struct request_queue *backingq = bdev_get_queue(I_BDEV(inode));
770
771		max_discard_sectors = backingq->limits.max_write_zeroes_sectors;
772		granularity = bdev_discard_granularity(I_BDEV(inode)) ?:
773			queue_physical_block_size(backingq);
774
775	/*
776	 * We use punch hole to reclaim the free space used by the
777	 * image a.k.a. discard.
778	 */
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;
782	}
783
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;
788	else
789		lim->discard_granularity = 0;
790}
791
792struct loop_worker {
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;
800};
801
802static void loop_workfn(struct work_struct *work);
803
804#ifdef CONFIG_BLK_CGROUP
805static inline int queue_on_root_worker(struct cgroup_subsys_state *css)
806{
807	return !css || css == blkcg_root_css;
808}
809#else
810static inline int queue_on_root_worker(struct cgroup_subsys_state *css)
811{
812	return !css;
813}
814#endif
815
816static void loop_queue_work(struct loop_device *lo, struct loop_cmd *cmd)
817{
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;
822
823	spin_lock_irq(&lo->lo_work_lock);
824
825	if (queue_on_root_worker(cmd->blkcg_css))
826		goto queue_work;
827
828	node = &lo->worker_tree.rb_node;
829
830	while (*node) {
831		parent = *node;
832		cur_worker = container_of(*node, struct loop_worker, rb_node);
833		if (cur_worker->blkcg_css == cmd->blkcg_css) {
834			worker = cur_worker;
835			break;
836		} else if ((long)cur_worker->blkcg_css < (long)cmd->blkcg_css) {
837			node = &(*node)->rb_left;
838		} else {
839			node = &(*node)->rb_right;
840		}
841	}
842	if (worker)
843		goto queue_work;
844
845	worker = kzalloc(sizeof(struct loop_worker), GFP_NOWAIT | __GFP_NOWARN);
846	/*
847	 * In the event we cannot allocate a worker, just queue on the
848	 * rootcg worker and issue the I/O as the rootcg
849	 */
850	if (!worker) {
851		cmd->blkcg_css = NULL;
852		if (cmd->memcg_css)
853			css_put(cmd->memcg_css);
854		cmd->memcg_css = NULL;
855		goto queue_work;
856	}
857
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);
863	worker->lo = lo;
864	rb_link_node(&worker->rb_node, parent, node);
865	rb_insert_color(&worker->rb_node, &lo->worker_tree);
866queue_work:
867	if (worker) {
868		/*
869		 * We need to remove from the idle list here while
870		 * holding the lock so that the idle timer doesn't
871		 * free the worker
872		 */
873		if (!list_empty(&worker->idle_list))
874			list_del_init(&worker->idle_list);
875		work = &worker->work;
876		cmd_list = &worker->cmd_list;
877	} else {
878		work = &lo->rootcg_work;
879		cmd_list = &lo->rootcg_cmd_list;
880	}
881	list_add_tail(&cmd->list_entry, cmd_list);
882	queue_work(lo->workqueue, work);
883	spin_unlock_irq(&lo->lo_work_lock);
884}
885
886static void loop_set_timer(struct loop_device *lo)
887{
888	timer_reduce(&lo->timer, jiffies + LOOP_IDLE_WORKER_TIMEOUT);
889}
890
891static void loop_free_idle_workers(struct loop_device *lo, bool delete_all)
892{
893	struct loop_worker *pos, *worker;
894
895	spin_lock_irq(&lo->lo_work_lock);
896	list_for_each_entry_safe(worker, pos, &lo->idle_worker_list,
897				idle_list) {
898		if (!delete_all &&
899		    time_is_after_jiffies(worker->last_ran_at +
900					  LOOP_IDLE_WORKER_TIMEOUT))
901			break;
902		list_del(&worker->idle_list);
903		rb_erase(&worker->rb_node, &lo->worker_tree);
904		css_put(worker->blkcg_css);
905		kfree(worker);
906	}
907	if (!list_empty(&lo->idle_worker_list))
908		loop_set_timer(lo);
909	spin_unlock_irq(&lo->lo_work_lock);
910}
911
912static void loop_free_idle_workers_timer(struct timer_list *timer)
913{
914	struct loop_device *lo = container_of(timer, struct loop_device, timer);
915
916	return loop_free_idle_workers(lo, false);
917}
918
919static void loop_update_rotational(struct loop_device *lo)
920{
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;
925	bool nonrot = true;
926
927	/* not all filesystems (e.g. tmpfs) have a sb->s_bdev */
928	if (file_bdev)
929		nonrot = bdev_nonrot(file_bdev);
930
931	if (nonrot)
932		blk_queue_flag_set(QUEUE_FLAG_NONROT, q);
933	else
934		blk_queue_flag_clear(QUEUE_FLAG_NONROT, q);
935}
936
937/**
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
941 *
942 * Configures the loop device parameters according to the passed
943 * in loop_info64 configuration.
944 */
945static int
946loop_set_status_from_info(struct loop_device *lo,
947			  const struct loop_info64 *info)
948{
949	if ((unsigned int) info->lo_encrypt_key_size > LO_KEY_SIZE)
950		return -EINVAL;
951
952	switch (info->lo_encrypt_type) {
953	case LO_CRYPT_NONE:
954		break;
955	case LO_CRYPT_XOR:
956		pr_warn("support for the xor transformation has been removed.\n");
957		return -EINVAL;
958	case LO_CRYPT_CRYPTOAPI:
959		pr_warn("support for cryptoloop has been removed.  Use dm-crypt instead.\n");
960		return -EINVAL;
961	default:
962		return -EINVAL;
963	}
964
965	/* Avoid assigning overflow values */
966	if (info->lo_offset > LLONG_MAX || info->lo_sizelimit > LLONG_MAX)
967		return -EOVERFLOW;
968
969	lo->lo_offset = info->lo_offset;
970	lo->lo_sizelimit = info->lo_sizelimit;
971
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;
975	return 0;
976}
977
978static int loop_reconfigure_limits(struct loop_device *lo, unsigned short bsize,
979		bool update_discard_settings)
980{
981	struct queue_limits lim;
982
983	lim = queue_limits_start_update(lo->lo_queue);
984	lim.logical_block_size = bsize;
985	lim.physical_block_size = bsize;
986	lim.io_min = bsize;
987	if (update_discard_settings)
988		loop_config_discard(lo, &lim);
989	return queue_limits_commit_update(lo->lo_queue, &lim);
990}
991
992static int loop_configure(struct loop_device *lo, blk_mode_t mode,
993			  struct block_device *bdev,
994			  const struct loop_config *config)
995{
996	struct file *file = fget(config->fd);
997	struct inode *inode;
998	struct address_space *mapping;
999	int error;
1000	loff_t size;
1001	bool partscan;
1002	unsigned short bsize;
1003	bool is_loop;
1004
1005	if (!file)
1006		return -EBADF;
1007	is_loop = is_loop_device(file);
1008
1009	/* This is safe, since we have a reference from open(). */
1010	__module_get(THIS_MODULE);
1011
1012	/*
1013	 * If we don't hold exclusive handle for the device, upgrade to it
1014	 * here to avoid changing device under exclusive owner.
1015	 */
1016	if (!(mode & BLK_OPEN_EXCL)) {
1017		error = bd_prepare_to_claim(bdev, loop_configure, NULL);
1018		if (error)
1019			goto out_putf;
1020	}
1021
1022	error = loop_global_lock_killable(lo, is_loop);
1023	if (error)
1024		goto out_bdev;
1025
1026	error = -EBUSY;
1027	if (lo->lo_state != Lo_unbound)
1028		goto out_unlock;
1029
1030	error = loop_validate_file(file, bdev);
1031	if (error)
1032		goto out_unlock;
1033
1034	mapping = file->f_mapping;
1035	inode = mapping->host;
1036
1037	if ((config->info.lo_flags & ~LOOP_CONFIGURE_SETTABLE_FLAGS) != 0) {
1038		error = -EINVAL;
1039		goto out_unlock;
1040	}
1041
1042	if (config->block_size) {
1043		error = blk_validate_block_size(config->block_size);
1044		if (error)
1045			goto out_unlock;
1046	}
1047
1048	error = loop_set_status_from_info(lo, &config->info);
1049	if (error)
1050		goto out_unlock;
1051
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;
1055
1056	if (!lo->workqueue) {
1057		lo->workqueue = alloc_workqueue("loop%d",
1058						WQ_UNBOUND | WQ_FREEZABLE,
1059						0, lo->lo_number);
1060		if (!lo->workqueue) {
1061			error = -ENOMEM;
1062			goto out_unlock;
1063		}
1064	}
1065
1066	/* suppress uevents while reconfiguring the device */
1067	dev_set_uevent_suppress(disk_to_dev(lo->lo_disk), 1);
1068
1069	disk_force_media_change(lo->lo_disk);
1070	set_disk_ro(lo->lo_disk, (lo->lo_flags & LO_FLAGS_READ_ONLY) != 0);
1071
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));
1077
1078	if (!(lo->lo_flags & LO_FLAGS_READ_ONLY) && file->f_op->fsync)
1079		blk_queue_write_cache(lo->lo_queue, true, false);
1080
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);
1086	else
1087		bsize = 512;
1088
1089	error = loop_reconfigure_limits(lo, bsize, true);
1090	if (WARN_ON_ONCE(error))
1091		goto out_unlock;
1092
1093	loop_update_rotational(lo);
1094	loop_update_dio(lo);
1095	loop_sysfs_init(lo);
1096
1097	size = get_loop_size(lo, file);
1098	loop_set_size(lo, size);
1099
1100	/* Order wrt reading lo_state in loop_validate_file(). */
1101	wmb();
1102
1103	lo->lo_state = Lo_bound;
1104	if (part_shift)
1105		lo->lo_flags |= LO_FLAGS_PARTSCAN;
1106	partscan = lo->lo_flags & LO_FLAGS_PARTSCAN;
1107	if (partscan)
1108		clear_bit(GD_SUPPRESS_PART_SCAN, &lo->lo_disk->state);
1109
1110	/* enable and uncork uevent now that we are done */
1111	dev_set_uevent_suppress(disk_to_dev(lo->lo_disk), 0);
1112
1113	loop_global_unlock(lo, is_loop);
1114	if (partscan)
1115		loop_reread_partitions(lo);
1116
1117	if (!(mode & BLK_OPEN_EXCL))
1118		bd_abort_claiming(bdev, loop_configure);
1119
1120	return 0;
1121
1122out_unlock:
1123	loop_global_unlock(lo, is_loop);
1124out_bdev:
1125	if (!(mode & BLK_OPEN_EXCL))
1126		bd_abort_claiming(bdev, loop_configure);
1127out_putf:
1128	fput(file);
1129	/* This is safe: open() is still holding a reference. */
1130	module_put(THIS_MODULE);
1131	return error;
1132}
1133
1134static void __loop_clr_fd(struct loop_device *lo, bool release)
1135{
1136	struct file *filp;
1137	gfp_t gfp = lo->old_gfp_mask;
1138
1139	if (test_bit(QUEUE_FLAG_WC, &lo->lo_queue->queue_flags))
1140		blk_queue_write_cache(lo->lo_queue, false, false);
1141
1142	/*
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.
1146	 */
1147	if (!release)
1148		blk_mq_freeze_queue(lo->lo_queue);
1149
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);
1154
1155	lo->lo_device = NULL;
1156	lo->lo_offset = 0;
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);
1167	if (!release)
1168		blk_mq_unfreeze_queue(lo->lo_queue);
1169
1170	disk_force_media_change(lo->lo_disk);
1171
1172	if (lo->lo_flags & LO_FLAGS_PARTSCAN) {
1173		int err;
1174
1175		/*
1176		 * open_mutex has been held already in release path, so don't
1177		 * acquire it if this function is called in such case.
1178		 *
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.
1182		 */
1183		if (!release)
1184			mutex_lock(&lo->lo_disk->open_mutex);
1185		err = bdev_disk_changed(lo->lo_disk, false);
1186		if (!release)
1187			mutex_unlock(&lo->lo_disk->open_mutex);
1188		if (err)
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 */
1192	}
1193
1194	/*
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.
1199	 */
1200	lo->lo_flags = 0;
1201	if (!part_shift)
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);
1206
1207	/*
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.
1211	 */
1212	fput(filp);
1213}
1214
1215static int loop_clr_fd(struct loop_device *lo)
1216{
1217	int err;
1218
1219	/*
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.
1222	 *
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
1226	 * loop device.
1227	 */
1228	err = loop_global_lock_killable(lo, true);
1229	if (err)
1230		return err;
1231	if (lo->lo_state != Lo_bound) {
1232		loop_global_unlock(lo, true);
1233		return -ENXIO;
1234	}
1235	/*
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.
1244	 */
1245	if (disk_openers(lo->lo_disk) > 1) {
1246		lo->lo_flags |= LO_FLAGS_AUTOCLEAR;
1247		loop_global_unlock(lo, true);
1248		return 0;
1249	}
1250	lo->lo_state = Lo_rundown;
1251	loop_global_unlock(lo, true);
1252
1253	__loop_clr_fd(lo, false);
1254	return 0;
1255}
1256
1257static int
1258loop_set_status(struct loop_device *lo, const struct loop_info64 *info)
1259{
1260	int err;
1261	int prev_lo_flags;
1262	bool partscan = false;
1263	bool size_changed = false;
1264
1265	err = mutex_lock_killable(&lo->lo_mutex);
1266	if (err)
1267		return err;
1268	if (lo->lo_state != Lo_bound) {
1269		err = -ENXIO;
1270		goto out_unlock;
1271	}
1272
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);
1278	}
1279
1280	/* I/O need to be drained during transfer transition */
1281	blk_mq_freeze_queue(lo->lo_queue);
1282
1283	prev_lo_flags = lo->lo_flags;
1284
1285	err = loop_set_status_from_info(lo, info);
1286	if (err)
1287		goto out_unfreeze;
1288
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;
1295
1296	if (size_changed) {
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);
1300	}
1301
1302	/* update dio if lo_offset or transfer is changed */
1303	__loop_update_dio(lo, lo->use_dio);
1304
1305out_unfreeze:
1306	blk_mq_unfreeze_queue(lo->lo_queue);
1307
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);
1311		partscan = true;
1312	}
1313out_unlock:
1314	mutex_unlock(&lo->lo_mutex);
1315	if (partscan)
1316		loop_reread_partitions(lo);
1317
1318	return err;
1319}
1320
1321static int
1322loop_get_status(struct loop_device *lo, struct loop_info64 *info)
1323{
1324	struct path path;
1325	struct kstat stat;
1326	int ret;
1327
1328	ret = mutex_lock_killable(&lo->lo_mutex);
1329	if (ret)
1330		return ret;
1331	if (lo->lo_state != Lo_bound) {
1332		mutex_unlock(&lo->lo_mutex);
1333		return -ENXIO;
1334	}
1335
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);
1342
1343	/* Drop lo_mutex while we call into the filesystem. */
1344	path = lo->lo_backing_file->f_path;
1345	path_get(&path);
1346	mutex_unlock(&lo->lo_mutex);
1347	ret = vfs_getattr(&path, &stat, STATX_INO, AT_STATX_SYNC_AS_STAT);
1348	if (!ret) {
1349		info->lo_device = huge_encode_dev(stat.dev);
1350		info->lo_inode = stat.ino;
1351		info->lo_rdevice = huge_encode_dev(stat.rdev);
1352	}
1353	path_put(&path);
1354	return ret;
1355}
1356
1357static void
1358loop_info64_from_old(const struct loop_info *info, struct loop_info64 *info64)
1359{
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);
1369}
1370
1371static int
1372loop_info64_to_old(const struct loop_info64 *info64, struct loop_info *info)
1373{
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);
1382
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)
1388		return -EOVERFLOW;
1389
1390	return 0;
1391}
1392
1393static int
1394loop_set_status_old(struct loop_device *lo, const struct loop_info __user *arg)
1395{
1396	struct loop_info info;
1397	struct loop_info64 info64;
1398
1399	if (copy_from_user(&info, arg, sizeof (struct loop_info)))
1400		return -EFAULT;
1401	loop_info64_from_old(&info, &info64);
1402	return loop_set_status(lo, &info64);
1403}
1404
1405static int
1406loop_set_status64(struct loop_device *lo, const struct loop_info64 __user *arg)
1407{
1408	struct loop_info64 info64;
1409
1410	if (copy_from_user(&info64, arg, sizeof (struct loop_info64)))
1411		return -EFAULT;
1412	return loop_set_status(lo, &info64);
1413}
1414
1415static int
1416loop_get_status_old(struct loop_device *lo, struct loop_info __user *arg) {
1417	struct loop_info info;
1418	struct loop_info64 info64;
1419	int err;
1420
1421	if (!arg)
1422		return -EINVAL;
1423	err = loop_get_status(lo, &info64);
1424	if (!err)
1425		err = loop_info64_to_old(&info64, &info);
1426	if (!err && copy_to_user(arg, &info, sizeof(info)))
1427		err = -EFAULT;
1428
1429	return err;
1430}
1431
1432static int
1433loop_get_status64(struct loop_device *lo, struct loop_info64 __user *arg) {
1434	struct loop_info64 info64;
1435	int err;
1436
1437	if (!arg)
1438		return -EINVAL;
1439	err = loop_get_status(lo, &info64);
1440	if (!err && copy_to_user(arg, &info64, sizeof(info64)))
1441		err = -EFAULT;
1442
1443	return err;
1444}
1445
1446static int loop_set_capacity(struct loop_device *lo)
1447{
1448	loff_t size;
1449
1450	if (unlikely(lo->lo_state != Lo_bound))
1451		return -ENXIO;
1452
1453	size = get_loop_size(lo, lo->lo_backing_file);
1454	loop_set_size(lo, size);
1455
1456	return 0;
1457}
1458
1459static int loop_set_dio(struct loop_device *lo, unsigned long arg)
1460{
1461	int error = -ENXIO;
1462	if (lo->lo_state != Lo_bound)
1463		goto out;
1464
1465	__loop_update_dio(lo, !!arg);
1466	if (lo->use_dio == !!arg)
1467		return 0;
1468	error = -EINVAL;
1469 out:
1470	return error;
1471}
1472
1473static int loop_set_block_size(struct loop_device *lo, unsigned long arg)
1474{
1475	int err = 0;
1476
1477	if (lo->lo_state != Lo_bound)
1478		return -ENXIO;
1479
1480	err = blk_validate_block_size(arg);
1481	if (err)
1482		return err;
1483
1484	if (lo->lo_queue->limits.logical_block_size == arg)
1485		return 0;
1486
1487	sync_blockdev(lo->lo_device);
1488	invalidate_bdev(lo->lo_device);
1489
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);
1494
1495	return err;
1496}
1497
1498static int lo_simple_ioctl(struct loop_device *lo, unsigned int cmd,
1499			   unsigned long arg)
1500{
1501	int err;
1502
1503	err = mutex_lock_killable(&lo->lo_mutex);
1504	if (err)
1505		return err;
1506	switch (cmd) {
1507	case LOOP_SET_CAPACITY:
1508		err = loop_set_capacity(lo);
1509		break;
1510	case LOOP_SET_DIRECT_IO:
1511		err = loop_set_dio(lo, arg);
1512		break;
1513	case LOOP_SET_BLOCK_SIZE:
1514		err = loop_set_block_size(lo, arg);
1515		break;
1516	default:
1517		err = -EINVAL;
1518	}
1519	mutex_unlock(&lo->lo_mutex);
1520	return err;
1521}
1522
1523static int lo_ioctl(struct block_device *bdev, blk_mode_t mode,
1524	unsigned int cmd, unsigned long arg)
1525{
1526	struct loop_device *lo = bdev->bd_disk->private_data;
1527	void __user *argp = (void __user *) arg;
1528	int err;
1529
1530	switch (cmd) {
1531	case LOOP_SET_FD: {
1532		/*
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.
1536		 */
1537		struct loop_config config;
1538
1539		memset(&config, 0, sizeof(config));
1540		config.fd = arg;
1541
1542		return loop_configure(lo, mode, bdev, &config);
1543	}
1544	case LOOP_CONFIGURE: {
1545		struct loop_config config;
1546
1547		if (copy_from_user(&config, argp, sizeof(config)))
1548			return -EFAULT;
1549
1550		return loop_configure(lo, mode, bdev, &config);
1551	}
1552	case LOOP_CHANGE_FD:
1553		return loop_change_fd(lo, bdev, arg);
1554	case LOOP_CLR_FD:
1555		return loop_clr_fd(lo);
1556	case LOOP_SET_STATUS:
1557		err = -EPERM;
1558		if ((mode & BLK_OPEN_WRITE) || capable(CAP_SYS_ADMIN))
1559			err = loop_set_status_old(lo, argp);
1560		break;
1561	case LOOP_GET_STATUS:
1562		return loop_get_status_old(lo, argp);
1563	case LOOP_SET_STATUS64:
1564		err = -EPERM;
1565		if ((mode & BLK_OPEN_WRITE) || capable(CAP_SYS_ADMIN))
1566			err = loop_set_status64(lo, argp);
1567		break;
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))
1574			return -EPERM;
1575		fallthrough;
1576	default:
1577		err = lo_simple_ioctl(lo, cmd, arg);
1578		break;
1579	}
1580
1581	return err;
1582}
1583
1584#ifdef CONFIG_COMPAT
1585struct 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];
1597	char		reserved[4];
1598};
1599
1600/*
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
1603 */
1604static noinline int
1605loop_info64_from_compat(const struct compat_loop_info __user *arg,
1606			struct loop_info64 *info64)
1607{
1608	struct compat_loop_info info;
1609
1610	if (copy_from_user(&info, arg, sizeof(info)))
1611		return -EFAULT;
1612
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);
1622	return 0;
1623}
1624
1625/*
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
1628 */
1629static noinline int
1630loop_info64_to_compat(const struct loop_info64 *info64,
1631		      struct compat_loop_info __user *arg)
1632{
1633	struct compat_loop_info info;
1634
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);
1643
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)
1649		return -EOVERFLOW;
1650
1651	if (copy_to_user(arg, &info, sizeof(info)))
1652		return -EFAULT;
1653	return 0;
1654}
1655
1656static int
1657loop_set_status_compat(struct loop_device *lo,
1658		       const struct compat_loop_info __user *arg)
1659{
1660	struct loop_info64 info64;
1661	int ret;
1662
1663	ret = loop_info64_from_compat(arg, &info64);
1664	if (ret < 0)
1665		return ret;
1666	return loop_set_status(lo, &info64);
1667}
1668
1669static int
1670loop_get_status_compat(struct loop_device *lo,
1671		       struct compat_loop_info __user *arg)
1672{
1673	struct loop_info64 info64;
1674	int err;
1675
1676	if (!arg)
1677		return -EINVAL;
1678	err = loop_get_status(lo, &info64);
1679	if (!err)
1680		err = loop_info64_to_compat(&info64, arg);
1681	return err;
1682}
1683
1684static int lo_compat_ioctl(struct block_device *bdev, blk_mode_t mode,
1685			   unsigned int cmd, unsigned long arg)
1686{
1687	struct loop_device *lo = bdev->bd_disk->private_data;
1688	int err;
1689
1690	switch(cmd) {
1691	case LOOP_SET_STATUS:
1692		err = loop_set_status_compat(lo,
1693			     (const struct compat_loop_info __user *)arg);
1694		break;
1695	case LOOP_GET_STATUS:
1696		err = loop_get_status_compat(lo,
1697				     (struct compat_loop_info __user *)arg);
1698		break;
1699	case LOOP_SET_CAPACITY:
1700	case LOOP_CLR_FD:
1701	case LOOP_GET_STATUS64:
1702	case LOOP_SET_STATUS64:
1703	case LOOP_CONFIGURE:
1704		arg = (unsigned long) compat_ptr(arg);
1705		fallthrough;
1706	case LOOP_SET_FD:
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);
1711		break;
1712	default:
1713		err = -ENOIOCTLCMD;
1714		break;
1715	}
1716	return err;
1717}
1718#endif
1719
1720static void lo_release(struct gendisk *disk)
1721{
1722	struct loop_device *lo = disk->private_data;
1723
1724	if (disk_openers(disk) > 0)
1725		return;
1726
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);
1731		/*
1732		 * In autoclear mode, stop the loop thread
1733		 * and remove configuration after last close.
1734		 */
1735		__loop_clr_fd(lo, true);
1736		return;
1737	}
1738	mutex_unlock(&lo->lo_mutex);
1739}
1740
1741static void lo_free_disk(struct gendisk *disk)
1742{
1743	struct loop_device *lo = disk->private_data;
1744
1745	if (lo->workqueue)
1746		destroy_workqueue(lo->workqueue);
1747	loop_free_idle_workers(lo, true);
1748	timer_shutdown_sync(&lo->timer);
1749	mutex_destroy(&lo->lo_mutex);
1750	kfree(lo);
1751}
1752
1753static const struct block_device_operations lo_fops = {
1754	.owner =	THIS_MODULE,
1755	.release =	lo_release,
1756	.ioctl =	lo_ioctl,
1757#ifdef CONFIG_COMPAT
1758	.compat_ioctl =	lo_compat_ioctl,
1759#endif
1760	.free_disk =	lo_free_disk,
1761};
1762
1763/*
1764 * And now the modules code and kernel interface.
1765 */
1766
1767/*
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.
1776 */
1777static int max_loop = CONFIG_BLK_DEV_LOOP_MIN_COUNT;
1778
1779#ifdef CONFIG_BLOCK_LEGACY_AUTOLOAD
1780static bool max_loop_specified;
1781
1782static int max_loop_param_set_int(const char *val,
1783				  const struct kernel_param *kp)
1784{
1785	int ret;
1786
1787	ret = param_set_int(val, kp);
1788	if (ret < 0)
1789		return ret;
1790
1791	max_loop_specified = true;
1792	return 0;
1793}
1794
1795static const struct kernel_param_ops max_loop_param_ops = {
1796	.set = max_loop_param_set_int,
1797	.get = param_get_int,
1798};
1799
1800module_param_cb(max_loop, &max_loop_param_ops, &max_loop, 0444);
1801MODULE_PARM_DESC(max_loop, "Maximum number of loop devices");
1802#else
1803module_param(max_loop, int, 0444);
1804MODULE_PARM_DESC(max_loop, "Initial number of loop devices");
1805#endif
1806
1807module_param(max_part, int, 0444);
1808MODULE_PARM_DESC(max_part, "Maximum number of partitions per loop device");
1809
1810static int hw_queue_depth = LOOP_DEFAULT_HW_Q_DEPTH;
1811
1812static int loop_set_hw_queue_depth(const char *s, const struct kernel_param *p)
1813{
1814	int qd, ret;
1815
1816	ret = kstrtoint(s, 0, &qd);
1817	if (ret < 0)
1818		return ret;
1819	if (qd < 1)
1820		return -EINVAL;
1821	hw_queue_depth = qd;
1822	return 0;
1823}
1824
1825static const struct kernel_param_ops loop_hw_qdepth_param_ops = {
1826	.set	= loop_set_hw_queue_depth,
1827	.get	= param_get_int,
1828};
1829
1830device_param_cb(hw_queue_depth, &loop_hw_qdepth_param_ops, &hw_queue_depth, 0444);
1831MODULE_PARM_DESC(hw_queue_depth, "Queue depth for each hardware queue. Default: " __stringify(LOOP_DEFAULT_HW_Q_DEPTH));
1832
1833MODULE_LICENSE("GPL");
1834MODULE_ALIAS_BLOCKDEV_MAJOR(LOOP_MAJOR);
1835
1836static blk_status_t loop_queue_rq(struct blk_mq_hw_ctx *hctx,
1837		const struct blk_mq_queue_data *bd)
1838{
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;
1842
1843	blk_mq_start_request(rq);
1844
1845	if (lo->lo_state != Lo_bound)
1846		return BLK_STS_IOERR;
1847
1848	switch (req_op(rq)) {
1849	case REQ_OP_FLUSH:
1850	case REQ_OP_DISCARD:
1851	case REQ_OP_WRITE_ZEROES:
1852		cmd->use_aio = false;
1853		break;
1854	default:
1855		cmd->use_aio = lo->use_dio;
1856		break;
1857	}
1858
1859	/* always use the first bio's css */
1860	cmd->blkcg_css = NULL;
1861	cmd->memcg_css = NULL;
1862#ifdef CONFIG_BLK_CGROUP
1863	if (rq->bio) {
1864		cmd->blkcg_css = bio_blkcg_css(rq->bio);
1865#ifdef CONFIG_MEMCG
1866		if (cmd->blkcg_css) {
1867			cmd->memcg_css =
1868				cgroup_get_e_css(cmd->blkcg_css->cgroup,
1869						&memory_cgrp_subsys);
1870		}
1871#endif
1872	}
1873#endif
1874	loop_queue_work(lo, cmd);
1875
1876	return BLK_STS_OK;
1877}
1878
1879static void loop_handle_cmd(struct loop_cmd *cmd)
1880{
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;
1886	int ret = 0;
1887	struct mem_cgroup *old_memcg = NULL;
1888	const bool use_aio = cmd->use_aio;
1889
1890	if (write && (lo->lo_flags & LO_FLAGS_READ_ONLY)) {
1891		ret = -EIO;
1892		goto failed;
1893	}
1894
1895	if (cmd_blkcg_css)
1896		kthread_associate_blkcg(cmd_blkcg_css);
1897	if (cmd_memcg_css)
1898		old_memcg = set_active_memcg(
1899			mem_cgroup_from_css(cmd_memcg_css));
1900
1901	/*
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.
1906	 */
1907	ret = do_req_filebacked(lo, rq);
1908
1909	if (cmd_blkcg_css)
1910		kthread_associate_blkcg(NULL);
1911
1912	if (cmd_memcg_css) {
1913		set_active_memcg(old_memcg);
1914		css_put(cmd_memcg_css);
1915	}
1916 failed:
1917	/* complete non-aio request */
1918	if (!use_aio || ret) {
1919		if (ret == -EOPNOTSUPP)
1920			cmd->ret = ret;
1921		else
1922			cmd->ret = ret ? -EIO : 0;
1923		if (likely(!blk_should_fake_timeout(rq->q)))
1924			blk_mq_complete_request(rq);
1925	}
1926}
1927
1928static void loop_process_work(struct loop_worker *worker,
1929			struct list_head *cmd_list, struct loop_device *lo)
1930{
1931	int orig_flags = current->flags;
1932	struct loop_cmd *cmd;
1933
1934	current->flags |= PF_LOCAL_THROTTLE | PF_MEMALLOC_NOIO;
1935	spin_lock_irq(&lo->lo_work_lock);
1936	while (!list_empty(cmd_list)) {
1937		cmd = container_of(
1938			cmd_list->next, struct loop_cmd, list_entry);
1939		list_del(cmd_list->next);
1940		spin_unlock_irq(&lo->lo_work_lock);
1941
1942		loop_handle_cmd(cmd);
1943		cond_resched();
1944
1945		spin_lock_irq(&lo->lo_work_lock);
1946	}
1947
1948	/*
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
1952	 */
1953	if (worker && !work_pending(&worker->work)) {
1954		worker->last_ran_at = jiffies;
1955		list_add_tail(&worker->idle_list, &lo->idle_worker_list);
1956		loop_set_timer(lo);
1957	}
1958	spin_unlock_irq(&lo->lo_work_lock);
1959	current->flags = orig_flags;
1960}
1961
1962static void loop_workfn(struct work_struct *work)
1963{
1964	struct loop_worker *worker =
1965		container_of(work, struct loop_worker, work);
1966	loop_process_work(worker, &worker->cmd_list, worker->lo);
1967}
1968
1969static void loop_rootcg_workfn(struct work_struct *work)
1970{
1971	struct loop_device *lo =
1972		container_of(work, struct loop_device, rootcg_work);
1973	loop_process_work(NULL, &lo->rootcg_cmd_list, lo);
1974}
1975
1976static const struct blk_mq_ops loop_mq_ops = {
1977	.queue_rq       = loop_queue_rq,
1978	.complete	= lo_complete_rq,
1979};
1980
1981static int loop_add(int i)
1982{
1983	struct queue_limits lim = {
1984		/*
1985		 * Random number picked from the historic block max_sectors cap.
1986		 */
1987		.max_hw_sectors		= 2560u,
1988	};
1989	struct loop_device *lo;
1990	struct gendisk *disk;
1991	int err;
1992
1993	err = -ENOMEM;
1994	lo = kzalloc(sizeof(*lo), GFP_KERNEL);
1995	if (!lo)
1996		goto out;
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;
2001
2002	err = mutex_lock_killable(&loop_ctl_mutex);
2003	if (err)
2004		goto out_free_dev;
2005
2006	/* allocate id, if @id >= 0, we're requesting that specific id */
2007	if (i >= 0) {
2008		err = idr_alloc(&loop_index_idr, lo, i, i + 1, GFP_KERNEL);
2009		if (err == -ENOSPC)
2010			err = -EEXIST;
2011	} else {
2012		err = idr_alloc(&loop_index_idr, lo, 0, 0, GFP_KERNEL);
2013	}
2014	mutex_unlock(&loop_ctl_mutex);
2015	if (err < 0)
2016		goto out_free_dev;
2017	i = err;
2018
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;
2027
2028	err = blk_mq_alloc_tag_set(&lo->tag_set);
2029	if (err)
2030		goto out_free_idr;
2031
2032	disk = lo->lo_disk = blk_mq_alloc_disk(&lo->tag_set, &lim, lo);
2033	if (IS_ERR(disk)) {
2034		err = PTR_ERR(disk);
2035		goto out_cleanup_tags;
2036	}
2037	lo->lo_queue = lo->lo_disk->queue;
2038
2039	/*
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.
2044	 */
2045	blk_queue_flag_set(QUEUE_FLAG_NOMERGES, lo->lo_queue);
2046
2047	/*
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
2054	 * used.
2055	 *
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.
2059	 *
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.
2064	 */
2065	if (!part_shift)
2066		set_bit(GD_SUPPRESS_PART_SCAN, &disk->state);
2067	mutex_init(&lo->lo_mutex);
2068	lo->lo_number		= i;
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);
2084	if (err)
2085		goto out_cleanup_disk;
2086
2087	/* Show this loop device. */
2088	mutex_lock(&loop_ctl_mutex);
2089	lo->idr_visible = true;
2090	mutex_unlock(&loop_ctl_mutex);
2091
2092	return i;
2093
2094out_cleanup_disk:
2095	put_disk(disk);
2096out_cleanup_tags:
2097	blk_mq_free_tag_set(&lo->tag_set);
2098out_free_idr:
2099	mutex_lock(&loop_ctl_mutex);
2100	idr_remove(&loop_index_idr, i);
2101	mutex_unlock(&loop_ctl_mutex);
2102out_free_dev:
2103	kfree(lo);
2104out:
2105	return err;
2106}
2107
2108static void loop_remove(struct loop_device *lo)
2109{
2110	/* Make this loop device unreachable from pathname. */
2111	del_gendisk(lo->lo_disk);
2112	blk_mq_free_tag_set(&lo->tag_set);
2113
2114	mutex_lock(&loop_ctl_mutex);
2115	idr_remove(&loop_index_idr, lo->lo_number);
2116	mutex_unlock(&loop_ctl_mutex);
2117
2118	put_disk(lo->lo_disk);
2119}
2120
2121#ifdef CONFIG_BLOCK_LEGACY_AUTOLOAD
2122static void loop_probe(dev_t dev)
2123{
2124	int idx = MINOR(dev) >> part_shift;
2125
2126	if (max_loop_specified && max_loop && idx >= max_loop)
2127		return;
2128	loop_add(idx);
2129}
2130#else
2131#define loop_probe NULL
2132#endif /* !CONFIG_BLOCK_LEGACY_AUTOLOAD */
2133
2134static int loop_control_remove(int idx)
2135{
2136	struct loop_device *lo;
2137	int ret;
2138
2139	if (idx < 0) {
2140		pr_warn_once("deleting an unspecified loop device is not supported.\n");
2141		return -EINVAL;
2142	}
2143
2144	/* Hide this loop device for serialization. */
2145	ret = mutex_lock_killable(&loop_ctl_mutex);
2146	if (ret)
2147		return ret;
2148	lo = idr_find(&loop_index_idr, idx);
2149	if (!lo || !lo->idr_visible)
2150		ret = -ENODEV;
2151	else
2152		lo->idr_visible = false;
2153	mutex_unlock(&loop_ctl_mutex);
2154	if (ret)
2155		return ret;
2156
2157	/* Check whether this loop device can be removed. */
2158	ret = mutex_lock_killable(&lo->lo_mutex);
2159	if (ret)
2160		goto mark_visible;
2161	if (lo->lo_state != Lo_unbound || disk_openers(lo->lo_disk) > 0) {
2162		mutex_unlock(&lo->lo_mutex);
2163		ret = -EBUSY;
2164		goto mark_visible;
2165	}
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);
2169
2170	loop_remove(lo);
2171	return 0;
2172
2173mark_visible:
2174	/* Show this loop device again. */
2175	mutex_lock(&loop_ctl_mutex);
2176	lo->idr_visible = true;
2177	mutex_unlock(&loop_ctl_mutex);
2178	return ret;
2179}
2180
2181static int loop_control_get_free(int idx)
2182{
2183	struct loop_device *lo;
2184	int id, ret;
2185
2186	ret = mutex_lock_killable(&loop_ctl_mutex);
2187	if (ret)
2188		return ret;
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)
2192			goto found;
2193	}
2194	mutex_unlock(&loop_ctl_mutex);
2195	return loop_add(-1);
2196found:
2197	mutex_unlock(&loop_ctl_mutex);
2198	return id;
2199}
2200
2201static long loop_control_ioctl(struct file *file, unsigned int cmd,
2202			       unsigned long parm)
2203{
2204	switch (cmd) {
2205	case LOOP_CTL_ADD:
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);
2211	default:
2212		return -ENOSYS;
2213	}
2214}
2215
2216static 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,
2222};
2223
2224static struct miscdevice loop_misc = {
2225	.minor		= LOOP_CTRL_MINOR,
2226	.name		= "loop-control",
2227	.fops		= &loop_ctl_fops,
2228};
2229
2230MODULE_ALIAS_MISCDEV(LOOP_CTRL_MINOR);
2231MODULE_ALIAS("devname:loop-control");
2232
2233static int __init loop_init(void)
2234{
2235	int i;
2236	int err;
2237
2238	part_shift = 0;
2239	if (max_part > 0) {
2240		part_shift = fls(max_part);
2241
2242		/*
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.
2246		 *
2247		 * Note that -1 is required because partition 0 is reserved
2248		 * for the whole disk.
2249		 */
2250		max_part = (1UL << part_shift) - 1;
2251	}
2252
2253	if ((1UL << part_shift) > DISK_MAX_PARTS) {
2254		err = -EINVAL;
2255		goto err_out;
2256	}
2257
2258	if (max_loop > 1UL << (MINORBITS - part_shift)) {
2259		err = -EINVAL;
2260		goto err_out;
2261	}
2262
2263	err = misc_register(&loop_misc);
2264	if (err < 0)
2265		goto err_out;
2266
2267
2268	if (__register_blkdev(LOOP_MAJOR, "loop", loop_probe)) {
2269		err = -EIO;
2270		goto misc_out;
2271	}
2272
2273	/* pre-create number of devices given by config or max_loop */
2274	for (i = 0; i < max_loop; i++)
2275		loop_add(i);
2276
2277	printk(KERN_INFO "loop: module loaded\n");
2278	return 0;
2279
2280misc_out:
2281	misc_deregister(&loop_misc);
2282err_out:
2283	return err;
2284}
2285
2286static void __exit loop_exit(void)
2287{
2288	struct loop_device *lo;
2289	int id;
2290
2291	unregister_blkdev(LOOP_MAJOR, "loop");
2292	misc_deregister(&loop_misc);
2293
2294	/*
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.
2299	 */
2300	idr_for_each_entry(&loop_index_idr, lo, id)
2301		loop_remove(lo);
2302
2303	idr_destroy(&loop_index_idr);
2304}
2305
2306module_init(loop_init);
2307module_exit(loop_exit);
2308
2309#ifndef MODULE
2310static int __init max_loop_setup(char *str)
2311{
2312	max_loop = simple_strtol(str, NULL, 0);
2313#ifdef CONFIG_BLOCK_LEGACY_AUTOLOAD
2314	max_loop_specified = true;
2315#endif
2316	return 1;
2317}
2318
2319__setup("max_loop=", max_loop_setup);
2320#endif
2321