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