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