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