xref: /openbmc/linux/drivers/block/loop.c (revision e515be8f)
1 /*
2  *  linux/drivers/block/loop.c
3  *
4  *  Written by Theodore Ts'o, 3/29/93
5  *
6  * Copyright 1993 by Theodore Ts'o.  Redistribution of this file is
7  * permitted under the GNU General Public License.
8  *
9  * DES encryption plus some minor changes by Werner Almesberger, 30-MAY-1993
10  * more DES encryption plus IDEA encryption by Nicholas J. Leon, June 20, 1996
11  *
12  * Modularized and updated for 1.1.16 kernel - Mitch Dsouza 28th May 1994
13  * Adapted for 1.3.59 kernel - Andries Brouwer, 1 Feb 1996
14  *
15  * Fixed do_loop_request() re-entrancy - Vincent.Renardias@waw.com Mar 20, 1997
16  *
17  * Added devfs support - Richard Gooch <rgooch@atnf.csiro.au> 16-Jan-1998
18  *
19  * Handle sparse backing files correctly - Kenn Humborg, Jun 28, 1998
20  *
21  * Loadable modules and other fixes by AK, 1998
22  *
23  * Make real block number available to downstream transfer functions, enables
24  * CBC (and relatives) mode encryption requiring unique IVs per data block.
25  * Reed H. Petty, rhp@draper.net
26  *
27  * Maximum number of loop devices now dynamic via max_loop module parameter.
28  * Russell Kroll <rkroll@exploits.org> 19990701
29  *
30  * Maximum number of loop devices when compiled-in now selectable by passing
31  * max_loop=<1-255> to the kernel on boot.
32  * Erik I. Bolsø, <eriki@himolde.no>, Oct 31, 1999
33  *
34  * Completely rewrite request handling to be make_request_fn style and
35  * non blocking, pushing work to a helper thread. Lots of fixes from
36  * Al Viro too.
37  * Jens Axboe <axboe@suse.de>, Nov 2000
38  *
39  * Support up to 256 loop devices
40  * Heinz Mauelshagen <mge@sistina.com>, Feb 2002
41  *
42  * Support for falling back on the write file operation when the address space
43  * operations write_begin is not available on the backing filesystem.
44  * Anton Altaparmakov, 16 Feb 2005
45  *
46  * Still To Fix:
47  * - Advisory locking is ignored here.
48  * - Should use an own CAP_* category instead of CAP_SYS_ADMIN
49  *
50  */
51 
52 #include <linux/module.h>
53 #include <linux/moduleparam.h>
54 #include <linux/sched.h>
55 #include <linux/fs.h>
56 #include <linux/pagemap.h>
57 #include <linux/file.h>
58 #include <linux/stat.h>
59 #include <linux/errno.h>
60 #include <linux/major.h>
61 #include <linux/wait.h>
62 #include <linux/blkdev.h>
63 #include <linux/blkpg.h>
64 #include <linux/init.h>
65 #include <linux/swap.h>
66 #include <linux/slab.h>
67 #include <linux/compat.h>
68 #include <linux/suspend.h>
69 #include <linux/freezer.h>
70 #include <linux/mutex.h>
71 #include <linux/writeback.h>
72 #include <linux/completion.h>
73 #include <linux/highmem.h>
74 #include <linux/splice.h>
75 #include <linux/sysfs.h>
76 #include <linux/miscdevice.h>
77 #include <linux/falloc.h>
78 #include <linux/uio.h>
79 #include <linux/ioprio.h>
80 #include <linux/blk-cgroup.h>
81 #include <linux/sched/mm.h>
82 
83 #include "loop.h"
84 
85 #include <linux/uaccess.h>
86 
87 #define LOOP_IDLE_WORKER_TIMEOUT (60 * HZ)
88 
89 static DEFINE_IDR(loop_index_idr);
90 static DEFINE_MUTEX(loop_ctl_mutex);
91 static DEFINE_MUTEX(loop_validate_mutex);
92 
93 /**
94  * loop_global_lock_killable() - take locks for safe loop_validate_file() test
95  *
96  * @lo: struct loop_device
97  * @global: true if @lo is about to bind another "struct loop_device", false otherwise
98  *
99  * Returns 0 on success, -EINTR otherwise.
100  *
101  * Since loop_validate_file() traverses on other "struct loop_device" if
102  * is_loop_device() is true, we need a global lock for serializing concurrent
103  * loop_configure()/loop_change_fd()/__loop_clr_fd() calls.
104  */
105 static int loop_global_lock_killable(struct loop_device *lo, bool global)
106 {
107 	int err;
108 
109 	if (global) {
110 		err = mutex_lock_killable(&loop_validate_mutex);
111 		if (err)
112 			return err;
113 	}
114 	err = mutex_lock_killable(&lo->lo_mutex);
115 	if (err && global)
116 		mutex_unlock(&loop_validate_mutex);
117 	return err;
118 }
119 
120 /**
121  * loop_global_unlock() - release locks taken by loop_global_lock_killable()
122  *
123  * @lo: struct loop_device
124  * @global: true if @lo was about to bind another "struct loop_device", false otherwise
125  */
126 static void loop_global_unlock(struct loop_device *lo, bool global)
127 {
128 	mutex_unlock(&lo->lo_mutex);
129 	if (global)
130 		mutex_unlock(&loop_validate_mutex);
131 }
132 
133 static int max_part;
134 static int part_shift;
135 
136 static int transfer_xor(struct loop_device *lo, int cmd,
137 			struct page *raw_page, unsigned raw_off,
138 			struct page *loop_page, unsigned loop_off,
139 			int size, sector_t real_block)
140 {
141 	char *raw_buf = kmap_atomic(raw_page) + raw_off;
142 	char *loop_buf = kmap_atomic(loop_page) + loop_off;
143 	char *in, *out, *key;
144 	int i, keysize;
145 
146 	if (cmd == READ) {
147 		in = raw_buf;
148 		out = loop_buf;
149 	} else {
150 		in = loop_buf;
151 		out = raw_buf;
152 	}
153 
154 	key = lo->lo_encrypt_key;
155 	keysize = lo->lo_encrypt_key_size;
156 	for (i = 0; i < size; i++)
157 		*out++ = *in++ ^ key[(i & 511) % keysize];
158 
159 	kunmap_atomic(loop_buf);
160 	kunmap_atomic(raw_buf);
161 	cond_resched();
162 	return 0;
163 }
164 
165 static int xor_init(struct loop_device *lo, const struct loop_info64 *info)
166 {
167 	if (unlikely(info->lo_encrypt_key_size <= 0))
168 		return -EINVAL;
169 	return 0;
170 }
171 
172 static struct loop_func_table none_funcs = {
173 	.number = LO_CRYPT_NONE,
174 };
175 
176 static struct loop_func_table xor_funcs = {
177 	.number = LO_CRYPT_XOR,
178 	.transfer = transfer_xor,
179 	.init = xor_init
180 };
181 
182 /* xfer_funcs[0] is special - its release function is never called */
183 static struct loop_func_table *xfer_funcs[MAX_LO_CRYPT] = {
184 	&none_funcs,
185 	&xor_funcs
186 };
187 
188 static loff_t get_size(loff_t offset, loff_t sizelimit, struct file *file)
189 {
190 	loff_t loopsize;
191 
192 	/* Compute loopsize in bytes */
193 	loopsize = i_size_read(file->f_mapping->host);
194 	if (offset > 0)
195 		loopsize -= offset;
196 	/* offset is beyond i_size, weird but possible */
197 	if (loopsize < 0)
198 		return 0;
199 
200 	if (sizelimit > 0 && sizelimit < loopsize)
201 		loopsize = sizelimit;
202 	/*
203 	 * Unfortunately, if we want to do I/O on the device,
204 	 * the number of 512-byte sectors has to fit into a sector_t.
205 	 */
206 	return loopsize >> 9;
207 }
208 
209 static loff_t get_loop_size(struct loop_device *lo, struct file *file)
210 {
211 	return get_size(lo->lo_offset, lo->lo_sizelimit, file);
212 }
213 
214 static void __loop_update_dio(struct loop_device *lo, bool dio)
215 {
216 	struct file *file = lo->lo_backing_file;
217 	struct address_space *mapping = file->f_mapping;
218 	struct inode *inode = mapping->host;
219 	unsigned short sb_bsize = 0;
220 	unsigned dio_align = 0;
221 	bool use_dio;
222 
223 	if (inode->i_sb->s_bdev) {
224 		sb_bsize = bdev_logical_block_size(inode->i_sb->s_bdev);
225 		dio_align = sb_bsize - 1;
226 	}
227 
228 	/*
229 	 * We support direct I/O only if lo_offset is aligned with the
230 	 * logical I/O size of backing device, and the logical block
231 	 * size of loop is bigger than the backing device's and the loop
232 	 * needn't transform transfer.
233 	 *
234 	 * TODO: the above condition may be loosed in the future, and
235 	 * direct I/O may be switched runtime at that time because most
236 	 * of requests in sane applications should be PAGE_SIZE aligned
237 	 */
238 	if (dio) {
239 		if (queue_logical_block_size(lo->lo_queue) >= sb_bsize &&
240 				!(lo->lo_offset & dio_align) &&
241 				mapping->a_ops->direct_IO &&
242 				!lo->transfer)
243 			use_dio = true;
244 		else
245 			use_dio = false;
246 	} else {
247 		use_dio = false;
248 	}
249 
250 	if (lo->use_dio == use_dio)
251 		return;
252 
253 	/* flush dirty pages before changing direct IO */
254 	vfs_fsync(file, 0);
255 
256 	/*
257 	 * The flag of LO_FLAGS_DIRECT_IO is handled similarly with
258 	 * LO_FLAGS_READ_ONLY, both are set from kernel, and losetup
259 	 * will get updated by ioctl(LOOP_GET_STATUS)
260 	 */
261 	if (lo->lo_state == Lo_bound)
262 		blk_mq_freeze_queue(lo->lo_queue);
263 	lo->use_dio = use_dio;
264 	if (use_dio) {
265 		blk_queue_flag_clear(QUEUE_FLAG_NOMERGES, lo->lo_queue);
266 		lo->lo_flags |= LO_FLAGS_DIRECT_IO;
267 	} else {
268 		blk_queue_flag_set(QUEUE_FLAG_NOMERGES, lo->lo_queue);
269 		lo->lo_flags &= ~LO_FLAGS_DIRECT_IO;
270 	}
271 	if (lo->lo_state == Lo_bound)
272 		blk_mq_unfreeze_queue(lo->lo_queue);
273 }
274 
275 /**
276  * loop_validate_block_size() - validates the passed in block size
277  * @bsize: size to validate
278  */
279 static int
280 loop_validate_block_size(unsigned short bsize)
281 {
282 	if (bsize < 512 || bsize > PAGE_SIZE || !is_power_of_2(bsize))
283 		return -EINVAL;
284 
285 	return 0;
286 }
287 
288 /**
289  * loop_set_size() - sets device size and notifies userspace
290  * @lo: struct loop_device to set the size for
291  * @size: new size of the loop device
292  *
293  * Callers must validate that the size passed into this function fits into
294  * a sector_t, eg using loop_validate_size()
295  */
296 static void loop_set_size(struct loop_device *lo, loff_t size)
297 {
298 	if (!set_capacity_and_notify(lo->lo_disk, size))
299 		kobject_uevent(&disk_to_dev(lo->lo_disk)->kobj, KOBJ_CHANGE);
300 }
301 
302 static inline int
303 lo_do_transfer(struct loop_device *lo, int cmd,
304 	       struct page *rpage, unsigned roffs,
305 	       struct page *lpage, unsigned loffs,
306 	       int size, sector_t rblock)
307 {
308 	int ret;
309 
310 	ret = lo->transfer(lo, cmd, rpage, roffs, lpage, loffs, size, rblock);
311 	if (likely(!ret))
312 		return 0;
313 
314 	printk_ratelimited(KERN_ERR
315 		"loop: Transfer error at byte offset %llu, length %i.\n",
316 		(unsigned long long)rblock << 9, size);
317 	return ret;
318 }
319 
320 static int lo_write_bvec(struct file *file, struct bio_vec *bvec, loff_t *ppos)
321 {
322 	struct iov_iter i;
323 	ssize_t bw;
324 
325 	iov_iter_bvec(&i, WRITE, bvec, 1, bvec->bv_len);
326 
327 	file_start_write(file);
328 	bw = vfs_iter_write(file, &i, ppos, 0);
329 	file_end_write(file);
330 
331 	if (likely(bw ==  bvec->bv_len))
332 		return 0;
333 
334 	printk_ratelimited(KERN_ERR
335 		"loop: Write error at byte offset %llu, length %i.\n",
336 		(unsigned long long)*ppos, bvec->bv_len);
337 	if (bw >= 0)
338 		bw = -EIO;
339 	return bw;
340 }
341 
342 static int lo_write_simple(struct loop_device *lo, struct request *rq,
343 		loff_t pos)
344 {
345 	struct bio_vec bvec;
346 	struct req_iterator iter;
347 	int ret = 0;
348 
349 	rq_for_each_segment(bvec, rq, iter) {
350 		ret = lo_write_bvec(lo->lo_backing_file, &bvec, &pos);
351 		if (ret < 0)
352 			break;
353 		cond_resched();
354 	}
355 
356 	return ret;
357 }
358 
359 /*
360  * This is the slow, transforming version that needs to double buffer the
361  * data as it cannot do the transformations in place without having direct
362  * access to the destination pages of the backing file.
363  */
364 static int lo_write_transfer(struct loop_device *lo, struct request *rq,
365 		loff_t pos)
366 {
367 	struct bio_vec bvec, b;
368 	struct req_iterator iter;
369 	struct page *page;
370 	int ret = 0;
371 
372 	page = alloc_page(GFP_NOIO);
373 	if (unlikely(!page))
374 		return -ENOMEM;
375 
376 	rq_for_each_segment(bvec, rq, iter) {
377 		ret = lo_do_transfer(lo, WRITE, page, 0, bvec.bv_page,
378 			bvec.bv_offset, bvec.bv_len, pos >> 9);
379 		if (unlikely(ret))
380 			break;
381 
382 		b.bv_page = page;
383 		b.bv_offset = 0;
384 		b.bv_len = bvec.bv_len;
385 		ret = lo_write_bvec(lo->lo_backing_file, &b, &pos);
386 		if (ret < 0)
387 			break;
388 	}
389 
390 	__free_page(page);
391 	return ret;
392 }
393 
394 static int lo_read_simple(struct loop_device *lo, struct request *rq,
395 		loff_t pos)
396 {
397 	struct bio_vec bvec;
398 	struct req_iterator iter;
399 	struct iov_iter i;
400 	ssize_t len;
401 
402 	rq_for_each_segment(bvec, rq, iter) {
403 		iov_iter_bvec(&i, READ, &bvec, 1, bvec.bv_len);
404 		len = vfs_iter_read(lo->lo_backing_file, &i, &pos, 0);
405 		if (len < 0)
406 			return len;
407 
408 		flush_dcache_page(bvec.bv_page);
409 
410 		if (len != bvec.bv_len) {
411 			struct bio *bio;
412 
413 			__rq_for_each_bio(bio, rq)
414 				zero_fill_bio(bio);
415 			break;
416 		}
417 		cond_resched();
418 	}
419 
420 	return 0;
421 }
422 
423 static int lo_read_transfer(struct loop_device *lo, struct request *rq,
424 		loff_t pos)
425 {
426 	struct bio_vec bvec, b;
427 	struct req_iterator iter;
428 	struct iov_iter i;
429 	struct page *page;
430 	ssize_t len;
431 	int ret = 0;
432 
433 	page = alloc_page(GFP_NOIO);
434 	if (unlikely(!page))
435 		return -ENOMEM;
436 
437 	rq_for_each_segment(bvec, rq, iter) {
438 		loff_t offset = pos;
439 
440 		b.bv_page = page;
441 		b.bv_offset = 0;
442 		b.bv_len = bvec.bv_len;
443 
444 		iov_iter_bvec(&i, READ, &b, 1, b.bv_len);
445 		len = vfs_iter_read(lo->lo_backing_file, &i, &pos, 0);
446 		if (len < 0) {
447 			ret = len;
448 			goto out_free_page;
449 		}
450 
451 		ret = lo_do_transfer(lo, READ, page, 0, bvec.bv_page,
452 			bvec.bv_offset, len, offset >> 9);
453 		if (ret)
454 			goto out_free_page;
455 
456 		flush_dcache_page(bvec.bv_page);
457 
458 		if (len != bvec.bv_len) {
459 			struct bio *bio;
460 
461 			__rq_for_each_bio(bio, rq)
462 				zero_fill_bio(bio);
463 			break;
464 		}
465 	}
466 
467 	ret = 0;
468 out_free_page:
469 	__free_page(page);
470 	return ret;
471 }
472 
473 static int lo_fallocate(struct loop_device *lo, struct request *rq, loff_t pos,
474 			int mode)
475 {
476 	/*
477 	 * We use fallocate to manipulate the space mappings used by the image
478 	 * a.k.a. discard/zerorange. However we do not support this if
479 	 * encryption is enabled, because it may give an attacker useful
480 	 * information.
481 	 */
482 	struct file *file = lo->lo_backing_file;
483 	struct request_queue *q = lo->lo_queue;
484 	int ret;
485 
486 	mode |= FALLOC_FL_KEEP_SIZE;
487 
488 	if (!blk_queue_discard(q)) {
489 		ret = -EOPNOTSUPP;
490 		goto out;
491 	}
492 
493 	ret = file->f_op->fallocate(file, mode, pos, blk_rq_bytes(rq));
494 	if (unlikely(ret && ret != -EINVAL && ret != -EOPNOTSUPP))
495 		ret = -EIO;
496  out:
497 	return ret;
498 }
499 
500 static int lo_req_flush(struct loop_device *lo, struct request *rq)
501 {
502 	struct file *file = lo->lo_backing_file;
503 	int ret = vfs_fsync(file, 0);
504 	if (unlikely(ret && ret != -EINVAL))
505 		ret = -EIO;
506 
507 	return ret;
508 }
509 
510 static void lo_complete_rq(struct request *rq)
511 {
512 	struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
513 	blk_status_t ret = BLK_STS_OK;
514 
515 	if (!cmd->use_aio || cmd->ret < 0 || cmd->ret == blk_rq_bytes(rq) ||
516 	    req_op(rq) != REQ_OP_READ) {
517 		if (cmd->ret < 0)
518 			ret = errno_to_blk_status(cmd->ret);
519 		goto end_io;
520 	}
521 
522 	/*
523 	 * Short READ - if we got some data, advance our request and
524 	 * retry it. If we got no data, end the rest with EIO.
525 	 */
526 	if (cmd->ret) {
527 		blk_update_request(rq, BLK_STS_OK, cmd->ret);
528 		cmd->ret = 0;
529 		blk_mq_requeue_request(rq, true);
530 	} else {
531 		if (cmd->use_aio) {
532 			struct bio *bio = rq->bio;
533 
534 			while (bio) {
535 				zero_fill_bio(bio);
536 				bio = bio->bi_next;
537 			}
538 		}
539 		ret = BLK_STS_IOERR;
540 end_io:
541 		blk_mq_end_request(rq, ret);
542 	}
543 }
544 
545 static void lo_rw_aio_do_completion(struct loop_cmd *cmd)
546 {
547 	struct request *rq = blk_mq_rq_from_pdu(cmd);
548 
549 	if (!atomic_dec_and_test(&cmd->ref))
550 		return;
551 	kfree(cmd->bvec);
552 	cmd->bvec = NULL;
553 	if (likely(!blk_should_fake_timeout(rq->q)))
554 		blk_mq_complete_request(rq);
555 }
556 
557 static void lo_rw_aio_complete(struct kiocb *iocb, long ret, long ret2)
558 {
559 	struct loop_cmd *cmd = container_of(iocb, struct loop_cmd, iocb);
560 
561 	cmd->ret = ret;
562 	lo_rw_aio_do_completion(cmd);
563 }
564 
565 static int lo_rw_aio(struct loop_device *lo, struct loop_cmd *cmd,
566 		     loff_t pos, bool rw)
567 {
568 	struct iov_iter iter;
569 	struct req_iterator rq_iter;
570 	struct bio_vec *bvec;
571 	struct request *rq = blk_mq_rq_from_pdu(cmd);
572 	struct bio *bio = rq->bio;
573 	struct file *file = lo->lo_backing_file;
574 	struct bio_vec tmp;
575 	unsigned int offset;
576 	int nr_bvec = 0;
577 	int ret;
578 
579 	rq_for_each_bvec(tmp, rq, rq_iter)
580 		nr_bvec++;
581 
582 	if (rq->bio != rq->biotail) {
583 
584 		bvec = kmalloc_array(nr_bvec, sizeof(struct bio_vec),
585 				     GFP_NOIO);
586 		if (!bvec)
587 			return -EIO;
588 		cmd->bvec = bvec;
589 
590 		/*
591 		 * The bios of the request may be started from the middle of
592 		 * the 'bvec' because of bio splitting, so we can't directly
593 		 * copy bio->bi_iov_vec to new bvec. The rq_for_each_bvec
594 		 * API will take care of all details for us.
595 		 */
596 		rq_for_each_bvec(tmp, rq, rq_iter) {
597 			*bvec = tmp;
598 			bvec++;
599 		}
600 		bvec = cmd->bvec;
601 		offset = 0;
602 	} else {
603 		/*
604 		 * Same here, this bio may be started from the middle of the
605 		 * 'bvec' because of bio splitting, so offset from the bvec
606 		 * must be passed to iov iterator
607 		 */
608 		offset = bio->bi_iter.bi_bvec_done;
609 		bvec = __bvec_iter_bvec(bio->bi_io_vec, bio->bi_iter);
610 	}
611 	atomic_set(&cmd->ref, 2);
612 
613 	iov_iter_bvec(&iter, rw, bvec, nr_bvec, blk_rq_bytes(rq));
614 	iter.iov_offset = offset;
615 
616 	cmd->iocb.ki_pos = pos;
617 	cmd->iocb.ki_filp = file;
618 	cmd->iocb.ki_complete = lo_rw_aio_complete;
619 	cmd->iocb.ki_flags = IOCB_DIRECT;
620 	cmd->iocb.ki_ioprio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_NONE, 0);
621 
622 	if (rw == WRITE)
623 		ret = call_write_iter(file, &cmd->iocb, &iter);
624 	else
625 		ret = call_read_iter(file, &cmd->iocb, &iter);
626 
627 	lo_rw_aio_do_completion(cmd);
628 
629 	if (ret != -EIOCBQUEUED)
630 		cmd->iocb.ki_complete(&cmd->iocb, ret, 0);
631 	return 0;
632 }
633 
634 static int do_req_filebacked(struct loop_device *lo, struct request *rq)
635 {
636 	struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
637 	loff_t pos = ((loff_t) blk_rq_pos(rq) << 9) + lo->lo_offset;
638 
639 	/*
640 	 * lo_write_simple and lo_read_simple should have been covered
641 	 * by io submit style function like lo_rw_aio(), one blocker
642 	 * is that lo_read_simple() need to call flush_dcache_page after
643 	 * the page is written from kernel, and it isn't easy to handle
644 	 * this in io submit style function which submits all segments
645 	 * of the req at one time. And direct read IO doesn't need to
646 	 * run flush_dcache_page().
647 	 */
648 	switch (req_op(rq)) {
649 	case REQ_OP_FLUSH:
650 		return lo_req_flush(lo, rq);
651 	case REQ_OP_WRITE_ZEROES:
652 		/*
653 		 * If the caller doesn't want deallocation, call zeroout to
654 		 * write zeroes the range.  Otherwise, punch them out.
655 		 */
656 		return lo_fallocate(lo, rq, pos,
657 			(rq->cmd_flags & REQ_NOUNMAP) ?
658 				FALLOC_FL_ZERO_RANGE :
659 				FALLOC_FL_PUNCH_HOLE);
660 	case REQ_OP_DISCARD:
661 		return lo_fallocate(lo, rq, pos, FALLOC_FL_PUNCH_HOLE);
662 	case REQ_OP_WRITE:
663 		if (lo->transfer)
664 			return lo_write_transfer(lo, rq, pos);
665 		else if (cmd->use_aio)
666 			return lo_rw_aio(lo, cmd, pos, WRITE);
667 		else
668 			return lo_write_simple(lo, rq, pos);
669 	case REQ_OP_READ:
670 		if (lo->transfer)
671 			return lo_read_transfer(lo, rq, pos);
672 		else if (cmd->use_aio)
673 			return lo_rw_aio(lo, cmd, pos, READ);
674 		else
675 			return lo_read_simple(lo, rq, pos);
676 	default:
677 		WARN_ON_ONCE(1);
678 		return -EIO;
679 	}
680 }
681 
682 static inline void loop_update_dio(struct loop_device *lo)
683 {
684 	__loop_update_dio(lo, (lo->lo_backing_file->f_flags & O_DIRECT) |
685 				lo->use_dio);
686 }
687 
688 static void loop_reread_partitions(struct loop_device *lo)
689 {
690 	int rc;
691 
692 	mutex_lock(&lo->lo_disk->open_mutex);
693 	rc = bdev_disk_changed(lo->lo_disk, false);
694 	mutex_unlock(&lo->lo_disk->open_mutex);
695 	if (rc)
696 		pr_warn("%s: partition scan of loop%d (%s) failed (rc=%d)\n",
697 			__func__, lo->lo_number, lo->lo_file_name, rc);
698 }
699 
700 static inline int is_loop_device(struct file *file)
701 {
702 	struct inode *i = file->f_mapping->host;
703 
704 	return i && S_ISBLK(i->i_mode) && imajor(i) == LOOP_MAJOR;
705 }
706 
707 static int loop_validate_file(struct file *file, struct block_device *bdev)
708 {
709 	struct inode	*inode = file->f_mapping->host;
710 	struct file	*f = file;
711 
712 	/* Avoid recursion */
713 	while (is_loop_device(f)) {
714 		struct loop_device *l;
715 
716 		lockdep_assert_held(&loop_validate_mutex);
717 		if (f->f_mapping->host->i_rdev == bdev->bd_dev)
718 			return -EBADF;
719 
720 		l = I_BDEV(f->f_mapping->host)->bd_disk->private_data;
721 		if (l->lo_state != Lo_bound)
722 			return -EINVAL;
723 		/* Order wrt setting lo->lo_backing_file in loop_configure(). */
724 		rmb();
725 		f = l->lo_backing_file;
726 	}
727 	if (!S_ISREG(inode->i_mode) && !S_ISBLK(inode->i_mode))
728 		return -EINVAL;
729 	return 0;
730 }
731 
732 /*
733  * loop_change_fd switched the backing store of a loopback device to
734  * a new file. This is useful for operating system installers to free up
735  * the original file and in High Availability environments to switch to
736  * an alternative location for the content in case of server meltdown.
737  * This can only work if the loop device is used read-only, and if the
738  * new backing store is the same size and type as the old backing store.
739  */
740 static int loop_change_fd(struct loop_device *lo, struct block_device *bdev,
741 			  unsigned int arg)
742 {
743 	struct file *file = fget(arg);
744 	struct file *old_file;
745 	int error;
746 	bool partscan;
747 	bool is_loop;
748 
749 	if (!file)
750 		return -EBADF;
751 	is_loop = is_loop_device(file);
752 	error = loop_global_lock_killable(lo, is_loop);
753 	if (error)
754 		goto out_putf;
755 	error = -ENXIO;
756 	if (lo->lo_state != Lo_bound)
757 		goto out_err;
758 
759 	/* the loop device has to be read-only */
760 	error = -EINVAL;
761 	if (!(lo->lo_flags & LO_FLAGS_READ_ONLY))
762 		goto out_err;
763 
764 	error = loop_validate_file(file, bdev);
765 	if (error)
766 		goto out_err;
767 
768 	old_file = lo->lo_backing_file;
769 
770 	error = -EINVAL;
771 
772 	/* size of the new backing store needs to be the same */
773 	if (get_loop_size(lo, file) != get_loop_size(lo, old_file))
774 		goto out_err;
775 
776 	/* and ... switch */
777 	disk_force_media_change(lo->lo_disk, DISK_EVENT_MEDIA_CHANGE);
778 	blk_mq_freeze_queue(lo->lo_queue);
779 	mapping_set_gfp_mask(old_file->f_mapping, lo->old_gfp_mask);
780 	lo->lo_backing_file = file;
781 	lo->old_gfp_mask = mapping_gfp_mask(file->f_mapping);
782 	mapping_set_gfp_mask(file->f_mapping,
783 			     lo->old_gfp_mask & ~(__GFP_IO|__GFP_FS));
784 	loop_update_dio(lo);
785 	blk_mq_unfreeze_queue(lo->lo_queue);
786 	partscan = lo->lo_flags & LO_FLAGS_PARTSCAN;
787 	loop_global_unlock(lo, is_loop);
788 
789 	/*
790 	 * Flush loop_validate_file() before fput(), for l->lo_backing_file
791 	 * might be pointing at old_file which might be the last reference.
792 	 */
793 	if (!is_loop) {
794 		mutex_lock(&loop_validate_mutex);
795 		mutex_unlock(&loop_validate_mutex);
796 	}
797 	/*
798 	 * We must drop file reference outside of lo_mutex as dropping
799 	 * the file ref can take open_mutex which creates circular locking
800 	 * dependency.
801 	 */
802 	fput(old_file);
803 	if (partscan)
804 		loop_reread_partitions(lo);
805 	return 0;
806 
807 out_err:
808 	loop_global_unlock(lo, is_loop);
809 out_putf:
810 	fput(file);
811 	return error;
812 }
813 
814 /* loop sysfs attributes */
815 
816 static ssize_t loop_attr_show(struct device *dev, char *page,
817 			      ssize_t (*callback)(struct loop_device *, char *))
818 {
819 	struct gendisk *disk = dev_to_disk(dev);
820 	struct loop_device *lo = disk->private_data;
821 
822 	return callback(lo, page);
823 }
824 
825 #define LOOP_ATTR_RO(_name)						\
826 static ssize_t loop_attr_##_name##_show(struct loop_device *, char *);	\
827 static ssize_t loop_attr_do_show_##_name(struct device *d,		\
828 				struct device_attribute *attr, char *b)	\
829 {									\
830 	return loop_attr_show(d, b, loop_attr_##_name##_show);		\
831 }									\
832 static struct device_attribute loop_attr_##_name =			\
833 	__ATTR(_name, 0444, loop_attr_do_show_##_name, NULL);
834 
835 static ssize_t loop_attr_backing_file_show(struct loop_device *lo, char *buf)
836 {
837 	ssize_t ret;
838 	char *p = NULL;
839 
840 	spin_lock_irq(&lo->lo_lock);
841 	if (lo->lo_backing_file)
842 		p = file_path(lo->lo_backing_file, buf, PAGE_SIZE - 1);
843 	spin_unlock_irq(&lo->lo_lock);
844 
845 	if (IS_ERR_OR_NULL(p))
846 		ret = PTR_ERR(p);
847 	else {
848 		ret = strlen(p);
849 		memmove(buf, p, ret);
850 		buf[ret++] = '\n';
851 		buf[ret] = 0;
852 	}
853 
854 	return ret;
855 }
856 
857 static ssize_t loop_attr_offset_show(struct loop_device *lo, char *buf)
858 {
859 	return sprintf(buf, "%llu\n", (unsigned long long)lo->lo_offset);
860 }
861 
862 static ssize_t loop_attr_sizelimit_show(struct loop_device *lo, char *buf)
863 {
864 	return sprintf(buf, "%llu\n", (unsigned long long)lo->lo_sizelimit);
865 }
866 
867 static ssize_t loop_attr_autoclear_show(struct loop_device *lo, char *buf)
868 {
869 	int autoclear = (lo->lo_flags & LO_FLAGS_AUTOCLEAR);
870 
871 	return sprintf(buf, "%s\n", autoclear ? "1" : "0");
872 }
873 
874 static ssize_t loop_attr_partscan_show(struct loop_device *lo, char *buf)
875 {
876 	int partscan = (lo->lo_flags & LO_FLAGS_PARTSCAN);
877 
878 	return sprintf(buf, "%s\n", partscan ? "1" : "0");
879 }
880 
881 static ssize_t loop_attr_dio_show(struct loop_device *lo, char *buf)
882 {
883 	int dio = (lo->lo_flags & LO_FLAGS_DIRECT_IO);
884 
885 	return sprintf(buf, "%s\n", dio ? "1" : "0");
886 }
887 
888 LOOP_ATTR_RO(backing_file);
889 LOOP_ATTR_RO(offset);
890 LOOP_ATTR_RO(sizelimit);
891 LOOP_ATTR_RO(autoclear);
892 LOOP_ATTR_RO(partscan);
893 LOOP_ATTR_RO(dio);
894 
895 static struct attribute *loop_attrs[] = {
896 	&loop_attr_backing_file.attr,
897 	&loop_attr_offset.attr,
898 	&loop_attr_sizelimit.attr,
899 	&loop_attr_autoclear.attr,
900 	&loop_attr_partscan.attr,
901 	&loop_attr_dio.attr,
902 	NULL,
903 };
904 
905 static struct attribute_group loop_attribute_group = {
906 	.name = "loop",
907 	.attrs= loop_attrs,
908 };
909 
910 static void loop_sysfs_init(struct loop_device *lo)
911 {
912 	lo->sysfs_inited = !sysfs_create_group(&disk_to_dev(lo->lo_disk)->kobj,
913 						&loop_attribute_group);
914 }
915 
916 static void loop_sysfs_exit(struct loop_device *lo)
917 {
918 	if (lo->sysfs_inited)
919 		sysfs_remove_group(&disk_to_dev(lo->lo_disk)->kobj,
920 				   &loop_attribute_group);
921 }
922 
923 static void loop_config_discard(struct loop_device *lo)
924 {
925 	struct file *file = lo->lo_backing_file;
926 	struct inode *inode = file->f_mapping->host;
927 	struct request_queue *q = lo->lo_queue;
928 	u32 granularity, max_discard_sectors;
929 
930 	/*
931 	 * If the backing device is a block device, mirror its zeroing
932 	 * capability. Set the discard sectors to the block device's zeroing
933 	 * capabilities because loop discards result in blkdev_issue_zeroout(),
934 	 * not blkdev_issue_discard(). This maintains consistent behavior with
935 	 * file-backed loop devices: discarded regions read back as zero.
936 	 */
937 	if (S_ISBLK(inode->i_mode) && !lo->lo_encrypt_key_size) {
938 		struct request_queue *backingq = bdev_get_queue(I_BDEV(inode));
939 
940 		max_discard_sectors = backingq->limits.max_write_zeroes_sectors;
941 		granularity = backingq->limits.discard_granularity ?:
942 			queue_physical_block_size(backingq);
943 
944 	/*
945 	 * We use punch hole to reclaim the free space used by the
946 	 * image a.k.a. discard. However we do not support discard if
947 	 * encryption is enabled, because it may give an attacker
948 	 * useful information.
949 	 */
950 	} else if (!file->f_op->fallocate || lo->lo_encrypt_key_size) {
951 		max_discard_sectors = 0;
952 		granularity = 0;
953 
954 	} else {
955 		max_discard_sectors = UINT_MAX >> 9;
956 		granularity = inode->i_sb->s_blocksize;
957 	}
958 
959 	if (max_discard_sectors) {
960 		q->limits.discard_granularity = granularity;
961 		blk_queue_max_discard_sectors(q, max_discard_sectors);
962 		blk_queue_max_write_zeroes_sectors(q, max_discard_sectors);
963 		blk_queue_flag_set(QUEUE_FLAG_DISCARD, q);
964 	} else {
965 		q->limits.discard_granularity = 0;
966 		blk_queue_max_discard_sectors(q, 0);
967 		blk_queue_max_write_zeroes_sectors(q, 0);
968 		blk_queue_flag_clear(QUEUE_FLAG_DISCARD, q);
969 	}
970 	q->limits.discard_alignment = 0;
971 }
972 
973 struct loop_worker {
974 	struct rb_node rb_node;
975 	struct work_struct work;
976 	struct list_head cmd_list;
977 	struct list_head idle_list;
978 	struct loop_device *lo;
979 	struct cgroup_subsys_state *blkcg_css;
980 	unsigned long last_ran_at;
981 };
982 
983 static void loop_workfn(struct work_struct *work);
984 static void loop_rootcg_workfn(struct work_struct *work);
985 static void loop_free_idle_workers(struct timer_list *timer);
986 
987 #ifdef CONFIG_BLK_CGROUP
988 static inline int queue_on_root_worker(struct cgroup_subsys_state *css)
989 {
990 	return !css || css == blkcg_root_css;
991 }
992 #else
993 static inline int queue_on_root_worker(struct cgroup_subsys_state *css)
994 {
995 	return !css;
996 }
997 #endif
998 
999 static void loop_queue_work(struct loop_device *lo, struct loop_cmd *cmd)
1000 {
1001 	struct rb_node **node = &(lo->worker_tree.rb_node), *parent = NULL;
1002 	struct loop_worker *cur_worker, *worker = NULL;
1003 	struct work_struct *work;
1004 	struct list_head *cmd_list;
1005 
1006 	spin_lock_irq(&lo->lo_work_lock);
1007 
1008 	if (queue_on_root_worker(cmd->blkcg_css))
1009 		goto queue_work;
1010 
1011 	node = &lo->worker_tree.rb_node;
1012 
1013 	while (*node) {
1014 		parent = *node;
1015 		cur_worker = container_of(*node, struct loop_worker, rb_node);
1016 		if (cur_worker->blkcg_css == cmd->blkcg_css) {
1017 			worker = cur_worker;
1018 			break;
1019 		} else if ((long)cur_worker->blkcg_css < (long)cmd->blkcg_css) {
1020 			node = &(*node)->rb_left;
1021 		} else {
1022 			node = &(*node)->rb_right;
1023 		}
1024 	}
1025 	if (worker)
1026 		goto queue_work;
1027 
1028 	worker = kzalloc(sizeof(struct loop_worker), GFP_NOWAIT | __GFP_NOWARN);
1029 	/*
1030 	 * In the event we cannot allocate a worker, just queue on the
1031 	 * rootcg worker and issue the I/O as the rootcg
1032 	 */
1033 	if (!worker) {
1034 		cmd->blkcg_css = NULL;
1035 		if (cmd->memcg_css)
1036 			css_put(cmd->memcg_css);
1037 		cmd->memcg_css = NULL;
1038 		goto queue_work;
1039 	}
1040 
1041 	worker->blkcg_css = cmd->blkcg_css;
1042 	css_get(worker->blkcg_css);
1043 	INIT_WORK(&worker->work, loop_workfn);
1044 	INIT_LIST_HEAD(&worker->cmd_list);
1045 	INIT_LIST_HEAD(&worker->idle_list);
1046 	worker->lo = lo;
1047 	rb_link_node(&worker->rb_node, parent, node);
1048 	rb_insert_color(&worker->rb_node, &lo->worker_tree);
1049 queue_work:
1050 	if (worker) {
1051 		/*
1052 		 * We need to remove from the idle list here while
1053 		 * holding the lock so that the idle timer doesn't
1054 		 * free the worker
1055 		 */
1056 		if (!list_empty(&worker->idle_list))
1057 			list_del_init(&worker->idle_list);
1058 		work = &worker->work;
1059 		cmd_list = &worker->cmd_list;
1060 	} else {
1061 		work = &lo->rootcg_work;
1062 		cmd_list = &lo->rootcg_cmd_list;
1063 	}
1064 	list_add_tail(&cmd->list_entry, cmd_list);
1065 	queue_work(lo->workqueue, work);
1066 	spin_unlock_irq(&lo->lo_work_lock);
1067 }
1068 
1069 static void loop_update_rotational(struct loop_device *lo)
1070 {
1071 	struct file *file = lo->lo_backing_file;
1072 	struct inode *file_inode = file->f_mapping->host;
1073 	struct block_device *file_bdev = file_inode->i_sb->s_bdev;
1074 	struct request_queue *q = lo->lo_queue;
1075 	bool nonrot = true;
1076 
1077 	/* not all filesystems (e.g. tmpfs) have a sb->s_bdev */
1078 	if (file_bdev)
1079 		nonrot = blk_queue_nonrot(bdev_get_queue(file_bdev));
1080 
1081 	if (nonrot)
1082 		blk_queue_flag_set(QUEUE_FLAG_NONROT, q);
1083 	else
1084 		blk_queue_flag_clear(QUEUE_FLAG_NONROT, q);
1085 }
1086 
1087 static int
1088 loop_release_xfer(struct loop_device *lo)
1089 {
1090 	int err = 0;
1091 	struct loop_func_table *xfer = lo->lo_encryption;
1092 
1093 	if (xfer) {
1094 		if (xfer->release)
1095 			err = xfer->release(lo);
1096 		lo->transfer = NULL;
1097 		lo->lo_encryption = NULL;
1098 		module_put(xfer->owner);
1099 	}
1100 	return err;
1101 }
1102 
1103 static int
1104 loop_init_xfer(struct loop_device *lo, struct loop_func_table *xfer,
1105 	       const struct loop_info64 *i)
1106 {
1107 	int err = 0;
1108 
1109 	if (xfer) {
1110 		struct module *owner = xfer->owner;
1111 
1112 		if (!try_module_get(owner))
1113 			return -EINVAL;
1114 		if (xfer->init)
1115 			err = xfer->init(lo, i);
1116 		if (err)
1117 			module_put(owner);
1118 		else
1119 			lo->lo_encryption = xfer;
1120 	}
1121 	return err;
1122 }
1123 
1124 /**
1125  * loop_set_status_from_info - configure device from loop_info
1126  * @lo: struct loop_device to configure
1127  * @info: struct loop_info64 to configure the device with
1128  *
1129  * Configures the loop device parameters according to the passed
1130  * in loop_info64 configuration.
1131  */
1132 static int
1133 loop_set_status_from_info(struct loop_device *lo,
1134 			  const struct loop_info64 *info)
1135 {
1136 	int err;
1137 	struct loop_func_table *xfer;
1138 	kuid_t uid = current_uid();
1139 
1140 	if ((unsigned int) info->lo_encrypt_key_size > LO_KEY_SIZE)
1141 		return -EINVAL;
1142 
1143 	err = loop_release_xfer(lo);
1144 	if (err)
1145 		return err;
1146 
1147 	if (info->lo_encrypt_type) {
1148 		unsigned int type = info->lo_encrypt_type;
1149 
1150 		if (type >= MAX_LO_CRYPT)
1151 			return -EINVAL;
1152 		xfer = xfer_funcs[type];
1153 		if (xfer == NULL)
1154 			return -EINVAL;
1155 	} else
1156 		xfer = NULL;
1157 
1158 	err = loop_init_xfer(lo, xfer, info);
1159 	if (err)
1160 		return err;
1161 
1162 	lo->lo_offset = info->lo_offset;
1163 	lo->lo_sizelimit = info->lo_sizelimit;
1164 	memcpy(lo->lo_file_name, info->lo_file_name, LO_NAME_SIZE);
1165 	memcpy(lo->lo_crypt_name, info->lo_crypt_name, LO_NAME_SIZE);
1166 	lo->lo_file_name[LO_NAME_SIZE-1] = 0;
1167 	lo->lo_crypt_name[LO_NAME_SIZE-1] = 0;
1168 
1169 	if (!xfer)
1170 		xfer = &none_funcs;
1171 	lo->transfer = xfer->transfer;
1172 	lo->ioctl = xfer->ioctl;
1173 
1174 	lo->lo_flags = info->lo_flags;
1175 
1176 	lo->lo_encrypt_key_size = info->lo_encrypt_key_size;
1177 	lo->lo_init[0] = info->lo_init[0];
1178 	lo->lo_init[1] = info->lo_init[1];
1179 	if (info->lo_encrypt_key_size) {
1180 		memcpy(lo->lo_encrypt_key, info->lo_encrypt_key,
1181 		       info->lo_encrypt_key_size);
1182 		lo->lo_key_owner = uid;
1183 	}
1184 
1185 	return 0;
1186 }
1187 
1188 static int loop_configure(struct loop_device *lo, fmode_t mode,
1189 			  struct block_device *bdev,
1190 			  const struct loop_config *config)
1191 {
1192 	struct file *file = fget(config->fd);
1193 	struct inode *inode;
1194 	struct address_space *mapping;
1195 	int error;
1196 	loff_t size;
1197 	bool partscan;
1198 	unsigned short bsize;
1199 	bool is_loop;
1200 
1201 	if (!file)
1202 		return -EBADF;
1203 	is_loop = is_loop_device(file);
1204 
1205 	/* This is safe, since we have a reference from open(). */
1206 	__module_get(THIS_MODULE);
1207 
1208 	/*
1209 	 * If we don't hold exclusive handle for the device, upgrade to it
1210 	 * here to avoid changing device under exclusive owner.
1211 	 */
1212 	if (!(mode & FMODE_EXCL)) {
1213 		error = bd_prepare_to_claim(bdev, loop_configure);
1214 		if (error)
1215 			goto out_putf;
1216 	}
1217 
1218 	error = loop_global_lock_killable(lo, is_loop);
1219 	if (error)
1220 		goto out_bdev;
1221 
1222 	error = -EBUSY;
1223 	if (lo->lo_state != Lo_unbound)
1224 		goto out_unlock;
1225 
1226 	error = loop_validate_file(file, bdev);
1227 	if (error)
1228 		goto out_unlock;
1229 
1230 	mapping = file->f_mapping;
1231 	inode = mapping->host;
1232 
1233 	if ((config->info.lo_flags & ~LOOP_CONFIGURE_SETTABLE_FLAGS) != 0) {
1234 		error = -EINVAL;
1235 		goto out_unlock;
1236 	}
1237 
1238 	if (config->block_size) {
1239 		error = loop_validate_block_size(config->block_size);
1240 		if (error)
1241 			goto out_unlock;
1242 	}
1243 
1244 	error = loop_set_status_from_info(lo, &config->info);
1245 	if (error)
1246 		goto out_unlock;
1247 
1248 	if (!(file->f_mode & FMODE_WRITE) || !(mode & FMODE_WRITE) ||
1249 	    !file->f_op->write_iter)
1250 		lo->lo_flags |= LO_FLAGS_READ_ONLY;
1251 
1252 	lo->workqueue = alloc_workqueue("loop%d",
1253 					WQ_UNBOUND | WQ_FREEZABLE,
1254 					0,
1255 					lo->lo_number);
1256 	if (!lo->workqueue) {
1257 		error = -ENOMEM;
1258 		goto out_unlock;
1259 	}
1260 
1261 	disk_force_media_change(lo->lo_disk, DISK_EVENT_MEDIA_CHANGE);
1262 	set_disk_ro(lo->lo_disk, (lo->lo_flags & LO_FLAGS_READ_ONLY) != 0);
1263 
1264 	INIT_WORK(&lo->rootcg_work, loop_rootcg_workfn);
1265 	INIT_LIST_HEAD(&lo->rootcg_cmd_list);
1266 	INIT_LIST_HEAD(&lo->idle_worker_list);
1267 	lo->worker_tree = RB_ROOT;
1268 	timer_setup(&lo->timer, loop_free_idle_workers,
1269 		TIMER_DEFERRABLE);
1270 	lo->use_dio = lo->lo_flags & LO_FLAGS_DIRECT_IO;
1271 	lo->lo_device = bdev;
1272 	lo->lo_backing_file = file;
1273 	lo->old_gfp_mask = mapping_gfp_mask(mapping);
1274 	mapping_set_gfp_mask(mapping, lo->old_gfp_mask & ~(__GFP_IO|__GFP_FS));
1275 
1276 	if (!(lo->lo_flags & LO_FLAGS_READ_ONLY) && file->f_op->fsync)
1277 		blk_queue_write_cache(lo->lo_queue, true, false);
1278 
1279 	if (config->block_size)
1280 		bsize = config->block_size;
1281 	else if ((lo->lo_backing_file->f_flags & O_DIRECT) && inode->i_sb->s_bdev)
1282 		/* In case of direct I/O, match underlying block size */
1283 		bsize = bdev_logical_block_size(inode->i_sb->s_bdev);
1284 	else
1285 		bsize = 512;
1286 
1287 	blk_queue_logical_block_size(lo->lo_queue, bsize);
1288 	blk_queue_physical_block_size(lo->lo_queue, bsize);
1289 	blk_queue_io_min(lo->lo_queue, bsize);
1290 
1291 	loop_config_discard(lo);
1292 	loop_update_rotational(lo);
1293 	loop_update_dio(lo);
1294 	loop_sysfs_init(lo);
1295 
1296 	size = get_loop_size(lo, file);
1297 	loop_set_size(lo, size);
1298 
1299 	/* Order wrt reading lo_state in loop_validate_file(). */
1300 	wmb();
1301 
1302 	lo->lo_state = Lo_bound;
1303 	if (part_shift)
1304 		lo->lo_flags |= LO_FLAGS_PARTSCAN;
1305 	partscan = lo->lo_flags & LO_FLAGS_PARTSCAN;
1306 	if (partscan)
1307 		lo->lo_disk->flags &= ~GENHD_FL_NO_PART_SCAN;
1308 
1309 	loop_global_unlock(lo, is_loop);
1310 	if (partscan)
1311 		loop_reread_partitions(lo);
1312 	if (!(mode & FMODE_EXCL))
1313 		bd_abort_claiming(bdev, loop_configure);
1314 	return 0;
1315 
1316 out_unlock:
1317 	loop_global_unlock(lo, is_loop);
1318 out_bdev:
1319 	if (!(mode & FMODE_EXCL))
1320 		bd_abort_claiming(bdev, loop_configure);
1321 out_putf:
1322 	fput(file);
1323 	/* This is safe: open() is still holding a reference. */
1324 	module_put(THIS_MODULE);
1325 	return error;
1326 }
1327 
1328 static int __loop_clr_fd(struct loop_device *lo, bool release)
1329 {
1330 	struct file *filp = NULL;
1331 	gfp_t gfp = lo->old_gfp_mask;
1332 	struct block_device *bdev = lo->lo_device;
1333 	int err = 0;
1334 	bool partscan = false;
1335 	int lo_number;
1336 	struct loop_worker *pos, *worker;
1337 
1338 	/*
1339 	 * Flush loop_configure() and loop_change_fd(). It is acceptable for
1340 	 * loop_validate_file() to succeed, for actual clear operation has not
1341 	 * started yet.
1342 	 */
1343 	mutex_lock(&loop_validate_mutex);
1344 	mutex_unlock(&loop_validate_mutex);
1345 	/*
1346 	 * loop_validate_file() now fails because l->lo_state != Lo_bound
1347 	 * became visible.
1348 	 */
1349 
1350 	mutex_lock(&lo->lo_mutex);
1351 	if (WARN_ON_ONCE(lo->lo_state != Lo_rundown)) {
1352 		err = -ENXIO;
1353 		goto out_unlock;
1354 	}
1355 
1356 	filp = lo->lo_backing_file;
1357 	if (filp == NULL) {
1358 		err = -EINVAL;
1359 		goto out_unlock;
1360 	}
1361 
1362 	if (test_bit(QUEUE_FLAG_WC, &lo->lo_queue->queue_flags))
1363 		blk_queue_write_cache(lo->lo_queue, false, false);
1364 
1365 	/* freeze request queue during the transition */
1366 	blk_mq_freeze_queue(lo->lo_queue);
1367 
1368 	destroy_workqueue(lo->workqueue);
1369 	spin_lock_irq(&lo->lo_work_lock);
1370 	list_for_each_entry_safe(worker, pos, &lo->idle_worker_list,
1371 				idle_list) {
1372 		list_del(&worker->idle_list);
1373 		rb_erase(&worker->rb_node, &lo->worker_tree);
1374 		css_put(worker->blkcg_css);
1375 		kfree(worker);
1376 	}
1377 	spin_unlock_irq(&lo->lo_work_lock);
1378 	del_timer_sync(&lo->timer);
1379 
1380 	spin_lock_irq(&lo->lo_lock);
1381 	lo->lo_backing_file = NULL;
1382 	spin_unlock_irq(&lo->lo_lock);
1383 
1384 	loop_release_xfer(lo);
1385 	lo->transfer = NULL;
1386 	lo->ioctl = NULL;
1387 	lo->lo_device = NULL;
1388 	lo->lo_encryption = NULL;
1389 	lo->lo_offset = 0;
1390 	lo->lo_sizelimit = 0;
1391 	lo->lo_encrypt_key_size = 0;
1392 	memset(lo->lo_encrypt_key, 0, LO_KEY_SIZE);
1393 	memset(lo->lo_crypt_name, 0, LO_NAME_SIZE);
1394 	memset(lo->lo_file_name, 0, LO_NAME_SIZE);
1395 	blk_queue_logical_block_size(lo->lo_queue, 512);
1396 	blk_queue_physical_block_size(lo->lo_queue, 512);
1397 	blk_queue_io_min(lo->lo_queue, 512);
1398 	invalidate_disk(lo->lo_disk);
1399 	loop_sysfs_exit(lo);
1400 	if (bdev) {
1401 		/* let user-space know about this change */
1402 		kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, KOBJ_CHANGE);
1403 	}
1404 	mapping_set_gfp_mask(filp->f_mapping, gfp);
1405 	/* This is safe: open() is still holding a reference. */
1406 	module_put(THIS_MODULE);
1407 	blk_mq_unfreeze_queue(lo->lo_queue);
1408 
1409 	partscan = lo->lo_flags & LO_FLAGS_PARTSCAN && bdev;
1410 	lo_number = lo->lo_number;
1411 	disk_force_media_change(lo->lo_disk, DISK_EVENT_MEDIA_CHANGE);
1412 out_unlock:
1413 	mutex_unlock(&lo->lo_mutex);
1414 	if (partscan) {
1415 		/*
1416 		 * open_mutex has been held already in release path, so don't
1417 		 * acquire it if this function is called in such case.
1418 		 *
1419 		 * If the reread partition isn't from release path, lo_refcnt
1420 		 * must be at least one and it can only become zero when the
1421 		 * current holder is released.
1422 		 */
1423 		if (!release)
1424 			mutex_lock(&lo->lo_disk->open_mutex);
1425 		err = bdev_disk_changed(lo->lo_disk, false);
1426 		if (!release)
1427 			mutex_unlock(&lo->lo_disk->open_mutex);
1428 		if (err)
1429 			pr_warn("%s: partition scan of loop%d failed (rc=%d)\n",
1430 				__func__, lo_number, err);
1431 		/* Device is gone, no point in returning error */
1432 		err = 0;
1433 	}
1434 
1435 	/*
1436 	 * lo->lo_state is set to Lo_unbound here after above partscan has
1437 	 * finished.
1438 	 *
1439 	 * There cannot be anybody else entering __loop_clr_fd() as
1440 	 * lo->lo_backing_file is already cleared and Lo_rundown state
1441 	 * protects us from all the other places trying to change the 'lo'
1442 	 * device.
1443 	 */
1444 	mutex_lock(&lo->lo_mutex);
1445 	lo->lo_flags = 0;
1446 	if (!part_shift)
1447 		lo->lo_disk->flags |= GENHD_FL_NO_PART_SCAN;
1448 	lo->lo_state = Lo_unbound;
1449 	mutex_unlock(&lo->lo_mutex);
1450 
1451 	/*
1452 	 * Need not hold lo_mutex to fput backing file. Calling fput holding
1453 	 * lo_mutex triggers a circular lock dependency possibility warning as
1454 	 * fput can take open_mutex which is usually taken before lo_mutex.
1455 	 */
1456 	if (filp)
1457 		fput(filp);
1458 	return err;
1459 }
1460 
1461 static int loop_clr_fd(struct loop_device *lo)
1462 {
1463 	int err;
1464 
1465 	err = mutex_lock_killable(&lo->lo_mutex);
1466 	if (err)
1467 		return err;
1468 	if (lo->lo_state != Lo_bound) {
1469 		mutex_unlock(&lo->lo_mutex);
1470 		return -ENXIO;
1471 	}
1472 	/*
1473 	 * If we've explicitly asked to tear down the loop device,
1474 	 * and it has an elevated reference count, set it for auto-teardown when
1475 	 * the last reference goes away. This stops $!~#$@ udev from
1476 	 * preventing teardown because it decided that it needs to run blkid on
1477 	 * the loopback device whenever they appear. xfstests is notorious for
1478 	 * failing tests because blkid via udev races with a losetup
1479 	 * <dev>/do something like mkfs/losetup -d <dev> causing the losetup -d
1480 	 * command to fail with EBUSY.
1481 	 */
1482 	if (atomic_read(&lo->lo_refcnt) > 1) {
1483 		lo->lo_flags |= LO_FLAGS_AUTOCLEAR;
1484 		mutex_unlock(&lo->lo_mutex);
1485 		return 0;
1486 	}
1487 	lo->lo_state = Lo_rundown;
1488 	mutex_unlock(&lo->lo_mutex);
1489 
1490 	return __loop_clr_fd(lo, false);
1491 }
1492 
1493 static int
1494 loop_set_status(struct loop_device *lo, const struct loop_info64 *info)
1495 {
1496 	int err;
1497 	kuid_t uid = current_uid();
1498 	int prev_lo_flags;
1499 	bool partscan = false;
1500 	bool size_changed = false;
1501 
1502 	err = mutex_lock_killable(&lo->lo_mutex);
1503 	if (err)
1504 		return err;
1505 	if (lo->lo_encrypt_key_size &&
1506 	    !uid_eq(lo->lo_key_owner, uid) &&
1507 	    !capable(CAP_SYS_ADMIN)) {
1508 		err = -EPERM;
1509 		goto out_unlock;
1510 	}
1511 	if (lo->lo_state != Lo_bound) {
1512 		err = -ENXIO;
1513 		goto out_unlock;
1514 	}
1515 
1516 	if (lo->lo_offset != info->lo_offset ||
1517 	    lo->lo_sizelimit != info->lo_sizelimit) {
1518 		size_changed = true;
1519 		sync_blockdev(lo->lo_device);
1520 		invalidate_bdev(lo->lo_device);
1521 	}
1522 
1523 	/* I/O need to be drained during transfer transition */
1524 	blk_mq_freeze_queue(lo->lo_queue);
1525 
1526 	if (size_changed && lo->lo_device->bd_inode->i_mapping->nrpages) {
1527 		/* If any pages were dirtied after invalidate_bdev(), try again */
1528 		err = -EAGAIN;
1529 		pr_warn("%s: loop%d (%s) has still dirty pages (nrpages=%lu)\n",
1530 			__func__, lo->lo_number, lo->lo_file_name,
1531 			lo->lo_device->bd_inode->i_mapping->nrpages);
1532 		goto out_unfreeze;
1533 	}
1534 
1535 	prev_lo_flags = lo->lo_flags;
1536 
1537 	err = loop_set_status_from_info(lo, info);
1538 	if (err)
1539 		goto out_unfreeze;
1540 
1541 	/* Mask out flags that can't be set using LOOP_SET_STATUS. */
1542 	lo->lo_flags &= LOOP_SET_STATUS_SETTABLE_FLAGS;
1543 	/* For those flags, use the previous values instead */
1544 	lo->lo_flags |= prev_lo_flags & ~LOOP_SET_STATUS_SETTABLE_FLAGS;
1545 	/* For flags that can't be cleared, use previous values too */
1546 	lo->lo_flags |= prev_lo_flags & ~LOOP_SET_STATUS_CLEARABLE_FLAGS;
1547 
1548 	if (size_changed) {
1549 		loff_t new_size = get_size(lo->lo_offset, lo->lo_sizelimit,
1550 					   lo->lo_backing_file);
1551 		loop_set_size(lo, new_size);
1552 	}
1553 
1554 	loop_config_discard(lo);
1555 
1556 	/* update dio if lo_offset or transfer is changed */
1557 	__loop_update_dio(lo, lo->use_dio);
1558 
1559 out_unfreeze:
1560 	blk_mq_unfreeze_queue(lo->lo_queue);
1561 
1562 	if (!err && (lo->lo_flags & LO_FLAGS_PARTSCAN) &&
1563 	     !(prev_lo_flags & LO_FLAGS_PARTSCAN)) {
1564 		lo->lo_disk->flags &= ~GENHD_FL_NO_PART_SCAN;
1565 		partscan = true;
1566 	}
1567 out_unlock:
1568 	mutex_unlock(&lo->lo_mutex);
1569 	if (partscan)
1570 		loop_reread_partitions(lo);
1571 
1572 	return err;
1573 }
1574 
1575 static int
1576 loop_get_status(struct loop_device *lo, struct loop_info64 *info)
1577 {
1578 	struct path path;
1579 	struct kstat stat;
1580 	int ret;
1581 
1582 	ret = mutex_lock_killable(&lo->lo_mutex);
1583 	if (ret)
1584 		return ret;
1585 	if (lo->lo_state != Lo_bound) {
1586 		mutex_unlock(&lo->lo_mutex);
1587 		return -ENXIO;
1588 	}
1589 
1590 	memset(info, 0, sizeof(*info));
1591 	info->lo_number = lo->lo_number;
1592 	info->lo_offset = lo->lo_offset;
1593 	info->lo_sizelimit = lo->lo_sizelimit;
1594 	info->lo_flags = lo->lo_flags;
1595 	memcpy(info->lo_file_name, lo->lo_file_name, LO_NAME_SIZE);
1596 	memcpy(info->lo_crypt_name, lo->lo_crypt_name, LO_NAME_SIZE);
1597 	info->lo_encrypt_type =
1598 		lo->lo_encryption ? lo->lo_encryption->number : 0;
1599 	if (lo->lo_encrypt_key_size && capable(CAP_SYS_ADMIN)) {
1600 		info->lo_encrypt_key_size = lo->lo_encrypt_key_size;
1601 		memcpy(info->lo_encrypt_key, lo->lo_encrypt_key,
1602 		       lo->lo_encrypt_key_size);
1603 	}
1604 
1605 	/* Drop lo_mutex while we call into the filesystem. */
1606 	path = lo->lo_backing_file->f_path;
1607 	path_get(&path);
1608 	mutex_unlock(&lo->lo_mutex);
1609 	ret = vfs_getattr(&path, &stat, STATX_INO, AT_STATX_SYNC_AS_STAT);
1610 	if (!ret) {
1611 		info->lo_device = huge_encode_dev(stat.dev);
1612 		info->lo_inode = stat.ino;
1613 		info->lo_rdevice = huge_encode_dev(stat.rdev);
1614 	}
1615 	path_put(&path);
1616 	return ret;
1617 }
1618 
1619 static void
1620 loop_info64_from_old(const struct loop_info *info, struct loop_info64 *info64)
1621 {
1622 	memset(info64, 0, sizeof(*info64));
1623 	info64->lo_number = info->lo_number;
1624 	info64->lo_device = info->lo_device;
1625 	info64->lo_inode = info->lo_inode;
1626 	info64->lo_rdevice = info->lo_rdevice;
1627 	info64->lo_offset = info->lo_offset;
1628 	info64->lo_sizelimit = 0;
1629 	info64->lo_encrypt_type = info->lo_encrypt_type;
1630 	info64->lo_encrypt_key_size = info->lo_encrypt_key_size;
1631 	info64->lo_flags = info->lo_flags;
1632 	info64->lo_init[0] = info->lo_init[0];
1633 	info64->lo_init[1] = info->lo_init[1];
1634 	if (info->lo_encrypt_type == LO_CRYPT_CRYPTOAPI)
1635 		memcpy(info64->lo_crypt_name, info->lo_name, LO_NAME_SIZE);
1636 	else
1637 		memcpy(info64->lo_file_name, info->lo_name, LO_NAME_SIZE);
1638 	memcpy(info64->lo_encrypt_key, info->lo_encrypt_key, LO_KEY_SIZE);
1639 }
1640 
1641 static int
1642 loop_info64_to_old(const struct loop_info64 *info64, struct loop_info *info)
1643 {
1644 	memset(info, 0, sizeof(*info));
1645 	info->lo_number = info64->lo_number;
1646 	info->lo_device = info64->lo_device;
1647 	info->lo_inode = info64->lo_inode;
1648 	info->lo_rdevice = info64->lo_rdevice;
1649 	info->lo_offset = info64->lo_offset;
1650 	info->lo_encrypt_type = info64->lo_encrypt_type;
1651 	info->lo_encrypt_key_size = info64->lo_encrypt_key_size;
1652 	info->lo_flags = info64->lo_flags;
1653 	info->lo_init[0] = info64->lo_init[0];
1654 	info->lo_init[1] = info64->lo_init[1];
1655 	if (info->lo_encrypt_type == LO_CRYPT_CRYPTOAPI)
1656 		memcpy(info->lo_name, info64->lo_crypt_name, LO_NAME_SIZE);
1657 	else
1658 		memcpy(info->lo_name, info64->lo_file_name, LO_NAME_SIZE);
1659 	memcpy(info->lo_encrypt_key, info64->lo_encrypt_key, LO_KEY_SIZE);
1660 
1661 	/* error in case values were truncated */
1662 	if (info->lo_device != info64->lo_device ||
1663 	    info->lo_rdevice != info64->lo_rdevice ||
1664 	    info->lo_inode != info64->lo_inode ||
1665 	    info->lo_offset != info64->lo_offset)
1666 		return -EOVERFLOW;
1667 
1668 	return 0;
1669 }
1670 
1671 static int
1672 loop_set_status_old(struct loop_device *lo, const struct loop_info __user *arg)
1673 {
1674 	struct loop_info info;
1675 	struct loop_info64 info64;
1676 
1677 	if (copy_from_user(&info, arg, sizeof (struct loop_info)))
1678 		return -EFAULT;
1679 	loop_info64_from_old(&info, &info64);
1680 	return loop_set_status(lo, &info64);
1681 }
1682 
1683 static int
1684 loop_set_status64(struct loop_device *lo, const struct loop_info64 __user *arg)
1685 {
1686 	struct loop_info64 info64;
1687 
1688 	if (copy_from_user(&info64, arg, sizeof (struct loop_info64)))
1689 		return -EFAULT;
1690 	return loop_set_status(lo, &info64);
1691 }
1692 
1693 static int
1694 loop_get_status_old(struct loop_device *lo, struct loop_info __user *arg) {
1695 	struct loop_info info;
1696 	struct loop_info64 info64;
1697 	int err;
1698 
1699 	if (!arg)
1700 		return -EINVAL;
1701 	err = loop_get_status(lo, &info64);
1702 	if (!err)
1703 		err = loop_info64_to_old(&info64, &info);
1704 	if (!err && copy_to_user(arg, &info, sizeof(info)))
1705 		err = -EFAULT;
1706 
1707 	return err;
1708 }
1709 
1710 static int
1711 loop_get_status64(struct loop_device *lo, struct loop_info64 __user *arg) {
1712 	struct loop_info64 info64;
1713 	int err;
1714 
1715 	if (!arg)
1716 		return -EINVAL;
1717 	err = loop_get_status(lo, &info64);
1718 	if (!err && copy_to_user(arg, &info64, sizeof(info64)))
1719 		err = -EFAULT;
1720 
1721 	return err;
1722 }
1723 
1724 static int loop_set_capacity(struct loop_device *lo)
1725 {
1726 	loff_t size;
1727 
1728 	if (unlikely(lo->lo_state != Lo_bound))
1729 		return -ENXIO;
1730 
1731 	size = get_loop_size(lo, lo->lo_backing_file);
1732 	loop_set_size(lo, size);
1733 
1734 	return 0;
1735 }
1736 
1737 static int loop_set_dio(struct loop_device *lo, unsigned long arg)
1738 {
1739 	int error = -ENXIO;
1740 	if (lo->lo_state != Lo_bound)
1741 		goto out;
1742 
1743 	__loop_update_dio(lo, !!arg);
1744 	if (lo->use_dio == !!arg)
1745 		return 0;
1746 	error = -EINVAL;
1747  out:
1748 	return error;
1749 }
1750 
1751 static int loop_set_block_size(struct loop_device *lo, unsigned long arg)
1752 {
1753 	int err = 0;
1754 
1755 	if (lo->lo_state != Lo_bound)
1756 		return -ENXIO;
1757 
1758 	err = loop_validate_block_size(arg);
1759 	if (err)
1760 		return err;
1761 
1762 	if (lo->lo_queue->limits.logical_block_size == arg)
1763 		return 0;
1764 
1765 	sync_blockdev(lo->lo_device);
1766 	invalidate_bdev(lo->lo_device);
1767 
1768 	blk_mq_freeze_queue(lo->lo_queue);
1769 
1770 	/* invalidate_bdev should have truncated all the pages */
1771 	if (lo->lo_device->bd_inode->i_mapping->nrpages) {
1772 		err = -EAGAIN;
1773 		pr_warn("%s: loop%d (%s) has still dirty pages (nrpages=%lu)\n",
1774 			__func__, lo->lo_number, lo->lo_file_name,
1775 			lo->lo_device->bd_inode->i_mapping->nrpages);
1776 		goto out_unfreeze;
1777 	}
1778 
1779 	blk_queue_logical_block_size(lo->lo_queue, arg);
1780 	blk_queue_physical_block_size(lo->lo_queue, arg);
1781 	blk_queue_io_min(lo->lo_queue, arg);
1782 	loop_update_dio(lo);
1783 out_unfreeze:
1784 	blk_mq_unfreeze_queue(lo->lo_queue);
1785 
1786 	return err;
1787 }
1788 
1789 static int lo_simple_ioctl(struct loop_device *lo, unsigned int cmd,
1790 			   unsigned long arg)
1791 {
1792 	int err;
1793 
1794 	err = mutex_lock_killable(&lo->lo_mutex);
1795 	if (err)
1796 		return err;
1797 	switch (cmd) {
1798 	case LOOP_SET_CAPACITY:
1799 		err = loop_set_capacity(lo);
1800 		break;
1801 	case LOOP_SET_DIRECT_IO:
1802 		err = loop_set_dio(lo, arg);
1803 		break;
1804 	case LOOP_SET_BLOCK_SIZE:
1805 		err = loop_set_block_size(lo, arg);
1806 		break;
1807 	default:
1808 		err = lo->ioctl ? lo->ioctl(lo, cmd, arg) : -EINVAL;
1809 	}
1810 	mutex_unlock(&lo->lo_mutex);
1811 	return err;
1812 }
1813 
1814 static int lo_ioctl(struct block_device *bdev, fmode_t mode,
1815 	unsigned int cmd, unsigned long arg)
1816 {
1817 	struct loop_device *lo = bdev->bd_disk->private_data;
1818 	void __user *argp = (void __user *) arg;
1819 	int err;
1820 
1821 	switch (cmd) {
1822 	case LOOP_SET_FD: {
1823 		/*
1824 		 * Legacy case - pass in a zeroed out struct loop_config with
1825 		 * only the file descriptor set , which corresponds with the
1826 		 * default parameters we'd have used otherwise.
1827 		 */
1828 		struct loop_config config;
1829 
1830 		memset(&config, 0, sizeof(config));
1831 		config.fd = arg;
1832 
1833 		return loop_configure(lo, mode, bdev, &config);
1834 	}
1835 	case LOOP_CONFIGURE: {
1836 		struct loop_config config;
1837 
1838 		if (copy_from_user(&config, argp, sizeof(config)))
1839 			return -EFAULT;
1840 
1841 		return loop_configure(lo, mode, bdev, &config);
1842 	}
1843 	case LOOP_CHANGE_FD:
1844 		return loop_change_fd(lo, bdev, arg);
1845 	case LOOP_CLR_FD:
1846 		return loop_clr_fd(lo);
1847 	case LOOP_SET_STATUS:
1848 		err = -EPERM;
1849 		if ((mode & FMODE_WRITE) || capable(CAP_SYS_ADMIN)) {
1850 			err = loop_set_status_old(lo, argp);
1851 		}
1852 		break;
1853 	case LOOP_GET_STATUS:
1854 		return loop_get_status_old(lo, argp);
1855 	case LOOP_SET_STATUS64:
1856 		err = -EPERM;
1857 		if ((mode & FMODE_WRITE) || capable(CAP_SYS_ADMIN)) {
1858 			err = loop_set_status64(lo, argp);
1859 		}
1860 		break;
1861 	case LOOP_GET_STATUS64:
1862 		return loop_get_status64(lo, argp);
1863 	case LOOP_SET_CAPACITY:
1864 	case LOOP_SET_DIRECT_IO:
1865 	case LOOP_SET_BLOCK_SIZE:
1866 		if (!(mode & FMODE_WRITE) && !capable(CAP_SYS_ADMIN))
1867 			return -EPERM;
1868 		fallthrough;
1869 	default:
1870 		err = lo_simple_ioctl(lo, cmd, arg);
1871 		break;
1872 	}
1873 
1874 	return err;
1875 }
1876 
1877 #ifdef CONFIG_COMPAT
1878 struct compat_loop_info {
1879 	compat_int_t	lo_number;      /* ioctl r/o */
1880 	compat_dev_t	lo_device;      /* ioctl r/o */
1881 	compat_ulong_t	lo_inode;       /* ioctl r/o */
1882 	compat_dev_t	lo_rdevice;     /* ioctl r/o */
1883 	compat_int_t	lo_offset;
1884 	compat_int_t	lo_encrypt_type;
1885 	compat_int_t	lo_encrypt_key_size;    /* ioctl w/o */
1886 	compat_int_t	lo_flags;       /* ioctl r/o */
1887 	char		lo_name[LO_NAME_SIZE];
1888 	unsigned char	lo_encrypt_key[LO_KEY_SIZE]; /* ioctl w/o */
1889 	compat_ulong_t	lo_init[2];
1890 	char		reserved[4];
1891 };
1892 
1893 /*
1894  * Transfer 32-bit compatibility structure in userspace to 64-bit loop info
1895  * - noinlined to reduce stack space usage in main part of driver
1896  */
1897 static noinline int
1898 loop_info64_from_compat(const struct compat_loop_info __user *arg,
1899 			struct loop_info64 *info64)
1900 {
1901 	struct compat_loop_info info;
1902 
1903 	if (copy_from_user(&info, arg, sizeof(info)))
1904 		return -EFAULT;
1905 
1906 	memset(info64, 0, sizeof(*info64));
1907 	info64->lo_number = info.lo_number;
1908 	info64->lo_device = info.lo_device;
1909 	info64->lo_inode = info.lo_inode;
1910 	info64->lo_rdevice = info.lo_rdevice;
1911 	info64->lo_offset = info.lo_offset;
1912 	info64->lo_sizelimit = 0;
1913 	info64->lo_encrypt_type = info.lo_encrypt_type;
1914 	info64->lo_encrypt_key_size = info.lo_encrypt_key_size;
1915 	info64->lo_flags = info.lo_flags;
1916 	info64->lo_init[0] = info.lo_init[0];
1917 	info64->lo_init[1] = info.lo_init[1];
1918 	if (info.lo_encrypt_type == LO_CRYPT_CRYPTOAPI)
1919 		memcpy(info64->lo_crypt_name, info.lo_name, LO_NAME_SIZE);
1920 	else
1921 		memcpy(info64->lo_file_name, info.lo_name, LO_NAME_SIZE);
1922 	memcpy(info64->lo_encrypt_key, info.lo_encrypt_key, LO_KEY_SIZE);
1923 	return 0;
1924 }
1925 
1926 /*
1927  * Transfer 64-bit loop info to 32-bit compatibility structure in userspace
1928  * - noinlined to reduce stack space usage in main part of driver
1929  */
1930 static noinline int
1931 loop_info64_to_compat(const struct loop_info64 *info64,
1932 		      struct compat_loop_info __user *arg)
1933 {
1934 	struct compat_loop_info info;
1935 
1936 	memset(&info, 0, sizeof(info));
1937 	info.lo_number = info64->lo_number;
1938 	info.lo_device = info64->lo_device;
1939 	info.lo_inode = info64->lo_inode;
1940 	info.lo_rdevice = info64->lo_rdevice;
1941 	info.lo_offset = info64->lo_offset;
1942 	info.lo_encrypt_type = info64->lo_encrypt_type;
1943 	info.lo_encrypt_key_size = info64->lo_encrypt_key_size;
1944 	info.lo_flags = info64->lo_flags;
1945 	info.lo_init[0] = info64->lo_init[0];
1946 	info.lo_init[1] = info64->lo_init[1];
1947 	if (info.lo_encrypt_type == LO_CRYPT_CRYPTOAPI)
1948 		memcpy(info.lo_name, info64->lo_crypt_name, LO_NAME_SIZE);
1949 	else
1950 		memcpy(info.lo_name, info64->lo_file_name, LO_NAME_SIZE);
1951 	memcpy(info.lo_encrypt_key, info64->lo_encrypt_key, LO_KEY_SIZE);
1952 
1953 	/* error in case values were truncated */
1954 	if (info.lo_device != info64->lo_device ||
1955 	    info.lo_rdevice != info64->lo_rdevice ||
1956 	    info.lo_inode != info64->lo_inode ||
1957 	    info.lo_offset != info64->lo_offset ||
1958 	    info.lo_init[0] != info64->lo_init[0] ||
1959 	    info.lo_init[1] != info64->lo_init[1])
1960 		return -EOVERFLOW;
1961 
1962 	if (copy_to_user(arg, &info, sizeof(info)))
1963 		return -EFAULT;
1964 	return 0;
1965 }
1966 
1967 static int
1968 loop_set_status_compat(struct loop_device *lo,
1969 		       const struct compat_loop_info __user *arg)
1970 {
1971 	struct loop_info64 info64;
1972 	int ret;
1973 
1974 	ret = loop_info64_from_compat(arg, &info64);
1975 	if (ret < 0)
1976 		return ret;
1977 	return loop_set_status(lo, &info64);
1978 }
1979 
1980 static int
1981 loop_get_status_compat(struct loop_device *lo,
1982 		       struct compat_loop_info __user *arg)
1983 {
1984 	struct loop_info64 info64;
1985 	int err;
1986 
1987 	if (!arg)
1988 		return -EINVAL;
1989 	err = loop_get_status(lo, &info64);
1990 	if (!err)
1991 		err = loop_info64_to_compat(&info64, arg);
1992 	return err;
1993 }
1994 
1995 static int lo_compat_ioctl(struct block_device *bdev, fmode_t mode,
1996 			   unsigned int cmd, unsigned long arg)
1997 {
1998 	struct loop_device *lo = bdev->bd_disk->private_data;
1999 	int err;
2000 
2001 	switch(cmd) {
2002 	case LOOP_SET_STATUS:
2003 		err = loop_set_status_compat(lo,
2004 			     (const struct compat_loop_info __user *)arg);
2005 		break;
2006 	case LOOP_GET_STATUS:
2007 		err = loop_get_status_compat(lo,
2008 				     (struct compat_loop_info __user *)arg);
2009 		break;
2010 	case LOOP_SET_CAPACITY:
2011 	case LOOP_CLR_FD:
2012 	case LOOP_GET_STATUS64:
2013 	case LOOP_SET_STATUS64:
2014 	case LOOP_CONFIGURE:
2015 		arg = (unsigned long) compat_ptr(arg);
2016 		fallthrough;
2017 	case LOOP_SET_FD:
2018 	case LOOP_CHANGE_FD:
2019 	case LOOP_SET_BLOCK_SIZE:
2020 	case LOOP_SET_DIRECT_IO:
2021 		err = lo_ioctl(bdev, mode, cmd, arg);
2022 		break;
2023 	default:
2024 		err = -ENOIOCTLCMD;
2025 		break;
2026 	}
2027 	return err;
2028 }
2029 #endif
2030 
2031 static int lo_open(struct block_device *bdev, fmode_t mode)
2032 {
2033 	struct loop_device *lo = bdev->bd_disk->private_data;
2034 	int err;
2035 
2036 	err = mutex_lock_killable(&lo->lo_mutex);
2037 	if (err)
2038 		return err;
2039 	if (lo->lo_state == Lo_deleting)
2040 		err = -ENXIO;
2041 	else
2042 		atomic_inc(&lo->lo_refcnt);
2043 	mutex_unlock(&lo->lo_mutex);
2044 	return err;
2045 }
2046 
2047 static void lo_release(struct gendisk *disk, fmode_t mode)
2048 {
2049 	struct loop_device *lo = disk->private_data;
2050 
2051 	mutex_lock(&lo->lo_mutex);
2052 	if (atomic_dec_return(&lo->lo_refcnt))
2053 		goto out_unlock;
2054 
2055 	if (lo->lo_flags & LO_FLAGS_AUTOCLEAR) {
2056 		if (lo->lo_state != Lo_bound)
2057 			goto out_unlock;
2058 		lo->lo_state = Lo_rundown;
2059 		mutex_unlock(&lo->lo_mutex);
2060 		/*
2061 		 * In autoclear mode, stop the loop thread
2062 		 * and remove configuration after last close.
2063 		 */
2064 		__loop_clr_fd(lo, true);
2065 		return;
2066 	} else if (lo->lo_state == Lo_bound) {
2067 		/*
2068 		 * Otherwise keep thread (if running) and config,
2069 		 * but flush possible ongoing bios in thread.
2070 		 */
2071 		blk_mq_freeze_queue(lo->lo_queue);
2072 		blk_mq_unfreeze_queue(lo->lo_queue);
2073 	}
2074 
2075 out_unlock:
2076 	mutex_unlock(&lo->lo_mutex);
2077 }
2078 
2079 static const struct block_device_operations lo_fops = {
2080 	.owner =	THIS_MODULE,
2081 	.open =		lo_open,
2082 	.release =	lo_release,
2083 	.ioctl =	lo_ioctl,
2084 #ifdef CONFIG_COMPAT
2085 	.compat_ioctl =	lo_compat_ioctl,
2086 #endif
2087 };
2088 
2089 /*
2090  * And now the modules code and kernel interface.
2091  */
2092 static int max_loop;
2093 module_param(max_loop, int, 0444);
2094 MODULE_PARM_DESC(max_loop, "Maximum number of loop devices");
2095 module_param(max_part, int, 0444);
2096 MODULE_PARM_DESC(max_part, "Maximum number of partitions per loop device");
2097 MODULE_LICENSE("GPL");
2098 MODULE_ALIAS_BLOCKDEV_MAJOR(LOOP_MAJOR);
2099 
2100 int loop_register_transfer(struct loop_func_table *funcs)
2101 {
2102 	unsigned int n = funcs->number;
2103 
2104 	if (n >= MAX_LO_CRYPT || xfer_funcs[n])
2105 		return -EINVAL;
2106 	xfer_funcs[n] = funcs;
2107 	return 0;
2108 }
2109 
2110 int loop_unregister_transfer(int number)
2111 {
2112 	unsigned int n = number;
2113 	struct loop_func_table *xfer;
2114 
2115 	if (n == 0 || n >= MAX_LO_CRYPT || (xfer = xfer_funcs[n]) == NULL)
2116 		return -EINVAL;
2117 	/*
2118 	 * This function is called from only cleanup_cryptoloop().
2119 	 * Given that each loop device that has a transfer enabled holds a
2120 	 * reference to the module implementing it we should never get here
2121 	 * with a transfer that is set (unless forced module unloading is
2122 	 * requested). Thus, check module's refcount and warn if this is
2123 	 * not a clean unloading.
2124 	 */
2125 #ifdef CONFIG_MODULE_UNLOAD
2126 	if (xfer->owner && module_refcount(xfer->owner) != -1)
2127 		pr_err("Danger! Unregistering an in use transfer function.\n");
2128 #endif
2129 
2130 	xfer_funcs[n] = NULL;
2131 	return 0;
2132 }
2133 
2134 EXPORT_SYMBOL(loop_register_transfer);
2135 EXPORT_SYMBOL(loop_unregister_transfer);
2136 
2137 static blk_status_t loop_queue_rq(struct blk_mq_hw_ctx *hctx,
2138 		const struct blk_mq_queue_data *bd)
2139 {
2140 	struct request *rq = bd->rq;
2141 	struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
2142 	struct loop_device *lo = rq->q->queuedata;
2143 
2144 	blk_mq_start_request(rq);
2145 
2146 	if (lo->lo_state != Lo_bound)
2147 		return BLK_STS_IOERR;
2148 
2149 	switch (req_op(rq)) {
2150 	case REQ_OP_FLUSH:
2151 	case REQ_OP_DISCARD:
2152 	case REQ_OP_WRITE_ZEROES:
2153 		cmd->use_aio = false;
2154 		break;
2155 	default:
2156 		cmd->use_aio = lo->use_dio;
2157 		break;
2158 	}
2159 
2160 	/* always use the first bio's css */
2161 	cmd->blkcg_css = NULL;
2162 	cmd->memcg_css = NULL;
2163 #ifdef CONFIG_BLK_CGROUP
2164 	if (rq->bio && rq->bio->bi_blkg) {
2165 		cmd->blkcg_css = &bio_blkcg(rq->bio)->css;
2166 #ifdef CONFIG_MEMCG
2167 		cmd->memcg_css =
2168 			cgroup_get_e_css(cmd->blkcg_css->cgroup,
2169 					&memory_cgrp_subsys);
2170 #endif
2171 	}
2172 #endif
2173 	loop_queue_work(lo, cmd);
2174 
2175 	return BLK_STS_OK;
2176 }
2177 
2178 static void loop_handle_cmd(struct loop_cmd *cmd)
2179 {
2180 	struct request *rq = blk_mq_rq_from_pdu(cmd);
2181 	const bool write = op_is_write(req_op(rq));
2182 	struct loop_device *lo = rq->q->queuedata;
2183 	int ret = 0;
2184 	struct mem_cgroup *old_memcg = NULL;
2185 
2186 	if (write && (lo->lo_flags & LO_FLAGS_READ_ONLY)) {
2187 		ret = -EIO;
2188 		goto failed;
2189 	}
2190 
2191 	if (cmd->blkcg_css)
2192 		kthread_associate_blkcg(cmd->blkcg_css);
2193 	if (cmd->memcg_css)
2194 		old_memcg = set_active_memcg(
2195 			mem_cgroup_from_css(cmd->memcg_css));
2196 
2197 	ret = do_req_filebacked(lo, rq);
2198 
2199 	if (cmd->blkcg_css)
2200 		kthread_associate_blkcg(NULL);
2201 
2202 	if (cmd->memcg_css) {
2203 		set_active_memcg(old_memcg);
2204 		css_put(cmd->memcg_css);
2205 	}
2206  failed:
2207 	/* complete non-aio request */
2208 	if (!cmd->use_aio || ret) {
2209 		if (ret == -EOPNOTSUPP)
2210 			cmd->ret = ret;
2211 		else
2212 			cmd->ret = ret ? -EIO : 0;
2213 		if (likely(!blk_should_fake_timeout(rq->q)))
2214 			blk_mq_complete_request(rq);
2215 	}
2216 }
2217 
2218 static void loop_set_timer(struct loop_device *lo)
2219 {
2220 	timer_reduce(&lo->timer, jiffies + LOOP_IDLE_WORKER_TIMEOUT);
2221 }
2222 
2223 static void loop_process_work(struct loop_worker *worker,
2224 			struct list_head *cmd_list, struct loop_device *lo)
2225 {
2226 	int orig_flags = current->flags;
2227 	struct loop_cmd *cmd;
2228 
2229 	current->flags |= PF_LOCAL_THROTTLE | PF_MEMALLOC_NOIO;
2230 	spin_lock_irq(&lo->lo_work_lock);
2231 	while (!list_empty(cmd_list)) {
2232 		cmd = container_of(
2233 			cmd_list->next, struct loop_cmd, list_entry);
2234 		list_del(cmd_list->next);
2235 		spin_unlock_irq(&lo->lo_work_lock);
2236 
2237 		loop_handle_cmd(cmd);
2238 		cond_resched();
2239 
2240 		spin_lock_irq(&lo->lo_work_lock);
2241 	}
2242 
2243 	/*
2244 	 * We only add to the idle list if there are no pending cmds
2245 	 * *and* the worker will not run again which ensures that it
2246 	 * is safe to free any worker on the idle list
2247 	 */
2248 	if (worker && !work_pending(&worker->work)) {
2249 		worker->last_ran_at = jiffies;
2250 		list_add_tail(&worker->idle_list, &lo->idle_worker_list);
2251 		loop_set_timer(lo);
2252 	}
2253 	spin_unlock_irq(&lo->lo_work_lock);
2254 	current->flags = orig_flags;
2255 }
2256 
2257 static void loop_workfn(struct work_struct *work)
2258 {
2259 	struct loop_worker *worker =
2260 		container_of(work, struct loop_worker, work);
2261 	loop_process_work(worker, &worker->cmd_list, worker->lo);
2262 }
2263 
2264 static void loop_rootcg_workfn(struct work_struct *work)
2265 {
2266 	struct loop_device *lo =
2267 		container_of(work, struct loop_device, rootcg_work);
2268 	loop_process_work(NULL, &lo->rootcg_cmd_list, lo);
2269 }
2270 
2271 static void loop_free_idle_workers(struct timer_list *timer)
2272 {
2273 	struct loop_device *lo = container_of(timer, struct loop_device, timer);
2274 	struct loop_worker *pos, *worker;
2275 
2276 	spin_lock_irq(&lo->lo_work_lock);
2277 	list_for_each_entry_safe(worker, pos, &lo->idle_worker_list,
2278 				idle_list) {
2279 		if (time_is_after_jiffies(worker->last_ran_at +
2280 						LOOP_IDLE_WORKER_TIMEOUT))
2281 			break;
2282 		list_del(&worker->idle_list);
2283 		rb_erase(&worker->rb_node, &lo->worker_tree);
2284 		css_put(worker->blkcg_css);
2285 		kfree(worker);
2286 	}
2287 	if (!list_empty(&lo->idle_worker_list))
2288 		loop_set_timer(lo);
2289 	spin_unlock_irq(&lo->lo_work_lock);
2290 }
2291 
2292 static const struct blk_mq_ops loop_mq_ops = {
2293 	.queue_rq       = loop_queue_rq,
2294 	.complete	= lo_complete_rq,
2295 };
2296 
2297 static int loop_add(int i)
2298 {
2299 	struct loop_device *lo;
2300 	struct gendisk *disk;
2301 	int err;
2302 
2303 	err = -ENOMEM;
2304 	lo = kzalloc(sizeof(*lo), GFP_KERNEL);
2305 	if (!lo)
2306 		goto out;
2307 	lo->lo_state = Lo_unbound;
2308 
2309 	err = mutex_lock_killable(&loop_ctl_mutex);
2310 	if (err)
2311 		goto out_free_dev;
2312 
2313 	/* allocate id, if @id >= 0, we're requesting that specific id */
2314 	if (i >= 0) {
2315 		err = idr_alloc(&loop_index_idr, lo, i, i + 1, GFP_KERNEL);
2316 		if (err == -ENOSPC)
2317 			err = -EEXIST;
2318 	} else {
2319 		err = idr_alloc(&loop_index_idr, lo, 0, 0, GFP_KERNEL);
2320 	}
2321 	mutex_unlock(&loop_ctl_mutex);
2322 	if (err < 0)
2323 		goto out_free_dev;
2324 	i = err;
2325 
2326 	err = -ENOMEM;
2327 	lo->tag_set.ops = &loop_mq_ops;
2328 	lo->tag_set.nr_hw_queues = 1;
2329 	lo->tag_set.queue_depth = 128;
2330 	lo->tag_set.numa_node = NUMA_NO_NODE;
2331 	lo->tag_set.cmd_size = sizeof(struct loop_cmd);
2332 	lo->tag_set.flags = BLK_MQ_F_SHOULD_MERGE | BLK_MQ_F_STACKING |
2333 		BLK_MQ_F_NO_SCHED_BY_DEFAULT;
2334 	lo->tag_set.driver_data = lo;
2335 
2336 	err = blk_mq_alloc_tag_set(&lo->tag_set);
2337 	if (err)
2338 		goto out_free_idr;
2339 
2340 	disk = lo->lo_disk = blk_mq_alloc_disk(&lo->tag_set, lo);
2341 	if (IS_ERR(disk)) {
2342 		err = PTR_ERR(disk);
2343 		goto out_cleanup_tags;
2344 	}
2345 	lo->lo_queue = lo->lo_disk->queue;
2346 
2347 	blk_queue_max_hw_sectors(lo->lo_queue, BLK_DEF_MAX_SECTORS);
2348 
2349 	/*
2350 	 * By default, we do buffer IO, so it doesn't make sense to enable
2351 	 * merge because the I/O submitted to backing file is handled page by
2352 	 * page. For directio mode, merge does help to dispatch bigger request
2353 	 * to underlayer disk. We will enable merge once directio is enabled.
2354 	 */
2355 	blk_queue_flag_set(QUEUE_FLAG_NOMERGES, lo->lo_queue);
2356 
2357 	/*
2358 	 * Disable partition scanning by default. The in-kernel partition
2359 	 * scanning can be requested individually per-device during its
2360 	 * setup. Userspace can always add and remove partitions from all
2361 	 * devices. The needed partition minors are allocated from the
2362 	 * extended minor space, the main loop device numbers will continue
2363 	 * to match the loop minors, regardless of the number of partitions
2364 	 * used.
2365 	 *
2366 	 * If max_part is given, partition scanning is globally enabled for
2367 	 * all loop devices. The minors for the main loop devices will be
2368 	 * multiples of max_part.
2369 	 *
2370 	 * Note: Global-for-all-devices, set-only-at-init, read-only module
2371 	 * parameteters like 'max_loop' and 'max_part' make things needlessly
2372 	 * complicated, are too static, inflexible and may surprise
2373 	 * userspace tools. Parameters like this in general should be avoided.
2374 	 */
2375 	if (!part_shift)
2376 		disk->flags |= GENHD_FL_NO_PART_SCAN;
2377 	disk->flags |= GENHD_FL_EXT_DEVT;
2378 	atomic_set(&lo->lo_refcnt, 0);
2379 	mutex_init(&lo->lo_mutex);
2380 	lo->lo_number		= i;
2381 	spin_lock_init(&lo->lo_lock);
2382 	spin_lock_init(&lo->lo_work_lock);
2383 	disk->major		= LOOP_MAJOR;
2384 	disk->first_minor	= i << part_shift;
2385 	disk->minors		= 1 << part_shift;
2386 	disk->fops		= &lo_fops;
2387 	disk->private_data	= lo;
2388 	disk->queue		= lo->lo_queue;
2389 	disk->events		= DISK_EVENT_MEDIA_CHANGE;
2390 	disk->event_flags	= DISK_EVENT_FLAG_UEVENT;
2391 	sprintf(disk->disk_name, "loop%d", i);
2392 	/* Make this loop device reachable from pathname. */
2393 	add_disk(disk);
2394 	/* Show this loop device. */
2395 	mutex_lock(&loop_ctl_mutex);
2396 	lo->idr_visible = true;
2397 	mutex_unlock(&loop_ctl_mutex);
2398 	return i;
2399 
2400 out_cleanup_tags:
2401 	blk_mq_free_tag_set(&lo->tag_set);
2402 out_free_idr:
2403 	mutex_lock(&loop_ctl_mutex);
2404 	idr_remove(&loop_index_idr, i);
2405 	mutex_unlock(&loop_ctl_mutex);
2406 out_free_dev:
2407 	kfree(lo);
2408 out:
2409 	return err;
2410 }
2411 
2412 static void loop_remove(struct loop_device *lo)
2413 {
2414 	/* Make this loop device unreachable from pathname. */
2415 	del_gendisk(lo->lo_disk);
2416 	blk_cleanup_disk(lo->lo_disk);
2417 	blk_mq_free_tag_set(&lo->tag_set);
2418 	mutex_lock(&loop_ctl_mutex);
2419 	idr_remove(&loop_index_idr, lo->lo_number);
2420 	mutex_unlock(&loop_ctl_mutex);
2421 	/* There is no route which can find this loop device. */
2422 	mutex_destroy(&lo->lo_mutex);
2423 	kfree(lo);
2424 }
2425 
2426 static void loop_probe(dev_t dev)
2427 {
2428 	int idx = MINOR(dev) >> part_shift;
2429 
2430 	if (max_loop && idx >= max_loop)
2431 		return;
2432 	loop_add(idx);
2433 }
2434 
2435 static int loop_control_remove(int idx)
2436 {
2437 	struct loop_device *lo;
2438 	int ret;
2439 
2440 	if (idx < 0) {
2441 		pr_warn("deleting an unspecified loop device is not supported.\n");
2442 		return -EINVAL;
2443 	}
2444 
2445 	/* Hide this loop device for serialization. */
2446 	ret = mutex_lock_killable(&loop_ctl_mutex);
2447 	if (ret)
2448 		return ret;
2449 	lo = idr_find(&loop_index_idr, idx);
2450 	if (!lo || !lo->idr_visible)
2451 		ret = -ENODEV;
2452 	else
2453 		lo->idr_visible = false;
2454 	mutex_unlock(&loop_ctl_mutex);
2455 	if (ret)
2456 		return ret;
2457 
2458 	/* Check whether this loop device can be removed. */
2459 	ret = mutex_lock_killable(&lo->lo_mutex);
2460 	if (ret)
2461 		goto mark_visible;
2462 	if (lo->lo_state != Lo_unbound ||
2463 	    atomic_read(&lo->lo_refcnt) > 0) {
2464 		mutex_unlock(&lo->lo_mutex);
2465 		ret = -EBUSY;
2466 		goto mark_visible;
2467 	}
2468 	/* Mark this loop device no longer open()-able. */
2469 	lo->lo_state = Lo_deleting;
2470 	mutex_unlock(&lo->lo_mutex);
2471 
2472 	loop_remove(lo);
2473 	return 0;
2474 
2475 mark_visible:
2476 	/* Show this loop device again. */
2477 	mutex_lock(&loop_ctl_mutex);
2478 	lo->idr_visible = true;
2479 	mutex_unlock(&loop_ctl_mutex);
2480 	return ret;
2481 }
2482 
2483 static int loop_control_get_free(int idx)
2484 {
2485 	struct loop_device *lo;
2486 	int id, ret;
2487 
2488 	ret = mutex_lock_killable(&loop_ctl_mutex);
2489 	if (ret)
2490 		return ret;
2491 	idr_for_each_entry(&loop_index_idr, lo, id) {
2492 		/* Hitting a race results in creating a new loop device which is harmless. */
2493 		if (lo->idr_visible && data_race(lo->lo_state) == Lo_unbound)
2494 			goto found;
2495 	}
2496 	mutex_unlock(&loop_ctl_mutex);
2497 	return loop_add(-1);
2498 found:
2499 	mutex_unlock(&loop_ctl_mutex);
2500 	return id;
2501 }
2502 
2503 static long loop_control_ioctl(struct file *file, unsigned int cmd,
2504 			       unsigned long parm)
2505 {
2506 	switch (cmd) {
2507 	case LOOP_CTL_ADD:
2508 		return loop_add(parm);
2509 	case LOOP_CTL_REMOVE:
2510 		return loop_control_remove(parm);
2511 	case LOOP_CTL_GET_FREE:
2512 		return loop_control_get_free(parm);
2513 	default:
2514 		return -ENOSYS;
2515 	}
2516 }
2517 
2518 static const struct file_operations loop_ctl_fops = {
2519 	.open		= nonseekable_open,
2520 	.unlocked_ioctl	= loop_control_ioctl,
2521 	.compat_ioctl	= loop_control_ioctl,
2522 	.owner		= THIS_MODULE,
2523 	.llseek		= noop_llseek,
2524 };
2525 
2526 static struct miscdevice loop_misc = {
2527 	.minor		= LOOP_CTRL_MINOR,
2528 	.name		= "loop-control",
2529 	.fops		= &loop_ctl_fops,
2530 };
2531 
2532 MODULE_ALIAS_MISCDEV(LOOP_CTRL_MINOR);
2533 MODULE_ALIAS("devname:loop-control");
2534 
2535 static int __init loop_init(void)
2536 {
2537 	int i, nr;
2538 	int err;
2539 
2540 	part_shift = 0;
2541 	if (max_part > 0) {
2542 		part_shift = fls(max_part);
2543 
2544 		/*
2545 		 * Adjust max_part according to part_shift as it is exported
2546 		 * to user space so that user can decide correct minor number
2547 		 * if [s]he want to create more devices.
2548 		 *
2549 		 * Note that -1 is required because partition 0 is reserved
2550 		 * for the whole disk.
2551 		 */
2552 		max_part = (1UL << part_shift) - 1;
2553 	}
2554 
2555 	if ((1UL << part_shift) > DISK_MAX_PARTS) {
2556 		err = -EINVAL;
2557 		goto err_out;
2558 	}
2559 
2560 	if (max_loop > 1UL << (MINORBITS - part_shift)) {
2561 		err = -EINVAL;
2562 		goto err_out;
2563 	}
2564 
2565 	/*
2566 	 * If max_loop is specified, create that many devices upfront.
2567 	 * This also becomes a hard limit. If max_loop is not specified,
2568 	 * create CONFIG_BLK_DEV_LOOP_MIN_COUNT loop devices at module
2569 	 * init time. Loop devices can be requested on-demand with the
2570 	 * /dev/loop-control interface, or be instantiated by accessing
2571 	 * a 'dead' device node.
2572 	 */
2573 	if (max_loop)
2574 		nr = max_loop;
2575 	else
2576 		nr = CONFIG_BLK_DEV_LOOP_MIN_COUNT;
2577 
2578 	err = misc_register(&loop_misc);
2579 	if (err < 0)
2580 		goto err_out;
2581 
2582 
2583 	if (__register_blkdev(LOOP_MAJOR, "loop", loop_probe)) {
2584 		err = -EIO;
2585 		goto misc_out;
2586 	}
2587 
2588 	/* pre-create number of devices given by config or max_loop */
2589 	for (i = 0; i < nr; i++)
2590 		loop_add(i);
2591 
2592 	printk(KERN_INFO "loop: module loaded\n");
2593 	return 0;
2594 
2595 misc_out:
2596 	misc_deregister(&loop_misc);
2597 err_out:
2598 	return err;
2599 }
2600 
2601 static void __exit loop_exit(void)
2602 {
2603 	struct loop_device *lo;
2604 	int id;
2605 
2606 	unregister_blkdev(LOOP_MAJOR, "loop");
2607 	misc_deregister(&loop_misc);
2608 
2609 	/*
2610 	 * There is no need to use loop_ctl_mutex here, for nobody else can
2611 	 * access loop_index_idr when this module is unloading (unless forced
2612 	 * module unloading is requested). If this is not a clean unloading,
2613 	 * we have no means to avoid kernel crash.
2614 	 */
2615 	idr_for_each_entry(&loop_index_idr, lo, id)
2616 		loop_remove(lo);
2617 
2618 	idr_destroy(&loop_index_idr);
2619 }
2620 
2621 module_init(loop_init);
2622 module_exit(loop_exit);
2623 
2624 #ifndef MODULE
2625 static int __init max_loop_setup(char *str)
2626 {
2627 	max_loop = simple_strtol(str, NULL, 0);
2628 	return 1;
2629 }
2630 
2631 __setup("max_loop=", max_loop_setup);
2632 #endif
2633