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