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