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