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