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