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