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