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