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