xref: /openbmc/linux/drivers/block/loop.c (revision 47e96246)
11da177e4SLinus Torvalds /*
21da177e4SLinus Torvalds  *  linux/drivers/block/loop.c
31da177e4SLinus Torvalds  *
41da177e4SLinus Torvalds  *  Written by Theodore Ts'o, 3/29/93
51da177e4SLinus Torvalds  *
61da177e4SLinus Torvalds  * Copyright 1993 by Theodore Ts'o.  Redistribution of this file is
71da177e4SLinus Torvalds  * permitted under the GNU General Public License.
81da177e4SLinus Torvalds  *
91da177e4SLinus Torvalds  * DES encryption plus some minor changes by Werner Almesberger, 30-MAY-1993
101da177e4SLinus Torvalds  * more DES encryption plus IDEA encryption by Nicholas J. Leon, June 20, 1996
111da177e4SLinus Torvalds  *
121da177e4SLinus Torvalds  * Modularized and updated for 1.1.16 kernel - Mitch Dsouza 28th May 1994
131da177e4SLinus Torvalds  * Adapted for 1.3.59 kernel - Andries Brouwer, 1 Feb 1996
141da177e4SLinus Torvalds  *
151da177e4SLinus Torvalds  * Fixed do_loop_request() re-entrancy - Vincent.Renardias@waw.com Mar 20, 1997
161da177e4SLinus Torvalds  *
171da177e4SLinus Torvalds  * Added devfs support - Richard Gooch <rgooch@atnf.csiro.au> 16-Jan-1998
181da177e4SLinus Torvalds  *
191da177e4SLinus Torvalds  * Handle sparse backing files correctly - Kenn Humborg, Jun 28, 1998
201da177e4SLinus Torvalds  *
211da177e4SLinus Torvalds  * Loadable modules and other fixes by AK, 1998
221da177e4SLinus Torvalds  *
231da177e4SLinus Torvalds  * Make real block number available to downstream transfer functions, enables
241da177e4SLinus Torvalds  * CBC (and relatives) mode encryption requiring unique IVs per data block.
251da177e4SLinus Torvalds  * Reed H. Petty, rhp@draper.net
261da177e4SLinus Torvalds  *
271da177e4SLinus Torvalds  * Maximum number of loop devices now dynamic via max_loop module parameter.
281da177e4SLinus Torvalds  * Russell Kroll <rkroll@exploits.org> 19990701
291da177e4SLinus Torvalds  *
301da177e4SLinus Torvalds  * Maximum number of loop devices when compiled-in now selectable by passing
311da177e4SLinus Torvalds  * max_loop=<1-255> to the kernel on boot.
3296de0e25SJan Engelhardt  * Erik I. Bolsø, <eriki@himolde.no>, Oct 31, 1999
331da177e4SLinus Torvalds  *
341da177e4SLinus Torvalds  * Completely rewrite request handling to be make_request_fn style and
351da177e4SLinus Torvalds  * non blocking, pushing work to a helper thread. Lots of fixes from
361da177e4SLinus Torvalds  * Al Viro too.
371da177e4SLinus Torvalds  * Jens Axboe <axboe@suse.de>, Nov 2000
381da177e4SLinus Torvalds  *
391da177e4SLinus Torvalds  * Support up to 256 loop devices
401da177e4SLinus Torvalds  * Heinz Mauelshagen <mge@sistina.com>, Feb 2002
411da177e4SLinus Torvalds  *
421da177e4SLinus Torvalds  * Support for falling back on the write file operation when the address space
434e02ed4bSNick Piggin  * operations write_begin is not available on the backing filesystem.
441da177e4SLinus Torvalds  * Anton Altaparmakov, 16 Feb 2005
451da177e4SLinus Torvalds  *
461da177e4SLinus Torvalds  * Still To Fix:
471da177e4SLinus Torvalds  * - Advisory locking is ignored here.
481da177e4SLinus Torvalds  * - Should use an own CAP_* category instead of CAP_SYS_ADMIN
491da177e4SLinus Torvalds  *
501da177e4SLinus Torvalds  */
511da177e4SLinus Torvalds 
521da177e4SLinus Torvalds #include <linux/module.h>
531da177e4SLinus Torvalds #include <linux/moduleparam.h>
541da177e4SLinus Torvalds #include <linux/sched.h>
551da177e4SLinus Torvalds #include <linux/fs.h>
564ee60ec1SMatthew Wilcox (Oracle) #include <linux/pagemap.h>
571da177e4SLinus Torvalds #include <linux/file.h>
581da177e4SLinus Torvalds #include <linux/stat.h>
591da177e4SLinus Torvalds #include <linux/errno.h>
601da177e4SLinus Torvalds #include <linux/major.h>
611da177e4SLinus Torvalds #include <linux/wait.h>
621da177e4SLinus Torvalds #include <linux/blkdev.h>
631da177e4SLinus Torvalds #include <linux/blkpg.h>
641da177e4SLinus Torvalds #include <linux/init.h>
651da177e4SLinus Torvalds #include <linux/swap.h>
661da177e4SLinus Torvalds #include <linux/slab.h>
67863d5b82SDavid Howells #include <linux/compat.h>
681da177e4SLinus Torvalds #include <linux/suspend.h>
6983144186SRafael J. Wysocki #include <linux/freezer.h>
702a48fc0aSArnd Bergmann #include <linux/mutex.h>
711da177e4SLinus Torvalds #include <linux/writeback.h>
721da177e4SLinus Torvalds #include <linux/completion.h>
731da177e4SLinus Torvalds #include <linux/highmem.h>
74d6b29d7cSJens Axboe #include <linux/splice.h>
75ee862730SMilan Broz #include <linux/sysfs.h>
76770fe30aSKay Sievers #include <linux/miscdevice.h>
77dfaa2ef6SLukas Czerner #include <linux/falloc.h>
78283e7e5dSAl Viro #include <linux/uio.h>
79d9a08a9eSAdam Manzanares #include <linux/ioprio.h>
80db6638d7SDennis Zhou #include <linux/blk-cgroup.h>
81c74d40e8SDan Schatzberg #include <linux/sched/mm.h>
82d9a08a9eSAdam Manzanares 
8383a87611SAl Viro #include "loop.h"
841da177e4SLinus Torvalds 
857c0f6ba6SLinus Torvalds #include <linux/uaccess.h>
861da177e4SLinus Torvalds 
8787579e9bSDan Schatzberg #define LOOP_IDLE_WORKER_TIMEOUT (60 * HZ)
8887579e9bSDan Schatzberg 
8934dd82afSKay Sievers static DEFINE_IDR(loop_index_idr);
90310ca162STetsuo Handa static DEFINE_MUTEX(loop_ctl_mutex);
913ce6e1f6STetsuo Handa static DEFINE_MUTEX(loop_validate_mutex);
923ce6e1f6STetsuo Handa 
933ce6e1f6STetsuo Handa /**
943ce6e1f6STetsuo Handa  * loop_global_lock_killable() - take locks for safe loop_validate_file() test
953ce6e1f6STetsuo Handa  *
963ce6e1f6STetsuo Handa  * @lo: struct loop_device
973ce6e1f6STetsuo Handa  * @global: true if @lo is about to bind another "struct loop_device", false otherwise
983ce6e1f6STetsuo Handa  *
993ce6e1f6STetsuo Handa  * Returns 0 on success, -EINTR otherwise.
1003ce6e1f6STetsuo Handa  *
1013ce6e1f6STetsuo Handa  * Since loop_validate_file() traverses on other "struct loop_device" if
1023ce6e1f6STetsuo Handa  * is_loop_device() is true, we need a global lock for serializing concurrent
1033ce6e1f6STetsuo Handa  * loop_configure()/loop_change_fd()/__loop_clr_fd() calls.
1043ce6e1f6STetsuo Handa  */
1053ce6e1f6STetsuo Handa static int loop_global_lock_killable(struct loop_device *lo, bool global)
1063ce6e1f6STetsuo Handa {
1073ce6e1f6STetsuo Handa 	int err;
1083ce6e1f6STetsuo Handa 
1093ce6e1f6STetsuo Handa 	if (global) {
1103ce6e1f6STetsuo Handa 		err = mutex_lock_killable(&loop_validate_mutex);
1113ce6e1f6STetsuo Handa 		if (err)
1123ce6e1f6STetsuo Handa 			return err;
1133ce6e1f6STetsuo Handa 	}
1143ce6e1f6STetsuo Handa 	err = mutex_lock_killable(&lo->lo_mutex);
1153ce6e1f6STetsuo Handa 	if (err && global)
1163ce6e1f6STetsuo Handa 		mutex_unlock(&loop_validate_mutex);
1173ce6e1f6STetsuo Handa 	return err;
1183ce6e1f6STetsuo Handa }
1193ce6e1f6STetsuo Handa 
1203ce6e1f6STetsuo Handa /**
1213ce6e1f6STetsuo Handa  * loop_global_unlock() - release locks taken by loop_global_lock_killable()
1223ce6e1f6STetsuo Handa  *
1233ce6e1f6STetsuo Handa  * @lo: struct loop_device
1243ce6e1f6STetsuo Handa  * @global: true if @lo was about to bind another "struct loop_device", false otherwise
1253ce6e1f6STetsuo Handa  */
1263ce6e1f6STetsuo Handa static void loop_global_unlock(struct loop_device *lo, bool global)
1273ce6e1f6STetsuo Handa {
1283ce6e1f6STetsuo Handa 	mutex_unlock(&lo->lo_mutex);
1293ce6e1f6STetsuo Handa 	if (global)
1303ce6e1f6STetsuo Handa 		mutex_unlock(&loop_validate_mutex);
1313ce6e1f6STetsuo Handa }
1321da177e4SLinus Torvalds 
133476a4813SLaurent Vivier static int max_part;
134476a4813SLaurent Vivier static int part_shift;
135476a4813SLaurent Vivier 
1367035b5dfSDmitry Monakhov static loff_t get_size(loff_t offset, loff_t sizelimit, struct file *file)
1371da177e4SLinus Torvalds {
138b7a1da69SGuo Chao 	loff_t loopsize;
1391da177e4SLinus Torvalds 
1401da177e4SLinus Torvalds 	/* Compute loopsize in bytes */
141b7a1da69SGuo Chao 	loopsize = i_size_read(file->f_mapping->host);
142b7a1da69SGuo Chao 	if (offset > 0)
143b7a1da69SGuo Chao 		loopsize -= offset;
144b7a1da69SGuo Chao 	/* offset is beyond i_size, weird but possible */
1457035b5dfSDmitry Monakhov 	if (loopsize < 0)
1467035b5dfSDmitry Monakhov 		return 0;
1471da177e4SLinus Torvalds 
1487035b5dfSDmitry Monakhov 	if (sizelimit > 0 && sizelimit < loopsize)
1497035b5dfSDmitry Monakhov 		loopsize = sizelimit;
1501da177e4SLinus Torvalds 	/*
1511da177e4SLinus Torvalds 	 * Unfortunately, if we want to do I/O on the device,
1521da177e4SLinus Torvalds 	 * the number of 512-byte sectors has to fit into a sector_t.
1531da177e4SLinus Torvalds 	 */
1541da177e4SLinus Torvalds 	return loopsize >> 9;
1551da177e4SLinus Torvalds }
1561da177e4SLinus Torvalds 
1577035b5dfSDmitry Monakhov static loff_t get_loop_size(struct loop_device *lo, struct file *file)
1581da177e4SLinus Torvalds {
1597035b5dfSDmitry Monakhov 	return get_size(lo->lo_offset, lo->lo_sizelimit, file);
1607035b5dfSDmitry Monakhov }
1617035b5dfSDmitry Monakhov 
1622e5ab5f3SMing Lei static void __loop_update_dio(struct loop_device *lo, bool dio)
1632e5ab5f3SMing Lei {
1642e5ab5f3SMing Lei 	struct file *file = lo->lo_backing_file;
1652e5ab5f3SMing Lei 	struct address_space *mapping = file->f_mapping;
1662e5ab5f3SMing Lei 	struct inode *inode = mapping->host;
1672e5ab5f3SMing Lei 	unsigned short sb_bsize = 0;
1682e5ab5f3SMing Lei 	unsigned dio_align = 0;
1692e5ab5f3SMing Lei 	bool use_dio;
1702e5ab5f3SMing Lei 
1712e5ab5f3SMing Lei 	if (inode->i_sb->s_bdev) {
1722e5ab5f3SMing Lei 		sb_bsize = bdev_logical_block_size(inode->i_sb->s_bdev);
1732e5ab5f3SMing Lei 		dio_align = sb_bsize - 1;
1742e5ab5f3SMing Lei 	}
1752e5ab5f3SMing Lei 
1762e5ab5f3SMing Lei 	/*
1772e5ab5f3SMing Lei 	 * We support direct I/O only if lo_offset is aligned with the
1782e5ab5f3SMing Lei 	 * logical I/O size of backing device, and the logical block
179*47e96246SChristoph Hellwig 	 * size of loop is bigger than the backing device's.
1802e5ab5f3SMing Lei 	 *
1812e5ab5f3SMing Lei 	 * TODO: the above condition may be loosed in the future, and
1822e5ab5f3SMing Lei 	 * direct I/O may be switched runtime at that time because most
18389d790abSMasahiro Yamada 	 * of requests in sane applications should be PAGE_SIZE aligned
1842e5ab5f3SMing Lei 	 */
1852e5ab5f3SMing Lei 	if (dio) {
1862e5ab5f3SMing Lei 		if (queue_logical_block_size(lo->lo_queue) >= sb_bsize &&
1872e5ab5f3SMing Lei 				!(lo->lo_offset & dio_align) &&
188*47e96246SChristoph Hellwig 				mapping->a_ops->direct_IO)
1892e5ab5f3SMing Lei 			use_dio = true;
1902e5ab5f3SMing Lei 		else
1912e5ab5f3SMing Lei 			use_dio = false;
1922e5ab5f3SMing Lei 	} else {
1932e5ab5f3SMing Lei 		use_dio = false;
1942e5ab5f3SMing Lei 	}
1952e5ab5f3SMing Lei 
1962e5ab5f3SMing Lei 	if (lo->use_dio == use_dio)
1972e5ab5f3SMing Lei 		return;
1982e5ab5f3SMing Lei 
1992e5ab5f3SMing Lei 	/* flush dirty pages before changing direct IO */
2002e5ab5f3SMing Lei 	vfs_fsync(file, 0);
2012e5ab5f3SMing Lei 
2022e5ab5f3SMing Lei 	/*
2032e5ab5f3SMing Lei 	 * The flag of LO_FLAGS_DIRECT_IO is handled similarly with
2042e5ab5f3SMing Lei 	 * LO_FLAGS_READ_ONLY, both are set from kernel, and losetup
2052e5ab5f3SMing Lei 	 * will get updated by ioctl(LOOP_GET_STATUS)
2062e5ab5f3SMing Lei 	 */
2070fbcf579SMartijn Coenen 	if (lo->lo_state == Lo_bound)
2082e5ab5f3SMing Lei 		blk_mq_freeze_queue(lo->lo_queue);
2092e5ab5f3SMing Lei 	lo->use_dio = use_dio;
21040326d8aSShaohua Li 	if (use_dio) {
2118b904b5bSBart Van Assche 		blk_queue_flag_clear(QUEUE_FLAG_NOMERGES, lo->lo_queue);
2122e5ab5f3SMing Lei 		lo->lo_flags |= LO_FLAGS_DIRECT_IO;
21340326d8aSShaohua Li 	} else {
2148b904b5bSBart Van Assche 		blk_queue_flag_set(QUEUE_FLAG_NOMERGES, lo->lo_queue);
2152e5ab5f3SMing Lei 		lo->lo_flags &= ~LO_FLAGS_DIRECT_IO;
21640326d8aSShaohua Li 	}
2170fbcf579SMartijn Coenen 	if (lo->lo_state == Lo_bound)
2182e5ab5f3SMing Lei 		blk_mq_unfreeze_queue(lo->lo_queue);
2192e5ab5f3SMing Lei }
2202e5ab5f3SMing Lei 
2215795b6f5SMartijn Coenen /**
2223448914eSMartijn Coenen  * loop_validate_block_size() - validates the passed in block size
2233448914eSMartijn Coenen  * @bsize: size to validate
2243448914eSMartijn Coenen  */
2257035b5dfSDmitry Monakhov static int
2263448914eSMartijn Coenen loop_validate_block_size(unsigned short bsize)
2277035b5dfSDmitry Monakhov {
2283448914eSMartijn Coenen 	if (bsize < 512 || bsize > PAGE_SIZE || !is_power_of_2(bsize))
2293448914eSMartijn Coenen 		return -EINVAL;
2303448914eSMartijn Coenen 
2313448914eSMartijn Coenen 	return 0;
2323448914eSMartijn Coenen }
2333448914eSMartijn Coenen 
2343448914eSMartijn Coenen /**
2355795b6f5SMartijn Coenen  * loop_set_size() - sets device size and notifies userspace
2365795b6f5SMartijn Coenen  * @lo: struct loop_device to set the size for
2375795b6f5SMartijn Coenen  * @size: new size of the loop device
2385795b6f5SMartijn Coenen  *
2395795b6f5SMartijn Coenen  * Callers must validate that the size passed into this function fits into
2405795b6f5SMartijn Coenen  * a sector_t, eg using loop_validate_size()
2415795b6f5SMartijn Coenen  */
2425795b6f5SMartijn Coenen static void loop_set_size(struct loop_device *lo, loff_t size)
2435795b6f5SMartijn Coenen {
244449f4ec9SChristoph Hellwig 	if (!set_capacity_and_notify(lo->lo_disk, size))
2453b4f85d0SChristoph Hellwig 		kobject_uevent(&disk_to_dev(lo->lo_disk)->kobj, KOBJ_CHANGE);
2461da177e4SLinus Torvalds }
2471da177e4SLinus Torvalds 
248aa4d8616SChristoph Hellwig static int lo_write_bvec(struct file *file, struct bio_vec *bvec, loff_t *ppos)
2491da177e4SLinus Torvalds {
250aa4d8616SChristoph Hellwig 	struct iov_iter i;
2511da177e4SLinus Torvalds 	ssize_t bw;
252283e7e5dSAl Viro 
253b6207430SChristoph Hellwig 	iov_iter_bvec(&i, WRITE, bvec, 1, bvec->bv_len);
2541da177e4SLinus Torvalds 
25503d95eb2SAl Viro 	file_start_write(file);
256abbb6589SChristoph Hellwig 	bw = vfs_iter_write(file, &i, ppos, 0);
25703d95eb2SAl Viro 	file_end_write(file);
258aa4d8616SChristoph Hellwig 
259aa4d8616SChristoph Hellwig 	if (likely(bw ==  bvec->bv_len))
2601da177e4SLinus Torvalds 		return 0;
261aa4d8616SChristoph Hellwig 
262aa4d8616SChristoph Hellwig 	printk_ratelimited(KERN_ERR
263aa4d8616SChristoph Hellwig 		"loop: Write error at byte offset %llu, length %i.\n",
264aa4d8616SChristoph Hellwig 		(unsigned long long)*ppos, bvec->bv_len);
2651da177e4SLinus Torvalds 	if (bw >= 0)
2661da177e4SLinus Torvalds 		bw = -EIO;
2671da177e4SLinus Torvalds 	return bw;
2681da177e4SLinus Torvalds }
2691da177e4SLinus Torvalds 
270aa4d8616SChristoph Hellwig static int lo_write_simple(struct loop_device *lo, struct request *rq,
271aa4d8616SChristoph Hellwig 		loff_t pos)
2721da177e4SLinus Torvalds {
273aa4d8616SChristoph Hellwig 	struct bio_vec bvec;
274aa4d8616SChristoph Hellwig 	struct req_iterator iter;
275aa4d8616SChristoph Hellwig 	int ret = 0;
276aa4d8616SChristoph Hellwig 
277aa4d8616SChristoph Hellwig 	rq_for_each_segment(bvec, rq, iter) {
278aa4d8616SChristoph Hellwig 		ret = lo_write_bvec(lo->lo_backing_file, &bvec, &pos);
279aa4d8616SChristoph Hellwig 		if (ret < 0)
280aa4d8616SChristoph Hellwig 			break;
2811da177e4SLinus Torvalds 		cond_resched();
2821da177e4SLinus Torvalds 	}
2831da177e4SLinus Torvalds 
284aa4d8616SChristoph Hellwig 	return ret;
285aa4d8616SChristoph Hellwig }
286aa4d8616SChristoph Hellwig 
287aa4d8616SChristoph Hellwig static int lo_read_simple(struct loop_device *lo, struct request *rq,
288aa4d8616SChristoph Hellwig 		loff_t pos)
2891da177e4SLinus Torvalds {
2907988613bSKent Overstreet 	struct bio_vec bvec;
29130112013SMing Lei 	struct req_iterator iter;
292aa4d8616SChristoph Hellwig 	struct iov_iter i;
293aa4d8616SChristoph Hellwig 	ssize_t len;
2941da177e4SLinus Torvalds 
29530112013SMing Lei 	rq_for_each_segment(bvec, rq, iter) {
296b6207430SChristoph Hellwig 		iov_iter_bvec(&i, READ, &bvec, 1, bvec.bv_len);
29718e9710eSChristoph Hellwig 		len = vfs_iter_read(lo->lo_backing_file, &i, &pos, 0);
298aa4d8616SChristoph Hellwig 		if (len < 0)
299aa4d8616SChristoph Hellwig 			return len;
300306df071SDave Young 
301aa4d8616SChristoph Hellwig 		flush_dcache_page(bvec.bv_page);
302aa4d8616SChristoph Hellwig 
303aa4d8616SChristoph Hellwig 		if (len != bvec.bv_len) {
30430112013SMing Lei 			struct bio *bio;
30530112013SMing Lei 
30630112013SMing Lei 			__rq_for_each_bio(bio, rq)
307306df071SDave Young 				zero_fill_bio(bio);
3081da177e4SLinus Torvalds 			break;
309306df071SDave Young 		}
310aa4d8616SChristoph Hellwig 		cond_resched();
3111da177e4SLinus Torvalds 	}
312aa4d8616SChristoph Hellwig 
313306df071SDave Young 	return 0;
3141da177e4SLinus Torvalds }
3151da177e4SLinus Torvalds 
316efcfec57SDarrick J. Wong static int lo_fallocate(struct loop_device *lo, struct request *rq, loff_t pos,
317efcfec57SDarrick J. Wong 			int mode)
318cf655d95SMing Lei {
319cf655d95SMing Lei 	/*
320efcfec57SDarrick J. Wong 	 * We use fallocate to manipulate the space mappings used by the image
321*47e96246SChristoph Hellwig 	 * a.k.a. discard/zerorange.
322cf655d95SMing Lei 	 */
323cf655d95SMing Lei 	struct file *file = lo->lo_backing_file;
324c52abf56SEvan Green 	struct request_queue *q = lo->lo_queue;
325cf655d95SMing Lei 	int ret;
326cf655d95SMing Lei 
327efcfec57SDarrick J. Wong 	mode |= FALLOC_FL_KEEP_SIZE;
328efcfec57SDarrick J. Wong 
329c52abf56SEvan Green 	if (!blk_queue_discard(q)) {
330cf655d95SMing Lei 		ret = -EOPNOTSUPP;
331cf655d95SMing Lei 		goto out;
332cf655d95SMing Lei 	}
333cf655d95SMing Lei 
334cf655d95SMing Lei 	ret = file->f_op->fallocate(file, mode, pos, blk_rq_bytes(rq));
335cf655d95SMing Lei 	if (unlikely(ret && ret != -EINVAL && ret != -EOPNOTSUPP))
336cf655d95SMing Lei 		ret = -EIO;
337cf655d95SMing Lei  out:
338cf655d95SMing Lei 	return ret;
339cf655d95SMing Lei }
340cf655d95SMing Lei 
341cf655d95SMing Lei static int lo_req_flush(struct loop_device *lo, struct request *rq)
342cf655d95SMing Lei {
343cf655d95SMing Lei 	struct file *file = lo->lo_backing_file;
344cf655d95SMing Lei 	int ret = vfs_fsync(file, 0);
345cf655d95SMing Lei 	if (unlikely(ret && ret != -EINVAL))
346cf655d95SMing Lei 		ret = -EIO;
347cf655d95SMing Lei 
348cf655d95SMing Lei 	return ret;
349cf655d95SMing Lei }
350cf655d95SMing Lei 
351fe2cb290SChristoph Hellwig static void lo_complete_rq(struct request *rq)
352bc07c10aSMing Lei {
353fe2cb290SChristoph Hellwig 	struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
354f9de14bcSJens Axboe 	blk_status_t ret = BLK_STS_OK;
355bc07c10aSMing Lei 
356f9de14bcSJens Axboe 	if (!cmd->use_aio || cmd->ret < 0 || cmd->ret == blk_rq_bytes(rq) ||
357f9de14bcSJens Axboe 	    req_op(rq) != REQ_OP_READ) {
358f9de14bcSJens Axboe 		if (cmd->ret < 0)
3598cd55087SEvan Green 			ret = errno_to_blk_status(cmd->ret);
360f9de14bcSJens Axboe 		goto end_io;
361bc07c10aSMing Lei 	}
362fe2cb290SChristoph Hellwig 
363f9de14bcSJens Axboe 	/*
364f9de14bcSJens Axboe 	 * Short READ - if we got some data, advance our request and
365f9de14bcSJens Axboe 	 * retry it. If we got no data, end the rest with EIO.
366f9de14bcSJens Axboe 	 */
367f9de14bcSJens Axboe 	if (cmd->ret) {
368f9de14bcSJens Axboe 		blk_update_request(rq, BLK_STS_OK, cmd->ret);
369f9de14bcSJens Axboe 		cmd->ret = 0;
370f9de14bcSJens Axboe 		blk_mq_requeue_request(rq, true);
371f9de14bcSJens Axboe 	} else {
372f9de14bcSJens Axboe 		if (cmd->use_aio) {
373f9de14bcSJens Axboe 			struct bio *bio = rq->bio;
374f9de14bcSJens Axboe 
375f9de14bcSJens Axboe 			while (bio) {
376f9de14bcSJens Axboe 				zero_fill_bio(bio);
377f9de14bcSJens Axboe 				bio = bio->bi_next;
378f9de14bcSJens Axboe 			}
379f9de14bcSJens Axboe 		}
380f9de14bcSJens Axboe 		ret = BLK_STS_IOERR;
381f9de14bcSJens Axboe end_io:
382f9de14bcSJens Axboe 		blk_mq_end_request(rq, ret);
383f9de14bcSJens Axboe 	}
384bc07c10aSMing Lei }
385bc07c10aSMing Lei 
38692d77332SShaohua Li static void lo_rw_aio_do_completion(struct loop_cmd *cmd)
38792d77332SShaohua Li {
3881894e916SJens Axboe 	struct request *rq = blk_mq_rq_from_pdu(cmd);
3891894e916SJens Axboe 
39092d77332SShaohua Li 	if (!atomic_dec_and_test(&cmd->ref))
39192d77332SShaohua Li 		return;
39292d77332SShaohua Li 	kfree(cmd->bvec);
39392d77332SShaohua Li 	cmd->bvec = NULL;
39415f73f5bSChristoph Hellwig 	if (likely(!blk_should_fake_timeout(rq->q)))
3951894e916SJens Axboe 		blk_mq_complete_request(rq);
39692d77332SShaohua Li }
39792d77332SShaohua Li 
398bc07c10aSMing Lei static void lo_rw_aio_complete(struct kiocb *iocb, long ret, long ret2)
399bc07c10aSMing Lei {
400bc07c10aSMing Lei 	struct loop_cmd *cmd = container_of(iocb, struct loop_cmd, iocb);
401bc07c10aSMing Lei 
402fe2cb290SChristoph Hellwig 	cmd->ret = ret;
40392d77332SShaohua Li 	lo_rw_aio_do_completion(cmd);
404bc07c10aSMing Lei }
405bc07c10aSMing Lei 
406bc07c10aSMing Lei static int lo_rw_aio(struct loop_device *lo, struct loop_cmd *cmd,
407bc07c10aSMing Lei 		     loff_t pos, bool rw)
408bc07c10aSMing Lei {
409bc07c10aSMing Lei 	struct iov_iter iter;
41086af5952SMing Lei 	struct req_iterator rq_iter;
411bc07c10aSMing Lei 	struct bio_vec *bvec;
4121894e916SJens Axboe 	struct request *rq = blk_mq_rq_from_pdu(cmd);
41340326d8aSShaohua Li 	struct bio *bio = rq->bio;
414bc07c10aSMing Lei 	struct file *file = lo->lo_backing_file;
41586af5952SMing Lei 	struct bio_vec tmp;
41640326d8aSShaohua Li 	unsigned int offset;
41786af5952SMing Lei 	int nr_bvec = 0;
418bc07c10aSMing Lei 	int ret;
419bc07c10aSMing Lei 
42086af5952SMing Lei 	rq_for_each_bvec(tmp, rq, rq_iter)
42186af5952SMing Lei 		nr_bvec++;
422bc07c10aSMing Lei 
42386af5952SMing Lei 	if (rq->bio != rq->biotail) {
42486af5952SMing Lei 
42586af5952SMing Lei 		bvec = kmalloc_array(nr_bvec, sizeof(struct bio_vec),
4266da2ec56SKees Cook 				     GFP_NOIO);
42740326d8aSShaohua Li 		if (!bvec)
42840326d8aSShaohua Li 			return -EIO;
42940326d8aSShaohua Li 		cmd->bvec = bvec;
43040326d8aSShaohua Li 
431a7297a6aSMing Lei 		/*
43240326d8aSShaohua Li 		 * The bios of the request may be started from the middle of
43340326d8aSShaohua Li 		 * the 'bvec' because of bio splitting, so we can't directly
43486af5952SMing Lei 		 * copy bio->bi_iov_vec to new bvec. The rq_for_each_bvec
43540326d8aSShaohua Li 		 * API will take care of all details for us.
436a7297a6aSMing Lei 		 */
43786af5952SMing Lei 		rq_for_each_bvec(tmp, rq, rq_iter) {
43840326d8aSShaohua Li 			*bvec = tmp;
43940326d8aSShaohua Li 			bvec++;
44040326d8aSShaohua Li 		}
44140326d8aSShaohua Li 		bvec = cmd->bvec;
44240326d8aSShaohua Li 		offset = 0;
44340326d8aSShaohua Li 	} else {
44440326d8aSShaohua Li 		/*
44540326d8aSShaohua Li 		 * Same here, this bio may be started from the middle of the
44640326d8aSShaohua Li 		 * 'bvec' because of bio splitting, so offset from the bvec
44740326d8aSShaohua Li 		 * must be passed to iov iterator
44840326d8aSShaohua Li 		 */
44940326d8aSShaohua Li 		offset = bio->bi_iter.bi_bvec_done;
45040326d8aSShaohua Li 		bvec = __bvec_iter_bvec(bio->bi_io_vec, bio->bi_iter);
45140326d8aSShaohua Li 	}
45292d77332SShaohua Li 	atomic_set(&cmd->ref, 2);
45340326d8aSShaohua Li 
454b6207430SChristoph Hellwig 	iov_iter_bvec(&iter, rw, bvec, nr_bvec, blk_rq_bytes(rq));
45540326d8aSShaohua Li 	iter.iov_offset = offset;
456bc07c10aSMing Lei 
457bc07c10aSMing Lei 	cmd->iocb.ki_pos = pos;
458bc07c10aSMing Lei 	cmd->iocb.ki_filp = file;
459bc07c10aSMing Lei 	cmd->iocb.ki_complete = lo_rw_aio_complete;
460bc07c10aSMing Lei 	cmd->iocb.ki_flags = IOCB_DIRECT;
461d9a08a9eSAdam Manzanares 	cmd->iocb.ki_ioprio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_NONE, 0);
462bc07c10aSMing Lei 
463bc07c10aSMing Lei 	if (rw == WRITE)
464bb7462b6SMiklos Szeredi 		ret = call_write_iter(file, &cmd->iocb, &iter);
465bc07c10aSMing Lei 	else
466bb7462b6SMiklos Szeredi 		ret = call_read_iter(file, &cmd->iocb, &iter);
467bc07c10aSMing Lei 
46892d77332SShaohua Li 	lo_rw_aio_do_completion(cmd);
46992d77332SShaohua Li 
470bc07c10aSMing Lei 	if (ret != -EIOCBQUEUED)
471bc07c10aSMing Lei 		cmd->iocb.ki_complete(&cmd->iocb, ret, 0);
472bc07c10aSMing Lei 	return 0;
473bc07c10aSMing Lei }
474bc07c10aSMing Lei 
475c1c87c2bSChristoph Hellwig static int do_req_filebacked(struct loop_device *lo, struct request *rq)
476bc07c10aSMing Lei {
477bc07c10aSMing Lei 	struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
478c1c87c2bSChristoph Hellwig 	loff_t pos = ((loff_t) blk_rq_pos(rq) << 9) + lo->lo_offset;
479bc07c10aSMing Lei 
480bc07c10aSMing Lei 	/*
481bc07c10aSMing Lei 	 * lo_write_simple and lo_read_simple should have been covered
482bc07c10aSMing Lei 	 * by io submit style function like lo_rw_aio(), one blocker
483bc07c10aSMing Lei 	 * is that lo_read_simple() need to call flush_dcache_page after
484bc07c10aSMing Lei 	 * the page is written from kernel, and it isn't easy to handle
485bc07c10aSMing Lei 	 * this in io submit style function which submits all segments
486bc07c10aSMing Lei 	 * of the req at one time. And direct read IO doesn't need to
487bc07c10aSMing Lei 	 * run flush_dcache_page().
488bc07c10aSMing Lei 	 */
489c1c87c2bSChristoph Hellwig 	switch (req_op(rq)) {
490c1c87c2bSChristoph Hellwig 	case REQ_OP_FLUSH:
491c1c87c2bSChristoph Hellwig 		return lo_req_flush(lo, rq);
49219372e27SChristoph Hellwig 	case REQ_OP_WRITE_ZEROES:
493efcfec57SDarrick J. Wong 		/*
494efcfec57SDarrick J. Wong 		 * If the caller doesn't want deallocation, call zeroout to
495efcfec57SDarrick J. Wong 		 * write zeroes the range.  Otherwise, punch them out.
496efcfec57SDarrick J. Wong 		 */
497efcfec57SDarrick J. Wong 		return lo_fallocate(lo, rq, pos,
498efcfec57SDarrick J. Wong 			(rq->cmd_flags & REQ_NOUNMAP) ?
499efcfec57SDarrick J. Wong 				FALLOC_FL_ZERO_RANGE :
500efcfec57SDarrick J. Wong 				FALLOC_FL_PUNCH_HOLE);
501efcfec57SDarrick J. Wong 	case REQ_OP_DISCARD:
502efcfec57SDarrick J. Wong 		return lo_fallocate(lo, rq, pos, FALLOC_FL_PUNCH_HOLE);
503c1c87c2bSChristoph Hellwig 	case REQ_OP_WRITE:
504*47e96246SChristoph Hellwig 		if (cmd->use_aio)
505c1c87c2bSChristoph Hellwig 			return lo_rw_aio(lo, cmd, pos, WRITE);
506c1c87c2bSChristoph Hellwig 		else
507bc07c10aSMing Lei 			return lo_write_simple(lo, rq, pos);
508c1c87c2bSChristoph Hellwig 	case REQ_OP_READ:
509*47e96246SChristoph Hellwig 		if (cmd->use_aio)
510c1c87c2bSChristoph Hellwig 			return lo_rw_aio(lo, cmd, pos, READ);
511bc07c10aSMing Lei 		else
512bc07c10aSMing Lei 			return lo_read_simple(lo, rq, pos);
513c1c87c2bSChristoph Hellwig 	default:
514c1c87c2bSChristoph Hellwig 		WARN_ON_ONCE(1);
515c1c87c2bSChristoph Hellwig 		return -EIO;
516bc07c10aSMing Lei 	}
5171da177e4SLinus Torvalds }
5181da177e4SLinus Torvalds 
5192e5ab5f3SMing Lei static inline void loop_update_dio(struct loop_device *lo)
5202e5ab5f3SMing Lei {
521efbe3c24SIra Weiny 	__loop_update_dio(lo, (lo->lo_backing_file->f_flags & O_DIRECT) |
5222e5ab5f3SMing Lei 				lo->use_dio);
5232e5ab5f3SMing Lei }
5242e5ab5f3SMing Lei 
5250384264eSChristoph Hellwig static void loop_reread_partitions(struct loop_device *lo)
52606f0e9e6SMing Lei {
52706f0e9e6SMing Lei 	int rc;
52806f0e9e6SMing Lei 
5290384264eSChristoph Hellwig 	mutex_lock(&lo->lo_disk->open_mutex);
5300384264eSChristoph Hellwig 	rc = bdev_disk_changed(lo->lo_disk, false);
5310384264eSChristoph Hellwig 	mutex_unlock(&lo->lo_disk->open_mutex);
53206f0e9e6SMing Lei 	if (rc)
53306f0e9e6SMing Lei 		pr_warn("%s: partition scan of loop%d (%s) failed (rc=%d)\n",
53406f0e9e6SMing Lei 			__func__, lo->lo_number, lo->lo_file_name, rc);
53506f0e9e6SMing Lei }
53606f0e9e6SMing Lei 
537d2ac838eSTheodore Ts'o static inline int is_loop_device(struct file *file)
538d2ac838eSTheodore Ts'o {
539d2ac838eSTheodore Ts'o 	struct inode *i = file->f_mapping->host;
540d2ac838eSTheodore Ts'o 
5416f24784fSAl Viro 	return i && S_ISBLK(i->i_mode) && imajor(i) == LOOP_MAJOR;
542d2ac838eSTheodore Ts'o }
543d2ac838eSTheodore Ts'o 
544d2ac838eSTheodore Ts'o static int loop_validate_file(struct file *file, struct block_device *bdev)
545d2ac838eSTheodore Ts'o {
546d2ac838eSTheodore Ts'o 	struct inode	*inode = file->f_mapping->host;
547d2ac838eSTheodore Ts'o 	struct file	*f = file;
548d2ac838eSTheodore Ts'o 
549d2ac838eSTheodore Ts'o 	/* Avoid recursion */
550d2ac838eSTheodore Ts'o 	while (is_loop_device(f)) {
551d2ac838eSTheodore Ts'o 		struct loop_device *l;
552d2ac838eSTheodore Ts'o 
5533ce6e1f6STetsuo Handa 		lockdep_assert_held(&loop_validate_mutex);
5544e7b5671SChristoph Hellwig 		if (f->f_mapping->host->i_rdev == bdev->bd_dev)
555d2ac838eSTheodore Ts'o 			return -EBADF;
556d2ac838eSTheodore Ts'o 
5574e7b5671SChristoph Hellwig 		l = I_BDEV(f->f_mapping->host)->bd_disk->private_data;
5583ce6e1f6STetsuo Handa 		if (l->lo_state != Lo_bound)
559d2ac838eSTheodore Ts'o 			return -EINVAL;
5603ce6e1f6STetsuo Handa 		/* Order wrt setting lo->lo_backing_file in loop_configure(). */
5613ce6e1f6STetsuo Handa 		rmb();
562d2ac838eSTheodore Ts'o 		f = l->lo_backing_file;
563d2ac838eSTheodore Ts'o 	}
564d2ac838eSTheodore Ts'o 	if (!S_ISREG(inode->i_mode) && !S_ISBLK(inode->i_mode))
565d2ac838eSTheodore Ts'o 		return -EINVAL;
566d2ac838eSTheodore Ts'o 	return 0;
567d2ac838eSTheodore Ts'o }
568d2ac838eSTheodore Ts'o 
5691da177e4SLinus Torvalds /*
5701da177e4SLinus Torvalds  * loop_change_fd switched the backing store of a loopback device to
5711da177e4SLinus Torvalds  * a new file. This is useful for operating system installers to free up
5721da177e4SLinus Torvalds  * the original file and in High Availability environments to switch to
5731da177e4SLinus Torvalds  * an alternative location for the content in case of server meltdown.
5741da177e4SLinus Torvalds  * This can only work if the loop device is used read-only, and if the
5751da177e4SLinus Torvalds  * new backing store is the same size and type as the old backing store.
5761da177e4SLinus Torvalds  */
577bb214884SAl Viro static int loop_change_fd(struct loop_device *lo, struct block_device *bdev,
578bb214884SAl Viro 			  unsigned int arg)
5791da177e4SLinus Torvalds {
5803ce6e1f6STetsuo Handa 	struct file *file = fget(arg);
5813ce6e1f6STetsuo Handa 	struct file *old_file;
5821da177e4SLinus Torvalds 	int error;
58385b0a54aSJan Kara 	bool partscan;
5843ce6e1f6STetsuo Handa 	bool is_loop;
5851da177e4SLinus Torvalds 
5863ce6e1f6STetsuo Handa 	if (!file)
5873ce6e1f6STetsuo Handa 		return -EBADF;
5883ce6e1f6STetsuo Handa 	is_loop = is_loop_device(file);
5893ce6e1f6STetsuo Handa 	error = loop_global_lock_killable(lo, is_loop);
590c3710770SJan Kara 	if (error)
5913ce6e1f6STetsuo Handa 		goto out_putf;
5921da177e4SLinus Torvalds 	error = -ENXIO;
5931da177e4SLinus Torvalds 	if (lo->lo_state != Lo_bound)
5941dded9acSJan Kara 		goto out_err;
5951da177e4SLinus Torvalds 
5961da177e4SLinus Torvalds 	/* the loop device has to be read-only */
5971da177e4SLinus Torvalds 	error = -EINVAL;
5981da177e4SLinus Torvalds 	if (!(lo->lo_flags & LO_FLAGS_READ_ONLY))
5991dded9acSJan Kara 		goto out_err;
6001da177e4SLinus Torvalds 
601d2ac838eSTheodore Ts'o 	error = loop_validate_file(file, bdev);
602d2ac838eSTheodore Ts'o 	if (error)
6031dded9acSJan Kara 		goto out_err;
604d2ac838eSTheodore Ts'o 
6051da177e4SLinus Torvalds 	old_file = lo->lo_backing_file;
6061da177e4SLinus Torvalds 
6071da177e4SLinus Torvalds 	error = -EINVAL;
6081da177e4SLinus Torvalds 
6091da177e4SLinus Torvalds 	/* size of the new backing store needs to be the same */
6101da177e4SLinus Torvalds 	if (get_loop_size(lo, file) != get_loop_size(lo, old_file))
6111dded9acSJan Kara 		goto out_err;
6121da177e4SLinus Torvalds 
6131da177e4SLinus Torvalds 	/* and ... switch */
6149f65c489SMatteo Croce 	disk_force_media_change(lo->lo_disk, DISK_EVENT_MEDIA_CHANGE);
61543cade80SOmar Sandoval 	blk_mq_freeze_queue(lo->lo_queue);
61643cade80SOmar Sandoval 	mapping_set_gfp_mask(old_file->f_mapping, lo->old_gfp_mask);
61743cade80SOmar Sandoval 	lo->lo_backing_file = file;
61843cade80SOmar Sandoval 	lo->old_gfp_mask = mapping_gfp_mask(file->f_mapping);
61943cade80SOmar Sandoval 	mapping_set_gfp_mask(file->f_mapping,
62043cade80SOmar Sandoval 			     lo->old_gfp_mask & ~(__GFP_IO|__GFP_FS));
62143cade80SOmar Sandoval 	loop_update_dio(lo);
62243cade80SOmar Sandoval 	blk_mq_unfreeze_queue(lo->lo_queue);
62385b0a54aSJan Kara 	partscan = lo->lo_flags & LO_FLAGS_PARTSCAN;
6243ce6e1f6STetsuo Handa 	loop_global_unlock(lo, is_loop);
6253ce6e1f6STetsuo Handa 
6263ce6e1f6STetsuo Handa 	/*
6273ce6e1f6STetsuo Handa 	 * Flush loop_validate_file() before fput(), for l->lo_backing_file
6283ce6e1f6STetsuo Handa 	 * might be pointing at old_file which might be the last reference.
6293ce6e1f6STetsuo Handa 	 */
6303ce6e1f6STetsuo Handa 	if (!is_loop) {
6313ce6e1f6STetsuo Handa 		mutex_lock(&loop_validate_mutex);
6323ce6e1f6STetsuo Handa 		mutex_unlock(&loop_validate_mutex);
6333ce6e1f6STetsuo Handa 	}
6341dded9acSJan Kara 	/*
6356cc8e743SPavel Tatashin 	 * We must drop file reference outside of lo_mutex as dropping
636a8698707SChristoph Hellwig 	 * the file ref can take open_mutex which creates circular locking
6371dded9acSJan Kara 	 * dependency.
6381dded9acSJan Kara 	 */
6391dded9acSJan Kara 	fput(old_file);
64085b0a54aSJan Kara 	if (partscan)
6410384264eSChristoph Hellwig 		loop_reread_partitions(lo);
6421da177e4SLinus Torvalds 	return 0;
6431da177e4SLinus Torvalds 
6441dded9acSJan Kara out_err:
6453ce6e1f6STetsuo Handa 	loop_global_unlock(lo, is_loop);
6463ce6e1f6STetsuo Handa out_putf:
6471dded9acSJan Kara 	fput(file);
6481da177e4SLinus Torvalds 	return error;
6491da177e4SLinus Torvalds }
6501da177e4SLinus Torvalds 
651ee862730SMilan Broz /* loop sysfs attributes */
652ee862730SMilan Broz 
653ee862730SMilan Broz static ssize_t loop_attr_show(struct device *dev, char *page,
654ee862730SMilan Broz 			      ssize_t (*callback)(struct loop_device *, char *))
655ee862730SMilan Broz {
65634dd82afSKay Sievers 	struct gendisk *disk = dev_to_disk(dev);
65734dd82afSKay Sievers 	struct loop_device *lo = disk->private_data;
658ee862730SMilan Broz 
65934dd82afSKay Sievers 	return callback(lo, page);
660ee862730SMilan Broz }
661ee862730SMilan Broz 
662ee862730SMilan Broz #define LOOP_ATTR_RO(_name)						\
663ee862730SMilan Broz static ssize_t loop_attr_##_name##_show(struct loop_device *, char *);	\
664ee862730SMilan Broz static ssize_t loop_attr_do_show_##_name(struct device *d,		\
665ee862730SMilan Broz 				struct device_attribute *attr, char *b)	\
666ee862730SMilan Broz {									\
667ee862730SMilan Broz 	return loop_attr_show(d, b, loop_attr_##_name##_show);		\
668ee862730SMilan Broz }									\
669ee862730SMilan Broz static struct device_attribute loop_attr_##_name =			\
6705657a819SJoe Perches 	__ATTR(_name, 0444, loop_attr_do_show_##_name, NULL);
671ee862730SMilan Broz 
672ee862730SMilan Broz static ssize_t loop_attr_backing_file_show(struct loop_device *lo, char *buf)
673ee862730SMilan Broz {
674ee862730SMilan Broz 	ssize_t ret;
675ee862730SMilan Broz 	char *p = NULL;
676ee862730SMilan Broz 
67705eb0f25SKay Sievers 	spin_lock_irq(&lo->lo_lock);
678ee862730SMilan Broz 	if (lo->lo_backing_file)
6799bf39ab2SMiklos Szeredi 		p = file_path(lo->lo_backing_file, buf, PAGE_SIZE - 1);
68005eb0f25SKay Sievers 	spin_unlock_irq(&lo->lo_lock);
681ee862730SMilan Broz 
682ee862730SMilan Broz 	if (IS_ERR_OR_NULL(p))
683ee862730SMilan Broz 		ret = PTR_ERR(p);
684ee862730SMilan Broz 	else {
685ee862730SMilan Broz 		ret = strlen(p);
686ee862730SMilan Broz 		memmove(buf, p, ret);
687ee862730SMilan Broz 		buf[ret++] = '\n';
688ee862730SMilan Broz 		buf[ret] = 0;
689ee862730SMilan Broz 	}
690ee862730SMilan Broz 
691ee862730SMilan Broz 	return ret;
692ee862730SMilan Broz }
693ee862730SMilan Broz 
694ee862730SMilan Broz static ssize_t loop_attr_offset_show(struct loop_device *lo, char *buf)
695ee862730SMilan Broz {
696ee862730SMilan Broz 	return sprintf(buf, "%llu\n", (unsigned long long)lo->lo_offset);
697ee862730SMilan Broz }
698ee862730SMilan Broz 
699ee862730SMilan Broz static ssize_t loop_attr_sizelimit_show(struct loop_device *lo, char *buf)
700ee862730SMilan Broz {
701ee862730SMilan Broz 	return sprintf(buf, "%llu\n", (unsigned long long)lo->lo_sizelimit);
702ee862730SMilan Broz }
703ee862730SMilan Broz 
704ee862730SMilan Broz static ssize_t loop_attr_autoclear_show(struct loop_device *lo, char *buf)
705ee862730SMilan Broz {
706ee862730SMilan Broz 	int autoclear = (lo->lo_flags & LO_FLAGS_AUTOCLEAR);
707ee862730SMilan Broz 
708ee862730SMilan Broz 	return sprintf(buf, "%s\n", autoclear ? "1" : "0");
709ee862730SMilan Broz }
710ee862730SMilan Broz 
711e03c8dd1SKay Sievers static ssize_t loop_attr_partscan_show(struct loop_device *lo, char *buf)
712e03c8dd1SKay Sievers {
713e03c8dd1SKay Sievers 	int partscan = (lo->lo_flags & LO_FLAGS_PARTSCAN);
714e03c8dd1SKay Sievers 
715e03c8dd1SKay Sievers 	return sprintf(buf, "%s\n", partscan ? "1" : "0");
716e03c8dd1SKay Sievers }
717e03c8dd1SKay Sievers 
7182e5ab5f3SMing Lei static ssize_t loop_attr_dio_show(struct loop_device *lo, char *buf)
7192e5ab5f3SMing Lei {
7202e5ab5f3SMing Lei 	int dio = (lo->lo_flags & LO_FLAGS_DIRECT_IO);
7212e5ab5f3SMing Lei 
7222e5ab5f3SMing Lei 	return sprintf(buf, "%s\n", dio ? "1" : "0");
7232e5ab5f3SMing Lei }
7242e5ab5f3SMing Lei 
725ee862730SMilan Broz LOOP_ATTR_RO(backing_file);
726ee862730SMilan Broz LOOP_ATTR_RO(offset);
727ee862730SMilan Broz LOOP_ATTR_RO(sizelimit);
728ee862730SMilan Broz LOOP_ATTR_RO(autoclear);
729e03c8dd1SKay Sievers LOOP_ATTR_RO(partscan);
7302e5ab5f3SMing Lei LOOP_ATTR_RO(dio);
731ee862730SMilan Broz 
732ee862730SMilan Broz static struct attribute *loop_attrs[] = {
733ee862730SMilan Broz 	&loop_attr_backing_file.attr,
734ee862730SMilan Broz 	&loop_attr_offset.attr,
735ee862730SMilan Broz 	&loop_attr_sizelimit.attr,
736ee862730SMilan Broz 	&loop_attr_autoclear.attr,
737e03c8dd1SKay Sievers 	&loop_attr_partscan.attr,
7382e5ab5f3SMing Lei 	&loop_attr_dio.attr,
739ee862730SMilan Broz 	NULL,
740ee862730SMilan Broz };
741ee862730SMilan Broz 
742ee862730SMilan Broz static struct attribute_group loop_attribute_group = {
743ee862730SMilan Broz 	.name = "loop",
744ee862730SMilan Broz 	.attrs= loop_attrs,
745ee862730SMilan Broz };
746ee862730SMilan Broz 
747d3349b6bSTetsuo Handa static void loop_sysfs_init(struct loop_device *lo)
748ee862730SMilan Broz {
749d3349b6bSTetsuo Handa 	lo->sysfs_inited = !sysfs_create_group(&disk_to_dev(lo->lo_disk)->kobj,
750ee862730SMilan Broz 						&loop_attribute_group);
751ee862730SMilan Broz }
752ee862730SMilan Broz 
753ee862730SMilan Broz static void loop_sysfs_exit(struct loop_device *lo)
754ee862730SMilan Broz {
755d3349b6bSTetsuo Handa 	if (lo->sysfs_inited)
756ee862730SMilan Broz 		sysfs_remove_group(&disk_to_dev(lo->lo_disk)->kobj,
757ee862730SMilan Broz 				   &loop_attribute_group);
758ee862730SMilan Broz }
759ee862730SMilan Broz 
760dfaa2ef6SLukas Czerner static void loop_config_discard(struct loop_device *lo)
761dfaa2ef6SLukas Czerner {
762dfaa2ef6SLukas Czerner 	struct file *file = lo->lo_backing_file;
763dfaa2ef6SLukas Czerner 	struct inode *inode = file->f_mapping->host;
764dfaa2ef6SLukas Czerner 	struct request_queue *q = lo->lo_queue;
765bcb21c8cSMing Lei 	u32 granularity, max_discard_sectors;
766dfaa2ef6SLukas Czerner 
767dfaa2ef6SLukas Czerner 	/*
768c52abf56SEvan Green 	 * If the backing device is a block device, mirror its zeroing
769c52abf56SEvan Green 	 * capability. Set the discard sectors to the block device's zeroing
770c52abf56SEvan Green 	 * capabilities because loop discards result in blkdev_issue_zeroout(),
771c52abf56SEvan Green 	 * not blkdev_issue_discard(). This maintains consistent behavior with
772c52abf56SEvan Green 	 * file-backed loop devices: discarded regions read back as zero.
773c52abf56SEvan Green 	 */
774*47e96246SChristoph Hellwig 	if (S_ISBLK(inode->i_mode)) {
7754e7b5671SChristoph Hellwig 		struct request_queue *backingq = bdev_get_queue(I_BDEV(inode));
776c52abf56SEvan Green 
777bcb21c8cSMing Lei 		max_discard_sectors = backingq->limits.max_write_zeroes_sectors;
778bcb21c8cSMing Lei 		granularity = backingq->limits.discard_granularity ?:
779bcb21c8cSMing Lei 			queue_physical_block_size(backingq);
780c52abf56SEvan Green 
781c52abf56SEvan Green 	/*
782dfaa2ef6SLukas Czerner 	 * We use punch hole to reclaim the free space used by the
783*47e96246SChristoph Hellwig 	 * image a.k.a. discard.
784dfaa2ef6SLukas Czerner 	 */
785*47e96246SChristoph Hellwig 	} else if (!file->f_op->fallocate) {
786bcb21c8cSMing Lei 		max_discard_sectors = 0;
787bcb21c8cSMing Lei 		granularity = 0;
788dfaa2ef6SLukas Czerner 
789c52abf56SEvan Green 	} else {
790bcb21c8cSMing Lei 		max_discard_sectors = UINT_MAX >> 9;
791bcb21c8cSMing Lei 		granularity = inode->i_sb->s_blocksize;
792c52abf56SEvan Green 	}
793c52abf56SEvan Green 
794bcb21c8cSMing Lei 	if (max_discard_sectors) {
795bcb21c8cSMing Lei 		q->limits.discard_granularity = granularity;
796bcb21c8cSMing Lei 		blk_queue_max_discard_sectors(q, max_discard_sectors);
797bcb21c8cSMing Lei 		blk_queue_max_write_zeroes_sectors(q, max_discard_sectors);
7988b904b5bSBart Van Assche 		blk_queue_flag_set(QUEUE_FLAG_DISCARD, q);
799bcb21c8cSMing Lei 	} else {
800bcb21c8cSMing Lei 		q->limits.discard_granularity = 0;
801bcb21c8cSMing Lei 		blk_queue_max_discard_sectors(q, 0);
802bcb21c8cSMing Lei 		blk_queue_max_write_zeroes_sectors(q, 0);
803c52abf56SEvan Green 		blk_queue_flag_clear(QUEUE_FLAG_DISCARD, q);
804dfaa2ef6SLukas Czerner 	}
805bcb21c8cSMing Lei 	q->limits.discard_alignment = 0;
806bcb21c8cSMing Lei }
807dfaa2ef6SLukas Czerner 
80887579e9bSDan Schatzberg struct loop_worker {
80987579e9bSDan Schatzberg 	struct rb_node rb_node;
81087579e9bSDan Schatzberg 	struct work_struct work;
81187579e9bSDan Schatzberg 	struct list_head cmd_list;
81287579e9bSDan Schatzberg 	struct list_head idle_list;
81387579e9bSDan Schatzberg 	struct loop_device *lo;
814c74d40e8SDan Schatzberg 	struct cgroup_subsys_state *blkcg_css;
81587579e9bSDan Schatzberg 	unsigned long last_ran_at;
81687579e9bSDan Schatzberg };
817e03a3d7aSMing Lei 
81887579e9bSDan Schatzberg static void loop_workfn(struct work_struct *work);
81987579e9bSDan Schatzberg static void loop_rootcg_workfn(struct work_struct *work);
82087579e9bSDan Schatzberg static void loop_free_idle_workers(struct timer_list *timer);
821b2ee7d46SNeilBrown 
82287579e9bSDan Schatzberg #ifdef CONFIG_BLK_CGROUP
82387579e9bSDan Schatzberg static inline int queue_on_root_worker(struct cgroup_subsys_state *css)
824e03a3d7aSMing Lei {
82587579e9bSDan Schatzberg 	return !css || css == blkcg_root_css;
82687579e9bSDan Schatzberg }
82787579e9bSDan Schatzberg #else
82887579e9bSDan Schatzberg static inline int queue_on_root_worker(struct cgroup_subsys_state *css)
82987579e9bSDan Schatzberg {
83087579e9bSDan Schatzberg 	return !css;
83187579e9bSDan Schatzberg }
83287579e9bSDan Schatzberg #endif
83387579e9bSDan Schatzberg 
83487579e9bSDan Schatzberg static void loop_queue_work(struct loop_device *lo, struct loop_cmd *cmd)
83587579e9bSDan Schatzberg {
83687579e9bSDan Schatzberg 	struct rb_node **node = &(lo->worker_tree.rb_node), *parent = NULL;
83787579e9bSDan Schatzberg 	struct loop_worker *cur_worker, *worker = NULL;
83887579e9bSDan Schatzberg 	struct work_struct *work;
83987579e9bSDan Schatzberg 	struct list_head *cmd_list;
84087579e9bSDan Schatzberg 
84187579e9bSDan Schatzberg 	spin_lock_irq(&lo->lo_work_lock);
84287579e9bSDan Schatzberg 
843c74d40e8SDan Schatzberg 	if (queue_on_root_worker(cmd->blkcg_css))
84487579e9bSDan Schatzberg 		goto queue_work;
84587579e9bSDan Schatzberg 
84687579e9bSDan Schatzberg 	node = &lo->worker_tree.rb_node;
84787579e9bSDan Schatzberg 
84887579e9bSDan Schatzberg 	while (*node) {
84987579e9bSDan Schatzberg 		parent = *node;
85087579e9bSDan Schatzberg 		cur_worker = container_of(*node, struct loop_worker, rb_node);
851c74d40e8SDan Schatzberg 		if (cur_worker->blkcg_css == cmd->blkcg_css) {
85287579e9bSDan Schatzberg 			worker = cur_worker;
85387579e9bSDan Schatzberg 			break;
854c74d40e8SDan Schatzberg 		} else if ((long)cur_worker->blkcg_css < (long)cmd->blkcg_css) {
85587579e9bSDan Schatzberg 			node = &(*node)->rb_left;
85687579e9bSDan Schatzberg 		} else {
85787579e9bSDan Schatzberg 			node = &(*node)->rb_right;
85887579e9bSDan Schatzberg 		}
85987579e9bSDan Schatzberg 	}
86087579e9bSDan Schatzberg 	if (worker)
86187579e9bSDan Schatzberg 		goto queue_work;
86287579e9bSDan Schatzberg 
86387579e9bSDan Schatzberg 	worker = kzalloc(sizeof(struct loop_worker), GFP_NOWAIT | __GFP_NOWARN);
86487579e9bSDan Schatzberg 	/*
86587579e9bSDan Schatzberg 	 * In the event we cannot allocate a worker, just queue on the
866c74d40e8SDan Schatzberg 	 * rootcg worker and issue the I/O as the rootcg
86787579e9bSDan Schatzberg 	 */
868c74d40e8SDan Schatzberg 	if (!worker) {
869c74d40e8SDan Schatzberg 		cmd->blkcg_css = NULL;
870c74d40e8SDan Schatzberg 		if (cmd->memcg_css)
871c74d40e8SDan Schatzberg 			css_put(cmd->memcg_css);
872c74d40e8SDan Schatzberg 		cmd->memcg_css = NULL;
87387579e9bSDan Schatzberg 		goto queue_work;
874c74d40e8SDan Schatzberg 	}
87587579e9bSDan Schatzberg 
876c74d40e8SDan Schatzberg 	worker->blkcg_css = cmd->blkcg_css;
877c74d40e8SDan Schatzberg 	css_get(worker->blkcg_css);
87887579e9bSDan Schatzberg 	INIT_WORK(&worker->work, loop_workfn);
87987579e9bSDan Schatzberg 	INIT_LIST_HEAD(&worker->cmd_list);
88087579e9bSDan Schatzberg 	INIT_LIST_HEAD(&worker->idle_list);
88187579e9bSDan Schatzberg 	worker->lo = lo;
88287579e9bSDan Schatzberg 	rb_link_node(&worker->rb_node, parent, node);
88387579e9bSDan Schatzberg 	rb_insert_color(&worker->rb_node, &lo->worker_tree);
88487579e9bSDan Schatzberg queue_work:
88587579e9bSDan Schatzberg 	if (worker) {
88687579e9bSDan Schatzberg 		/*
88787579e9bSDan Schatzberg 		 * We need to remove from the idle list here while
88887579e9bSDan Schatzberg 		 * holding the lock so that the idle timer doesn't
88987579e9bSDan Schatzberg 		 * free the worker
89087579e9bSDan Schatzberg 		 */
89187579e9bSDan Schatzberg 		if (!list_empty(&worker->idle_list))
89287579e9bSDan Schatzberg 			list_del_init(&worker->idle_list);
89387579e9bSDan Schatzberg 		work = &worker->work;
89487579e9bSDan Schatzberg 		cmd_list = &worker->cmd_list;
89587579e9bSDan Schatzberg 	} else {
89687579e9bSDan Schatzberg 		work = &lo->rootcg_work;
89787579e9bSDan Schatzberg 		cmd_list = &lo->rootcg_cmd_list;
89887579e9bSDan Schatzberg 	}
89987579e9bSDan Schatzberg 	list_add_tail(&cmd->list_entry, cmd_list);
90087579e9bSDan Schatzberg 	queue_work(lo->workqueue, work);
90187579e9bSDan Schatzberg 	spin_unlock_irq(&lo->lo_work_lock);
902e03a3d7aSMing Lei }
903e03a3d7aSMing Lei 
90456a85fd8SHolger Hoffstätte static void loop_update_rotational(struct loop_device *lo)
90556a85fd8SHolger Hoffstätte {
90656a85fd8SHolger Hoffstätte 	struct file *file = lo->lo_backing_file;
90756a85fd8SHolger Hoffstätte 	struct inode *file_inode = file->f_mapping->host;
90856a85fd8SHolger Hoffstätte 	struct block_device *file_bdev = file_inode->i_sb->s_bdev;
90956a85fd8SHolger Hoffstätte 	struct request_queue *q = lo->lo_queue;
91056a85fd8SHolger Hoffstätte 	bool nonrot = true;
91156a85fd8SHolger Hoffstätte 
91256a85fd8SHolger Hoffstätte 	/* not all filesystems (e.g. tmpfs) have a sb->s_bdev */
91356a85fd8SHolger Hoffstätte 	if (file_bdev)
91456a85fd8SHolger Hoffstätte 		nonrot = blk_queue_nonrot(bdev_get_queue(file_bdev));
91556a85fd8SHolger Hoffstätte 
91656a85fd8SHolger Hoffstätte 	if (nonrot)
91756a85fd8SHolger Hoffstätte 		blk_queue_flag_set(QUEUE_FLAG_NONROT, q);
91856a85fd8SHolger Hoffstätte 	else
91956a85fd8SHolger Hoffstätte 		blk_queue_flag_clear(QUEUE_FLAG_NONROT, q);
92056a85fd8SHolger Hoffstätte }
92156a85fd8SHolger Hoffstätte 
92262ab466cSMartijn Coenen /**
92362ab466cSMartijn Coenen  * loop_set_status_from_info - configure device from loop_info
92462ab466cSMartijn Coenen  * @lo: struct loop_device to configure
92562ab466cSMartijn Coenen  * @info: struct loop_info64 to configure the device with
92662ab466cSMartijn Coenen  *
92762ab466cSMartijn Coenen  * Configures the loop device parameters according to the passed
92862ab466cSMartijn Coenen  * in loop_info64 configuration.
92962ab466cSMartijn Coenen  */
93062ab466cSMartijn Coenen static int
93162ab466cSMartijn Coenen loop_set_status_from_info(struct loop_device *lo,
93262ab466cSMartijn Coenen 			  const struct loop_info64 *info)
93362ab466cSMartijn Coenen {
93462ab466cSMartijn Coenen 	if ((unsigned int) info->lo_encrypt_key_size > LO_KEY_SIZE)
93562ab466cSMartijn Coenen 		return -EINVAL;
93662ab466cSMartijn Coenen 
937*47e96246SChristoph Hellwig 	switch (info->lo_encrypt_type) {
938*47e96246SChristoph Hellwig 	case LO_CRYPT_NONE:
939*47e96246SChristoph Hellwig 		break;
940*47e96246SChristoph Hellwig 	case LO_CRYPT_XOR:
941*47e96246SChristoph Hellwig 		pr_warn("support for the xor transformation has been removed.\n");
94262ab466cSMartijn Coenen 		return -EINVAL;
943*47e96246SChristoph Hellwig 	case LO_CRYPT_CRYPTOAPI:
944*47e96246SChristoph Hellwig 		pr_warn("support for cryptoloop has been removed.  Use dm-crypt instead.\n");
94562ab466cSMartijn Coenen 		return -EINVAL;
946*47e96246SChristoph Hellwig 	default:
947*47e96246SChristoph Hellwig 		return -EINVAL;
948*47e96246SChristoph Hellwig 	}
94962ab466cSMartijn Coenen 
95062ab466cSMartijn Coenen 	lo->lo_offset = info->lo_offset;
95162ab466cSMartijn Coenen 	lo->lo_sizelimit = info->lo_sizelimit;
95262ab466cSMartijn Coenen 	memcpy(lo->lo_file_name, info->lo_file_name, LO_NAME_SIZE);
95362ab466cSMartijn Coenen 	lo->lo_file_name[LO_NAME_SIZE-1] = 0;
954faf1d254SMartijn Coenen 	lo->lo_flags = info->lo_flags;
95562ab466cSMartijn Coenen 	return 0;
95662ab466cSMartijn Coenen }
95762ab466cSMartijn Coenen 
9583448914eSMartijn Coenen static int loop_configure(struct loop_device *lo, fmode_t mode,
9593448914eSMartijn Coenen 			  struct block_device *bdev,
9603448914eSMartijn Coenen 			  const struct loop_config *config)
9611da177e4SLinus Torvalds {
9623ce6e1f6STetsuo Handa 	struct file *file = fget(config->fd);
9631da177e4SLinus Torvalds 	struct inode *inode;
9641da177e4SLinus Torvalds 	struct address_space *mapping;
9651da177e4SLinus Torvalds 	int error;
9661da177e4SLinus Torvalds 	loff_t size;
96785b0a54aSJan Kara 	bool partscan;
9683448914eSMartijn Coenen 	unsigned short bsize;
9693ce6e1f6STetsuo Handa 	bool is_loop;
9703ce6e1f6STetsuo Handa 
9713ce6e1f6STetsuo Handa 	if (!file)
9723ce6e1f6STetsuo Handa 		return -EBADF;
9733ce6e1f6STetsuo Handa 	is_loop = is_loop_device(file);
9741da177e4SLinus Torvalds 
9751da177e4SLinus Torvalds 	/* This is safe, since we have a reference from open(). */
9761da177e4SLinus Torvalds 	__module_get(THIS_MODULE);
9771da177e4SLinus Torvalds 
97833ec3e53SJan Kara 	/*
97933ec3e53SJan Kara 	 * If we don't hold exclusive handle for the device, upgrade to it
98033ec3e53SJan Kara 	 * here to avoid changing device under exclusive owner.
98133ec3e53SJan Kara 	 */
98233ec3e53SJan Kara 	if (!(mode & FMODE_EXCL)) {
98337c3fc9aSChristoph Hellwig 		error = bd_prepare_to_claim(bdev, loop_configure);
984ecbe6bc0SChristoph Hellwig 		if (error)
985757ecf40SJan Kara 			goto out_putf;
98633ec3e53SJan Kara 	}
98733ec3e53SJan Kara 
9883ce6e1f6STetsuo Handa 	error = loop_global_lock_killable(lo, is_loop);
98933ec3e53SJan Kara 	if (error)
99033ec3e53SJan Kara 		goto out_bdev;
991757ecf40SJan Kara 
9921da177e4SLinus Torvalds 	error = -EBUSY;
9931da177e4SLinus Torvalds 	if (lo->lo_state != Lo_unbound)
994757ecf40SJan Kara 		goto out_unlock;
9951da177e4SLinus Torvalds 
996d2ac838eSTheodore Ts'o 	error = loop_validate_file(file, bdev);
997d2ac838eSTheodore Ts'o 	if (error)
998757ecf40SJan Kara 		goto out_unlock;
9991da177e4SLinus Torvalds 
10001da177e4SLinus Torvalds 	mapping = file->f_mapping;
10011da177e4SLinus Torvalds 	inode = mapping->host;
10021da177e4SLinus Torvalds 
10033448914eSMartijn Coenen 	if ((config->info.lo_flags & ~LOOP_CONFIGURE_SETTABLE_FLAGS) != 0) {
10043448914eSMartijn Coenen 		error = -EINVAL;
10053448914eSMartijn Coenen 		goto out_unlock;
10063448914eSMartijn Coenen 	}
10073448914eSMartijn Coenen 
10083448914eSMartijn Coenen 	if (config->block_size) {
10093448914eSMartijn Coenen 		error = loop_validate_block_size(config->block_size);
10103448914eSMartijn Coenen 		if (error)
10113448914eSMartijn Coenen 			goto out_unlock;
10123448914eSMartijn Coenen 	}
10133448914eSMartijn Coenen 
10143448914eSMartijn Coenen 	error = loop_set_status_from_info(lo, &config->info);
10153448914eSMartijn Coenen 	if (error)
10163448914eSMartijn Coenen 		goto out_unlock;
10173448914eSMartijn Coenen 
1018456be148SChristoph Hellwig 	if (!(file->f_mode & FMODE_WRITE) || !(mode & FMODE_WRITE) ||
1019283e7e5dSAl Viro 	    !file->f_op->write_iter)
10203448914eSMartijn Coenen 		lo->lo_flags |= LO_FLAGS_READ_ONLY;
1021083a6a50SMartijn Coenen 
102287579e9bSDan Schatzberg 	lo->workqueue = alloc_workqueue("loop%d",
102387579e9bSDan Schatzberg 					WQ_UNBOUND | WQ_FREEZABLE,
102487579e9bSDan Schatzberg 					0,
102587579e9bSDan Schatzberg 					lo->lo_number);
102687579e9bSDan Schatzberg 	if (!lo->workqueue) {
102787579e9bSDan Schatzberg 		error = -ENOMEM;
1028757ecf40SJan Kara 		goto out_unlock;
102987579e9bSDan Schatzberg 	}
10301da177e4SLinus Torvalds 
10319f65c489SMatteo Croce 	disk_force_media_change(lo->lo_disk, DISK_EVENT_MEDIA_CHANGE);
10327a2f0ce1SChristoph Hellwig 	set_disk_ro(lo->lo_disk, (lo->lo_flags & LO_FLAGS_READ_ONLY) != 0);
10331da177e4SLinus Torvalds 
103487579e9bSDan Schatzberg 	INIT_WORK(&lo->rootcg_work, loop_rootcg_workfn);
103587579e9bSDan Schatzberg 	INIT_LIST_HEAD(&lo->rootcg_cmd_list);
103687579e9bSDan Schatzberg 	INIT_LIST_HEAD(&lo->idle_worker_list);
103787579e9bSDan Schatzberg 	lo->worker_tree = RB_ROOT;
103887579e9bSDan Schatzberg 	timer_setup(&lo->timer, loop_free_idle_workers,
103987579e9bSDan Schatzberg 		TIMER_DEFERRABLE);
10403448914eSMartijn Coenen 	lo->use_dio = lo->lo_flags & LO_FLAGS_DIRECT_IO;
10411da177e4SLinus Torvalds 	lo->lo_device = bdev;
10421da177e4SLinus Torvalds 	lo->lo_backing_file = file;
10431da177e4SLinus Torvalds 	lo->old_gfp_mask = mapping_gfp_mask(mapping);
10441da177e4SLinus Torvalds 	mapping_set_gfp_mask(mapping, lo->old_gfp_mask & ~(__GFP_IO|__GFP_FS));
10451da177e4SLinus Torvalds 
10463448914eSMartijn Coenen 	if (!(lo->lo_flags & LO_FLAGS_READ_ONLY) && file->f_op->fsync)
104721d0727fSJens Axboe 		blk_queue_write_cache(lo->lo_queue, true, false);
104868db1961SNikanth Karthikesan 
10493448914eSMartijn Coenen 	if (config->block_size)
10503448914eSMartijn Coenen 		bsize = config->block_size;
105196ed320dSLinus Torvalds 	else if ((lo->lo_backing_file->f_flags & O_DIRECT) && inode->i_sb->s_bdev)
105285560117SMartijn Coenen 		/* In case of direct I/O, match underlying block size */
10533448914eSMartijn Coenen 		bsize = bdev_logical_block_size(inode->i_sb->s_bdev);
10543448914eSMartijn Coenen 	else
10553448914eSMartijn Coenen 		bsize = 512;
105685560117SMartijn Coenen 
105785560117SMartijn Coenen 	blk_queue_logical_block_size(lo->lo_queue, bsize);
105885560117SMartijn Coenen 	blk_queue_physical_block_size(lo->lo_queue, bsize);
105985560117SMartijn Coenen 	blk_queue_io_min(lo->lo_queue, bsize);
106085560117SMartijn Coenen 
10612b9ac22bSKristian Klausen 	loop_config_discard(lo);
106256a85fd8SHolger Hoffstätte 	loop_update_rotational(lo);
10632e5ab5f3SMing Lei 	loop_update_dio(lo);
1064ee862730SMilan Broz 	loop_sysfs_init(lo);
106579e5dc59SMartijn Coenen 
106679e5dc59SMartijn Coenen 	size = get_loop_size(lo, file);
10675795b6f5SMartijn Coenen 	loop_set_size(lo, size);
10681da177e4SLinus Torvalds 
10693ce6e1f6STetsuo Handa 	/* Order wrt reading lo_state in loop_validate_file(). */
10703ce6e1f6STetsuo Handa 	wmb();
10713ce6e1f6STetsuo Handa 
10726c997918SSerge E. Hallyn 	lo->lo_state = Lo_bound;
1073e03c8dd1SKay Sievers 	if (part_shift)
1074e03c8dd1SKay Sievers 		lo->lo_flags |= LO_FLAGS_PARTSCAN;
107585b0a54aSJan Kara 	partscan = lo->lo_flags & LO_FLAGS_PARTSCAN;
1076fe6a8fc5SLennart Poettering 	if (partscan)
1077fe6a8fc5SLennart Poettering 		lo->lo_disk->flags &= ~GENHD_FL_NO_PART_SCAN;
1078c1681bf8SAnatol Pomozov 
10793ce6e1f6STetsuo Handa 	loop_global_unlock(lo, is_loop);
108085b0a54aSJan Kara 	if (partscan)
10810384264eSChristoph Hellwig 		loop_reread_partitions(lo);
108237c3fc9aSChristoph Hellwig 	if (!(mode & FMODE_EXCL))
108337c3fc9aSChristoph Hellwig 		bd_abort_claiming(bdev, loop_configure);
10841da177e4SLinus Torvalds 	return 0;
10851da177e4SLinus Torvalds 
1086757ecf40SJan Kara out_unlock:
10873ce6e1f6STetsuo Handa 	loop_global_unlock(lo, is_loop);
108833ec3e53SJan Kara out_bdev:
108937c3fc9aSChristoph Hellwig 	if (!(mode & FMODE_EXCL))
109037c3fc9aSChristoph Hellwig 		bd_abort_claiming(bdev, loop_configure);
10911da177e4SLinus Torvalds out_putf:
10921da177e4SLinus Torvalds 	fput(file);
10931da177e4SLinus Torvalds 	/* This is safe: open() is still holding a reference. */
10941da177e4SLinus Torvalds 	module_put(THIS_MODULE);
10951da177e4SLinus Torvalds 	return error;
10961da177e4SLinus Torvalds }
10971da177e4SLinus Torvalds 
10980da03cabSJan Kara static int __loop_clr_fd(struct loop_device *lo, bool release)
10991da177e4SLinus Torvalds {
11007ccd0791SJan Kara 	struct file *filp = NULL;
1101b4e3ca1aSAl Viro 	gfp_t gfp = lo->old_gfp_mask;
11024c823cc3SAyan George 	struct block_device *bdev = lo->lo_device;
11037ccd0791SJan Kara 	int err = 0;
11040da03cabSJan Kara 	bool partscan = false;
11050da03cabSJan Kara 	int lo_number;
110687579e9bSDan Schatzberg 	struct loop_worker *pos, *worker;
11071da177e4SLinus Torvalds 
11083ce6e1f6STetsuo Handa 	/*
11093ce6e1f6STetsuo Handa 	 * Flush loop_configure() and loop_change_fd(). It is acceptable for
11103ce6e1f6STetsuo Handa 	 * loop_validate_file() to succeed, for actual clear operation has not
11113ce6e1f6STetsuo Handa 	 * started yet.
11123ce6e1f6STetsuo Handa 	 */
11133ce6e1f6STetsuo Handa 	mutex_lock(&loop_validate_mutex);
11143ce6e1f6STetsuo Handa 	mutex_unlock(&loop_validate_mutex);
11153ce6e1f6STetsuo Handa 	/*
11163ce6e1f6STetsuo Handa 	 * loop_validate_file() now fails because l->lo_state != Lo_bound
11173ce6e1f6STetsuo Handa 	 * became visible.
11183ce6e1f6STetsuo Handa 	 */
11193ce6e1f6STetsuo Handa 
11206cc8e743SPavel Tatashin 	mutex_lock(&lo->lo_mutex);
11217ccd0791SJan Kara 	if (WARN_ON_ONCE(lo->lo_state != Lo_rundown)) {
11227ccd0791SJan Kara 		err = -ENXIO;
11237ccd0791SJan Kara 		goto out_unlock;
11247ccd0791SJan Kara 	}
11251da177e4SLinus Torvalds 
11267ccd0791SJan Kara 	filp = lo->lo_backing_file;
11277ccd0791SJan Kara 	if (filp == NULL) {
11287ccd0791SJan Kara 		err = -EINVAL;
11297ccd0791SJan Kara 		goto out_unlock;
11307ccd0791SJan Kara 	}
11311da177e4SLinus Torvalds 
11324ceddce5SMauricio Faria de Oliveira 	if (test_bit(QUEUE_FLAG_WC, &lo->lo_queue->queue_flags))
11334ceddce5SMauricio Faria de Oliveira 		blk_queue_write_cache(lo->lo_queue, false, false);
11344ceddce5SMauricio Faria de Oliveira 
1135f8933667SMing Lei 	/* freeze request queue during the transition */
1136f8933667SMing Lei 	blk_mq_freeze_queue(lo->lo_queue);
1137f8933667SMing Lei 
113887579e9bSDan Schatzberg 	destroy_workqueue(lo->workqueue);
113987579e9bSDan Schatzberg 	spin_lock_irq(&lo->lo_work_lock);
114087579e9bSDan Schatzberg 	list_for_each_entry_safe(worker, pos, &lo->idle_worker_list,
114187579e9bSDan Schatzberg 				idle_list) {
114287579e9bSDan Schatzberg 		list_del(&worker->idle_list);
114387579e9bSDan Schatzberg 		rb_erase(&worker->rb_node, &lo->worker_tree);
1144c74d40e8SDan Schatzberg 		css_put(worker->blkcg_css);
114587579e9bSDan Schatzberg 		kfree(worker);
114687579e9bSDan Schatzberg 	}
114787579e9bSDan Schatzberg 	spin_unlock_irq(&lo->lo_work_lock);
114887579e9bSDan Schatzberg 	del_timer_sync(&lo->timer);
114987579e9bSDan Schatzberg 
11501da177e4SLinus Torvalds 	spin_lock_irq(&lo->lo_lock);
11511da177e4SLinus Torvalds 	lo->lo_backing_file = NULL;
115205eb0f25SKay Sievers 	spin_unlock_irq(&lo->lo_lock);
11531da177e4SLinus Torvalds 
11541da177e4SLinus Torvalds 	lo->lo_device = NULL;
11551da177e4SLinus Torvalds 	lo->lo_offset = 0;
11561da177e4SLinus Torvalds 	lo->lo_sizelimit = 0;
11571da177e4SLinus Torvalds 	memset(lo->lo_file_name, 0, LO_NAME_SIZE);
115889e4fdecSOmar Sandoval 	blk_queue_logical_block_size(lo->lo_queue, 512);
1159bf093753SOmar Sandoval 	blk_queue_physical_block_size(lo->lo_queue, 512);
1160bf093753SOmar Sandoval 	blk_queue_io_min(lo->lo_queue, 512);
1161c1681bf8SAnatol Pomozov 	if (bdev) {
1162f98393a6SPeter Zijlstra 		invalidate_bdev(bdev);
1163eedffa28SJeff Layton 		bdev->bd_inode->i_mapping->wb_err = 0;
1164c1681bf8SAnatol Pomozov 	}
116573285082SKen Chen 	set_capacity(lo->lo_disk, 0);
116651a0bb0cSMilan Broz 	loop_sysfs_exit(lo);
1167c3473c63SDavid Zeuthen 	if (bdev) {
1168c3473c63SDavid Zeuthen 		/* let user-space know about this change */
1169c3473c63SDavid Zeuthen 		kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, KOBJ_CHANGE);
1170c3473c63SDavid Zeuthen 	}
11711da177e4SLinus Torvalds 	mapping_set_gfp_mask(filp->f_mapping, gfp);
11721da177e4SLinus Torvalds 	/* This is safe: open() is still holding a reference. */
11731da177e4SLinus Torvalds 	module_put(THIS_MODULE);
1174f8933667SMing Lei 	blk_mq_unfreeze_queue(lo->lo_queue);
1175f8933667SMing Lei 
11760da03cabSJan Kara 	partscan = lo->lo_flags & LO_FLAGS_PARTSCAN && bdev;
11770da03cabSJan Kara 	lo_number = lo->lo_number;
11789f65c489SMatteo Croce 	disk_force_media_change(lo->lo_disk, DISK_EVENT_MEDIA_CHANGE);
11790da03cabSJan Kara out_unlock:
11806cc8e743SPavel Tatashin 	mutex_unlock(&lo->lo_mutex);
11810da03cabSJan Kara 	if (partscan) {
1182d57f3374SJan Kara 		/*
1183a8698707SChristoph Hellwig 		 * open_mutex has been held already in release path, so don't
1184d57f3374SJan Kara 		 * acquire it if this function is called in such case.
1185d57f3374SJan Kara 		 *
1186d57f3374SJan Kara 		 * If the reread partition isn't from release path, lo_refcnt
1187d57f3374SJan Kara 		 * must be at least one and it can only become zero when the
1188d57f3374SJan Kara 		 * current holder is released.
1189d57f3374SJan Kara 		 */
1190f0b870dfSChristoph Hellwig 		if (!release)
11910384264eSChristoph Hellwig 			mutex_lock(&lo->lo_disk->open_mutex);
11920384264eSChristoph Hellwig 		err = bdev_disk_changed(lo->lo_disk, false);
1193f0b870dfSChristoph Hellwig 		if (!release)
11940384264eSChristoph Hellwig 			mutex_unlock(&lo->lo_disk->open_mutex);
119540853d6fSDongli Zhang 		if (err)
1196d57f3374SJan Kara 			pr_warn("%s: partition scan of loop%d failed (rc=%d)\n",
11970da03cabSJan Kara 				__func__, lo_number, err);
1198d57f3374SJan Kara 		/* Device is gone, no point in returning error */
1199d57f3374SJan Kara 		err = 0;
1200d57f3374SJan Kara 	}
1201758a58d0SDongli Zhang 
1202758a58d0SDongli Zhang 	/*
1203758a58d0SDongli Zhang 	 * lo->lo_state is set to Lo_unbound here after above partscan has
1204758a58d0SDongli Zhang 	 * finished.
1205758a58d0SDongli Zhang 	 *
1206758a58d0SDongli Zhang 	 * There cannot be anybody else entering __loop_clr_fd() as
1207758a58d0SDongli Zhang 	 * lo->lo_backing_file is already cleared and Lo_rundown state
1208758a58d0SDongli Zhang 	 * protects us from all the other places trying to change the 'lo'
1209758a58d0SDongli Zhang 	 * device.
1210758a58d0SDongli Zhang 	 */
12116cc8e743SPavel Tatashin 	mutex_lock(&lo->lo_mutex);
1212758a58d0SDongli Zhang 	lo->lo_flags = 0;
1213758a58d0SDongli Zhang 	if (!part_shift)
1214758a58d0SDongli Zhang 		lo->lo_disk->flags |= GENHD_FL_NO_PART_SCAN;
1215758a58d0SDongli Zhang 	lo->lo_state = Lo_unbound;
12166cc8e743SPavel Tatashin 	mutex_unlock(&lo->lo_mutex);
1217758a58d0SDongli Zhang 
1218f028f3b2SNikanth Karthikesan 	/*
12196cc8e743SPavel Tatashin 	 * Need not hold lo_mutex to fput backing file. Calling fput holding
12206cc8e743SPavel Tatashin 	 * lo_mutex triggers a circular lock dependency possibility warning as
1221a8698707SChristoph Hellwig 	 * fput can take open_mutex which is usually taken before lo_mutex.
1222f028f3b2SNikanth Karthikesan 	 */
12237ccd0791SJan Kara 	if (filp)
1224f028f3b2SNikanth Karthikesan 		fput(filp);
12257ccd0791SJan Kara 	return err;
12261da177e4SLinus Torvalds }
12271da177e4SLinus Torvalds 
1228a2505b79SJan Kara static int loop_clr_fd(struct loop_device *lo)
1229a2505b79SJan Kara {
12307ccd0791SJan Kara 	int err;
12317ccd0791SJan Kara 
12326cc8e743SPavel Tatashin 	err = mutex_lock_killable(&lo->lo_mutex);
12337ccd0791SJan Kara 	if (err)
12347ccd0791SJan Kara 		return err;
12357ccd0791SJan Kara 	if (lo->lo_state != Lo_bound) {
12366cc8e743SPavel Tatashin 		mutex_unlock(&lo->lo_mutex);
1237a2505b79SJan Kara 		return -ENXIO;
12387ccd0791SJan Kara 	}
1239a2505b79SJan Kara 	/*
1240a2505b79SJan Kara 	 * If we've explicitly asked to tear down the loop device,
1241a2505b79SJan Kara 	 * and it has an elevated reference count, set it for auto-teardown when
1242a2505b79SJan Kara 	 * the last reference goes away. This stops $!~#$@ udev from
1243a2505b79SJan Kara 	 * preventing teardown because it decided that it needs to run blkid on
1244a2505b79SJan Kara 	 * the loopback device whenever they appear. xfstests is notorious for
1245a2505b79SJan Kara 	 * failing tests because blkid via udev races with a losetup
1246a2505b79SJan Kara 	 * <dev>/do something like mkfs/losetup -d <dev> causing the losetup -d
1247a2505b79SJan Kara 	 * command to fail with EBUSY.
1248a2505b79SJan Kara 	 */
1249a2505b79SJan Kara 	if (atomic_read(&lo->lo_refcnt) > 1) {
1250a2505b79SJan Kara 		lo->lo_flags |= LO_FLAGS_AUTOCLEAR;
12516cc8e743SPavel Tatashin 		mutex_unlock(&lo->lo_mutex);
1252a2505b79SJan Kara 		return 0;
1253a2505b79SJan Kara 	}
1254a2505b79SJan Kara 	lo->lo_state = Lo_rundown;
12556cc8e743SPavel Tatashin 	mutex_unlock(&lo->lo_mutex);
1256a2505b79SJan Kara 
12570da03cabSJan Kara 	return __loop_clr_fd(lo, false);
1258a2505b79SJan Kara }
1259a2505b79SJan Kara 
12601da177e4SLinus Torvalds static int
12611da177e4SLinus Torvalds loop_set_status(struct loop_device *lo, const struct loop_info64 *info)
12621da177e4SLinus Torvalds {
12631da177e4SLinus Torvalds 	int err;
1264faf1d254SMartijn Coenen 	int prev_lo_flags;
126585b0a54aSJan Kara 	bool partscan = false;
12660c3796c2SMartijn Coenen 	bool size_changed = false;
12671da177e4SLinus Torvalds 
12686cc8e743SPavel Tatashin 	err = mutex_lock_killable(&lo->lo_mutex);
1269550df5fdSJan Kara 	if (err)
1270550df5fdSJan Kara 		return err;
1271550df5fdSJan Kara 	if (lo->lo_state != Lo_bound) {
1272550df5fdSJan Kara 		err = -ENXIO;
1273550df5fdSJan Kara 		goto out_unlock;
1274550df5fdSJan Kara 	}
12751da177e4SLinus Torvalds 
12765db470e2SJaegeuk Kim 	if (lo->lo_offset != info->lo_offset ||
12775db470e2SJaegeuk Kim 	    lo->lo_sizelimit != info->lo_sizelimit) {
12780c3796c2SMartijn Coenen 		size_changed = true;
12795db470e2SJaegeuk Kim 		sync_blockdev(lo->lo_device);
1280f4bd34b1SZheng Bin 		invalidate_bdev(lo->lo_device);
12815db470e2SJaegeuk Kim 	}
12825db470e2SJaegeuk Kim 
1283ecdd0959SMing Lei 	/* I/O need to be drained during transfer transition */
1284ecdd0959SMing Lei 	blk_mq_freeze_queue(lo->lo_queue);
1285ecdd0959SMing Lei 
12860c3796c2SMartijn Coenen 	if (size_changed && lo->lo_device->bd_inode->i_mapping->nrpages) {
1287f4bd34b1SZheng Bin 		/* If any pages were dirtied after invalidate_bdev(), try again */
12885db470e2SJaegeuk Kim 		err = -EAGAIN;
12895db470e2SJaegeuk Kim 		pr_warn("%s: loop%d (%s) has still dirty pages (nrpages=%lu)\n",
12905db470e2SJaegeuk Kim 			__func__, lo->lo_number, lo->lo_file_name,
12915db470e2SJaegeuk Kim 			lo->lo_device->bd_inode->i_mapping->nrpages);
12925db470e2SJaegeuk Kim 		goto out_unfreeze;
12935db470e2SJaegeuk Kim 	}
12940c3796c2SMartijn Coenen 
1295faf1d254SMartijn Coenen 	prev_lo_flags = lo->lo_flags;
1296faf1d254SMartijn Coenen 
12970c3796c2SMartijn Coenen 	err = loop_set_status_from_info(lo, info);
12980c3796c2SMartijn Coenen 	if (err)
1299550df5fdSJan Kara 		goto out_unfreeze;
13000c3796c2SMartijn Coenen 
1301faf1d254SMartijn Coenen 	/* Mask out flags that can't be set using LOOP_SET_STATUS. */
13026ac92fb5SMartijn Coenen 	lo->lo_flags &= LOOP_SET_STATUS_SETTABLE_FLAGS;
1303faf1d254SMartijn Coenen 	/* For those flags, use the previous values instead */
1304faf1d254SMartijn Coenen 	lo->lo_flags |= prev_lo_flags & ~LOOP_SET_STATUS_SETTABLE_FLAGS;
1305faf1d254SMartijn Coenen 	/* For flags that can't be cleared, use previous values too */
1306faf1d254SMartijn Coenen 	lo->lo_flags |= prev_lo_flags & ~LOOP_SET_STATUS_CLEARABLE_FLAGS;
1307faf1d254SMartijn Coenen 
1308b0bd158dSMartijn Coenen 	if (size_changed) {
1309b0bd158dSMartijn Coenen 		loff_t new_size = get_size(lo->lo_offset, lo->lo_sizelimit,
1310b0bd158dSMartijn Coenen 					   lo->lo_backing_file);
1311b0bd158dSMartijn Coenen 		loop_set_size(lo, new_size);
1312b040ad9cSArnd Bergmann 	}
1313541c742aSGuo Chao 
1314dfaa2ef6SLukas Czerner 	loop_config_discard(lo);
13151da177e4SLinus Torvalds 
13162e5ab5f3SMing Lei 	/* update dio if lo_offset or transfer is changed */
13172e5ab5f3SMing Lei 	__loop_update_dio(lo, lo->use_dio);
13182e5ab5f3SMing Lei 
1319550df5fdSJan Kara out_unfreeze:
1320ecdd0959SMing Lei 	blk_mq_unfreeze_queue(lo->lo_queue);
1321e02898b4SOmar Sandoval 
1322faf1d254SMartijn Coenen 	if (!err && (lo->lo_flags & LO_FLAGS_PARTSCAN) &&
1323faf1d254SMartijn Coenen 	     !(prev_lo_flags & LO_FLAGS_PARTSCAN)) {
1324e02898b4SOmar Sandoval 		lo->lo_disk->flags &= ~GENHD_FL_NO_PART_SCAN;
132585b0a54aSJan Kara 		partscan = true;
1326e02898b4SOmar Sandoval 	}
1327550df5fdSJan Kara out_unlock:
13286cc8e743SPavel Tatashin 	mutex_unlock(&lo->lo_mutex);
132985b0a54aSJan Kara 	if (partscan)
13300384264eSChristoph Hellwig 		loop_reread_partitions(lo);
1331e02898b4SOmar Sandoval 
1332ecdd0959SMing Lei 	return err;
13331da177e4SLinus Torvalds }
13341da177e4SLinus Torvalds 
13351da177e4SLinus Torvalds static int
13361da177e4SLinus Torvalds loop_get_status(struct loop_device *lo, struct loop_info64 *info)
13371da177e4SLinus Torvalds {
1338b1ab5fa3STetsuo Handa 	struct path path;
13391da177e4SLinus Torvalds 	struct kstat stat;
13402d1d4c1eSOmar Sandoval 	int ret;
13411da177e4SLinus Torvalds 
13426cc8e743SPavel Tatashin 	ret = mutex_lock_killable(&lo->lo_mutex);
13434a5ce9baSJan Kara 	if (ret)
13444a5ce9baSJan Kara 		return ret;
13452d1d4c1eSOmar Sandoval 	if (lo->lo_state != Lo_bound) {
13466cc8e743SPavel Tatashin 		mutex_unlock(&lo->lo_mutex);
13471da177e4SLinus Torvalds 		return -ENXIO;
13482d1d4c1eSOmar Sandoval 	}
13492d1d4c1eSOmar Sandoval 
13501da177e4SLinus Torvalds 	memset(info, 0, sizeof(*info));
13511da177e4SLinus Torvalds 	info->lo_number = lo->lo_number;
13521da177e4SLinus Torvalds 	info->lo_offset = lo->lo_offset;
13531da177e4SLinus Torvalds 	info->lo_sizelimit = lo->lo_sizelimit;
13541da177e4SLinus Torvalds 	info->lo_flags = lo->lo_flags;
13551da177e4SLinus Torvalds 	memcpy(info->lo_file_name, lo->lo_file_name, LO_NAME_SIZE);
13562d1d4c1eSOmar Sandoval 
13576cc8e743SPavel Tatashin 	/* Drop lo_mutex while we call into the filesystem. */
1358b1ab5fa3STetsuo Handa 	path = lo->lo_backing_file->f_path;
1359b1ab5fa3STetsuo Handa 	path_get(&path);
13606cc8e743SPavel Tatashin 	mutex_unlock(&lo->lo_mutex);
1361b1ab5fa3STetsuo Handa 	ret = vfs_getattr(&path, &stat, STATX_INO, AT_STATX_SYNC_AS_STAT);
13622d1d4c1eSOmar Sandoval 	if (!ret) {
13632d1d4c1eSOmar Sandoval 		info->lo_device = huge_encode_dev(stat.dev);
13642d1d4c1eSOmar Sandoval 		info->lo_inode = stat.ino;
13652d1d4c1eSOmar Sandoval 		info->lo_rdevice = huge_encode_dev(stat.rdev);
13662d1d4c1eSOmar Sandoval 	}
1367b1ab5fa3STetsuo Handa 	path_put(&path);
13682d1d4c1eSOmar Sandoval 	return ret;
13691da177e4SLinus Torvalds }
13701da177e4SLinus Torvalds 
13711da177e4SLinus Torvalds static void
13721da177e4SLinus Torvalds loop_info64_from_old(const struct loop_info *info, struct loop_info64 *info64)
13731da177e4SLinus Torvalds {
13741da177e4SLinus Torvalds 	memset(info64, 0, sizeof(*info64));
13751da177e4SLinus Torvalds 	info64->lo_number = info->lo_number;
13761da177e4SLinus Torvalds 	info64->lo_device = info->lo_device;
13771da177e4SLinus Torvalds 	info64->lo_inode = info->lo_inode;
13781da177e4SLinus Torvalds 	info64->lo_rdevice = info->lo_rdevice;
13791da177e4SLinus Torvalds 	info64->lo_offset = info->lo_offset;
13801da177e4SLinus Torvalds 	info64->lo_sizelimit = 0;
13811da177e4SLinus Torvalds 	info64->lo_flags = info->lo_flags;
13821da177e4SLinus Torvalds 	memcpy(info64->lo_file_name, info->lo_name, LO_NAME_SIZE);
13831da177e4SLinus Torvalds }
13841da177e4SLinus Torvalds 
13851da177e4SLinus Torvalds static int
13861da177e4SLinus Torvalds loop_info64_to_old(const struct loop_info64 *info64, struct loop_info *info)
13871da177e4SLinus Torvalds {
13881da177e4SLinus Torvalds 	memset(info, 0, sizeof(*info));
13891da177e4SLinus Torvalds 	info->lo_number = info64->lo_number;
13901da177e4SLinus Torvalds 	info->lo_device = info64->lo_device;
13911da177e4SLinus Torvalds 	info->lo_inode = info64->lo_inode;
13921da177e4SLinus Torvalds 	info->lo_rdevice = info64->lo_rdevice;
13931da177e4SLinus Torvalds 	info->lo_offset = info64->lo_offset;
13941da177e4SLinus Torvalds 	info->lo_flags = info64->lo_flags;
13951da177e4SLinus Torvalds 	memcpy(info->lo_name, info64->lo_file_name, LO_NAME_SIZE);
13961da177e4SLinus Torvalds 
13971da177e4SLinus Torvalds 	/* error in case values were truncated */
13981da177e4SLinus Torvalds 	if (info->lo_device != info64->lo_device ||
13991da177e4SLinus Torvalds 	    info->lo_rdevice != info64->lo_rdevice ||
14001da177e4SLinus Torvalds 	    info->lo_inode != info64->lo_inode ||
14011da177e4SLinus Torvalds 	    info->lo_offset != info64->lo_offset)
14021da177e4SLinus Torvalds 		return -EOVERFLOW;
14031da177e4SLinus Torvalds 
14041da177e4SLinus Torvalds 	return 0;
14051da177e4SLinus Torvalds }
14061da177e4SLinus Torvalds 
14071da177e4SLinus Torvalds static int
14081da177e4SLinus Torvalds loop_set_status_old(struct loop_device *lo, const struct loop_info __user *arg)
14091da177e4SLinus Torvalds {
14101da177e4SLinus Torvalds 	struct loop_info info;
14111da177e4SLinus Torvalds 	struct loop_info64 info64;
14121da177e4SLinus Torvalds 
14131da177e4SLinus Torvalds 	if (copy_from_user(&info, arg, sizeof (struct loop_info)))
14141da177e4SLinus Torvalds 		return -EFAULT;
14151da177e4SLinus Torvalds 	loop_info64_from_old(&info, &info64);
14161da177e4SLinus Torvalds 	return loop_set_status(lo, &info64);
14171da177e4SLinus Torvalds }
14181da177e4SLinus Torvalds 
14191da177e4SLinus Torvalds static int
14201da177e4SLinus Torvalds loop_set_status64(struct loop_device *lo, const struct loop_info64 __user *arg)
14211da177e4SLinus Torvalds {
14221da177e4SLinus Torvalds 	struct loop_info64 info64;
14231da177e4SLinus Torvalds 
14241da177e4SLinus Torvalds 	if (copy_from_user(&info64, arg, sizeof (struct loop_info64)))
14251da177e4SLinus Torvalds 		return -EFAULT;
14261da177e4SLinus Torvalds 	return loop_set_status(lo, &info64);
14271da177e4SLinus Torvalds }
14281da177e4SLinus Torvalds 
14291da177e4SLinus Torvalds static int
14301da177e4SLinus Torvalds loop_get_status_old(struct loop_device *lo, struct loop_info __user *arg) {
14311da177e4SLinus Torvalds 	struct loop_info info;
14321da177e4SLinus Torvalds 	struct loop_info64 info64;
1433bdac616dSOmar Sandoval 	int err;
14341da177e4SLinus Torvalds 
14354a5ce9baSJan Kara 	if (!arg)
1436bdac616dSOmar Sandoval 		return -EINVAL;
14371da177e4SLinus Torvalds 	err = loop_get_status(lo, &info64);
14381da177e4SLinus Torvalds 	if (!err)
14391da177e4SLinus Torvalds 		err = loop_info64_to_old(&info64, &info);
14401da177e4SLinus Torvalds 	if (!err && copy_to_user(arg, &info, sizeof(info)))
14411da177e4SLinus Torvalds 		err = -EFAULT;
14421da177e4SLinus Torvalds 
14431da177e4SLinus Torvalds 	return err;
14441da177e4SLinus Torvalds }
14451da177e4SLinus Torvalds 
14461da177e4SLinus Torvalds static int
14471da177e4SLinus Torvalds loop_get_status64(struct loop_device *lo, struct loop_info64 __user *arg) {
14481da177e4SLinus Torvalds 	struct loop_info64 info64;
1449bdac616dSOmar Sandoval 	int err;
14501da177e4SLinus Torvalds 
14514a5ce9baSJan Kara 	if (!arg)
1452bdac616dSOmar Sandoval 		return -EINVAL;
14531da177e4SLinus Torvalds 	err = loop_get_status(lo, &info64);
14541da177e4SLinus Torvalds 	if (!err && copy_to_user(arg, &info64, sizeof(info64)))
14551da177e4SLinus Torvalds 		err = -EFAULT;
14561da177e4SLinus Torvalds 
14571da177e4SLinus Torvalds 	return err;
14581da177e4SLinus Torvalds }
14591da177e4SLinus Torvalds 
146051001b7dSHannes Reinecke static int loop_set_capacity(struct loop_device *lo)
146153d66608SJ. R. Okajima {
14620a6ed1b5SMartijn Coenen 	loff_t size;
14630a6ed1b5SMartijn Coenen 
146453d66608SJ. R. Okajima 	if (unlikely(lo->lo_state != Lo_bound))
14657b0576a3SGuo Chao 		return -ENXIO;
146653d66608SJ. R. Okajima 
14670a6ed1b5SMartijn Coenen 	size = get_loop_size(lo, lo->lo_backing_file);
14680a6ed1b5SMartijn Coenen 	loop_set_size(lo, size);
1469083a6a50SMartijn Coenen 
1470083a6a50SMartijn Coenen 	return 0;
147153d66608SJ. R. Okajima }
147253d66608SJ. R. Okajima 
1473ab1cb278SMing Lei static int loop_set_dio(struct loop_device *lo, unsigned long arg)
1474ab1cb278SMing Lei {
1475ab1cb278SMing Lei 	int error = -ENXIO;
1476ab1cb278SMing Lei 	if (lo->lo_state != Lo_bound)
1477ab1cb278SMing Lei 		goto out;
1478ab1cb278SMing Lei 
1479ab1cb278SMing Lei 	__loop_update_dio(lo, !!arg);
1480ab1cb278SMing Lei 	if (lo->use_dio == !!arg)
1481ab1cb278SMing Lei 		return 0;
1482ab1cb278SMing Lei 	error = -EINVAL;
1483ab1cb278SMing Lei  out:
1484ab1cb278SMing Lei 	return error;
1485ab1cb278SMing Lei }
1486ab1cb278SMing Lei 
148789e4fdecSOmar Sandoval static int loop_set_block_size(struct loop_device *lo, unsigned long arg)
148889e4fdecSOmar Sandoval {
14895db470e2SJaegeuk Kim 	int err = 0;
14905db470e2SJaegeuk Kim 
149189e4fdecSOmar Sandoval 	if (lo->lo_state != Lo_bound)
149289e4fdecSOmar Sandoval 		return -ENXIO;
149389e4fdecSOmar Sandoval 
14943448914eSMartijn Coenen 	err = loop_validate_block_size(arg);
14953448914eSMartijn Coenen 	if (err)
14963448914eSMartijn Coenen 		return err;
149789e4fdecSOmar Sandoval 
14987e81f99aSMartijn Coenen 	if (lo->lo_queue->limits.logical_block_size == arg)
14997e81f99aSMartijn Coenen 		return 0;
15007e81f99aSMartijn Coenen 
15015db470e2SJaegeuk Kim 	sync_blockdev(lo->lo_device);
1502f4bd34b1SZheng Bin 	invalidate_bdev(lo->lo_device);
15035db470e2SJaegeuk Kim 
150489e4fdecSOmar Sandoval 	blk_mq_freeze_queue(lo->lo_queue);
150589e4fdecSOmar Sandoval 
1506f4bd34b1SZheng Bin 	/* invalidate_bdev should have truncated all the pages */
15077e81f99aSMartijn Coenen 	if (lo->lo_device->bd_inode->i_mapping->nrpages) {
15085db470e2SJaegeuk Kim 		err = -EAGAIN;
15095db470e2SJaegeuk Kim 		pr_warn("%s: loop%d (%s) has still dirty pages (nrpages=%lu)\n",
15105db470e2SJaegeuk Kim 			__func__, lo->lo_number, lo->lo_file_name,
15115db470e2SJaegeuk Kim 			lo->lo_device->bd_inode->i_mapping->nrpages);
15125db470e2SJaegeuk Kim 		goto out_unfreeze;
15135db470e2SJaegeuk Kim 	}
15145db470e2SJaegeuk Kim 
151589e4fdecSOmar Sandoval 	blk_queue_logical_block_size(lo->lo_queue, arg);
1516bf093753SOmar Sandoval 	blk_queue_physical_block_size(lo->lo_queue, arg);
1517bf093753SOmar Sandoval 	blk_queue_io_min(lo->lo_queue, arg);
151889e4fdecSOmar Sandoval 	loop_update_dio(lo);
15195db470e2SJaegeuk Kim out_unfreeze:
152089e4fdecSOmar Sandoval 	blk_mq_unfreeze_queue(lo->lo_queue);
152189e4fdecSOmar Sandoval 
15225db470e2SJaegeuk Kim 	return err;
152389e4fdecSOmar Sandoval }
152489e4fdecSOmar Sandoval 
1525a1316544SJan Kara static int lo_simple_ioctl(struct loop_device *lo, unsigned int cmd,
1526a1316544SJan Kara 			   unsigned long arg)
15271da177e4SLinus Torvalds {
15281da177e4SLinus Torvalds 	int err;
15291da177e4SLinus Torvalds 
15306cc8e743SPavel Tatashin 	err = mutex_lock_killable(&lo->lo_mutex);
15313148ffbdSOmar Sandoval 	if (err)
1532a1316544SJan Kara 		return err;
15331da177e4SLinus Torvalds 	switch (cmd) {
153453d66608SJ. R. Okajima 	case LOOP_SET_CAPACITY:
153551001b7dSHannes Reinecke 		err = loop_set_capacity(lo);
153653d66608SJ. R. Okajima 		break;
1537ab1cb278SMing Lei 	case LOOP_SET_DIRECT_IO:
1538ab1cb278SMing Lei 		err = loop_set_dio(lo, arg);
1539ab1cb278SMing Lei 		break;
154089e4fdecSOmar Sandoval 	case LOOP_SET_BLOCK_SIZE:
154189e4fdecSOmar Sandoval 		err = loop_set_block_size(lo, arg);
154289e4fdecSOmar Sandoval 		break;
15431da177e4SLinus Torvalds 	default:
1544*47e96246SChristoph Hellwig 		err = -EINVAL;
15451da177e4SLinus Torvalds 	}
15466cc8e743SPavel Tatashin 	mutex_unlock(&lo->lo_mutex);
1547a1316544SJan Kara 	return err;
1548a1316544SJan Kara }
1549f028f3b2SNikanth Karthikesan 
1550a1316544SJan Kara static int lo_ioctl(struct block_device *bdev, fmode_t mode,
1551a1316544SJan Kara 	unsigned int cmd, unsigned long arg)
1552a1316544SJan Kara {
1553a1316544SJan Kara 	struct loop_device *lo = bdev->bd_disk->private_data;
1554571fae6eSMartijn Coenen 	void __user *argp = (void __user *) arg;
1555a1316544SJan Kara 	int err;
1556a1316544SJan Kara 
1557a1316544SJan Kara 	switch (cmd) {
15583448914eSMartijn Coenen 	case LOOP_SET_FD: {
15593448914eSMartijn Coenen 		/*
15603448914eSMartijn Coenen 		 * Legacy case - pass in a zeroed out struct loop_config with
15613448914eSMartijn Coenen 		 * only the file descriptor set , which corresponds with the
15623448914eSMartijn Coenen 		 * default parameters we'd have used otherwise.
15633448914eSMartijn Coenen 		 */
15643448914eSMartijn Coenen 		struct loop_config config;
15653448914eSMartijn Coenen 
15663448914eSMartijn Coenen 		memset(&config, 0, sizeof(config));
15673448914eSMartijn Coenen 		config.fd = arg;
15683448914eSMartijn Coenen 
15693448914eSMartijn Coenen 		return loop_configure(lo, mode, bdev, &config);
15703448914eSMartijn Coenen 	}
15713448914eSMartijn Coenen 	case LOOP_CONFIGURE: {
15723448914eSMartijn Coenen 		struct loop_config config;
15733448914eSMartijn Coenen 
15743448914eSMartijn Coenen 		if (copy_from_user(&config, argp, sizeof(config)))
15753448914eSMartijn Coenen 			return -EFAULT;
15763448914eSMartijn Coenen 
15773448914eSMartijn Coenen 		return loop_configure(lo, mode, bdev, &config);
15783448914eSMartijn Coenen 	}
1579a1316544SJan Kara 	case LOOP_CHANGE_FD:
1580c3710770SJan Kara 		return loop_change_fd(lo, bdev, arg);
1581a1316544SJan Kara 	case LOOP_CLR_FD:
15827ccd0791SJan Kara 		return loop_clr_fd(lo);
1583a1316544SJan Kara 	case LOOP_SET_STATUS:
1584a1316544SJan Kara 		err = -EPERM;
1585a1316544SJan Kara 		if ((mode & FMODE_WRITE) || capable(CAP_SYS_ADMIN)) {
1586571fae6eSMartijn Coenen 			err = loop_set_status_old(lo, argp);
1587a1316544SJan Kara 		}
1588a1316544SJan Kara 		break;
1589a1316544SJan Kara 	case LOOP_GET_STATUS:
1590571fae6eSMartijn Coenen 		return loop_get_status_old(lo, argp);
1591a1316544SJan Kara 	case LOOP_SET_STATUS64:
1592a1316544SJan Kara 		err = -EPERM;
1593a1316544SJan Kara 		if ((mode & FMODE_WRITE) || capable(CAP_SYS_ADMIN)) {
1594571fae6eSMartijn Coenen 			err = loop_set_status64(lo, argp);
1595a1316544SJan Kara 		}
1596a1316544SJan Kara 		break;
1597a1316544SJan Kara 	case LOOP_GET_STATUS64:
1598571fae6eSMartijn Coenen 		return loop_get_status64(lo, argp);
1599a1316544SJan Kara 	case LOOP_SET_CAPACITY:
1600a1316544SJan Kara 	case LOOP_SET_DIRECT_IO:
1601a1316544SJan Kara 	case LOOP_SET_BLOCK_SIZE:
1602a1316544SJan Kara 		if (!(mode & FMODE_WRITE) && !capable(CAP_SYS_ADMIN))
1603a1316544SJan Kara 			return -EPERM;
1604df561f66SGustavo A. R. Silva 		fallthrough;
1605a1316544SJan Kara 	default:
1606a1316544SJan Kara 		err = lo_simple_ioctl(lo, cmd, arg);
1607a1316544SJan Kara 		break;
1608a1316544SJan Kara 	}
1609a1316544SJan Kara 
16101da177e4SLinus Torvalds 	return err;
16111da177e4SLinus Torvalds }
16121da177e4SLinus Torvalds 
1613863d5b82SDavid Howells #ifdef CONFIG_COMPAT
1614863d5b82SDavid Howells struct compat_loop_info {
1615863d5b82SDavid Howells 	compat_int_t	lo_number;      /* ioctl r/o */
1616863d5b82SDavid Howells 	compat_dev_t	lo_device;      /* ioctl r/o */
1617863d5b82SDavid Howells 	compat_ulong_t	lo_inode;       /* ioctl r/o */
1618863d5b82SDavid Howells 	compat_dev_t	lo_rdevice;     /* ioctl r/o */
1619863d5b82SDavid Howells 	compat_int_t	lo_offset;
1620863d5b82SDavid Howells 	compat_int_t	lo_encrypt_key_size;    /* ioctl w/o */
1621863d5b82SDavid Howells 	compat_int_t	lo_flags;       /* ioctl r/o */
1622863d5b82SDavid Howells 	char		lo_name[LO_NAME_SIZE];
1623863d5b82SDavid Howells 	unsigned char	lo_encrypt_key[LO_KEY_SIZE]; /* ioctl w/o */
1624863d5b82SDavid Howells 	compat_ulong_t	lo_init[2];
1625863d5b82SDavid Howells 	char		reserved[4];
1626863d5b82SDavid Howells };
1627863d5b82SDavid Howells 
1628863d5b82SDavid Howells /*
1629863d5b82SDavid Howells  * Transfer 32-bit compatibility structure in userspace to 64-bit loop info
1630863d5b82SDavid Howells  * - noinlined to reduce stack space usage in main part of driver
1631863d5b82SDavid Howells  */
1632863d5b82SDavid Howells static noinline int
1633ba674cfcSAl Viro loop_info64_from_compat(const struct compat_loop_info __user *arg,
1634863d5b82SDavid Howells 			struct loop_info64 *info64)
1635863d5b82SDavid Howells {
1636863d5b82SDavid Howells 	struct compat_loop_info info;
1637863d5b82SDavid Howells 
1638863d5b82SDavid Howells 	if (copy_from_user(&info, arg, sizeof(info)))
1639863d5b82SDavid Howells 		return -EFAULT;
1640863d5b82SDavid Howells 
1641863d5b82SDavid Howells 	memset(info64, 0, sizeof(*info64));
1642863d5b82SDavid Howells 	info64->lo_number = info.lo_number;
1643863d5b82SDavid Howells 	info64->lo_device = info.lo_device;
1644863d5b82SDavid Howells 	info64->lo_inode = info.lo_inode;
1645863d5b82SDavid Howells 	info64->lo_rdevice = info.lo_rdevice;
1646863d5b82SDavid Howells 	info64->lo_offset = info.lo_offset;
1647863d5b82SDavid Howells 	info64->lo_sizelimit = 0;
1648863d5b82SDavid Howells 	info64->lo_flags = info.lo_flags;
1649863d5b82SDavid Howells 	memcpy(info64->lo_file_name, info.lo_name, LO_NAME_SIZE);
1650863d5b82SDavid Howells 	return 0;
1651863d5b82SDavid Howells }
1652863d5b82SDavid Howells 
1653863d5b82SDavid Howells /*
1654863d5b82SDavid Howells  * Transfer 64-bit loop info to 32-bit compatibility structure in userspace
1655863d5b82SDavid Howells  * - noinlined to reduce stack space usage in main part of driver
1656863d5b82SDavid Howells  */
1657863d5b82SDavid Howells static noinline int
1658863d5b82SDavid Howells loop_info64_to_compat(const struct loop_info64 *info64,
1659863d5b82SDavid Howells 		      struct compat_loop_info __user *arg)
1660863d5b82SDavid Howells {
1661863d5b82SDavid Howells 	struct compat_loop_info info;
1662863d5b82SDavid Howells 
1663863d5b82SDavid Howells 	memset(&info, 0, sizeof(info));
1664863d5b82SDavid Howells 	info.lo_number = info64->lo_number;
1665863d5b82SDavid Howells 	info.lo_device = info64->lo_device;
1666863d5b82SDavid Howells 	info.lo_inode = info64->lo_inode;
1667863d5b82SDavid Howells 	info.lo_rdevice = info64->lo_rdevice;
1668863d5b82SDavid Howells 	info.lo_offset = info64->lo_offset;
1669863d5b82SDavid Howells 	info.lo_flags = info64->lo_flags;
1670863d5b82SDavid Howells 	memcpy(info.lo_name, info64->lo_file_name, LO_NAME_SIZE);
1671863d5b82SDavid Howells 
1672863d5b82SDavid Howells 	/* error in case values were truncated */
1673863d5b82SDavid Howells 	if (info.lo_device != info64->lo_device ||
1674863d5b82SDavid Howells 	    info.lo_rdevice != info64->lo_rdevice ||
1675863d5b82SDavid Howells 	    info.lo_inode != info64->lo_inode ||
1676*47e96246SChristoph Hellwig 	    info.lo_offset != info64->lo_offset)
1677863d5b82SDavid Howells 		return -EOVERFLOW;
1678863d5b82SDavid Howells 
1679863d5b82SDavid Howells 	if (copy_to_user(arg, &info, sizeof(info)))
1680863d5b82SDavid Howells 		return -EFAULT;
1681863d5b82SDavid Howells 	return 0;
1682863d5b82SDavid Howells }
1683863d5b82SDavid Howells 
1684863d5b82SDavid Howells static int
1685863d5b82SDavid Howells loop_set_status_compat(struct loop_device *lo,
1686863d5b82SDavid Howells 		       const struct compat_loop_info __user *arg)
1687863d5b82SDavid Howells {
1688863d5b82SDavid Howells 	struct loop_info64 info64;
1689863d5b82SDavid Howells 	int ret;
1690863d5b82SDavid Howells 
1691863d5b82SDavid Howells 	ret = loop_info64_from_compat(arg, &info64);
1692863d5b82SDavid Howells 	if (ret < 0)
1693863d5b82SDavid Howells 		return ret;
1694863d5b82SDavid Howells 	return loop_set_status(lo, &info64);
1695863d5b82SDavid Howells }
1696863d5b82SDavid Howells 
1697863d5b82SDavid Howells static int
1698863d5b82SDavid Howells loop_get_status_compat(struct loop_device *lo,
1699863d5b82SDavid Howells 		       struct compat_loop_info __user *arg)
1700863d5b82SDavid Howells {
1701863d5b82SDavid Howells 	struct loop_info64 info64;
1702bdac616dSOmar Sandoval 	int err;
1703863d5b82SDavid Howells 
17044a5ce9baSJan Kara 	if (!arg)
1705bdac616dSOmar Sandoval 		return -EINVAL;
1706863d5b82SDavid Howells 	err = loop_get_status(lo, &info64);
1707863d5b82SDavid Howells 	if (!err)
1708863d5b82SDavid Howells 		err = loop_info64_to_compat(&info64, arg);
1709863d5b82SDavid Howells 	return err;
1710863d5b82SDavid Howells }
1711863d5b82SDavid Howells 
1712bb214884SAl Viro static int lo_compat_ioctl(struct block_device *bdev, fmode_t mode,
1713bb214884SAl Viro 			   unsigned int cmd, unsigned long arg)
1714863d5b82SDavid Howells {
1715bb214884SAl Viro 	struct loop_device *lo = bdev->bd_disk->private_data;
1716863d5b82SDavid Howells 	int err;
1717863d5b82SDavid Howells 
1718863d5b82SDavid Howells 	switch(cmd) {
1719863d5b82SDavid Howells 	case LOOP_SET_STATUS:
17203148ffbdSOmar Sandoval 		err = loop_set_status_compat(lo,
17213148ffbdSOmar Sandoval 			     (const struct compat_loop_info __user *)arg);
1722863d5b82SDavid Howells 		break;
1723863d5b82SDavid Howells 	case LOOP_GET_STATUS:
17243148ffbdSOmar Sandoval 		err = loop_get_status_compat(lo,
17253148ffbdSOmar Sandoval 				     (struct compat_loop_info __user *)arg);
1726863d5b82SDavid Howells 		break;
172753d66608SJ. R. Okajima 	case LOOP_SET_CAPACITY:
1728863d5b82SDavid Howells 	case LOOP_CLR_FD:
1729863d5b82SDavid Howells 	case LOOP_GET_STATUS64:
1730863d5b82SDavid Howells 	case LOOP_SET_STATUS64:
17313448914eSMartijn Coenen 	case LOOP_CONFIGURE:
1732863d5b82SDavid Howells 		arg = (unsigned long) compat_ptr(arg);
1733df561f66SGustavo A. R. Silva 		fallthrough;
1734863d5b82SDavid Howells 	case LOOP_SET_FD:
1735863d5b82SDavid Howells 	case LOOP_CHANGE_FD:
17369fea4b39SEvan Green 	case LOOP_SET_BLOCK_SIZE:
1737fdbe4eeeSAlessio Balsini 	case LOOP_SET_DIRECT_IO:
1738bb214884SAl Viro 		err = lo_ioctl(bdev, mode, cmd, arg);
1739863d5b82SDavid Howells 		break;
1740863d5b82SDavid Howells 	default:
1741863d5b82SDavid Howells 		err = -ENOIOCTLCMD;
1742863d5b82SDavid Howells 		break;
1743863d5b82SDavid Howells 	}
1744863d5b82SDavid Howells 	return err;
1745863d5b82SDavid Howells }
1746863d5b82SDavid Howells #endif
1747863d5b82SDavid Howells 
1748bb214884SAl Viro static int lo_open(struct block_device *bdev, fmode_t mode)
17491da177e4SLinus Torvalds {
1750990e7811SChristoph Hellwig 	struct loop_device *lo = bdev->bd_disk->private_data;
17510a42e99bSJan Kara 	int err;
1752770fe30aSKay Sievers 
17536cc8e743SPavel Tatashin 	err = mutex_lock_killable(&lo->lo_mutex);
17546cc8e743SPavel Tatashin 	if (err)
1755770fe30aSKay Sievers 		return err;
1756990e7811SChristoph Hellwig 	if (lo->lo_state == Lo_deleting)
1757990e7811SChristoph Hellwig 		err = -ENXIO;
1758990e7811SChristoph Hellwig 	else
17596cc8e743SPavel Tatashin 		atomic_inc(&lo->lo_refcnt);
17606cc8e743SPavel Tatashin 	mutex_unlock(&lo->lo_mutex);
1761990e7811SChristoph Hellwig 	return err;
17621da177e4SLinus Torvalds }
17631da177e4SLinus Torvalds 
1764967d1dc1SJan Kara static void lo_release(struct gendisk *disk, fmode_t mode)
17651da177e4SLinus Torvalds {
17666cc8e743SPavel Tatashin 	struct loop_device *lo = disk->private_data;
17671da177e4SLinus Torvalds 
17686cc8e743SPavel Tatashin 	mutex_lock(&lo->lo_mutex);
1769f8933667SMing Lei 	if (atomic_dec_return(&lo->lo_refcnt))
17700a42e99bSJan Kara 		goto out_unlock;
1771f8933667SMing Lei 
177214f27939SMilan Broz 	if (lo->lo_flags & LO_FLAGS_AUTOCLEAR) {
1773a2505b79SJan Kara 		if (lo->lo_state != Lo_bound)
1774a2505b79SJan Kara 			goto out_unlock;
1775a2505b79SJan Kara 		lo->lo_state = Lo_rundown;
17766cc8e743SPavel Tatashin 		mutex_unlock(&lo->lo_mutex);
177714f27939SMilan Broz 		/*
177814f27939SMilan Broz 		 * In autoclear mode, stop the loop thread
177914f27939SMilan Broz 		 * and remove configuration after last close.
178014f27939SMilan Broz 		 */
17810da03cabSJan Kara 		__loop_clr_fd(lo, true);
17820a42e99bSJan Kara 		return;
178343cade80SOmar Sandoval 	} else if (lo->lo_state == Lo_bound) {
178414f27939SMilan Broz 		/*
178514f27939SMilan Broz 		 * Otherwise keep thread (if running) and config,
178614f27939SMilan Broz 		 * but flush possible ongoing bios in thread.
178714f27939SMilan Broz 		 */
178843cade80SOmar Sandoval 		blk_mq_freeze_queue(lo->lo_queue);
178943cade80SOmar Sandoval 		blk_mq_unfreeze_queue(lo->lo_queue);
179014f27939SMilan Broz 	}
179196c58655SDavid Woodhouse 
17920a42e99bSJan Kara out_unlock:
17936cc8e743SPavel Tatashin 	mutex_unlock(&lo->lo_mutex);
1794ae665016SLinus Torvalds }
1795ae665016SLinus Torvalds 
179683d5cde4SAlexey Dobriyan static const struct block_device_operations lo_fops = {
17971da177e4SLinus Torvalds 	.owner =	THIS_MODULE,
1798bb214884SAl Viro 	.open =		lo_open,
1799bb214884SAl Viro 	.release =	lo_release,
1800bb214884SAl Viro 	.ioctl =	lo_ioctl,
1801863d5b82SDavid Howells #ifdef CONFIG_COMPAT
1802bb214884SAl Viro 	.compat_ioctl =	lo_compat_ioctl,
1803863d5b82SDavid Howells #endif
18041da177e4SLinus Torvalds };
18051da177e4SLinus Torvalds 
18061da177e4SLinus Torvalds /*
18071da177e4SLinus Torvalds  * And now the modules code and kernel interface.
18081da177e4SLinus Torvalds  */
180973285082SKen Chen static int max_loop;
18105657a819SJoe Perches module_param(max_loop, int, 0444);
1811a47653fcSKen Chen MODULE_PARM_DESC(max_loop, "Maximum number of loop devices");
18125657a819SJoe Perches module_param(max_part, int, 0444);
1813476a4813SLaurent Vivier MODULE_PARM_DESC(max_part, "Maximum number of partitions per loop device");
18141da177e4SLinus Torvalds MODULE_LICENSE("GPL");
18151da177e4SLinus Torvalds MODULE_ALIAS_BLOCKDEV_MAJOR(LOOP_MAJOR);
18161da177e4SLinus Torvalds 
1817fc17b653SChristoph Hellwig static blk_status_t loop_queue_rq(struct blk_mq_hw_ctx *hctx,
1818b5dd2f60SMing Lei 		const struct blk_mq_queue_data *bd)
1819b5dd2f60SMing Lei {
18201894e916SJens Axboe 	struct request *rq = bd->rq;
18211894e916SJens Axboe 	struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
18221894e916SJens Axboe 	struct loop_device *lo = rq->q->queuedata;
1823b5dd2f60SMing Lei 
18241894e916SJens Axboe 	blk_mq_start_request(rq);
1825b5dd2f60SMing Lei 
1826f4aa4c7bSMing Lei 	if (lo->lo_state != Lo_bound)
1827fc17b653SChristoph Hellwig 		return BLK_STS_IOERR;
1828f4aa4c7bSMing Lei 
18291894e916SJens Axboe 	switch (req_op(rq)) {
1830f0225cacSChristoph Hellwig 	case REQ_OP_FLUSH:
1831f0225cacSChristoph Hellwig 	case REQ_OP_DISCARD:
183219372e27SChristoph Hellwig 	case REQ_OP_WRITE_ZEROES:
1833bc07c10aSMing Lei 		cmd->use_aio = false;
1834f0225cacSChristoph Hellwig 		break;
1835f0225cacSChristoph Hellwig 	default:
1836f0225cacSChristoph Hellwig 		cmd->use_aio = lo->use_dio;
1837f0225cacSChristoph Hellwig 		break;
1838f0225cacSChristoph Hellwig 	}
1839bc07c10aSMing Lei 
1840d4478e92SShaohua Li 	/* always use the first bio's css */
1841c74d40e8SDan Schatzberg 	cmd->blkcg_css = NULL;
1842c74d40e8SDan Schatzberg 	cmd->memcg_css = NULL;
18430b508bc9SShaohua Li #ifdef CONFIG_BLK_CGROUP
1844c74d40e8SDan Schatzberg 	if (rq->bio && rq->bio->bi_blkg) {
1845c74d40e8SDan Schatzberg 		cmd->blkcg_css = &bio_blkcg(rq->bio)->css;
1846c74d40e8SDan Schatzberg #ifdef CONFIG_MEMCG
1847c74d40e8SDan Schatzberg 		cmd->memcg_css =
1848c74d40e8SDan Schatzberg 			cgroup_get_e_css(cmd->blkcg_css->cgroup,
1849c74d40e8SDan Schatzberg 					&memory_cgrp_subsys);
1850d4478e92SShaohua Li #endif
1851c74d40e8SDan Schatzberg 	}
1852c74d40e8SDan Schatzberg #endif
185387579e9bSDan Schatzberg 	loop_queue_work(lo, cmd);
1854b5dd2f60SMing Lei 
1855fc17b653SChristoph Hellwig 	return BLK_STS_OK;
1856b5dd2f60SMing Lei }
1857b5dd2f60SMing Lei 
1858b5dd2f60SMing Lei static void loop_handle_cmd(struct loop_cmd *cmd)
1859b5dd2f60SMing Lei {
18601894e916SJens Axboe 	struct request *rq = blk_mq_rq_from_pdu(cmd);
18611894e916SJens Axboe 	const bool write = op_is_write(req_op(rq));
18621894e916SJens Axboe 	struct loop_device *lo = rq->q->queuedata;
1863f4829a9bSChristoph Hellwig 	int ret = 0;
1864c74d40e8SDan Schatzberg 	struct mem_cgroup *old_memcg = NULL;
1865b5dd2f60SMing Lei 
1866f4829a9bSChristoph Hellwig 	if (write && (lo->lo_flags & LO_FLAGS_READ_ONLY)) {
1867f4829a9bSChristoph Hellwig 		ret = -EIO;
1868b5dd2f60SMing Lei 		goto failed;
1869f4829a9bSChristoph Hellwig 	}
1870b5dd2f60SMing Lei 
1871c74d40e8SDan Schatzberg 	if (cmd->blkcg_css)
1872c74d40e8SDan Schatzberg 		kthread_associate_blkcg(cmd->blkcg_css);
1873c74d40e8SDan Schatzberg 	if (cmd->memcg_css)
1874c74d40e8SDan Schatzberg 		old_memcg = set_active_memcg(
1875c74d40e8SDan Schatzberg 			mem_cgroup_from_css(cmd->memcg_css));
1876c74d40e8SDan Schatzberg 
18771894e916SJens Axboe 	ret = do_req_filebacked(lo, rq);
1878c74d40e8SDan Schatzberg 
1879c74d40e8SDan Schatzberg 	if (cmd->blkcg_css)
1880c74d40e8SDan Schatzberg 		kthread_associate_blkcg(NULL);
1881c74d40e8SDan Schatzberg 
1882c74d40e8SDan Schatzberg 	if (cmd->memcg_css) {
1883c74d40e8SDan Schatzberg 		set_active_memcg(old_memcg);
1884c74d40e8SDan Schatzberg 		css_put(cmd->memcg_css);
1885c74d40e8SDan Schatzberg 	}
1886b5dd2f60SMing Lei  failed:
1887bc07c10aSMing Lei 	/* complete non-aio request */
1888fe2cb290SChristoph Hellwig 	if (!cmd->use_aio || ret) {
18898cd55087SEvan Green 		if (ret == -EOPNOTSUPP)
18908cd55087SEvan Green 			cmd->ret = ret;
18918cd55087SEvan Green 		else
1892fe2cb290SChristoph Hellwig 			cmd->ret = ret ? -EIO : 0;
189315f73f5bSChristoph Hellwig 		if (likely(!blk_should_fake_timeout(rq->q)))
18941894e916SJens Axboe 			blk_mq_complete_request(rq);
1895fe2cb290SChristoph Hellwig 	}
1896b5dd2f60SMing Lei }
1897b5dd2f60SMing Lei 
189887579e9bSDan Schatzberg static void loop_set_timer(struct loop_device *lo)
1899b5dd2f60SMing Lei {
190087579e9bSDan Schatzberg 	timer_reduce(&lo->timer, jiffies + LOOP_IDLE_WORKER_TIMEOUT);
1901b5dd2f60SMing Lei }
1902b5dd2f60SMing Lei 
190387579e9bSDan Schatzberg static void loop_process_work(struct loop_worker *worker,
190487579e9bSDan Schatzberg 			struct list_head *cmd_list, struct loop_device *lo)
1905b5dd2f60SMing Lei {
190687579e9bSDan Schatzberg 	int orig_flags = current->flags;
190787579e9bSDan Schatzberg 	struct loop_cmd *cmd;
1908b5dd2f60SMing Lei 
190987579e9bSDan Schatzberg 	current->flags |= PF_LOCAL_THROTTLE | PF_MEMALLOC_NOIO;
191087579e9bSDan Schatzberg 	spin_lock_irq(&lo->lo_work_lock);
191187579e9bSDan Schatzberg 	while (!list_empty(cmd_list)) {
191287579e9bSDan Schatzberg 		cmd = container_of(
191387579e9bSDan Schatzberg 			cmd_list->next, struct loop_cmd, list_entry);
191487579e9bSDan Schatzberg 		list_del(cmd_list->next);
191587579e9bSDan Schatzberg 		spin_unlock_irq(&lo->lo_work_lock);
191687579e9bSDan Schatzberg 
191787579e9bSDan Schatzberg 		loop_handle_cmd(cmd);
191887579e9bSDan Schatzberg 		cond_resched();
191987579e9bSDan Schatzberg 
192087579e9bSDan Schatzberg 		spin_lock_irq(&lo->lo_work_lock);
192187579e9bSDan Schatzberg 	}
192287579e9bSDan Schatzberg 
192387579e9bSDan Schatzberg 	/*
192487579e9bSDan Schatzberg 	 * We only add to the idle list if there are no pending cmds
192587579e9bSDan Schatzberg 	 * *and* the worker will not run again which ensures that it
192687579e9bSDan Schatzberg 	 * is safe to free any worker on the idle list
192787579e9bSDan Schatzberg 	 */
192887579e9bSDan Schatzberg 	if (worker && !work_pending(&worker->work)) {
192987579e9bSDan Schatzberg 		worker->last_ran_at = jiffies;
193087579e9bSDan Schatzberg 		list_add_tail(&worker->idle_list, &lo->idle_worker_list);
193187579e9bSDan Schatzberg 		loop_set_timer(lo);
193287579e9bSDan Schatzberg 	}
193387579e9bSDan Schatzberg 	spin_unlock_irq(&lo->lo_work_lock);
193487579e9bSDan Schatzberg 	current->flags = orig_flags;
193587579e9bSDan Schatzberg }
193687579e9bSDan Schatzberg 
193787579e9bSDan Schatzberg static void loop_workfn(struct work_struct *work)
193887579e9bSDan Schatzberg {
193987579e9bSDan Schatzberg 	struct loop_worker *worker =
194087579e9bSDan Schatzberg 		container_of(work, struct loop_worker, work);
194187579e9bSDan Schatzberg 	loop_process_work(worker, &worker->cmd_list, worker->lo);
194287579e9bSDan Schatzberg }
194387579e9bSDan Schatzberg 
194487579e9bSDan Schatzberg static void loop_rootcg_workfn(struct work_struct *work)
194587579e9bSDan Schatzberg {
194687579e9bSDan Schatzberg 	struct loop_device *lo =
194787579e9bSDan Schatzberg 		container_of(work, struct loop_device, rootcg_work);
194887579e9bSDan Schatzberg 	loop_process_work(NULL, &lo->rootcg_cmd_list, lo);
194987579e9bSDan Schatzberg }
195087579e9bSDan Schatzberg 
195187579e9bSDan Schatzberg static void loop_free_idle_workers(struct timer_list *timer)
195287579e9bSDan Schatzberg {
195387579e9bSDan Schatzberg 	struct loop_device *lo = container_of(timer, struct loop_device, timer);
195487579e9bSDan Schatzberg 	struct loop_worker *pos, *worker;
195587579e9bSDan Schatzberg 
195687579e9bSDan Schatzberg 	spin_lock_irq(&lo->lo_work_lock);
195787579e9bSDan Schatzberg 	list_for_each_entry_safe(worker, pos, &lo->idle_worker_list,
195887579e9bSDan Schatzberg 				idle_list) {
195987579e9bSDan Schatzberg 		if (time_is_after_jiffies(worker->last_ran_at +
196087579e9bSDan Schatzberg 						LOOP_IDLE_WORKER_TIMEOUT))
196187579e9bSDan Schatzberg 			break;
196287579e9bSDan Schatzberg 		list_del(&worker->idle_list);
196387579e9bSDan Schatzberg 		rb_erase(&worker->rb_node, &lo->worker_tree);
1964c74d40e8SDan Schatzberg 		css_put(worker->blkcg_css);
196587579e9bSDan Schatzberg 		kfree(worker);
196687579e9bSDan Schatzberg 	}
196787579e9bSDan Schatzberg 	if (!list_empty(&lo->idle_worker_list))
196887579e9bSDan Schatzberg 		loop_set_timer(lo);
196987579e9bSDan Schatzberg 	spin_unlock_irq(&lo->lo_work_lock);
1970b5dd2f60SMing Lei }
1971b5dd2f60SMing Lei 
1972f363b089SEric Biggers static const struct blk_mq_ops loop_mq_ops = {
1973b5dd2f60SMing Lei 	.queue_rq       = loop_queue_rq,
1974fe2cb290SChristoph Hellwig 	.complete	= lo_complete_rq,
1975b5dd2f60SMing Lei };
1976b5dd2f60SMing Lei 
1977d6da83d0SChristoph Hellwig static int loop_add(int i)
19781da177e4SLinus Torvalds {
197973285082SKen Chen 	struct loop_device *lo;
198073285082SKen Chen 	struct gendisk *disk;
198134dd82afSKay Sievers 	int err;
19821da177e4SLinus Torvalds 
198334dd82afSKay Sievers 	err = -ENOMEM;
198468d740d7SSilva Paulo 	lo = kzalloc(sizeof(*lo), GFP_KERNEL);
198568d740d7SSilva Paulo 	if (!lo)
198673285082SKen Chen 		goto out;
1987ef7e7c82SMikulas Patocka 	lo->lo_state = Lo_unbound;
1988ef7e7c82SMikulas Patocka 
198918d1f200SChristoph Hellwig 	err = mutex_lock_killable(&loop_ctl_mutex);
199018d1f200SChristoph Hellwig 	if (err)
199118d1f200SChristoph Hellwig 		goto out_free_dev;
199218d1f200SChristoph Hellwig 
1993c718aa65STejun Heo 	/* allocate id, if @id >= 0, we're requesting that specific id */
199434dd82afSKay Sievers 	if (i >= 0) {
1995c718aa65STejun Heo 		err = idr_alloc(&loop_index_idr, lo, i, i + 1, GFP_KERNEL);
1996c718aa65STejun Heo 		if (err == -ENOSPC)
199734dd82afSKay Sievers 			err = -EEXIST;
199834dd82afSKay Sievers 	} else {
1999c718aa65STejun Heo 		err = idr_alloc(&loop_index_idr, lo, 0, 0, GFP_KERNEL);
200034dd82afSKay Sievers 	}
20011c500ad7STetsuo Handa 	mutex_unlock(&loop_ctl_mutex);
200234dd82afSKay Sievers 	if (err < 0)
20031c500ad7STetsuo Handa 		goto out_free_dev;
2004c718aa65STejun Heo 	i = err;
20051da177e4SLinus Torvalds 
2006183cfb57SWei Yongjun 	err = -ENOMEM;
2007b5dd2f60SMing Lei 	lo->tag_set.ops = &loop_mq_ops;
2008b5dd2f60SMing Lei 	lo->tag_set.nr_hw_queues = 1;
2009b5dd2f60SMing Lei 	lo->tag_set.queue_depth = 128;
2010b5dd2f60SMing Lei 	lo->tag_set.numa_node = NUMA_NO_NODE;
2011b5dd2f60SMing Lei 	lo->tag_set.cmd_size = sizeof(struct loop_cmd);
20122112f5c1SBart Van Assche 	lo->tag_set.flags = BLK_MQ_F_SHOULD_MERGE | BLK_MQ_F_STACKING |
20132112f5c1SBart Van Assche 		BLK_MQ_F_NO_SCHED_BY_DEFAULT;
2014b5dd2f60SMing Lei 	lo->tag_set.driver_data = lo;
2015b5dd2f60SMing Lei 
2016b5dd2f60SMing Lei 	err = blk_mq_alloc_tag_set(&lo->tag_set);
2017b5dd2f60SMing Lei 	if (err)
20183ec981e3SMikulas Patocka 		goto out_free_idr;
201973285082SKen Chen 
20201c99502fSChristoph Hellwig 	disk = lo->lo_disk = blk_mq_alloc_disk(&lo->tag_set, lo);
20211c99502fSChristoph Hellwig 	if (IS_ERR(disk)) {
20221c99502fSChristoph Hellwig 		err = PTR_ERR(disk);
2023b5dd2f60SMing Lei 		goto out_cleanup_tags;
2024b5dd2f60SMing Lei 	}
20251c99502fSChristoph Hellwig 	lo->lo_queue = lo->lo_disk->queue;
2026ef7e7c82SMikulas Patocka 
202754bb0adeSShaohua Li 	blk_queue_max_hw_sectors(lo->lo_queue, BLK_DEF_MAX_SECTORS);
202840326d8aSShaohua Li 
20295b5e20f4SMing Lei 	/*
203040326d8aSShaohua Li 	 * By default, we do buffer IO, so it doesn't make sense to enable
203140326d8aSShaohua Li 	 * merge because the I/O submitted to backing file is handled page by
203240326d8aSShaohua Li 	 * page. For directio mode, merge does help to dispatch bigger request
203340326d8aSShaohua Li 	 * to underlayer disk. We will enable merge once directio is enabled.
20345b5e20f4SMing Lei 	 */
20358b904b5bSBart Van Assche 	blk_queue_flag_set(QUEUE_FLAG_NOMERGES, lo->lo_queue);
20365b5e20f4SMing Lei 
2037e03c8dd1SKay Sievers 	/*
2038e03c8dd1SKay Sievers 	 * Disable partition scanning by default. The in-kernel partition
2039e03c8dd1SKay Sievers 	 * scanning can be requested individually per-device during its
2040e03c8dd1SKay Sievers 	 * setup. Userspace can always add and remove partitions from all
2041e03c8dd1SKay Sievers 	 * devices. The needed partition minors are allocated from the
2042e03c8dd1SKay Sievers 	 * extended minor space, the main loop device numbers will continue
2043e03c8dd1SKay Sievers 	 * to match the loop minors, regardless of the number of partitions
2044e03c8dd1SKay Sievers 	 * used.
2045e03c8dd1SKay Sievers 	 *
2046e03c8dd1SKay Sievers 	 * If max_part is given, partition scanning is globally enabled for
2047e03c8dd1SKay Sievers 	 * all loop devices. The minors for the main loop devices will be
2048e03c8dd1SKay Sievers 	 * multiples of max_part.
2049e03c8dd1SKay Sievers 	 *
2050e03c8dd1SKay Sievers 	 * Note: Global-for-all-devices, set-only-at-init, read-only module
2051e03c8dd1SKay Sievers 	 * parameteters like 'max_loop' and 'max_part' make things needlessly
2052e03c8dd1SKay Sievers 	 * complicated, are too static, inflexible and may surprise
2053e03c8dd1SKay Sievers 	 * userspace tools. Parameters like this in general should be avoided.
2054e03c8dd1SKay Sievers 	 */
2055e03c8dd1SKay Sievers 	if (!part_shift)
2056e03c8dd1SKay Sievers 		disk->flags |= GENHD_FL_NO_PART_SCAN;
2057e03c8dd1SKay Sievers 	disk->flags |= GENHD_FL_EXT_DEVT;
2058f8933667SMing Lei 	atomic_set(&lo->lo_refcnt, 0);
20596cc8e743SPavel Tatashin 	mutex_init(&lo->lo_mutex);
20601da177e4SLinus Torvalds 	lo->lo_number		= i;
20611da177e4SLinus Torvalds 	spin_lock_init(&lo->lo_lock);
206287579e9bSDan Schatzberg 	spin_lock_init(&lo->lo_work_lock);
20631da177e4SLinus Torvalds 	disk->major		= LOOP_MAJOR;
2064476a4813SLaurent Vivier 	disk->first_minor	= i << part_shift;
20651c99502fSChristoph Hellwig 	disk->minors		= 1 << part_shift;
20661da177e4SLinus Torvalds 	disk->fops		= &lo_fops;
20671da177e4SLinus Torvalds 	disk->private_data	= lo;
20681da177e4SLinus Torvalds 	disk->queue		= lo->lo_queue;
20699f65c489SMatteo Croce 	disk->events		= DISK_EVENT_MEDIA_CHANGE;
20709f65c489SMatteo Croce 	disk->event_flags	= DISK_EVENT_FLAG_UEVENT;
207173285082SKen Chen 	sprintf(disk->disk_name, "loop%d", i);
20721c500ad7STetsuo Handa 	/* Make this loop device reachable from pathname. */
2073905705f0SLuis Chamberlain 	err = add_disk(disk);
2074905705f0SLuis Chamberlain 	if (err)
2075905705f0SLuis Chamberlain 		goto out_cleanup_disk;
2076905705f0SLuis Chamberlain 
20771c500ad7STetsuo Handa 	/* Show this loop device. */
20781c500ad7STetsuo Handa 	mutex_lock(&loop_ctl_mutex);
20791c500ad7STetsuo Handa 	lo->idr_visible = true;
208018d1f200SChristoph Hellwig 	mutex_unlock(&loop_ctl_mutex);
2081905705f0SLuis Chamberlain 
208218d1f200SChristoph Hellwig 	return i;
208373285082SKen Chen 
2084905705f0SLuis Chamberlain out_cleanup_disk:
2085905705f0SLuis Chamberlain 	blk_cleanup_disk(disk);
2086b5dd2f60SMing Lei out_cleanup_tags:
2087b5dd2f60SMing Lei 	blk_mq_free_tag_set(&lo->tag_set);
20883ec981e3SMikulas Patocka out_free_idr:
20891c500ad7STetsuo Handa 	mutex_lock(&loop_ctl_mutex);
20903ec981e3SMikulas Patocka 	idr_remove(&loop_index_idr, i);
209118d1f200SChristoph Hellwig 	mutex_unlock(&loop_ctl_mutex);
209273285082SKen Chen out_free_dev:
209373285082SKen Chen 	kfree(lo);
209473285082SKen Chen out:
209534dd82afSKay Sievers 	return err;
20961da177e4SLinus Torvalds }
20971da177e4SLinus Torvalds 
209834dd82afSKay Sievers static void loop_remove(struct loop_device *lo)
209973285082SKen Chen {
21001c500ad7STetsuo Handa 	/* Make this loop device unreachable from pathname. */
21016cd18e71SNeilBrown 	del_gendisk(lo->lo_disk);
21021c99502fSChristoph Hellwig 	blk_cleanup_disk(lo->lo_disk);
2103b5dd2f60SMing Lei 	blk_mq_free_tag_set(&lo->tag_set);
21041c500ad7STetsuo Handa 	mutex_lock(&loop_ctl_mutex);
21051c500ad7STetsuo Handa 	idr_remove(&loop_index_idr, lo->lo_number);
21061c500ad7STetsuo Handa 	mutex_unlock(&loop_ctl_mutex);
21071c500ad7STetsuo Handa 	/* There is no route which can find this loop device. */
21086cc8e743SPavel Tatashin 	mutex_destroy(&lo->lo_mutex);
210973285082SKen Chen 	kfree(lo);
211073285082SKen Chen }
211173285082SKen Chen 
21128410d38cSChristoph Hellwig static void loop_probe(dev_t dev)
211373285082SKen Chen {
21148410d38cSChristoph Hellwig 	int idx = MINOR(dev) >> part_shift;
21158410d38cSChristoph Hellwig 
21168410d38cSChristoph Hellwig 	if (max_loop && idx >= max_loop)
21178410d38cSChristoph Hellwig 		return;
2118d6da83d0SChristoph Hellwig 	loop_add(idx);
2119f9d10764SChristoph Hellwig }
2120f9d10764SChristoph Hellwig 
2121f9d10764SChristoph Hellwig static int loop_control_remove(int idx)
2122770fe30aSKay Sievers {
2123770fe30aSKay Sievers 	struct loop_device *lo;
21240a42e99bSJan Kara 	int ret;
2125e5d66a10SChristoph Hellwig 
2126e5d66a10SChristoph Hellwig 	if (idx < 0) {
2127e5d66a10SChristoph Hellwig 		pr_warn("deleting an unspecified loop device is not supported.\n");
2128e5d66a10SChristoph Hellwig 		return -EINVAL;
2129e5d66a10SChristoph Hellwig 	}
2130770fe30aSKay Sievers 
21311c500ad7STetsuo Handa 	/* Hide this loop device for serialization. */
21320a42e99bSJan Kara 	ret = mutex_lock_killable(&loop_ctl_mutex);
21330a42e99bSJan Kara 	if (ret)
21340a42e99bSJan Kara 		return ret;
2135b9848081SChristoph Hellwig 	lo = idr_find(&loop_index_idr, idx);
21361c500ad7STetsuo Handa 	if (!lo || !lo->idr_visible)
2137b9848081SChristoph Hellwig 		ret = -ENODEV;
21381c500ad7STetsuo Handa 	else
21391c500ad7STetsuo Handa 		lo->idr_visible = false;
21401c500ad7STetsuo Handa 	mutex_unlock(&loop_ctl_mutex);
21411c500ad7STetsuo Handa 	if (ret)
21421c500ad7STetsuo Handa 		return ret;
2143f9d10764SChristoph Hellwig 
21441c500ad7STetsuo Handa 	/* Check whether this loop device can be removed. */
21456cc8e743SPavel Tatashin 	ret = mutex_lock_killable(&lo->lo_mutex);
21466cc8e743SPavel Tatashin 	if (ret)
21471c500ad7STetsuo Handa 		goto mark_visible;
2148f9d10764SChristoph Hellwig 	if (lo->lo_state != Lo_unbound ||
2149f9d10764SChristoph Hellwig 	    atomic_read(&lo->lo_refcnt) > 0) {
21506cc8e743SPavel Tatashin 		mutex_unlock(&lo->lo_mutex);
2151770fe30aSKay Sievers 		ret = -EBUSY;
21521c500ad7STetsuo Handa 		goto mark_visible;
2153770fe30aSKay Sievers 	}
21541c500ad7STetsuo Handa 	/* Mark this loop device no longer open()-able. */
2155990e7811SChristoph Hellwig 	lo->lo_state = Lo_deleting;
21566cc8e743SPavel Tatashin 	mutex_unlock(&lo->lo_mutex);
2157f9d10764SChristoph Hellwig 
2158770fe30aSKay Sievers 	loop_remove(lo);
21591c500ad7STetsuo Handa 	return 0;
21601c500ad7STetsuo Handa 
21611c500ad7STetsuo Handa mark_visible:
21621c500ad7STetsuo Handa 	/* Show this loop device again. */
21631c500ad7STetsuo Handa 	mutex_lock(&loop_ctl_mutex);
21641c500ad7STetsuo Handa 	lo->idr_visible = true;
2165f9d10764SChristoph Hellwig 	mutex_unlock(&loop_ctl_mutex);
2166f9d10764SChristoph Hellwig 	return ret;
2167770fe30aSKay Sievers }
2168f9d10764SChristoph Hellwig 
2169f9d10764SChristoph Hellwig static int loop_control_get_free(int idx)
2170f9d10764SChristoph Hellwig {
2171f9d10764SChristoph Hellwig 	struct loop_device *lo;
2172b9848081SChristoph Hellwig 	int id, ret;
2173f9d10764SChristoph Hellwig 
2174f9d10764SChristoph Hellwig 	ret = mutex_lock_killable(&loop_ctl_mutex);
2175f9d10764SChristoph Hellwig 	if (ret)
2176f9d10764SChristoph Hellwig 		return ret;
2177b9848081SChristoph Hellwig 	idr_for_each_entry(&loop_index_idr, lo, id) {
21781c500ad7STetsuo Handa 		/* Hitting a race results in creating a new loop device which is harmless. */
21791c500ad7STetsuo Handa 		if (lo->idr_visible && data_race(lo->lo_state) == Lo_unbound)
2180b9848081SChristoph Hellwig 			goto found;
2181b9848081SChristoph Hellwig 	}
21820a42e99bSJan Kara 	mutex_unlock(&loop_ctl_mutex);
218318d1f200SChristoph Hellwig 	return loop_add(-1);
2184b9848081SChristoph Hellwig found:
2185b9848081SChristoph Hellwig 	mutex_unlock(&loop_ctl_mutex);
2186b9848081SChristoph Hellwig 	return id;
2187770fe30aSKay Sievers }
2188770fe30aSKay Sievers 
2189f9d10764SChristoph Hellwig static long loop_control_ioctl(struct file *file, unsigned int cmd,
2190f9d10764SChristoph Hellwig 			       unsigned long parm)
2191f9d10764SChristoph Hellwig {
2192f9d10764SChristoph Hellwig 	switch (cmd) {
2193f9d10764SChristoph Hellwig 	case LOOP_CTL_ADD:
219418d1f200SChristoph Hellwig 		return loop_add(parm);
2195f9d10764SChristoph Hellwig 	case LOOP_CTL_REMOVE:
2196f9d10764SChristoph Hellwig 		return loop_control_remove(parm);
2197f9d10764SChristoph Hellwig 	case LOOP_CTL_GET_FREE:
2198f9d10764SChristoph Hellwig 		return loop_control_get_free(parm);
2199f9d10764SChristoph Hellwig 	default:
2200f9d10764SChristoph Hellwig 		return -ENOSYS;
2201f9d10764SChristoph Hellwig 	}
2202f9d10764SChristoph Hellwig }
2203f9d10764SChristoph Hellwig 
2204770fe30aSKay Sievers static const struct file_operations loop_ctl_fops = {
2205770fe30aSKay Sievers 	.open		= nonseekable_open,
2206770fe30aSKay Sievers 	.unlocked_ioctl	= loop_control_ioctl,
2207770fe30aSKay Sievers 	.compat_ioctl	= loop_control_ioctl,
2208770fe30aSKay Sievers 	.owner		= THIS_MODULE,
2209770fe30aSKay Sievers 	.llseek		= noop_llseek,
2210770fe30aSKay Sievers };
2211770fe30aSKay Sievers 
2212770fe30aSKay Sievers static struct miscdevice loop_misc = {
2213770fe30aSKay Sievers 	.minor		= LOOP_CTRL_MINOR,
2214770fe30aSKay Sievers 	.name		= "loop-control",
2215770fe30aSKay Sievers 	.fops		= &loop_ctl_fops,
2216770fe30aSKay Sievers };
2217770fe30aSKay Sievers 
2218770fe30aSKay Sievers MODULE_ALIAS_MISCDEV(LOOP_CTRL_MINOR);
2219770fe30aSKay Sievers MODULE_ALIAS("devname:loop-control");
2220770fe30aSKay Sievers 
222173285082SKen Chen static int __init loop_init(void)
222273285082SKen Chen {
2223a47653fcSKen Chen 	int i, nr;
2224770fe30aSKay Sievers 	int err;
2225a47653fcSKen Chen 
2226476a4813SLaurent Vivier 	part_shift = 0;
2227ac04fee0SNamhyung Kim 	if (max_part > 0) {
2228476a4813SLaurent Vivier 		part_shift = fls(max_part);
2229476a4813SLaurent Vivier 
2230ac04fee0SNamhyung Kim 		/*
2231ac04fee0SNamhyung Kim 		 * Adjust max_part according to part_shift as it is exported
2232ac04fee0SNamhyung Kim 		 * to user space so that user can decide correct minor number
2233ac04fee0SNamhyung Kim 		 * if [s]he want to create more devices.
2234ac04fee0SNamhyung Kim 		 *
2235ac04fee0SNamhyung Kim 		 * Note that -1 is required because partition 0 is reserved
2236ac04fee0SNamhyung Kim 		 * for the whole disk.
2237ac04fee0SNamhyung Kim 		 */
2238ac04fee0SNamhyung Kim 		max_part = (1UL << part_shift) - 1;
2239ac04fee0SNamhyung Kim 	}
2240ac04fee0SNamhyung Kim 
2241b1a66504SGuo Chao 	if ((1UL << part_shift) > DISK_MAX_PARTS) {
2242b1a66504SGuo Chao 		err = -EINVAL;
2243a8c1d064SAnton Volkov 		goto err_out;
2244b1a66504SGuo Chao 	}
224578f4bb36SNamhyung Kim 
2246b1a66504SGuo Chao 	if (max_loop > 1UL << (MINORBITS - part_shift)) {
2247b1a66504SGuo Chao 		err = -EINVAL;
2248a8c1d064SAnton Volkov 		goto err_out;
2249b1a66504SGuo Chao 	}
225073285082SKen Chen 
2251d134b00bSKay Sievers 	/*
2252d134b00bSKay Sievers 	 * If max_loop is specified, create that many devices upfront.
2253d134b00bSKay Sievers 	 * This also becomes a hard limit. If max_loop is not specified,
2254d134b00bSKay Sievers 	 * create CONFIG_BLK_DEV_LOOP_MIN_COUNT loop devices at module
2255d134b00bSKay Sievers 	 * init time. Loop devices can be requested on-demand with the
2256d134b00bSKay Sievers 	 * /dev/loop-control interface, or be instantiated by accessing
2257d134b00bSKay Sievers 	 * a 'dead' device node.
2258d134b00bSKay Sievers 	 */
2259aeb2b0b1SLukas Bulwahn 	if (max_loop)
2260a47653fcSKen Chen 		nr = max_loop;
2261aeb2b0b1SLukas Bulwahn 	else
2262d134b00bSKay Sievers 		nr = CONFIG_BLK_DEV_LOOP_MIN_COUNT;
2263a47653fcSKen Chen 
2264a8c1d064SAnton Volkov 	err = misc_register(&loop_misc);
2265a8c1d064SAnton Volkov 	if (err < 0)
2266a8c1d064SAnton Volkov 		goto err_out;
2267a8c1d064SAnton Volkov 
2268a8c1d064SAnton Volkov 
22698410d38cSChristoph Hellwig 	if (__register_blkdev(LOOP_MAJOR, "loop", loop_probe)) {
2270b1a66504SGuo Chao 		err = -EIO;
2271b1a66504SGuo Chao 		goto misc_out;
2272b1a66504SGuo Chao 	}
2273a47653fcSKen Chen 
2274d134b00bSKay Sievers 	/* pre-create number of devices given by config or max_loop */
227534dd82afSKay Sievers 	for (i = 0; i < nr; i++)
2276d6da83d0SChristoph Hellwig 		loop_add(i);
227734dd82afSKay Sievers 
227873285082SKen Chen 	printk(KERN_INFO "loop: module loaded\n");
22791da177e4SLinus Torvalds 	return 0;
2280b1a66504SGuo Chao 
2281b1a66504SGuo Chao misc_out:
2282b1a66504SGuo Chao 	misc_deregister(&loop_misc);
2283a8c1d064SAnton Volkov err_out:
2284b1a66504SGuo Chao 	return err;
228534dd82afSKay Sievers }
2286a47653fcSKen Chen 
228773285082SKen Chen static void __exit loop_exit(void)
22881da177e4SLinus Torvalds {
22898e60947dSChristoph Hellwig 	struct loop_device *lo;
22908e60947dSChristoph Hellwig 	int id;
22918e60947dSChristoph Hellwig 
22928b52d8beSChristoph Hellwig 	unregister_blkdev(LOOP_MAJOR, "loop");
22938b52d8beSChristoph Hellwig 	misc_deregister(&loop_misc);
2294200f9337SLuis Chamberlain 
22951c500ad7STetsuo Handa 	/*
22961c500ad7STetsuo Handa 	 * There is no need to use loop_ctl_mutex here, for nobody else can
22971c500ad7STetsuo Handa 	 * access loop_index_idr when this module is unloading (unless forced
22981c500ad7STetsuo Handa 	 * module unloading is requested). If this is not a clean unloading,
22991c500ad7STetsuo Handa 	 * we have no means to avoid kernel crash.
23001c500ad7STetsuo Handa 	 */
23018e60947dSChristoph Hellwig 	idr_for_each_entry(&loop_index_idr, lo, id)
23028e60947dSChristoph Hellwig 		loop_remove(lo);
2303bd5c39edSChristoph Hellwig 
2304bd5c39edSChristoph Hellwig 	idr_destroy(&loop_index_idr);
23051da177e4SLinus Torvalds }
23061da177e4SLinus Torvalds 
23071da177e4SLinus Torvalds module_init(loop_init);
23081da177e4SLinus Torvalds module_exit(loop_exit);
23091da177e4SLinus Torvalds 
23101da177e4SLinus Torvalds #ifndef MODULE
23111da177e4SLinus Torvalds static int __init max_loop_setup(char *str)
23121da177e4SLinus Torvalds {
23131da177e4SLinus Torvalds 	max_loop = simple_strtol(str, NULL, 0);
23141da177e4SLinus Torvalds 	return 1;
23151da177e4SLinus Torvalds }
23161da177e4SLinus Torvalds 
23171da177e4SLinus Torvalds __setup("max_loop=", max_loop_setup);
23181da177e4SLinus Torvalds #endif
2319