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