xref: /openbmc/linux/drivers/block/loop.c (revision 2cf429b5)
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>
8206582bc8SMing Lei #include <linux/statfs.h>
83d9a08a9eSAdam Manzanares 
8483a87611SAl Viro #include "loop.h"
851da177e4SLinus Torvalds 
867c0f6ba6SLinus Torvalds #include <linux/uaccess.h>
871da177e4SLinus Torvalds 
8887579e9bSDan Schatzberg #define LOOP_IDLE_WORKER_TIMEOUT (60 * HZ)
89ef44c508SChaitanya Kulkarni #define LOOP_DEFAULT_HW_Q_DEPTH (128)
9087579e9bSDan Schatzberg 
9134dd82afSKay Sievers static DEFINE_IDR(loop_index_idr);
92310ca162STetsuo Handa static DEFINE_MUTEX(loop_ctl_mutex);
933ce6e1f6STetsuo Handa static DEFINE_MUTEX(loop_validate_mutex);
943ce6e1f6STetsuo Handa 
953ce6e1f6STetsuo Handa /**
963ce6e1f6STetsuo Handa  * loop_global_lock_killable() - take locks for safe loop_validate_file() test
973ce6e1f6STetsuo Handa  *
983ce6e1f6STetsuo Handa  * @lo: struct loop_device
993ce6e1f6STetsuo Handa  * @global: true if @lo is about to bind another "struct loop_device", false otherwise
1003ce6e1f6STetsuo Handa  *
1013ce6e1f6STetsuo Handa  * Returns 0 on success, -EINTR otherwise.
1023ce6e1f6STetsuo Handa  *
1033ce6e1f6STetsuo Handa  * Since loop_validate_file() traverses on other "struct loop_device" if
1043ce6e1f6STetsuo Handa  * is_loop_device() is true, we need a global lock for serializing concurrent
1053ce6e1f6STetsuo Handa  * loop_configure()/loop_change_fd()/__loop_clr_fd() calls.
1063ce6e1f6STetsuo Handa  */
1073ce6e1f6STetsuo Handa static int loop_global_lock_killable(struct loop_device *lo, bool global)
1083ce6e1f6STetsuo Handa {
1093ce6e1f6STetsuo Handa 	int err;
1103ce6e1f6STetsuo Handa 
1113ce6e1f6STetsuo Handa 	if (global) {
1123ce6e1f6STetsuo Handa 		err = mutex_lock_killable(&loop_validate_mutex);
1133ce6e1f6STetsuo Handa 		if (err)
1143ce6e1f6STetsuo Handa 			return err;
1153ce6e1f6STetsuo Handa 	}
1163ce6e1f6STetsuo Handa 	err = mutex_lock_killable(&lo->lo_mutex);
1173ce6e1f6STetsuo Handa 	if (err && global)
1183ce6e1f6STetsuo Handa 		mutex_unlock(&loop_validate_mutex);
1193ce6e1f6STetsuo Handa 	return err;
1203ce6e1f6STetsuo Handa }
1213ce6e1f6STetsuo Handa 
1223ce6e1f6STetsuo Handa /**
1233ce6e1f6STetsuo Handa  * loop_global_unlock() - release locks taken by loop_global_lock_killable()
1243ce6e1f6STetsuo Handa  *
1253ce6e1f6STetsuo Handa  * @lo: struct loop_device
1263ce6e1f6STetsuo Handa  * @global: true if @lo was about to bind another "struct loop_device", false otherwise
1273ce6e1f6STetsuo Handa  */
1283ce6e1f6STetsuo Handa static void loop_global_unlock(struct loop_device *lo, bool global)
1293ce6e1f6STetsuo Handa {
1303ce6e1f6STetsuo Handa 	mutex_unlock(&lo->lo_mutex);
1313ce6e1f6STetsuo Handa 	if (global)
1323ce6e1f6STetsuo Handa 		mutex_unlock(&loop_validate_mutex);
1333ce6e1f6STetsuo Handa }
1341da177e4SLinus Torvalds 
135476a4813SLaurent Vivier static int max_part;
136476a4813SLaurent Vivier static int part_shift;
137476a4813SLaurent Vivier 
1387035b5dfSDmitry Monakhov static loff_t get_size(loff_t offset, loff_t sizelimit, struct file *file)
1391da177e4SLinus Torvalds {
140b7a1da69SGuo Chao 	loff_t loopsize;
1411da177e4SLinus Torvalds 
1421da177e4SLinus Torvalds 	/* Compute loopsize in bytes */
143b7a1da69SGuo Chao 	loopsize = i_size_read(file->f_mapping->host);
144b7a1da69SGuo Chao 	if (offset > 0)
145b7a1da69SGuo Chao 		loopsize -= offset;
146b7a1da69SGuo Chao 	/* offset is beyond i_size, weird but possible */
1477035b5dfSDmitry Monakhov 	if (loopsize < 0)
1487035b5dfSDmitry Monakhov 		return 0;
1491da177e4SLinus Torvalds 
1507035b5dfSDmitry Monakhov 	if (sizelimit > 0 && sizelimit < loopsize)
1517035b5dfSDmitry Monakhov 		loopsize = sizelimit;
1521da177e4SLinus Torvalds 	/*
1531da177e4SLinus Torvalds 	 * Unfortunately, if we want to do I/O on the device,
1541da177e4SLinus Torvalds 	 * the number of 512-byte sectors has to fit into a sector_t.
1551da177e4SLinus Torvalds 	 */
1561da177e4SLinus Torvalds 	return loopsize >> 9;
1571da177e4SLinus Torvalds }
1581da177e4SLinus Torvalds 
1597035b5dfSDmitry Monakhov static loff_t get_loop_size(struct loop_device *lo, struct file *file)
1601da177e4SLinus Torvalds {
1617035b5dfSDmitry Monakhov 	return get_size(lo->lo_offset, lo->lo_sizelimit, file);
1627035b5dfSDmitry Monakhov }
1637035b5dfSDmitry Monakhov 
1642e5ab5f3SMing Lei static void __loop_update_dio(struct loop_device *lo, bool dio)
1652e5ab5f3SMing Lei {
1662e5ab5f3SMing Lei 	struct file *file = lo->lo_backing_file;
1672e5ab5f3SMing Lei 	struct address_space *mapping = file->f_mapping;
1682e5ab5f3SMing Lei 	struct inode *inode = mapping->host;
1692e5ab5f3SMing Lei 	unsigned short sb_bsize = 0;
1702e5ab5f3SMing Lei 	unsigned dio_align = 0;
1712e5ab5f3SMing Lei 	bool use_dio;
1722e5ab5f3SMing Lei 
1732e5ab5f3SMing Lei 	if (inode->i_sb->s_bdev) {
1742e5ab5f3SMing Lei 		sb_bsize = bdev_logical_block_size(inode->i_sb->s_bdev);
1752e5ab5f3SMing Lei 		dio_align = sb_bsize - 1;
1762e5ab5f3SMing Lei 	}
1772e5ab5f3SMing Lei 
1782e5ab5f3SMing Lei 	/*
1792e5ab5f3SMing Lei 	 * We support direct I/O only if lo_offset is aligned with the
1802e5ab5f3SMing Lei 	 * logical I/O size of backing device, and the logical block
18147e96246SChristoph Hellwig 	 * size of loop is bigger than the backing device's.
1822e5ab5f3SMing Lei 	 *
1832e5ab5f3SMing Lei 	 * TODO: the above condition may be loosed in the future, and
1842e5ab5f3SMing Lei 	 * direct I/O may be switched runtime at that time because most
18589d790abSMasahiro Yamada 	 * of requests in sane applications should be PAGE_SIZE aligned
1862e5ab5f3SMing Lei 	 */
1872e5ab5f3SMing Lei 	if (dio) {
1882e5ab5f3SMing Lei 		if (queue_logical_block_size(lo->lo_queue) >= sb_bsize &&
1892e5ab5f3SMing Lei 				!(lo->lo_offset & dio_align) &&
19047e96246SChristoph Hellwig 				mapping->a_ops->direct_IO)
1912e5ab5f3SMing Lei 			use_dio = true;
1922e5ab5f3SMing Lei 		else
1932e5ab5f3SMing Lei 			use_dio = false;
1942e5ab5f3SMing Lei 	} else {
1952e5ab5f3SMing Lei 		use_dio = false;
1962e5ab5f3SMing Lei 	}
1972e5ab5f3SMing Lei 
1982e5ab5f3SMing Lei 	if (lo->use_dio == use_dio)
1992e5ab5f3SMing Lei 		return;
2002e5ab5f3SMing Lei 
2012e5ab5f3SMing Lei 	/* flush dirty pages before changing direct IO */
2022e5ab5f3SMing Lei 	vfs_fsync(file, 0);
2032e5ab5f3SMing Lei 
2042e5ab5f3SMing Lei 	/*
2052e5ab5f3SMing Lei 	 * The flag of LO_FLAGS_DIRECT_IO is handled similarly with
2062e5ab5f3SMing Lei 	 * LO_FLAGS_READ_ONLY, both are set from kernel, and losetup
2072e5ab5f3SMing Lei 	 * will get updated by ioctl(LOOP_GET_STATUS)
2082e5ab5f3SMing Lei 	 */
2090fbcf579SMartijn Coenen 	if (lo->lo_state == Lo_bound)
2102e5ab5f3SMing Lei 		blk_mq_freeze_queue(lo->lo_queue);
2112e5ab5f3SMing Lei 	lo->use_dio = use_dio;
21240326d8aSShaohua Li 	if (use_dio) {
2138b904b5bSBart Van Assche 		blk_queue_flag_clear(QUEUE_FLAG_NOMERGES, lo->lo_queue);
2142e5ab5f3SMing Lei 		lo->lo_flags |= LO_FLAGS_DIRECT_IO;
21540326d8aSShaohua Li 	} else {
2168b904b5bSBart Van Assche 		blk_queue_flag_set(QUEUE_FLAG_NOMERGES, lo->lo_queue);
2172e5ab5f3SMing Lei 		lo->lo_flags &= ~LO_FLAGS_DIRECT_IO;
21840326d8aSShaohua Li 	}
2190fbcf579SMartijn Coenen 	if (lo->lo_state == Lo_bound)
2202e5ab5f3SMing Lei 		blk_mq_unfreeze_queue(lo->lo_queue);
2212e5ab5f3SMing Lei }
2222e5ab5f3SMing Lei 
2235795b6f5SMartijn Coenen /**
2245795b6f5SMartijn Coenen  * loop_set_size() - sets device size and notifies userspace
2255795b6f5SMartijn Coenen  * @lo: struct loop_device to set the size for
2265795b6f5SMartijn Coenen  * @size: new size of the loop device
2275795b6f5SMartijn Coenen  *
2285795b6f5SMartijn Coenen  * Callers must validate that the size passed into this function fits into
2295795b6f5SMartijn Coenen  * a sector_t, eg using loop_validate_size()
2305795b6f5SMartijn Coenen  */
2315795b6f5SMartijn Coenen static void loop_set_size(struct loop_device *lo, loff_t size)
2325795b6f5SMartijn Coenen {
233449f4ec9SChristoph Hellwig 	if (!set_capacity_and_notify(lo->lo_disk, size))
2343b4f85d0SChristoph Hellwig 		kobject_uevent(&disk_to_dev(lo->lo_disk)->kobj, KOBJ_CHANGE);
2351da177e4SLinus Torvalds }
2361da177e4SLinus Torvalds 
237aa4d8616SChristoph Hellwig static int lo_write_bvec(struct file *file, struct bio_vec *bvec, loff_t *ppos)
2381da177e4SLinus Torvalds {
239aa4d8616SChristoph Hellwig 	struct iov_iter i;
2401da177e4SLinus Torvalds 	ssize_t bw;
241283e7e5dSAl Viro 
242b6207430SChristoph Hellwig 	iov_iter_bvec(&i, WRITE, bvec, 1, bvec->bv_len);
2431da177e4SLinus Torvalds 
24403d95eb2SAl Viro 	file_start_write(file);
245abbb6589SChristoph Hellwig 	bw = vfs_iter_write(file, &i, ppos, 0);
24603d95eb2SAl Viro 	file_end_write(file);
247aa4d8616SChristoph Hellwig 
248aa4d8616SChristoph Hellwig 	if (likely(bw ==  bvec->bv_len))
2491da177e4SLinus Torvalds 		return 0;
250aa4d8616SChristoph Hellwig 
251aa4d8616SChristoph Hellwig 	printk_ratelimited(KERN_ERR
252aa4d8616SChristoph Hellwig 		"loop: Write error at byte offset %llu, length %i.\n",
253aa4d8616SChristoph Hellwig 		(unsigned long long)*ppos, bvec->bv_len);
2541da177e4SLinus Torvalds 	if (bw >= 0)
2551da177e4SLinus Torvalds 		bw = -EIO;
2561da177e4SLinus Torvalds 	return bw;
2571da177e4SLinus Torvalds }
2581da177e4SLinus Torvalds 
259aa4d8616SChristoph Hellwig static int lo_write_simple(struct loop_device *lo, struct request *rq,
260aa4d8616SChristoph Hellwig 		loff_t pos)
2611da177e4SLinus Torvalds {
262aa4d8616SChristoph Hellwig 	struct bio_vec bvec;
263aa4d8616SChristoph Hellwig 	struct req_iterator iter;
264aa4d8616SChristoph Hellwig 	int ret = 0;
265aa4d8616SChristoph Hellwig 
266aa4d8616SChristoph Hellwig 	rq_for_each_segment(bvec, rq, iter) {
267aa4d8616SChristoph Hellwig 		ret = lo_write_bvec(lo->lo_backing_file, &bvec, &pos);
268aa4d8616SChristoph Hellwig 		if (ret < 0)
269aa4d8616SChristoph Hellwig 			break;
2701da177e4SLinus Torvalds 		cond_resched();
2711da177e4SLinus Torvalds 	}
2721da177e4SLinus Torvalds 
273aa4d8616SChristoph Hellwig 	return ret;
274aa4d8616SChristoph Hellwig }
275aa4d8616SChristoph Hellwig 
276aa4d8616SChristoph Hellwig static int lo_read_simple(struct loop_device *lo, struct request *rq,
277aa4d8616SChristoph Hellwig 		loff_t pos)
2781da177e4SLinus Torvalds {
2797988613bSKent Overstreet 	struct bio_vec bvec;
28030112013SMing Lei 	struct req_iterator iter;
281aa4d8616SChristoph Hellwig 	struct iov_iter i;
282aa4d8616SChristoph Hellwig 	ssize_t len;
2831da177e4SLinus Torvalds 
28430112013SMing Lei 	rq_for_each_segment(bvec, rq, iter) {
285b6207430SChristoph Hellwig 		iov_iter_bvec(&i, READ, &bvec, 1, bvec.bv_len);
28618e9710eSChristoph Hellwig 		len = vfs_iter_read(lo->lo_backing_file, &i, &pos, 0);
287aa4d8616SChristoph Hellwig 		if (len < 0)
288aa4d8616SChristoph Hellwig 			return len;
289306df071SDave Young 
290aa4d8616SChristoph Hellwig 		flush_dcache_page(bvec.bv_page);
291aa4d8616SChristoph Hellwig 
292aa4d8616SChristoph Hellwig 		if (len != bvec.bv_len) {
29330112013SMing Lei 			struct bio *bio;
29430112013SMing Lei 
29530112013SMing Lei 			__rq_for_each_bio(bio, rq)
296306df071SDave Young 				zero_fill_bio(bio);
2971da177e4SLinus Torvalds 			break;
298306df071SDave Young 		}
299aa4d8616SChristoph Hellwig 		cond_resched();
3001da177e4SLinus Torvalds 	}
301aa4d8616SChristoph Hellwig 
302306df071SDave Young 	return 0;
3031da177e4SLinus Torvalds }
3041da177e4SLinus Torvalds 
305efcfec57SDarrick J. Wong static int lo_fallocate(struct loop_device *lo, struct request *rq, loff_t pos,
306efcfec57SDarrick J. Wong 			int mode)
307cf655d95SMing Lei {
308cf655d95SMing Lei 	/*
309efcfec57SDarrick J. Wong 	 * We use fallocate to manipulate the space mappings used by the image
31047e96246SChristoph Hellwig 	 * a.k.a. discard/zerorange.
311cf655d95SMing Lei 	 */
312cf655d95SMing Lei 	struct file *file = lo->lo_backing_file;
313cf655d95SMing Lei 	int ret;
314cf655d95SMing Lei 
315efcfec57SDarrick J. Wong 	mode |= FALLOC_FL_KEEP_SIZE;
316efcfec57SDarrick J. Wong 
31770200574SChristoph Hellwig 	if (!bdev_max_discard_sectors(lo->lo_device))
31870200574SChristoph Hellwig 		return -EOPNOTSUPP;
319cf655d95SMing Lei 
320cf655d95SMing Lei 	ret = file->f_op->fallocate(file, mode, pos, blk_rq_bytes(rq));
321cf655d95SMing Lei 	if (unlikely(ret && ret != -EINVAL && ret != -EOPNOTSUPP))
32270200574SChristoph Hellwig 		return -EIO;
323cf655d95SMing Lei 	return ret;
324cf655d95SMing Lei }
325cf655d95SMing Lei 
326cf655d95SMing Lei static int lo_req_flush(struct loop_device *lo, struct request *rq)
327cf655d95SMing Lei {
3289c64e38cSChaitanya Kulkarni 	int ret = vfs_fsync(lo->lo_backing_file, 0);
329cf655d95SMing Lei 	if (unlikely(ret && ret != -EINVAL))
330cf655d95SMing Lei 		ret = -EIO;
331cf655d95SMing Lei 
332cf655d95SMing Lei 	return ret;
333cf655d95SMing Lei }
334cf655d95SMing Lei 
335fe2cb290SChristoph Hellwig static void lo_complete_rq(struct request *rq)
336bc07c10aSMing Lei {
337fe2cb290SChristoph Hellwig 	struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
338f9de14bcSJens Axboe 	blk_status_t ret = BLK_STS_OK;
339bc07c10aSMing Lei 
340f9de14bcSJens Axboe 	if (!cmd->use_aio || cmd->ret < 0 || cmd->ret == blk_rq_bytes(rq) ||
341f9de14bcSJens Axboe 	    req_op(rq) != REQ_OP_READ) {
342f9de14bcSJens Axboe 		if (cmd->ret < 0)
3438cd55087SEvan Green 			ret = errno_to_blk_status(cmd->ret);
344f9de14bcSJens Axboe 		goto end_io;
345bc07c10aSMing Lei 	}
346fe2cb290SChristoph Hellwig 
347f9de14bcSJens Axboe 	/*
348f9de14bcSJens Axboe 	 * Short READ - if we got some data, advance our request and
349f9de14bcSJens Axboe 	 * retry it. If we got no data, end the rest with EIO.
350f9de14bcSJens Axboe 	 */
351f9de14bcSJens Axboe 	if (cmd->ret) {
352f9de14bcSJens Axboe 		blk_update_request(rq, BLK_STS_OK, cmd->ret);
353f9de14bcSJens Axboe 		cmd->ret = 0;
354f9de14bcSJens Axboe 		blk_mq_requeue_request(rq, true);
355f9de14bcSJens Axboe 	} else {
356f9de14bcSJens Axboe 		if (cmd->use_aio) {
357f9de14bcSJens Axboe 			struct bio *bio = rq->bio;
358f9de14bcSJens Axboe 
359f9de14bcSJens Axboe 			while (bio) {
360f9de14bcSJens Axboe 				zero_fill_bio(bio);
361f9de14bcSJens Axboe 				bio = bio->bi_next;
362f9de14bcSJens Axboe 			}
363f9de14bcSJens Axboe 		}
364f9de14bcSJens Axboe 		ret = BLK_STS_IOERR;
365f9de14bcSJens Axboe end_io:
366f9de14bcSJens Axboe 		blk_mq_end_request(rq, ret);
367f9de14bcSJens Axboe 	}
368bc07c10aSMing Lei }
369bc07c10aSMing Lei 
37092d77332SShaohua Li static void lo_rw_aio_do_completion(struct loop_cmd *cmd)
37192d77332SShaohua Li {
3721894e916SJens Axboe 	struct request *rq = blk_mq_rq_from_pdu(cmd);
3731894e916SJens Axboe 
37492d77332SShaohua Li 	if (!atomic_dec_and_test(&cmd->ref))
37592d77332SShaohua Li 		return;
37692d77332SShaohua Li 	kfree(cmd->bvec);
37792d77332SShaohua Li 	cmd->bvec = NULL;
37815f73f5bSChristoph Hellwig 	if (likely(!blk_should_fake_timeout(rq->q)))
3791894e916SJens Axboe 		blk_mq_complete_request(rq);
38092d77332SShaohua Li }
38192d77332SShaohua Li 
3826b19b766SJens Axboe static void lo_rw_aio_complete(struct kiocb *iocb, long ret)
383bc07c10aSMing Lei {
384bc07c10aSMing Lei 	struct loop_cmd *cmd = container_of(iocb, struct loop_cmd, iocb);
385bc07c10aSMing Lei 
386fe2cb290SChristoph Hellwig 	cmd->ret = ret;
38792d77332SShaohua Li 	lo_rw_aio_do_completion(cmd);
388bc07c10aSMing Lei }
389bc07c10aSMing Lei 
390bc07c10aSMing Lei static int lo_rw_aio(struct loop_device *lo, struct loop_cmd *cmd,
391bc07c10aSMing Lei 		     loff_t pos, bool rw)
392bc07c10aSMing Lei {
393bc07c10aSMing Lei 	struct iov_iter iter;
39486af5952SMing Lei 	struct req_iterator rq_iter;
395bc07c10aSMing Lei 	struct bio_vec *bvec;
3961894e916SJens Axboe 	struct request *rq = blk_mq_rq_from_pdu(cmd);
39740326d8aSShaohua Li 	struct bio *bio = rq->bio;
398bc07c10aSMing Lei 	struct file *file = lo->lo_backing_file;
39986af5952SMing Lei 	struct bio_vec tmp;
40040326d8aSShaohua Li 	unsigned int offset;
40186af5952SMing Lei 	int nr_bvec = 0;
402bc07c10aSMing Lei 	int ret;
403bc07c10aSMing Lei 
40486af5952SMing Lei 	rq_for_each_bvec(tmp, rq, rq_iter)
40586af5952SMing Lei 		nr_bvec++;
406bc07c10aSMing Lei 
40786af5952SMing Lei 	if (rq->bio != rq->biotail) {
40886af5952SMing Lei 
40986af5952SMing Lei 		bvec = kmalloc_array(nr_bvec, sizeof(struct bio_vec),
4106da2ec56SKees Cook 				     GFP_NOIO);
41140326d8aSShaohua Li 		if (!bvec)
41240326d8aSShaohua Li 			return -EIO;
41340326d8aSShaohua Li 		cmd->bvec = bvec;
41440326d8aSShaohua Li 
415a7297a6aSMing Lei 		/*
41640326d8aSShaohua Li 		 * The bios of the request may be started from the middle of
41740326d8aSShaohua Li 		 * the 'bvec' because of bio splitting, so we can't directly
41886af5952SMing Lei 		 * copy bio->bi_iov_vec to new bvec. The rq_for_each_bvec
41940326d8aSShaohua Li 		 * API will take care of all details for us.
420a7297a6aSMing Lei 		 */
42186af5952SMing Lei 		rq_for_each_bvec(tmp, rq, rq_iter) {
42240326d8aSShaohua Li 			*bvec = tmp;
42340326d8aSShaohua Li 			bvec++;
42440326d8aSShaohua Li 		}
42540326d8aSShaohua Li 		bvec = cmd->bvec;
42640326d8aSShaohua Li 		offset = 0;
42740326d8aSShaohua Li 	} else {
42840326d8aSShaohua Li 		/*
42940326d8aSShaohua Li 		 * Same here, this bio may be started from the middle of the
43040326d8aSShaohua Li 		 * 'bvec' because of bio splitting, so offset from the bvec
43140326d8aSShaohua Li 		 * must be passed to iov iterator
43240326d8aSShaohua Li 		 */
43340326d8aSShaohua Li 		offset = bio->bi_iter.bi_bvec_done;
43440326d8aSShaohua Li 		bvec = __bvec_iter_bvec(bio->bi_io_vec, bio->bi_iter);
43540326d8aSShaohua Li 	}
43692d77332SShaohua Li 	atomic_set(&cmd->ref, 2);
43740326d8aSShaohua Li 
438b6207430SChristoph Hellwig 	iov_iter_bvec(&iter, rw, bvec, nr_bvec, blk_rq_bytes(rq));
43940326d8aSShaohua Li 	iter.iov_offset = offset;
440bc07c10aSMing Lei 
441bc07c10aSMing Lei 	cmd->iocb.ki_pos = pos;
442bc07c10aSMing Lei 	cmd->iocb.ki_filp = file;
443bc07c10aSMing Lei 	cmd->iocb.ki_complete = lo_rw_aio_complete;
444bc07c10aSMing Lei 	cmd->iocb.ki_flags = IOCB_DIRECT;
445d9a08a9eSAdam Manzanares 	cmd->iocb.ki_ioprio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_NONE, 0);
446bc07c10aSMing Lei 
447bc07c10aSMing Lei 	if (rw == WRITE)
448bb7462b6SMiklos Szeredi 		ret = call_write_iter(file, &cmd->iocb, &iter);
449bc07c10aSMing Lei 	else
450bb7462b6SMiklos Szeredi 		ret = call_read_iter(file, &cmd->iocb, &iter);
451bc07c10aSMing Lei 
45292d77332SShaohua Li 	lo_rw_aio_do_completion(cmd);
45392d77332SShaohua Li 
454bc07c10aSMing Lei 	if (ret != -EIOCBQUEUED)
4556b19b766SJens Axboe 		lo_rw_aio_complete(&cmd->iocb, ret);
456bc07c10aSMing Lei 	return 0;
457bc07c10aSMing Lei }
458bc07c10aSMing Lei 
459c1c87c2bSChristoph Hellwig static int do_req_filebacked(struct loop_device *lo, struct request *rq)
460bc07c10aSMing Lei {
461bc07c10aSMing Lei 	struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
462c1c87c2bSChristoph Hellwig 	loff_t pos = ((loff_t) blk_rq_pos(rq) << 9) + lo->lo_offset;
463bc07c10aSMing Lei 
464bc07c10aSMing Lei 	/*
465bc07c10aSMing Lei 	 * lo_write_simple and lo_read_simple should have been covered
466bc07c10aSMing Lei 	 * by io submit style function like lo_rw_aio(), one blocker
467bc07c10aSMing Lei 	 * is that lo_read_simple() need to call flush_dcache_page after
468bc07c10aSMing Lei 	 * the page is written from kernel, and it isn't easy to handle
469bc07c10aSMing Lei 	 * this in io submit style function which submits all segments
470bc07c10aSMing Lei 	 * of the req at one time. And direct read IO doesn't need to
471bc07c10aSMing Lei 	 * run flush_dcache_page().
472bc07c10aSMing Lei 	 */
473c1c87c2bSChristoph Hellwig 	switch (req_op(rq)) {
474c1c87c2bSChristoph Hellwig 	case REQ_OP_FLUSH:
475c1c87c2bSChristoph Hellwig 		return lo_req_flush(lo, rq);
47619372e27SChristoph Hellwig 	case REQ_OP_WRITE_ZEROES:
477efcfec57SDarrick J. Wong 		/*
478efcfec57SDarrick J. Wong 		 * If the caller doesn't want deallocation, call zeroout to
479efcfec57SDarrick J. Wong 		 * write zeroes the range.  Otherwise, punch them out.
480efcfec57SDarrick J. Wong 		 */
481efcfec57SDarrick J. Wong 		return lo_fallocate(lo, rq, pos,
482efcfec57SDarrick J. Wong 			(rq->cmd_flags & REQ_NOUNMAP) ?
483efcfec57SDarrick J. Wong 				FALLOC_FL_ZERO_RANGE :
484efcfec57SDarrick J. Wong 				FALLOC_FL_PUNCH_HOLE);
485efcfec57SDarrick J. Wong 	case REQ_OP_DISCARD:
486efcfec57SDarrick J. Wong 		return lo_fallocate(lo, rq, pos, FALLOC_FL_PUNCH_HOLE);
487c1c87c2bSChristoph Hellwig 	case REQ_OP_WRITE:
48847e96246SChristoph Hellwig 		if (cmd->use_aio)
489c1c87c2bSChristoph Hellwig 			return lo_rw_aio(lo, cmd, pos, WRITE);
490c1c87c2bSChristoph Hellwig 		else
491bc07c10aSMing Lei 			return lo_write_simple(lo, rq, pos);
492c1c87c2bSChristoph Hellwig 	case REQ_OP_READ:
49347e96246SChristoph Hellwig 		if (cmd->use_aio)
494c1c87c2bSChristoph Hellwig 			return lo_rw_aio(lo, cmd, pos, READ);
495bc07c10aSMing Lei 		else
496bc07c10aSMing Lei 			return lo_read_simple(lo, rq, pos);
497c1c87c2bSChristoph Hellwig 	default:
498c1c87c2bSChristoph Hellwig 		WARN_ON_ONCE(1);
499c1c87c2bSChristoph Hellwig 		return -EIO;
500bc07c10aSMing Lei 	}
5011da177e4SLinus Torvalds }
5021da177e4SLinus Torvalds 
5032e5ab5f3SMing Lei static inline void loop_update_dio(struct loop_device *lo)
5042e5ab5f3SMing Lei {
505efbe3c24SIra Weiny 	__loop_update_dio(lo, (lo->lo_backing_file->f_flags & O_DIRECT) |
5062e5ab5f3SMing Lei 				lo->use_dio);
5072e5ab5f3SMing Lei }
5082e5ab5f3SMing Lei 
5090384264eSChristoph Hellwig static void loop_reread_partitions(struct loop_device *lo)
51006f0e9e6SMing Lei {
51106f0e9e6SMing Lei 	int rc;
51206f0e9e6SMing Lei 
5130384264eSChristoph Hellwig 	mutex_lock(&lo->lo_disk->open_mutex);
5140384264eSChristoph Hellwig 	rc = bdev_disk_changed(lo->lo_disk, false);
5150384264eSChristoph Hellwig 	mutex_unlock(&lo->lo_disk->open_mutex);
51606f0e9e6SMing Lei 	if (rc)
51706f0e9e6SMing Lei 		pr_warn("%s: partition scan of loop%d (%s) failed (rc=%d)\n",
51806f0e9e6SMing Lei 			__func__, lo->lo_number, lo->lo_file_name, rc);
51906f0e9e6SMing Lei }
52006f0e9e6SMing Lei 
521d2ac838eSTheodore Ts'o static inline int is_loop_device(struct file *file)
522d2ac838eSTheodore Ts'o {
523d2ac838eSTheodore Ts'o 	struct inode *i = file->f_mapping->host;
524d2ac838eSTheodore Ts'o 
5256f24784fSAl Viro 	return i && S_ISBLK(i->i_mode) && imajor(i) == LOOP_MAJOR;
526d2ac838eSTheodore Ts'o }
527d2ac838eSTheodore Ts'o 
528d2ac838eSTheodore Ts'o static int loop_validate_file(struct file *file, struct block_device *bdev)
529d2ac838eSTheodore Ts'o {
530d2ac838eSTheodore Ts'o 	struct inode	*inode = file->f_mapping->host;
531d2ac838eSTheodore Ts'o 	struct file	*f = file;
532d2ac838eSTheodore Ts'o 
533d2ac838eSTheodore Ts'o 	/* Avoid recursion */
534d2ac838eSTheodore Ts'o 	while (is_loop_device(f)) {
535d2ac838eSTheodore Ts'o 		struct loop_device *l;
536d2ac838eSTheodore Ts'o 
5373ce6e1f6STetsuo Handa 		lockdep_assert_held(&loop_validate_mutex);
5384e7b5671SChristoph Hellwig 		if (f->f_mapping->host->i_rdev == bdev->bd_dev)
539d2ac838eSTheodore Ts'o 			return -EBADF;
540d2ac838eSTheodore Ts'o 
5414e7b5671SChristoph Hellwig 		l = I_BDEV(f->f_mapping->host)->bd_disk->private_data;
5423ce6e1f6STetsuo Handa 		if (l->lo_state != Lo_bound)
543d2ac838eSTheodore Ts'o 			return -EINVAL;
5443ce6e1f6STetsuo Handa 		/* Order wrt setting lo->lo_backing_file in loop_configure(). */
5453ce6e1f6STetsuo Handa 		rmb();
546d2ac838eSTheodore Ts'o 		f = l->lo_backing_file;
547d2ac838eSTheodore Ts'o 	}
548d2ac838eSTheodore Ts'o 	if (!S_ISREG(inode->i_mode) && !S_ISBLK(inode->i_mode))
549d2ac838eSTheodore Ts'o 		return -EINVAL;
550d2ac838eSTheodore Ts'o 	return 0;
551d2ac838eSTheodore Ts'o }
552d2ac838eSTheodore Ts'o 
5531da177e4SLinus Torvalds /*
5541da177e4SLinus Torvalds  * loop_change_fd switched the backing store of a loopback device to
5551da177e4SLinus Torvalds  * a new file. This is useful for operating system installers to free up
5561da177e4SLinus Torvalds  * the original file and in High Availability environments to switch to
5571da177e4SLinus Torvalds  * an alternative location for the content in case of server meltdown.
5581da177e4SLinus Torvalds  * This can only work if the loop device is used read-only, and if the
5591da177e4SLinus Torvalds  * new backing store is the same size and type as the old backing store.
5601da177e4SLinus Torvalds  */
561bb214884SAl Viro static int loop_change_fd(struct loop_device *lo, struct block_device *bdev,
562bb214884SAl Viro 			  unsigned int arg)
5631da177e4SLinus Torvalds {
5643ce6e1f6STetsuo Handa 	struct file *file = fget(arg);
5653ce6e1f6STetsuo Handa 	struct file *old_file;
5661da177e4SLinus Torvalds 	int error;
56785b0a54aSJan Kara 	bool partscan;
5683ce6e1f6STetsuo Handa 	bool is_loop;
5691da177e4SLinus Torvalds 
5703ce6e1f6STetsuo Handa 	if (!file)
5713ce6e1f6STetsuo Handa 		return -EBADF;
5723ce6e1f6STetsuo Handa 	is_loop = is_loop_device(file);
5733ce6e1f6STetsuo Handa 	error = loop_global_lock_killable(lo, is_loop);
574c3710770SJan Kara 	if (error)
5753ce6e1f6STetsuo Handa 		goto out_putf;
5761da177e4SLinus Torvalds 	error = -ENXIO;
5771da177e4SLinus Torvalds 	if (lo->lo_state != Lo_bound)
5781dded9acSJan Kara 		goto out_err;
5791da177e4SLinus Torvalds 
5801da177e4SLinus Torvalds 	/* the loop device has to be read-only */
5811da177e4SLinus Torvalds 	error = -EINVAL;
5821da177e4SLinus Torvalds 	if (!(lo->lo_flags & LO_FLAGS_READ_ONLY))
5831dded9acSJan Kara 		goto out_err;
5841da177e4SLinus Torvalds 
585d2ac838eSTheodore Ts'o 	error = loop_validate_file(file, bdev);
586d2ac838eSTheodore Ts'o 	if (error)
5871dded9acSJan Kara 		goto out_err;
588d2ac838eSTheodore Ts'o 
5891da177e4SLinus Torvalds 	old_file = lo->lo_backing_file;
5901da177e4SLinus Torvalds 
5911da177e4SLinus Torvalds 	error = -EINVAL;
5921da177e4SLinus Torvalds 
5931da177e4SLinus Torvalds 	/* size of the new backing store needs to be the same */
5941da177e4SLinus Torvalds 	if (get_loop_size(lo, file) != get_loop_size(lo, old_file))
5951dded9acSJan Kara 		goto out_err;
5961da177e4SLinus Torvalds 
5971da177e4SLinus Torvalds 	/* and ... switch */
5989f65c489SMatteo Croce 	disk_force_media_change(lo->lo_disk, DISK_EVENT_MEDIA_CHANGE);
59943cade80SOmar Sandoval 	blk_mq_freeze_queue(lo->lo_queue);
60043cade80SOmar Sandoval 	mapping_set_gfp_mask(old_file->f_mapping, lo->old_gfp_mask);
60143cade80SOmar Sandoval 	lo->lo_backing_file = file;
60243cade80SOmar Sandoval 	lo->old_gfp_mask = mapping_gfp_mask(file->f_mapping);
60343cade80SOmar Sandoval 	mapping_set_gfp_mask(file->f_mapping,
60443cade80SOmar Sandoval 			     lo->old_gfp_mask & ~(__GFP_IO|__GFP_FS));
60543cade80SOmar Sandoval 	loop_update_dio(lo);
60643cade80SOmar Sandoval 	blk_mq_unfreeze_queue(lo->lo_queue);
60785b0a54aSJan Kara 	partscan = lo->lo_flags & LO_FLAGS_PARTSCAN;
6083ce6e1f6STetsuo Handa 	loop_global_unlock(lo, is_loop);
6093ce6e1f6STetsuo Handa 
6103ce6e1f6STetsuo Handa 	/*
6113ce6e1f6STetsuo Handa 	 * Flush loop_validate_file() before fput(), for l->lo_backing_file
6123ce6e1f6STetsuo Handa 	 * might be pointing at old_file which might be the last reference.
6133ce6e1f6STetsuo Handa 	 */
6143ce6e1f6STetsuo Handa 	if (!is_loop) {
6153ce6e1f6STetsuo Handa 		mutex_lock(&loop_validate_mutex);
6163ce6e1f6STetsuo Handa 		mutex_unlock(&loop_validate_mutex);
6173ce6e1f6STetsuo Handa 	}
6181dded9acSJan Kara 	/*
6196cc8e743SPavel Tatashin 	 * We must drop file reference outside of lo_mutex as dropping
620a8698707SChristoph Hellwig 	 * the file ref can take open_mutex which creates circular locking
6211dded9acSJan Kara 	 * dependency.
6221dded9acSJan Kara 	 */
6231dded9acSJan Kara 	fput(old_file);
62485b0a54aSJan Kara 	if (partscan)
6250384264eSChristoph Hellwig 		loop_reread_partitions(lo);
6261da177e4SLinus Torvalds 	return 0;
6271da177e4SLinus Torvalds 
6281dded9acSJan Kara out_err:
6293ce6e1f6STetsuo Handa 	loop_global_unlock(lo, is_loop);
6303ce6e1f6STetsuo Handa out_putf:
6311dded9acSJan Kara 	fput(file);
6321da177e4SLinus Torvalds 	return error;
6331da177e4SLinus Torvalds }
6341da177e4SLinus Torvalds 
635ee862730SMilan Broz /* loop sysfs attributes */
636ee862730SMilan Broz 
637ee862730SMilan Broz static ssize_t loop_attr_show(struct device *dev, char *page,
638ee862730SMilan Broz 			      ssize_t (*callback)(struct loop_device *, char *))
639ee862730SMilan Broz {
64034dd82afSKay Sievers 	struct gendisk *disk = dev_to_disk(dev);
64134dd82afSKay Sievers 	struct loop_device *lo = disk->private_data;
642ee862730SMilan Broz 
64334dd82afSKay Sievers 	return callback(lo, page);
644ee862730SMilan Broz }
645ee862730SMilan Broz 
646ee862730SMilan Broz #define LOOP_ATTR_RO(_name)						\
647ee862730SMilan Broz static ssize_t loop_attr_##_name##_show(struct loop_device *, char *);	\
648ee862730SMilan Broz static ssize_t loop_attr_do_show_##_name(struct device *d,		\
649ee862730SMilan Broz 				struct device_attribute *attr, char *b)	\
650ee862730SMilan Broz {									\
651ee862730SMilan Broz 	return loop_attr_show(d, b, loop_attr_##_name##_show);		\
652ee862730SMilan Broz }									\
653ee862730SMilan Broz static struct device_attribute loop_attr_##_name =			\
6545657a819SJoe Perches 	__ATTR(_name, 0444, loop_attr_do_show_##_name, NULL);
655ee862730SMilan Broz 
656ee862730SMilan Broz static ssize_t loop_attr_backing_file_show(struct loop_device *lo, char *buf)
657ee862730SMilan Broz {
658ee862730SMilan Broz 	ssize_t ret;
659ee862730SMilan Broz 	char *p = NULL;
660ee862730SMilan Broz 
66105eb0f25SKay Sievers 	spin_lock_irq(&lo->lo_lock);
662ee862730SMilan Broz 	if (lo->lo_backing_file)
6639bf39ab2SMiklos Szeredi 		p = file_path(lo->lo_backing_file, buf, PAGE_SIZE - 1);
66405eb0f25SKay Sievers 	spin_unlock_irq(&lo->lo_lock);
665ee862730SMilan Broz 
666ee862730SMilan Broz 	if (IS_ERR_OR_NULL(p))
667ee862730SMilan Broz 		ret = PTR_ERR(p);
668ee862730SMilan Broz 	else {
669ee862730SMilan Broz 		ret = strlen(p);
670ee862730SMilan Broz 		memmove(buf, p, ret);
671ee862730SMilan Broz 		buf[ret++] = '\n';
672ee862730SMilan Broz 		buf[ret] = 0;
673ee862730SMilan Broz 	}
674ee862730SMilan Broz 
675ee862730SMilan Broz 	return ret;
676ee862730SMilan Broz }
677ee862730SMilan Broz 
678ee862730SMilan Broz static ssize_t loop_attr_offset_show(struct loop_device *lo, char *buf)
679ee862730SMilan Broz {
680b27824d3SChaitanya Kulkarni 	return sysfs_emit(buf, "%llu\n", (unsigned long long)lo->lo_offset);
681ee862730SMilan Broz }
682ee862730SMilan Broz 
683ee862730SMilan Broz static ssize_t loop_attr_sizelimit_show(struct loop_device *lo, char *buf)
684ee862730SMilan Broz {
685b27824d3SChaitanya Kulkarni 	return sysfs_emit(buf, "%llu\n", (unsigned long long)lo->lo_sizelimit);
686ee862730SMilan Broz }
687ee862730SMilan Broz 
688ee862730SMilan Broz static ssize_t loop_attr_autoclear_show(struct loop_device *lo, char *buf)
689ee862730SMilan Broz {
690ee862730SMilan Broz 	int autoclear = (lo->lo_flags & LO_FLAGS_AUTOCLEAR);
691ee862730SMilan Broz 
692b27824d3SChaitanya Kulkarni 	return sysfs_emit(buf, "%s\n", autoclear ? "1" : "0");
693ee862730SMilan Broz }
694ee862730SMilan Broz 
695e03c8dd1SKay Sievers static ssize_t loop_attr_partscan_show(struct loop_device *lo, char *buf)
696e03c8dd1SKay Sievers {
697e03c8dd1SKay Sievers 	int partscan = (lo->lo_flags & LO_FLAGS_PARTSCAN);
698e03c8dd1SKay Sievers 
699b27824d3SChaitanya Kulkarni 	return sysfs_emit(buf, "%s\n", partscan ? "1" : "0");
700e03c8dd1SKay Sievers }
701e03c8dd1SKay Sievers 
7022e5ab5f3SMing Lei static ssize_t loop_attr_dio_show(struct loop_device *lo, char *buf)
7032e5ab5f3SMing Lei {
7042e5ab5f3SMing Lei 	int dio = (lo->lo_flags & LO_FLAGS_DIRECT_IO);
7052e5ab5f3SMing Lei 
706b27824d3SChaitanya Kulkarni 	return sysfs_emit(buf, "%s\n", dio ? "1" : "0");
7072e5ab5f3SMing Lei }
7082e5ab5f3SMing Lei 
709ee862730SMilan Broz LOOP_ATTR_RO(backing_file);
710ee862730SMilan Broz LOOP_ATTR_RO(offset);
711ee862730SMilan Broz LOOP_ATTR_RO(sizelimit);
712ee862730SMilan Broz LOOP_ATTR_RO(autoclear);
713e03c8dd1SKay Sievers LOOP_ATTR_RO(partscan);
7142e5ab5f3SMing Lei LOOP_ATTR_RO(dio);
715ee862730SMilan Broz 
716ee862730SMilan Broz static struct attribute *loop_attrs[] = {
717ee862730SMilan Broz 	&loop_attr_backing_file.attr,
718ee862730SMilan Broz 	&loop_attr_offset.attr,
719ee862730SMilan Broz 	&loop_attr_sizelimit.attr,
720ee862730SMilan Broz 	&loop_attr_autoclear.attr,
721e03c8dd1SKay Sievers 	&loop_attr_partscan.attr,
7222e5ab5f3SMing Lei 	&loop_attr_dio.attr,
723ee862730SMilan Broz 	NULL,
724ee862730SMilan Broz };
725ee862730SMilan Broz 
726ee862730SMilan Broz static struct attribute_group loop_attribute_group = {
727ee862730SMilan Broz 	.name = "loop",
728ee862730SMilan Broz 	.attrs= loop_attrs,
729ee862730SMilan Broz };
730ee862730SMilan Broz 
731d3349b6bSTetsuo Handa static void loop_sysfs_init(struct loop_device *lo)
732ee862730SMilan Broz {
733d3349b6bSTetsuo Handa 	lo->sysfs_inited = !sysfs_create_group(&disk_to_dev(lo->lo_disk)->kobj,
734ee862730SMilan Broz 						&loop_attribute_group);
735ee862730SMilan Broz }
736ee862730SMilan Broz 
737ee862730SMilan Broz static void loop_sysfs_exit(struct loop_device *lo)
738ee862730SMilan Broz {
739d3349b6bSTetsuo Handa 	if (lo->sysfs_inited)
740ee862730SMilan Broz 		sysfs_remove_group(&disk_to_dev(lo->lo_disk)->kobj,
741ee862730SMilan Broz 				   &loop_attribute_group);
742ee862730SMilan Broz }
743ee862730SMilan Broz 
744dfaa2ef6SLukas Czerner static void loop_config_discard(struct loop_device *lo)
745dfaa2ef6SLukas Czerner {
746dfaa2ef6SLukas Czerner 	struct file *file = lo->lo_backing_file;
747dfaa2ef6SLukas Czerner 	struct inode *inode = file->f_mapping->host;
748dfaa2ef6SLukas Czerner 	struct request_queue *q = lo->lo_queue;
749bcb21c8cSMing Lei 	u32 granularity, max_discard_sectors;
750dfaa2ef6SLukas Czerner 
751dfaa2ef6SLukas Czerner 	/*
752c52abf56SEvan Green 	 * If the backing device is a block device, mirror its zeroing
753c52abf56SEvan Green 	 * capability. Set the discard sectors to the block device's zeroing
754c52abf56SEvan Green 	 * capabilities because loop discards result in blkdev_issue_zeroout(),
755c52abf56SEvan Green 	 * not blkdev_issue_discard(). This maintains consistent behavior with
756c52abf56SEvan Green 	 * file-backed loop devices: discarded regions read back as zero.
757c52abf56SEvan Green 	 */
75847e96246SChristoph Hellwig 	if (S_ISBLK(inode->i_mode)) {
7594e7b5671SChristoph Hellwig 		struct request_queue *backingq = bdev_get_queue(I_BDEV(inode));
760c52abf56SEvan Green 
761bcb21c8cSMing Lei 		max_discard_sectors = backingq->limits.max_write_zeroes_sectors;
7627b47ef52SChristoph Hellwig 		granularity = bdev_discard_granularity(I_BDEV(inode)) ?:
763bcb21c8cSMing Lei 			queue_physical_block_size(backingq);
764c52abf56SEvan Green 
765c52abf56SEvan Green 	/*
766dfaa2ef6SLukas Czerner 	 * We use punch hole to reclaim the free space used by the
76747e96246SChristoph Hellwig 	 * image a.k.a. discard.
768dfaa2ef6SLukas Czerner 	 */
76947e96246SChristoph Hellwig 	} else if (!file->f_op->fallocate) {
770bcb21c8cSMing Lei 		max_discard_sectors = 0;
771bcb21c8cSMing Lei 		granularity = 0;
772dfaa2ef6SLukas Czerner 
773c52abf56SEvan Green 	} else {
77406582bc8SMing Lei 		struct kstatfs sbuf;
77506582bc8SMing Lei 
776bcb21c8cSMing Lei 		max_discard_sectors = UINT_MAX >> 9;
77706582bc8SMing Lei 		if (!vfs_statfs(&file->f_path, &sbuf))
77806582bc8SMing Lei 			granularity = sbuf.f_bsize;
77906582bc8SMing Lei 		else
78006582bc8SMing Lei 			max_discard_sectors = 0;
781c52abf56SEvan Green 	}
782c52abf56SEvan Green 
783bcb21c8cSMing Lei 	if (max_discard_sectors) {
784bcb21c8cSMing Lei 		q->limits.discard_granularity = granularity;
785bcb21c8cSMing Lei 		blk_queue_max_discard_sectors(q, max_discard_sectors);
786bcb21c8cSMing Lei 		blk_queue_max_write_zeroes_sectors(q, max_discard_sectors);
787bcb21c8cSMing Lei 	} else {
788bcb21c8cSMing Lei 		q->limits.discard_granularity = 0;
789bcb21c8cSMing Lei 		blk_queue_max_discard_sectors(q, 0);
790bcb21c8cSMing Lei 		blk_queue_max_write_zeroes_sectors(q, 0);
791dfaa2ef6SLukas Czerner 	}
792bcb21c8cSMing Lei 	q->limits.discard_alignment = 0;
793bcb21c8cSMing Lei }
794dfaa2ef6SLukas Czerner 
79587579e9bSDan Schatzberg struct loop_worker {
79687579e9bSDan Schatzberg 	struct rb_node rb_node;
79787579e9bSDan Schatzberg 	struct work_struct work;
79887579e9bSDan Schatzberg 	struct list_head cmd_list;
79987579e9bSDan Schatzberg 	struct list_head idle_list;
80087579e9bSDan Schatzberg 	struct loop_device *lo;
801c74d40e8SDan Schatzberg 	struct cgroup_subsys_state *blkcg_css;
80287579e9bSDan Schatzberg 	unsigned long last_ran_at;
80387579e9bSDan Schatzberg };
804e03a3d7aSMing Lei 
80587579e9bSDan Schatzberg static void loop_workfn(struct work_struct *work);
80687579e9bSDan Schatzberg static void loop_rootcg_workfn(struct work_struct *work);
807b2ee7d46SNeilBrown 
80887579e9bSDan Schatzberg #ifdef CONFIG_BLK_CGROUP
80987579e9bSDan Schatzberg static inline int queue_on_root_worker(struct cgroup_subsys_state *css)
810e03a3d7aSMing Lei {
81187579e9bSDan Schatzberg 	return !css || css == blkcg_root_css;
81287579e9bSDan Schatzberg }
81387579e9bSDan Schatzberg #else
81487579e9bSDan Schatzberg static inline int queue_on_root_worker(struct cgroup_subsys_state *css)
81587579e9bSDan Schatzberg {
81687579e9bSDan Schatzberg 	return !css;
81787579e9bSDan Schatzberg }
81887579e9bSDan Schatzberg #endif
81987579e9bSDan Schatzberg 
82087579e9bSDan Schatzberg static void loop_queue_work(struct loop_device *lo, struct loop_cmd *cmd)
82187579e9bSDan Schatzberg {
822413ec805SColin Ian King 	struct rb_node **node, *parent = NULL;
82387579e9bSDan Schatzberg 	struct loop_worker *cur_worker, *worker = NULL;
82487579e9bSDan Schatzberg 	struct work_struct *work;
82587579e9bSDan Schatzberg 	struct list_head *cmd_list;
82687579e9bSDan Schatzberg 
82787579e9bSDan Schatzberg 	spin_lock_irq(&lo->lo_work_lock);
82887579e9bSDan Schatzberg 
829c74d40e8SDan Schatzberg 	if (queue_on_root_worker(cmd->blkcg_css))
83087579e9bSDan Schatzberg 		goto queue_work;
83187579e9bSDan Schatzberg 
83287579e9bSDan Schatzberg 	node = &lo->worker_tree.rb_node;
83387579e9bSDan Schatzberg 
83487579e9bSDan Schatzberg 	while (*node) {
83587579e9bSDan Schatzberg 		parent = *node;
83687579e9bSDan Schatzberg 		cur_worker = container_of(*node, struct loop_worker, rb_node);
837c74d40e8SDan Schatzberg 		if (cur_worker->blkcg_css == cmd->blkcg_css) {
83887579e9bSDan Schatzberg 			worker = cur_worker;
83987579e9bSDan Schatzberg 			break;
840c74d40e8SDan Schatzberg 		} else if ((long)cur_worker->blkcg_css < (long)cmd->blkcg_css) {
84187579e9bSDan Schatzberg 			node = &(*node)->rb_left;
84287579e9bSDan Schatzberg 		} else {
84387579e9bSDan Schatzberg 			node = &(*node)->rb_right;
84487579e9bSDan Schatzberg 		}
84587579e9bSDan Schatzberg 	}
84687579e9bSDan Schatzberg 	if (worker)
84787579e9bSDan Schatzberg 		goto queue_work;
84887579e9bSDan Schatzberg 
84987579e9bSDan Schatzberg 	worker = kzalloc(sizeof(struct loop_worker), GFP_NOWAIT | __GFP_NOWARN);
85087579e9bSDan Schatzberg 	/*
85187579e9bSDan Schatzberg 	 * In the event we cannot allocate a worker, just queue on the
852c74d40e8SDan Schatzberg 	 * rootcg worker and issue the I/O as the rootcg
85387579e9bSDan Schatzberg 	 */
854c74d40e8SDan Schatzberg 	if (!worker) {
855c74d40e8SDan Schatzberg 		cmd->blkcg_css = NULL;
856c74d40e8SDan Schatzberg 		if (cmd->memcg_css)
857c74d40e8SDan Schatzberg 			css_put(cmd->memcg_css);
858c74d40e8SDan Schatzberg 		cmd->memcg_css = NULL;
85987579e9bSDan Schatzberg 		goto queue_work;
860c74d40e8SDan Schatzberg 	}
86187579e9bSDan Schatzberg 
862c74d40e8SDan Schatzberg 	worker->blkcg_css = cmd->blkcg_css;
863c74d40e8SDan Schatzberg 	css_get(worker->blkcg_css);
86487579e9bSDan Schatzberg 	INIT_WORK(&worker->work, loop_workfn);
86587579e9bSDan Schatzberg 	INIT_LIST_HEAD(&worker->cmd_list);
86687579e9bSDan Schatzberg 	INIT_LIST_HEAD(&worker->idle_list);
86787579e9bSDan Schatzberg 	worker->lo = lo;
86887579e9bSDan Schatzberg 	rb_link_node(&worker->rb_node, parent, node);
86987579e9bSDan Schatzberg 	rb_insert_color(&worker->rb_node, &lo->worker_tree);
87087579e9bSDan Schatzberg queue_work:
87187579e9bSDan Schatzberg 	if (worker) {
87287579e9bSDan Schatzberg 		/*
87387579e9bSDan Schatzberg 		 * We need to remove from the idle list here while
87487579e9bSDan Schatzberg 		 * holding the lock so that the idle timer doesn't
87587579e9bSDan Schatzberg 		 * free the worker
87687579e9bSDan Schatzberg 		 */
87787579e9bSDan Schatzberg 		if (!list_empty(&worker->idle_list))
87887579e9bSDan Schatzberg 			list_del_init(&worker->idle_list);
87987579e9bSDan Schatzberg 		work = &worker->work;
88087579e9bSDan Schatzberg 		cmd_list = &worker->cmd_list;
88187579e9bSDan Schatzberg 	} else {
88287579e9bSDan Schatzberg 		work = &lo->rootcg_work;
88387579e9bSDan Schatzberg 		cmd_list = &lo->rootcg_cmd_list;
88487579e9bSDan Schatzberg 	}
88587579e9bSDan Schatzberg 	list_add_tail(&cmd->list_entry, cmd_list);
88687579e9bSDan Schatzberg 	queue_work(lo->workqueue, work);
88787579e9bSDan Schatzberg 	spin_unlock_irq(&lo->lo_work_lock);
888e03a3d7aSMing Lei }
889e03a3d7aSMing Lei 
890*2cf429b5SChristoph Hellwig static void loop_set_timer(struct loop_device *lo)
891*2cf429b5SChristoph Hellwig {
892*2cf429b5SChristoph Hellwig 	timer_reduce(&lo->timer, jiffies + LOOP_IDLE_WORKER_TIMEOUT);
893*2cf429b5SChristoph Hellwig }
894*2cf429b5SChristoph Hellwig 
895*2cf429b5SChristoph Hellwig static void loop_free_idle_workers(struct loop_device *lo, bool delete_all)
896*2cf429b5SChristoph Hellwig {
897*2cf429b5SChristoph Hellwig 	struct loop_worker *pos, *worker;
898*2cf429b5SChristoph Hellwig 
899*2cf429b5SChristoph Hellwig 	spin_lock_irq(&lo->lo_work_lock);
900*2cf429b5SChristoph Hellwig 	list_for_each_entry_safe(worker, pos, &lo->idle_worker_list,
901*2cf429b5SChristoph Hellwig 				idle_list) {
902*2cf429b5SChristoph Hellwig 		if (!delete_all &&
903*2cf429b5SChristoph Hellwig 		    time_is_after_jiffies(worker->last_ran_at +
904*2cf429b5SChristoph Hellwig 					  LOOP_IDLE_WORKER_TIMEOUT))
905*2cf429b5SChristoph Hellwig 			break;
906*2cf429b5SChristoph Hellwig 		list_del(&worker->idle_list);
907*2cf429b5SChristoph Hellwig 		rb_erase(&worker->rb_node, &lo->worker_tree);
908*2cf429b5SChristoph Hellwig 		css_put(worker->blkcg_css);
909*2cf429b5SChristoph Hellwig 		kfree(worker);
910*2cf429b5SChristoph Hellwig 	}
911*2cf429b5SChristoph Hellwig 	if (!list_empty(&lo->idle_worker_list))
912*2cf429b5SChristoph Hellwig 		loop_set_timer(lo);
913*2cf429b5SChristoph Hellwig 	spin_unlock_irq(&lo->lo_work_lock);
914*2cf429b5SChristoph Hellwig }
915*2cf429b5SChristoph Hellwig 
916*2cf429b5SChristoph Hellwig static void loop_free_idle_workers_timer(struct timer_list *timer)
917*2cf429b5SChristoph Hellwig {
918*2cf429b5SChristoph Hellwig 	struct loop_device *lo = container_of(timer, struct loop_device, timer);
919*2cf429b5SChristoph Hellwig 
920*2cf429b5SChristoph Hellwig 	return loop_free_idle_workers(lo, false);
921*2cf429b5SChristoph Hellwig }
922*2cf429b5SChristoph Hellwig 
92356a85fd8SHolger Hoffstätte static void loop_update_rotational(struct loop_device *lo)
92456a85fd8SHolger Hoffstätte {
92556a85fd8SHolger Hoffstätte 	struct file *file = lo->lo_backing_file;
92656a85fd8SHolger Hoffstätte 	struct inode *file_inode = file->f_mapping->host;
92756a85fd8SHolger Hoffstätte 	struct block_device *file_bdev = file_inode->i_sb->s_bdev;
92856a85fd8SHolger Hoffstätte 	struct request_queue *q = lo->lo_queue;
92956a85fd8SHolger Hoffstätte 	bool nonrot = true;
93056a85fd8SHolger Hoffstätte 
93156a85fd8SHolger Hoffstätte 	/* not all filesystems (e.g. tmpfs) have a sb->s_bdev */
93256a85fd8SHolger Hoffstätte 	if (file_bdev)
93310f0d2a5SChristoph Hellwig 		nonrot = bdev_nonrot(file_bdev);
93456a85fd8SHolger Hoffstätte 
93556a85fd8SHolger Hoffstätte 	if (nonrot)
93656a85fd8SHolger Hoffstätte 		blk_queue_flag_set(QUEUE_FLAG_NONROT, q);
93756a85fd8SHolger Hoffstätte 	else
93856a85fd8SHolger Hoffstätte 		blk_queue_flag_clear(QUEUE_FLAG_NONROT, q);
93956a85fd8SHolger Hoffstätte }
94056a85fd8SHolger Hoffstätte 
94162ab466cSMartijn Coenen /**
94262ab466cSMartijn Coenen  * loop_set_status_from_info - configure device from loop_info
94362ab466cSMartijn Coenen  * @lo: struct loop_device to configure
94462ab466cSMartijn Coenen  * @info: struct loop_info64 to configure the device with
94562ab466cSMartijn Coenen  *
94662ab466cSMartijn Coenen  * Configures the loop device parameters according to the passed
94762ab466cSMartijn Coenen  * in loop_info64 configuration.
94862ab466cSMartijn Coenen  */
94962ab466cSMartijn Coenen static int
95062ab466cSMartijn Coenen loop_set_status_from_info(struct loop_device *lo,
95162ab466cSMartijn Coenen 			  const struct loop_info64 *info)
95262ab466cSMartijn Coenen {
95362ab466cSMartijn Coenen 	if ((unsigned int) info->lo_encrypt_key_size > LO_KEY_SIZE)
95462ab466cSMartijn Coenen 		return -EINVAL;
95562ab466cSMartijn Coenen 
95647e96246SChristoph Hellwig 	switch (info->lo_encrypt_type) {
95747e96246SChristoph Hellwig 	case LO_CRYPT_NONE:
95847e96246SChristoph Hellwig 		break;
95947e96246SChristoph Hellwig 	case LO_CRYPT_XOR:
96047e96246SChristoph Hellwig 		pr_warn("support for the xor transformation has been removed.\n");
96162ab466cSMartijn Coenen 		return -EINVAL;
96247e96246SChristoph Hellwig 	case LO_CRYPT_CRYPTOAPI:
96347e96246SChristoph Hellwig 		pr_warn("support for cryptoloop has been removed.  Use dm-crypt instead.\n");
96462ab466cSMartijn Coenen 		return -EINVAL;
96547e96246SChristoph Hellwig 	default:
96647e96246SChristoph Hellwig 		return -EINVAL;
96747e96246SChristoph Hellwig 	}
96862ab466cSMartijn Coenen 
96962ab466cSMartijn Coenen 	lo->lo_offset = info->lo_offset;
97062ab466cSMartijn Coenen 	lo->lo_sizelimit = info->lo_sizelimit;
97162ab466cSMartijn Coenen 	memcpy(lo->lo_file_name, info->lo_file_name, LO_NAME_SIZE);
97262ab466cSMartijn Coenen 	lo->lo_file_name[LO_NAME_SIZE-1] = 0;
973faf1d254SMartijn Coenen 	lo->lo_flags = info->lo_flags;
97462ab466cSMartijn Coenen 	return 0;
97562ab466cSMartijn Coenen }
97662ab466cSMartijn Coenen 
9773448914eSMartijn Coenen static int loop_configure(struct loop_device *lo, fmode_t mode,
9783448914eSMartijn Coenen 			  struct block_device *bdev,
9793448914eSMartijn Coenen 			  const struct loop_config *config)
9801da177e4SLinus Torvalds {
9813ce6e1f6STetsuo Handa 	struct file *file = fget(config->fd);
9821da177e4SLinus Torvalds 	struct inode *inode;
9831da177e4SLinus Torvalds 	struct address_space *mapping;
9841da177e4SLinus Torvalds 	int error;
9851da177e4SLinus Torvalds 	loff_t size;
98685b0a54aSJan Kara 	bool partscan;
9873448914eSMartijn Coenen 	unsigned short bsize;
9883ce6e1f6STetsuo Handa 	bool is_loop;
9893ce6e1f6STetsuo Handa 
9903ce6e1f6STetsuo Handa 	if (!file)
9913ce6e1f6STetsuo Handa 		return -EBADF;
9923ce6e1f6STetsuo Handa 	is_loop = is_loop_device(file);
9931da177e4SLinus Torvalds 
9941da177e4SLinus Torvalds 	/* This is safe, since we have a reference from open(). */
9951da177e4SLinus Torvalds 	__module_get(THIS_MODULE);
9961da177e4SLinus Torvalds 
99733ec3e53SJan Kara 	/*
99833ec3e53SJan Kara 	 * If we don't hold exclusive handle for the device, upgrade to it
99933ec3e53SJan Kara 	 * here to avoid changing device under exclusive owner.
100033ec3e53SJan Kara 	 */
100133ec3e53SJan Kara 	if (!(mode & FMODE_EXCL)) {
100237c3fc9aSChristoph Hellwig 		error = bd_prepare_to_claim(bdev, loop_configure);
1003ecbe6bc0SChristoph Hellwig 		if (error)
1004757ecf40SJan Kara 			goto out_putf;
100533ec3e53SJan Kara 	}
100633ec3e53SJan Kara 
10073ce6e1f6STetsuo Handa 	error = loop_global_lock_killable(lo, is_loop);
100833ec3e53SJan Kara 	if (error)
100933ec3e53SJan Kara 		goto out_bdev;
1010757ecf40SJan Kara 
10111da177e4SLinus Torvalds 	error = -EBUSY;
10121da177e4SLinus Torvalds 	if (lo->lo_state != Lo_unbound)
1013757ecf40SJan Kara 		goto out_unlock;
10141da177e4SLinus Torvalds 
1015d2ac838eSTheodore Ts'o 	error = loop_validate_file(file, bdev);
1016d2ac838eSTheodore Ts'o 	if (error)
1017757ecf40SJan Kara 		goto out_unlock;
10181da177e4SLinus Torvalds 
10191da177e4SLinus Torvalds 	mapping = file->f_mapping;
10201da177e4SLinus Torvalds 	inode = mapping->host;
10211da177e4SLinus Torvalds 
10223448914eSMartijn Coenen 	if ((config->info.lo_flags & ~LOOP_CONFIGURE_SETTABLE_FLAGS) != 0) {
10233448914eSMartijn Coenen 		error = -EINVAL;
10243448914eSMartijn Coenen 		goto out_unlock;
10253448914eSMartijn Coenen 	}
10263448914eSMartijn Coenen 
10273448914eSMartijn Coenen 	if (config->block_size) {
1028af3c570fSXie Yongji 		error = blk_validate_block_size(config->block_size);
10293448914eSMartijn Coenen 		if (error)
10303448914eSMartijn Coenen 			goto out_unlock;
10313448914eSMartijn Coenen 	}
10323448914eSMartijn Coenen 
10333448914eSMartijn Coenen 	error = loop_set_status_from_info(lo, &config->info);
10343448914eSMartijn Coenen 	if (error)
10353448914eSMartijn Coenen 		goto out_unlock;
10363448914eSMartijn Coenen 
1037456be148SChristoph Hellwig 	if (!(file->f_mode & FMODE_WRITE) || !(mode & FMODE_WRITE) ||
1038283e7e5dSAl Viro 	    !file->f_op->write_iter)
10393448914eSMartijn Coenen 		lo->lo_flags |= LO_FLAGS_READ_ONLY;
1040083a6a50SMartijn Coenen 
104187579e9bSDan Schatzberg 	lo->workqueue = alloc_workqueue("loop%d",
104287579e9bSDan Schatzberg 					WQ_UNBOUND | WQ_FREEZABLE,
104387579e9bSDan Schatzberg 					0,
104487579e9bSDan Schatzberg 					lo->lo_number);
104587579e9bSDan Schatzberg 	if (!lo->workqueue) {
104687579e9bSDan Schatzberg 		error = -ENOMEM;
1047757ecf40SJan Kara 		goto out_unlock;
104887579e9bSDan Schatzberg 	}
10491da177e4SLinus Torvalds 
10509f65c489SMatteo Croce 	disk_force_media_change(lo->lo_disk, DISK_EVENT_MEDIA_CHANGE);
10517a2f0ce1SChristoph Hellwig 	set_disk_ro(lo->lo_disk, (lo->lo_flags & LO_FLAGS_READ_ONLY) != 0);
10521da177e4SLinus Torvalds 
105387579e9bSDan Schatzberg 	INIT_WORK(&lo->rootcg_work, loop_rootcg_workfn);
105487579e9bSDan Schatzberg 	INIT_LIST_HEAD(&lo->rootcg_cmd_list);
105587579e9bSDan Schatzberg 	INIT_LIST_HEAD(&lo->idle_worker_list);
105687579e9bSDan Schatzberg 	lo->worker_tree = RB_ROOT;
1057*2cf429b5SChristoph Hellwig 	timer_setup(&lo->timer, loop_free_idle_workers_timer,
105887579e9bSDan Schatzberg 		TIMER_DEFERRABLE);
10593448914eSMartijn Coenen 	lo->use_dio = lo->lo_flags & LO_FLAGS_DIRECT_IO;
10601da177e4SLinus Torvalds 	lo->lo_device = bdev;
10611da177e4SLinus Torvalds 	lo->lo_backing_file = file;
10621da177e4SLinus Torvalds 	lo->old_gfp_mask = mapping_gfp_mask(mapping);
10631da177e4SLinus Torvalds 	mapping_set_gfp_mask(mapping, lo->old_gfp_mask & ~(__GFP_IO|__GFP_FS));
10641da177e4SLinus Torvalds 
10653448914eSMartijn Coenen 	if (!(lo->lo_flags & LO_FLAGS_READ_ONLY) && file->f_op->fsync)
106621d0727fSJens Axboe 		blk_queue_write_cache(lo->lo_queue, true, false);
106768db1961SNikanth Karthikesan 
10683448914eSMartijn Coenen 	if (config->block_size)
10693448914eSMartijn Coenen 		bsize = config->block_size;
107096ed320dSLinus Torvalds 	else if ((lo->lo_backing_file->f_flags & O_DIRECT) && inode->i_sb->s_bdev)
107185560117SMartijn Coenen 		/* In case of direct I/O, match underlying block size */
10723448914eSMartijn Coenen 		bsize = bdev_logical_block_size(inode->i_sb->s_bdev);
10733448914eSMartijn Coenen 	else
10743448914eSMartijn Coenen 		bsize = 512;
107585560117SMartijn Coenen 
107685560117SMartijn Coenen 	blk_queue_logical_block_size(lo->lo_queue, bsize);
107785560117SMartijn Coenen 	blk_queue_physical_block_size(lo->lo_queue, bsize);
107885560117SMartijn Coenen 	blk_queue_io_min(lo->lo_queue, bsize);
107985560117SMartijn Coenen 
10802b9ac22bSKristian Klausen 	loop_config_discard(lo);
108156a85fd8SHolger Hoffstätte 	loop_update_rotational(lo);
10822e5ab5f3SMing Lei 	loop_update_dio(lo);
1083ee862730SMilan Broz 	loop_sysfs_init(lo);
108479e5dc59SMartijn Coenen 
108579e5dc59SMartijn Coenen 	size = get_loop_size(lo, file);
10865795b6f5SMartijn Coenen 	loop_set_size(lo, size);
10871da177e4SLinus Torvalds 
10883ce6e1f6STetsuo Handa 	/* Order wrt reading lo_state in loop_validate_file(). */
10893ce6e1f6STetsuo Handa 	wmb();
10903ce6e1f6STetsuo Handa 
10916c997918SSerge E. Hallyn 	lo->lo_state = Lo_bound;
1092e03c8dd1SKay Sievers 	if (part_shift)
1093e03c8dd1SKay Sievers 		lo->lo_flags |= LO_FLAGS_PARTSCAN;
109485b0a54aSJan Kara 	partscan = lo->lo_flags & LO_FLAGS_PARTSCAN;
1095fe6a8fc5SLennart Poettering 	if (partscan)
109646e7eac6SChristoph Hellwig 		lo->lo_disk->flags &= ~GENHD_FL_NO_PART;
1097c1681bf8SAnatol Pomozov 
10983ce6e1f6STetsuo Handa 	loop_global_unlock(lo, is_loop);
109985b0a54aSJan Kara 	if (partscan)
11000384264eSChristoph Hellwig 		loop_reread_partitions(lo);
110137c3fc9aSChristoph Hellwig 	if (!(mode & FMODE_EXCL))
110237c3fc9aSChristoph Hellwig 		bd_abort_claiming(bdev, loop_configure);
11031da177e4SLinus Torvalds 	return 0;
11041da177e4SLinus Torvalds 
1105757ecf40SJan Kara out_unlock:
11063ce6e1f6STetsuo Handa 	loop_global_unlock(lo, is_loop);
110733ec3e53SJan Kara out_bdev:
110837c3fc9aSChristoph Hellwig 	if (!(mode & FMODE_EXCL))
110937c3fc9aSChristoph Hellwig 		bd_abort_claiming(bdev, loop_configure);
11101da177e4SLinus Torvalds out_putf:
11111da177e4SLinus Torvalds 	fput(file);
11121da177e4SLinus Torvalds 	/* This is safe: open() is still holding a reference. */
11131da177e4SLinus Torvalds 	module_put(THIS_MODULE);
11141da177e4SLinus Torvalds 	return error;
11151da177e4SLinus Torvalds }
11161da177e4SLinus Torvalds 
1117bf23747eSTetsuo Handa static void __loop_clr_fd(struct loop_device *lo, bool release)
11181da177e4SLinus Torvalds {
11196050fa4cSTetsuo Handa 	struct file *filp;
1120b4e3ca1aSAl Viro 	gfp_t gfp = lo->old_gfp_mask;
11211da177e4SLinus Torvalds 
11223ce6e1f6STetsuo Handa 	/*
11233ce6e1f6STetsuo Handa 	 * Flush loop_configure() and loop_change_fd(). It is acceptable for
11243ce6e1f6STetsuo Handa 	 * loop_validate_file() to succeed, for actual clear operation has not
11253ce6e1f6STetsuo Handa 	 * started yet.
11263ce6e1f6STetsuo Handa 	 */
11273ce6e1f6STetsuo Handa 	mutex_lock(&loop_validate_mutex);
11283ce6e1f6STetsuo Handa 	mutex_unlock(&loop_validate_mutex);
11293ce6e1f6STetsuo Handa 	/*
11303ce6e1f6STetsuo Handa 	 * loop_validate_file() now fails because l->lo_state != Lo_bound
11313ce6e1f6STetsuo Handa 	 * became visible.
11323ce6e1f6STetsuo Handa 	 */
11333ce6e1f6STetsuo Handa 
11346050fa4cSTetsuo Handa 	/*
11356050fa4cSTetsuo Handa 	 * Since this function is called upon "ioctl(LOOP_CLR_FD)" xor "close()
11366050fa4cSTetsuo Handa 	 * after ioctl(LOOP_CLR_FD)", it is a sign of something going wrong if
11376050fa4cSTetsuo Handa 	 * lo->lo_state has changed while waiting for lo->lo_mutex.
11386050fa4cSTetsuo Handa 	 */
11396cc8e743SPavel Tatashin 	mutex_lock(&lo->lo_mutex);
11406050fa4cSTetsuo Handa 	BUG_ON(lo->lo_state != Lo_rundown);
11416050fa4cSTetsuo Handa 	mutex_unlock(&lo->lo_mutex);
11421da177e4SLinus Torvalds 
11434ceddce5SMauricio Faria de Oliveira 	if (test_bit(QUEUE_FLAG_WC, &lo->lo_queue->queue_flags))
11444ceddce5SMauricio Faria de Oliveira 		blk_queue_write_cache(lo->lo_queue, false, false);
11454ceddce5SMauricio Faria de Oliveira 
1146f8933667SMing Lei 	/* freeze request queue during the transition */
1147f8933667SMing Lei 	blk_mq_freeze_queue(lo->lo_queue);
1148f8933667SMing Lei 
114987579e9bSDan Schatzberg 	destroy_workqueue(lo->workqueue);
1150*2cf429b5SChristoph Hellwig 	loop_free_idle_workers(lo, true);
115187579e9bSDan Schatzberg 	del_timer_sync(&lo->timer);
115287579e9bSDan Schatzberg 
11531da177e4SLinus Torvalds 	spin_lock_irq(&lo->lo_lock);
11546050fa4cSTetsuo Handa 	filp = lo->lo_backing_file;
11551da177e4SLinus Torvalds 	lo->lo_backing_file = NULL;
115605eb0f25SKay Sievers 	spin_unlock_irq(&lo->lo_lock);
11571da177e4SLinus Torvalds 
11581da177e4SLinus Torvalds 	lo->lo_device = NULL;
11591da177e4SLinus Torvalds 	lo->lo_offset = 0;
11601da177e4SLinus Torvalds 	lo->lo_sizelimit = 0;
11611da177e4SLinus Torvalds 	memset(lo->lo_file_name, 0, LO_NAME_SIZE);
116289e4fdecSOmar Sandoval 	blk_queue_logical_block_size(lo->lo_queue, 512);
1163bf093753SOmar Sandoval 	blk_queue_physical_block_size(lo->lo_queue, 512);
1164bf093753SOmar Sandoval 	blk_queue_io_min(lo->lo_queue, 512);
1165e515be8fSXie Yongji 	invalidate_disk(lo->lo_disk);
116651a0bb0cSMilan Broz 	loop_sysfs_exit(lo);
1167c3473c63SDavid Zeuthen 	/* let user-space know about this change */
116819f553dbSXie Yongji 	kobject_uevent(&disk_to_dev(lo->lo_disk)->kobj, KOBJ_CHANGE);
11691da177e4SLinus Torvalds 	mapping_set_gfp_mask(filp->f_mapping, gfp);
1170bf23747eSTetsuo Handa 	/* This is safe: open() is still holding a reference. */
1171bf23747eSTetsuo Handa 	module_put(THIS_MODULE);
1172f8933667SMing Lei 	blk_mq_unfreeze_queue(lo->lo_queue);
1173f8933667SMing Lei 
11749f65c489SMatteo Croce 	disk_force_media_change(lo->lo_disk, DISK_EVENT_MEDIA_CHANGE);
11756050fa4cSTetsuo Handa 
11766050fa4cSTetsuo Handa 	if (lo->lo_flags & LO_FLAGS_PARTSCAN) {
11776050fa4cSTetsuo Handa 		int err;
11786050fa4cSTetsuo Handa 
1179bf23747eSTetsuo Handa 		/*
1180bf23747eSTetsuo Handa 		 * open_mutex has been held already in release path, so don't
1181bf23747eSTetsuo Handa 		 * acquire it if this function is called in such case.
1182bf23747eSTetsuo Handa 		 *
1183bf23747eSTetsuo Handa 		 * If the reread partition isn't from release path, lo_refcnt
1184bf23747eSTetsuo Handa 		 * must be at least one and it can only become zero when the
1185bf23747eSTetsuo Handa 		 * current holder is released.
1186bf23747eSTetsuo Handa 		 */
1187bf23747eSTetsuo Handa 		if (!release)
11880384264eSChristoph Hellwig 			mutex_lock(&lo->lo_disk->open_mutex);
11890384264eSChristoph Hellwig 		err = bdev_disk_changed(lo->lo_disk, false);
1190bf23747eSTetsuo Handa 		if (!release)
11910384264eSChristoph Hellwig 			mutex_unlock(&lo->lo_disk->open_mutex);
119240853d6fSDongli Zhang 		if (err)
1193d57f3374SJan Kara 			pr_warn("%s: partition scan of loop%d failed (rc=%d)\n",
11946050fa4cSTetsuo Handa 				__func__, lo->lo_number, err);
1195d57f3374SJan Kara 		/* Device is gone, no point in returning error */
1196d57f3374SJan Kara 	}
1197758a58d0SDongli Zhang 
1198bf23747eSTetsuo Handa 	/*
1199bf23747eSTetsuo Handa 	 * lo->lo_state is set to Lo_unbound here after above partscan has
1200bf23747eSTetsuo Handa 	 * finished. There cannot be anybody else entering __loop_clr_fd() as
1201bf23747eSTetsuo Handa 	 * Lo_rundown state protects us from all the other places trying to
1202bf23747eSTetsuo Handa 	 * change the 'lo' device.
1203bf23747eSTetsuo Handa 	 */
1204758a58d0SDongli Zhang 	lo->lo_flags = 0;
1205758a58d0SDongli Zhang 	if (!part_shift)
120646e7eac6SChristoph Hellwig 		lo->lo_disk->flags |= GENHD_FL_NO_PART;
12076050fa4cSTetsuo Handa 	mutex_lock(&lo->lo_mutex);
1208758a58d0SDongli Zhang 	lo->lo_state = Lo_unbound;
12096cc8e743SPavel Tatashin 	mutex_unlock(&lo->lo_mutex);
1210758a58d0SDongli Zhang 
1211bf23747eSTetsuo Handa 	/*
1212bf23747eSTetsuo Handa 	 * Need not hold lo_mutex to fput backing file. Calling fput holding
1213bf23747eSTetsuo Handa 	 * lo_mutex triggers a circular lock dependency possibility warning as
1214bf23747eSTetsuo Handa 	 * fput can take open_mutex which is usually taken before lo_mutex.
1215bf23747eSTetsuo Handa 	 */
1216bf23747eSTetsuo Handa 	fput(filp);
12171da177e4SLinus Torvalds }
12181da177e4SLinus Torvalds 
1219a2505b79SJan Kara static int loop_clr_fd(struct loop_device *lo)
1220a2505b79SJan Kara {
12217ccd0791SJan Kara 	int err;
12227ccd0791SJan Kara 
12236cc8e743SPavel Tatashin 	err = mutex_lock_killable(&lo->lo_mutex);
12247ccd0791SJan Kara 	if (err)
12257ccd0791SJan Kara 		return err;
12267ccd0791SJan Kara 	if (lo->lo_state != Lo_bound) {
12276cc8e743SPavel Tatashin 		mutex_unlock(&lo->lo_mutex);
1228a2505b79SJan Kara 		return -ENXIO;
12297ccd0791SJan Kara 	}
1230a2505b79SJan Kara 	/*
1231a2505b79SJan Kara 	 * If we've explicitly asked to tear down the loop device,
1232a2505b79SJan Kara 	 * and it has an elevated reference count, set it for auto-teardown when
1233a2505b79SJan Kara 	 * the last reference goes away. This stops $!~#$@ udev from
1234a2505b79SJan Kara 	 * preventing teardown because it decided that it needs to run blkid on
1235a2505b79SJan Kara 	 * the loopback device whenever they appear. xfstests is notorious for
1236a2505b79SJan Kara 	 * failing tests because blkid via udev races with a losetup
1237a2505b79SJan Kara 	 * <dev>/do something like mkfs/losetup -d <dev> causing the losetup -d
1238a2505b79SJan Kara 	 * command to fail with EBUSY.
1239a2505b79SJan Kara 	 */
1240a2505b79SJan Kara 	if (atomic_read(&lo->lo_refcnt) > 1) {
1241a2505b79SJan Kara 		lo->lo_flags |= LO_FLAGS_AUTOCLEAR;
12426cc8e743SPavel Tatashin 		mutex_unlock(&lo->lo_mutex);
1243a2505b79SJan Kara 		return 0;
1244a2505b79SJan Kara 	}
1245a2505b79SJan Kara 	lo->lo_state = Lo_rundown;
12466cc8e743SPavel Tatashin 	mutex_unlock(&lo->lo_mutex);
1247a2505b79SJan Kara 
1248bf23747eSTetsuo Handa 	__loop_clr_fd(lo, false);
12496050fa4cSTetsuo Handa 	return 0;
1250a2505b79SJan Kara }
1251a2505b79SJan Kara 
12521da177e4SLinus Torvalds static int
12531da177e4SLinus Torvalds loop_set_status(struct loop_device *lo, const struct loop_info64 *info)
12541da177e4SLinus Torvalds {
12551da177e4SLinus Torvalds 	int err;
1256faf1d254SMartijn Coenen 	int prev_lo_flags;
125785b0a54aSJan Kara 	bool partscan = false;
12580c3796c2SMartijn Coenen 	bool size_changed = false;
12591da177e4SLinus Torvalds 
12606cc8e743SPavel Tatashin 	err = mutex_lock_killable(&lo->lo_mutex);
1261550df5fdSJan Kara 	if (err)
1262550df5fdSJan Kara 		return err;
1263550df5fdSJan Kara 	if (lo->lo_state != Lo_bound) {
1264550df5fdSJan Kara 		err = -ENXIO;
1265550df5fdSJan Kara 		goto out_unlock;
1266550df5fdSJan Kara 	}
12671da177e4SLinus Torvalds 
12685db470e2SJaegeuk Kim 	if (lo->lo_offset != info->lo_offset ||
12695db470e2SJaegeuk Kim 	    lo->lo_sizelimit != info->lo_sizelimit) {
12700c3796c2SMartijn Coenen 		size_changed = true;
12715db470e2SJaegeuk Kim 		sync_blockdev(lo->lo_device);
1272f4bd34b1SZheng Bin 		invalidate_bdev(lo->lo_device);
12735db470e2SJaegeuk Kim 	}
12745db470e2SJaegeuk Kim 
1275ecdd0959SMing Lei 	/* I/O need to be drained during transfer transition */
1276ecdd0959SMing Lei 	blk_mq_freeze_queue(lo->lo_queue);
1277ecdd0959SMing Lei 
12780c3796c2SMartijn Coenen 	if (size_changed && lo->lo_device->bd_inode->i_mapping->nrpages) {
1279f4bd34b1SZheng Bin 		/* If any pages were dirtied after invalidate_bdev(), try again */
12805db470e2SJaegeuk Kim 		err = -EAGAIN;
1281d9a74051SColin Ian King 		pr_warn("%s: loop%d (%s) still has dirty pages (nrpages=%lu)\n",
12825db470e2SJaegeuk Kim 			__func__, lo->lo_number, lo->lo_file_name,
12835db470e2SJaegeuk Kim 			lo->lo_device->bd_inode->i_mapping->nrpages);
12845db470e2SJaegeuk Kim 		goto out_unfreeze;
12855db470e2SJaegeuk Kim 	}
12860c3796c2SMartijn Coenen 
1287faf1d254SMartijn Coenen 	prev_lo_flags = lo->lo_flags;
1288faf1d254SMartijn Coenen 
12890c3796c2SMartijn Coenen 	err = loop_set_status_from_info(lo, info);
12900c3796c2SMartijn Coenen 	if (err)
1291550df5fdSJan Kara 		goto out_unfreeze;
12920c3796c2SMartijn Coenen 
1293faf1d254SMartijn Coenen 	/* Mask out flags that can't be set using LOOP_SET_STATUS. */
12946ac92fb5SMartijn Coenen 	lo->lo_flags &= LOOP_SET_STATUS_SETTABLE_FLAGS;
1295faf1d254SMartijn Coenen 	/* For those flags, use the previous values instead */
1296faf1d254SMartijn Coenen 	lo->lo_flags |= prev_lo_flags & ~LOOP_SET_STATUS_SETTABLE_FLAGS;
1297faf1d254SMartijn Coenen 	/* For flags that can't be cleared, use previous values too */
1298faf1d254SMartijn Coenen 	lo->lo_flags |= prev_lo_flags & ~LOOP_SET_STATUS_CLEARABLE_FLAGS;
1299faf1d254SMartijn Coenen 
1300b0bd158dSMartijn Coenen 	if (size_changed) {
1301b0bd158dSMartijn Coenen 		loff_t new_size = get_size(lo->lo_offset, lo->lo_sizelimit,
1302b0bd158dSMartijn Coenen 					   lo->lo_backing_file);
1303b0bd158dSMartijn Coenen 		loop_set_size(lo, new_size);
1304b040ad9cSArnd Bergmann 	}
1305541c742aSGuo Chao 
1306dfaa2ef6SLukas Czerner 	loop_config_discard(lo);
13071da177e4SLinus Torvalds 
13082e5ab5f3SMing Lei 	/* update dio if lo_offset or transfer is changed */
13092e5ab5f3SMing Lei 	__loop_update_dio(lo, lo->use_dio);
13102e5ab5f3SMing Lei 
1311550df5fdSJan Kara out_unfreeze:
1312ecdd0959SMing Lei 	blk_mq_unfreeze_queue(lo->lo_queue);
1313e02898b4SOmar Sandoval 
1314faf1d254SMartijn Coenen 	if (!err && (lo->lo_flags & LO_FLAGS_PARTSCAN) &&
1315faf1d254SMartijn Coenen 	     !(prev_lo_flags & LO_FLAGS_PARTSCAN)) {
131646e7eac6SChristoph Hellwig 		lo->lo_disk->flags &= ~GENHD_FL_NO_PART;
131785b0a54aSJan Kara 		partscan = true;
1318e02898b4SOmar Sandoval 	}
1319550df5fdSJan Kara out_unlock:
13206cc8e743SPavel Tatashin 	mutex_unlock(&lo->lo_mutex);
132185b0a54aSJan Kara 	if (partscan)
13220384264eSChristoph Hellwig 		loop_reread_partitions(lo);
1323e02898b4SOmar Sandoval 
1324ecdd0959SMing Lei 	return err;
13251da177e4SLinus Torvalds }
13261da177e4SLinus Torvalds 
13271da177e4SLinus Torvalds static int
13281da177e4SLinus Torvalds loop_get_status(struct loop_device *lo, struct loop_info64 *info)
13291da177e4SLinus Torvalds {
1330b1ab5fa3STetsuo Handa 	struct path path;
13311da177e4SLinus Torvalds 	struct kstat stat;
13322d1d4c1eSOmar Sandoval 	int ret;
13331da177e4SLinus Torvalds 
13346cc8e743SPavel Tatashin 	ret = mutex_lock_killable(&lo->lo_mutex);
13354a5ce9baSJan Kara 	if (ret)
13364a5ce9baSJan Kara 		return ret;
13372d1d4c1eSOmar Sandoval 	if (lo->lo_state != Lo_bound) {
13386cc8e743SPavel Tatashin 		mutex_unlock(&lo->lo_mutex);
13391da177e4SLinus Torvalds 		return -ENXIO;
13402d1d4c1eSOmar Sandoval 	}
13412d1d4c1eSOmar Sandoval 
13421da177e4SLinus Torvalds 	memset(info, 0, sizeof(*info));
13431da177e4SLinus Torvalds 	info->lo_number = lo->lo_number;
13441da177e4SLinus Torvalds 	info->lo_offset = lo->lo_offset;
13451da177e4SLinus Torvalds 	info->lo_sizelimit = lo->lo_sizelimit;
13461da177e4SLinus Torvalds 	info->lo_flags = lo->lo_flags;
13471da177e4SLinus Torvalds 	memcpy(info->lo_file_name, lo->lo_file_name, LO_NAME_SIZE);
13482d1d4c1eSOmar Sandoval 
13496cc8e743SPavel Tatashin 	/* Drop lo_mutex while we call into the filesystem. */
1350b1ab5fa3STetsuo Handa 	path = lo->lo_backing_file->f_path;
1351b1ab5fa3STetsuo Handa 	path_get(&path);
13526cc8e743SPavel Tatashin 	mutex_unlock(&lo->lo_mutex);
1353b1ab5fa3STetsuo Handa 	ret = vfs_getattr(&path, &stat, STATX_INO, AT_STATX_SYNC_AS_STAT);
13542d1d4c1eSOmar Sandoval 	if (!ret) {
13552d1d4c1eSOmar Sandoval 		info->lo_device = huge_encode_dev(stat.dev);
13562d1d4c1eSOmar Sandoval 		info->lo_inode = stat.ino;
13572d1d4c1eSOmar Sandoval 		info->lo_rdevice = huge_encode_dev(stat.rdev);
13582d1d4c1eSOmar Sandoval 	}
1359b1ab5fa3STetsuo Handa 	path_put(&path);
13602d1d4c1eSOmar Sandoval 	return ret;
13611da177e4SLinus Torvalds }
13621da177e4SLinus Torvalds 
13631da177e4SLinus Torvalds static void
13641da177e4SLinus Torvalds loop_info64_from_old(const struct loop_info *info, struct loop_info64 *info64)
13651da177e4SLinus Torvalds {
13661da177e4SLinus Torvalds 	memset(info64, 0, sizeof(*info64));
13671da177e4SLinus Torvalds 	info64->lo_number = info->lo_number;
13681da177e4SLinus Torvalds 	info64->lo_device = info->lo_device;
13691da177e4SLinus Torvalds 	info64->lo_inode = info->lo_inode;
13701da177e4SLinus Torvalds 	info64->lo_rdevice = info->lo_rdevice;
13711da177e4SLinus Torvalds 	info64->lo_offset = info->lo_offset;
13721da177e4SLinus Torvalds 	info64->lo_sizelimit = 0;
13731da177e4SLinus Torvalds 	info64->lo_flags = info->lo_flags;
13741da177e4SLinus Torvalds 	memcpy(info64->lo_file_name, info->lo_name, LO_NAME_SIZE);
13751da177e4SLinus Torvalds }
13761da177e4SLinus Torvalds 
13771da177e4SLinus Torvalds static int
13781da177e4SLinus Torvalds loop_info64_to_old(const struct loop_info64 *info64, struct loop_info *info)
13791da177e4SLinus Torvalds {
13801da177e4SLinus Torvalds 	memset(info, 0, sizeof(*info));
13811da177e4SLinus Torvalds 	info->lo_number = info64->lo_number;
13821da177e4SLinus Torvalds 	info->lo_device = info64->lo_device;
13831da177e4SLinus Torvalds 	info->lo_inode = info64->lo_inode;
13841da177e4SLinus Torvalds 	info->lo_rdevice = info64->lo_rdevice;
13851da177e4SLinus Torvalds 	info->lo_offset = info64->lo_offset;
13861da177e4SLinus Torvalds 	info->lo_flags = info64->lo_flags;
13871da177e4SLinus Torvalds 	memcpy(info->lo_name, info64->lo_file_name, LO_NAME_SIZE);
13881da177e4SLinus Torvalds 
13891da177e4SLinus Torvalds 	/* error in case values were truncated */
13901da177e4SLinus Torvalds 	if (info->lo_device != info64->lo_device ||
13911da177e4SLinus Torvalds 	    info->lo_rdevice != info64->lo_rdevice ||
13921da177e4SLinus Torvalds 	    info->lo_inode != info64->lo_inode ||
13931da177e4SLinus Torvalds 	    info->lo_offset != info64->lo_offset)
13941da177e4SLinus Torvalds 		return -EOVERFLOW;
13951da177e4SLinus Torvalds 
13961da177e4SLinus Torvalds 	return 0;
13971da177e4SLinus Torvalds }
13981da177e4SLinus Torvalds 
13991da177e4SLinus Torvalds static int
14001da177e4SLinus Torvalds loop_set_status_old(struct loop_device *lo, const struct loop_info __user *arg)
14011da177e4SLinus Torvalds {
14021da177e4SLinus Torvalds 	struct loop_info info;
14031da177e4SLinus Torvalds 	struct loop_info64 info64;
14041da177e4SLinus Torvalds 
14051da177e4SLinus Torvalds 	if (copy_from_user(&info, arg, sizeof (struct loop_info)))
14061da177e4SLinus Torvalds 		return -EFAULT;
14071da177e4SLinus Torvalds 	loop_info64_from_old(&info, &info64);
14081da177e4SLinus Torvalds 	return loop_set_status(lo, &info64);
14091da177e4SLinus Torvalds }
14101da177e4SLinus Torvalds 
14111da177e4SLinus Torvalds static int
14121da177e4SLinus Torvalds loop_set_status64(struct loop_device *lo, const struct loop_info64 __user *arg)
14131da177e4SLinus Torvalds {
14141da177e4SLinus Torvalds 	struct loop_info64 info64;
14151da177e4SLinus Torvalds 
14161da177e4SLinus Torvalds 	if (copy_from_user(&info64, arg, sizeof (struct loop_info64)))
14171da177e4SLinus Torvalds 		return -EFAULT;
14181da177e4SLinus Torvalds 	return loop_set_status(lo, &info64);
14191da177e4SLinus Torvalds }
14201da177e4SLinus Torvalds 
14211da177e4SLinus Torvalds static int
14221da177e4SLinus Torvalds loop_get_status_old(struct loop_device *lo, struct loop_info __user *arg) {
14231da177e4SLinus Torvalds 	struct loop_info info;
14241da177e4SLinus Torvalds 	struct loop_info64 info64;
1425bdac616dSOmar Sandoval 	int err;
14261da177e4SLinus Torvalds 
14274a5ce9baSJan Kara 	if (!arg)
1428bdac616dSOmar Sandoval 		return -EINVAL;
14291da177e4SLinus Torvalds 	err = loop_get_status(lo, &info64);
14301da177e4SLinus Torvalds 	if (!err)
14311da177e4SLinus Torvalds 		err = loop_info64_to_old(&info64, &info);
14321da177e4SLinus Torvalds 	if (!err && copy_to_user(arg, &info, sizeof(info)))
14331da177e4SLinus Torvalds 		err = -EFAULT;
14341da177e4SLinus Torvalds 
14351da177e4SLinus Torvalds 	return err;
14361da177e4SLinus Torvalds }
14371da177e4SLinus Torvalds 
14381da177e4SLinus Torvalds static int
14391da177e4SLinus Torvalds loop_get_status64(struct loop_device *lo, struct loop_info64 __user *arg) {
14401da177e4SLinus Torvalds 	struct loop_info64 info64;
1441bdac616dSOmar Sandoval 	int err;
14421da177e4SLinus Torvalds 
14434a5ce9baSJan Kara 	if (!arg)
1444bdac616dSOmar Sandoval 		return -EINVAL;
14451da177e4SLinus Torvalds 	err = loop_get_status(lo, &info64);
14461da177e4SLinus Torvalds 	if (!err && copy_to_user(arg, &info64, sizeof(info64)))
14471da177e4SLinus Torvalds 		err = -EFAULT;
14481da177e4SLinus Torvalds 
14491da177e4SLinus Torvalds 	return err;
14501da177e4SLinus Torvalds }
14511da177e4SLinus Torvalds 
145251001b7dSHannes Reinecke static int loop_set_capacity(struct loop_device *lo)
145353d66608SJ. R. Okajima {
14540a6ed1b5SMartijn Coenen 	loff_t size;
14550a6ed1b5SMartijn Coenen 
145653d66608SJ. R. Okajima 	if (unlikely(lo->lo_state != Lo_bound))
14577b0576a3SGuo Chao 		return -ENXIO;
145853d66608SJ. R. Okajima 
14590a6ed1b5SMartijn Coenen 	size = get_loop_size(lo, lo->lo_backing_file);
14600a6ed1b5SMartijn Coenen 	loop_set_size(lo, size);
1461083a6a50SMartijn Coenen 
1462083a6a50SMartijn Coenen 	return 0;
146353d66608SJ. R. Okajima }
146453d66608SJ. R. Okajima 
1465ab1cb278SMing Lei static int loop_set_dio(struct loop_device *lo, unsigned long arg)
1466ab1cb278SMing Lei {
1467ab1cb278SMing Lei 	int error = -ENXIO;
1468ab1cb278SMing Lei 	if (lo->lo_state != Lo_bound)
1469ab1cb278SMing Lei 		goto out;
1470ab1cb278SMing Lei 
1471ab1cb278SMing Lei 	__loop_update_dio(lo, !!arg);
1472ab1cb278SMing Lei 	if (lo->use_dio == !!arg)
1473ab1cb278SMing Lei 		return 0;
1474ab1cb278SMing Lei 	error = -EINVAL;
1475ab1cb278SMing Lei  out:
1476ab1cb278SMing Lei 	return error;
1477ab1cb278SMing Lei }
1478ab1cb278SMing Lei 
147989e4fdecSOmar Sandoval static int loop_set_block_size(struct loop_device *lo, unsigned long arg)
148089e4fdecSOmar Sandoval {
14815db470e2SJaegeuk Kim 	int err = 0;
14825db470e2SJaegeuk Kim 
148389e4fdecSOmar Sandoval 	if (lo->lo_state != Lo_bound)
148489e4fdecSOmar Sandoval 		return -ENXIO;
148589e4fdecSOmar Sandoval 
1486af3c570fSXie Yongji 	err = blk_validate_block_size(arg);
14873448914eSMartijn Coenen 	if (err)
14883448914eSMartijn Coenen 		return err;
148989e4fdecSOmar Sandoval 
14907e81f99aSMartijn Coenen 	if (lo->lo_queue->limits.logical_block_size == arg)
14917e81f99aSMartijn Coenen 		return 0;
14927e81f99aSMartijn Coenen 
14935db470e2SJaegeuk Kim 	sync_blockdev(lo->lo_device);
1494f4bd34b1SZheng Bin 	invalidate_bdev(lo->lo_device);
14955db470e2SJaegeuk Kim 
149689e4fdecSOmar Sandoval 	blk_mq_freeze_queue(lo->lo_queue);
149789e4fdecSOmar Sandoval 
1498f4bd34b1SZheng Bin 	/* invalidate_bdev should have truncated all the pages */
14997e81f99aSMartijn Coenen 	if (lo->lo_device->bd_inode->i_mapping->nrpages) {
15005db470e2SJaegeuk Kim 		err = -EAGAIN;
1501d9a74051SColin Ian King 		pr_warn("%s: loop%d (%s) still has dirty pages (nrpages=%lu)\n",
15025db470e2SJaegeuk Kim 			__func__, lo->lo_number, lo->lo_file_name,
15035db470e2SJaegeuk Kim 			lo->lo_device->bd_inode->i_mapping->nrpages);
15045db470e2SJaegeuk Kim 		goto out_unfreeze;
15055db470e2SJaegeuk Kim 	}
15065db470e2SJaegeuk Kim 
150789e4fdecSOmar Sandoval 	blk_queue_logical_block_size(lo->lo_queue, arg);
1508bf093753SOmar Sandoval 	blk_queue_physical_block_size(lo->lo_queue, arg);
1509bf093753SOmar Sandoval 	blk_queue_io_min(lo->lo_queue, arg);
151089e4fdecSOmar Sandoval 	loop_update_dio(lo);
15115db470e2SJaegeuk Kim out_unfreeze:
151289e4fdecSOmar Sandoval 	blk_mq_unfreeze_queue(lo->lo_queue);
151389e4fdecSOmar Sandoval 
15145db470e2SJaegeuk Kim 	return err;
151589e4fdecSOmar Sandoval }
151689e4fdecSOmar Sandoval 
1517a1316544SJan Kara static int lo_simple_ioctl(struct loop_device *lo, unsigned int cmd,
1518a1316544SJan Kara 			   unsigned long arg)
15191da177e4SLinus Torvalds {
15201da177e4SLinus Torvalds 	int err;
15211da177e4SLinus Torvalds 
15226cc8e743SPavel Tatashin 	err = mutex_lock_killable(&lo->lo_mutex);
15233148ffbdSOmar Sandoval 	if (err)
1524a1316544SJan Kara 		return err;
15251da177e4SLinus Torvalds 	switch (cmd) {
152653d66608SJ. R. Okajima 	case LOOP_SET_CAPACITY:
152751001b7dSHannes Reinecke 		err = loop_set_capacity(lo);
152853d66608SJ. R. Okajima 		break;
1529ab1cb278SMing Lei 	case LOOP_SET_DIRECT_IO:
1530ab1cb278SMing Lei 		err = loop_set_dio(lo, arg);
1531ab1cb278SMing Lei 		break;
153289e4fdecSOmar Sandoval 	case LOOP_SET_BLOCK_SIZE:
153389e4fdecSOmar Sandoval 		err = loop_set_block_size(lo, arg);
153489e4fdecSOmar Sandoval 		break;
15351da177e4SLinus Torvalds 	default:
153647e96246SChristoph Hellwig 		err = -EINVAL;
15371da177e4SLinus Torvalds 	}
15386cc8e743SPavel Tatashin 	mutex_unlock(&lo->lo_mutex);
1539a1316544SJan Kara 	return err;
1540a1316544SJan Kara }
1541f028f3b2SNikanth Karthikesan 
1542a1316544SJan Kara static int lo_ioctl(struct block_device *bdev, fmode_t mode,
1543a1316544SJan Kara 	unsigned int cmd, unsigned long arg)
1544a1316544SJan Kara {
1545a1316544SJan Kara 	struct loop_device *lo = bdev->bd_disk->private_data;
1546571fae6eSMartijn Coenen 	void __user *argp = (void __user *) arg;
1547a1316544SJan Kara 	int err;
1548a1316544SJan Kara 
1549a1316544SJan Kara 	switch (cmd) {
15503448914eSMartijn Coenen 	case LOOP_SET_FD: {
15513448914eSMartijn Coenen 		/*
15523448914eSMartijn Coenen 		 * Legacy case - pass in a zeroed out struct loop_config with
15533448914eSMartijn Coenen 		 * only the file descriptor set , which corresponds with the
15543448914eSMartijn Coenen 		 * default parameters we'd have used otherwise.
15553448914eSMartijn Coenen 		 */
15563448914eSMartijn Coenen 		struct loop_config config;
15573448914eSMartijn Coenen 
15583448914eSMartijn Coenen 		memset(&config, 0, sizeof(config));
15593448914eSMartijn Coenen 		config.fd = arg;
15603448914eSMartijn Coenen 
15613448914eSMartijn Coenen 		return loop_configure(lo, mode, bdev, &config);
15623448914eSMartijn Coenen 	}
15633448914eSMartijn Coenen 	case LOOP_CONFIGURE: {
15643448914eSMartijn Coenen 		struct loop_config config;
15653448914eSMartijn Coenen 
15663448914eSMartijn Coenen 		if (copy_from_user(&config, argp, sizeof(config)))
15673448914eSMartijn Coenen 			return -EFAULT;
15683448914eSMartijn Coenen 
15693448914eSMartijn Coenen 		return loop_configure(lo, mode, bdev, &config);
15703448914eSMartijn Coenen 	}
1571a1316544SJan Kara 	case LOOP_CHANGE_FD:
1572c3710770SJan Kara 		return loop_change_fd(lo, bdev, arg);
1573a1316544SJan Kara 	case LOOP_CLR_FD:
15747ccd0791SJan Kara 		return loop_clr_fd(lo);
1575a1316544SJan Kara 	case LOOP_SET_STATUS:
1576a1316544SJan Kara 		err = -EPERM;
1577a1316544SJan Kara 		if ((mode & FMODE_WRITE) || capable(CAP_SYS_ADMIN)) {
1578571fae6eSMartijn Coenen 			err = loop_set_status_old(lo, argp);
1579a1316544SJan Kara 		}
1580a1316544SJan Kara 		break;
1581a1316544SJan Kara 	case LOOP_GET_STATUS:
1582571fae6eSMartijn Coenen 		return loop_get_status_old(lo, argp);
1583a1316544SJan Kara 	case LOOP_SET_STATUS64:
1584a1316544SJan Kara 		err = -EPERM;
1585a1316544SJan Kara 		if ((mode & FMODE_WRITE) || capable(CAP_SYS_ADMIN)) {
1586571fae6eSMartijn Coenen 			err = loop_set_status64(lo, argp);
1587a1316544SJan Kara 		}
1588a1316544SJan Kara 		break;
1589a1316544SJan Kara 	case LOOP_GET_STATUS64:
1590571fae6eSMartijn Coenen 		return loop_get_status64(lo, argp);
1591a1316544SJan Kara 	case LOOP_SET_CAPACITY:
1592a1316544SJan Kara 	case LOOP_SET_DIRECT_IO:
1593a1316544SJan Kara 	case LOOP_SET_BLOCK_SIZE:
1594a1316544SJan Kara 		if (!(mode & FMODE_WRITE) && !capable(CAP_SYS_ADMIN))
1595a1316544SJan Kara 			return -EPERM;
1596df561f66SGustavo A. R. Silva 		fallthrough;
1597a1316544SJan Kara 	default:
1598a1316544SJan Kara 		err = lo_simple_ioctl(lo, cmd, arg);
1599a1316544SJan Kara 		break;
1600a1316544SJan Kara 	}
1601a1316544SJan Kara 
16021da177e4SLinus Torvalds 	return err;
16031da177e4SLinus Torvalds }
16041da177e4SLinus Torvalds 
1605863d5b82SDavid Howells #ifdef CONFIG_COMPAT
1606863d5b82SDavid Howells struct compat_loop_info {
1607863d5b82SDavid Howells 	compat_int_t	lo_number;      /* ioctl r/o */
1608863d5b82SDavid Howells 	compat_dev_t	lo_device;      /* ioctl r/o */
1609863d5b82SDavid Howells 	compat_ulong_t	lo_inode;       /* ioctl r/o */
1610863d5b82SDavid Howells 	compat_dev_t	lo_rdevice;     /* ioctl r/o */
1611863d5b82SDavid Howells 	compat_int_t	lo_offset;
1612f941c51eSCarlos Llamas 	compat_int_t	lo_encrypt_type;        /* obsolete, ignored */
1613863d5b82SDavid Howells 	compat_int_t	lo_encrypt_key_size;    /* ioctl w/o */
1614863d5b82SDavid Howells 	compat_int_t	lo_flags;       /* ioctl r/o */
1615863d5b82SDavid Howells 	char		lo_name[LO_NAME_SIZE];
1616863d5b82SDavid Howells 	unsigned char	lo_encrypt_key[LO_KEY_SIZE]; /* ioctl w/o */
1617863d5b82SDavid Howells 	compat_ulong_t	lo_init[2];
1618863d5b82SDavid Howells 	char		reserved[4];
1619863d5b82SDavid Howells };
1620863d5b82SDavid Howells 
1621863d5b82SDavid Howells /*
1622863d5b82SDavid Howells  * Transfer 32-bit compatibility structure in userspace to 64-bit loop info
1623863d5b82SDavid Howells  * - noinlined to reduce stack space usage in main part of driver
1624863d5b82SDavid Howells  */
1625863d5b82SDavid Howells static noinline int
1626ba674cfcSAl Viro loop_info64_from_compat(const struct compat_loop_info __user *arg,
1627863d5b82SDavid Howells 			struct loop_info64 *info64)
1628863d5b82SDavid Howells {
1629863d5b82SDavid Howells 	struct compat_loop_info info;
1630863d5b82SDavid Howells 
1631863d5b82SDavid Howells 	if (copy_from_user(&info, arg, sizeof(info)))
1632863d5b82SDavid Howells 		return -EFAULT;
1633863d5b82SDavid Howells 
1634863d5b82SDavid Howells 	memset(info64, 0, sizeof(*info64));
1635863d5b82SDavid Howells 	info64->lo_number = info.lo_number;
1636863d5b82SDavid Howells 	info64->lo_device = info.lo_device;
1637863d5b82SDavid Howells 	info64->lo_inode = info.lo_inode;
1638863d5b82SDavid Howells 	info64->lo_rdevice = info.lo_rdevice;
1639863d5b82SDavid Howells 	info64->lo_offset = info.lo_offset;
1640863d5b82SDavid Howells 	info64->lo_sizelimit = 0;
1641863d5b82SDavid Howells 	info64->lo_flags = info.lo_flags;
1642863d5b82SDavid Howells 	memcpy(info64->lo_file_name, info.lo_name, LO_NAME_SIZE);
1643863d5b82SDavid Howells 	return 0;
1644863d5b82SDavid Howells }
1645863d5b82SDavid Howells 
1646863d5b82SDavid Howells /*
1647863d5b82SDavid Howells  * Transfer 64-bit loop info to 32-bit compatibility structure in userspace
1648863d5b82SDavid Howells  * - noinlined to reduce stack space usage in main part of driver
1649863d5b82SDavid Howells  */
1650863d5b82SDavid Howells static noinline int
1651863d5b82SDavid Howells loop_info64_to_compat(const struct loop_info64 *info64,
1652863d5b82SDavid Howells 		      struct compat_loop_info __user *arg)
1653863d5b82SDavid Howells {
1654863d5b82SDavid Howells 	struct compat_loop_info info;
1655863d5b82SDavid Howells 
1656863d5b82SDavid Howells 	memset(&info, 0, sizeof(info));
1657863d5b82SDavid Howells 	info.lo_number = info64->lo_number;
1658863d5b82SDavid Howells 	info.lo_device = info64->lo_device;
1659863d5b82SDavid Howells 	info.lo_inode = info64->lo_inode;
1660863d5b82SDavid Howells 	info.lo_rdevice = info64->lo_rdevice;
1661863d5b82SDavid Howells 	info.lo_offset = info64->lo_offset;
1662863d5b82SDavid Howells 	info.lo_flags = info64->lo_flags;
1663863d5b82SDavid Howells 	memcpy(info.lo_name, info64->lo_file_name, LO_NAME_SIZE);
1664863d5b82SDavid Howells 
1665863d5b82SDavid Howells 	/* error in case values were truncated */
1666863d5b82SDavid Howells 	if (info.lo_device != info64->lo_device ||
1667863d5b82SDavid Howells 	    info.lo_rdevice != info64->lo_rdevice ||
1668863d5b82SDavid Howells 	    info.lo_inode != info64->lo_inode ||
166947e96246SChristoph Hellwig 	    info.lo_offset != info64->lo_offset)
1670863d5b82SDavid Howells 		return -EOVERFLOW;
1671863d5b82SDavid Howells 
1672863d5b82SDavid Howells 	if (copy_to_user(arg, &info, sizeof(info)))
1673863d5b82SDavid Howells 		return -EFAULT;
1674863d5b82SDavid Howells 	return 0;
1675863d5b82SDavid Howells }
1676863d5b82SDavid Howells 
1677863d5b82SDavid Howells static int
1678863d5b82SDavid Howells loop_set_status_compat(struct loop_device *lo,
1679863d5b82SDavid Howells 		       const struct compat_loop_info __user *arg)
1680863d5b82SDavid Howells {
1681863d5b82SDavid Howells 	struct loop_info64 info64;
1682863d5b82SDavid Howells 	int ret;
1683863d5b82SDavid Howells 
1684863d5b82SDavid Howells 	ret = loop_info64_from_compat(arg, &info64);
1685863d5b82SDavid Howells 	if (ret < 0)
1686863d5b82SDavid Howells 		return ret;
1687863d5b82SDavid Howells 	return loop_set_status(lo, &info64);
1688863d5b82SDavid Howells }
1689863d5b82SDavid Howells 
1690863d5b82SDavid Howells static int
1691863d5b82SDavid Howells loop_get_status_compat(struct loop_device *lo,
1692863d5b82SDavid Howells 		       struct compat_loop_info __user *arg)
1693863d5b82SDavid Howells {
1694863d5b82SDavid Howells 	struct loop_info64 info64;
1695bdac616dSOmar Sandoval 	int err;
1696863d5b82SDavid Howells 
16974a5ce9baSJan Kara 	if (!arg)
1698bdac616dSOmar Sandoval 		return -EINVAL;
1699863d5b82SDavid Howells 	err = loop_get_status(lo, &info64);
1700863d5b82SDavid Howells 	if (!err)
1701863d5b82SDavid Howells 		err = loop_info64_to_compat(&info64, arg);
1702863d5b82SDavid Howells 	return err;
1703863d5b82SDavid Howells }
1704863d5b82SDavid Howells 
1705bb214884SAl Viro static int lo_compat_ioctl(struct block_device *bdev, fmode_t mode,
1706bb214884SAl Viro 			   unsigned int cmd, unsigned long arg)
1707863d5b82SDavid Howells {
1708bb214884SAl Viro 	struct loop_device *lo = bdev->bd_disk->private_data;
1709863d5b82SDavid Howells 	int err;
1710863d5b82SDavid Howells 
1711863d5b82SDavid Howells 	switch(cmd) {
1712863d5b82SDavid Howells 	case LOOP_SET_STATUS:
17133148ffbdSOmar Sandoval 		err = loop_set_status_compat(lo,
17143148ffbdSOmar Sandoval 			     (const struct compat_loop_info __user *)arg);
1715863d5b82SDavid Howells 		break;
1716863d5b82SDavid Howells 	case LOOP_GET_STATUS:
17173148ffbdSOmar Sandoval 		err = loop_get_status_compat(lo,
17183148ffbdSOmar Sandoval 				     (struct compat_loop_info __user *)arg);
1719863d5b82SDavid Howells 		break;
172053d66608SJ. R. Okajima 	case LOOP_SET_CAPACITY:
1721863d5b82SDavid Howells 	case LOOP_CLR_FD:
1722863d5b82SDavid Howells 	case LOOP_GET_STATUS64:
1723863d5b82SDavid Howells 	case LOOP_SET_STATUS64:
17243448914eSMartijn Coenen 	case LOOP_CONFIGURE:
1725863d5b82SDavid Howells 		arg = (unsigned long) compat_ptr(arg);
1726df561f66SGustavo A. R. Silva 		fallthrough;
1727863d5b82SDavid Howells 	case LOOP_SET_FD:
1728863d5b82SDavid Howells 	case LOOP_CHANGE_FD:
17299fea4b39SEvan Green 	case LOOP_SET_BLOCK_SIZE:
1730fdbe4eeeSAlessio Balsini 	case LOOP_SET_DIRECT_IO:
1731bb214884SAl Viro 		err = lo_ioctl(bdev, mode, cmd, arg);
1732863d5b82SDavid Howells 		break;
1733863d5b82SDavid Howells 	default:
1734863d5b82SDavid Howells 		err = -ENOIOCTLCMD;
1735863d5b82SDavid Howells 		break;
1736863d5b82SDavid Howells 	}
1737863d5b82SDavid Howells 	return err;
1738863d5b82SDavid Howells }
1739863d5b82SDavid Howells #endif
1740863d5b82SDavid Howells 
1741bb214884SAl Viro static int lo_open(struct block_device *bdev, fmode_t mode)
17421da177e4SLinus Torvalds {
1743990e7811SChristoph Hellwig 	struct loop_device *lo = bdev->bd_disk->private_data;
17440a42e99bSJan Kara 	int err;
1745770fe30aSKay Sievers 
17466cc8e743SPavel Tatashin 	err = mutex_lock_killable(&lo->lo_mutex);
17476cc8e743SPavel Tatashin 	if (err)
1748770fe30aSKay Sievers 		return err;
1749990e7811SChristoph Hellwig 	if (lo->lo_state == Lo_deleting)
1750990e7811SChristoph Hellwig 		err = -ENXIO;
1751990e7811SChristoph Hellwig 	else
17526cc8e743SPavel Tatashin 		atomic_inc(&lo->lo_refcnt);
17536cc8e743SPavel Tatashin 	mutex_unlock(&lo->lo_mutex);
1754990e7811SChristoph Hellwig 	return err;
17551da177e4SLinus Torvalds }
17561da177e4SLinus Torvalds 
1757967d1dc1SJan Kara static void lo_release(struct gendisk *disk, fmode_t mode)
17581da177e4SLinus Torvalds {
17596cc8e743SPavel Tatashin 	struct loop_device *lo = disk->private_data;
17601da177e4SLinus Torvalds 
17616cc8e743SPavel Tatashin 	mutex_lock(&lo->lo_mutex);
1762f8933667SMing Lei 	if (atomic_dec_return(&lo->lo_refcnt))
17630a42e99bSJan Kara 		goto out_unlock;
1764f8933667SMing Lei 
176514f27939SMilan Broz 	if (lo->lo_flags & LO_FLAGS_AUTOCLEAR) {
1766a2505b79SJan Kara 		if (lo->lo_state != Lo_bound)
1767a2505b79SJan Kara 			goto out_unlock;
1768a2505b79SJan Kara 		lo->lo_state = Lo_rundown;
17696cc8e743SPavel Tatashin 		mutex_unlock(&lo->lo_mutex);
177014f27939SMilan Broz 		/*
177114f27939SMilan Broz 		 * In autoclear mode, stop the loop thread
177214f27939SMilan Broz 		 * and remove configuration after last close.
177314f27939SMilan Broz 		 */
1774bf23747eSTetsuo Handa 		__loop_clr_fd(lo, true);
17750a42e99bSJan Kara 		return;
177643cade80SOmar Sandoval 	} else if (lo->lo_state == Lo_bound) {
177714f27939SMilan Broz 		/*
177814f27939SMilan Broz 		 * Otherwise keep thread (if running) and config,
177914f27939SMilan Broz 		 * but flush possible ongoing bios in thread.
178014f27939SMilan Broz 		 */
178143cade80SOmar Sandoval 		blk_mq_freeze_queue(lo->lo_queue);
178243cade80SOmar Sandoval 		blk_mq_unfreeze_queue(lo->lo_queue);
178314f27939SMilan Broz 	}
178496c58655SDavid Woodhouse 
17850a42e99bSJan Kara out_unlock:
17866cc8e743SPavel Tatashin 	mutex_unlock(&lo->lo_mutex);
1787ae665016SLinus Torvalds }
1788ae665016SLinus Torvalds 
178983d5cde4SAlexey Dobriyan static const struct block_device_operations lo_fops = {
17901da177e4SLinus Torvalds 	.owner =	THIS_MODULE,
1791bb214884SAl Viro 	.open =		lo_open,
1792bb214884SAl Viro 	.release =	lo_release,
1793bb214884SAl Viro 	.ioctl =	lo_ioctl,
1794863d5b82SDavid Howells #ifdef CONFIG_COMPAT
1795bb214884SAl Viro 	.compat_ioctl =	lo_compat_ioctl,
1796863d5b82SDavid Howells #endif
17971da177e4SLinus Torvalds };
17981da177e4SLinus Torvalds 
17991da177e4SLinus Torvalds /*
18001da177e4SLinus Torvalds  * And now the modules code and kernel interface.
18011da177e4SLinus Torvalds  */
180273285082SKen Chen static int max_loop;
18035657a819SJoe Perches module_param(max_loop, int, 0444);
1804a47653fcSKen Chen MODULE_PARM_DESC(max_loop, "Maximum number of loop devices");
18055657a819SJoe Perches module_param(max_part, int, 0444);
1806476a4813SLaurent Vivier MODULE_PARM_DESC(max_part, "Maximum number of partitions per loop device");
1807ef44c508SChaitanya Kulkarni 
1808ef44c508SChaitanya Kulkarni static int hw_queue_depth = LOOP_DEFAULT_HW_Q_DEPTH;
1809ef44c508SChaitanya Kulkarni 
1810ef44c508SChaitanya Kulkarni static int loop_set_hw_queue_depth(const char *s, const struct kernel_param *p)
1811ef44c508SChaitanya Kulkarni {
1812ef44c508SChaitanya Kulkarni 	int ret = kstrtoint(s, 10, &hw_queue_depth);
1813ef44c508SChaitanya Kulkarni 
1814ef44c508SChaitanya Kulkarni 	return (ret || (hw_queue_depth < 1)) ? -EINVAL : 0;
1815ef44c508SChaitanya Kulkarni }
1816ef44c508SChaitanya Kulkarni 
1817ef44c508SChaitanya Kulkarni static const struct kernel_param_ops loop_hw_qdepth_param_ops = {
1818ef44c508SChaitanya Kulkarni 	.set	= loop_set_hw_queue_depth,
1819ef44c508SChaitanya Kulkarni 	.get	= param_get_int,
1820ef44c508SChaitanya Kulkarni };
1821ef44c508SChaitanya Kulkarni 
1822ef44c508SChaitanya Kulkarni device_param_cb(hw_queue_depth, &loop_hw_qdepth_param_ops, &hw_queue_depth, 0444);
1823ef44c508SChaitanya Kulkarni MODULE_PARM_DESC(hw_queue_depth, "Queue depth for each hardware queue. Default: 128");
1824ef44c508SChaitanya Kulkarni 
18251da177e4SLinus Torvalds MODULE_LICENSE("GPL");
18261da177e4SLinus Torvalds MODULE_ALIAS_BLOCKDEV_MAJOR(LOOP_MAJOR);
18271da177e4SLinus Torvalds 
1828fc17b653SChristoph Hellwig static blk_status_t loop_queue_rq(struct blk_mq_hw_ctx *hctx,
1829b5dd2f60SMing Lei 		const struct blk_mq_queue_data *bd)
1830b5dd2f60SMing Lei {
18311894e916SJens Axboe 	struct request *rq = bd->rq;
18321894e916SJens Axboe 	struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
18331894e916SJens Axboe 	struct loop_device *lo = rq->q->queuedata;
1834b5dd2f60SMing Lei 
18351894e916SJens Axboe 	blk_mq_start_request(rq);
1836b5dd2f60SMing Lei 
1837f4aa4c7bSMing Lei 	if (lo->lo_state != Lo_bound)
1838fc17b653SChristoph Hellwig 		return BLK_STS_IOERR;
1839f4aa4c7bSMing Lei 
18401894e916SJens Axboe 	switch (req_op(rq)) {
1841f0225cacSChristoph Hellwig 	case REQ_OP_FLUSH:
1842f0225cacSChristoph Hellwig 	case REQ_OP_DISCARD:
184319372e27SChristoph Hellwig 	case REQ_OP_WRITE_ZEROES:
1844bc07c10aSMing Lei 		cmd->use_aio = false;
1845f0225cacSChristoph Hellwig 		break;
1846f0225cacSChristoph Hellwig 	default:
1847f0225cacSChristoph Hellwig 		cmd->use_aio = lo->use_dio;
1848f0225cacSChristoph Hellwig 		break;
1849f0225cacSChristoph Hellwig 	}
1850bc07c10aSMing Lei 
1851d4478e92SShaohua Li 	/* always use the first bio's css */
1852c74d40e8SDan Schatzberg 	cmd->blkcg_css = NULL;
1853c74d40e8SDan Schatzberg 	cmd->memcg_css = NULL;
18540b508bc9SShaohua Li #ifdef CONFIG_BLK_CGROUP
1855c74d40e8SDan Schatzberg 	if (rq->bio && rq->bio->bi_blkg) {
1856c74d40e8SDan Schatzberg 		cmd->blkcg_css = &bio_blkcg(rq->bio)->css;
1857c74d40e8SDan Schatzberg #ifdef CONFIG_MEMCG
1858c74d40e8SDan Schatzberg 		cmd->memcg_css =
1859c74d40e8SDan Schatzberg 			cgroup_get_e_css(cmd->blkcg_css->cgroup,
1860c74d40e8SDan Schatzberg 					&memory_cgrp_subsys);
1861d4478e92SShaohua Li #endif
1862c74d40e8SDan Schatzberg 	}
1863c74d40e8SDan Schatzberg #endif
186487579e9bSDan Schatzberg 	loop_queue_work(lo, cmd);
1865b5dd2f60SMing Lei 
1866fc17b653SChristoph Hellwig 	return BLK_STS_OK;
1867b5dd2f60SMing Lei }
1868b5dd2f60SMing Lei 
1869b5dd2f60SMing Lei static void loop_handle_cmd(struct loop_cmd *cmd)
1870b5dd2f60SMing Lei {
18711894e916SJens Axboe 	struct request *rq = blk_mq_rq_from_pdu(cmd);
18721894e916SJens Axboe 	const bool write = op_is_write(req_op(rq));
18731894e916SJens Axboe 	struct loop_device *lo = rq->q->queuedata;
1874f4829a9bSChristoph Hellwig 	int ret = 0;
1875c74d40e8SDan Schatzberg 	struct mem_cgroup *old_memcg = NULL;
1876b5dd2f60SMing Lei 
1877f4829a9bSChristoph Hellwig 	if (write && (lo->lo_flags & LO_FLAGS_READ_ONLY)) {
1878f4829a9bSChristoph Hellwig 		ret = -EIO;
1879b5dd2f60SMing Lei 		goto failed;
1880f4829a9bSChristoph Hellwig 	}
1881b5dd2f60SMing Lei 
1882c74d40e8SDan Schatzberg 	if (cmd->blkcg_css)
1883c74d40e8SDan Schatzberg 		kthread_associate_blkcg(cmd->blkcg_css);
1884c74d40e8SDan Schatzberg 	if (cmd->memcg_css)
1885c74d40e8SDan Schatzberg 		old_memcg = set_active_memcg(
1886c74d40e8SDan Schatzberg 			mem_cgroup_from_css(cmd->memcg_css));
1887c74d40e8SDan Schatzberg 
18881894e916SJens Axboe 	ret = do_req_filebacked(lo, rq);
1889c74d40e8SDan Schatzberg 
1890c74d40e8SDan Schatzberg 	if (cmd->blkcg_css)
1891c74d40e8SDan Schatzberg 		kthread_associate_blkcg(NULL);
1892c74d40e8SDan Schatzberg 
1893c74d40e8SDan Schatzberg 	if (cmd->memcg_css) {
1894c74d40e8SDan Schatzberg 		set_active_memcg(old_memcg);
1895c74d40e8SDan Schatzberg 		css_put(cmd->memcg_css);
1896c74d40e8SDan Schatzberg 	}
1897b5dd2f60SMing Lei  failed:
1898bc07c10aSMing Lei 	/* complete non-aio request */
1899fe2cb290SChristoph Hellwig 	if (!cmd->use_aio || ret) {
19008cd55087SEvan Green 		if (ret == -EOPNOTSUPP)
19018cd55087SEvan Green 			cmd->ret = ret;
19028cd55087SEvan Green 		else
1903fe2cb290SChristoph Hellwig 			cmd->ret = ret ? -EIO : 0;
190415f73f5bSChristoph Hellwig 		if (likely(!blk_should_fake_timeout(rq->q)))
19051894e916SJens Axboe 			blk_mq_complete_request(rq);
1906fe2cb290SChristoph Hellwig 	}
1907b5dd2f60SMing Lei }
1908b5dd2f60SMing Lei 
190987579e9bSDan Schatzberg static void loop_process_work(struct loop_worker *worker,
191087579e9bSDan Schatzberg 			struct list_head *cmd_list, struct loop_device *lo)
1911b5dd2f60SMing Lei {
191287579e9bSDan Schatzberg 	int orig_flags = current->flags;
191387579e9bSDan Schatzberg 	struct loop_cmd *cmd;
1914b5dd2f60SMing Lei 
191587579e9bSDan Schatzberg 	current->flags |= PF_LOCAL_THROTTLE | PF_MEMALLOC_NOIO;
191687579e9bSDan Schatzberg 	spin_lock_irq(&lo->lo_work_lock);
191787579e9bSDan Schatzberg 	while (!list_empty(cmd_list)) {
191887579e9bSDan Schatzberg 		cmd = container_of(
191987579e9bSDan Schatzberg 			cmd_list->next, struct loop_cmd, list_entry);
192087579e9bSDan Schatzberg 		list_del(cmd_list->next);
192187579e9bSDan Schatzberg 		spin_unlock_irq(&lo->lo_work_lock);
192287579e9bSDan Schatzberg 
192387579e9bSDan Schatzberg 		loop_handle_cmd(cmd);
192487579e9bSDan Schatzberg 		cond_resched();
192587579e9bSDan Schatzberg 
192687579e9bSDan Schatzberg 		spin_lock_irq(&lo->lo_work_lock);
192787579e9bSDan Schatzberg 	}
192887579e9bSDan Schatzberg 
192987579e9bSDan Schatzberg 	/*
193087579e9bSDan Schatzberg 	 * We only add to the idle list if there are no pending cmds
193187579e9bSDan Schatzberg 	 * *and* the worker will not run again which ensures that it
193287579e9bSDan Schatzberg 	 * is safe to free any worker on the idle list
193387579e9bSDan Schatzberg 	 */
193487579e9bSDan Schatzberg 	if (worker && !work_pending(&worker->work)) {
193587579e9bSDan Schatzberg 		worker->last_ran_at = jiffies;
193687579e9bSDan Schatzberg 		list_add_tail(&worker->idle_list, &lo->idle_worker_list);
193787579e9bSDan Schatzberg 		loop_set_timer(lo);
193887579e9bSDan Schatzberg 	}
193987579e9bSDan Schatzberg 	spin_unlock_irq(&lo->lo_work_lock);
194087579e9bSDan Schatzberg 	current->flags = orig_flags;
194187579e9bSDan Schatzberg }
194287579e9bSDan Schatzberg 
194387579e9bSDan Schatzberg static void loop_workfn(struct work_struct *work)
194487579e9bSDan Schatzberg {
194587579e9bSDan Schatzberg 	struct loop_worker *worker =
194687579e9bSDan Schatzberg 		container_of(work, struct loop_worker, work);
194787579e9bSDan Schatzberg 	loop_process_work(worker, &worker->cmd_list, worker->lo);
194887579e9bSDan Schatzberg }
194987579e9bSDan Schatzberg 
195087579e9bSDan Schatzberg static void loop_rootcg_workfn(struct work_struct *work)
195187579e9bSDan Schatzberg {
195287579e9bSDan Schatzberg 	struct loop_device *lo =
195387579e9bSDan Schatzberg 		container_of(work, struct loop_device, rootcg_work);
195487579e9bSDan Schatzberg 	loop_process_work(NULL, &lo->rootcg_cmd_list, lo);
195587579e9bSDan Schatzberg }
195687579e9bSDan Schatzberg 
1957f363b089SEric Biggers static const struct blk_mq_ops loop_mq_ops = {
1958b5dd2f60SMing Lei 	.queue_rq       = loop_queue_rq,
1959fe2cb290SChristoph Hellwig 	.complete	= lo_complete_rq,
1960b5dd2f60SMing Lei };
1961b5dd2f60SMing Lei 
1962d6da83d0SChristoph Hellwig static int loop_add(int i)
19631da177e4SLinus Torvalds {
196473285082SKen Chen 	struct loop_device *lo;
196573285082SKen Chen 	struct gendisk *disk;
196634dd82afSKay Sievers 	int err;
19671da177e4SLinus Torvalds 
196834dd82afSKay Sievers 	err = -ENOMEM;
196968d740d7SSilva Paulo 	lo = kzalloc(sizeof(*lo), GFP_KERNEL);
197068d740d7SSilva Paulo 	if (!lo)
197173285082SKen Chen 		goto out;
1972ef7e7c82SMikulas Patocka 	lo->lo_state = Lo_unbound;
1973ef7e7c82SMikulas Patocka 
197418d1f200SChristoph Hellwig 	err = mutex_lock_killable(&loop_ctl_mutex);
197518d1f200SChristoph Hellwig 	if (err)
197618d1f200SChristoph Hellwig 		goto out_free_dev;
197718d1f200SChristoph Hellwig 
1978c718aa65STejun Heo 	/* allocate id, if @id >= 0, we're requesting that specific id */
197934dd82afSKay Sievers 	if (i >= 0) {
1980c718aa65STejun Heo 		err = idr_alloc(&loop_index_idr, lo, i, i + 1, GFP_KERNEL);
1981c718aa65STejun Heo 		if (err == -ENOSPC)
198234dd82afSKay Sievers 			err = -EEXIST;
198334dd82afSKay Sievers 	} else {
1984c718aa65STejun Heo 		err = idr_alloc(&loop_index_idr, lo, 0, 0, GFP_KERNEL);
198534dd82afSKay Sievers 	}
19861c500ad7STetsuo Handa 	mutex_unlock(&loop_ctl_mutex);
198734dd82afSKay Sievers 	if (err < 0)
19881c500ad7STetsuo Handa 		goto out_free_dev;
1989c718aa65STejun Heo 	i = err;
19901da177e4SLinus Torvalds 
1991b5dd2f60SMing Lei 	lo->tag_set.ops = &loop_mq_ops;
1992b5dd2f60SMing Lei 	lo->tag_set.nr_hw_queues = 1;
1993ef44c508SChaitanya Kulkarni 	lo->tag_set.queue_depth = hw_queue_depth;
1994b5dd2f60SMing Lei 	lo->tag_set.numa_node = NUMA_NO_NODE;
1995b5dd2f60SMing Lei 	lo->tag_set.cmd_size = sizeof(struct loop_cmd);
19962112f5c1SBart Van Assche 	lo->tag_set.flags = BLK_MQ_F_SHOULD_MERGE | BLK_MQ_F_STACKING |
19972112f5c1SBart Van Assche 		BLK_MQ_F_NO_SCHED_BY_DEFAULT;
1998b5dd2f60SMing Lei 	lo->tag_set.driver_data = lo;
1999b5dd2f60SMing Lei 
2000b5dd2f60SMing Lei 	err = blk_mq_alloc_tag_set(&lo->tag_set);
2001b5dd2f60SMing Lei 	if (err)
20023ec981e3SMikulas Patocka 		goto out_free_idr;
200373285082SKen Chen 
20041c99502fSChristoph Hellwig 	disk = lo->lo_disk = blk_mq_alloc_disk(&lo->tag_set, lo);
20051c99502fSChristoph Hellwig 	if (IS_ERR(disk)) {
20061c99502fSChristoph Hellwig 		err = PTR_ERR(disk);
2007b5dd2f60SMing Lei 		goto out_cleanup_tags;
2008b5dd2f60SMing Lei 	}
20091c99502fSChristoph Hellwig 	lo->lo_queue = lo->lo_disk->queue;
2010ef7e7c82SMikulas Patocka 
201154bb0adeSShaohua Li 	blk_queue_max_hw_sectors(lo->lo_queue, BLK_DEF_MAX_SECTORS);
201240326d8aSShaohua Li 
20135b5e20f4SMing Lei 	/*
201440326d8aSShaohua Li 	 * By default, we do buffer IO, so it doesn't make sense to enable
201540326d8aSShaohua Li 	 * merge because the I/O submitted to backing file is handled page by
201640326d8aSShaohua Li 	 * page. For directio mode, merge does help to dispatch bigger request
201740326d8aSShaohua Li 	 * to underlayer disk. We will enable merge once directio is enabled.
20185b5e20f4SMing Lei 	 */
20198b904b5bSBart Van Assche 	blk_queue_flag_set(QUEUE_FLAG_NOMERGES, lo->lo_queue);
20205b5e20f4SMing Lei 
2021e03c8dd1SKay Sievers 	/*
2022e03c8dd1SKay Sievers 	 * Disable partition scanning by default. The in-kernel partition
2023e03c8dd1SKay Sievers 	 * scanning can be requested individually per-device during its
2024e03c8dd1SKay Sievers 	 * setup. Userspace can always add and remove partitions from all
2025e03c8dd1SKay Sievers 	 * devices. The needed partition minors are allocated from the
2026e03c8dd1SKay Sievers 	 * extended minor space, the main loop device numbers will continue
2027e03c8dd1SKay Sievers 	 * to match the loop minors, regardless of the number of partitions
2028e03c8dd1SKay Sievers 	 * used.
2029e03c8dd1SKay Sievers 	 *
2030e03c8dd1SKay Sievers 	 * If max_part is given, partition scanning is globally enabled for
2031e03c8dd1SKay Sievers 	 * all loop devices. The minors for the main loop devices will be
2032e03c8dd1SKay Sievers 	 * multiples of max_part.
2033e03c8dd1SKay Sievers 	 *
2034e03c8dd1SKay Sievers 	 * Note: Global-for-all-devices, set-only-at-init, read-only module
2035e03c8dd1SKay Sievers 	 * parameteters like 'max_loop' and 'max_part' make things needlessly
2036e03c8dd1SKay Sievers 	 * complicated, are too static, inflexible and may surprise
2037e03c8dd1SKay Sievers 	 * userspace tools. Parameters like this in general should be avoided.
2038e03c8dd1SKay Sievers 	 */
2039e03c8dd1SKay Sievers 	if (!part_shift)
204046e7eac6SChristoph Hellwig 		disk->flags |= GENHD_FL_NO_PART;
2041f8933667SMing Lei 	atomic_set(&lo->lo_refcnt, 0);
20426cc8e743SPavel Tatashin 	mutex_init(&lo->lo_mutex);
20431da177e4SLinus Torvalds 	lo->lo_number		= i;
20441da177e4SLinus Torvalds 	spin_lock_init(&lo->lo_lock);
204587579e9bSDan Schatzberg 	spin_lock_init(&lo->lo_work_lock);
20461da177e4SLinus Torvalds 	disk->major		= LOOP_MAJOR;
2047476a4813SLaurent Vivier 	disk->first_minor	= i << part_shift;
20481c99502fSChristoph Hellwig 	disk->minors		= 1 << part_shift;
20491da177e4SLinus Torvalds 	disk->fops		= &lo_fops;
20501da177e4SLinus Torvalds 	disk->private_data	= lo;
20511da177e4SLinus Torvalds 	disk->queue		= lo->lo_queue;
20529f65c489SMatteo Croce 	disk->events		= DISK_EVENT_MEDIA_CHANGE;
20539f65c489SMatteo Croce 	disk->event_flags	= DISK_EVENT_FLAG_UEVENT;
205473285082SKen Chen 	sprintf(disk->disk_name, "loop%d", i);
20551c500ad7STetsuo Handa 	/* Make this loop device reachable from pathname. */
2056905705f0SLuis Chamberlain 	err = add_disk(disk);
2057905705f0SLuis Chamberlain 	if (err)
2058905705f0SLuis Chamberlain 		goto out_cleanup_disk;
2059905705f0SLuis Chamberlain 
20601c500ad7STetsuo Handa 	/* Show this loop device. */
20611c500ad7STetsuo Handa 	mutex_lock(&loop_ctl_mutex);
20621c500ad7STetsuo Handa 	lo->idr_visible = true;
206318d1f200SChristoph Hellwig 	mutex_unlock(&loop_ctl_mutex);
2064905705f0SLuis Chamberlain 
206518d1f200SChristoph Hellwig 	return i;
206673285082SKen Chen 
2067905705f0SLuis Chamberlain out_cleanup_disk:
2068905705f0SLuis Chamberlain 	blk_cleanup_disk(disk);
2069b5dd2f60SMing Lei out_cleanup_tags:
2070b5dd2f60SMing Lei 	blk_mq_free_tag_set(&lo->tag_set);
20713ec981e3SMikulas Patocka out_free_idr:
20721c500ad7STetsuo Handa 	mutex_lock(&loop_ctl_mutex);
20733ec981e3SMikulas Patocka 	idr_remove(&loop_index_idr, i);
207418d1f200SChristoph Hellwig 	mutex_unlock(&loop_ctl_mutex);
207573285082SKen Chen out_free_dev:
207673285082SKen Chen 	kfree(lo);
207773285082SKen Chen out:
207834dd82afSKay Sievers 	return err;
20791da177e4SLinus Torvalds }
20801da177e4SLinus Torvalds 
208134dd82afSKay Sievers static void loop_remove(struct loop_device *lo)
208273285082SKen Chen {
20831c500ad7STetsuo Handa 	/* Make this loop device unreachable from pathname. */
20846cd18e71SNeilBrown 	del_gendisk(lo->lo_disk);
20851c99502fSChristoph Hellwig 	blk_cleanup_disk(lo->lo_disk);
2086b5dd2f60SMing Lei 	blk_mq_free_tag_set(&lo->tag_set);
2087ce8d7861SChristoph Hellwig 
20881c500ad7STetsuo Handa 	mutex_lock(&loop_ctl_mutex);
20891c500ad7STetsuo Handa 	idr_remove(&loop_index_idr, lo->lo_number);
20901c500ad7STetsuo Handa 	mutex_unlock(&loop_ctl_mutex);
20911c500ad7STetsuo Handa 	/* There is no route which can find this loop device. */
20926cc8e743SPavel Tatashin 	mutex_destroy(&lo->lo_mutex);
209373285082SKen Chen 	kfree(lo);
209473285082SKen Chen }
209573285082SKen Chen 
20968410d38cSChristoph Hellwig static void loop_probe(dev_t dev)
209773285082SKen Chen {
20988410d38cSChristoph Hellwig 	int idx = MINOR(dev) >> part_shift;
20998410d38cSChristoph Hellwig 
21008410d38cSChristoph Hellwig 	if (max_loop && idx >= max_loop)
21018410d38cSChristoph Hellwig 		return;
2102d6da83d0SChristoph Hellwig 	loop_add(idx);
2103f9d10764SChristoph Hellwig }
2104f9d10764SChristoph Hellwig 
2105f9d10764SChristoph Hellwig static int loop_control_remove(int idx)
2106770fe30aSKay Sievers {
2107770fe30aSKay Sievers 	struct loop_device *lo;
21080a42e99bSJan Kara 	int ret;
2109e5d66a10SChristoph Hellwig 
2110e5d66a10SChristoph Hellwig 	if (idx < 0) {
2111e3f9387aSTetsuo Handa 		pr_warn_once("deleting an unspecified loop device is not supported.\n");
2112e5d66a10SChristoph Hellwig 		return -EINVAL;
2113e5d66a10SChristoph Hellwig 	}
2114770fe30aSKay Sievers 
21151c500ad7STetsuo Handa 	/* Hide this loop device for serialization. */
21160a42e99bSJan Kara 	ret = mutex_lock_killable(&loop_ctl_mutex);
21170a42e99bSJan Kara 	if (ret)
21180a42e99bSJan Kara 		return ret;
2119b9848081SChristoph Hellwig 	lo = idr_find(&loop_index_idr, idx);
21201c500ad7STetsuo Handa 	if (!lo || !lo->idr_visible)
2121b9848081SChristoph Hellwig 		ret = -ENODEV;
21221c500ad7STetsuo Handa 	else
21231c500ad7STetsuo Handa 		lo->idr_visible = false;
21241c500ad7STetsuo Handa 	mutex_unlock(&loop_ctl_mutex);
21251c500ad7STetsuo Handa 	if (ret)
21261c500ad7STetsuo Handa 		return ret;
2127f9d10764SChristoph Hellwig 
21281c500ad7STetsuo Handa 	/* Check whether this loop device can be removed. */
21296cc8e743SPavel Tatashin 	ret = mutex_lock_killable(&lo->lo_mutex);
21306cc8e743SPavel Tatashin 	if (ret)
21311c500ad7STetsuo Handa 		goto mark_visible;
2132f9d10764SChristoph Hellwig 	if (lo->lo_state != Lo_unbound ||
2133f9d10764SChristoph Hellwig 	    atomic_read(&lo->lo_refcnt) > 0) {
21346cc8e743SPavel Tatashin 		mutex_unlock(&lo->lo_mutex);
2135770fe30aSKay Sievers 		ret = -EBUSY;
21361c500ad7STetsuo Handa 		goto mark_visible;
2137770fe30aSKay Sievers 	}
21381c500ad7STetsuo Handa 	/* Mark this loop device no longer open()-able. */
2139990e7811SChristoph Hellwig 	lo->lo_state = Lo_deleting;
21406cc8e743SPavel Tatashin 	mutex_unlock(&lo->lo_mutex);
2141f9d10764SChristoph Hellwig 
2142770fe30aSKay Sievers 	loop_remove(lo);
21431c500ad7STetsuo Handa 	return 0;
21441c500ad7STetsuo Handa 
21451c500ad7STetsuo Handa mark_visible:
21461c500ad7STetsuo Handa 	/* Show this loop device again. */
21471c500ad7STetsuo Handa 	mutex_lock(&loop_ctl_mutex);
21481c500ad7STetsuo Handa 	lo->idr_visible = true;
2149f9d10764SChristoph Hellwig 	mutex_unlock(&loop_ctl_mutex);
2150f9d10764SChristoph Hellwig 	return ret;
2151770fe30aSKay Sievers }
2152f9d10764SChristoph Hellwig 
2153f9d10764SChristoph Hellwig static int loop_control_get_free(int idx)
2154f9d10764SChristoph Hellwig {
2155f9d10764SChristoph Hellwig 	struct loop_device *lo;
2156b9848081SChristoph Hellwig 	int id, ret;
2157f9d10764SChristoph Hellwig 
2158f9d10764SChristoph Hellwig 	ret = mutex_lock_killable(&loop_ctl_mutex);
2159f9d10764SChristoph Hellwig 	if (ret)
2160f9d10764SChristoph Hellwig 		return ret;
2161b9848081SChristoph Hellwig 	idr_for_each_entry(&loop_index_idr, lo, id) {
21621c500ad7STetsuo Handa 		/* Hitting a race results in creating a new loop device which is harmless. */
21631c500ad7STetsuo Handa 		if (lo->idr_visible && data_race(lo->lo_state) == Lo_unbound)
2164b9848081SChristoph Hellwig 			goto found;
2165b9848081SChristoph Hellwig 	}
21660a42e99bSJan Kara 	mutex_unlock(&loop_ctl_mutex);
216718d1f200SChristoph Hellwig 	return loop_add(-1);
2168b9848081SChristoph Hellwig found:
2169b9848081SChristoph Hellwig 	mutex_unlock(&loop_ctl_mutex);
2170b9848081SChristoph Hellwig 	return id;
2171770fe30aSKay Sievers }
2172770fe30aSKay Sievers 
2173f9d10764SChristoph Hellwig static long loop_control_ioctl(struct file *file, unsigned int cmd,
2174f9d10764SChristoph Hellwig 			       unsigned long parm)
2175f9d10764SChristoph Hellwig {
2176f9d10764SChristoph Hellwig 	switch (cmd) {
2177f9d10764SChristoph Hellwig 	case LOOP_CTL_ADD:
217818d1f200SChristoph Hellwig 		return loop_add(parm);
2179f9d10764SChristoph Hellwig 	case LOOP_CTL_REMOVE:
2180f9d10764SChristoph Hellwig 		return loop_control_remove(parm);
2181f9d10764SChristoph Hellwig 	case LOOP_CTL_GET_FREE:
2182f9d10764SChristoph Hellwig 		return loop_control_get_free(parm);
2183f9d10764SChristoph Hellwig 	default:
2184f9d10764SChristoph Hellwig 		return -ENOSYS;
2185f9d10764SChristoph Hellwig 	}
2186f9d10764SChristoph Hellwig }
2187f9d10764SChristoph Hellwig 
2188770fe30aSKay Sievers static const struct file_operations loop_ctl_fops = {
2189770fe30aSKay Sievers 	.open		= nonseekable_open,
2190770fe30aSKay Sievers 	.unlocked_ioctl	= loop_control_ioctl,
2191770fe30aSKay Sievers 	.compat_ioctl	= loop_control_ioctl,
2192770fe30aSKay Sievers 	.owner		= THIS_MODULE,
2193770fe30aSKay Sievers 	.llseek		= noop_llseek,
2194770fe30aSKay Sievers };
2195770fe30aSKay Sievers 
2196770fe30aSKay Sievers static struct miscdevice loop_misc = {
2197770fe30aSKay Sievers 	.minor		= LOOP_CTRL_MINOR,
2198770fe30aSKay Sievers 	.name		= "loop-control",
2199770fe30aSKay Sievers 	.fops		= &loop_ctl_fops,
2200770fe30aSKay Sievers };
2201770fe30aSKay Sievers 
2202770fe30aSKay Sievers MODULE_ALIAS_MISCDEV(LOOP_CTRL_MINOR);
2203770fe30aSKay Sievers MODULE_ALIAS("devname:loop-control");
2204770fe30aSKay Sievers 
220573285082SKen Chen static int __init loop_init(void)
220673285082SKen Chen {
2207a47653fcSKen Chen 	int i, nr;
2208770fe30aSKay Sievers 	int err;
2209a47653fcSKen Chen 
2210476a4813SLaurent Vivier 	part_shift = 0;
2211ac04fee0SNamhyung Kim 	if (max_part > 0) {
2212476a4813SLaurent Vivier 		part_shift = fls(max_part);
2213476a4813SLaurent Vivier 
2214ac04fee0SNamhyung Kim 		/*
2215ac04fee0SNamhyung Kim 		 * Adjust max_part according to part_shift as it is exported
2216ac04fee0SNamhyung Kim 		 * to user space so that user can decide correct minor number
2217ac04fee0SNamhyung Kim 		 * if [s]he want to create more devices.
2218ac04fee0SNamhyung Kim 		 *
2219ac04fee0SNamhyung Kim 		 * Note that -1 is required because partition 0 is reserved
2220ac04fee0SNamhyung Kim 		 * for the whole disk.
2221ac04fee0SNamhyung Kim 		 */
2222ac04fee0SNamhyung Kim 		max_part = (1UL << part_shift) - 1;
2223ac04fee0SNamhyung Kim 	}
2224ac04fee0SNamhyung Kim 
2225b1a66504SGuo Chao 	if ((1UL << part_shift) > DISK_MAX_PARTS) {
2226b1a66504SGuo Chao 		err = -EINVAL;
2227a8c1d064SAnton Volkov 		goto err_out;
2228b1a66504SGuo Chao 	}
222978f4bb36SNamhyung Kim 
2230b1a66504SGuo Chao 	if (max_loop > 1UL << (MINORBITS - part_shift)) {
2231b1a66504SGuo Chao 		err = -EINVAL;
2232a8c1d064SAnton Volkov 		goto err_out;
2233b1a66504SGuo Chao 	}
223473285082SKen Chen 
2235d134b00bSKay Sievers 	/*
2236d134b00bSKay Sievers 	 * If max_loop is specified, create that many devices upfront.
2237d134b00bSKay Sievers 	 * This also becomes a hard limit. If max_loop is not specified,
2238d134b00bSKay Sievers 	 * create CONFIG_BLK_DEV_LOOP_MIN_COUNT loop devices at module
2239d134b00bSKay Sievers 	 * init time. Loop devices can be requested on-demand with the
2240d134b00bSKay Sievers 	 * /dev/loop-control interface, or be instantiated by accessing
2241d134b00bSKay Sievers 	 * a 'dead' device node.
2242d134b00bSKay Sievers 	 */
2243aeb2b0b1SLukas Bulwahn 	if (max_loop)
2244a47653fcSKen Chen 		nr = max_loop;
2245aeb2b0b1SLukas Bulwahn 	else
2246d134b00bSKay Sievers 		nr = CONFIG_BLK_DEV_LOOP_MIN_COUNT;
2247a47653fcSKen Chen 
2248a8c1d064SAnton Volkov 	err = misc_register(&loop_misc);
2249a8c1d064SAnton Volkov 	if (err < 0)
2250a8c1d064SAnton Volkov 		goto err_out;
2251a8c1d064SAnton Volkov 
2252a8c1d064SAnton Volkov 
22538410d38cSChristoph Hellwig 	if (__register_blkdev(LOOP_MAJOR, "loop", loop_probe)) {
2254b1a66504SGuo Chao 		err = -EIO;
2255b1a66504SGuo Chao 		goto misc_out;
2256b1a66504SGuo Chao 	}
2257a47653fcSKen Chen 
2258d134b00bSKay Sievers 	/* pre-create number of devices given by config or max_loop */
225934dd82afSKay Sievers 	for (i = 0; i < nr; i++)
2260d6da83d0SChristoph Hellwig 		loop_add(i);
226134dd82afSKay Sievers 
226273285082SKen Chen 	printk(KERN_INFO "loop: module loaded\n");
22631da177e4SLinus Torvalds 	return 0;
2264b1a66504SGuo Chao 
2265b1a66504SGuo Chao misc_out:
2266b1a66504SGuo Chao 	misc_deregister(&loop_misc);
2267a8c1d064SAnton Volkov err_out:
2268b1a66504SGuo Chao 	return err;
226934dd82afSKay Sievers }
2270a47653fcSKen Chen 
227173285082SKen Chen static void __exit loop_exit(void)
22721da177e4SLinus Torvalds {
22738e60947dSChristoph Hellwig 	struct loop_device *lo;
22748e60947dSChristoph Hellwig 	int id;
22758e60947dSChristoph Hellwig 
22768b52d8beSChristoph Hellwig 	unregister_blkdev(LOOP_MAJOR, "loop");
22778b52d8beSChristoph Hellwig 	misc_deregister(&loop_misc);
2278200f9337SLuis Chamberlain 
22791c500ad7STetsuo Handa 	/*
22801c500ad7STetsuo Handa 	 * There is no need to use loop_ctl_mutex here, for nobody else can
22811c500ad7STetsuo Handa 	 * access loop_index_idr when this module is unloading (unless forced
22821c500ad7STetsuo Handa 	 * module unloading is requested). If this is not a clean unloading,
22831c500ad7STetsuo Handa 	 * we have no means to avoid kernel crash.
22841c500ad7STetsuo Handa 	 */
22858e60947dSChristoph Hellwig 	idr_for_each_entry(&loop_index_idr, lo, id)
22868e60947dSChristoph Hellwig 		loop_remove(lo);
2287bd5c39edSChristoph Hellwig 
2288bd5c39edSChristoph Hellwig 	idr_destroy(&loop_index_idr);
22891da177e4SLinus Torvalds }
22901da177e4SLinus Torvalds 
22911da177e4SLinus Torvalds module_init(loop_init);
22921da177e4SLinus Torvalds module_exit(loop_exit);
22931da177e4SLinus Torvalds 
22941da177e4SLinus Torvalds #ifndef MODULE
22951da177e4SLinus Torvalds static int __init max_loop_setup(char *str)
22961da177e4SLinus Torvalds {
22971da177e4SLinus Torvalds 	max_loop = simple_strtol(str, NULL, 0);
22981da177e4SLinus Torvalds 	return 1;
22991da177e4SLinus Torvalds }
23001da177e4SLinus Torvalds 
23011da177e4SLinus Torvalds __setup("max_loop=", max_loop_setup);
23021da177e4SLinus Torvalds #endif
2303