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