xref: /linux/drivers/block/loop.c (revision cb2076b0910f3b19036ec7d50530113fcb9736c8)
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_array(nr_bvec, sizeof(struct bio_vec),
359 				     GFP_NOIO);
360 		if (!bvec)
361 			return -EIO;
362 		cmd->bvec = bvec;
363 
364 		/*
365 		 * The bios of the request may be started from the middle of
366 		 * the 'bvec' because of bio splitting, so we can't directly
367 		 * copy bio->bi_iov_vec to new bvec. The rq_for_each_bvec
368 		 * API will take care of all details for us.
369 		 */
370 		rq_for_each_bvec(tmp, rq, rq_iter) {
371 			*bvec = tmp;
372 			bvec++;
373 		}
374 		bvec = cmd->bvec;
375 		offset = 0;
376 	} else {
377 		/*
378 		 * Same here, this bio may be started from the middle of the
379 		 * 'bvec' because of bio splitting, so offset from the bvec
380 		 * must be passed to iov iterator
381 		 */
382 		offset = bio->bi_iter.bi_bvec_done;
383 		bvec = __bvec_iter_bvec(bio->bi_io_vec, bio->bi_iter);
384 	}
385 	atomic_set(&cmd->ref, 2);
386 
387 	iov_iter_bvec(&iter, rw, bvec, nr_bvec, blk_rq_bytes(rq));
388 	iter.iov_offset = offset;
389 
390 	cmd->iocb.ki_pos = pos;
391 	cmd->iocb.ki_filp = file;
392 	cmd->iocb.ki_ioprio = req_get_ioprio(rq);
393 	if (cmd->use_aio) {
394 		cmd->iocb.ki_complete = lo_rw_aio_complete;
395 		cmd->iocb.ki_flags = IOCB_DIRECT;
396 	} else {
397 		cmd->iocb.ki_complete = NULL;
398 		cmd->iocb.ki_flags = 0;
399 	}
400 
401 	if (rw == ITER_SOURCE) {
402 		kiocb_start_write(&cmd->iocb);
403 		ret = file->f_op->write_iter(&cmd->iocb, &iter);
404 	} else
405 		ret = file->f_op->read_iter(&cmd->iocb, &iter);
406 
407 	lo_rw_aio_do_completion(cmd);
408 
409 	if (ret != -EIOCBQUEUED)
410 		lo_rw_aio_complete(&cmd->iocb, ret);
411 	return -EIOCBQUEUED;
412 }
413 
do_req_filebacked(struct loop_device * lo,struct request * rq)414 static int do_req_filebacked(struct loop_device *lo, struct request *rq)
415 {
416 	struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
417 	loff_t pos = ((loff_t) blk_rq_pos(rq) << 9) + lo->lo_offset;
418 
419 	switch (req_op(rq)) {
420 	case REQ_OP_FLUSH:
421 		return lo_req_flush(lo, rq);
422 	case REQ_OP_WRITE_ZEROES:
423 		/*
424 		 * If the caller doesn't want deallocation, call zeroout to
425 		 * write zeroes the range.  Otherwise, punch them out.
426 		 */
427 		return lo_fallocate(lo, rq, pos,
428 			(rq->cmd_flags & REQ_NOUNMAP) ?
429 				FALLOC_FL_ZERO_RANGE :
430 				FALLOC_FL_PUNCH_HOLE);
431 	case REQ_OP_DISCARD:
432 		return lo_fallocate(lo, rq, pos, FALLOC_FL_PUNCH_HOLE);
433 	case REQ_OP_WRITE:
434 		return lo_rw_aio(lo, cmd, pos, ITER_SOURCE);
435 	case REQ_OP_READ:
436 		return lo_rw_aio(lo, cmd, pos, ITER_DEST);
437 	default:
438 		WARN_ON_ONCE(1);
439 		return -EIO;
440 	}
441 }
442 
loop_reread_partitions(struct loop_device * lo)443 static void loop_reread_partitions(struct loop_device *lo)
444 {
445 	int rc;
446 
447 	mutex_lock(&lo->lo_disk->open_mutex);
448 	rc = bdev_disk_changed(lo->lo_disk, false);
449 	mutex_unlock(&lo->lo_disk->open_mutex);
450 	if (rc)
451 		pr_warn("%s: partition scan of loop%d (%s) failed (rc=%d)\n",
452 			__func__, lo->lo_number, lo->lo_file_name, rc);
453 }
454 
loop_query_min_dio_size(struct loop_device * lo)455 static unsigned int loop_query_min_dio_size(struct loop_device *lo)
456 {
457 	struct file *file = lo->lo_backing_file;
458 	struct block_device *sb_bdev = file->f_mapping->host->i_sb->s_bdev;
459 	struct kstat st;
460 
461 	/*
462 	 * Use the minimal dio alignment of the file system if provided.
463 	 */
464 	if (!vfs_getattr(&file->f_path, &st, STATX_DIOALIGN, 0) &&
465 	    (st.result_mask & STATX_DIOALIGN))
466 		return st.dio_offset_align;
467 
468 	/*
469 	 * In a perfect world this wouldn't be needed, but as of Linux 6.13 only
470 	 * a handful of file systems support the STATX_DIOALIGN flag.
471 	 */
472 	if (sb_bdev)
473 		return bdev_logical_block_size(sb_bdev);
474 	return SECTOR_SIZE;
475 }
476 
is_loop_device(struct file * file)477 static inline int is_loop_device(struct file *file)
478 {
479 	struct inode *i = file->f_mapping->host;
480 
481 	return i && S_ISBLK(i->i_mode) && imajor(i) == LOOP_MAJOR;
482 }
483 
loop_validate_file(struct file * file,struct block_device * bdev)484 static int loop_validate_file(struct file *file, struct block_device *bdev)
485 {
486 	struct inode	*inode = file->f_mapping->host;
487 	struct file	*f = file;
488 
489 	/* Avoid recursion */
490 	while (is_loop_device(f)) {
491 		struct loop_device *l;
492 
493 		lockdep_assert_held(&loop_validate_mutex);
494 		if (f->f_mapping->host->i_rdev == bdev->bd_dev)
495 			return -EBADF;
496 
497 		l = I_BDEV(f->f_mapping->host)->bd_disk->private_data;
498 		if (l->lo_state != Lo_bound)
499 			return -EINVAL;
500 		/* Order wrt setting lo->lo_backing_file in loop_configure(). */
501 		rmb();
502 		f = l->lo_backing_file;
503 	}
504 	if (!S_ISREG(inode->i_mode) && !S_ISBLK(inode->i_mode))
505 		return -EINVAL;
506 	return 0;
507 }
508 
loop_assign_backing_file(struct loop_device * lo,struct file * file)509 static void loop_assign_backing_file(struct loop_device *lo, struct file *file)
510 {
511 	lo->lo_backing_file = file;
512 	lo->old_gfp_mask = mapping_gfp_mask(file->f_mapping);
513 	mapping_set_gfp_mask(file->f_mapping,
514 			lo->old_gfp_mask & ~(__GFP_IO | __GFP_FS));
515 	if (lo->lo_backing_file->f_flags & O_DIRECT)
516 		lo->lo_flags |= LO_FLAGS_DIRECT_IO;
517 	lo->lo_min_dio_size = loop_query_min_dio_size(lo);
518 }
519 
loop_check_backing_file(struct file * file)520 static int loop_check_backing_file(struct file *file)
521 {
522 	if (!file->f_op->read_iter)
523 		return -EINVAL;
524 
525 	if ((file->f_mode & FMODE_WRITE) && !file->f_op->write_iter)
526 		return -EINVAL;
527 
528 	return 0;
529 }
530 
531 /*
532  * loop_change_fd switched the backing store of a loopback device to
533  * a new file. This is useful for operating system installers to free up
534  * the original file and in High Availability environments to switch to
535  * an alternative location for the content in case of server meltdown.
536  * This can only work if the loop device is used read-only, and if the
537  * new backing store is the same size and type as the old backing store.
538  */
loop_change_fd(struct loop_device * lo,struct block_device * bdev,unsigned int arg)539 static int loop_change_fd(struct loop_device *lo, struct block_device *bdev,
540 			  unsigned int arg)
541 {
542 	struct file *file = fget(arg);
543 	struct file *old_file;
544 	unsigned int memflags;
545 	int error;
546 	bool partscan;
547 	bool is_loop;
548 
549 	if (!file)
550 		return -EBADF;
551 
552 	error = loop_check_backing_file(file);
553 	if (error) {
554 		fput(file);
555 		return error;
556 	}
557 
558 	/* suppress uevents while reconfiguring the device */
559 	dev_set_uevent_suppress(disk_to_dev(lo->lo_disk), 1);
560 
561 	is_loop = is_loop_device(file);
562 	error = loop_global_lock_killable(lo, is_loop);
563 	if (error)
564 		goto out_putf;
565 	error = -ENXIO;
566 	if (lo->lo_state != Lo_bound)
567 		goto out_err;
568 
569 	/* the loop device has to be read-only */
570 	error = -EINVAL;
571 	if (!(lo->lo_flags & LO_FLAGS_READ_ONLY))
572 		goto out_err;
573 
574 	error = loop_validate_file(file, bdev);
575 	if (error)
576 		goto out_err;
577 
578 	old_file = lo->lo_backing_file;
579 
580 	error = -EINVAL;
581 
582 	/* size of the new backing store needs to be the same */
583 	if (lo_calculate_size(lo, file) != lo_calculate_size(lo, old_file))
584 		goto out_err;
585 
586 	/*
587 	 * We might switch to direct I/O mode for the loop device, write back
588 	 * all dirty data the page cache now that so that the individual I/O
589 	 * operations don't have to do that.
590 	 */
591 	vfs_fsync(file, 0);
592 
593 	/* and ... switch */
594 	disk_force_media_change(lo->lo_disk);
595 	memflags = blk_mq_freeze_queue(lo->lo_queue);
596 	mapping_set_gfp_mask(old_file->f_mapping, lo->old_gfp_mask);
597 	loop_assign_backing_file(lo, file);
598 	loop_update_dio(lo);
599 	blk_mq_unfreeze_queue(lo->lo_queue, memflags);
600 	partscan = lo->lo_flags & LO_FLAGS_PARTSCAN;
601 	loop_global_unlock(lo, is_loop);
602 
603 	/*
604 	 * Flush loop_validate_file() before fput(), for l->lo_backing_file
605 	 * might be pointing at old_file which might be the last reference.
606 	 */
607 	if (!is_loop) {
608 		mutex_lock(&loop_validate_mutex);
609 		mutex_unlock(&loop_validate_mutex);
610 	}
611 	/*
612 	 * We must drop file reference outside of lo_mutex as dropping
613 	 * the file ref can take open_mutex which creates circular locking
614 	 * dependency.
615 	 */
616 	fput(old_file);
617 	dev_set_uevent_suppress(disk_to_dev(lo->lo_disk), 0);
618 	if (partscan)
619 		loop_reread_partitions(lo);
620 
621 	error = 0;
622 done:
623 	kobject_uevent(&disk_to_dev(lo->lo_disk)->kobj, KOBJ_CHANGE);
624 	return error;
625 
626 out_err:
627 	loop_global_unlock(lo, is_loop);
628 out_putf:
629 	fput(file);
630 	dev_set_uevent_suppress(disk_to_dev(lo->lo_disk), 0);
631 	goto done;
632 }
633 
634 /* loop sysfs attributes */
635 
loop_attr_show(struct device * dev,char * page,ssize_t (* callback)(struct loop_device *,char *))636 static ssize_t loop_attr_show(struct device *dev, char *page,
637 			      ssize_t (*callback)(struct loop_device *, char *))
638 {
639 	struct gendisk *disk = dev_to_disk(dev);
640 	struct loop_device *lo = disk->private_data;
641 
642 	return callback(lo, page);
643 }
644 
645 #define LOOP_ATTR_RO(_name)						\
646 static ssize_t loop_attr_##_name##_show(struct loop_device *, char *);	\
647 static ssize_t loop_attr_do_show_##_name(struct device *d,		\
648 				struct device_attribute *attr, char *b)	\
649 {									\
650 	return loop_attr_show(d, b, loop_attr_##_name##_show);		\
651 }									\
652 static struct device_attribute loop_attr_##_name =			\
653 	__ATTR(_name, 0444, loop_attr_do_show_##_name, NULL);
654 
loop_attr_backing_file_show(struct loop_device * lo,char * buf)655 static ssize_t loop_attr_backing_file_show(struct loop_device *lo, char *buf)
656 {
657 	ssize_t ret;
658 	char *p = NULL;
659 
660 	spin_lock_irq(&lo->lo_lock);
661 	if (lo->lo_backing_file)
662 		p = file_path(lo->lo_backing_file, buf, PAGE_SIZE - 1);
663 	spin_unlock_irq(&lo->lo_lock);
664 
665 	if (IS_ERR_OR_NULL(p))
666 		ret = PTR_ERR(p);
667 	else {
668 		ret = strlen(p);
669 		memmove(buf, p, ret);
670 		buf[ret++] = '\n';
671 		buf[ret] = 0;
672 	}
673 
674 	return ret;
675 }
676 
loop_attr_offset_show(struct loop_device * lo,char * buf)677 static ssize_t loop_attr_offset_show(struct loop_device *lo, char *buf)
678 {
679 	return sysfs_emit(buf, "%llu\n", (unsigned long long)lo->lo_offset);
680 }
681 
loop_attr_sizelimit_show(struct loop_device * lo,char * buf)682 static ssize_t loop_attr_sizelimit_show(struct loop_device *lo, char *buf)
683 {
684 	return sysfs_emit(buf, "%llu\n", (unsigned long long)lo->lo_sizelimit);
685 }
686 
loop_attr_autoclear_show(struct loop_device * lo,char * buf)687 static ssize_t loop_attr_autoclear_show(struct loop_device *lo, char *buf)
688 {
689 	int autoclear = (lo->lo_flags & LO_FLAGS_AUTOCLEAR);
690 
691 	return sysfs_emit(buf, "%s\n", autoclear ? "1" : "0");
692 }
693 
loop_attr_partscan_show(struct loop_device * lo,char * buf)694 static ssize_t loop_attr_partscan_show(struct loop_device *lo, char *buf)
695 {
696 	int partscan = (lo->lo_flags & LO_FLAGS_PARTSCAN);
697 
698 	return sysfs_emit(buf, "%s\n", partscan ? "1" : "0");
699 }
700 
loop_attr_dio_show(struct loop_device * lo,char * buf)701 static ssize_t loop_attr_dio_show(struct loop_device *lo, char *buf)
702 {
703 	int dio = (lo->lo_flags & LO_FLAGS_DIRECT_IO);
704 
705 	return sysfs_emit(buf, "%s\n", dio ? "1" : "0");
706 }
707 
708 LOOP_ATTR_RO(backing_file);
709 LOOP_ATTR_RO(offset);
710 LOOP_ATTR_RO(sizelimit);
711 LOOP_ATTR_RO(autoclear);
712 LOOP_ATTR_RO(partscan);
713 LOOP_ATTR_RO(dio);
714 
715 static struct attribute *loop_attrs[] = {
716 	&loop_attr_backing_file.attr,
717 	&loop_attr_offset.attr,
718 	&loop_attr_sizelimit.attr,
719 	&loop_attr_autoclear.attr,
720 	&loop_attr_partscan.attr,
721 	&loop_attr_dio.attr,
722 	NULL,
723 };
724 
725 static struct attribute_group loop_attribute_group = {
726 	.name = "loop",
727 	.attrs= loop_attrs,
728 };
729 
loop_sysfs_init(struct loop_device * lo)730 static void loop_sysfs_init(struct loop_device *lo)
731 {
732 	lo->sysfs_inited = !sysfs_create_group(&disk_to_dev(lo->lo_disk)->kobj,
733 						&loop_attribute_group);
734 }
735 
loop_sysfs_exit(struct loop_device * lo)736 static void loop_sysfs_exit(struct loop_device *lo)
737 {
738 	if (lo->sysfs_inited)
739 		sysfs_remove_group(&disk_to_dev(lo->lo_disk)->kobj,
740 				   &loop_attribute_group);
741 }
742 
loop_get_discard_config(struct loop_device * lo,u32 * granularity,u32 * max_discard_sectors)743 static void loop_get_discard_config(struct loop_device *lo,
744 				    u32 *granularity, u32 *max_discard_sectors)
745 {
746 	struct file *file = lo->lo_backing_file;
747 	struct inode *inode = file->f_mapping->host;
748 	struct kstatfs sbuf;
749 
750 	/*
751 	 * If the backing device is a block device, mirror its zeroing
752 	 * capability. Set the discard sectors to the block device's zeroing
753 	 * capabilities because loop discards result in blkdev_issue_zeroout(),
754 	 * not blkdev_issue_discard(). This maintains consistent behavior with
755 	 * file-backed loop devices: discarded regions read back as zero.
756 	 */
757 	if (S_ISBLK(inode->i_mode)) {
758 		struct block_device *bdev = I_BDEV(inode);
759 
760 		*max_discard_sectors = bdev_write_zeroes_sectors(bdev);
761 		*granularity = bdev_discard_granularity(bdev);
762 
763 	/*
764 	 * We use punch hole to reclaim the free space used by the
765 	 * image a.k.a. discard.
766 	 */
767 	} else if (file->f_op->fallocate && !vfs_statfs(&file->f_path, &sbuf)) {
768 		*max_discard_sectors = UINT_MAX >> 9;
769 		*granularity = sbuf.f_bsize;
770 	}
771 }
772 
773 struct loop_worker {
774 	struct rb_node rb_node;
775 	struct work_struct work;
776 	struct list_head cmd_list;
777 	struct list_head idle_list;
778 	struct loop_device *lo;
779 	struct cgroup_subsys_state *blkcg_css;
780 	unsigned long last_ran_at;
781 };
782 
783 static void loop_workfn(struct work_struct *work);
784 
785 #ifdef CONFIG_BLK_CGROUP
queue_on_root_worker(struct cgroup_subsys_state * css)786 static inline int queue_on_root_worker(struct cgroup_subsys_state *css)
787 {
788 	return !css || css == blkcg_root_css;
789 }
790 #else
queue_on_root_worker(struct cgroup_subsys_state * css)791 static inline int queue_on_root_worker(struct cgroup_subsys_state *css)
792 {
793 	return !css;
794 }
795 #endif
796 
loop_queue_work(struct loop_device * lo,struct loop_cmd * cmd)797 static void loop_queue_work(struct loop_device *lo, struct loop_cmd *cmd)
798 {
799 	struct rb_node **node, *parent = NULL;
800 	struct loop_worker *cur_worker, *worker = NULL;
801 	struct work_struct *work;
802 	struct list_head *cmd_list;
803 
804 	spin_lock_irq(&lo->lo_work_lock);
805 
806 	if (queue_on_root_worker(cmd->blkcg_css))
807 		goto queue_work;
808 
809 	node = &lo->worker_tree.rb_node;
810 
811 	while (*node) {
812 		parent = *node;
813 		cur_worker = container_of(*node, struct loop_worker, rb_node);
814 		if (cur_worker->blkcg_css == cmd->blkcg_css) {
815 			worker = cur_worker;
816 			break;
817 		} else if ((long)cur_worker->blkcg_css < (long)cmd->blkcg_css) {
818 			node = &(*node)->rb_left;
819 		} else {
820 			node = &(*node)->rb_right;
821 		}
822 	}
823 	if (worker)
824 		goto queue_work;
825 
826 	worker = kzalloc(sizeof(struct loop_worker), GFP_NOWAIT);
827 	/*
828 	 * In the event we cannot allocate a worker, just queue on the
829 	 * rootcg worker and issue the I/O as the rootcg
830 	 */
831 	if (!worker) {
832 		cmd->blkcg_css = NULL;
833 		if (cmd->memcg_css)
834 			css_put(cmd->memcg_css);
835 		cmd->memcg_css = NULL;
836 		goto queue_work;
837 	}
838 
839 	worker->blkcg_css = cmd->blkcg_css;
840 	css_get(worker->blkcg_css);
841 	INIT_WORK(&worker->work, loop_workfn);
842 	INIT_LIST_HEAD(&worker->cmd_list);
843 	INIT_LIST_HEAD(&worker->idle_list);
844 	worker->lo = lo;
845 	rb_link_node(&worker->rb_node, parent, node);
846 	rb_insert_color(&worker->rb_node, &lo->worker_tree);
847 queue_work:
848 	if (worker) {
849 		/*
850 		 * We need to remove from the idle list here while
851 		 * holding the lock so that the idle timer doesn't
852 		 * free the worker
853 		 */
854 		if (!list_empty(&worker->idle_list))
855 			list_del_init(&worker->idle_list);
856 		work = &worker->work;
857 		cmd_list = &worker->cmd_list;
858 	} else {
859 		work = &lo->rootcg_work;
860 		cmd_list = &lo->rootcg_cmd_list;
861 	}
862 	list_add_tail(&cmd->list_entry, cmd_list);
863 	queue_work(lo->workqueue, work);
864 	spin_unlock_irq(&lo->lo_work_lock);
865 }
866 
loop_set_timer(struct loop_device * lo)867 static void loop_set_timer(struct loop_device *lo)
868 {
869 	timer_reduce(&lo->timer, jiffies + LOOP_IDLE_WORKER_TIMEOUT);
870 }
871 
loop_free_idle_workers(struct loop_device * lo,bool delete_all)872 static void loop_free_idle_workers(struct loop_device *lo, bool delete_all)
873 {
874 	struct loop_worker *pos, *worker;
875 
876 	spin_lock_irq(&lo->lo_work_lock);
877 	list_for_each_entry_safe(worker, pos, &lo->idle_worker_list,
878 				idle_list) {
879 		if (!delete_all &&
880 		    time_is_after_jiffies(worker->last_ran_at +
881 					  LOOP_IDLE_WORKER_TIMEOUT))
882 			break;
883 		list_del(&worker->idle_list);
884 		rb_erase(&worker->rb_node, &lo->worker_tree);
885 		css_put(worker->blkcg_css);
886 		kfree(worker);
887 	}
888 	if (!list_empty(&lo->idle_worker_list))
889 		loop_set_timer(lo);
890 	spin_unlock_irq(&lo->lo_work_lock);
891 }
892 
loop_free_idle_workers_timer(struct timer_list * timer)893 static void loop_free_idle_workers_timer(struct timer_list *timer)
894 {
895 	struct loop_device *lo = container_of(timer, struct loop_device, timer);
896 
897 	return loop_free_idle_workers(lo, false);
898 }
899 
900 /**
901  * loop_set_status_from_info - configure device from loop_info
902  * @lo: struct loop_device to configure
903  * @info: struct loop_info64 to configure the device with
904  *
905  * Configures the loop device parameters according to the passed
906  * in loop_info64 configuration.
907  */
908 static int
loop_set_status_from_info(struct loop_device * lo,const struct loop_info64 * info)909 loop_set_status_from_info(struct loop_device *lo,
910 			  const struct loop_info64 *info)
911 {
912 	if ((unsigned int) info->lo_encrypt_key_size > LO_KEY_SIZE)
913 		return -EINVAL;
914 
915 	switch (info->lo_encrypt_type) {
916 	case LO_CRYPT_NONE:
917 		break;
918 	case LO_CRYPT_XOR:
919 		pr_warn("support for the xor transformation has been removed.\n");
920 		return -EINVAL;
921 	case LO_CRYPT_CRYPTOAPI:
922 		pr_warn("support for cryptoloop has been removed.  Use dm-crypt instead.\n");
923 		return -EINVAL;
924 	default:
925 		return -EINVAL;
926 	}
927 
928 	/* Avoid assigning overflow values */
929 	if (info->lo_offset > LLONG_MAX || info->lo_sizelimit > LLONG_MAX)
930 		return -EOVERFLOW;
931 
932 	lo->lo_offset = info->lo_offset;
933 	lo->lo_sizelimit = info->lo_sizelimit;
934 
935 	memcpy(lo->lo_file_name, info->lo_file_name, LO_NAME_SIZE);
936 	lo->lo_file_name[LO_NAME_SIZE-1] = 0;
937 	return 0;
938 }
939 
loop_default_blocksize(struct loop_device * lo)940 static unsigned int loop_default_blocksize(struct loop_device *lo)
941 {
942 	/* In case of direct I/O, match underlying minimum I/O size */
943 	if (lo->lo_flags & LO_FLAGS_DIRECT_IO)
944 		return lo->lo_min_dio_size;
945 	return SECTOR_SIZE;
946 }
947 
loop_update_limits(struct loop_device * lo,struct queue_limits * lim,unsigned int bsize)948 static void loop_update_limits(struct loop_device *lo, struct queue_limits *lim,
949 		unsigned int bsize)
950 {
951 	struct file *file = lo->lo_backing_file;
952 	struct inode *inode = file->f_mapping->host;
953 	struct block_device *backing_bdev = NULL;
954 	u32 granularity = 0, max_discard_sectors = 0;
955 
956 	if (S_ISBLK(inode->i_mode))
957 		backing_bdev = I_BDEV(inode);
958 	else if (inode->i_sb->s_bdev)
959 		backing_bdev = inode->i_sb->s_bdev;
960 
961 	if (!bsize)
962 		bsize = loop_default_blocksize(lo);
963 
964 	loop_get_discard_config(lo, &granularity, &max_discard_sectors);
965 
966 	lim->logical_block_size = bsize;
967 	lim->physical_block_size = bsize;
968 	lim->io_min = bsize;
969 	lim->features &= ~(BLK_FEAT_WRITE_CACHE | BLK_FEAT_ROTATIONAL);
970 	if (file->f_op->fsync && !(lo->lo_flags & LO_FLAGS_READ_ONLY))
971 		lim->features |= BLK_FEAT_WRITE_CACHE;
972 	if (backing_bdev && !bdev_nonrot(backing_bdev))
973 		lim->features |= BLK_FEAT_ROTATIONAL;
974 	lim->max_hw_discard_sectors = max_discard_sectors;
975 	lim->max_write_zeroes_sectors = max_discard_sectors;
976 	if (max_discard_sectors)
977 		lim->discard_granularity = granularity;
978 	else
979 		lim->discard_granularity = 0;
980 }
981 
loop_configure(struct loop_device * lo,blk_mode_t mode,struct block_device * bdev,const struct loop_config * config)982 static int loop_configure(struct loop_device *lo, blk_mode_t mode,
983 			  struct block_device *bdev,
984 			  const struct loop_config *config)
985 {
986 	struct file *file = fget(config->fd);
987 	struct queue_limits lim;
988 	int error;
989 	loff_t size;
990 	bool partscan;
991 	bool is_loop;
992 
993 	if (!file)
994 		return -EBADF;
995 
996 	error = loop_check_backing_file(file);
997 	if (error) {
998 		fput(file);
999 		return error;
1000 	}
1001 
1002 	is_loop = is_loop_device(file);
1003 
1004 	/* This is safe, since we have a reference from open(). */
1005 	__module_get(THIS_MODULE);
1006 
1007 	/*
1008 	 * If we don't hold exclusive handle for the device, upgrade to it
1009 	 * here to avoid changing device under exclusive owner.
1010 	 */
1011 	if (!(mode & BLK_OPEN_EXCL)) {
1012 		error = bd_prepare_to_claim(bdev, loop_configure, NULL);
1013 		if (error)
1014 			goto out_putf;
1015 	}
1016 
1017 	error = loop_global_lock_killable(lo, is_loop);
1018 	if (error)
1019 		goto out_bdev;
1020 
1021 	error = -EBUSY;
1022 	if (lo->lo_state != Lo_unbound)
1023 		goto out_unlock;
1024 
1025 	error = loop_validate_file(file, bdev);
1026 	if (error)
1027 		goto out_unlock;
1028 
1029 	if ((config->info.lo_flags & ~LOOP_CONFIGURE_SETTABLE_FLAGS) != 0) {
1030 		error = -EINVAL;
1031 		goto out_unlock;
1032 	}
1033 
1034 	error = loop_set_status_from_info(lo, &config->info);
1035 	if (error)
1036 		goto out_unlock;
1037 	lo->lo_flags = config->info.lo_flags;
1038 
1039 	if (!(file->f_mode & FMODE_WRITE) || !(mode & BLK_OPEN_WRITE) ||
1040 	    !file->f_op->write_iter)
1041 		lo->lo_flags |= LO_FLAGS_READ_ONLY;
1042 
1043 	if (!lo->workqueue) {
1044 		lo->workqueue = alloc_workqueue("loop%d",
1045 						WQ_UNBOUND | WQ_FREEZABLE,
1046 						0, lo->lo_number);
1047 		if (!lo->workqueue) {
1048 			error = -ENOMEM;
1049 			goto out_unlock;
1050 		}
1051 	}
1052 
1053 	/* suppress uevents while reconfiguring the device */
1054 	dev_set_uevent_suppress(disk_to_dev(lo->lo_disk), 1);
1055 
1056 	disk_force_media_change(lo->lo_disk);
1057 	set_disk_ro(lo->lo_disk, (lo->lo_flags & LO_FLAGS_READ_ONLY) != 0);
1058 
1059 	lo->lo_device = bdev;
1060 	loop_assign_backing_file(lo, file);
1061 
1062 	lim = queue_limits_start_update(lo->lo_queue);
1063 	loop_update_limits(lo, &lim, config->block_size);
1064 	/* No need to freeze the queue as the device isn't bound yet. */
1065 	error = queue_limits_commit_update(lo->lo_queue, &lim);
1066 	if (error)
1067 		goto out_unlock;
1068 
1069 	/*
1070 	 * We might switch to direct I/O mode for the loop device, write back
1071 	 * all dirty data the page cache now that so that the individual I/O
1072 	 * operations don't have to do that.
1073 	 */
1074 	vfs_fsync(file, 0);
1075 
1076 	loop_update_dio(lo);
1077 	loop_sysfs_init(lo);
1078 
1079 	size = lo_calculate_size(lo, file);
1080 	loop_set_size(lo, size);
1081 
1082 	/* Order wrt reading lo_state in loop_validate_file(). */
1083 	wmb();
1084 
1085 	WRITE_ONCE(lo->lo_state, Lo_bound);
1086 	if (part_shift)
1087 		lo->lo_flags |= LO_FLAGS_PARTSCAN;
1088 	partscan = lo->lo_flags & LO_FLAGS_PARTSCAN;
1089 	if (partscan)
1090 		clear_bit(GD_SUPPRESS_PART_SCAN, &lo->lo_disk->state);
1091 
1092 	dev_set_uevent_suppress(disk_to_dev(lo->lo_disk), 0);
1093 	kobject_uevent(&disk_to_dev(lo->lo_disk)->kobj, KOBJ_CHANGE);
1094 
1095 	loop_global_unlock(lo, is_loop);
1096 	if (partscan)
1097 		loop_reread_partitions(lo);
1098 
1099 	if (!(mode & BLK_OPEN_EXCL))
1100 		bd_abort_claiming(bdev, loop_configure);
1101 
1102 	return 0;
1103 
1104 out_unlock:
1105 	loop_global_unlock(lo, is_loop);
1106 out_bdev:
1107 	if (!(mode & BLK_OPEN_EXCL))
1108 		bd_abort_claiming(bdev, loop_configure);
1109 out_putf:
1110 	fput(file);
1111 	/* This is safe: open() is still holding a reference. */
1112 	module_put(THIS_MODULE);
1113 	return error;
1114 }
1115 
__loop_clr_fd(struct loop_device * lo)1116 static void __loop_clr_fd(struct loop_device *lo)
1117 {
1118 	struct queue_limits lim;
1119 	struct file *filp;
1120 	gfp_t gfp = lo->old_gfp_mask;
1121 
1122 	spin_lock_irq(&lo->lo_lock);
1123 	filp = lo->lo_backing_file;
1124 	lo->lo_backing_file = NULL;
1125 	spin_unlock_irq(&lo->lo_lock);
1126 
1127 	lo->lo_device = NULL;
1128 	lo->lo_offset = 0;
1129 	lo->lo_sizelimit = 0;
1130 	memset(lo->lo_file_name, 0, LO_NAME_SIZE);
1131 
1132 	/*
1133 	 * Reset the block size to the default.
1134 	 *
1135 	 * No queue freezing needed because this is called from the final
1136 	 * ->release call only, so there can't be any outstanding I/O.
1137 	 */
1138 	lim = queue_limits_start_update(lo->lo_queue);
1139 	lim.logical_block_size = SECTOR_SIZE;
1140 	lim.physical_block_size = SECTOR_SIZE;
1141 	lim.io_min = SECTOR_SIZE;
1142 	queue_limits_commit_update(lo->lo_queue, &lim);
1143 
1144 	invalidate_disk(lo->lo_disk);
1145 	loop_sysfs_exit(lo);
1146 	/* let user-space know about this change */
1147 	kobject_uevent(&disk_to_dev(lo->lo_disk)->kobj, KOBJ_CHANGE);
1148 	mapping_set_gfp_mask(filp->f_mapping, gfp);
1149 	/* This is safe: open() is still holding a reference. */
1150 	module_put(THIS_MODULE);
1151 
1152 	disk_force_media_change(lo->lo_disk);
1153 
1154 	if (lo->lo_flags & LO_FLAGS_PARTSCAN) {
1155 		int err;
1156 
1157 		/*
1158 		 * open_mutex has been held already in release path, so don't
1159 		 * acquire it if this function is called in such case.
1160 		 *
1161 		 * If the reread partition isn't from release path, lo_refcnt
1162 		 * must be at least one and it can only become zero when the
1163 		 * current holder is released.
1164 		 */
1165 		err = bdev_disk_changed(lo->lo_disk, false);
1166 		if (err)
1167 			pr_warn("%s: partition scan of loop%d failed (rc=%d)\n",
1168 				__func__, lo->lo_number, err);
1169 		/* Device is gone, no point in returning error */
1170 	}
1171 
1172 	/*
1173 	 * lo->lo_state is set to Lo_unbound here after above partscan has
1174 	 * finished. There cannot be anybody else entering __loop_clr_fd() as
1175 	 * Lo_rundown state protects us from all the other places trying to
1176 	 * change the 'lo' device.
1177 	 */
1178 	lo->lo_flags = 0;
1179 	if (!part_shift)
1180 		set_bit(GD_SUPPRESS_PART_SCAN, &lo->lo_disk->state);
1181 	mutex_lock(&lo->lo_mutex);
1182 	WRITE_ONCE(lo->lo_state, Lo_unbound);
1183 	mutex_unlock(&lo->lo_mutex);
1184 
1185 	/*
1186 	 * Need not hold lo_mutex to fput backing file. Calling fput holding
1187 	 * lo_mutex triggers a circular lock dependency possibility warning as
1188 	 * fput can take open_mutex which is usually taken before lo_mutex.
1189 	 */
1190 	fput(filp);
1191 }
1192 
loop_clr_fd(struct loop_device * lo)1193 static int loop_clr_fd(struct loop_device *lo)
1194 {
1195 	int err;
1196 
1197 	/*
1198 	 * Since lo_ioctl() is called without locks held, it is possible that
1199 	 * loop_configure()/loop_change_fd() and loop_clr_fd() run in parallel.
1200 	 *
1201 	 * Therefore, use global lock when setting Lo_rundown state in order to
1202 	 * make sure that loop_validate_file() will fail if the "struct file"
1203 	 * which loop_configure()/loop_change_fd() found via fget() was this
1204 	 * loop device.
1205 	 */
1206 	err = loop_global_lock_killable(lo, true);
1207 	if (err)
1208 		return err;
1209 	if (lo->lo_state != Lo_bound) {
1210 		loop_global_unlock(lo, true);
1211 		return -ENXIO;
1212 	}
1213 	/*
1214 	 * Mark the device for removing the backing device on last close.
1215 	 * If we are the only opener, also switch the state to roundown here to
1216 	 * prevent new openers from coming in.
1217 	 */
1218 
1219 	lo->lo_flags |= LO_FLAGS_AUTOCLEAR;
1220 	if (disk_openers(lo->lo_disk) == 1)
1221 		WRITE_ONCE(lo->lo_state, Lo_rundown);
1222 	loop_global_unlock(lo, true);
1223 
1224 	return 0;
1225 }
1226 
1227 static int
loop_set_status(struct loop_device * lo,blk_mode_t mode,struct block_device * bdev,const struct loop_info64 * info)1228 loop_set_status(struct loop_device *lo, blk_mode_t mode,
1229 		struct block_device *bdev, const struct loop_info64 *info)
1230 {
1231 	int err;
1232 	bool partscan = false;
1233 	bool size_changed = false;
1234 	unsigned int memflags;
1235 
1236 	/*
1237 	 * If we don't hold exclusive handle for the device, upgrade to it
1238 	 * here to avoid changing device under exclusive owner.
1239 	 */
1240 	if (!(mode & BLK_OPEN_EXCL)) {
1241 		err = bd_prepare_to_claim(bdev, loop_set_status, NULL);
1242 		if (err)
1243 			goto out_reread_partitions;
1244 	}
1245 
1246 	err = mutex_lock_killable(&lo->lo_mutex);
1247 	if (err)
1248 		goto out_abort_claiming;
1249 
1250 	if (lo->lo_state != Lo_bound) {
1251 		err = -ENXIO;
1252 		goto out_unlock;
1253 	}
1254 
1255 	if (lo->lo_offset != info->lo_offset ||
1256 	    lo->lo_sizelimit != info->lo_sizelimit) {
1257 		size_changed = true;
1258 		sync_blockdev(lo->lo_device);
1259 		invalidate_bdev(lo->lo_device);
1260 	}
1261 
1262 	/* I/O needs to be drained before changing lo_offset or lo_sizelimit */
1263 	memflags = blk_mq_freeze_queue(lo->lo_queue);
1264 
1265 	err = loop_set_status_from_info(lo, info);
1266 	if (err)
1267 		goto out_unfreeze;
1268 
1269 	partscan = !(lo->lo_flags & LO_FLAGS_PARTSCAN) &&
1270 		(info->lo_flags & LO_FLAGS_PARTSCAN);
1271 
1272 	lo->lo_flags &= ~LOOP_SET_STATUS_CLEARABLE_FLAGS;
1273 	lo->lo_flags |= (info->lo_flags & LOOP_SET_STATUS_SETTABLE_FLAGS);
1274 
1275 	/* update the direct I/O flag if lo_offset changed */
1276 	loop_update_dio(lo);
1277 
1278 out_unfreeze:
1279 	blk_mq_unfreeze_queue(lo->lo_queue, memflags);
1280 	if (partscan)
1281 		clear_bit(GD_SUPPRESS_PART_SCAN, &lo->lo_disk->state);
1282 	if (!err && size_changed) {
1283 		loff_t new_size = lo_calculate_size(lo, lo->lo_backing_file);
1284 		loop_set_size(lo, new_size);
1285 	}
1286 out_unlock:
1287 	mutex_unlock(&lo->lo_mutex);
1288 out_abort_claiming:
1289 	if (!(mode & BLK_OPEN_EXCL))
1290 		bd_abort_claiming(bdev, loop_set_status);
1291 out_reread_partitions:
1292 	if (partscan)
1293 		loop_reread_partitions(lo);
1294 
1295 	return err;
1296 }
1297 
1298 static int
loop_get_status(struct loop_device * lo,struct loop_info64 * info)1299 loop_get_status(struct loop_device *lo, struct loop_info64 *info)
1300 {
1301 	struct path path;
1302 	struct kstat stat;
1303 	int ret;
1304 
1305 	ret = mutex_lock_killable(&lo->lo_mutex);
1306 	if (ret)
1307 		return ret;
1308 	if (lo->lo_state != Lo_bound) {
1309 		mutex_unlock(&lo->lo_mutex);
1310 		return -ENXIO;
1311 	}
1312 
1313 	memset(info, 0, sizeof(*info));
1314 	info->lo_number = lo->lo_number;
1315 	info->lo_offset = lo->lo_offset;
1316 	info->lo_sizelimit = lo->lo_sizelimit;
1317 	info->lo_flags = lo->lo_flags;
1318 	memcpy(info->lo_file_name, lo->lo_file_name, LO_NAME_SIZE);
1319 
1320 	/* Drop lo_mutex while we call into the filesystem. */
1321 	path = lo->lo_backing_file->f_path;
1322 	path_get(&path);
1323 	mutex_unlock(&lo->lo_mutex);
1324 	ret = vfs_getattr(&path, &stat, STATX_INO, AT_STATX_SYNC_AS_STAT);
1325 	if (!ret) {
1326 		info->lo_device = huge_encode_dev(stat.dev);
1327 		info->lo_inode = stat.ino;
1328 		info->lo_rdevice = huge_encode_dev(stat.rdev);
1329 	}
1330 	path_put(&path);
1331 	return ret;
1332 }
1333 
1334 static void
loop_info64_from_old(const struct loop_info * info,struct loop_info64 * info64)1335 loop_info64_from_old(const struct loop_info *info, struct loop_info64 *info64)
1336 {
1337 	memset(info64, 0, sizeof(*info64));
1338 	info64->lo_number = info->lo_number;
1339 	info64->lo_device = info->lo_device;
1340 	info64->lo_inode = info->lo_inode;
1341 	info64->lo_rdevice = info->lo_rdevice;
1342 	info64->lo_offset = info->lo_offset;
1343 	info64->lo_sizelimit = 0;
1344 	info64->lo_flags = info->lo_flags;
1345 	memcpy(info64->lo_file_name, info->lo_name, LO_NAME_SIZE);
1346 }
1347 
1348 static int
loop_info64_to_old(const struct loop_info64 * info64,struct loop_info * info)1349 loop_info64_to_old(const struct loop_info64 *info64, struct loop_info *info)
1350 {
1351 	memset(info, 0, sizeof(*info));
1352 	info->lo_number = info64->lo_number;
1353 	info->lo_device = info64->lo_device;
1354 	info->lo_inode = info64->lo_inode;
1355 	info->lo_rdevice = info64->lo_rdevice;
1356 	info->lo_offset = info64->lo_offset;
1357 	info->lo_flags = info64->lo_flags;
1358 	memcpy(info->lo_name, info64->lo_file_name, LO_NAME_SIZE);
1359 
1360 	/* error in case values were truncated */
1361 	if (info->lo_device != info64->lo_device ||
1362 	    info->lo_rdevice != info64->lo_rdevice ||
1363 	    info->lo_inode != info64->lo_inode ||
1364 	    info->lo_offset != info64->lo_offset)
1365 		return -EOVERFLOW;
1366 
1367 	return 0;
1368 }
1369 
1370 static int
loop_set_status_old(struct loop_device * lo,blk_mode_t mode,struct block_device * bdev,const struct loop_info __user * arg)1371 loop_set_status_old(struct loop_device *lo, blk_mode_t mode,
1372 		    struct block_device *bdev,
1373 		    const struct loop_info __user *arg)
1374 {
1375 	struct loop_info info;
1376 	struct loop_info64 info64;
1377 
1378 	if (copy_from_user(&info, arg, sizeof (struct loop_info)))
1379 		return -EFAULT;
1380 	loop_info64_from_old(&info, &info64);
1381 	return loop_set_status(lo, mode, bdev, &info64);
1382 }
1383 
1384 static int
loop_set_status64(struct loop_device * lo,blk_mode_t mode,struct block_device * bdev,const struct loop_info64 __user * arg)1385 loop_set_status64(struct loop_device *lo, blk_mode_t mode,
1386 		  struct block_device *bdev,
1387 		  const struct loop_info64 __user *arg)
1388 {
1389 	struct loop_info64 info64;
1390 
1391 	if (copy_from_user(&info64, arg, sizeof (struct loop_info64)))
1392 		return -EFAULT;
1393 	return loop_set_status(lo, mode, bdev, &info64);
1394 }
1395 
1396 static int
loop_get_status_old(struct loop_device * lo,struct loop_info __user * arg)1397 loop_get_status_old(struct loop_device *lo, struct loop_info __user *arg) {
1398 	struct loop_info info;
1399 	struct loop_info64 info64;
1400 	int err;
1401 
1402 	if (!arg)
1403 		return -EINVAL;
1404 	err = loop_get_status(lo, &info64);
1405 	if (!err)
1406 		err = loop_info64_to_old(&info64, &info);
1407 	if (!err && copy_to_user(arg, &info, sizeof(info)))
1408 		err = -EFAULT;
1409 
1410 	return err;
1411 }
1412 
1413 static int
loop_get_status64(struct loop_device * lo,struct loop_info64 __user * arg)1414 loop_get_status64(struct loop_device *lo, struct loop_info64 __user *arg) {
1415 	struct loop_info64 info64;
1416 	int err;
1417 
1418 	if (!arg)
1419 		return -EINVAL;
1420 	err = loop_get_status(lo, &info64);
1421 	if (!err && copy_to_user(arg, &info64, sizeof(info64)))
1422 		err = -EFAULT;
1423 
1424 	return err;
1425 }
1426 
loop_set_capacity(struct loop_device * lo)1427 static int loop_set_capacity(struct loop_device *lo)
1428 {
1429 	loff_t size;
1430 
1431 	if (unlikely(lo->lo_state != Lo_bound))
1432 		return -ENXIO;
1433 
1434 	size = lo_calculate_size(lo, lo->lo_backing_file);
1435 	loop_set_size(lo, size);
1436 
1437 	return 0;
1438 }
1439 
loop_set_dio(struct loop_device * lo,unsigned long arg)1440 static int loop_set_dio(struct loop_device *lo, unsigned long arg)
1441 {
1442 	bool use_dio = !!arg;
1443 	unsigned int memflags;
1444 
1445 	if (lo->lo_state != Lo_bound)
1446 		return -ENXIO;
1447 	if (use_dio == !!(lo->lo_flags & LO_FLAGS_DIRECT_IO))
1448 		return 0;
1449 
1450 	if (use_dio) {
1451 		if (!lo_can_use_dio(lo))
1452 			return -EINVAL;
1453 		/* flush dirty pages before starting to use direct I/O */
1454 		vfs_fsync(lo->lo_backing_file, 0);
1455 	}
1456 
1457 	memflags = blk_mq_freeze_queue(lo->lo_queue);
1458 	if (use_dio)
1459 		lo->lo_flags |= LO_FLAGS_DIRECT_IO;
1460 	else
1461 		lo->lo_flags &= ~LO_FLAGS_DIRECT_IO;
1462 	blk_mq_unfreeze_queue(lo->lo_queue, memflags);
1463 	return 0;
1464 }
1465 
loop_set_block_size(struct loop_device * lo,blk_mode_t mode,struct block_device * bdev,unsigned long arg)1466 static int loop_set_block_size(struct loop_device *lo, blk_mode_t mode,
1467 			       struct block_device *bdev, unsigned long arg)
1468 {
1469 	struct queue_limits lim;
1470 	unsigned int memflags;
1471 	int err = 0;
1472 
1473 	/*
1474 	 * If we don't hold exclusive handle for the device, upgrade to it
1475 	 * here to avoid changing device under exclusive owner.
1476 	 */
1477 	if (!(mode & BLK_OPEN_EXCL)) {
1478 		err = bd_prepare_to_claim(bdev, loop_set_block_size, NULL);
1479 		if (err)
1480 			return err;
1481 	}
1482 
1483 	err = mutex_lock_killable(&lo->lo_mutex);
1484 	if (err)
1485 		goto abort_claim;
1486 
1487 	if (lo->lo_state != Lo_bound) {
1488 		err = -ENXIO;
1489 		goto unlock;
1490 	}
1491 
1492 	if (lo->lo_queue->limits.logical_block_size == arg)
1493 		goto unlock;
1494 
1495 	sync_blockdev(lo->lo_device);
1496 	invalidate_bdev(lo->lo_device);
1497 
1498 	lim = queue_limits_start_update(lo->lo_queue);
1499 	loop_update_limits(lo, &lim, arg);
1500 
1501 	memflags = blk_mq_freeze_queue(lo->lo_queue);
1502 	err = queue_limits_commit_update(lo->lo_queue, &lim);
1503 	loop_update_dio(lo);
1504 	blk_mq_unfreeze_queue(lo->lo_queue, memflags);
1505 
1506 unlock:
1507 	mutex_unlock(&lo->lo_mutex);
1508 abort_claim:
1509 	if (!(mode & BLK_OPEN_EXCL))
1510 		bd_abort_claiming(bdev, loop_set_block_size);
1511 	return err;
1512 }
1513 
lo_simple_ioctl(struct loop_device * lo,unsigned int cmd,unsigned long arg)1514 static int lo_simple_ioctl(struct loop_device *lo, unsigned int cmd,
1515 			   unsigned long arg)
1516 {
1517 	int err;
1518 
1519 	err = mutex_lock_killable(&lo->lo_mutex);
1520 	if (err)
1521 		return err;
1522 	switch (cmd) {
1523 	case LOOP_SET_CAPACITY:
1524 		err = loop_set_capacity(lo);
1525 		break;
1526 	case LOOP_SET_DIRECT_IO:
1527 		err = loop_set_dio(lo, arg);
1528 		break;
1529 	default:
1530 		err = -EINVAL;
1531 	}
1532 	mutex_unlock(&lo->lo_mutex);
1533 	return err;
1534 }
1535 
lo_ioctl(struct block_device * bdev,blk_mode_t mode,unsigned int cmd,unsigned long arg)1536 static int lo_ioctl(struct block_device *bdev, blk_mode_t mode,
1537 	unsigned int cmd, unsigned long arg)
1538 {
1539 	struct loop_device *lo = bdev->bd_disk->private_data;
1540 	void __user *argp = (void __user *) arg;
1541 	int err;
1542 
1543 	switch (cmd) {
1544 	case LOOP_SET_FD: {
1545 		/*
1546 		 * Legacy case - pass in a zeroed out struct loop_config with
1547 		 * only the file descriptor set , which corresponds with the
1548 		 * default parameters we'd have used otherwise.
1549 		 */
1550 		struct loop_config config;
1551 
1552 		memset(&config, 0, sizeof(config));
1553 		config.fd = arg;
1554 
1555 		return loop_configure(lo, mode, bdev, &config);
1556 	}
1557 	case LOOP_CONFIGURE: {
1558 		struct loop_config config;
1559 
1560 		if (copy_from_user(&config, argp, sizeof(config)))
1561 			return -EFAULT;
1562 
1563 		return loop_configure(lo, mode, bdev, &config);
1564 	}
1565 	case LOOP_CHANGE_FD:
1566 		return loop_change_fd(lo, bdev, arg);
1567 	case LOOP_CLR_FD:
1568 		return loop_clr_fd(lo);
1569 	case LOOP_SET_STATUS:
1570 		err = -EPERM;
1571 		if ((mode & BLK_OPEN_WRITE) || capable(CAP_SYS_ADMIN))
1572 			err = loop_set_status_old(lo, mode, bdev, argp);
1573 		break;
1574 	case LOOP_GET_STATUS:
1575 		return loop_get_status_old(lo, argp);
1576 	case LOOP_SET_STATUS64:
1577 		err = -EPERM;
1578 		if ((mode & BLK_OPEN_WRITE) || capable(CAP_SYS_ADMIN))
1579 			err = loop_set_status64(lo, mode, bdev, argp);
1580 		break;
1581 	case LOOP_GET_STATUS64:
1582 		return loop_get_status64(lo, argp);
1583 	case LOOP_SET_BLOCK_SIZE:
1584 		if (!(mode & BLK_OPEN_WRITE) && !capable(CAP_SYS_ADMIN))
1585 			return -EPERM;
1586 		return loop_set_block_size(lo, mode, bdev, arg);
1587 	case LOOP_SET_CAPACITY:
1588 	case LOOP_SET_DIRECT_IO:
1589 		if (!(mode & BLK_OPEN_WRITE) && !capable(CAP_SYS_ADMIN))
1590 			return -EPERM;
1591 		fallthrough;
1592 	default:
1593 		err = lo_simple_ioctl(lo, cmd, arg);
1594 		break;
1595 	}
1596 
1597 	return err;
1598 }
1599 
1600 #ifdef CONFIG_COMPAT
1601 struct compat_loop_info {
1602 	compat_int_t	lo_number;      /* ioctl r/o */
1603 	compat_dev_t	lo_device;      /* ioctl r/o */
1604 	compat_ulong_t	lo_inode;       /* ioctl r/o */
1605 	compat_dev_t	lo_rdevice;     /* ioctl r/o */
1606 	compat_int_t	lo_offset;
1607 	compat_int_t	lo_encrypt_type;        /* obsolete, ignored */
1608 	compat_int_t	lo_encrypt_key_size;    /* ioctl w/o */
1609 	compat_int_t	lo_flags;       /* ioctl r/o */
1610 	char		lo_name[LO_NAME_SIZE];
1611 	unsigned char	lo_encrypt_key[LO_KEY_SIZE]; /* ioctl w/o */
1612 	compat_ulong_t	lo_init[2];
1613 	char		reserved[4];
1614 };
1615 
1616 /*
1617  * Transfer 32-bit compatibility structure in userspace to 64-bit loop info
1618  * - noinlined to reduce stack space usage in main part of driver
1619  */
1620 static noinline int
loop_info64_from_compat(const struct compat_loop_info __user * arg,struct loop_info64 * info64)1621 loop_info64_from_compat(const struct compat_loop_info __user *arg,
1622 			struct loop_info64 *info64)
1623 {
1624 	struct compat_loop_info info;
1625 
1626 	if (copy_from_user(&info, arg, sizeof(info)))
1627 		return -EFAULT;
1628 
1629 	memset(info64, 0, sizeof(*info64));
1630 	info64->lo_number = info.lo_number;
1631 	info64->lo_device = info.lo_device;
1632 	info64->lo_inode = info.lo_inode;
1633 	info64->lo_rdevice = info.lo_rdevice;
1634 	info64->lo_offset = info.lo_offset;
1635 	info64->lo_sizelimit = 0;
1636 	info64->lo_flags = info.lo_flags;
1637 	memcpy(info64->lo_file_name, info.lo_name, LO_NAME_SIZE);
1638 	return 0;
1639 }
1640 
1641 /*
1642  * Transfer 64-bit loop info to 32-bit compatibility structure in userspace
1643  * - noinlined to reduce stack space usage in main part of driver
1644  */
1645 static noinline int
loop_info64_to_compat(const struct loop_info64 * info64,struct compat_loop_info __user * arg)1646 loop_info64_to_compat(const struct loop_info64 *info64,
1647 		      struct compat_loop_info __user *arg)
1648 {
1649 	struct compat_loop_info info;
1650 
1651 	memset(&info, 0, sizeof(info));
1652 	info.lo_number = info64->lo_number;
1653 	info.lo_device = info64->lo_device;
1654 	info.lo_inode = info64->lo_inode;
1655 	info.lo_rdevice = info64->lo_rdevice;
1656 	info.lo_offset = info64->lo_offset;
1657 	info.lo_flags = info64->lo_flags;
1658 	memcpy(info.lo_name, info64->lo_file_name, LO_NAME_SIZE);
1659 
1660 	/* error in case values were truncated */
1661 	if (info.lo_device != info64->lo_device ||
1662 	    info.lo_rdevice != info64->lo_rdevice ||
1663 	    info.lo_inode != info64->lo_inode ||
1664 	    info.lo_offset != info64->lo_offset)
1665 		return -EOVERFLOW;
1666 
1667 	if (copy_to_user(arg, &info, sizeof(info)))
1668 		return -EFAULT;
1669 	return 0;
1670 }
1671 
1672 static int
loop_set_status_compat(struct loop_device * lo,blk_mode_t mode,struct block_device * bdev,const struct compat_loop_info __user * arg)1673 loop_set_status_compat(struct loop_device *lo, blk_mode_t mode,
1674 		    struct block_device *bdev,
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, mode, bdev, &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, mode, bdev,
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(sizeof(*lo), GFP_KERNEL);
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