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