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