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