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