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