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