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