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