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