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