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