xref: /openbmc/linux/drivers/block/loop.c (revision 6b19b766)
11da177e4SLinus Torvalds /*
21da177e4SLinus Torvalds  *  linux/drivers/block/loop.c
31da177e4SLinus Torvalds  *
41da177e4SLinus Torvalds  *  Written by Theodore Ts'o, 3/29/93
51da177e4SLinus Torvalds  *
61da177e4SLinus Torvalds  * Copyright 1993 by Theodore Ts'o.  Redistribution of this file is
71da177e4SLinus Torvalds  * permitted under the GNU General Public License.
81da177e4SLinus Torvalds  *
91da177e4SLinus Torvalds  * DES encryption plus some minor changes by Werner Almesberger, 30-MAY-1993
101da177e4SLinus Torvalds  * more DES encryption plus IDEA encryption by Nicholas J. Leon, June 20, 1996
111da177e4SLinus Torvalds  *
121da177e4SLinus Torvalds  * Modularized and updated for 1.1.16 kernel - Mitch Dsouza 28th May 1994
131da177e4SLinus Torvalds  * Adapted for 1.3.59 kernel - Andries Brouwer, 1 Feb 1996
141da177e4SLinus Torvalds  *
151da177e4SLinus Torvalds  * Fixed do_loop_request() re-entrancy - Vincent.Renardias@waw.com Mar 20, 1997
161da177e4SLinus Torvalds  *
171da177e4SLinus Torvalds  * Added devfs support - Richard Gooch <rgooch@atnf.csiro.au> 16-Jan-1998
181da177e4SLinus Torvalds  *
191da177e4SLinus Torvalds  * Handle sparse backing files correctly - Kenn Humborg, Jun 28, 1998
201da177e4SLinus Torvalds  *
211da177e4SLinus Torvalds  * Loadable modules and other fixes by AK, 1998
221da177e4SLinus Torvalds  *
231da177e4SLinus Torvalds  * Make real block number available to downstream transfer functions, enables
241da177e4SLinus Torvalds  * CBC (and relatives) mode encryption requiring unique IVs per data block.
251da177e4SLinus Torvalds  * Reed H. Petty, rhp@draper.net
261da177e4SLinus Torvalds  *
271da177e4SLinus Torvalds  * Maximum number of loop devices now dynamic via max_loop module parameter.
281da177e4SLinus Torvalds  * Russell Kroll <rkroll@exploits.org> 19990701
291da177e4SLinus Torvalds  *
301da177e4SLinus Torvalds  * Maximum number of loop devices when compiled-in now selectable by passing
311da177e4SLinus Torvalds  * max_loop=<1-255> to the kernel on boot.
3296de0e25SJan Engelhardt  * Erik I. Bolsø, <eriki@himolde.no>, Oct 31, 1999
331da177e4SLinus Torvalds  *
341da177e4SLinus Torvalds  * Completely rewrite request handling to be make_request_fn style and
351da177e4SLinus Torvalds  * non blocking, pushing work to a helper thread. Lots of fixes from
361da177e4SLinus Torvalds  * Al Viro too.
371da177e4SLinus Torvalds  * Jens Axboe <axboe@suse.de>, Nov 2000
381da177e4SLinus Torvalds  *
391da177e4SLinus Torvalds  * Support up to 256 loop devices
401da177e4SLinus Torvalds  * Heinz Mauelshagen <mge@sistina.com>, Feb 2002
411da177e4SLinus Torvalds  *
421da177e4SLinus Torvalds  * Support for falling back on the write file operation when the address space
434e02ed4bSNick Piggin  * operations write_begin is not available on the backing filesystem.
441da177e4SLinus Torvalds  * Anton Altaparmakov, 16 Feb 2005
451da177e4SLinus Torvalds  *
461da177e4SLinus Torvalds  * Still To Fix:
471da177e4SLinus Torvalds  * - Advisory locking is ignored here.
481da177e4SLinus Torvalds  * - Should use an own CAP_* category instead of CAP_SYS_ADMIN
491da177e4SLinus Torvalds  *
501da177e4SLinus Torvalds  */
511da177e4SLinus Torvalds 
521da177e4SLinus Torvalds #include <linux/module.h>
531da177e4SLinus Torvalds #include <linux/moduleparam.h>
541da177e4SLinus Torvalds #include <linux/sched.h>
551da177e4SLinus Torvalds #include <linux/fs.h>
564ee60ec1SMatthew Wilcox (Oracle) #include <linux/pagemap.h>
571da177e4SLinus Torvalds #include <linux/file.h>
581da177e4SLinus Torvalds #include <linux/stat.h>
591da177e4SLinus Torvalds #include <linux/errno.h>
601da177e4SLinus Torvalds #include <linux/major.h>
611da177e4SLinus Torvalds #include <linux/wait.h>
621da177e4SLinus Torvalds #include <linux/blkdev.h>
631da177e4SLinus Torvalds #include <linux/blkpg.h>
641da177e4SLinus Torvalds #include <linux/init.h>
651da177e4SLinus Torvalds #include <linux/swap.h>
661da177e4SLinus Torvalds #include <linux/slab.h>
67863d5b82SDavid Howells #include <linux/compat.h>
681da177e4SLinus Torvalds #include <linux/suspend.h>
6983144186SRafael J. Wysocki #include <linux/freezer.h>
702a48fc0aSArnd Bergmann #include <linux/mutex.h>
711da177e4SLinus Torvalds #include <linux/writeback.h>
721da177e4SLinus Torvalds #include <linux/completion.h>
731da177e4SLinus Torvalds #include <linux/highmem.h>
74d6b29d7cSJens Axboe #include <linux/splice.h>
75ee862730SMilan Broz #include <linux/sysfs.h>
76770fe30aSKay Sievers #include <linux/miscdevice.h>
77dfaa2ef6SLukas Czerner #include <linux/falloc.h>
78283e7e5dSAl Viro #include <linux/uio.h>
79d9a08a9eSAdam Manzanares #include <linux/ioprio.h>
80db6638d7SDennis Zhou #include <linux/blk-cgroup.h>
81c74d40e8SDan Schatzberg #include <linux/sched/mm.h>
82d9a08a9eSAdam Manzanares 
8383a87611SAl Viro #include "loop.h"
841da177e4SLinus Torvalds 
857c0f6ba6SLinus Torvalds #include <linux/uaccess.h>
861da177e4SLinus Torvalds 
8787579e9bSDan Schatzberg #define LOOP_IDLE_WORKER_TIMEOUT (60 * HZ)
8887579e9bSDan Schatzberg 
8934dd82afSKay Sievers static DEFINE_IDR(loop_index_idr);
90310ca162STetsuo Handa static DEFINE_MUTEX(loop_ctl_mutex);
913ce6e1f6STetsuo Handa static DEFINE_MUTEX(loop_validate_mutex);
923ce6e1f6STetsuo Handa 
933ce6e1f6STetsuo Handa /**
943ce6e1f6STetsuo Handa  * loop_global_lock_killable() - take locks for safe loop_validate_file() test
953ce6e1f6STetsuo Handa  *
963ce6e1f6STetsuo Handa  * @lo: struct loop_device
973ce6e1f6STetsuo Handa  * @global: true if @lo is about to bind another "struct loop_device", false otherwise
983ce6e1f6STetsuo Handa  *
993ce6e1f6STetsuo Handa  * Returns 0 on success, -EINTR otherwise.
1003ce6e1f6STetsuo Handa  *
1013ce6e1f6STetsuo Handa  * Since loop_validate_file() traverses on other "struct loop_device" if
1023ce6e1f6STetsuo Handa  * is_loop_device() is true, we need a global lock for serializing concurrent
1033ce6e1f6STetsuo Handa  * loop_configure()/loop_change_fd()/__loop_clr_fd() calls.
1043ce6e1f6STetsuo Handa  */
1053ce6e1f6STetsuo Handa static int loop_global_lock_killable(struct loop_device *lo, bool global)
1063ce6e1f6STetsuo Handa {
1073ce6e1f6STetsuo Handa 	int err;
1083ce6e1f6STetsuo Handa 
1093ce6e1f6STetsuo Handa 	if (global) {
1103ce6e1f6STetsuo Handa 		err = mutex_lock_killable(&loop_validate_mutex);
1113ce6e1f6STetsuo Handa 		if (err)
1123ce6e1f6STetsuo Handa 			return err;
1133ce6e1f6STetsuo Handa 	}
1143ce6e1f6STetsuo Handa 	err = mutex_lock_killable(&lo->lo_mutex);
1153ce6e1f6STetsuo Handa 	if (err && global)
1163ce6e1f6STetsuo Handa 		mutex_unlock(&loop_validate_mutex);
1173ce6e1f6STetsuo Handa 	return err;
1183ce6e1f6STetsuo Handa }
1193ce6e1f6STetsuo Handa 
1203ce6e1f6STetsuo Handa /**
1213ce6e1f6STetsuo Handa  * loop_global_unlock() - release locks taken by loop_global_lock_killable()
1223ce6e1f6STetsuo Handa  *
1233ce6e1f6STetsuo Handa  * @lo: struct loop_device
1243ce6e1f6STetsuo Handa  * @global: true if @lo was about to bind another "struct loop_device", false otherwise
1253ce6e1f6STetsuo Handa  */
1263ce6e1f6STetsuo Handa static void loop_global_unlock(struct loop_device *lo, bool global)
1273ce6e1f6STetsuo Handa {
1283ce6e1f6STetsuo Handa 	mutex_unlock(&lo->lo_mutex);
1293ce6e1f6STetsuo Handa 	if (global)
1303ce6e1f6STetsuo Handa 		mutex_unlock(&loop_validate_mutex);
1313ce6e1f6STetsuo Handa }
1321da177e4SLinus Torvalds 
133476a4813SLaurent Vivier static int max_part;
134476a4813SLaurent Vivier static int part_shift;
135476a4813SLaurent Vivier 
1361da177e4SLinus Torvalds static int transfer_xor(struct loop_device *lo, int cmd,
1371da177e4SLinus Torvalds 			struct page *raw_page, unsigned raw_off,
1381da177e4SLinus Torvalds 			struct page *loop_page, unsigned loop_off,
1391da177e4SLinus Torvalds 			int size, sector_t real_block)
1401da177e4SLinus Torvalds {
141cfd8005cSCong Wang 	char *raw_buf = kmap_atomic(raw_page) + raw_off;
142cfd8005cSCong Wang 	char *loop_buf = kmap_atomic(loop_page) + loop_off;
1431da177e4SLinus Torvalds 	char *in, *out, *key;
1441da177e4SLinus Torvalds 	int i, keysize;
1451da177e4SLinus Torvalds 
1461da177e4SLinus Torvalds 	if (cmd == READ) {
1471da177e4SLinus Torvalds 		in = raw_buf;
1481da177e4SLinus Torvalds 		out = loop_buf;
1491da177e4SLinus Torvalds 	} else {
1501da177e4SLinus Torvalds 		in = loop_buf;
1511da177e4SLinus Torvalds 		out = raw_buf;
1521da177e4SLinus Torvalds 	}
1531da177e4SLinus Torvalds 
1541da177e4SLinus Torvalds 	key = lo->lo_encrypt_key;
1551da177e4SLinus Torvalds 	keysize = lo->lo_encrypt_key_size;
1561da177e4SLinus Torvalds 	for (i = 0; i < size; i++)
1571da177e4SLinus Torvalds 		*out++ = *in++ ^ key[(i & 511) % keysize];
1581da177e4SLinus Torvalds 
159cfd8005cSCong Wang 	kunmap_atomic(loop_buf);
160cfd8005cSCong Wang 	kunmap_atomic(raw_buf);
1611da177e4SLinus Torvalds 	cond_resched();
1621da177e4SLinus Torvalds 	return 0;
1631da177e4SLinus Torvalds }
1641da177e4SLinus Torvalds 
1651da177e4SLinus Torvalds static int xor_init(struct loop_device *lo, const struct loop_info64 *info)
1661da177e4SLinus Torvalds {
1671da177e4SLinus Torvalds 	if (unlikely(info->lo_encrypt_key_size <= 0))
1681da177e4SLinus Torvalds 		return -EINVAL;
1691da177e4SLinus Torvalds 	return 0;
1701da177e4SLinus Torvalds }
1711da177e4SLinus Torvalds 
1721da177e4SLinus Torvalds static struct loop_func_table none_funcs = {
1731da177e4SLinus Torvalds 	.number = LO_CRYPT_NONE,
1741da177e4SLinus Torvalds };
1751da177e4SLinus Torvalds 
1761da177e4SLinus Torvalds static struct loop_func_table xor_funcs = {
1771da177e4SLinus Torvalds 	.number = LO_CRYPT_XOR,
1781da177e4SLinus Torvalds 	.transfer = transfer_xor,
1791da177e4SLinus Torvalds 	.init = xor_init
1801da177e4SLinus Torvalds };
1811da177e4SLinus Torvalds 
1821da177e4SLinus Torvalds /* xfer_funcs[0] is special - its release function is never called */
1831da177e4SLinus Torvalds static struct loop_func_table *xfer_funcs[MAX_LO_CRYPT] = {
1841da177e4SLinus Torvalds 	&none_funcs,
1851da177e4SLinus Torvalds 	&xor_funcs
1861da177e4SLinus Torvalds };
1871da177e4SLinus Torvalds 
1887035b5dfSDmitry Monakhov static loff_t get_size(loff_t offset, loff_t sizelimit, struct file *file)
1891da177e4SLinus Torvalds {
190b7a1da69SGuo Chao 	loff_t loopsize;
1911da177e4SLinus Torvalds 
1921da177e4SLinus Torvalds 	/* Compute loopsize in bytes */
193b7a1da69SGuo Chao 	loopsize = i_size_read(file->f_mapping->host);
194b7a1da69SGuo Chao 	if (offset > 0)
195b7a1da69SGuo Chao 		loopsize -= offset;
196b7a1da69SGuo Chao 	/* offset is beyond i_size, weird but possible */
1977035b5dfSDmitry Monakhov 	if (loopsize < 0)
1987035b5dfSDmitry Monakhov 		return 0;
1991da177e4SLinus Torvalds 
2007035b5dfSDmitry Monakhov 	if (sizelimit > 0 && sizelimit < loopsize)
2017035b5dfSDmitry Monakhov 		loopsize = sizelimit;
2021da177e4SLinus Torvalds 	/*
2031da177e4SLinus Torvalds 	 * Unfortunately, if we want to do I/O on the device,
2041da177e4SLinus Torvalds 	 * the number of 512-byte sectors has to fit into a sector_t.
2051da177e4SLinus Torvalds 	 */
2061da177e4SLinus Torvalds 	return loopsize >> 9;
2071da177e4SLinus Torvalds }
2081da177e4SLinus Torvalds 
2097035b5dfSDmitry Monakhov static loff_t get_loop_size(struct loop_device *lo, struct file *file)
2101da177e4SLinus Torvalds {
2117035b5dfSDmitry Monakhov 	return get_size(lo->lo_offset, lo->lo_sizelimit, file);
2127035b5dfSDmitry Monakhov }
2137035b5dfSDmitry Monakhov 
2142e5ab5f3SMing Lei static void __loop_update_dio(struct loop_device *lo, bool dio)
2152e5ab5f3SMing Lei {
2162e5ab5f3SMing Lei 	struct file *file = lo->lo_backing_file;
2172e5ab5f3SMing Lei 	struct address_space *mapping = file->f_mapping;
2182e5ab5f3SMing Lei 	struct inode *inode = mapping->host;
2192e5ab5f3SMing Lei 	unsigned short sb_bsize = 0;
2202e5ab5f3SMing Lei 	unsigned dio_align = 0;
2212e5ab5f3SMing Lei 	bool use_dio;
2222e5ab5f3SMing Lei 
2232e5ab5f3SMing Lei 	if (inode->i_sb->s_bdev) {
2242e5ab5f3SMing Lei 		sb_bsize = bdev_logical_block_size(inode->i_sb->s_bdev);
2252e5ab5f3SMing Lei 		dio_align = sb_bsize - 1;
2262e5ab5f3SMing Lei 	}
2272e5ab5f3SMing Lei 
2282e5ab5f3SMing Lei 	/*
2292e5ab5f3SMing Lei 	 * We support direct I/O only if lo_offset is aligned with the
2302e5ab5f3SMing Lei 	 * logical I/O size of backing device, and the logical block
2312e5ab5f3SMing Lei 	 * size of loop is bigger than the backing device's and the loop
2322e5ab5f3SMing Lei 	 * needn't transform transfer.
2332e5ab5f3SMing Lei 	 *
2342e5ab5f3SMing Lei 	 * TODO: the above condition may be loosed in the future, and
2352e5ab5f3SMing Lei 	 * direct I/O may be switched runtime at that time because most
23689d790abSMasahiro Yamada 	 * of requests in sane applications should be PAGE_SIZE aligned
2372e5ab5f3SMing Lei 	 */
2382e5ab5f3SMing Lei 	if (dio) {
2392e5ab5f3SMing Lei 		if (queue_logical_block_size(lo->lo_queue) >= sb_bsize &&
2402e5ab5f3SMing Lei 				!(lo->lo_offset & dio_align) &&
2412e5ab5f3SMing Lei 				mapping->a_ops->direct_IO &&
2422e5ab5f3SMing Lei 				!lo->transfer)
2432e5ab5f3SMing Lei 			use_dio = true;
2442e5ab5f3SMing Lei 		else
2452e5ab5f3SMing Lei 			use_dio = false;
2462e5ab5f3SMing Lei 	} else {
2472e5ab5f3SMing Lei 		use_dio = false;
2482e5ab5f3SMing Lei 	}
2492e5ab5f3SMing Lei 
2502e5ab5f3SMing Lei 	if (lo->use_dio == use_dio)
2512e5ab5f3SMing Lei 		return;
2522e5ab5f3SMing Lei 
2532e5ab5f3SMing Lei 	/* flush dirty pages before changing direct IO */
2542e5ab5f3SMing Lei 	vfs_fsync(file, 0);
2552e5ab5f3SMing Lei 
2562e5ab5f3SMing Lei 	/*
2572e5ab5f3SMing Lei 	 * The flag of LO_FLAGS_DIRECT_IO is handled similarly with
2582e5ab5f3SMing Lei 	 * LO_FLAGS_READ_ONLY, both are set from kernel, and losetup
2592e5ab5f3SMing Lei 	 * will get updated by ioctl(LOOP_GET_STATUS)
2602e5ab5f3SMing Lei 	 */
2610fbcf579SMartijn Coenen 	if (lo->lo_state == Lo_bound)
2622e5ab5f3SMing Lei 		blk_mq_freeze_queue(lo->lo_queue);
2632e5ab5f3SMing Lei 	lo->use_dio = use_dio;
26440326d8aSShaohua Li 	if (use_dio) {
2658b904b5bSBart Van Assche 		blk_queue_flag_clear(QUEUE_FLAG_NOMERGES, lo->lo_queue);
2662e5ab5f3SMing Lei 		lo->lo_flags |= LO_FLAGS_DIRECT_IO;
26740326d8aSShaohua Li 	} else {
2688b904b5bSBart Van Assche 		blk_queue_flag_set(QUEUE_FLAG_NOMERGES, lo->lo_queue);
2692e5ab5f3SMing Lei 		lo->lo_flags &= ~LO_FLAGS_DIRECT_IO;
27040326d8aSShaohua Li 	}
2710fbcf579SMartijn Coenen 	if (lo->lo_state == Lo_bound)
2722e5ab5f3SMing Lei 		blk_mq_unfreeze_queue(lo->lo_queue);
2732e5ab5f3SMing Lei }
2742e5ab5f3SMing Lei 
2755795b6f5SMartijn Coenen /**
2763448914eSMartijn Coenen  * loop_validate_block_size() - validates the passed in block size
2773448914eSMartijn Coenen  * @bsize: size to validate
2783448914eSMartijn Coenen  */
2797035b5dfSDmitry Monakhov static int
2803448914eSMartijn Coenen loop_validate_block_size(unsigned short bsize)
2817035b5dfSDmitry Monakhov {
2823448914eSMartijn Coenen 	if (bsize < 512 || bsize > PAGE_SIZE || !is_power_of_2(bsize))
2833448914eSMartijn Coenen 		return -EINVAL;
2843448914eSMartijn Coenen 
2853448914eSMartijn Coenen 	return 0;
2863448914eSMartijn Coenen }
2873448914eSMartijn Coenen 
2883448914eSMartijn Coenen /**
2895795b6f5SMartijn Coenen  * loop_set_size() - sets device size and notifies userspace
2905795b6f5SMartijn Coenen  * @lo: struct loop_device to set the size for
2915795b6f5SMartijn Coenen  * @size: new size of the loop device
2925795b6f5SMartijn Coenen  *
2935795b6f5SMartijn Coenen  * Callers must validate that the size passed into this function fits into
2945795b6f5SMartijn Coenen  * a sector_t, eg using loop_validate_size()
2955795b6f5SMartijn Coenen  */
2965795b6f5SMartijn Coenen static void loop_set_size(struct loop_device *lo, loff_t size)
2975795b6f5SMartijn Coenen {
298449f4ec9SChristoph Hellwig 	if (!set_capacity_and_notify(lo->lo_disk, size))
2993b4f85d0SChristoph Hellwig 		kobject_uevent(&disk_to_dev(lo->lo_disk)->kobj, KOBJ_CHANGE);
3001da177e4SLinus Torvalds }
3011da177e4SLinus Torvalds 
3021da177e4SLinus Torvalds static inline int
3031da177e4SLinus Torvalds lo_do_transfer(struct loop_device *lo, int cmd,
3041da177e4SLinus Torvalds 	       struct page *rpage, unsigned roffs,
3051da177e4SLinus Torvalds 	       struct page *lpage, unsigned loffs,
3061da177e4SLinus Torvalds 	       int size, sector_t rblock)
3071da177e4SLinus Torvalds {
308aa4d8616SChristoph Hellwig 	int ret;
309aa4d8616SChristoph Hellwig 
310aa4d8616SChristoph Hellwig 	ret = lo->transfer(lo, cmd, rpage, roffs, lpage, loffs, size, rblock);
311aa4d8616SChristoph Hellwig 	if (likely(!ret))
3121da177e4SLinus Torvalds 		return 0;
3131da177e4SLinus Torvalds 
314aa4d8616SChristoph Hellwig 	printk_ratelimited(KERN_ERR
315aa4d8616SChristoph Hellwig 		"loop: Transfer error at byte offset %llu, length %i.\n",
316aa4d8616SChristoph Hellwig 		(unsigned long long)rblock << 9, size);
317aa4d8616SChristoph Hellwig 	return ret;
3181da177e4SLinus Torvalds }
3191da177e4SLinus Torvalds 
320aa4d8616SChristoph Hellwig static int lo_write_bvec(struct file *file, struct bio_vec *bvec, loff_t *ppos)
3211da177e4SLinus Torvalds {
322aa4d8616SChristoph Hellwig 	struct iov_iter i;
3231da177e4SLinus Torvalds 	ssize_t bw;
324283e7e5dSAl Viro 
325b6207430SChristoph Hellwig 	iov_iter_bvec(&i, WRITE, bvec, 1, bvec->bv_len);
3261da177e4SLinus Torvalds 
32703d95eb2SAl Viro 	file_start_write(file);
328abbb6589SChristoph Hellwig 	bw = vfs_iter_write(file, &i, ppos, 0);
32903d95eb2SAl Viro 	file_end_write(file);
330aa4d8616SChristoph Hellwig 
331aa4d8616SChristoph Hellwig 	if (likely(bw ==  bvec->bv_len))
3321da177e4SLinus Torvalds 		return 0;
333aa4d8616SChristoph Hellwig 
334aa4d8616SChristoph Hellwig 	printk_ratelimited(KERN_ERR
335aa4d8616SChristoph Hellwig 		"loop: Write error at byte offset %llu, length %i.\n",
336aa4d8616SChristoph Hellwig 		(unsigned long long)*ppos, bvec->bv_len);
3371da177e4SLinus Torvalds 	if (bw >= 0)
3381da177e4SLinus Torvalds 		bw = -EIO;
3391da177e4SLinus Torvalds 	return bw;
3401da177e4SLinus Torvalds }
3411da177e4SLinus Torvalds 
342aa4d8616SChristoph Hellwig static int lo_write_simple(struct loop_device *lo, struct request *rq,
343aa4d8616SChristoph Hellwig 		loff_t pos)
3441da177e4SLinus Torvalds {
345aa4d8616SChristoph Hellwig 	struct bio_vec bvec;
346aa4d8616SChristoph Hellwig 	struct req_iterator iter;
347aa4d8616SChristoph Hellwig 	int ret = 0;
348aa4d8616SChristoph Hellwig 
349aa4d8616SChristoph Hellwig 	rq_for_each_segment(bvec, rq, iter) {
350aa4d8616SChristoph Hellwig 		ret = lo_write_bvec(lo->lo_backing_file, &bvec, &pos);
351aa4d8616SChristoph Hellwig 		if (ret < 0)
352aa4d8616SChristoph Hellwig 			break;
3531da177e4SLinus Torvalds 		cond_resched();
3541da177e4SLinus Torvalds 	}
3551da177e4SLinus Torvalds 
356aa4d8616SChristoph Hellwig 	return ret;
357aa4d8616SChristoph Hellwig }
358aa4d8616SChristoph Hellwig 
359aa4d8616SChristoph Hellwig /*
360456be148SChristoph Hellwig  * This is the slow, transforming version that needs to double buffer the
361456be148SChristoph Hellwig  * data as it cannot do the transformations in place without having direct
362456be148SChristoph Hellwig  * access to the destination pages of the backing file.
3631da177e4SLinus Torvalds  */
364aa4d8616SChristoph Hellwig static int lo_write_transfer(struct loop_device *lo, struct request *rq,
365aa4d8616SChristoph Hellwig 		loff_t pos)
3661da177e4SLinus Torvalds {
367aa4d8616SChristoph Hellwig 	struct bio_vec bvec, b;
36830112013SMing Lei 	struct req_iterator iter;
369aa4d8616SChristoph Hellwig 	struct page *page;
3707988613bSKent Overstreet 	int ret = 0;
3711da177e4SLinus Torvalds 
372aa4d8616SChristoph Hellwig 	page = alloc_page(GFP_NOIO);
3731da177e4SLinus Torvalds 	if (unlikely(!page))
374aa4d8616SChristoph Hellwig 		return -ENOMEM;
375456be148SChristoph Hellwig 
37630112013SMing Lei 	rq_for_each_segment(bvec, rq, iter) {
377aa4d8616SChristoph Hellwig 		ret = lo_do_transfer(lo, WRITE, page, 0, bvec.bv_page,
378aa4d8616SChristoph Hellwig 			bvec.bv_offset, bvec.bv_len, pos >> 9);
379aa4d8616SChristoph Hellwig 		if (unlikely(ret))
380aa4d8616SChristoph Hellwig 			break;
381aa4d8616SChristoph Hellwig 
382aa4d8616SChristoph Hellwig 		b.bv_page = page;
383aa4d8616SChristoph Hellwig 		b.bv_offset = 0;
384aa4d8616SChristoph Hellwig 		b.bv_len = bvec.bv_len;
385aa4d8616SChristoph Hellwig 		ret = lo_write_bvec(lo->lo_backing_file, &b, &pos);
3861da177e4SLinus Torvalds 		if (ret < 0)
3871da177e4SLinus Torvalds 			break;
3881da177e4SLinus Torvalds 	}
389aa4d8616SChristoph Hellwig 
3901da177e4SLinus Torvalds 	__free_page(page);
3911da177e4SLinus Torvalds 	return ret;
3921da177e4SLinus Torvalds }
3931da177e4SLinus Torvalds 
394aa4d8616SChristoph Hellwig static int lo_read_simple(struct loop_device *lo, struct request *rq,
395aa4d8616SChristoph Hellwig 		loff_t pos)
3961da177e4SLinus Torvalds {
3977988613bSKent Overstreet 	struct bio_vec bvec;
39830112013SMing Lei 	struct req_iterator iter;
399aa4d8616SChristoph Hellwig 	struct iov_iter i;
400aa4d8616SChristoph Hellwig 	ssize_t len;
4011da177e4SLinus Torvalds 
40230112013SMing Lei 	rq_for_each_segment(bvec, rq, iter) {
403b6207430SChristoph Hellwig 		iov_iter_bvec(&i, READ, &bvec, 1, bvec.bv_len);
40418e9710eSChristoph Hellwig 		len = vfs_iter_read(lo->lo_backing_file, &i, &pos, 0);
405aa4d8616SChristoph Hellwig 		if (len < 0)
406aa4d8616SChristoph Hellwig 			return len;
407306df071SDave Young 
408aa4d8616SChristoph Hellwig 		flush_dcache_page(bvec.bv_page);
409aa4d8616SChristoph Hellwig 
410aa4d8616SChristoph Hellwig 		if (len != bvec.bv_len) {
41130112013SMing Lei 			struct bio *bio;
41230112013SMing Lei 
41330112013SMing Lei 			__rq_for_each_bio(bio, rq)
414306df071SDave Young 				zero_fill_bio(bio);
4151da177e4SLinus Torvalds 			break;
416306df071SDave Young 		}
417aa4d8616SChristoph Hellwig 		cond_resched();
4181da177e4SLinus Torvalds 	}
419aa4d8616SChristoph Hellwig 
420306df071SDave Young 	return 0;
4211da177e4SLinus Torvalds }
4221da177e4SLinus Torvalds 
423aa4d8616SChristoph Hellwig static int lo_read_transfer(struct loop_device *lo, struct request *rq,
424aa4d8616SChristoph Hellwig 		loff_t pos)
425aa4d8616SChristoph Hellwig {
426aa4d8616SChristoph Hellwig 	struct bio_vec bvec, b;
427aa4d8616SChristoph Hellwig 	struct req_iterator iter;
428aa4d8616SChristoph Hellwig 	struct iov_iter i;
429aa4d8616SChristoph Hellwig 	struct page *page;
430aa4d8616SChristoph Hellwig 	ssize_t len;
431aa4d8616SChristoph Hellwig 	int ret = 0;
432aa4d8616SChristoph Hellwig 
433aa4d8616SChristoph Hellwig 	page = alloc_page(GFP_NOIO);
434aa4d8616SChristoph Hellwig 	if (unlikely(!page))
435aa4d8616SChristoph Hellwig 		return -ENOMEM;
436aa4d8616SChristoph Hellwig 
437aa4d8616SChristoph Hellwig 	rq_for_each_segment(bvec, rq, iter) {
438aa4d8616SChristoph Hellwig 		loff_t offset = pos;
439aa4d8616SChristoph Hellwig 
440aa4d8616SChristoph Hellwig 		b.bv_page = page;
441aa4d8616SChristoph Hellwig 		b.bv_offset = 0;
442aa4d8616SChristoph Hellwig 		b.bv_len = bvec.bv_len;
443aa4d8616SChristoph Hellwig 
444b6207430SChristoph Hellwig 		iov_iter_bvec(&i, READ, &b, 1, b.bv_len);
44518e9710eSChristoph Hellwig 		len = vfs_iter_read(lo->lo_backing_file, &i, &pos, 0);
446aa4d8616SChristoph Hellwig 		if (len < 0) {
447aa4d8616SChristoph Hellwig 			ret = len;
448aa4d8616SChristoph Hellwig 			goto out_free_page;
449aa4d8616SChristoph Hellwig 		}
450aa4d8616SChristoph Hellwig 
451aa4d8616SChristoph Hellwig 		ret = lo_do_transfer(lo, READ, page, 0, bvec.bv_page,
452aa4d8616SChristoph Hellwig 			bvec.bv_offset, len, offset >> 9);
453aa4d8616SChristoph Hellwig 		if (ret)
454aa4d8616SChristoph Hellwig 			goto out_free_page;
455aa4d8616SChristoph Hellwig 
456aa4d8616SChristoph Hellwig 		flush_dcache_page(bvec.bv_page);
457aa4d8616SChristoph Hellwig 
458aa4d8616SChristoph Hellwig 		if (len != bvec.bv_len) {
459aa4d8616SChristoph Hellwig 			struct bio *bio;
460aa4d8616SChristoph Hellwig 
461aa4d8616SChristoph Hellwig 			__rq_for_each_bio(bio, rq)
462aa4d8616SChristoph Hellwig 				zero_fill_bio(bio);
463aa4d8616SChristoph Hellwig 			break;
464aa4d8616SChristoph Hellwig 		}
465aa4d8616SChristoph Hellwig 	}
466aa4d8616SChristoph Hellwig 
467aa4d8616SChristoph Hellwig 	ret = 0;
468aa4d8616SChristoph Hellwig out_free_page:
469aa4d8616SChristoph Hellwig 	__free_page(page);
470aa4d8616SChristoph Hellwig 	return ret;
471aa4d8616SChristoph Hellwig }
472aa4d8616SChristoph Hellwig 
473efcfec57SDarrick J. Wong static int lo_fallocate(struct loop_device *lo, struct request *rq, loff_t pos,
474efcfec57SDarrick J. Wong 			int mode)
475cf655d95SMing Lei {
476cf655d95SMing Lei 	/*
477efcfec57SDarrick J. Wong 	 * We use fallocate to manipulate the space mappings used by the image
478efcfec57SDarrick J. Wong 	 * a.k.a. discard/zerorange. However we do not support this if
479efcfec57SDarrick J. Wong 	 * encryption is enabled, because it may give an attacker useful
480efcfec57SDarrick J. Wong 	 * information.
481cf655d95SMing Lei 	 */
482cf655d95SMing Lei 	struct file *file = lo->lo_backing_file;
483c52abf56SEvan Green 	struct request_queue *q = lo->lo_queue;
484cf655d95SMing Lei 	int ret;
485cf655d95SMing Lei 
486efcfec57SDarrick J. Wong 	mode |= FALLOC_FL_KEEP_SIZE;
487efcfec57SDarrick J. Wong 
488c52abf56SEvan Green 	if (!blk_queue_discard(q)) {
489cf655d95SMing Lei 		ret = -EOPNOTSUPP;
490cf655d95SMing Lei 		goto out;
491cf655d95SMing Lei 	}
492cf655d95SMing Lei 
493cf655d95SMing Lei 	ret = file->f_op->fallocate(file, mode, pos, blk_rq_bytes(rq));
494cf655d95SMing Lei 	if (unlikely(ret && ret != -EINVAL && ret != -EOPNOTSUPP))
495cf655d95SMing Lei 		ret = -EIO;
496cf655d95SMing Lei  out:
497cf655d95SMing Lei 	return ret;
498cf655d95SMing Lei }
499cf655d95SMing Lei 
500cf655d95SMing Lei static int lo_req_flush(struct loop_device *lo, struct request *rq)
501cf655d95SMing Lei {
502cf655d95SMing Lei 	struct file *file = lo->lo_backing_file;
503cf655d95SMing Lei 	int ret = vfs_fsync(file, 0);
504cf655d95SMing Lei 	if (unlikely(ret && ret != -EINVAL))
505cf655d95SMing Lei 		ret = -EIO;
506cf655d95SMing Lei 
507cf655d95SMing Lei 	return ret;
508cf655d95SMing Lei }
509cf655d95SMing Lei 
510fe2cb290SChristoph Hellwig static void lo_complete_rq(struct request *rq)
511bc07c10aSMing Lei {
512fe2cb290SChristoph Hellwig 	struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
513f9de14bcSJens Axboe 	blk_status_t ret = BLK_STS_OK;
514bc07c10aSMing Lei 
515f9de14bcSJens Axboe 	if (!cmd->use_aio || cmd->ret < 0 || cmd->ret == blk_rq_bytes(rq) ||
516f9de14bcSJens Axboe 	    req_op(rq) != REQ_OP_READ) {
517f9de14bcSJens Axboe 		if (cmd->ret < 0)
5188cd55087SEvan Green 			ret = errno_to_blk_status(cmd->ret);
519f9de14bcSJens Axboe 		goto end_io;
520bc07c10aSMing Lei 	}
521fe2cb290SChristoph Hellwig 
522f9de14bcSJens Axboe 	/*
523f9de14bcSJens Axboe 	 * Short READ - if we got some data, advance our request and
524f9de14bcSJens Axboe 	 * retry it. If we got no data, end the rest with EIO.
525f9de14bcSJens Axboe 	 */
526f9de14bcSJens Axboe 	if (cmd->ret) {
527f9de14bcSJens Axboe 		blk_update_request(rq, BLK_STS_OK, cmd->ret);
528f9de14bcSJens Axboe 		cmd->ret = 0;
529f9de14bcSJens Axboe 		blk_mq_requeue_request(rq, true);
530f9de14bcSJens Axboe 	} else {
531f9de14bcSJens Axboe 		if (cmd->use_aio) {
532f9de14bcSJens Axboe 			struct bio *bio = rq->bio;
533f9de14bcSJens Axboe 
534f9de14bcSJens Axboe 			while (bio) {
535f9de14bcSJens Axboe 				zero_fill_bio(bio);
536f9de14bcSJens Axboe 				bio = bio->bi_next;
537f9de14bcSJens Axboe 			}
538f9de14bcSJens Axboe 		}
539f9de14bcSJens Axboe 		ret = BLK_STS_IOERR;
540f9de14bcSJens Axboe end_io:
541f9de14bcSJens Axboe 		blk_mq_end_request(rq, ret);
542f9de14bcSJens Axboe 	}
543bc07c10aSMing Lei }
544bc07c10aSMing Lei 
54592d77332SShaohua Li static void lo_rw_aio_do_completion(struct loop_cmd *cmd)
54692d77332SShaohua Li {
5471894e916SJens Axboe 	struct request *rq = blk_mq_rq_from_pdu(cmd);
5481894e916SJens Axboe 
54992d77332SShaohua Li 	if (!atomic_dec_and_test(&cmd->ref))
55092d77332SShaohua Li 		return;
55192d77332SShaohua Li 	kfree(cmd->bvec);
55292d77332SShaohua Li 	cmd->bvec = NULL;
55315f73f5bSChristoph Hellwig 	if (likely(!blk_should_fake_timeout(rq->q)))
5541894e916SJens Axboe 		blk_mq_complete_request(rq);
55592d77332SShaohua Li }
55692d77332SShaohua Li 
557*6b19b766SJens Axboe static void lo_rw_aio_complete(struct kiocb *iocb, long ret)
558bc07c10aSMing Lei {
559bc07c10aSMing Lei 	struct loop_cmd *cmd = container_of(iocb, struct loop_cmd, iocb);
560bc07c10aSMing Lei 
561fe2cb290SChristoph Hellwig 	cmd->ret = ret;
56292d77332SShaohua Li 	lo_rw_aio_do_completion(cmd);
563bc07c10aSMing Lei }
564bc07c10aSMing Lei 
565bc07c10aSMing Lei static int lo_rw_aio(struct loop_device *lo, struct loop_cmd *cmd,
566bc07c10aSMing Lei 		     loff_t pos, bool rw)
567bc07c10aSMing Lei {
568bc07c10aSMing Lei 	struct iov_iter iter;
56986af5952SMing Lei 	struct req_iterator rq_iter;
570bc07c10aSMing Lei 	struct bio_vec *bvec;
5711894e916SJens Axboe 	struct request *rq = blk_mq_rq_from_pdu(cmd);
57240326d8aSShaohua Li 	struct bio *bio = rq->bio;
573bc07c10aSMing Lei 	struct file *file = lo->lo_backing_file;
57486af5952SMing Lei 	struct bio_vec tmp;
57540326d8aSShaohua Li 	unsigned int offset;
57686af5952SMing Lei 	int nr_bvec = 0;
577bc07c10aSMing Lei 	int ret;
578bc07c10aSMing Lei 
57986af5952SMing Lei 	rq_for_each_bvec(tmp, rq, rq_iter)
58086af5952SMing Lei 		nr_bvec++;
581bc07c10aSMing Lei 
58286af5952SMing Lei 	if (rq->bio != rq->biotail) {
58386af5952SMing Lei 
58486af5952SMing Lei 		bvec = kmalloc_array(nr_bvec, sizeof(struct bio_vec),
5856da2ec56SKees Cook 				     GFP_NOIO);
58640326d8aSShaohua Li 		if (!bvec)
58740326d8aSShaohua Li 			return -EIO;
58840326d8aSShaohua Li 		cmd->bvec = bvec;
58940326d8aSShaohua Li 
590a7297a6aSMing Lei 		/*
59140326d8aSShaohua Li 		 * The bios of the request may be started from the middle of
59240326d8aSShaohua Li 		 * the 'bvec' because of bio splitting, so we can't directly
59386af5952SMing Lei 		 * copy bio->bi_iov_vec to new bvec. The rq_for_each_bvec
59440326d8aSShaohua Li 		 * API will take care of all details for us.
595a7297a6aSMing Lei 		 */
59686af5952SMing Lei 		rq_for_each_bvec(tmp, rq, rq_iter) {
59740326d8aSShaohua Li 			*bvec = tmp;
59840326d8aSShaohua Li 			bvec++;
59940326d8aSShaohua Li 		}
60040326d8aSShaohua Li 		bvec = cmd->bvec;
60140326d8aSShaohua Li 		offset = 0;
60240326d8aSShaohua Li 	} else {
60340326d8aSShaohua Li 		/*
60440326d8aSShaohua Li 		 * Same here, this bio may be started from the middle of the
60540326d8aSShaohua Li 		 * 'bvec' because of bio splitting, so offset from the bvec
60640326d8aSShaohua Li 		 * must be passed to iov iterator
60740326d8aSShaohua Li 		 */
60840326d8aSShaohua Li 		offset = bio->bi_iter.bi_bvec_done;
60940326d8aSShaohua Li 		bvec = __bvec_iter_bvec(bio->bi_io_vec, bio->bi_iter);
61040326d8aSShaohua Li 	}
61192d77332SShaohua Li 	atomic_set(&cmd->ref, 2);
61240326d8aSShaohua Li 
613b6207430SChristoph Hellwig 	iov_iter_bvec(&iter, rw, bvec, nr_bvec, blk_rq_bytes(rq));
61440326d8aSShaohua Li 	iter.iov_offset = offset;
615bc07c10aSMing Lei 
616bc07c10aSMing Lei 	cmd->iocb.ki_pos = pos;
617bc07c10aSMing Lei 	cmd->iocb.ki_filp = file;
618bc07c10aSMing Lei 	cmd->iocb.ki_complete = lo_rw_aio_complete;
619bc07c10aSMing Lei 	cmd->iocb.ki_flags = IOCB_DIRECT;
620d9a08a9eSAdam Manzanares 	cmd->iocb.ki_ioprio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_NONE, 0);
621bc07c10aSMing Lei 
622bc07c10aSMing Lei 	if (rw == WRITE)
623bb7462b6SMiklos Szeredi 		ret = call_write_iter(file, &cmd->iocb, &iter);
624bc07c10aSMing Lei 	else
625bb7462b6SMiklos Szeredi 		ret = call_read_iter(file, &cmd->iocb, &iter);
626bc07c10aSMing Lei 
62792d77332SShaohua Li 	lo_rw_aio_do_completion(cmd);
62892d77332SShaohua Li 
629bc07c10aSMing Lei 	if (ret != -EIOCBQUEUED)
630*6b19b766SJens Axboe 		lo_rw_aio_complete(&cmd->iocb, ret);
631bc07c10aSMing Lei 	return 0;
632bc07c10aSMing Lei }
633bc07c10aSMing Lei 
634c1c87c2bSChristoph Hellwig static int do_req_filebacked(struct loop_device *lo, struct request *rq)
635bc07c10aSMing Lei {
636bc07c10aSMing Lei 	struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
637c1c87c2bSChristoph Hellwig 	loff_t pos = ((loff_t) blk_rq_pos(rq) << 9) + lo->lo_offset;
638bc07c10aSMing Lei 
639bc07c10aSMing Lei 	/*
640bc07c10aSMing Lei 	 * lo_write_simple and lo_read_simple should have been covered
641bc07c10aSMing Lei 	 * by io submit style function like lo_rw_aio(), one blocker
642bc07c10aSMing Lei 	 * is that lo_read_simple() need to call flush_dcache_page after
643bc07c10aSMing Lei 	 * the page is written from kernel, and it isn't easy to handle
644bc07c10aSMing Lei 	 * this in io submit style function which submits all segments
645bc07c10aSMing Lei 	 * of the req at one time. And direct read IO doesn't need to
646bc07c10aSMing Lei 	 * run flush_dcache_page().
647bc07c10aSMing Lei 	 */
648c1c87c2bSChristoph Hellwig 	switch (req_op(rq)) {
649c1c87c2bSChristoph Hellwig 	case REQ_OP_FLUSH:
650c1c87c2bSChristoph Hellwig 		return lo_req_flush(lo, rq);
65119372e27SChristoph Hellwig 	case REQ_OP_WRITE_ZEROES:
652efcfec57SDarrick J. Wong 		/*
653efcfec57SDarrick J. Wong 		 * If the caller doesn't want deallocation, call zeroout to
654efcfec57SDarrick J. Wong 		 * write zeroes the range.  Otherwise, punch them out.
655efcfec57SDarrick J. Wong 		 */
656efcfec57SDarrick J. Wong 		return lo_fallocate(lo, rq, pos,
657efcfec57SDarrick J. Wong 			(rq->cmd_flags & REQ_NOUNMAP) ?
658efcfec57SDarrick J. Wong 				FALLOC_FL_ZERO_RANGE :
659efcfec57SDarrick J. Wong 				FALLOC_FL_PUNCH_HOLE);
660efcfec57SDarrick J. Wong 	case REQ_OP_DISCARD:
661efcfec57SDarrick J. Wong 		return lo_fallocate(lo, rq, pos, FALLOC_FL_PUNCH_HOLE);
662c1c87c2bSChristoph Hellwig 	case REQ_OP_WRITE:
663c1c87c2bSChristoph Hellwig 		if (lo->transfer)
664c1c87c2bSChristoph Hellwig 			return lo_write_transfer(lo, rq, pos);
665c1c87c2bSChristoph Hellwig 		else if (cmd->use_aio)
666c1c87c2bSChristoph Hellwig 			return lo_rw_aio(lo, cmd, pos, WRITE);
667c1c87c2bSChristoph Hellwig 		else
668bc07c10aSMing Lei 			return lo_write_simple(lo, rq, pos);
669c1c87c2bSChristoph Hellwig 	case REQ_OP_READ:
670c1c87c2bSChristoph Hellwig 		if (lo->transfer)
671c1c87c2bSChristoph Hellwig 			return lo_read_transfer(lo, rq, pos);
672c1c87c2bSChristoph Hellwig 		else if (cmd->use_aio)
673c1c87c2bSChristoph Hellwig 			return lo_rw_aio(lo, cmd, pos, READ);
674bc07c10aSMing Lei 		else
675bc07c10aSMing Lei 			return lo_read_simple(lo, rq, pos);
676c1c87c2bSChristoph Hellwig 	default:
677c1c87c2bSChristoph Hellwig 		WARN_ON_ONCE(1);
678c1c87c2bSChristoph Hellwig 		return -EIO;
679bc07c10aSMing Lei 	}
6801da177e4SLinus Torvalds }
6811da177e4SLinus Torvalds 
6822e5ab5f3SMing Lei static inline void loop_update_dio(struct loop_device *lo)
6832e5ab5f3SMing Lei {
684efbe3c24SIra Weiny 	__loop_update_dio(lo, (lo->lo_backing_file->f_flags & O_DIRECT) |
6852e5ab5f3SMing Lei 				lo->use_dio);
6862e5ab5f3SMing Lei }
6872e5ab5f3SMing Lei 
6880384264eSChristoph Hellwig static void loop_reread_partitions(struct loop_device *lo)
68906f0e9e6SMing Lei {
69006f0e9e6SMing Lei 	int rc;
69106f0e9e6SMing Lei 
6920384264eSChristoph Hellwig 	mutex_lock(&lo->lo_disk->open_mutex);
6930384264eSChristoph Hellwig 	rc = bdev_disk_changed(lo->lo_disk, false);
6940384264eSChristoph Hellwig 	mutex_unlock(&lo->lo_disk->open_mutex);
69506f0e9e6SMing Lei 	if (rc)
69606f0e9e6SMing Lei 		pr_warn("%s: partition scan of loop%d (%s) failed (rc=%d)\n",
69706f0e9e6SMing Lei 			__func__, lo->lo_number, lo->lo_file_name, rc);
69806f0e9e6SMing Lei }
69906f0e9e6SMing Lei 
700d2ac838eSTheodore Ts'o static inline int is_loop_device(struct file *file)
701d2ac838eSTheodore Ts'o {
702d2ac838eSTheodore Ts'o 	struct inode *i = file->f_mapping->host;
703d2ac838eSTheodore Ts'o 
7046f24784fSAl Viro 	return i && S_ISBLK(i->i_mode) && imajor(i) == LOOP_MAJOR;
705d2ac838eSTheodore Ts'o }
706d2ac838eSTheodore Ts'o 
707d2ac838eSTheodore Ts'o static int loop_validate_file(struct file *file, struct block_device *bdev)
708d2ac838eSTheodore Ts'o {
709d2ac838eSTheodore Ts'o 	struct inode	*inode = file->f_mapping->host;
710d2ac838eSTheodore Ts'o 	struct file	*f = file;
711d2ac838eSTheodore Ts'o 
712d2ac838eSTheodore Ts'o 	/* Avoid recursion */
713d2ac838eSTheodore Ts'o 	while (is_loop_device(f)) {
714d2ac838eSTheodore Ts'o 		struct loop_device *l;
715d2ac838eSTheodore Ts'o 
7163ce6e1f6STetsuo Handa 		lockdep_assert_held(&loop_validate_mutex);
7174e7b5671SChristoph Hellwig 		if (f->f_mapping->host->i_rdev == bdev->bd_dev)
718d2ac838eSTheodore Ts'o 			return -EBADF;
719d2ac838eSTheodore Ts'o 
7204e7b5671SChristoph Hellwig 		l = I_BDEV(f->f_mapping->host)->bd_disk->private_data;
7213ce6e1f6STetsuo Handa 		if (l->lo_state != Lo_bound)
722d2ac838eSTheodore Ts'o 			return -EINVAL;
7233ce6e1f6STetsuo Handa 		/* Order wrt setting lo->lo_backing_file in loop_configure(). */
7243ce6e1f6STetsuo Handa 		rmb();
725d2ac838eSTheodore Ts'o 		f = l->lo_backing_file;
726d2ac838eSTheodore Ts'o 	}
727d2ac838eSTheodore Ts'o 	if (!S_ISREG(inode->i_mode) && !S_ISBLK(inode->i_mode))
728d2ac838eSTheodore Ts'o 		return -EINVAL;
729d2ac838eSTheodore Ts'o 	return 0;
730d2ac838eSTheodore Ts'o }
731d2ac838eSTheodore Ts'o 
7321da177e4SLinus Torvalds /*
7331da177e4SLinus Torvalds  * loop_change_fd switched the backing store of a loopback device to
7341da177e4SLinus Torvalds  * a new file. This is useful for operating system installers to free up
7351da177e4SLinus Torvalds  * the original file and in High Availability environments to switch to
7361da177e4SLinus Torvalds  * an alternative location for the content in case of server meltdown.
7371da177e4SLinus Torvalds  * This can only work if the loop device is used read-only, and if the
7381da177e4SLinus Torvalds  * new backing store is the same size and type as the old backing store.
7391da177e4SLinus Torvalds  */
740bb214884SAl Viro static int loop_change_fd(struct loop_device *lo, struct block_device *bdev,
741bb214884SAl Viro 			  unsigned int arg)
7421da177e4SLinus Torvalds {
7433ce6e1f6STetsuo Handa 	struct file *file = fget(arg);
7443ce6e1f6STetsuo Handa 	struct file *old_file;
7451da177e4SLinus Torvalds 	int error;
74685b0a54aSJan Kara 	bool partscan;
7473ce6e1f6STetsuo Handa 	bool is_loop;
7481da177e4SLinus Torvalds 
7493ce6e1f6STetsuo Handa 	if (!file)
7503ce6e1f6STetsuo Handa 		return -EBADF;
7513ce6e1f6STetsuo Handa 	is_loop = is_loop_device(file);
7523ce6e1f6STetsuo Handa 	error = loop_global_lock_killable(lo, is_loop);
753c3710770SJan Kara 	if (error)
7543ce6e1f6STetsuo Handa 		goto out_putf;
7551da177e4SLinus Torvalds 	error = -ENXIO;
7561da177e4SLinus Torvalds 	if (lo->lo_state != Lo_bound)
7571dded9acSJan Kara 		goto out_err;
7581da177e4SLinus Torvalds 
7591da177e4SLinus Torvalds 	/* the loop device has to be read-only */
7601da177e4SLinus Torvalds 	error = -EINVAL;
7611da177e4SLinus Torvalds 	if (!(lo->lo_flags & LO_FLAGS_READ_ONLY))
7621dded9acSJan Kara 		goto out_err;
7631da177e4SLinus Torvalds 
764d2ac838eSTheodore Ts'o 	error = loop_validate_file(file, bdev);
765d2ac838eSTheodore Ts'o 	if (error)
7661dded9acSJan Kara 		goto out_err;
767d2ac838eSTheodore Ts'o 
7681da177e4SLinus Torvalds 	old_file = lo->lo_backing_file;
7691da177e4SLinus Torvalds 
7701da177e4SLinus Torvalds 	error = -EINVAL;
7711da177e4SLinus Torvalds 
7721da177e4SLinus Torvalds 	/* size of the new backing store needs to be the same */
7731da177e4SLinus Torvalds 	if (get_loop_size(lo, file) != get_loop_size(lo, old_file))
7741dded9acSJan Kara 		goto out_err;
7751da177e4SLinus Torvalds 
7761da177e4SLinus Torvalds 	/* and ... switch */
7779f65c489SMatteo Croce 	disk_force_media_change(lo->lo_disk, DISK_EVENT_MEDIA_CHANGE);
77843cade80SOmar Sandoval 	blk_mq_freeze_queue(lo->lo_queue);
77943cade80SOmar Sandoval 	mapping_set_gfp_mask(old_file->f_mapping, lo->old_gfp_mask);
78043cade80SOmar Sandoval 	lo->lo_backing_file = file;
78143cade80SOmar Sandoval 	lo->old_gfp_mask = mapping_gfp_mask(file->f_mapping);
78243cade80SOmar Sandoval 	mapping_set_gfp_mask(file->f_mapping,
78343cade80SOmar Sandoval 			     lo->old_gfp_mask & ~(__GFP_IO|__GFP_FS));
78443cade80SOmar Sandoval 	loop_update_dio(lo);
78543cade80SOmar Sandoval 	blk_mq_unfreeze_queue(lo->lo_queue);
78685b0a54aSJan Kara 	partscan = lo->lo_flags & LO_FLAGS_PARTSCAN;
7873ce6e1f6STetsuo Handa 	loop_global_unlock(lo, is_loop);
7883ce6e1f6STetsuo Handa 
7893ce6e1f6STetsuo Handa 	/*
7903ce6e1f6STetsuo Handa 	 * Flush loop_validate_file() before fput(), for l->lo_backing_file
7913ce6e1f6STetsuo Handa 	 * might be pointing at old_file which might be the last reference.
7923ce6e1f6STetsuo Handa 	 */
7933ce6e1f6STetsuo Handa 	if (!is_loop) {
7943ce6e1f6STetsuo Handa 		mutex_lock(&loop_validate_mutex);
7953ce6e1f6STetsuo Handa 		mutex_unlock(&loop_validate_mutex);
7963ce6e1f6STetsuo Handa 	}
7971dded9acSJan Kara 	/*
7986cc8e743SPavel Tatashin 	 * We must drop file reference outside of lo_mutex as dropping
799a8698707SChristoph Hellwig 	 * the file ref can take open_mutex which creates circular locking
8001dded9acSJan Kara 	 * dependency.
8011dded9acSJan Kara 	 */
8021dded9acSJan Kara 	fput(old_file);
80385b0a54aSJan Kara 	if (partscan)
8040384264eSChristoph Hellwig 		loop_reread_partitions(lo);
8051da177e4SLinus Torvalds 	return 0;
8061da177e4SLinus Torvalds 
8071dded9acSJan Kara out_err:
8083ce6e1f6STetsuo Handa 	loop_global_unlock(lo, is_loop);
8093ce6e1f6STetsuo Handa out_putf:
8101dded9acSJan Kara 	fput(file);
8111da177e4SLinus Torvalds 	return error;
8121da177e4SLinus Torvalds }
8131da177e4SLinus Torvalds 
814ee862730SMilan Broz /* loop sysfs attributes */
815ee862730SMilan Broz 
816ee862730SMilan Broz static ssize_t loop_attr_show(struct device *dev, char *page,
817ee862730SMilan Broz 			      ssize_t (*callback)(struct loop_device *, char *))
818ee862730SMilan Broz {
81934dd82afSKay Sievers 	struct gendisk *disk = dev_to_disk(dev);
82034dd82afSKay Sievers 	struct loop_device *lo = disk->private_data;
821ee862730SMilan Broz 
82234dd82afSKay Sievers 	return callback(lo, page);
823ee862730SMilan Broz }
824ee862730SMilan Broz 
825ee862730SMilan Broz #define LOOP_ATTR_RO(_name)						\
826ee862730SMilan Broz static ssize_t loop_attr_##_name##_show(struct loop_device *, char *);	\
827ee862730SMilan Broz static ssize_t loop_attr_do_show_##_name(struct device *d,		\
828ee862730SMilan Broz 				struct device_attribute *attr, char *b)	\
829ee862730SMilan Broz {									\
830ee862730SMilan Broz 	return loop_attr_show(d, b, loop_attr_##_name##_show);		\
831ee862730SMilan Broz }									\
832ee862730SMilan Broz static struct device_attribute loop_attr_##_name =			\
8335657a819SJoe Perches 	__ATTR(_name, 0444, loop_attr_do_show_##_name, NULL);
834ee862730SMilan Broz 
835ee862730SMilan Broz static ssize_t loop_attr_backing_file_show(struct loop_device *lo, char *buf)
836ee862730SMilan Broz {
837ee862730SMilan Broz 	ssize_t ret;
838ee862730SMilan Broz 	char *p = NULL;
839ee862730SMilan Broz 
84005eb0f25SKay Sievers 	spin_lock_irq(&lo->lo_lock);
841ee862730SMilan Broz 	if (lo->lo_backing_file)
8429bf39ab2SMiklos Szeredi 		p = file_path(lo->lo_backing_file, buf, PAGE_SIZE - 1);
84305eb0f25SKay Sievers 	spin_unlock_irq(&lo->lo_lock);
844ee862730SMilan Broz 
845ee862730SMilan Broz 	if (IS_ERR_OR_NULL(p))
846ee862730SMilan Broz 		ret = PTR_ERR(p);
847ee862730SMilan Broz 	else {
848ee862730SMilan Broz 		ret = strlen(p);
849ee862730SMilan Broz 		memmove(buf, p, ret);
850ee862730SMilan Broz 		buf[ret++] = '\n';
851ee862730SMilan Broz 		buf[ret] = 0;
852ee862730SMilan Broz 	}
853ee862730SMilan Broz 
854ee862730SMilan Broz 	return ret;
855ee862730SMilan Broz }
856ee862730SMilan Broz 
857ee862730SMilan Broz static ssize_t loop_attr_offset_show(struct loop_device *lo, char *buf)
858ee862730SMilan Broz {
859ee862730SMilan Broz 	return sprintf(buf, "%llu\n", (unsigned long long)lo->lo_offset);
860ee862730SMilan Broz }
861ee862730SMilan Broz 
862ee862730SMilan Broz static ssize_t loop_attr_sizelimit_show(struct loop_device *lo, char *buf)
863ee862730SMilan Broz {
864ee862730SMilan Broz 	return sprintf(buf, "%llu\n", (unsigned long long)lo->lo_sizelimit);
865ee862730SMilan Broz }
866ee862730SMilan Broz 
867ee862730SMilan Broz static ssize_t loop_attr_autoclear_show(struct loop_device *lo, char *buf)
868ee862730SMilan Broz {
869ee862730SMilan Broz 	int autoclear = (lo->lo_flags & LO_FLAGS_AUTOCLEAR);
870ee862730SMilan Broz 
871ee862730SMilan Broz 	return sprintf(buf, "%s\n", autoclear ? "1" : "0");
872ee862730SMilan Broz }
873ee862730SMilan Broz 
874e03c8dd1SKay Sievers static ssize_t loop_attr_partscan_show(struct loop_device *lo, char *buf)
875e03c8dd1SKay Sievers {
876e03c8dd1SKay Sievers 	int partscan = (lo->lo_flags & LO_FLAGS_PARTSCAN);
877e03c8dd1SKay Sievers 
878e03c8dd1SKay Sievers 	return sprintf(buf, "%s\n", partscan ? "1" : "0");
879e03c8dd1SKay Sievers }
880e03c8dd1SKay Sievers 
8812e5ab5f3SMing Lei static ssize_t loop_attr_dio_show(struct loop_device *lo, char *buf)
8822e5ab5f3SMing Lei {
8832e5ab5f3SMing Lei 	int dio = (lo->lo_flags & LO_FLAGS_DIRECT_IO);
8842e5ab5f3SMing Lei 
8852e5ab5f3SMing Lei 	return sprintf(buf, "%s\n", dio ? "1" : "0");
8862e5ab5f3SMing Lei }
8872e5ab5f3SMing Lei 
888ee862730SMilan Broz LOOP_ATTR_RO(backing_file);
889ee862730SMilan Broz LOOP_ATTR_RO(offset);
890ee862730SMilan Broz LOOP_ATTR_RO(sizelimit);
891ee862730SMilan Broz LOOP_ATTR_RO(autoclear);
892e03c8dd1SKay Sievers LOOP_ATTR_RO(partscan);
8932e5ab5f3SMing Lei LOOP_ATTR_RO(dio);
894ee862730SMilan Broz 
895ee862730SMilan Broz static struct attribute *loop_attrs[] = {
896ee862730SMilan Broz 	&loop_attr_backing_file.attr,
897ee862730SMilan Broz 	&loop_attr_offset.attr,
898ee862730SMilan Broz 	&loop_attr_sizelimit.attr,
899ee862730SMilan Broz 	&loop_attr_autoclear.attr,
900e03c8dd1SKay Sievers 	&loop_attr_partscan.attr,
9012e5ab5f3SMing Lei 	&loop_attr_dio.attr,
902ee862730SMilan Broz 	NULL,
903ee862730SMilan Broz };
904ee862730SMilan Broz 
905ee862730SMilan Broz static struct attribute_group loop_attribute_group = {
906ee862730SMilan Broz 	.name = "loop",
907ee862730SMilan Broz 	.attrs= loop_attrs,
908ee862730SMilan Broz };
909ee862730SMilan Broz 
910d3349b6bSTetsuo Handa static void loop_sysfs_init(struct loop_device *lo)
911ee862730SMilan Broz {
912d3349b6bSTetsuo Handa 	lo->sysfs_inited = !sysfs_create_group(&disk_to_dev(lo->lo_disk)->kobj,
913ee862730SMilan Broz 						&loop_attribute_group);
914ee862730SMilan Broz }
915ee862730SMilan Broz 
916ee862730SMilan Broz static void loop_sysfs_exit(struct loop_device *lo)
917ee862730SMilan Broz {
918d3349b6bSTetsuo Handa 	if (lo->sysfs_inited)
919ee862730SMilan Broz 		sysfs_remove_group(&disk_to_dev(lo->lo_disk)->kobj,
920ee862730SMilan Broz 				   &loop_attribute_group);
921ee862730SMilan Broz }
922ee862730SMilan Broz 
923dfaa2ef6SLukas Czerner static void loop_config_discard(struct loop_device *lo)
924dfaa2ef6SLukas Czerner {
925dfaa2ef6SLukas Czerner 	struct file *file = lo->lo_backing_file;
926dfaa2ef6SLukas Czerner 	struct inode *inode = file->f_mapping->host;
927dfaa2ef6SLukas Czerner 	struct request_queue *q = lo->lo_queue;
928bcb21c8cSMing Lei 	u32 granularity, max_discard_sectors;
929dfaa2ef6SLukas Czerner 
930dfaa2ef6SLukas Czerner 	/*
931c52abf56SEvan Green 	 * If the backing device is a block device, mirror its zeroing
932c52abf56SEvan Green 	 * capability. Set the discard sectors to the block device's zeroing
933c52abf56SEvan Green 	 * capabilities because loop discards result in blkdev_issue_zeroout(),
934c52abf56SEvan Green 	 * not blkdev_issue_discard(). This maintains consistent behavior with
935c52abf56SEvan Green 	 * file-backed loop devices: discarded regions read back as zero.
936c52abf56SEvan Green 	 */
937c52abf56SEvan Green 	if (S_ISBLK(inode->i_mode) && !lo->lo_encrypt_key_size) {
9384e7b5671SChristoph Hellwig 		struct request_queue *backingq = bdev_get_queue(I_BDEV(inode));
939c52abf56SEvan Green 
940bcb21c8cSMing Lei 		max_discard_sectors = backingq->limits.max_write_zeroes_sectors;
941bcb21c8cSMing Lei 		granularity = backingq->limits.discard_granularity ?:
942bcb21c8cSMing Lei 			queue_physical_block_size(backingq);
943c52abf56SEvan Green 
944c52abf56SEvan Green 	/*
945dfaa2ef6SLukas Czerner 	 * We use punch hole to reclaim the free space used by the
94612a64d2fSOlaf Hering 	 * image a.k.a. discard. However we do not support discard if
947dfaa2ef6SLukas Czerner 	 * encryption is enabled, because it may give an attacker
948dfaa2ef6SLukas Czerner 	 * useful information.
949dfaa2ef6SLukas Czerner 	 */
950c52abf56SEvan Green 	} else if (!file->f_op->fallocate || lo->lo_encrypt_key_size) {
951bcb21c8cSMing Lei 		max_discard_sectors = 0;
952bcb21c8cSMing Lei 		granularity = 0;
953dfaa2ef6SLukas Czerner 
954c52abf56SEvan Green 	} else {
955bcb21c8cSMing Lei 		max_discard_sectors = UINT_MAX >> 9;
956bcb21c8cSMing Lei 		granularity = inode->i_sb->s_blocksize;
957c52abf56SEvan Green 	}
958c52abf56SEvan Green 
959bcb21c8cSMing Lei 	if (max_discard_sectors) {
960bcb21c8cSMing Lei 		q->limits.discard_granularity = granularity;
961bcb21c8cSMing Lei 		blk_queue_max_discard_sectors(q, max_discard_sectors);
962bcb21c8cSMing Lei 		blk_queue_max_write_zeroes_sectors(q, max_discard_sectors);
9638b904b5bSBart Van Assche 		blk_queue_flag_set(QUEUE_FLAG_DISCARD, q);
964bcb21c8cSMing Lei 	} else {
965bcb21c8cSMing Lei 		q->limits.discard_granularity = 0;
966bcb21c8cSMing Lei 		blk_queue_max_discard_sectors(q, 0);
967bcb21c8cSMing Lei 		blk_queue_max_write_zeroes_sectors(q, 0);
968c52abf56SEvan Green 		blk_queue_flag_clear(QUEUE_FLAG_DISCARD, q);
969dfaa2ef6SLukas Czerner 	}
970bcb21c8cSMing Lei 	q->limits.discard_alignment = 0;
971bcb21c8cSMing Lei }
972dfaa2ef6SLukas Czerner 
97387579e9bSDan Schatzberg struct loop_worker {
97487579e9bSDan Schatzberg 	struct rb_node rb_node;
97587579e9bSDan Schatzberg 	struct work_struct work;
97687579e9bSDan Schatzberg 	struct list_head cmd_list;
97787579e9bSDan Schatzberg 	struct list_head idle_list;
97887579e9bSDan Schatzberg 	struct loop_device *lo;
979c74d40e8SDan Schatzberg 	struct cgroup_subsys_state *blkcg_css;
98087579e9bSDan Schatzberg 	unsigned long last_ran_at;
98187579e9bSDan Schatzberg };
982e03a3d7aSMing Lei 
98387579e9bSDan Schatzberg static void loop_workfn(struct work_struct *work);
98487579e9bSDan Schatzberg static void loop_rootcg_workfn(struct work_struct *work);
98587579e9bSDan Schatzberg static void loop_free_idle_workers(struct timer_list *timer);
986b2ee7d46SNeilBrown 
98787579e9bSDan Schatzberg #ifdef CONFIG_BLK_CGROUP
98887579e9bSDan Schatzberg static inline int queue_on_root_worker(struct cgroup_subsys_state *css)
989e03a3d7aSMing Lei {
99087579e9bSDan Schatzberg 	return !css || css == blkcg_root_css;
99187579e9bSDan Schatzberg }
99287579e9bSDan Schatzberg #else
99387579e9bSDan Schatzberg static inline int queue_on_root_worker(struct cgroup_subsys_state *css)
99487579e9bSDan Schatzberg {
99587579e9bSDan Schatzberg 	return !css;
99687579e9bSDan Schatzberg }
99787579e9bSDan Schatzberg #endif
99887579e9bSDan Schatzberg 
99987579e9bSDan Schatzberg static void loop_queue_work(struct loop_device *lo, struct loop_cmd *cmd)
100087579e9bSDan Schatzberg {
100187579e9bSDan Schatzberg 	struct rb_node **node = &(lo->worker_tree.rb_node), *parent = NULL;
100287579e9bSDan Schatzberg 	struct loop_worker *cur_worker, *worker = NULL;
100387579e9bSDan Schatzberg 	struct work_struct *work;
100487579e9bSDan Schatzberg 	struct list_head *cmd_list;
100587579e9bSDan Schatzberg 
100687579e9bSDan Schatzberg 	spin_lock_irq(&lo->lo_work_lock);
100787579e9bSDan Schatzberg 
1008c74d40e8SDan Schatzberg 	if (queue_on_root_worker(cmd->blkcg_css))
100987579e9bSDan Schatzberg 		goto queue_work;
101087579e9bSDan Schatzberg 
101187579e9bSDan Schatzberg 	node = &lo->worker_tree.rb_node;
101287579e9bSDan Schatzberg 
101387579e9bSDan Schatzberg 	while (*node) {
101487579e9bSDan Schatzberg 		parent = *node;
101587579e9bSDan Schatzberg 		cur_worker = container_of(*node, struct loop_worker, rb_node);
1016c74d40e8SDan Schatzberg 		if (cur_worker->blkcg_css == cmd->blkcg_css) {
101787579e9bSDan Schatzberg 			worker = cur_worker;
101887579e9bSDan Schatzberg 			break;
1019c74d40e8SDan Schatzberg 		} else if ((long)cur_worker->blkcg_css < (long)cmd->blkcg_css) {
102087579e9bSDan Schatzberg 			node = &(*node)->rb_left;
102187579e9bSDan Schatzberg 		} else {
102287579e9bSDan Schatzberg 			node = &(*node)->rb_right;
102387579e9bSDan Schatzberg 		}
102487579e9bSDan Schatzberg 	}
102587579e9bSDan Schatzberg 	if (worker)
102687579e9bSDan Schatzberg 		goto queue_work;
102787579e9bSDan Schatzberg 
102887579e9bSDan Schatzberg 	worker = kzalloc(sizeof(struct loop_worker), GFP_NOWAIT | __GFP_NOWARN);
102987579e9bSDan Schatzberg 	/*
103087579e9bSDan Schatzberg 	 * In the event we cannot allocate a worker, just queue on the
1031c74d40e8SDan Schatzberg 	 * rootcg worker and issue the I/O as the rootcg
103287579e9bSDan Schatzberg 	 */
1033c74d40e8SDan Schatzberg 	if (!worker) {
1034c74d40e8SDan Schatzberg 		cmd->blkcg_css = NULL;
1035c74d40e8SDan Schatzberg 		if (cmd->memcg_css)
1036c74d40e8SDan Schatzberg 			css_put(cmd->memcg_css);
1037c74d40e8SDan Schatzberg 		cmd->memcg_css = NULL;
103887579e9bSDan Schatzberg 		goto queue_work;
1039c74d40e8SDan Schatzberg 	}
104087579e9bSDan Schatzberg 
1041c74d40e8SDan Schatzberg 	worker->blkcg_css = cmd->blkcg_css;
1042c74d40e8SDan Schatzberg 	css_get(worker->blkcg_css);
104387579e9bSDan Schatzberg 	INIT_WORK(&worker->work, loop_workfn);
104487579e9bSDan Schatzberg 	INIT_LIST_HEAD(&worker->cmd_list);
104587579e9bSDan Schatzberg 	INIT_LIST_HEAD(&worker->idle_list);
104687579e9bSDan Schatzberg 	worker->lo = lo;
104787579e9bSDan Schatzberg 	rb_link_node(&worker->rb_node, parent, node);
104887579e9bSDan Schatzberg 	rb_insert_color(&worker->rb_node, &lo->worker_tree);
104987579e9bSDan Schatzberg queue_work:
105087579e9bSDan Schatzberg 	if (worker) {
105187579e9bSDan Schatzberg 		/*
105287579e9bSDan Schatzberg 		 * We need to remove from the idle list here while
105387579e9bSDan Schatzberg 		 * holding the lock so that the idle timer doesn't
105487579e9bSDan Schatzberg 		 * free the worker
105587579e9bSDan Schatzberg 		 */
105687579e9bSDan Schatzberg 		if (!list_empty(&worker->idle_list))
105787579e9bSDan Schatzberg 			list_del_init(&worker->idle_list);
105887579e9bSDan Schatzberg 		work = &worker->work;
105987579e9bSDan Schatzberg 		cmd_list = &worker->cmd_list;
106087579e9bSDan Schatzberg 	} else {
106187579e9bSDan Schatzberg 		work = &lo->rootcg_work;
106287579e9bSDan Schatzberg 		cmd_list = &lo->rootcg_cmd_list;
106387579e9bSDan Schatzberg 	}
106487579e9bSDan Schatzberg 	list_add_tail(&cmd->list_entry, cmd_list);
106587579e9bSDan Schatzberg 	queue_work(lo->workqueue, work);
106687579e9bSDan Schatzberg 	spin_unlock_irq(&lo->lo_work_lock);
1067e03a3d7aSMing Lei }
1068e03a3d7aSMing Lei 
106956a85fd8SHolger Hoffstätte static void loop_update_rotational(struct loop_device *lo)
107056a85fd8SHolger Hoffstätte {
107156a85fd8SHolger Hoffstätte 	struct file *file = lo->lo_backing_file;
107256a85fd8SHolger Hoffstätte 	struct inode *file_inode = file->f_mapping->host;
107356a85fd8SHolger Hoffstätte 	struct block_device *file_bdev = file_inode->i_sb->s_bdev;
107456a85fd8SHolger Hoffstätte 	struct request_queue *q = lo->lo_queue;
107556a85fd8SHolger Hoffstätte 	bool nonrot = true;
107656a85fd8SHolger Hoffstätte 
107756a85fd8SHolger Hoffstätte 	/* not all filesystems (e.g. tmpfs) have a sb->s_bdev */
107856a85fd8SHolger Hoffstätte 	if (file_bdev)
107956a85fd8SHolger Hoffstätte 		nonrot = blk_queue_nonrot(bdev_get_queue(file_bdev));
108056a85fd8SHolger Hoffstätte 
108156a85fd8SHolger Hoffstätte 	if (nonrot)
108256a85fd8SHolger Hoffstätte 		blk_queue_flag_set(QUEUE_FLAG_NONROT, q);
108356a85fd8SHolger Hoffstätte 	else
108456a85fd8SHolger Hoffstätte 		blk_queue_flag_clear(QUEUE_FLAG_NONROT, q);
108556a85fd8SHolger Hoffstätte }
108656a85fd8SHolger Hoffstätte 
10871da177e4SLinus Torvalds static int
10881da177e4SLinus Torvalds loop_release_xfer(struct loop_device *lo)
10891da177e4SLinus Torvalds {
10901da177e4SLinus Torvalds 	int err = 0;
10911da177e4SLinus Torvalds 	struct loop_func_table *xfer = lo->lo_encryption;
10921da177e4SLinus Torvalds 
10931da177e4SLinus Torvalds 	if (xfer) {
10941da177e4SLinus Torvalds 		if (xfer->release)
10951da177e4SLinus Torvalds 			err = xfer->release(lo);
10961da177e4SLinus Torvalds 		lo->transfer = NULL;
10971da177e4SLinus Torvalds 		lo->lo_encryption = NULL;
10981da177e4SLinus Torvalds 		module_put(xfer->owner);
10991da177e4SLinus Torvalds 	}
11001da177e4SLinus Torvalds 	return err;
11011da177e4SLinus Torvalds }
11021da177e4SLinus Torvalds 
11031da177e4SLinus Torvalds static int
11041da177e4SLinus Torvalds loop_init_xfer(struct loop_device *lo, struct loop_func_table *xfer,
11051da177e4SLinus Torvalds 	       const struct loop_info64 *i)
11061da177e4SLinus Torvalds {
11071da177e4SLinus Torvalds 	int err = 0;
11081da177e4SLinus Torvalds 
11091da177e4SLinus Torvalds 	if (xfer) {
11101da177e4SLinus Torvalds 		struct module *owner = xfer->owner;
11111da177e4SLinus Torvalds 
11121da177e4SLinus Torvalds 		if (!try_module_get(owner))
11131da177e4SLinus Torvalds 			return -EINVAL;
11141da177e4SLinus Torvalds 		if (xfer->init)
11151da177e4SLinus Torvalds 			err = xfer->init(lo, i);
11161da177e4SLinus Torvalds 		if (err)
11171da177e4SLinus Torvalds 			module_put(owner);
11181da177e4SLinus Torvalds 		else
11191da177e4SLinus Torvalds 			lo->lo_encryption = xfer;
11201da177e4SLinus Torvalds 	}
11211da177e4SLinus Torvalds 	return err;
11221da177e4SLinus Torvalds }
11231da177e4SLinus Torvalds 
112462ab466cSMartijn Coenen /**
112562ab466cSMartijn Coenen  * loop_set_status_from_info - configure device from loop_info
112662ab466cSMartijn Coenen  * @lo: struct loop_device to configure
112762ab466cSMartijn Coenen  * @info: struct loop_info64 to configure the device with
112862ab466cSMartijn Coenen  *
112962ab466cSMartijn Coenen  * Configures the loop device parameters according to the passed
113062ab466cSMartijn Coenen  * in loop_info64 configuration.
113162ab466cSMartijn Coenen  */
113262ab466cSMartijn Coenen static int
113362ab466cSMartijn Coenen loop_set_status_from_info(struct loop_device *lo,
113462ab466cSMartijn Coenen 			  const struct loop_info64 *info)
113562ab466cSMartijn Coenen {
113662ab466cSMartijn Coenen 	int err;
113762ab466cSMartijn Coenen 	struct loop_func_table *xfer;
113862ab466cSMartijn Coenen 	kuid_t uid = current_uid();
113962ab466cSMartijn Coenen 
114062ab466cSMartijn Coenen 	if ((unsigned int) info->lo_encrypt_key_size > LO_KEY_SIZE)
114162ab466cSMartijn Coenen 		return -EINVAL;
114262ab466cSMartijn Coenen 
114362ab466cSMartijn Coenen 	err = loop_release_xfer(lo);
114462ab466cSMartijn Coenen 	if (err)
114562ab466cSMartijn Coenen 		return err;
114662ab466cSMartijn Coenen 
114762ab466cSMartijn Coenen 	if (info->lo_encrypt_type) {
114862ab466cSMartijn Coenen 		unsigned int type = info->lo_encrypt_type;
114962ab466cSMartijn Coenen 
115062ab466cSMartijn Coenen 		if (type >= MAX_LO_CRYPT)
115162ab466cSMartijn Coenen 			return -EINVAL;
115262ab466cSMartijn Coenen 		xfer = xfer_funcs[type];
115362ab466cSMartijn Coenen 		if (xfer == NULL)
115462ab466cSMartijn Coenen 			return -EINVAL;
115562ab466cSMartijn Coenen 	} else
115662ab466cSMartijn Coenen 		xfer = NULL;
115762ab466cSMartijn Coenen 
115862ab466cSMartijn Coenen 	err = loop_init_xfer(lo, xfer, info);
115962ab466cSMartijn Coenen 	if (err)
116062ab466cSMartijn Coenen 		return err;
116162ab466cSMartijn Coenen 
116262ab466cSMartijn Coenen 	lo->lo_offset = info->lo_offset;
116362ab466cSMartijn Coenen 	lo->lo_sizelimit = info->lo_sizelimit;
116462ab466cSMartijn Coenen 	memcpy(lo->lo_file_name, info->lo_file_name, LO_NAME_SIZE);
116562ab466cSMartijn Coenen 	memcpy(lo->lo_crypt_name, info->lo_crypt_name, LO_NAME_SIZE);
116662ab466cSMartijn Coenen 	lo->lo_file_name[LO_NAME_SIZE-1] = 0;
116762ab466cSMartijn Coenen 	lo->lo_crypt_name[LO_NAME_SIZE-1] = 0;
116862ab466cSMartijn Coenen 
116962ab466cSMartijn Coenen 	if (!xfer)
117062ab466cSMartijn Coenen 		xfer = &none_funcs;
117162ab466cSMartijn Coenen 	lo->transfer = xfer->transfer;
117262ab466cSMartijn Coenen 	lo->ioctl = xfer->ioctl;
117362ab466cSMartijn Coenen 
1174faf1d254SMartijn Coenen 	lo->lo_flags = info->lo_flags;
117562ab466cSMartijn Coenen 
117662ab466cSMartijn Coenen 	lo->lo_encrypt_key_size = info->lo_encrypt_key_size;
117762ab466cSMartijn Coenen 	lo->lo_init[0] = info->lo_init[0];
117862ab466cSMartijn Coenen 	lo->lo_init[1] = info->lo_init[1];
117962ab466cSMartijn Coenen 	if (info->lo_encrypt_key_size) {
118062ab466cSMartijn Coenen 		memcpy(lo->lo_encrypt_key, info->lo_encrypt_key,
118162ab466cSMartijn Coenen 		       info->lo_encrypt_key_size);
118262ab466cSMartijn Coenen 		lo->lo_key_owner = uid;
118362ab466cSMartijn Coenen 	}
118462ab466cSMartijn Coenen 
118562ab466cSMartijn Coenen 	return 0;
118662ab466cSMartijn Coenen }
118762ab466cSMartijn Coenen 
11883448914eSMartijn Coenen static int loop_configure(struct loop_device *lo, fmode_t mode,
11893448914eSMartijn Coenen 			  struct block_device *bdev,
11903448914eSMartijn Coenen 			  const struct loop_config *config)
11911da177e4SLinus Torvalds {
11923ce6e1f6STetsuo Handa 	struct file *file = fget(config->fd);
11931da177e4SLinus Torvalds 	struct inode *inode;
11941da177e4SLinus Torvalds 	struct address_space *mapping;
11951da177e4SLinus Torvalds 	int error;
11961da177e4SLinus Torvalds 	loff_t size;
11971da177e4SLinus Torvalds 	bool partscan;
11983448914eSMartijn Coenen 	unsigned short bsize;
11993ce6e1f6STetsuo Handa 	bool is_loop;
12003ce6e1f6STetsuo Handa 
12013ce6e1f6STetsuo Handa 	if (!file)
12023ce6e1f6STetsuo Handa 		return -EBADF;
12033ce6e1f6STetsuo Handa 	is_loop = is_loop_device(file);
12041da177e4SLinus Torvalds 
12051da177e4SLinus Torvalds 	/* This is safe, since we have a reference from open(). */
12061da177e4SLinus Torvalds 	__module_get(THIS_MODULE);
12071da177e4SLinus Torvalds 
12081da177e4SLinus Torvalds 	/*
12091da177e4SLinus Torvalds 	 * If we don't hold exclusive handle for the device, upgrade to it
12101da177e4SLinus Torvalds 	 * here to avoid changing device under exclusive owner.
12111da177e4SLinus Torvalds 	 */
12121da177e4SLinus Torvalds 	if (!(mode & FMODE_EXCL)) {
121337c3fc9aSChristoph Hellwig 		error = bd_prepare_to_claim(bdev, loop_configure);
1214ecbe6bc0SChristoph Hellwig 		if (error)
12151da177e4SLinus Torvalds 			goto out_putf;
12161da177e4SLinus Torvalds 	}
12171da177e4SLinus Torvalds 
12183ce6e1f6STetsuo Handa 	error = loop_global_lock_killable(lo, is_loop);
12191da177e4SLinus Torvalds 	if (error)
12201da177e4SLinus Torvalds 		goto out_bdev;
12211da177e4SLinus Torvalds 
12221da177e4SLinus Torvalds 	error = -EBUSY;
12231da177e4SLinus Torvalds 	if (lo->lo_state != Lo_unbound)
12241da177e4SLinus Torvalds 		goto out_unlock;
12251da177e4SLinus Torvalds 
12261da177e4SLinus Torvalds 	error = loop_validate_file(file, bdev);
12271da177e4SLinus Torvalds 	if (error)
12281da177e4SLinus Torvalds 		goto out_unlock;
12291da177e4SLinus Torvalds 
12301da177e4SLinus Torvalds 	mapping = file->f_mapping;
12311da177e4SLinus Torvalds 	inode = mapping->host;
12321da177e4SLinus Torvalds 
12333448914eSMartijn Coenen 	if ((config->info.lo_flags & ~LOOP_CONFIGURE_SETTABLE_FLAGS) != 0) {
12343448914eSMartijn Coenen 		error = -EINVAL;
12353448914eSMartijn Coenen 		goto out_unlock;
12363448914eSMartijn Coenen 	}
12373448914eSMartijn Coenen 
12383448914eSMartijn Coenen 	if (config->block_size) {
12393448914eSMartijn Coenen 		error = loop_validate_block_size(config->block_size);
12403448914eSMartijn Coenen 		if (error)
12413448914eSMartijn Coenen 			goto out_unlock;
12423448914eSMartijn Coenen 	}
12433448914eSMartijn Coenen 
12443448914eSMartijn Coenen 	error = loop_set_status_from_info(lo, &config->info);
12453448914eSMartijn Coenen 	if (error)
12463448914eSMartijn Coenen 		goto out_unlock;
12473448914eSMartijn Coenen 
12481da177e4SLinus Torvalds 	if (!(file->f_mode & FMODE_WRITE) || !(mode & FMODE_WRITE) ||
12491da177e4SLinus Torvalds 	    !file->f_op->write_iter)
12503448914eSMartijn Coenen 		lo->lo_flags |= LO_FLAGS_READ_ONLY;
1251083a6a50SMartijn Coenen 
125287579e9bSDan Schatzberg 	lo->workqueue = alloc_workqueue("loop%d",
125387579e9bSDan Schatzberg 					WQ_UNBOUND | WQ_FREEZABLE,
125487579e9bSDan Schatzberg 					0,
125587579e9bSDan Schatzberg 					lo->lo_number);
125687579e9bSDan Schatzberg 	if (!lo->workqueue) {
125787579e9bSDan Schatzberg 		error = -ENOMEM;
12581da177e4SLinus Torvalds 		goto out_unlock;
125987579e9bSDan Schatzberg 	}
12601da177e4SLinus Torvalds 
12619f65c489SMatteo Croce 	disk_force_media_change(lo->lo_disk, DISK_EVENT_MEDIA_CHANGE);
12627a2f0ce1SChristoph Hellwig 	set_disk_ro(lo->lo_disk, (lo->lo_flags & LO_FLAGS_READ_ONLY) != 0);
12631da177e4SLinus Torvalds 
126487579e9bSDan Schatzberg 	INIT_WORK(&lo->rootcg_work, loop_rootcg_workfn);
126587579e9bSDan Schatzberg 	INIT_LIST_HEAD(&lo->rootcg_cmd_list);
126687579e9bSDan Schatzberg 	INIT_LIST_HEAD(&lo->idle_worker_list);
126787579e9bSDan Schatzberg 	lo->worker_tree = RB_ROOT;
126887579e9bSDan Schatzberg 	timer_setup(&lo->timer, loop_free_idle_workers,
126987579e9bSDan Schatzberg 		TIMER_DEFERRABLE);
12703448914eSMartijn Coenen 	lo->use_dio = lo->lo_flags & LO_FLAGS_DIRECT_IO;
12711da177e4SLinus Torvalds 	lo->lo_device = bdev;
12721da177e4SLinus Torvalds 	lo->lo_backing_file = file;
12731da177e4SLinus Torvalds 	lo->old_gfp_mask = mapping_gfp_mask(mapping);
12741da177e4SLinus Torvalds 	mapping_set_gfp_mask(mapping, lo->old_gfp_mask & ~(__GFP_IO|__GFP_FS));
12751da177e4SLinus Torvalds 
12763448914eSMartijn Coenen 	if (!(lo->lo_flags & LO_FLAGS_READ_ONLY) && file->f_op->fsync)
12771da177e4SLinus Torvalds 		blk_queue_write_cache(lo->lo_queue, true, false);
12781da177e4SLinus Torvalds 
12793448914eSMartijn Coenen 	if (config->block_size)
12803448914eSMartijn Coenen 		bsize = config->block_size;
128196ed320dSLinus Torvalds 	else if ((lo->lo_backing_file->f_flags & O_DIRECT) && inode->i_sb->s_bdev)
12821da177e4SLinus Torvalds 		/* In case of direct I/O, match underlying block size */
12833448914eSMartijn Coenen 		bsize = bdev_logical_block_size(inode->i_sb->s_bdev);
12843448914eSMartijn Coenen 	else
12853448914eSMartijn Coenen 		bsize = 512;
12861da177e4SLinus Torvalds 
12871da177e4SLinus Torvalds 	blk_queue_logical_block_size(lo->lo_queue, bsize);
12881da177e4SLinus Torvalds 	blk_queue_physical_block_size(lo->lo_queue, bsize);
12891da177e4SLinus Torvalds 	blk_queue_io_min(lo->lo_queue, bsize);
12901da177e4SLinus Torvalds 
12912b9ac22bSKristian Klausen 	loop_config_discard(lo);
12921da177e4SLinus Torvalds 	loop_update_rotational(lo);
12931da177e4SLinus Torvalds 	loop_update_dio(lo);
12941da177e4SLinus Torvalds 	loop_sysfs_init(lo);
129579e5dc59SMartijn Coenen 
129679e5dc59SMartijn Coenen 	size = get_loop_size(lo, file);
12975795b6f5SMartijn Coenen 	loop_set_size(lo, size);
12981da177e4SLinus Torvalds 
12993ce6e1f6STetsuo Handa 	/* Order wrt reading lo_state in loop_validate_file(). */
13003ce6e1f6STetsuo Handa 	wmb();
13013ce6e1f6STetsuo Handa 
13021da177e4SLinus Torvalds 	lo->lo_state = Lo_bound;
13031da177e4SLinus Torvalds 	if (part_shift)
13041da177e4SLinus Torvalds 		lo->lo_flags |= LO_FLAGS_PARTSCAN;
13051da177e4SLinus Torvalds 	partscan = lo->lo_flags & LO_FLAGS_PARTSCAN;
1306fe6a8fc5SLennart Poettering 	if (partscan)
1307fe6a8fc5SLennart Poettering 		lo->lo_disk->flags &= ~GENHD_FL_NO_PART_SCAN;
13081da177e4SLinus Torvalds 
13093ce6e1f6STetsuo Handa 	loop_global_unlock(lo, is_loop);
13101da177e4SLinus Torvalds 	if (partscan)
13110384264eSChristoph Hellwig 		loop_reread_partitions(lo);
131237c3fc9aSChristoph Hellwig 	if (!(mode & FMODE_EXCL))
131337c3fc9aSChristoph Hellwig 		bd_abort_claiming(bdev, loop_configure);
13141da177e4SLinus Torvalds 	return 0;
13151da177e4SLinus Torvalds 
13161da177e4SLinus Torvalds out_unlock:
13173ce6e1f6STetsuo Handa 	loop_global_unlock(lo, is_loop);
13181da177e4SLinus Torvalds out_bdev:
131937c3fc9aSChristoph Hellwig 	if (!(mode & FMODE_EXCL))
132037c3fc9aSChristoph Hellwig 		bd_abort_claiming(bdev, loop_configure);
13211da177e4SLinus Torvalds out_putf:
13221da177e4SLinus Torvalds 	fput(file);
13231da177e4SLinus Torvalds 	/* This is safe: open() is still holding a reference. */
13241da177e4SLinus Torvalds 	module_put(THIS_MODULE);
13251da177e4SLinus Torvalds 	return error;
13261da177e4SLinus Torvalds }
13271da177e4SLinus Torvalds 
13280da03cabSJan Kara static int __loop_clr_fd(struct loop_device *lo, bool release)
13291da177e4SLinus Torvalds {
13307ccd0791SJan Kara 	struct file *filp = NULL;
1331b4e3ca1aSAl Viro 	gfp_t gfp = lo->old_gfp_mask;
13324c823cc3SAyan George 	struct block_device *bdev = lo->lo_device;
13337ccd0791SJan Kara 	int err = 0;
13340da03cabSJan Kara 	bool partscan = false;
13350da03cabSJan Kara 	int lo_number;
133687579e9bSDan Schatzberg 	struct loop_worker *pos, *worker;
13371da177e4SLinus Torvalds 
13383ce6e1f6STetsuo Handa 	/*
13393ce6e1f6STetsuo Handa 	 * Flush loop_configure() and loop_change_fd(). It is acceptable for
13403ce6e1f6STetsuo Handa 	 * loop_validate_file() to succeed, for actual clear operation has not
13413ce6e1f6STetsuo Handa 	 * started yet.
13423ce6e1f6STetsuo Handa 	 */
13433ce6e1f6STetsuo Handa 	mutex_lock(&loop_validate_mutex);
13443ce6e1f6STetsuo Handa 	mutex_unlock(&loop_validate_mutex);
13453ce6e1f6STetsuo Handa 	/*
13463ce6e1f6STetsuo Handa 	 * loop_validate_file() now fails because l->lo_state != Lo_bound
13473ce6e1f6STetsuo Handa 	 * became visible.
13483ce6e1f6STetsuo Handa 	 */
13493ce6e1f6STetsuo Handa 
13506cc8e743SPavel Tatashin 	mutex_lock(&lo->lo_mutex);
13517ccd0791SJan Kara 	if (WARN_ON_ONCE(lo->lo_state != Lo_rundown)) {
13527ccd0791SJan Kara 		err = -ENXIO;
13537ccd0791SJan Kara 		goto out_unlock;
13547ccd0791SJan Kara 	}
13551da177e4SLinus Torvalds 
13567ccd0791SJan Kara 	filp = lo->lo_backing_file;
13577ccd0791SJan Kara 	if (filp == NULL) {
13587ccd0791SJan Kara 		err = -EINVAL;
13597ccd0791SJan Kara 		goto out_unlock;
13607ccd0791SJan Kara 	}
13611da177e4SLinus Torvalds 
13624ceddce5SMauricio Faria de Oliveira 	if (test_bit(QUEUE_FLAG_WC, &lo->lo_queue->queue_flags))
13634ceddce5SMauricio Faria de Oliveira 		blk_queue_write_cache(lo->lo_queue, false, false);
13644ceddce5SMauricio Faria de Oliveira 
1365f8933667SMing Lei 	/* freeze request queue during the transition */
1366f8933667SMing Lei 	blk_mq_freeze_queue(lo->lo_queue);
1367f8933667SMing Lei 
136887579e9bSDan Schatzberg 	destroy_workqueue(lo->workqueue);
136987579e9bSDan Schatzberg 	spin_lock_irq(&lo->lo_work_lock);
137087579e9bSDan Schatzberg 	list_for_each_entry_safe(worker, pos, &lo->idle_worker_list,
137187579e9bSDan Schatzberg 				idle_list) {
137287579e9bSDan Schatzberg 		list_del(&worker->idle_list);
137387579e9bSDan Schatzberg 		rb_erase(&worker->rb_node, &lo->worker_tree);
1374c74d40e8SDan Schatzberg 		css_put(worker->blkcg_css);
137587579e9bSDan Schatzberg 		kfree(worker);
137687579e9bSDan Schatzberg 	}
137787579e9bSDan Schatzberg 	spin_unlock_irq(&lo->lo_work_lock);
137887579e9bSDan Schatzberg 	del_timer_sync(&lo->timer);
137987579e9bSDan Schatzberg 
13801da177e4SLinus Torvalds 	spin_lock_irq(&lo->lo_lock);
13811da177e4SLinus Torvalds 	lo->lo_backing_file = NULL;
138205eb0f25SKay Sievers 	spin_unlock_irq(&lo->lo_lock);
13831da177e4SLinus Torvalds 
13841da177e4SLinus Torvalds 	loop_release_xfer(lo);
13851da177e4SLinus Torvalds 	lo->transfer = NULL;
13861da177e4SLinus Torvalds 	lo->ioctl = NULL;
13871da177e4SLinus Torvalds 	lo->lo_device = NULL;
13881da177e4SLinus Torvalds 	lo->lo_encryption = NULL;
13891da177e4SLinus Torvalds 	lo->lo_offset = 0;
13901da177e4SLinus Torvalds 	lo->lo_sizelimit = 0;
13911da177e4SLinus Torvalds 	lo->lo_encrypt_key_size = 0;
13921da177e4SLinus Torvalds 	memset(lo->lo_encrypt_key, 0, LO_KEY_SIZE);
13931da177e4SLinus Torvalds 	memset(lo->lo_crypt_name, 0, LO_NAME_SIZE);
13941da177e4SLinus Torvalds 	memset(lo->lo_file_name, 0, LO_NAME_SIZE);
139589e4fdecSOmar Sandoval 	blk_queue_logical_block_size(lo->lo_queue, 512);
1396bf093753SOmar Sandoval 	blk_queue_physical_block_size(lo->lo_queue, 512);
1397bf093753SOmar Sandoval 	blk_queue_io_min(lo->lo_queue, 512);
1398c1681bf8SAnatol Pomozov 	if (bdev) {
1399f98393a6SPeter Zijlstra 		invalidate_bdev(bdev);
1400eedffa28SJeff Layton 		bdev->bd_inode->i_mapping->wb_err = 0;
1401c1681bf8SAnatol Pomozov 	}
140273285082SKen Chen 	set_capacity(lo->lo_disk, 0);
140351a0bb0cSMilan Broz 	loop_sysfs_exit(lo);
1404c3473c63SDavid Zeuthen 	if (bdev) {
1405c3473c63SDavid Zeuthen 		/* let user-space know about this change */
1406c3473c63SDavid Zeuthen 		kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, KOBJ_CHANGE);
1407c3473c63SDavid Zeuthen 	}
14081da177e4SLinus Torvalds 	mapping_set_gfp_mask(filp->f_mapping, gfp);
14091da177e4SLinus Torvalds 	/* This is safe: open() is still holding a reference. */
14101da177e4SLinus Torvalds 	module_put(THIS_MODULE);
1411f8933667SMing Lei 	blk_mq_unfreeze_queue(lo->lo_queue);
1412f8933667SMing Lei 
14130da03cabSJan Kara 	partscan = lo->lo_flags & LO_FLAGS_PARTSCAN && bdev;
14140da03cabSJan Kara 	lo_number = lo->lo_number;
14159f65c489SMatteo Croce 	disk_force_media_change(lo->lo_disk, DISK_EVENT_MEDIA_CHANGE);
14160da03cabSJan Kara out_unlock:
14176cc8e743SPavel Tatashin 	mutex_unlock(&lo->lo_mutex);
14180da03cabSJan Kara 	if (partscan) {
1419d57f3374SJan Kara 		/*
1420a8698707SChristoph Hellwig 		 * open_mutex has been held already in release path, so don't
1421d57f3374SJan Kara 		 * acquire it if this function is called in such case.
1422d57f3374SJan Kara 		 *
1423d57f3374SJan Kara 		 * If the reread partition isn't from release path, lo_refcnt
1424d57f3374SJan Kara 		 * must be at least one and it can only become zero when the
1425d57f3374SJan Kara 		 * current holder is released.
1426d57f3374SJan Kara 		 */
1427f0b870dfSChristoph Hellwig 		if (!release)
14280384264eSChristoph Hellwig 			mutex_lock(&lo->lo_disk->open_mutex);
14290384264eSChristoph Hellwig 		err = bdev_disk_changed(lo->lo_disk, false);
1430f0b870dfSChristoph Hellwig 		if (!release)
14310384264eSChristoph Hellwig 			mutex_unlock(&lo->lo_disk->open_mutex);
143240853d6fSDongli Zhang 		if (err)
1433d57f3374SJan Kara 			pr_warn("%s: partition scan of loop%d failed (rc=%d)\n",
14340da03cabSJan Kara 				__func__, lo_number, err);
1435d57f3374SJan Kara 		/* Device is gone, no point in returning error */
1436d57f3374SJan Kara 		err = 0;
1437d57f3374SJan Kara 	}
1438758a58d0SDongli Zhang 
1439758a58d0SDongli Zhang 	/*
1440758a58d0SDongli Zhang 	 * lo->lo_state is set to Lo_unbound here after above partscan has
1441758a58d0SDongli Zhang 	 * finished.
1442758a58d0SDongli Zhang 	 *
1443758a58d0SDongli Zhang 	 * There cannot be anybody else entering __loop_clr_fd() as
1444758a58d0SDongli Zhang 	 * lo->lo_backing_file is already cleared and Lo_rundown state
1445758a58d0SDongli Zhang 	 * protects us from all the other places trying to change the 'lo'
1446758a58d0SDongli Zhang 	 * device.
1447758a58d0SDongli Zhang 	 */
14486cc8e743SPavel Tatashin 	mutex_lock(&lo->lo_mutex);
1449758a58d0SDongli Zhang 	lo->lo_flags = 0;
1450758a58d0SDongli Zhang 	if (!part_shift)
1451758a58d0SDongli Zhang 		lo->lo_disk->flags |= GENHD_FL_NO_PART_SCAN;
1452758a58d0SDongli Zhang 	lo->lo_state = Lo_unbound;
14536cc8e743SPavel Tatashin 	mutex_unlock(&lo->lo_mutex);
1454758a58d0SDongli Zhang 
1455f028f3b2SNikanth Karthikesan 	/*
14566cc8e743SPavel Tatashin 	 * Need not hold lo_mutex to fput backing file. Calling fput holding
14576cc8e743SPavel Tatashin 	 * lo_mutex triggers a circular lock dependency possibility warning as
1458a8698707SChristoph Hellwig 	 * fput can take open_mutex which is usually taken before lo_mutex.
1459f028f3b2SNikanth Karthikesan 	 */
14607ccd0791SJan Kara 	if (filp)
1461f028f3b2SNikanth Karthikesan 		fput(filp);
14627ccd0791SJan Kara 	return err;
14631da177e4SLinus Torvalds }
14641da177e4SLinus Torvalds 
1465a2505b79SJan Kara static int loop_clr_fd(struct loop_device *lo)
1466a2505b79SJan Kara {
14677ccd0791SJan Kara 	int err;
14687ccd0791SJan Kara 
14696cc8e743SPavel Tatashin 	err = mutex_lock_killable(&lo->lo_mutex);
14707ccd0791SJan Kara 	if (err)
14717ccd0791SJan Kara 		return err;
14727ccd0791SJan Kara 	if (lo->lo_state != Lo_bound) {
14736cc8e743SPavel Tatashin 		mutex_unlock(&lo->lo_mutex);
1474a2505b79SJan Kara 		return -ENXIO;
14757ccd0791SJan Kara 	}
1476a2505b79SJan Kara 	/*
1477a2505b79SJan Kara 	 * If we've explicitly asked to tear down the loop device,
1478a2505b79SJan Kara 	 * and it has an elevated reference count, set it for auto-teardown when
1479a2505b79SJan Kara 	 * the last reference goes away. This stops $!~#$@ udev from
1480a2505b79SJan Kara 	 * preventing teardown because it decided that it needs to run blkid on
1481a2505b79SJan Kara 	 * the loopback device whenever they appear. xfstests is notorious for
1482a2505b79SJan Kara 	 * failing tests because blkid via udev races with a losetup
1483a2505b79SJan Kara 	 * <dev>/do something like mkfs/losetup -d <dev> causing the losetup -d
1484a2505b79SJan Kara 	 * command to fail with EBUSY.
1485a2505b79SJan Kara 	 */
1486a2505b79SJan Kara 	if (atomic_read(&lo->lo_refcnt) > 1) {
1487a2505b79SJan Kara 		lo->lo_flags |= LO_FLAGS_AUTOCLEAR;
14886cc8e743SPavel Tatashin 		mutex_unlock(&lo->lo_mutex);
1489a2505b79SJan Kara 		return 0;
1490a2505b79SJan Kara 	}
1491a2505b79SJan Kara 	lo->lo_state = Lo_rundown;
14926cc8e743SPavel Tatashin 	mutex_unlock(&lo->lo_mutex);
1493a2505b79SJan Kara 
14940da03cabSJan Kara 	return __loop_clr_fd(lo, false);
1495a2505b79SJan Kara }
1496a2505b79SJan Kara 
14971da177e4SLinus Torvalds static int
14981da177e4SLinus Torvalds loop_set_status(struct loop_device *lo, const struct loop_info64 *info)
14991da177e4SLinus Torvalds {
15001da177e4SLinus Torvalds 	int err;
15010c3796c2SMartijn Coenen 	kuid_t uid = current_uid();
1502faf1d254SMartijn Coenen 	int prev_lo_flags;
150385b0a54aSJan Kara 	bool partscan = false;
15040c3796c2SMartijn Coenen 	bool size_changed = false;
15051da177e4SLinus Torvalds 
15066cc8e743SPavel Tatashin 	err = mutex_lock_killable(&lo->lo_mutex);
1507550df5fdSJan Kara 	if (err)
1508550df5fdSJan Kara 		return err;
1509b0fafa81SDavid Howells 	if (lo->lo_encrypt_key_size &&
1510e4849737SEric W. Biederman 	    !uid_eq(lo->lo_key_owner, uid) &&
1511550df5fdSJan Kara 	    !capable(CAP_SYS_ADMIN)) {
1512550df5fdSJan Kara 		err = -EPERM;
1513550df5fdSJan Kara 		goto out_unlock;
1514550df5fdSJan Kara 	}
1515550df5fdSJan Kara 	if (lo->lo_state != Lo_bound) {
1516550df5fdSJan Kara 		err = -ENXIO;
1517550df5fdSJan Kara 		goto out_unlock;
1518550df5fdSJan Kara 	}
15191da177e4SLinus Torvalds 
15205db470e2SJaegeuk Kim 	if (lo->lo_offset != info->lo_offset ||
15215db470e2SJaegeuk Kim 	    lo->lo_sizelimit != info->lo_sizelimit) {
15220c3796c2SMartijn Coenen 		size_changed = true;
15235db470e2SJaegeuk Kim 		sync_blockdev(lo->lo_device);
1524f4bd34b1SZheng Bin 		invalidate_bdev(lo->lo_device);
15255db470e2SJaegeuk Kim 	}
15265db470e2SJaegeuk Kim 
1527ecdd0959SMing Lei 	/* I/O need to be drained during transfer transition */
1528ecdd0959SMing Lei 	blk_mq_freeze_queue(lo->lo_queue);
1529ecdd0959SMing Lei 
15300c3796c2SMartijn Coenen 	if (size_changed && lo->lo_device->bd_inode->i_mapping->nrpages) {
1531f4bd34b1SZheng Bin 		/* If any pages were dirtied after invalidate_bdev(), try again */
15325db470e2SJaegeuk Kim 		err = -EAGAIN;
15335db470e2SJaegeuk Kim 		pr_warn("%s: loop%d (%s) has still dirty pages (nrpages=%lu)\n",
15345db470e2SJaegeuk Kim 			__func__, lo->lo_number, lo->lo_file_name,
15355db470e2SJaegeuk Kim 			lo->lo_device->bd_inode->i_mapping->nrpages);
15365db470e2SJaegeuk Kim 		goto out_unfreeze;
15375db470e2SJaegeuk Kim 	}
15380c3796c2SMartijn Coenen 
1539faf1d254SMartijn Coenen 	prev_lo_flags = lo->lo_flags;
1540faf1d254SMartijn Coenen 
15410c3796c2SMartijn Coenen 	err = loop_set_status_from_info(lo, info);
15420c3796c2SMartijn Coenen 	if (err)
1543550df5fdSJan Kara 		goto out_unfreeze;
15440c3796c2SMartijn Coenen 
1545faf1d254SMartijn Coenen 	/* Mask out flags that can't be set using LOOP_SET_STATUS. */
15466ac92fb5SMartijn Coenen 	lo->lo_flags &= LOOP_SET_STATUS_SETTABLE_FLAGS;
1547faf1d254SMartijn Coenen 	/* For those flags, use the previous values instead */
1548faf1d254SMartijn Coenen 	lo->lo_flags |= prev_lo_flags & ~LOOP_SET_STATUS_SETTABLE_FLAGS;
1549faf1d254SMartijn Coenen 	/* For flags that can't be cleared, use previous values too */
1550faf1d254SMartijn Coenen 	lo->lo_flags |= prev_lo_flags & ~LOOP_SET_STATUS_CLEARABLE_FLAGS;
1551faf1d254SMartijn Coenen 
1552b0bd158dSMartijn Coenen 	if (size_changed) {
1553b0bd158dSMartijn Coenen 		loff_t new_size = get_size(lo->lo_offset, lo->lo_sizelimit,
1554b0bd158dSMartijn Coenen 					   lo->lo_backing_file);
1555b0bd158dSMartijn Coenen 		loop_set_size(lo, new_size);
1556b040ad9cSArnd Bergmann 	}
1557541c742aSGuo Chao 
1558dfaa2ef6SLukas Czerner 	loop_config_discard(lo);
15591da177e4SLinus Torvalds 
15602e5ab5f3SMing Lei 	/* update dio if lo_offset or transfer is changed */
15612e5ab5f3SMing Lei 	__loop_update_dio(lo, lo->use_dio);
15622e5ab5f3SMing Lei 
1563550df5fdSJan Kara out_unfreeze:
1564ecdd0959SMing Lei 	blk_mq_unfreeze_queue(lo->lo_queue);
1565e02898b4SOmar Sandoval 
1566faf1d254SMartijn Coenen 	if (!err && (lo->lo_flags & LO_FLAGS_PARTSCAN) &&
1567faf1d254SMartijn Coenen 	     !(prev_lo_flags & LO_FLAGS_PARTSCAN)) {
1568e02898b4SOmar Sandoval 		lo->lo_disk->flags &= ~GENHD_FL_NO_PART_SCAN;
156985b0a54aSJan Kara 		partscan = true;
1570e02898b4SOmar Sandoval 	}
1571550df5fdSJan Kara out_unlock:
15726cc8e743SPavel Tatashin 	mutex_unlock(&lo->lo_mutex);
157385b0a54aSJan Kara 	if (partscan)
15740384264eSChristoph Hellwig 		loop_reread_partitions(lo);
1575e02898b4SOmar Sandoval 
1576ecdd0959SMing Lei 	return err;
15771da177e4SLinus Torvalds }
15781da177e4SLinus Torvalds 
15791da177e4SLinus Torvalds static int
15801da177e4SLinus Torvalds loop_get_status(struct loop_device *lo, struct loop_info64 *info)
15811da177e4SLinus Torvalds {
1582b1ab5fa3STetsuo Handa 	struct path path;
15831da177e4SLinus Torvalds 	struct kstat stat;
15842d1d4c1eSOmar Sandoval 	int ret;
15851da177e4SLinus Torvalds 
15866cc8e743SPavel Tatashin 	ret = mutex_lock_killable(&lo->lo_mutex);
15874a5ce9baSJan Kara 	if (ret)
15884a5ce9baSJan Kara 		return ret;
15892d1d4c1eSOmar Sandoval 	if (lo->lo_state != Lo_bound) {
15906cc8e743SPavel Tatashin 		mutex_unlock(&lo->lo_mutex);
15911da177e4SLinus Torvalds 		return -ENXIO;
15922d1d4c1eSOmar Sandoval 	}
15932d1d4c1eSOmar Sandoval 
15941da177e4SLinus Torvalds 	memset(info, 0, sizeof(*info));
15951da177e4SLinus Torvalds 	info->lo_number = lo->lo_number;
15961da177e4SLinus Torvalds 	info->lo_offset = lo->lo_offset;
15971da177e4SLinus Torvalds 	info->lo_sizelimit = lo->lo_sizelimit;
15981da177e4SLinus Torvalds 	info->lo_flags = lo->lo_flags;
15991da177e4SLinus Torvalds 	memcpy(info->lo_file_name, lo->lo_file_name, LO_NAME_SIZE);
16001da177e4SLinus Torvalds 	memcpy(info->lo_crypt_name, lo->lo_crypt_name, LO_NAME_SIZE);
16011da177e4SLinus Torvalds 	info->lo_encrypt_type =
16021da177e4SLinus Torvalds 		lo->lo_encryption ? lo->lo_encryption->number : 0;
16031da177e4SLinus Torvalds 	if (lo->lo_encrypt_key_size && capable(CAP_SYS_ADMIN)) {
16041da177e4SLinus Torvalds 		info->lo_encrypt_key_size = lo->lo_encrypt_key_size;
16051da177e4SLinus Torvalds 		memcpy(info->lo_encrypt_key, lo->lo_encrypt_key,
16061da177e4SLinus Torvalds 		       lo->lo_encrypt_key_size);
16071da177e4SLinus Torvalds 	}
16082d1d4c1eSOmar Sandoval 
16096cc8e743SPavel Tatashin 	/* Drop lo_mutex while we call into the filesystem. */
1610b1ab5fa3STetsuo Handa 	path = lo->lo_backing_file->f_path;
1611b1ab5fa3STetsuo Handa 	path_get(&path);
16126cc8e743SPavel Tatashin 	mutex_unlock(&lo->lo_mutex);
1613b1ab5fa3STetsuo Handa 	ret = vfs_getattr(&path, &stat, STATX_INO, AT_STATX_SYNC_AS_STAT);
16142d1d4c1eSOmar Sandoval 	if (!ret) {
16152d1d4c1eSOmar Sandoval 		info->lo_device = huge_encode_dev(stat.dev);
16162d1d4c1eSOmar Sandoval 		info->lo_inode = stat.ino;
16172d1d4c1eSOmar Sandoval 		info->lo_rdevice = huge_encode_dev(stat.rdev);
16182d1d4c1eSOmar Sandoval 	}
1619b1ab5fa3STetsuo Handa 	path_put(&path);
16202d1d4c1eSOmar Sandoval 	return ret;
16211da177e4SLinus Torvalds }
16221da177e4SLinus Torvalds 
16231da177e4SLinus Torvalds static void
16241da177e4SLinus Torvalds loop_info64_from_old(const struct loop_info *info, struct loop_info64 *info64)
16251da177e4SLinus Torvalds {
16261da177e4SLinus Torvalds 	memset(info64, 0, sizeof(*info64));
16271da177e4SLinus Torvalds 	info64->lo_number = info->lo_number;
16281da177e4SLinus Torvalds 	info64->lo_device = info->lo_device;
16291da177e4SLinus Torvalds 	info64->lo_inode = info->lo_inode;
16301da177e4SLinus Torvalds 	info64->lo_rdevice = info->lo_rdevice;
16311da177e4SLinus Torvalds 	info64->lo_offset = info->lo_offset;
16321da177e4SLinus Torvalds 	info64->lo_sizelimit = 0;
16331da177e4SLinus Torvalds 	info64->lo_encrypt_type = info->lo_encrypt_type;
16341da177e4SLinus Torvalds 	info64->lo_encrypt_key_size = info->lo_encrypt_key_size;
16351da177e4SLinus Torvalds 	info64->lo_flags = info->lo_flags;
16361da177e4SLinus Torvalds 	info64->lo_init[0] = info->lo_init[0];
16371da177e4SLinus Torvalds 	info64->lo_init[1] = info->lo_init[1];
16381da177e4SLinus Torvalds 	if (info->lo_encrypt_type == LO_CRYPT_CRYPTOAPI)
16391da177e4SLinus Torvalds 		memcpy(info64->lo_crypt_name, info->lo_name, LO_NAME_SIZE);
16401da177e4SLinus Torvalds 	else
16411da177e4SLinus Torvalds 		memcpy(info64->lo_file_name, info->lo_name, LO_NAME_SIZE);
16421da177e4SLinus Torvalds 	memcpy(info64->lo_encrypt_key, info->lo_encrypt_key, LO_KEY_SIZE);
16431da177e4SLinus Torvalds }
16441da177e4SLinus Torvalds 
16451da177e4SLinus Torvalds static int
16461da177e4SLinus Torvalds loop_info64_to_old(const struct loop_info64 *info64, struct loop_info *info)
16471da177e4SLinus Torvalds {
16481da177e4SLinus Torvalds 	memset(info, 0, sizeof(*info));
16491da177e4SLinus Torvalds 	info->lo_number = info64->lo_number;
16501da177e4SLinus Torvalds 	info->lo_device = info64->lo_device;
16511da177e4SLinus Torvalds 	info->lo_inode = info64->lo_inode;
16521da177e4SLinus Torvalds 	info->lo_rdevice = info64->lo_rdevice;
16531da177e4SLinus Torvalds 	info->lo_offset = info64->lo_offset;
16541da177e4SLinus Torvalds 	info->lo_encrypt_type = info64->lo_encrypt_type;
16551da177e4SLinus Torvalds 	info->lo_encrypt_key_size = info64->lo_encrypt_key_size;
16561da177e4SLinus Torvalds 	info->lo_flags = info64->lo_flags;
16571da177e4SLinus Torvalds 	info->lo_init[0] = info64->lo_init[0];
16581da177e4SLinus Torvalds 	info->lo_init[1] = info64->lo_init[1];
16591da177e4SLinus Torvalds 	if (info->lo_encrypt_type == LO_CRYPT_CRYPTOAPI)
16601da177e4SLinus Torvalds 		memcpy(info->lo_name, info64->lo_crypt_name, LO_NAME_SIZE);
16611da177e4SLinus Torvalds 	else
16621da177e4SLinus Torvalds 		memcpy(info->lo_name, info64->lo_file_name, LO_NAME_SIZE);
16631da177e4SLinus Torvalds 	memcpy(info->lo_encrypt_key, info64->lo_encrypt_key, LO_KEY_SIZE);
16641da177e4SLinus Torvalds 
16651da177e4SLinus Torvalds 	/* error in case values were truncated */
16661da177e4SLinus Torvalds 	if (info->lo_device != info64->lo_device ||
16671da177e4SLinus Torvalds 	    info->lo_rdevice != info64->lo_rdevice ||
16681da177e4SLinus Torvalds 	    info->lo_inode != info64->lo_inode ||
16691da177e4SLinus Torvalds 	    info->lo_offset != info64->lo_offset)
16701da177e4SLinus Torvalds 		return -EOVERFLOW;
16711da177e4SLinus Torvalds 
16721da177e4SLinus Torvalds 	return 0;
16731da177e4SLinus Torvalds }
16741da177e4SLinus Torvalds 
16751da177e4SLinus Torvalds static int
16761da177e4SLinus Torvalds loop_set_status_old(struct loop_device *lo, const struct loop_info __user *arg)
16771da177e4SLinus Torvalds {
16781da177e4SLinus Torvalds 	struct loop_info info;
16791da177e4SLinus Torvalds 	struct loop_info64 info64;
16801da177e4SLinus Torvalds 
16811da177e4SLinus Torvalds 	if (copy_from_user(&info, arg, sizeof (struct loop_info)))
16821da177e4SLinus Torvalds 		return -EFAULT;
16831da177e4SLinus Torvalds 	loop_info64_from_old(&info, &info64);
16841da177e4SLinus Torvalds 	return loop_set_status(lo, &info64);
16851da177e4SLinus Torvalds }
16861da177e4SLinus Torvalds 
16871da177e4SLinus Torvalds static int
16881da177e4SLinus Torvalds loop_set_status64(struct loop_device *lo, const struct loop_info64 __user *arg)
16891da177e4SLinus Torvalds {
16901da177e4SLinus Torvalds 	struct loop_info64 info64;
16911da177e4SLinus Torvalds 
16921da177e4SLinus Torvalds 	if (copy_from_user(&info64, arg, sizeof (struct loop_info64)))
16931da177e4SLinus Torvalds 		return -EFAULT;
16941da177e4SLinus Torvalds 	return loop_set_status(lo, &info64);
16951da177e4SLinus Torvalds }
16961da177e4SLinus Torvalds 
16971da177e4SLinus Torvalds static int
16981da177e4SLinus Torvalds loop_get_status_old(struct loop_device *lo, struct loop_info __user *arg) {
16991da177e4SLinus Torvalds 	struct loop_info info;
17001da177e4SLinus Torvalds 	struct loop_info64 info64;
1701bdac616dSOmar Sandoval 	int err;
17021da177e4SLinus Torvalds 
17034a5ce9baSJan Kara 	if (!arg)
1704bdac616dSOmar Sandoval 		return -EINVAL;
17051da177e4SLinus Torvalds 	err = loop_get_status(lo, &info64);
17061da177e4SLinus Torvalds 	if (!err)
17071da177e4SLinus Torvalds 		err = loop_info64_to_old(&info64, &info);
17081da177e4SLinus Torvalds 	if (!err && copy_to_user(arg, &info, sizeof(info)))
17091da177e4SLinus Torvalds 		err = -EFAULT;
17101da177e4SLinus Torvalds 
17111da177e4SLinus Torvalds 	return err;
17121da177e4SLinus Torvalds }
17131da177e4SLinus Torvalds 
17141da177e4SLinus Torvalds static int
17151da177e4SLinus Torvalds loop_get_status64(struct loop_device *lo, struct loop_info64 __user *arg) {
17161da177e4SLinus Torvalds 	struct loop_info64 info64;
1717bdac616dSOmar Sandoval 	int err;
17181da177e4SLinus Torvalds 
17194a5ce9baSJan Kara 	if (!arg)
1720bdac616dSOmar Sandoval 		return -EINVAL;
17211da177e4SLinus Torvalds 	err = loop_get_status(lo, &info64);
17221da177e4SLinus Torvalds 	if (!err && copy_to_user(arg, &info64, sizeof(info64)))
17231da177e4SLinus Torvalds 		err = -EFAULT;
17241da177e4SLinus Torvalds 
17251da177e4SLinus Torvalds 	return err;
17261da177e4SLinus Torvalds }
17271da177e4SLinus Torvalds 
172851001b7dSHannes Reinecke static int loop_set_capacity(struct loop_device *lo)
172953d66608SJ. R. Okajima {
17300a6ed1b5SMartijn Coenen 	loff_t size;
17310a6ed1b5SMartijn Coenen 
173253d66608SJ. R. Okajima 	if (unlikely(lo->lo_state != Lo_bound))
17337b0576a3SGuo Chao 		return -ENXIO;
173453d66608SJ. R. Okajima 
17350a6ed1b5SMartijn Coenen 	size = get_loop_size(lo, lo->lo_backing_file);
17360a6ed1b5SMartijn Coenen 	loop_set_size(lo, size);
1737083a6a50SMartijn Coenen 
1738083a6a50SMartijn Coenen 	return 0;
173953d66608SJ. R. Okajima }
174053d66608SJ. R. Okajima 
1741ab1cb278SMing Lei static int loop_set_dio(struct loop_device *lo, unsigned long arg)
1742ab1cb278SMing Lei {
1743ab1cb278SMing Lei 	int error = -ENXIO;
1744ab1cb278SMing Lei 	if (lo->lo_state != Lo_bound)
1745ab1cb278SMing Lei 		goto out;
1746ab1cb278SMing Lei 
1747ab1cb278SMing Lei 	__loop_update_dio(lo, !!arg);
1748ab1cb278SMing Lei 	if (lo->use_dio == !!arg)
1749ab1cb278SMing Lei 		return 0;
1750ab1cb278SMing Lei 	error = -EINVAL;
1751ab1cb278SMing Lei  out:
1752ab1cb278SMing Lei 	return error;
1753ab1cb278SMing Lei }
1754ab1cb278SMing Lei 
175589e4fdecSOmar Sandoval static int loop_set_block_size(struct loop_device *lo, unsigned long arg)
175689e4fdecSOmar Sandoval {
17575db470e2SJaegeuk Kim 	int err = 0;
17585db470e2SJaegeuk Kim 
175989e4fdecSOmar Sandoval 	if (lo->lo_state != Lo_bound)
176089e4fdecSOmar Sandoval 		return -ENXIO;
176189e4fdecSOmar Sandoval 
17623448914eSMartijn Coenen 	err = loop_validate_block_size(arg);
17633448914eSMartijn Coenen 	if (err)
17643448914eSMartijn Coenen 		return err;
176589e4fdecSOmar Sandoval 
17667e81f99aSMartijn Coenen 	if (lo->lo_queue->limits.logical_block_size == arg)
17677e81f99aSMartijn Coenen 		return 0;
17687e81f99aSMartijn Coenen 
17695db470e2SJaegeuk Kim 	sync_blockdev(lo->lo_device);
1770f4bd34b1SZheng Bin 	invalidate_bdev(lo->lo_device);
17715db470e2SJaegeuk Kim 
177289e4fdecSOmar Sandoval 	blk_mq_freeze_queue(lo->lo_queue);
177389e4fdecSOmar Sandoval 
1774f4bd34b1SZheng Bin 	/* invalidate_bdev should have truncated all the pages */
17757e81f99aSMartijn Coenen 	if (lo->lo_device->bd_inode->i_mapping->nrpages) {
17765db470e2SJaegeuk Kim 		err = -EAGAIN;
17775db470e2SJaegeuk Kim 		pr_warn("%s: loop%d (%s) has still dirty pages (nrpages=%lu)\n",
17785db470e2SJaegeuk Kim 			__func__, lo->lo_number, lo->lo_file_name,
17795db470e2SJaegeuk Kim 			lo->lo_device->bd_inode->i_mapping->nrpages);
17805db470e2SJaegeuk Kim 		goto out_unfreeze;
17815db470e2SJaegeuk Kim 	}
17825db470e2SJaegeuk Kim 
178389e4fdecSOmar Sandoval 	blk_queue_logical_block_size(lo->lo_queue, arg);
1784bf093753SOmar Sandoval 	blk_queue_physical_block_size(lo->lo_queue, arg);
1785bf093753SOmar Sandoval 	blk_queue_io_min(lo->lo_queue, arg);
178689e4fdecSOmar Sandoval 	loop_update_dio(lo);
17875db470e2SJaegeuk Kim out_unfreeze:
178889e4fdecSOmar Sandoval 	blk_mq_unfreeze_queue(lo->lo_queue);
178989e4fdecSOmar Sandoval 
17905db470e2SJaegeuk Kim 	return err;
179189e4fdecSOmar Sandoval }
179289e4fdecSOmar Sandoval 
1793a1316544SJan Kara static int lo_simple_ioctl(struct loop_device *lo, unsigned int cmd,
1794a1316544SJan Kara 			   unsigned long arg)
17951da177e4SLinus Torvalds {
17961da177e4SLinus Torvalds 	int err;
17971da177e4SLinus Torvalds 
17986cc8e743SPavel Tatashin 	err = mutex_lock_killable(&lo->lo_mutex);
17993148ffbdSOmar Sandoval 	if (err)
1800a1316544SJan Kara 		return err;
18011da177e4SLinus Torvalds 	switch (cmd) {
180253d66608SJ. R. Okajima 	case LOOP_SET_CAPACITY:
180351001b7dSHannes Reinecke 		err = loop_set_capacity(lo);
180453d66608SJ. R. Okajima 		break;
1805ab1cb278SMing Lei 	case LOOP_SET_DIRECT_IO:
1806ab1cb278SMing Lei 		err = loop_set_dio(lo, arg);
1807ab1cb278SMing Lei 		break;
180889e4fdecSOmar Sandoval 	case LOOP_SET_BLOCK_SIZE:
180989e4fdecSOmar Sandoval 		err = loop_set_block_size(lo, arg);
181089e4fdecSOmar Sandoval 		break;
18111da177e4SLinus Torvalds 	default:
18121da177e4SLinus Torvalds 		err = lo->ioctl ? lo->ioctl(lo, cmd, arg) : -EINVAL;
18131da177e4SLinus Torvalds 	}
18146cc8e743SPavel Tatashin 	mutex_unlock(&lo->lo_mutex);
1815a1316544SJan Kara 	return err;
1816a1316544SJan Kara }
1817f028f3b2SNikanth Karthikesan 
1818a1316544SJan Kara static int lo_ioctl(struct block_device *bdev, fmode_t mode,
1819a1316544SJan Kara 	unsigned int cmd, unsigned long arg)
1820a1316544SJan Kara {
1821a1316544SJan Kara 	struct loop_device *lo = bdev->bd_disk->private_data;
1822571fae6eSMartijn Coenen 	void __user *argp = (void __user *) arg;
1823a1316544SJan Kara 	int err;
1824a1316544SJan Kara 
1825a1316544SJan Kara 	switch (cmd) {
18263448914eSMartijn Coenen 	case LOOP_SET_FD: {
18273448914eSMartijn Coenen 		/*
18283448914eSMartijn Coenen 		 * Legacy case - pass in a zeroed out struct loop_config with
18293448914eSMartijn Coenen 		 * only the file descriptor set , which corresponds with the
18303448914eSMartijn Coenen 		 * default parameters we'd have used otherwise.
18313448914eSMartijn Coenen 		 */
18323448914eSMartijn Coenen 		struct loop_config config;
18333448914eSMartijn Coenen 
18343448914eSMartijn Coenen 		memset(&config, 0, sizeof(config));
18353448914eSMartijn Coenen 		config.fd = arg;
18363448914eSMartijn Coenen 
18373448914eSMartijn Coenen 		return loop_configure(lo, mode, bdev, &config);
18383448914eSMartijn Coenen 	}
18393448914eSMartijn Coenen 	case LOOP_CONFIGURE: {
18403448914eSMartijn Coenen 		struct loop_config config;
18413448914eSMartijn Coenen 
18423448914eSMartijn Coenen 		if (copy_from_user(&config, argp, sizeof(config)))
18433448914eSMartijn Coenen 			return -EFAULT;
18443448914eSMartijn Coenen 
18453448914eSMartijn Coenen 		return loop_configure(lo, mode, bdev, &config);
18463448914eSMartijn Coenen 	}
1847a1316544SJan Kara 	case LOOP_CHANGE_FD:
1848c3710770SJan Kara 		return loop_change_fd(lo, bdev, arg);
1849a1316544SJan Kara 	case LOOP_CLR_FD:
18507ccd0791SJan Kara 		return loop_clr_fd(lo);
1851a1316544SJan Kara 	case LOOP_SET_STATUS:
1852a1316544SJan Kara 		err = -EPERM;
1853a1316544SJan Kara 		if ((mode & FMODE_WRITE) || capable(CAP_SYS_ADMIN)) {
1854571fae6eSMartijn Coenen 			err = loop_set_status_old(lo, argp);
1855a1316544SJan Kara 		}
1856a1316544SJan Kara 		break;
1857a1316544SJan Kara 	case LOOP_GET_STATUS:
1858571fae6eSMartijn Coenen 		return loop_get_status_old(lo, argp);
1859a1316544SJan Kara 	case LOOP_SET_STATUS64:
1860a1316544SJan Kara 		err = -EPERM;
1861a1316544SJan Kara 		if ((mode & FMODE_WRITE) || capable(CAP_SYS_ADMIN)) {
1862571fae6eSMartijn Coenen 			err = loop_set_status64(lo, argp);
1863a1316544SJan Kara 		}
1864a1316544SJan Kara 		break;
1865a1316544SJan Kara 	case LOOP_GET_STATUS64:
1866571fae6eSMartijn Coenen 		return loop_get_status64(lo, argp);
1867a1316544SJan Kara 	case LOOP_SET_CAPACITY:
1868a1316544SJan Kara 	case LOOP_SET_DIRECT_IO:
1869a1316544SJan Kara 	case LOOP_SET_BLOCK_SIZE:
1870a1316544SJan Kara 		if (!(mode & FMODE_WRITE) && !capable(CAP_SYS_ADMIN))
1871a1316544SJan Kara 			return -EPERM;
1872df561f66SGustavo A. R. Silva 		fallthrough;
1873a1316544SJan Kara 	default:
1874a1316544SJan Kara 		err = lo_simple_ioctl(lo, cmd, arg);
1875a1316544SJan Kara 		break;
1876a1316544SJan Kara 	}
1877a1316544SJan Kara 
18781da177e4SLinus Torvalds 	return err;
18791da177e4SLinus Torvalds }
18801da177e4SLinus Torvalds 
1881863d5b82SDavid Howells #ifdef CONFIG_COMPAT
1882863d5b82SDavid Howells struct compat_loop_info {
1883863d5b82SDavid Howells 	compat_int_t	lo_number;      /* ioctl r/o */
1884863d5b82SDavid Howells 	compat_dev_t	lo_device;      /* ioctl r/o */
1885863d5b82SDavid Howells 	compat_ulong_t	lo_inode;       /* ioctl r/o */
1886863d5b82SDavid Howells 	compat_dev_t	lo_rdevice;     /* ioctl r/o */
1887863d5b82SDavid Howells 	compat_int_t	lo_offset;
1888863d5b82SDavid Howells 	compat_int_t	lo_encrypt_type;
1889863d5b82SDavid Howells 	compat_int_t	lo_encrypt_key_size;    /* ioctl w/o */
1890863d5b82SDavid Howells 	compat_int_t	lo_flags;       /* ioctl r/o */
1891863d5b82SDavid Howells 	char		lo_name[LO_NAME_SIZE];
1892863d5b82SDavid Howells 	unsigned char	lo_encrypt_key[LO_KEY_SIZE]; /* ioctl w/o */
1893863d5b82SDavid Howells 	compat_ulong_t	lo_init[2];
1894863d5b82SDavid Howells 	char		reserved[4];
1895863d5b82SDavid Howells };
1896863d5b82SDavid Howells 
1897863d5b82SDavid Howells /*
1898863d5b82SDavid Howells  * Transfer 32-bit compatibility structure in userspace to 64-bit loop info
1899863d5b82SDavid Howells  * - noinlined to reduce stack space usage in main part of driver
1900863d5b82SDavid Howells  */
1901863d5b82SDavid Howells static noinline int
1902ba674cfcSAl Viro loop_info64_from_compat(const struct compat_loop_info __user *arg,
1903863d5b82SDavid Howells 			struct loop_info64 *info64)
1904863d5b82SDavid Howells {
1905863d5b82SDavid Howells 	struct compat_loop_info info;
1906863d5b82SDavid Howells 
1907863d5b82SDavid Howells 	if (copy_from_user(&info, arg, sizeof(info)))
1908863d5b82SDavid Howells 		return -EFAULT;
1909863d5b82SDavid Howells 
1910863d5b82SDavid Howells 	memset(info64, 0, sizeof(*info64));
1911863d5b82SDavid Howells 	info64->lo_number = info.lo_number;
1912863d5b82SDavid Howells 	info64->lo_device = info.lo_device;
1913863d5b82SDavid Howells 	info64->lo_inode = info.lo_inode;
1914863d5b82SDavid Howells 	info64->lo_rdevice = info.lo_rdevice;
1915863d5b82SDavid Howells 	info64->lo_offset = info.lo_offset;
1916863d5b82SDavid Howells 	info64->lo_sizelimit = 0;
1917863d5b82SDavid Howells 	info64->lo_encrypt_type = info.lo_encrypt_type;
1918863d5b82SDavid Howells 	info64->lo_encrypt_key_size = info.lo_encrypt_key_size;
1919863d5b82SDavid Howells 	info64->lo_flags = info.lo_flags;
1920863d5b82SDavid Howells 	info64->lo_init[0] = info.lo_init[0];
1921863d5b82SDavid Howells 	info64->lo_init[1] = info.lo_init[1];
1922863d5b82SDavid Howells 	if (info.lo_encrypt_type == LO_CRYPT_CRYPTOAPI)
1923863d5b82SDavid Howells 		memcpy(info64->lo_crypt_name, info.lo_name, LO_NAME_SIZE);
1924863d5b82SDavid Howells 	else
1925863d5b82SDavid Howells 		memcpy(info64->lo_file_name, info.lo_name, LO_NAME_SIZE);
1926863d5b82SDavid Howells 	memcpy(info64->lo_encrypt_key, info.lo_encrypt_key, LO_KEY_SIZE);
1927863d5b82SDavid Howells 	return 0;
1928863d5b82SDavid Howells }
1929863d5b82SDavid Howells 
1930863d5b82SDavid Howells /*
1931863d5b82SDavid Howells  * Transfer 64-bit loop info to 32-bit compatibility structure in userspace
1932863d5b82SDavid Howells  * - noinlined to reduce stack space usage in main part of driver
1933863d5b82SDavid Howells  */
1934863d5b82SDavid Howells static noinline int
1935863d5b82SDavid Howells loop_info64_to_compat(const struct loop_info64 *info64,
1936863d5b82SDavid Howells 		      struct compat_loop_info __user *arg)
1937863d5b82SDavid Howells {
1938863d5b82SDavid Howells 	struct compat_loop_info info;
1939863d5b82SDavid Howells 
1940863d5b82SDavid Howells 	memset(&info, 0, sizeof(info));
1941863d5b82SDavid Howells 	info.lo_number = info64->lo_number;
1942863d5b82SDavid Howells 	info.lo_device = info64->lo_device;
1943863d5b82SDavid Howells 	info.lo_inode = info64->lo_inode;
1944863d5b82SDavid Howells 	info.lo_rdevice = info64->lo_rdevice;
1945863d5b82SDavid Howells 	info.lo_offset = info64->lo_offset;
1946863d5b82SDavid Howells 	info.lo_encrypt_type = info64->lo_encrypt_type;
1947863d5b82SDavid Howells 	info.lo_encrypt_key_size = info64->lo_encrypt_key_size;
1948863d5b82SDavid Howells 	info.lo_flags = info64->lo_flags;
1949863d5b82SDavid Howells 	info.lo_init[0] = info64->lo_init[0];
1950863d5b82SDavid Howells 	info.lo_init[1] = info64->lo_init[1];
1951863d5b82SDavid Howells 	if (info.lo_encrypt_type == LO_CRYPT_CRYPTOAPI)
1952863d5b82SDavid Howells 		memcpy(info.lo_name, info64->lo_crypt_name, LO_NAME_SIZE);
1953863d5b82SDavid Howells 	else
1954863d5b82SDavid Howells 		memcpy(info.lo_name, info64->lo_file_name, LO_NAME_SIZE);
1955863d5b82SDavid Howells 	memcpy(info.lo_encrypt_key, info64->lo_encrypt_key, LO_KEY_SIZE);
1956863d5b82SDavid Howells 
1957863d5b82SDavid Howells 	/* error in case values were truncated */
1958863d5b82SDavid Howells 	if (info.lo_device != info64->lo_device ||
1959863d5b82SDavid Howells 	    info.lo_rdevice != info64->lo_rdevice ||
1960863d5b82SDavid Howells 	    info.lo_inode != info64->lo_inode ||
1961863d5b82SDavid Howells 	    info.lo_offset != info64->lo_offset ||
1962863d5b82SDavid Howells 	    info.lo_init[0] != info64->lo_init[0] ||
1963863d5b82SDavid Howells 	    info.lo_init[1] != info64->lo_init[1])
1964863d5b82SDavid Howells 		return -EOVERFLOW;
1965863d5b82SDavid Howells 
1966863d5b82SDavid Howells 	if (copy_to_user(arg, &info, sizeof(info)))
1967863d5b82SDavid Howells 		return -EFAULT;
1968863d5b82SDavid Howells 	return 0;
1969863d5b82SDavid Howells }
1970863d5b82SDavid Howells 
1971863d5b82SDavid Howells static int
1972863d5b82SDavid Howells loop_set_status_compat(struct loop_device *lo,
1973863d5b82SDavid Howells 		       const struct compat_loop_info __user *arg)
1974863d5b82SDavid Howells {
1975863d5b82SDavid Howells 	struct loop_info64 info64;
1976863d5b82SDavid Howells 	int ret;
1977863d5b82SDavid Howells 
1978863d5b82SDavid Howells 	ret = loop_info64_from_compat(arg, &info64);
1979863d5b82SDavid Howells 	if (ret < 0)
1980863d5b82SDavid Howells 		return ret;
1981863d5b82SDavid Howells 	return loop_set_status(lo, &info64);
1982863d5b82SDavid Howells }
1983863d5b82SDavid Howells 
1984863d5b82SDavid Howells static int
1985863d5b82SDavid Howells loop_get_status_compat(struct loop_device *lo,
1986863d5b82SDavid Howells 		       struct compat_loop_info __user *arg)
1987863d5b82SDavid Howells {
1988863d5b82SDavid Howells 	struct loop_info64 info64;
1989bdac616dSOmar Sandoval 	int err;
1990863d5b82SDavid Howells 
19914a5ce9baSJan Kara 	if (!arg)
1992bdac616dSOmar Sandoval 		return -EINVAL;
1993863d5b82SDavid Howells 	err = loop_get_status(lo, &info64);
1994863d5b82SDavid Howells 	if (!err)
1995863d5b82SDavid Howells 		err = loop_info64_to_compat(&info64, arg);
1996863d5b82SDavid Howells 	return err;
1997863d5b82SDavid Howells }
1998863d5b82SDavid Howells 
1999bb214884SAl Viro static int lo_compat_ioctl(struct block_device *bdev, fmode_t mode,
2000bb214884SAl Viro 			   unsigned int cmd, unsigned long arg)
2001863d5b82SDavid Howells {
2002bb214884SAl Viro 	struct loop_device *lo = bdev->bd_disk->private_data;
2003863d5b82SDavid Howells 	int err;
2004863d5b82SDavid Howells 
2005863d5b82SDavid Howells 	switch(cmd) {
2006863d5b82SDavid Howells 	case LOOP_SET_STATUS:
20073148ffbdSOmar Sandoval 		err = loop_set_status_compat(lo,
20083148ffbdSOmar Sandoval 			     (const struct compat_loop_info __user *)arg);
2009863d5b82SDavid Howells 		break;
2010863d5b82SDavid Howells 	case LOOP_GET_STATUS:
20113148ffbdSOmar Sandoval 		err = loop_get_status_compat(lo,
20123148ffbdSOmar Sandoval 				     (struct compat_loop_info __user *)arg);
2013863d5b82SDavid Howells 		break;
201453d66608SJ. R. Okajima 	case LOOP_SET_CAPACITY:
2015863d5b82SDavid Howells 	case LOOP_CLR_FD:
2016863d5b82SDavid Howells 	case LOOP_GET_STATUS64:
2017863d5b82SDavid Howells 	case LOOP_SET_STATUS64:
20183448914eSMartijn Coenen 	case LOOP_CONFIGURE:
2019863d5b82SDavid Howells 		arg = (unsigned long) compat_ptr(arg);
2020df561f66SGustavo A. R. Silva 		fallthrough;
2021863d5b82SDavid Howells 	case LOOP_SET_FD:
2022863d5b82SDavid Howells 	case LOOP_CHANGE_FD:
20239fea4b39SEvan Green 	case LOOP_SET_BLOCK_SIZE:
2024fdbe4eeeSAlessio Balsini 	case LOOP_SET_DIRECT_IO:
2025bb214884SAl Viro 		err = lo_ioctl(bdev, mode, cmd, arg);
2026863d5b82SDavid Howells 		break;
2027863d5b82SDavid Howells 	default:
2028863d5b82SDavid Howells 		err = -ENOIOCTLCMD;
2029863d5b82SDavid Howells 		break;
2030863d5b82SDavid Howells 	}
2031863d5b82SDavid Howells 	return err;
2032863d5b82SDavid Howells }
2033863d5b82SDavid Howells #endif
2034863d5b82SDavid Howells 
2035bb214884SAl Viro static int lo_open(struct block_device *bdev, fmode_t mode)
20361da177e4SLinus Torvalds {
2037990e7811SChristoph Hellwig 	struct loop_device *lo = bdev->bd_disk->private_data;
20380a42e99bSJan Kara 	int err;
2039770fe30aSKay Sievers 
20406cc8e743SPavel Tatashin 	err = mutex_lock_killable(&lo->lo_mutex);
20416cc8e743SPavel Tatashin 	if (err)
2042770fe30aSKay Sievers 		return err;
2043990e7811SChristoph Hellwig 	if (lo->lo_state == Lo_deleting)
2044990e7811SChristoph Hellwig 		err = -ENXIO;
2045990e7811SChristoph Hellwig 	else
20466cc8e743SPavel Tatashin 		atomic_inc(&lo->lo_refcnt);
20476cc8e743SPavel Tatashin 	mutex_unlock(&lo->lo_mutex);
2048990e7811SChristoph Hellwig 	return err;
20491da177e4SLinus Torvalds }
20501da177e4SLinus Torvalds 
2051967d1dc1SJan Kara static void lo_release(struct gendisk *disk, fmode_t mode)
20521da177e4SLinus Torvalds {
20536cc8e743SPavel Tatashin 	struct loop_device *lo = disk->private_data;
20541da177e4SLinus Torvalds 
20556cc8e743SPavel Tatashin 	mutex_lock(&lo->lo_mutex);
2056f8933667SMing Lei 	if (atomic_dec_return(&lo->lo_refcnt))
20570a42e99bSJan Kara 		goto out_unlock;
2058f8933667SMing Lei 
205914f27939SMilan Broz 	if (lo->lo_flags & LO_FLAGS_AUTOCLEAR) {
2060a2505b79SJan Kara 		if (lo->lo_state != Lo_bound)
2061a2505b79SJan Kara 			goto out_unlock;
2062a2505b79SJan Kara 		lo->lo_state = Lo_rundown;
20636cc8e743SPavel Tatashin 		mutex_unlock(&lo->lo_mutex);
206414f27939SMilan Broz 		/*
206514f27939SMilan Broz 		 * In autoclear mode, stop the loop thread
206614f27939SMilan Broz 		 * and remove configuration after last close.
206714f27939SMilan Broz 		 */
20680da03cabSJan Kara 		__loop_clr_fd(lo, true);
20690a42e99bSJan Kara 		return;
207043cade80SOmar Sandoval 	} else if (lo->lo_state == Lo_bound) {
207114f27939SMilan Broz 		/*
207214f27939SMilan Broz 		 * Otherwise keep thread (if running) and config,
207314f27939SMilan Broz 		 * but flush possible ongoing bios in thread.
207414f27939SMilan Broz 		 */
207543cade80SOmar Sandoval 		blk_mq_freeze_queue(lo->lo_queue);
207643cade80SOmar Sandoval 		blk_mq_unfreeze_queue(lo->lo_queue);
207714f27939SMilan Broz 	}
207896c58655SDavid Woodhouse 
20790a42e99bSJan Kara out_unlock:
20806cc8e743SPavel Tatashin 	mutex_unlock(&lo->lo_mutex);
2081ae665016SLinus Torvalds }
2082ae665016SLinus Torvalds 
208383d5cde4SAlexey Dobriyan static const struct block_device_operations lo_fops = {
20841da177e4SLinus Torvalds 	.owner =	THIS_MODULE,
2085bb214884SAl Viro 	.open =		lo_open,
2086bb214884SAl Viro 	.release =	lo_release,
2087bb214884SAl Viro 	.ioctl =	lo_ioctl,
2088863d5b82SDavid Howells #ifdef CONFIG_COMPAT
2089bb214884SAl Viro 	.compat_ioctl =	lo_compat_ioctl,
2090863d5b82SDavid Howells #endif
20911da177e4SLinus Torvalds };
20921da177e4SLinus Torvalds 
20931da177e4SLinus Torvalds /*
20941da177e4SLinus Torvalds  * And now the modules code and kernel interface.
20951da177e4SLinus Torvalds  */
209673285082SKen Chen static int max_loop;
20975657a819SJoe Perches module_param(max_loop, int, 0444);
2098a47653fcSKen Chen MODULE_PARM_DESC(max_loop, "Maximum number of loop devices");
20995657a819SJoe Perches module_param(max_part, int, 0444);
2100476a4813SLaurent Vivier MODULE_PARM_DESC(max_part, "Maximum number of partitions per loop device");
21011da177e4SLinus Torvalds MODULE_LICENSE("GPL");
21021da177e4SLinus Torvalds MODULE_ALIAS_BLOCKDEV_MAJOR(LOOP_MAJOR);
21031da177e4SLinus Torvalds 
21041da177e4SLinus Torvalds int loop_register_transfer(struct loop_func_table *funcs)
21051da177e4SLinus Torvalds {
21061da177e4SLinus Torvalds 	unsigned int n = funcs->number;
21071da177e4SLinus Torvalds 
21081da177e4SLinus Torvalds 	if (n >= MAX_LO_CRYPT || xfer_funcs[n])
21091da177e4SLinus Torvalds 		return -EINVAL;
21101da177e4SLinus Torvalds 	xfer_funcs[n] = funcs;
21111da177e4SLinus Torvalds 	return 0;
21121da177e4SLinus Torvalds }
21131da177e4SLinus Torvalds 
21141da177e4SLinus Torvalds int loop_unregister_transfer(int number)
21151da177e4SLinus Torvalds {
21161da177e4SLinus Torvalds 	unsigned int n = number;
21171da177e4SLinus Torvalds 	struct loop_func_table *xfer;
21181da177e4SLinus Torvalds 
21191da177e4SLinus Torvalds 	if (n == 0 || n >= MAX_LO_CRYPT || (xfer = xfer_funcs[n]) == NULL)
21201da177e4SLinus Torvalds 		return -EINVAL;
21211c500ad7STetsuo Handa 	/*
21221c500ad7STetsuo Handa 	 * This function is called from only cleanup_cryptoloop().
21231c500ad7STetsuo Handa 	 * Given that each loop device that has a transfer enabled holds a
21241c500ad7STetsuo Handa 	 * reference to the module implementing it we should never get here
21251c500ad7STetsuo Handa 	 * with a transfer that is set (unless forced module unloading is
21261c500ad7STetsuo Handa 	 * requested). Thus, check module's refcount and warn if this is
21271c500ad7STetsuo Handa 	 * not a clean unloading.
21281c500ad7STetsuo Handa 	 */
21291c500ad7STetsuo Handa #ifdef CONFIG_MODULE_UNLOAD
21301c500ad7STetsuo Handa 	if (xfer->owner && module_refcount(xfer->owner) != -1)
21311c500ad7STetsuo Handa 		pr_err("Danger! Unregistering an in use transfer function.\n");
21321c500ad7STetsuo Handa #endif
21331da177e4SLinus Torvalds 
21341da177e4SLinus Torvalds 	xfer_funcs[n] = NULL;
21351da177e4SLinus Torvalds 	return 0;
21361da177e4SLinus Torvalds }
21371da177e4SLinus Torvalds 
21381da177e4SLinus Torvalds EXPORT_SYMBOL(loop_register_transfer);
21391da177e4SLinus Torvalds EXPORT_SYMBOL(loop_unregister_transfer);
21401da177e4SLinus Torvalds 
2141fc17b653SChristoph Hellwig static blk_status_t loop_queue_rq(struct blk_mq_hw_ctx *hctx,
2142b5dd2f60SMing Lei 		const struct blk_mq_queue_data *bd)
2143b5dd2f60SMing Lei {
21441894e916SJens Axboe 	struct request *rq = bd->rq;
21451894e916SJens Axboe 	struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
21461894e916SJens Axboe 	struct loop_device *lo = rq->q->queuedata;
2147b5dd2f60SMing Lei 
21481894e916SJens Axboe 	blk_mq_start_request(rq);
2149b5dd2f60SMing Lei 
2150f4aa4c7bSMing Lei 	if (lo->lo_state != Lo_bound)
2151fc17b653SChristoph Hellwig 		return BLK_STS_IOERR;
2152f4aa4c7bSMing Lei 
21531894e916SJens Axboe 	switch (req_op(rq)) {
2154f0225cacSChristoph Hellwig 	case REQ_OP_FLUSH:
2155f0225cacSChristoph Hellwig 	case REQ_OP_DISCARD:
215619372e27SChristoph Hellwig 	case REQ_OP_WRITE_ZEROES:
2157bc07c10aSMing Lei 		cmd->use_aio = false;
2158f0225cacSChristoph Hellwig 		break;
2159f0225cacSChristoph Hellwig 	default:
2160f0225cacSChristoph Hellwig 		cmd->use_aio = lo->use_dio;
2161f0225cacSChristoph Hellwig 		break;
2162f0225cacSChristoph Hellwig 	}
2163bc07c10aSMing Lei 
2164d4478e92SShaohua Li 	/* always use the first bio's css */
2165c74d40e8SDan Schatzberg 	cmd->blkcg_css = NULL;
2166c74d40e8SDan Schatzberg 	cmd->memcg_css = NULL;
21670b508bc9SShaohua Li #ifdef CONFIG_BLK_CGROUP
2168c74d40e8SDan Schatzberg 	if (rq->bio && rq->bio->bi_blkg) {
2169c74d40e8SDan Schatzberg 		cmd->blkcg_css = &bio_blkcg(rq->bio)->css;
2170c74d40e8SDan Schatzberg #ifdef CONFIG_MEMCG
2171c74d40e8SDan Schatzberg 		cmd->memcg_css =
2172c74d40e8SDan Schatzberg 			cgroup_get_e_css(cmd->blkcg_css->cgroup,
2173c74d40e8SDan Schatzberg 					&memory_cgrp_subsys);
2174d4478e92SShaohua Li #endif
2175c74d40e8SDan Schatzberg 	}
2176c74d40e8SDan Schatzberg #endif
217787579e9bSDan Schatzberg 	loop_queue_work(lo, cmd);
2178b5dd2f60SMing Lei 
2179fc17b653SChristoph Hellwig 	return BLK_STS_OK;
2180b5dd2f60SMing Lei }
2181b5dd2f60SMing Lei 
2182b5dd2f60SMing Lei static void loop_handle_cmd(struct loop_cmd *cmd)
2183b5dd2f60SMing Lei {
21841894e916SJens Axboe 	struct request *rq = blk_mq_rq_from_pdu(cmd);
21851894e916SJens Axboe 	const bool write = op_is_write(req_op(rq));
21861894e916SJens Axboe 	struct loop_device *lo = rq->q->queuedata;
2187f4829a9bSChristoph Hellwig 	int ret = 0;
2188c74d40e8SDan Schatzberg 	struct mem_cgroup *old_memcg = NULL;
2189b5dd2f60SMing Lei 
2190f4829a9bSChristoph Hellwig 	if (write && (lo->lo_flags & LO_FLAGS_READ_ONLY)) {
2191f4829a9bSChristoph Hellwig 		ret = -EIO;
2192b5dd2f60SMing Lei 		goto failed;
2193f4829a9bSChristoph Hellwig 	}
2194b5dd2f60SMing Lei 
2195c74d40e8SDan Schatzberg 	if (cmd->blkcg_css)
2196c74d40e8SDan Schatzberg 		kthread_associate_blkcg(cmd->blkcg_css);
2197c74d40e8SDan Schatzberg 	if (cmd->memcg_css)
2198c74d40e8SDan Schatzberg 		old_memcg = set_active_memcg(
2199c74d40e8SDan Schatzberg 			mem_cgroup_from_css(cmd->memcg_css));
2200c74d40e8SDan Schatzberg 
22011894e916SJens Axboe 	ret = do_req_filebacked(lo, rq);
2202c74d40e8SDan Schatzberg 
2203c74d40e8SDan Schatzberg 	if (cmd->blkcg_css)
2204c74d40e8SDan Schatzberg 		kthread_associate_blkcg(NULL);
2205c74d40e8SDan Schatzberg 
2206c74d40e8SDan Schatzberg 	if (cmd->memcg_css) {
2207c74d40e8SDan Schatzberg 		set_active_memcg(old_memcg);
2208c74d40e8SDan Schatzberg 		css_put(cmd->memcg_css);
2209c74d40e8SDan Schatzberg 	}
2210b5dd2f60SMing Lei  failed:
2211bc07c10aSMing Lei 	/* complete non-aio request */
2212fe2cb290SChristoph Hellwig 	if (!cmd->use_aio || ret) {
22138cd55087SEvan Green 		if (ret == -EOPNOTSUPP)
22148cd55087SEvan Green 			cmd->ret = ret;
22158cd55087SEvan Green 		else
2216fe2cb290SChristoph Hellwig 			cmd->ret = ret ? -EIO : 0;
221715f73f5bSChristoph Hellwig 		if (likely(!blk_should_fake_timeout(rq->q)))
22181894e916SJens Axboe 			blk_mq_complete_request(rq);
2219fe2cb290SChristoph Hellwig 	}
2220b5dd2f60SMing Lei }
2221b5dd2f60SMing Lei 
222287579e9bSDan Schatzberg static void loop_set_timer(struct loop_device *lo)
2223b5dd2f60SMing Lei {
222487579e9bSDan Schatzberg 	timer_reduce(&lo->timer, jiffies + LOOP_IDLE_WORKER_TIMEOUT);
2225b5dd2f60SMing Lei }
2226b5dd2f60SMing Lei 
222787579e9bSDan Schatzberg static void loop_process_work(struct loop_worker *worker,
222887579e9bSDan Schatzberg 			struct list_head *cmd_list, struct loop_device *lo)
2229b5dd2f60SMing Lei {
223087579e9bSDan Schatzberg 	int orig_flags = current->flags;
223187579e9bSDan Schatzberg 	struct loop_cmd *cmd;
2232b5dd2f60SMing Lei 
223387579e9bSDan Schatzberg 	current->flags |= PF_LOCAL_THROTTLE | PF_MEMALLOC_NOIO;
223487579e9bSDan Schatzberg 	spin_lock_irq(&lo->lo_work_lock);
223587579e9bSDan Schatzberg 	while (!list_empty(cmd_list)) {
223687579e9bSDan Schatzberg 		cmd = container_of(
223787579e9bSDan Schatzberg 			cmd_list->next, struct loop_cmd, list_entry);
223887579e9bSDan Schatzberg 		list_del(cmd_list->next);
223987579e9bSDan Schatzberg 		spin_unlock_irq(&lo->lo_work_lock);
224087579e9bSDan Schatzberg 
224187579e9bSDan Schatzberg 		loop_handle_cmd(cmd);
224287579e9bSDan Schatzberg 		cond_resched();
224387579e9bSDan Schatzberg 
224487579e9bSDan Schatzberg 		spin_lock_irq(&lo->lo_work_lock);
224587579e9bSDan Schatzberg 	}
224687579e9bSDan Schatzberg 
224787579e9bSDan Schatzberg 	/*
224887579e9bSDan Schatzberg 	 * We only add to the idle list if there are no pending cmds
224987579e9bSDan Schatzberg 	 * *and* the worker will not run again which ensures that it
225087579e9bSDan Schatzberg 	 * is safe to free any worker on the idle list
225187579e9bSDan Schatzberg 	 */
225287579e9bSDan Schatzberg 	if (worker && !work_pending(&worker->work)) {
225387579e9bSDan Schatzberg 		worker->last_ran_at = jiffies;
225487579e9bSDan Schatzberg 		list_add_tail(&worker->idle_list, &lo->idle_worker_list);
225587579e9bSDan Schatzberg 		loop_set_timer(lo);
225687579e9bSDan Schatzberg 	}
225787579e9bSDan Schatzberg 	spin_unlock_irq(&lo->lo_work_lock);
225887579e9bSDan Schatzberg 	current->flags = orig_flags;
225987579e9bSDan Schatzberg }
226087579e9bSDan Schatzberg 
226187579e9bSDan Schatzberg static void loop_workfn(struct work_struct *work)
226287579e9bSDan Schatzberg {
226387579e9bSDan Schatzberg 	struct loop_worker *worker =
226487579e9bSDan Schatzberg 		container_of(work, struct loop_worker, work);
226587579e9bSDan Schatzberg 	loop_process_work(worker, &worker->cmd_list, worker->lo);
226687579e9bSDan Schatzberg }
226787579e9bSDan Schatzberg 
226887579e9bSDan Schatzberg static void loop_rootcg_workfn(struct work_struct *work)
226987579e9bSDan Schatzberg {
227087579e9bSDan Schatzberg 	struct loop_device *lo =
227187579e9bSDan Schatzberg 		container_of(work, struct loop_device, rootcg_work);
227287579e9bSDan Schatzberg 	loop_process_work(NULL, &lo->rootcg_cmd_list, lo);
227387579e9bSDan Schatzberg }
227487579e9bSDan Schatzberg 
227587579e9bSDan Schatzberg static void loop_free_idle_workers(struct timer_list *timer)
227687579e9bSDan Schatzberg {
227787579e9bSDan Schatzberg 	struct loop_device *lo = container_of(timer, struct loop_device, timer);
227887579e9bSDan Schatzberg 	struct loop_worker *pos, *worker;
227987579e9bSDan Schatzberg 
228087579e9bSDan Schatzberg 	spin_lock_irq(&lo->lo_work_lock);
228187579e9bSDan Schatzberg 	list_for_each_entry_safe(worker, pos, &lo->idle_worker_list,
228287579e9bSDan Schatzberg 				idle_list) {
228387579e9bSDan Schatzberg 		if (time_is_after_jiffies(worker->last_ran_at +
228487579e9bSDan Schatzberg 						LOOP_IDLE_WORKER_TIMEOUT))
228587579e9bSDan Schatzberg 			break;
228687579e9bSDan Schatzberg 		list_del(&worker->idle_list);
228787579e9bSDan Schatzberg 		rb_erase(&worker->rb_node, &lo->worker_tree);
2288c74d40e8SDan Schatzberg 		css_put(worker->blkcg_css);
228987579e9bSDan Schatzberg 		kfree(worker);
229087579e9bSDan Schatzberg 	}
229187579e9bSDan Schatzberg 	if (!list_empty(&lo->idle_worker_list))
229287579e9bSDan Schatzberg 		loop_set_timer(lo);
229387579e9bSDan Schatzberg 	spin_unlock_irq(&lo->lo_work_lock);
2294b5dd2f60SMing Lei }
2295b5dd2f60SMing Lei 
2296f363b089SEric Biggers static const struct blk_mq_ops loop_mq_ops = {
2297b5dd2f60SMing Lei 	.queue_rq       = loop_queue_rq,
2298fe2cb290SChristoph Hellwig 	.complete	= lo_complete_rq,
2299b5dd2f60SMing Lei };
2300b5dd2f60SMing Lei 
2301d6da83d0SChristoph Hellwig static int loop_add(int i)
23021da177e4SLinus Torvalds {
230373285082SKen Chen 	struct loop_device *lo;
230473285082SKen Chen 	struct gendisk *disk;
230534dd82afSKay Sievers 	int err;
23061da177e4SLinus Torvalds 
230734dd82afSKay Sievers 	err = -ENOMEM;
230868d740d7SSilva Paulo 	lo = kzalloc(sizeof(*lo), GFP_KERNEL);
230968d740d7SSilva Paulo 	if (!lo)
231073285082SKen Chen 		goto out;
2311ef7e7c82SMikulas Patocka 	lo->lo_state = Lo_unbound;
2312ef7e7c82SMikulas Patocka 
231318d1f200SChristoph Hellwig 	err = mutex_lock_killable(&loop_ctl_mutex);
231418d1f200SChristoph Hellwig 	if (err)
231518d1f200SChristoph Hellwig 		goto out_free_dev;
231618d1f200SChristoph Hellwig 
2317c718aa65STejun Heo 	/* allocate id, if @id >= 0, we're requesting that specific id */
231834dd82afSKay Sievers 	if (i >= 0) {
2319c718aa65STejun Heo 		err = idr_alloc(&loop_index_idr, lo, i, i + 1, GFP_KERNEL);
2320c718aa65STejun Heo 		if (err == -ENOSPC)
232134dd82afSKay Sievers 			err = -EEXIST;
232234dd82afSKay Sievers 	} else {
2323c718aa65STejun Heo 		err = idr_alloc(&loop_index_idr, lo, 0, 0, GFP_KERNEL);
232434dd82afSKay Sievers 	}
23251c500ad7STetsuo Handa 	mutex_unlock(&loop_ctl_mutex);
232634dd82afSKay Sievers 	if (err < 0)
23271c500ad7STetsuo Handa 		goto out_free_dev;
2328c718aa65STejun Heo 	i = err;
23291da177e4SLinus Torvalds 
2330183cfb57SWei Yongjun 	err = -ENOMEM;
2331b5dd2f60SMing Lei 	lo->tag_set.ops = &loop_mq_ops;
2332b5dd2f60SMing Lei 	lo->tag_set.nr_hw_queues = 1;
2333b5dd2f60SMing Lei 	lo->tag_set.queue_depth = 128;
2334b5dd2f60SMing Lei 	lo->tag_set.numa_node = NUMA_NO_NODE;
2335b5dd2f60SMing Lei 	lo->tag_set.cmd_size = sizeof(struct loop_cmd);
23362112f5c1SBart Van Assche 	lo->tag_set.flags = BLK_MQ_F_SHOULD_MERGE | BLK_MQ_F_STACKING |
23372112f5c1SBart Van Assche 		BLK_MQ_F_NO_SCHED_BY_DEFAULT;
2338b5dd2f60SMing Lei 	lo->tag_set.driver_data = lo;
2339b5dd2f60SMing Lei 
2340b5dd2f60SMing Lei 	err = blk_mq_alloc_tag_set(&lo->tag_set);
2341b5dd2f60SMing Lei 	if (err)
23423ec981e3SMikulas Patocka 		goto out_free_idr;
234373285082SKen Chen 
23441c99502fSChristoph Hellwig 	disk = lo->lo_disk = blk_mq_alloc_disk(&lo->tag_set, lo);
23451c99502fSChristoph Hellwig 	if (IS_ERR(disk)) {
23461c99502fSChristoph Hellwig 		err = PTR_ERR(disk);
2347b5dd2f60SMing Lei 		goto out_cleanup_tags;
2348b5dd2f60SMing Lei 	}
23491c99502fSChristoph Hellwig 	lo->lo_queue = lo->lo_disk->queue;
2350ef7e7c82SMikulas Patocka 
235154bb0adeSShaohua Li 	blk_queue_max_hw_sectors(lo->lo_queue, BLK_DEF_MAX_SECTORS);
235240326d8aSShaohua Li 
23535b5e20f4SMing Lei 	/*
235440326d8aSShaohua Li 	 * By default, we do buffer IO, so it doesn't make sense to enable
235540326d8aSShaohua Li 	 * merge because the I/O submitted to backing file is handled page by
235640326d8aSShaohua Li 	 * page. For directio mode, merge does help to dispatch bigger request
235740326d8aSShaohua Li 	 * to underlayer disk. We will enable merge once directio is enabled.
23585b5e20f4SMing Lei 	 */
23598b904b5bSBart Van Assche 	blk_queue_flag_set(QUEUE_FLAG_NOMERGES, lo->lo_queue);
23605b5e20f4SMing Lei 
2361e03c8dd1SKay Sievers 	/*
2362e03c8dd1SKay Sievers 	 * Disable partition scanning by default. The in-kernel partition
2363e03c8dd1SKay Sievers 	 * scanning can be requested individually per-device during its
2364e03c8dd1SKay Sievers 	 * setup. Userspace can always add and remove partitions from all
2365e03c8dd1SKay Sievers 	 * devices. The needed partition minors are allocated from the
2366e03c8dd1SKay Sievers 	 * extended minor space, the main loop device numbers will continue
2367e03c8dd1SKay Sievers 	 * to match the loop minors, regardless of the number of partitions
2368e03c8dd1SKay Sievers 	 * used.
2369e03c8dd1SKay Sievers 	 *
2370e03c8dd1SKay Sievers 	 * If max_part is given, partition scanning is globally enabled for
2371e03c8dd1SKay Sievers 	 * all loop devices. The minors for the main loop devices will be
2372e03c8dd1SKay Sievers 	 * multiples of max_part.
2373e03c8dd1SKay Sievers 	 *
2374e03c8dd1SKay Sievers 	 * Note: Global-for-all-devices, set-only-at-init, read-only module
2375e03c8dd1SKay Sievers 	 * parameteters like 'max_loop' and 'max_part' make things needlessly
2376e03c8dd1SKay Sievers 	 * complicated, are too static, inflexible and may surprise
2377e03c8dd1SKay Sievers 	 * userspace tools. Parameters like this in general should be avoided.
2378e03c8dd1SKay Sievers 	 */
2379e03c8dd1SKay Sievers 	if (!part_shift)
2380e03c8dd1SKay Sievers 		disk->flags |= GENHD_FL_NO_PART_SCAN;
2381e03c8dd1SKay Sievers 	disk->flags |= GENHD_FL_EXT_DEVT;
2382f8933667SMing Lei 	atomic_set(&lo->lo_refcnt, 0);
23836cc8e743SPavel Tatashin 	mutex_init(&lo->lo_mutex);
23841da177e4SLinus Torvalds 	lo->lo_number		= i;
23851da177e4SLinus Torvalds 	spin_lock_init(&lo->lo_lock);
238687579e9bSDan Schatzberg 	spin_lock_init(&lo->lo_work_lock);
23871da177e4SLinus Torvalds 	disk->major		= LOOP_MAJOR;
2388476a4813SLaurent Vivier 	disk->first_minor	= i << part_shift;
23891c99502fSChristoph Hellwig 	disk->minors		= 1 << part_shift;
23901da177e4SLinus Torvalds 	disk->fops		= &lo_fops;
23911da177e4SLinus Torvalds 	disk->private_data	= lo;
23921da177e4SLinus Torvalds 	disk->queue		= lo->lo_queue;
23939f65c489SMatteo Croce 	disk->events		= DISK_EVENT_MEDIA_CHANGE;
23949f65c489SMatteo Croce 	disk->event_flags	= DISK_EVENT_FLAG_UEVENT;
239573285082SKen Chen 	sprintf(disk->disk_name, "loop%d", i);
23961c500ad7STetsuo Handa 	/* Make this loop device reachable from pathname. */
239734dd82afSKay Sievers 	add_disk(disk);
23981c500ad7STetsuo Handa 	/* Show this loop device. */
23991c500ad7STetsuo Handa 	mutex_lock(&loop_ctl_mutex);
24001c500ad7STetsuo Handa 	lo->idr_visible = true;
240118d1f200SChristoph Hellwig 	mutex_unlock(&loop_ctl_mutex);
240218d1f200SChristoph Hellwig 	return i;
240373285082SKen Chen 
2404b5dd2f60SMing Lei out_cleanup_tags:
2405b5dd2f60SMing Lei 	blk_mq_free_tag_set(&lo->tag_set);
24063ec981e3SMikulas Patocka out_free_idr:
24071c500ad7STetsuo Handa 	mutex_lock(&loop_ctl_mutex);
24083ec981e3SMikulas Patocka 	idr_remove(&loop_index_idr, i);
240918d1f200SChristoph Hellwig 	mutex_unlock(&loop_ctl_mutex);
241073285082SKen Chen out_free_dev:
241173285082SKen Chen 	kfree(lo);
241273285082SKen Chen out:
241334dd82afSKay Sievers 	return err;
24141da177e4SLinus Torvalds }
24151da177e4SLinus Torvalds 
241634dd82afSKay Sievers static void loop_remove(struct loop_device *lo)
241773285082SKen Chen {
24181c500ad7STetsuo Handa 	/* Make this loop device unreachable from pathname. */
24196cd18e71SNeilBrown 	del_gendisk(lo->lo_disk);
24201c99502fSChristoph Hellwig 	blk_cleanup_disk(lo->lo_disk);
2421b5dd2f60SMing Lei 	blk_mq_free_tag_set(&lo->tag_set);
24221c500ad7STetsuo Handa 	mutex_lock(&loop_ctl_mutex);
24231c500ad7STetsuo Handa 	idr_remove(&loop_index_idr, lo->lo_number);
24241c500ad7STetsuo Handa 	mutex_unlock(&loop_ctl_mutex);
24251c500ad7STetsuo Handa 	/* There is no route which can find this loop device. */
24266cc8e743SPavel Tatashin 	mutex_destroy(&lo->lo_mutex);
242773285082SKen Chen 	kfree(lo);
242873285082SKen Chen }
242973285082SKen Chen 
24308410d38cSChristoph Hellwig static void loop_probe(dev_t dev)
243173285082SKen Chen {
24328410d38cSChristoph Hellwig 	int idx = MINOR(dev) >> part_shift;
24338410d38cSChristoph Hellwig 
24348410d38cSChristoph Hellwig 	if (max_loop && idx >= max_loop)
24358410d38cSChristoph Hellwig 		return;
2436d6da83d0SChristoph Hellwig 	loop_add(idx);
2437f9d10764SChristoph Hellwig }
2438f9d10764SChristoph Hellwig 
2439f9d10764SChristoph Hellwig static int loop_control_remove(int idx)
2440770fe30aSKay Sievers {
2441770fe30aSKay Sievers 	struct loop_device *lo;
24420a42e99bSJan Kara 	int ret;
2443e5d66a10SChristoph Hellwig 
2444e5d66a10SChristoph Hellwig 	if (idx < 0) {
2445e5d66a10SChristoph Hellwig 		pr_warn("deleting an unspecified loop device is not supported.\n");
2446e5d66a10SChristoph Hellwig 		return -EINVAL;
2447e5d66a10SChristoph Hellwig 	}
2448770fe30aSKay Sievers 
24491c500ad7STetsuo Handa 	/* Hide this loop device for serialization. */
24500a42e99bSJan Kara 	ret = mutex_lock_killable(&loop_ctl_mutex);
24510a42e99bSJan Kara 	if (ret)
24520a42e99bSJan Kara 		return ret;
2453b9848081SChristoph Hellwig 	lo = idr_find(&loop_index_idr, idx);
24541c500ad7STetsuo Handa 	if (!lo || !lo->idr_visible)
2455b9848081SChristoph Hellwig 		ret = -ENODEV;
24561c500ad7STetsuo Handa 	else
24571c500ad7STetsuo Handa 		lo->idr_visible = false;
24581c500ad7STetsuo Handa 	mutex_unlock(&loop_ctl_mutex);
24591c500ad7STetsuo Handa 	if (ret)
24601c500ad7STetsuo Handa 		return ret;
2461f9d10764SChristoph Hellwig 
24621c500ad7STetsuo Handa 	/* Check whether this loop device can be removed. */
24636cc8e743SPavel Tatashin 	ret = mutex_lock_killable(&lo->lo_mutex);
24646cc8e743SPavel Tatashin 	if (ret)
24651c500ad7STetsuo Handa 		goto mark_visible;
2466f9d10764SChristoph Hellwig 	if (lo->lo_state != Lo_unbound ||
2467f9d10764SChristoph Hellwig 	    atomic_read(&lo->lo_refcnt) > 0) {
24686cc8e743SPavel Tatashin 		mutex_unlock(&lo->lo_mutex);
2469770fe30aSKay Sievers 		ret = -EBUSY;
24701c500ad7STetsuo Handa 		goto mark_visible;
2471770fe30aSKay Sievers 	}
24721c500ad7STetsuo Handa 	/* Mark this loop device no longer open()-able. */
2473990e7811SChristoph Hellwig 	lo->lo_state = Lo_deleting;
24746cc8e743SPavel Tatashin 	mutex_unlock(&lo->lo_mutex);
2475f9d10764SChristoph Hellwig 
2476770fe30aSKay Sievers 	loop_remove(lo);
24771c500ad7STetsuo Handa 	return 0;
24781c500ad7STetsuo Handa 
24791c500ad7STetsuo Handa mark_visible:
24801c500ad7STetsuo Handa 	/* Show this loop device again. */
24811c500ad7STetsuo Handa 	mutex_lock(&loop_ctl_mutex);
24821c500ad7STetsuo Handa 	lo->idr_visible = true;
2483f9d10764SChristoph Hellwig 	mutex_unlock(&loop_ctl_mutex);
2484f9d10764SChristoph Hellwig 	return ret;
2485770fe30aSKay Sievers }
2486f9d10764SChristoph Hellwig 
2487f9d10764SChristoph Hellwig static int loop_control_get_free(int idx)
2488f9d10764SChristoph Hellwig {
2489f9d10764SChristoph Hellwig 	struct loop_device *lo;
2490b9848081SChristoph Hellwig 	int id, ret;
2491f9d10764SChristoph Hellwig 
2492f9d10764SChristoph Hellwig 	ret = mutex_lock_killable(&loop_ctl_mutex);
2493f9d10764SChristoph Hellwig 	if (ret)
2494f9d10764SChristoph Hellwig 		return ret;
2495b9848081SChristoph Hellwig 	idr_for_each_entry(&loop_index_idr, lo, id) {
24961c500ad7STetsuo Handa 		/* Hitting a race results in creating a new loop device which is harmless. */
24971c500ad7STetsuo Handa 		if (lo->idr_visible && data_race(lo->lo_state) == Lo_unbound)
2498b9848081SChristoph Hellwig 			goto found;
2499b9848081SChristoph Hellwig 	}
25000a42e99bSJan Kara 	mutex_unlock(&loop_ctl_mutex);
250118d1f200SChristoph Hellwig 	return loop_add(-1);
2502b9848081SChristoph Hellwig found:
2503b9848081SChristoph Hellwig 	mutex_unlock(&loop_ctl_mutex);
2504b9848081SChristoph Hellwig 	return id;
2505770fe30aSKay Sievers }
2506770fe30aSKay Sievers 
2507f9d10764SChristoph Hellwig static long loop_control_ioctl(struct file *file, unsigned int cmd,
2508f9d10764SChristoph Hellwig 			       unsigned long parm)
2509f9d10764SChristoph Hellwig {
2510f9d10764SChristoph Hellwig 	switch (cmd) {
2511f9d10764SChristoph Hellwig 	case LOOP_CTL_ADD:
251218d1f200SChristoph Hellwig 		return loop_add(parm);
2513f9d10764SChristoph Hellwig 	case LOOP_CTL_REMOVE:
2514f9d10764SChristoph Hellwig 		return loop_control_remove(parm);
2515f9d10764SChristoph Hellwig 	case LOOP_CTL_GET_FREE:
2516f9d10764SChristoph Hellwig 		return loop_control_get_free(parm);
2517f9d10764SChristoph Hellwig 	default:
2518f9d10764SChristoph Hellwig 		return -ENOSYS;
2519f9d10764SChristoph Hellwig 	}
2520f9d10764SChristoph Hellwig }
2521f9d10764SChristoph Hellwig 
2522770fe30aSKay Sievers static const struct file_operations loop_ctl_fops = {
2523770fe30aSKay Sievers 	.open		= nonseekable_open,
2524770fe30aSKay Sievers 	.unlocked_ioctl	= loop_control_ioctl,
2525770fe30aSKay Sievers 	.compat_ioctl	= loop_control_ioctl,
2526770fe30aSKay Sievers 	.owner		= THIS_MODULE,
2527770fe30aSKay Sievers 	.llseek		= noop_llseek,
2528770fe30aSKay Sievers };
2529770fe30aSKay Sievers 
2530770fe30aSKay Sievers static struct miscdevice loop_misc = {
2531770fe30aSKay Sievers 	.minor		= LOOP_CTRL_MINOR,
2532770fe30aSKay Sievers 	.name		= "loop-control",
2533770fe30aSKay Sievers 	.fops		= &loop_ctl_fops,
2534770fe30aSKay Sievers };
2535770fe30aSKay Sievers 
2536770fe30aSKay Sievers MODULE_ALIAS_MISCDEV(LOOP_CTRL_MINOR);
2537770fe30aSKay Sievers MODULE_ALIAS("devname:loop-control");
2538770fe30aSKay Sievers 
253973285082SKen Chen static int __init loop_init(void)
254073285082SKen Chen {
2541a47653fcSKen Chen 	int i, nr;
2542770fe30aSKay Sievers 	int err;
2543a47653fcSKen Chen 
2544476a4813SLaurent Vivier 	part_shift = 0;
2545ac04fee0SNamhyung Kim 	if (max_part > 0) {
2546476a4813SLaurent Vivier 		part_shift = fls(max_part);
2547476a4813SLaurent Vivier 
2548ac04fee0SNamhyung Kim 		/*
2549ac04fee0SNamhyung Kim 		 * Adjust max_part according to part_shift as it is exported
2550ac04fee0SNamhyung Kim 		 * to user space so that user can decide correct minor number
2551ac04fee0SNamhyung Kim 		 * if [s]he want to create more devices.
2552ac04fee0SNamhyung Kim 		 *
2553ac04fee0SNamhyung Kim 		 * Note that -1 is required because partition 0 is reserved
2554ac04fee0SNamhyung Kim 		 * for the whole disk.
2555ac04fee0SNamhyung Kim 		 */
2556ac04fee0SNamhyung Kim 		max_part = (1UL << part_shift) - 1;
2557ac04fee0SNamhyung Kim 	}
2558ac04fee0SNamhyung Kim 
2559b1a66504SGuo Chao 	if ((1UL << part_shift) > DISK_MAX_PARTS) {
2560b1a66504SGuo Chao 		err = -EINVAL;
2561a8c1d064SAnton Volkov 		goto err_out;
2562b1a66504SGuo Chao 	}
256378f4bb36SNamhyung Kim 
2564b1a66504SGuo Chao 	if (max_loop > 1UL << (MINORBITS - part_shift)) {
2565b1a66504SGuo Chao 		err = -EINVAL;
2566a8c1d064SAnton Volkov 		goto err_out;
2567b1a66504SGuo Chao 	}
256873285082SKen Chen 
2569d134b00bSKay Sievers 	/*
2570d134b00bSKay Sievers 	 * If max_loop is specified, create that many devices upfront.
2571d134b00bSKay Sievers 	 * This also becomes a hard limit. If max_loop is not specified,
2572d134b00bSKay Sievers 	 * create CONFIG_BLK_DEV_LOOP_MIN_COUNT loop devices at module
2573d134b00bSKay Sievers 	 * init time. Loop devices can be requested on-demand with the
2574d134b00bSKay Sievers 	 * /dev/loop-control interface, or be instantiated by accessing
2575d134b00bSKay Sievers 	 * a 'dead' device node.
2576d134b00bSKay Sievers 	 */
2577aeb2b0b1SLukas Bulwahn 	if (max_loop)
2578a47653fcSKen Chen 		nr = max_loop;
2579aeb2b0b1SLukas Bulwahn 	else
2580d134b00bSKay Sievers 		nr = CONFIG_BLK_DEV_LOOP_MIN_COUNT;
2581a47653fcSKen Chen 
2582a8c1d064SAnton Volkov 	err = misc_register(&loop_misc);
2583a8c1d064SAnton Volkov 	if (err < 0)
2584a8c1d064SAnton Volkov 		goto err_out;
2585a8c1d064SAnton Volkov 
2586a8c1d064SAnton Volkov 
25878410d38cSChristoph Hellwig 	if (__register_blkdev(LOOP_MAJOR, "loop", loop_probe)) {
2588b1a66504SGuo Chao 		err = -EIO;
2589b1a66504SGuo Chao 		goto misc_out;
2590b1a66504SGuo Chao 	}
2591a47653fcSKen Chen 
2592d134b00bSKay Sievers 	/* pre-create number of devices given by config or max_loop */
259334dd82afSKay Sievers 	for (i = 0; i < nr; i++)
2594d6da83d0SChristoph Hellwig 		loop_add(i);
259534dd82afSKay Sievers 
259673285082SKen Chen 	printk(KERN_INFO "loop: module loaded\n");
25971da177e4SLinus Torvalds 	return 0;
2598b1a66504SGuo Chao 
2599b1a66504SGuo Chao misc_out:
2600b1a66504SGuo Chao 	misc_deregister(&loop_misc);
2601a8c1d064SAnton Volkov err_out:
2602b1a66504SGuo Chao 	return err;
260334dd82afSKay Sievers }
2604a47653fcSKen Chen 
260573285082SKen Chen static void __exit loop_exit(void)
26061da177e4SLinus Torvalds {
26078e60947dSChristoph Hellwig 	struct loop_device *lo;
26088e60947dSChristoph Hellwig 	int id;
26098e60947dSChristoph Hellwig 
26108b52d8beSChristoph Hellwig 	unregister_blkdev(LOOP_MAJOR, "loop");
26118b52d8beSChristoph Hellwig 	misc_deregister(&loop_misc);
2612200f9337SLuis Chamberlain 
26131c500ad7STetsuo Handa 	/*
26141c500ad7STetsuo Handa 	 * There is no need to use loop_ctl_mutex here, for nobody else can
26151c500ad7STetsuo Handa 	 * access loop_index_idr when this module is unloading (unless forced
26161c500ad7STetsuo Handa 	 * module unloading is requested). If this is not a clean unloading,
26171c500ad7STetsuo Handa 	 * we have no means to avoid kernel crash.
26181c500ad7STetsuo Handa 	 */
26198e60947dSChristoph Hellwig 	idr_for_each_entry(&loop_index_idr, lo, id)
26208e60947dSChristoph Hellwig 		loop_remove(lo);
2621bd5c39edSChristoph Hellwig 
2622bd5c39edSChristoph Hellwig 	idr_destroy(&loop_index_idr);
26231da177e4SLinus Torvalds }
26241da177e4SLinus Torvalds 
26251da177e4SLinus Torvalds module_init(loop_init);
26261da177e4SLinus Torvalds module_exit(loop_exit);
26271da177e4SLinus Torvalds 
26281da177e4SLinus Torvalds #ifndef MODULE
26291da177e4SLinus Torvalds static int __init max_loop_setup(char *str)
26301da177e4SLinus Torvalds {
26311da177e4SLinus Torvalds 	max_loop = simple_strtol(str, NULL, 0);
26321da177e4SLinus Torvalds 	return 1;
26331da177e4SLinus Torvalds }
26341da177e4SLinus Torvalds 
26351da177e4SLinus Torvalds __setup("max_loop=", max_loop_setup);
26361da177e4SLinus Torvalds #endif
2637