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