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