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