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