• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  linux/drivers/block/loop.c
3  *
4  *  Written by Theodore Ts'o, 3/29/93
5  *
6  * Copyright 1993 by Theodore Ts'o.  Redistribution of this file is
7  * permitted under the GNU General Public License.
8  *
9  * DES encryption plus some minor changes by Werner Almesberger, 30-MAY-1993
10  * more DES encryption plus IDEA encryption by Nicholas J. Leon, June 20, 1996
11  *
12  * Modularized and updated for 1.1.16 kernel - Mitch Dsouza 28th May 1994
13  * Adapted for 1.3.59 kernel - Andries Brouwer, 1 Feb 1996
14  *
15  * Fixed do_loop_request() re-entrancy - Vincent.Renardias@waw.com Mar 20, 1997
16  *
17  * Added devfs support - Richard Gooch <rgooch@atnf.csiro.au> 16-Jan-1998
18  *
19  * Handle sparse backing files correctly - Kenn Humborg, Jun 28, 1998
20  *
21  * Loadable modules and other fixes by AK, 1998
22  *
23  * Make real block number available to downstream transfer functions, enables
24  * CBC (and relatives) mode encryption requiring unique IVs per data block.
25  * Reed H. Petty, rhp@draper.net
26  *
27  * Maximum number of loop devices now dynamic via max_loop module parameter.
28  * Russell Kroll <rkroll@exploits.org> 19990701
29  *
30  * Maximum number of loop devices when compiled-in now selectable by passing
31  * max_loop=<1-255> to the kernel on boot.
32  * Erik I. Bolsø, <eriki@himolde.no>, Oct 31, 1999
33  *
34  * Completely rewrite request handling to be make_request_fn style and
35  * non blocking, pushing work to a helper thread. Lots of fixes from
36  * Al Viro too.
37  * Jens Axboe <axboe@suse.de>, Nov 2000
38  *
39  * Support up to 256 loop devices
40  * Heinz Mauelshagen <mge@sistina.com>, Feb 2002
41  *
42  * Support for falling back on the write file operation when the address space
43  * operations write_begin is not available on the backing filesystem.
44  * Anton Altaparmakov, 16 Feb 2005
45  *
46  * Still To Fix:
47  * - Advisory locking is ignored here.
48  * - Should use an own CAP_* category instead of CAP_SYS_ADMIN
49  *
50  */
51 
52 #include <linux/module.h>
53 #include <linux/moduleparam.h>
54 #include <linux/sched.h>
55 #include <linux/fs.h>
56 #include <linux/file.h>
57 #include <linux/stat.h>
58 #include <linux/errno.h>
59 #include <linux/major.h>
60 #include <linux/wait.h>
61 #include <linux/blkdev.h>
62 #include <linux/blkpg.h>
63 #include <linux/init.h>
64 #include <linux/swap.h>
65 #include <linux/slab.h>
66 #include <linux/compat.h>
67 #include <linux/suspend.h>
68 #include <linux/freezer.h>
69 #include <linux/mutex.h>
70 #include <linux/writeback.h>
71 #include <linux/completion.h>
72 #include <linux/highmem.h>
73 #include <linux/kthread.h>
74 #include <linux/splice.h>
75 #include <linux/sysfs.h>
76 #include <linux/miscdevice.h>
77 #include <linux/falloc.h>
78 #include <linux/uio.h>
79 #include <linux/ioprio.h>
80 #include <linux/blk-cgroup.h>
81 
82 #include "loop.h"
83 
84 #include <linux/uaccess.h>
85 
86 static DEFINE_IDR(loop_index_idr);
87 static DEFINE_MUTEX(loop_ctl_mutex);
88 
89 static int max_part;
90 static int part_shift;
91 
transfer_xor(struct loop_device * lo,int cmd,struct page * raw_page,unsigned raw_off,struct page * loop_page,unsigned loop_off,int size,sector_t real_block)92 static int transfer_xor(struct loop_device *lo, int cmd,
93 			struct page *raw_page, unsigned raw_off,
94 			struct page *loop_page, unsigned loop_off,
95 			int size, sector_t real_block)
96 {
97 	char *raw_buf = kmap_atomic(raw_page) + raw_off;
98 	char *loop_buf = kmap_atomic(loop_page) + loop_off;
99 	char *in, *out, *key;
100 	int i, keysize;
101 
102 	if (cmd == READ) {
103 		in = raw_buf;
104 		out = loop_buf;
105 	} else {
106 		in = loop_buf;
107 		out = raw_buf;
108 	}
109 
110 	key = lo->lo_encrypt_key;
111 	keysize = lo->lo_encrypt_key_size;
112 	for (i = 0; i < size; i++)
113 		*out++ = *in++ ^ key[(i & 511) % keysize];
114 
115 	kunmap_atomic(loop_buf);
116 	kunmap_atomic(raw_buf);
117 	cond_resched();
118 	return 0;
119 }
120 
xor_init(struct loop_device * lo,const struct loop_info64 * info)121 static int xor_init(struct loop_device *lo, const struct loop_info64 *info)
122 {
123 	if (unlikely(info->lo_encrypt_key_size <= 0))
124 		return -EINVAL;
125 	return 0;
126 }
127 
128 static struct loop_func_table none_funcs = {
129 	.number = LO_CRYPT_NONE,
130 };
131 
132 static struct loop_func_table xor_funcs = {
133 	.number = LO_CRYPT_XOR,
134 	.transfer = transfer_xor,
135 	.init = xor_init
136 };
137 
138 /* xfer_funcs[0] is special - its release function is never called */
139 static struct loop_func_table *xfer_funcs[MAX_LO_CRYPT] = {
140 	&none_funcs,
141 	&xor_funcs
142 };
143 
get_size(loff_t offset,loff_t sizelimit,struct file * file)144 static loff_t get_size(loff_t offset, loff_t sizelimit, struct file *file)
145 {
146 	loff_t loopsize;
147 
148 	/* Compute loopsize in bytes */
149 	loopsize = i_size_read(file->f_mapping->host);
150 	if (offset > 0)
151 		loopsize -= offset;
152 	/* offset is beyond i_size, weird but possible */
153 	if (loopsize < 0)
154 		return 0;
155 
156 	if (sizelimit > 0 && sizelimit < loopsize)
157 		loopsize = sizelimit;
158 	/*
159 	 * Unfortunately, if we want to do I/O on the device,
160 	 * the number of 512-byte sectors has to fit into a sector_t.
161 	 */
162 	return loopsize >> 9;
163 }
164 
get_loop_size(struct loop_device * lo,struct file * file)165 static loff_t get_loop_size(struct loop_device *lo, struct file *file)
166 {
167 	return get_size(lo->lo_offset, lo->lo_sizelimit, file);
168 }
169 
__loop_update_dio(struct loop_device * lo,bool dio)170 static void __loop_update_dio(struct loop_device *lo, bool dio)
171 {
172 	struct file *file = lo->lo_backing_file;
173 	struct address_space *mapping = file->f_mapping;
174 	struct inode *inode = mapping->host;
175 	unsigned short sb_bsize = 0;
176 	unsigned dio_align = 0;
177 	bool use_dio;
178 
179 	if (inode->i_sb->s_bdev) {
180 		sb_bsize = bdev_logical_block_size(inode->i_sb->s_bdev);
181 		dio_align = sb_bsize - 1;
182 	}
183 
184 	/*
185 	 * We support direct I/O only if lo_offset is aligned with the
186 	 * logical I/O size of backing device, and the logical block
187 	 * size of loop is bigger than the backing device's and the loop
188 	 * needn't transform transfer.
189 	 *
190 	 * TODO: the above condition may be loosed in the future, and
191 	 * direct I/O may be switched runtime at that time because most
192 	 * of requests in sane applications should be PAGE_SIZE aligned
193 	 */
194 	if (dio) {
195 		if (queue_logical_block_size(lo->lo_queue) >= sb_bsize &&
196 				!(lo->lo_offset & dio_align) &&
197 				mapping->a_ops->direct_IO &&
198 				!lo->transfer)
199 			use_dio = true;
200 		else
201 			use_dio = false;
202 	} else {
203 		use_dio = false;
204 	}
205 
206 	if (lo->use_dio == use_dio)
207 		return;
208 
209 	/* flush dirty pages before changing direct IO */
210 	vfs_fsync(file, 0);
211 
212 	/*
213 	 * The flag of LO_FLAGS_DIRECT_IO is handled similarly with
214 	 * LO_FLAGS_READ_ONLY, both are set from kernel, and losetup
215 	 * will get updated by ioctl(LOOP_GET_STATUS)
216 	 */
217 	blk_mq_freeze_queue(lo->lo_queue);
218 	lo->use_dio = use_dio;
219 	if (use_dio) {
220 		blk_queue_flag_clear(QUEUE_FLAG_NOMERGES, lo->lo_queue);
221 		lo->lo_flags |= LO_FLAGS_DIRECT_IO;
222 	} else {
223 		blk_queue_flag_set(QUEUE_FLAG_NOMERGES, lo->lo_queue);
224 		lo->lo_flags &= ~LO_FLAGS_DIRECT_IO;
225 	}
226 	blk_mq_unfreeze_queue(lo->lo_queue);
227 }
228 
229 static int
figure_loop_size(struct loop_device * lo,loff_t offset,loff_t sizelimit)230 figure_loop_size(struct loop_device *lo, loff_t offset, loff_t sizelimit)
231 {
232 	loff_t size = get_size(offset, sizelimit, lo->lo_backing_file);
233 	sector_t x = (sector_t)size;
234 	struct block_device *bdev = lo->lo_device;
235 
236 	if (unlikely((loff_t)x != size))
237 		return -EFBIG;
238 	if (lo->lo_offset != offset)
239 		lo->lo_offset = offset;
240 	if (lo->lo_sizelimit != sizelimit)
241 		lo->lo_sizelimit = sizelimit;
242 	set_capacity(lo->lo_disk, x);
243 	bd_set_size(bdev, (loff_t)get_capacity(bdev->bd_disk) << 9);
244 	/* let user-space know about the new size */
245 	kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, KOBJ_CHANGE);
246 	return 0;
247 }
248 
249 static inline int
lo_do_transfer(struct loop_device * lo,int cmd,struct page * rpage,unsigned roffs,struct page * lpage,unsigned loffs,int size,sector_t rblock)250 lo_do_transfer(struct loop_device *lo, int cmd,
251 	       struct page *rpage, unsigned roffs,
252 	       struct page *lpage, unsigned loffs,
253 	       int size, sector_t rblock)
254 {
255 	int ret;
256 
257 	ret = lo->transfer(lo, cmd, rpage, roffs, lpage, loffs, size, rblock);
258 	if (likely(!ret))
259 		return 0;
260 
261 	printk_ratelimited(KERN_ERR
262 		"loop: Transfer error at byte offset %llu, length %i.\n",
263 		(unsigned long long)rblock << 9, size);
264 	return ret;
265 }
266 
lo_write_bvec(struct file * file,struct bio_vec * bvec,loff_t * ppos)267 static int lo_write_bvec(struct file *file, struct bio_vec *bvec, loff_t *ppos)
268 {
269 	struct iov_iter i;
270 	ssize_t bw;
271 
272 	iov_iter_bvec(&i, WRITE, bvec, 1, bvec->bv_len);
273 
274 	file_start_write(file);
275 	bw = vfs_iter_write(file, &i, ppos, 0);
276 	file_end_write(file);
277 
278 	if (likely(bw ==  bvec->bv_len))
279 		return 0;
280 
281 	printk_ratelimited(KERN_ERR
282 		"loop: Write error at byte offset %llu, length %i.\n",
283 		(unsigned long long)*ppos, bvec->bv_len);
284 	if (bw >= 0)
285 		bw = -EIO;
286 	return bw;
287 }
288 
lo_write_simple(struct loop_device * lo,struct request * rq,loff_t pos)289 static int lo_write_simple(struct loop_device *lo, struct request *rq,
290 		loff_t pos)
291 {
292 	struct bio_vec bvec;
293 	struct req_iterator iter;
294 	int ret = 0;
295 
296 	rq_for_each_segment(bvec, rq, iter) {
297 		ret = lo_write_bvec(lo->lo_backing_file, &bvec, &pos);
298 		if (ret < 0)
299 			break;
300 		cond_resched();
301 	}
302 
303 	return ret;
304 }
305 
306 /*
307  * This is the slow, transforming version that needs to double buffer the
308  * data as it cannot do the transformations in place without having direct
309  * access to the destination pages of the backing file.
310  */
lo_write_transfer(struct loop_device * lo,struct request * rq,loff_t pos)311 static int lo_write_transfer(struct loop_device *lo, struct request *rq,
312 		loff_t pos)
313 {
314 	struct bio_vec bvec, b;
315 	struct req_iterator iter;
316 	struct page *page;
317 	int ret = 0;
318 
319 	page = alloc_page(GFP_NOIO);
320 	if (unlikely(!page))
321 		return -ENOMEM;
322 
323 	rq_for_each_segment(bvec, rq, iter) {
324 		ret = lo_do_transfer(lo, WRITE, page, 0, bvec.bv_page,
325 			bvec.bv_offset, bvec.bv_len, pos >> 9);
326 		if (unlikely(ret))
327 			break;
328 
329 		b.bv_page = page;
330 		b.bv_offset = 0;
331 		b.bv_len = bvec.bv_len;
332 		ret = lo_write_bvec(lo->lo_backing_file, &b, &pos);
333 		if (ret < 0)
334 			break;
335 	}
336 
337 	__free_page(page);
338 	return ret;
339 }
340 
lo_read_simple(struct loop_device * lo,struct request * rq,loff_t pos)341 static int lo_read_simple(struct loop_device *lo, struct request *rq,
342 		loff_t pos)
343 {
344 	struct bio_vec bvec;
345 	struct req_iterator iter;
346 	struct iov_iter i;
347 	ssize_t len;
348 
349 	rq_for_each_segment(bvec, rq, iter) {
350 		iov_iter_bvec(&i, READ, &bvec, 1, bvec.bv_len);
351 		len = vfs_iter_read(lo->lo_backing_file, &i, &pos, 0);
352 		if (len < 0)
353 			return len;
354 
355 		flush_dcache_page(bvec.bv_page);
356 
357 		if (len != bvec.bv_len) {
358 			struct bio *bio;
359 
360 			__rq_for_each_bio(bio, rq)
361 				zero_fill_bio(bio);
362 			break;
363 		}
364 		cond_resched();
365 	}
366 
367 	return 0;
368 }
369 
lo_read_transfer(struct loop_device * lo,struct request * rq,loff_t pos)370 static int lo_read_transfer(struct loop_device *lo, struct request *rq,
371 		loff_t pos)
372 {
373 	struct bio_vec bvec, b;
374 	struct req_iterator iter;
375 	struct iov_iter i;
376 	struct page *page;
377 	ssize_t len;
378 	int ret = 0;
379 
380 	page = alloc_page(GFP_NOIO);
381 	if (unlikely(!page))
382 		return -ENOMEM;
383 
384 	rq_for_each_segment(bvec, rq, iter) {
385 		loff_t offset = pos;
386 
387 		b.bv_page = page;
388 		b.bv_offset = 0;
389 		b.bv_len = bvec.bv_len;
390 
391 		iov_iter_bvec(&i, READ, &b, 1, b.bv_len);
392 		len = vfs_iter_read(lo->lo_backing_file, &i, &pos, 0);
393 		if (len < 0) {
394 			ret = len;
395 			goto out_free_page;
396 		}
397 
398 		ret = lo_do_transfer(lo, READ, page, 0, bvec.bv_page,
399 			bvec.bv_offset, len, offset >> 9);
400 		if (ret)
401 			goto out_free_page;
402 
403 		flush_dcache_page(bvec.bv_page);
404 
405 		if (len != bvec.bv_len) {
406 			struct bio *bio;
407 
408 			__rq_for_each_bio(bio, rq)
409 				zero_fill_bio(bio);
410 			break;
411 		}
412 	}
413 
414 	ret = 0;
415 out_free_page:
416 	__free_page(page);
417 	return ret;
418 }
419 
lo_fallocate(struct loop_device * lo,struct request * rq,loff_t pos,int mode)420 static int lo_fallocate(struct loop_device *lo, struct request *rq, loff_t pos,
421 			int mode)
422 {
423 	/*
424 	 * We use fallocate to manipulate the space mappings used by the image
425 	 * a.k.a. discard/zerorange. However we do not support this if
426 	 * encryption is enabled, because it may give an attacker useful
427 	 * information.
428 	 */
429 	struct file *file = lo->lo_backing_file;
430 	int ret;
431 
432 	mode |= FALLOC_FL_KEEP_SIZE;
433 
434 	if ((!file->f_op->fallocate) || lo->lo_encrypt_key_size) {
435 		ret = -EOPNOTSUPP;
436 		goto out;
437 	}
438 
439 	ret = file->f_op->fallocate(file, mode, pos, blk_rq_bytes(rq));
440 	if (unlikely(ret && ret != -EINVAL && ret != -EOPNOTSUPP))
441 		ret = -EIO;
442  out:
443 	return ret;
444 }
445 
lo_req_flush(struct loop_device * lo,struct request * rq)446 static int lo_req_flush(struct loop_device *lo, struct request *rq)
447 {
448 	struct file *file = lo->lo_backing_file;
449 	int ret = vfs_fsync(file, 0);
450 	if (unlikely(ret && ret != -EINVAL))
451 		ret = -EIO;
452 
453 	return ret;
454 }
455 
lo_complete_rq(struct request * rq)456 static void lo_complete_rq(struct request *rq)
457 {
458 	struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
459 	blk_status_t ret = BLK_STS_OK;
460 
461 	if (!cmd->use_aio || cmd->ret < 0 || cmd->ret == blk_rq_bytes(rq) ||
462 	    req_op(rq) != REQ_OP_READ) {
463 		if (cmd->ret < 0)
464 			ret = BLK_STS_IOERR;
465 		goto end_io;
466 	}
467 
468 	/*
469 	 * Short READ - if we got some data, advance our request and
470 	 * retry it. If we got no data, end the rest with EIO.
471 	 */
472 	if (cmd->ret) {
473 		blk_update_request(rq, BLK_STS_OK, cmd->ret);
474 		cmd->ret = 0;
475 		blk_mq_requeue_request(rq, true);
476 	} else {
477 		if (cmd->use_aio) {
478 			struct bio *bio = rq->bio;
479 
480 			while (bio) {
481 				zero_fill_bio(bio);
482 				bio = bio->bi_next;
483 			}
484 		}
485 		ret = BLK_STS_IOERR;
486 end_io:
487 		blk_mq_end_request(rq, ret);
488 	}
489 }
490 
lo_rw_aio_do_completion(struct loop_cmd * cmd)491 static void lo_rw_aio_do_completion(struct loop_cmd *cmd)
492 {
493 	struct request *rq = blk_mq_rq_from_pdu(cmd);
494 
495 	if (!atomic_dec_and_test(&cmd->ref))
496 		return;
497 	kfree(cmd->bvec);
498 	cmd->bvec = NULL;
499 	blk_mq_complete_request(rq);
500 }
501 
lo_rw_aio_complete(struct kiocb * iocb,long ret,long ret2)502 static void lo_rw_aio_complete(struct kiocb *iocb, long ret, long ret2)
503 {
504 	struct loop_cmd *cmd = container_of(iocb, struct loop_cmd, iocb);
505 
506 	if (cmd->css)
507 		css_put(cmd->css);
508 	cmd->ret = ret;
509 	lo_rw_aio_do_completion(cmd);
510 }
511 
lo_rw_aio(struct loop_device * lo,struct loop_cmd * cmd,loff_t pos,bool rw)512 static int lo_rw_aio(struct loop_device *lo, struct loop_cmd *cmd,
513 		     loff_t pos, bool rw)
514 {
515 	struct iov_iter iter;
516 	struct req_iterator rq_iter;
517 	struct bio_vec *bvec;
518 	struct request *rq = blk_mq_rq_from_pdu(cmd);
519 	struct bio *bio = rq->bio;
520 	struct file *file = lo->lo_backing_file;
521 	struct bio_vec tmp;
522 	unsigned int offset;
523 	int nr_bvec = 0;
524 	int ret;
525 
526 	rq_for_each_bvec(tmp, rq, rq_iter)
527 		nr_bvec++;
528 
529 	if (rq->bio != rq->biotail) {
530 
531 		bvec = kmalloc_array(nr_bvec, sizeof(struct bio_vec),
532 				     GFP_NOIO);
533 		if (!bvec)
534 			return -EIO;
535 		cmd->bvec = bvec;
536 
537 		/*
538 		 * The bios of the request may be started from the middle of
539 		 * the 'bvec' because of bio splitting, so we can't directly
540 		 * copy bio->bi_iov_vec to new bvec. The rq_for_each_bvec
541 		 * API will take care of all details for us.
542 		 */
543 		rq_for_each_bvec(tmp, rq, rq_iter) {
544 			*bvec = tmp;
545 			bvec++;
546 		}
547 		bvec = cmd->bvec;
548 		offset = 0;
549 	} else {
550 		/*
551 		 * Same here, this bio may be started from the middle of the
552 		 * 'bvec' because of bio splitting, so offset from the bvec
553 		 * must be passed to iov iterator
554 		 */
555 		offset = bio->bi_iter.bi_bvec_done;
556 		bvec = __bvec_iter_bvec(bio->bi_io_vec, bio->bi_iter);
557 	}
558 	atomic_set(&cmd->ref, 2);
559 
560 	iov_iter_bvec(&iter, rw, bvec, nr_bvec, blk_rq_bytes(rq));
561 	iter.iov_offset = offset;
562 
563 	cmd->iocb.ki_pos = pos;
564 	cmd->iocb.ki_filp = file;
565 	cmd->iocb.ki_complete = lo_rw_aio_complete;
566 	cmd->iocb.ki_flags = IOCB_DIRECT;
567 	cmd->iocb.ki_ioprio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_NONE, 0);
568 	if (cmd->css)
569 		kthread_associate_blkcg(cmd->css);
570 
571 	if (rw == WRITE)
572 		ret = call_write_iter(file, &cmd->iocb, &iter);
573 	else
574 		ret = call_read_iter(file, &cmd->iocb, &iter);
575 
576 	lo_rw_aio_do_completion(cmd);
577 	kthread_associate_blkcg(NULL);
578 
579 	if (ret != -EIOCBQUEUED)
580 		cmd->iocb.ki_complete(&cmd->iocb, ret, 0);
581 	return 0;
582 }
583 
do_req_filebacked(struct loop_device * lo,struct request * rq)584 static int do_req_filebacked(struct loop_device *lo, struct request *rq)
585 {
586 	struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
587 	loff_t pos = ((loff_t) blk_rq_pos(rq) << 9) + lo->lo_offset;
588 
589 	/*
590 	 * lo_write_simple and lo_read_simple should have been covered
591 	 * by io submit style function like lo_rw_aio(), one blocker
592 	 * is that lo_read_simple() need to call flush_dcache_page after
593 	 * the page is written from kernel, and it isn't easy to handle
594 	 * this in io submit style function which submits all segments
595 	 * of the req at one time. And direct read IO doesn't need to
596 	 * run flush_dcache_page().
597 	 */
598 	switch (req_op(rq)) {
599 	case REQ_OP_FLUSH:
600 		return lo_req_flush(lo, rq);
601 	case REQ_OP_WRITE_ZEROES:
602 		/*
603 		 * If the caller doesn't want deallocation, call zeroout to
604 		 * write zeroes the range.  Otherwise, punch them out.
605 		 */
606 		return lo_fallocate(lo, rq, pos,
607 			(rq->cmd_flags & REQ_NOUNMAP) ?
608 				FALLOC_FL_ZERO_RANGE :
609 				FALLOC_FL_PUNCH_HOLE);
610 	case REQ_OP_DISCARD:
611 		return lo_fallocate(lo, rq, pos, FALLOC_FL_PUNCH_HOLE);
612 	case REQ_OP_WRITE:
613 		if (lo->transfer)
614 			return lo_write_transfer(lo, rq, pos);
615 		else if (cmd->use_aio)
616 			return lo_rw_aio(lo, cmd, pos, WRITE);
617 		else
618 			return lo_write_simple(lo, rq, pos);
619 	case REQ_OP_READ:
620 		if (lo->transfer)
621 			return lo_read_transfer(lo, rq, pos);
622 		else if (cmd->use_aio)
623 			return lo_rw_aio(lo, cmd, pos, READ);
624 		else
625 			return lo_read_simple(lo, rq, pos);
626 	default:
627 		WARN_ON_ONCE(1);
628 		return -EIO;
629 	}
630 }
631 
loop_update_dio(struct loop_device * lo)632 static inline void loop_update_dio(struct loop_device *lo)
633 {
634 	__loop_update_dio(lo, io_is_direct(lo->lo_backing_file) |
635 			lo->use_dio);
636 }
637 
loop_reread_partitions(struct loop_device * lo,struct block_device * bdev)638 static void loop_reread_partitions(struct loop_device *lo,
639 				   struct block_device *bdev)
640 {
641 	int rc;
642 
643 	rc = blkdev_reread_part(bdev);
644 	if (rc)
645 		pr_warn("%s: partition scan of loop%d (%s) failed (rc=%d)\n",
646 			__func__, lo->lo_number, lo->lo_file_name, rc);
647 }
648 
is_loop_device(struct file * file)649 static inline int is_loop_device(struct file *file)
650 {
651 	struct inode *i = file->f_mapping->host;
652 
653 	return i && S_ISBLK(i->i_mode) && MAJOR(i->i_rdev) == LOOP_MAJOR;
654 }
655 
loop_validate_file(struct file * file,struct block_device * bdev)656 static int loop_validate_file(struct file *file, struct block_device *bdev)
657 {
658 	struct inode	*inode = file->f_mapping->host;
659 	struct file	*f = file;
660 
661 	/* Avoid recursion */
662 	while (is_loop_device(f)) {
663 		struct loop_device *l;
664 
665 		if (f->f_mapping->host->i_bdev == bdev)
666 			return -EBADF;
667 
668 		l = f->f_mapping->host->i_bdev->bd_disk->private_data;
669 		if (l->lo_state != Lo_bound) {
670 			return -EINVAL;
671 		}
672 		f = l->lo_backing_file;
673 	}
674 	if (!S_ISREG(inode->i_mode) && !S_ISBLK(inode->i_mode))
675 		return -EINVAL;
676 	return 0;
677 }
678 
679 /*
680  * loop_change_fd switched the backing store of a loopback device to
681  * a new file. This is useful for operating system installers to free up
682  * the original file and in High Availability environments to switch to
683  * an alternative location for the content in case of server meltdown.
684  * This can only work if the loop device is used read-only, and if the
685  * new backing store is the same size and type as the old backing store.
686  */
loop_change_fd(struct loop_device * lo,struct block_device * bdev,unsigned int arg)687 static int loop_change_fd(struct loop_device *lo, struct block_device *bdev,
688 			  unsigned int arg)
689 {
690 	struct file	*file = NULL, *old_file;
691 	int		error;
692 	bool		partscan;
693 
694 	error = mutex_lock_killable(&loop_ctl_mutex);
695 	if (error)
696 		return error;
697 	error = -ENXIO;
698 	if (lo->lo_state != Lo_bound)
699 		goto out_err;
700 
701 	/* the loop device has to be read-only */
702 	error = -EINVAL;
703 	if (!(lo->lo_flags & LO_FLAGS_READ_ONLY))
704 		goto out_err;
705 
706 	error = -EBADF;
707 	file = fget(arg);
708 	if (!file)
709 		goto out_err;
710 
711 	error = loop_validate_file(file, bdev);
712 	if (error)
713 		goto out_err;
714 
715 	old_file = lo->lo_backing_file;
716 
717 	error = -EINVAL;
718 
719 	/* size of the new backing store needs to be the same */
720 	if (get_loop_size(lo, file) != get_loop_size(lo, old_file))
721 		goto out_err;
722 
723 	/* and ... switch */
724 	blk_mq_freeze_queue(lo->lo_queue);
725 	mapping_set_gfp_mask(old_file->f_mapping, lo->old_gfp_mask);
726 	lo->lo_backing_file = file;
727 	lo->old_gfp_mask = mapping_gfp_mask(file->f_mapping);
728 	mapping_set_gfp_mask(file->f_mapping,
729 			     lo->old_gfp_mask & ~(__GFP_IO|__GFP_FS));
730 	loop_update_dio(lo);
731 	blk_mq_unfreeze_queue(lo->lo_queue);
732 	partscan = lo->lo_flags & LO_FLAGS_PARTSCAN;
733 	mutex_unlock(&loop_ctl_mutex);
734 	/*
735 	 * We must drop file reference outside of loop_ctl_mutex as dropping
736 	 * the file ref can take bd_mutex which creates circular locking
737 	 * dependency.
738 	 */
739 	fput(old_file);
740 	if (partscan)
741 		loop_reread_partitions(lo, bdev);
742 	return 0;
743 
744 out_err:
745 	mutex_unlock(&loop_ctl_mutex);
746 	if (file)
747 		fput(file);
748 	return error;
749 }
750 
751 /* loop sysfs attributes */
752 
loop_attr_show(struct device * dev,char * page,ssize_t (* callback)(struct loop_device *,char *))753 static ssize_t loop_attr_show(struct device *dev, char *page,
754 			      ssize_t (*callback)(struct loop_device *, char *))
755 {
756 	struct gendisk *disk = dev_to_disk(dev);
757 	struct loop_device *lo = disk->private_data;
758 
759 	return callback(lo, page);
760 }
761 
762 #define LOOP_ATTR_RO(_name)						\
763 static ssize_t loop_attr_##_name##_show(struct loop_device *, char *);	\
764 static ssize_t loop_attr_do_show_##_name(struct device *d,		\
765 				struct device_attribute *attr, char *b)	\
766 {									\
767 	return loop_attr_show(d, b, loop_attr_##_name##_show);		\
768 }									\
769 static struct device_attribute loop_attr_##_name =			\
770 	__ATTR(_name, 0444, loop_attr_do_show_##_name, NULL);
771 
loop_attr_backing_file_show(struct loop_device * lo,char * buf)772 static ssize_t loop_attr_backing_file_show(struct loop_device *lo, char *buf)
773 {
774 	ssize_t ret;
775 	char *p = NULL;
776 
777 	spin_lock_irq(&lo->lo_lock);
778 	if (lo->lo_backing_file)
779 		p = file_path(lo->lo_backing_file, buf, PAGE_SIZE - 1);
780 	spin_unlock_irq(&lo->lo_lock);
781 
782 	if (IS_ERR_OR_NULL(p))
783 		ret = PTR_ERR(p);
784 	else {
785 		ret = strlen(p);
786 		memmove(buf, p, ret);
787 		buf[ret++] = '\n';
788 		buf[ret] = 0;
789 	}
790 
791 	return ret;
792 }
793 
loop_attr_offset_show(struct loop_device * lo,char * buf)794 static ssize_t loop_attr_offset_show(struct loop_device *lo, char *buf)
795 {
796 	return sprintf(buf, "%llu\n", (unsigned long long)lo->lo_offset);
797 }
798 
loop_attr_sizelimit_show(struct loop_device * lo,char * buf)799 static ssize_t loop_attr_sizelimit_show(struct loop_device *lo, char *buf)
800 {
801 	return sprintf(buf, "%llu\n", (unsigned long long)lo->lo_sizelimit);
802 }
803 
loop_attr_autoclear_show(struct loop_device * lo,char * buf)804 static ssize_t loop_attr_autoclear_show(struct loop_device *lo, char *buf)
805 {
806 	int autoclear = (lo->lo_flags & LO_FLAGS_AUTOCLEAR);
807 
808 	return sprintf(buf, "%s\n", autoclear ? "1" : "0");
809 }
810 
loop_attr_partscan_show(struct loop_device * lo,char * buf)811 static ssize_t loop_attr_partscan_show(struct loop_device *lo, char *buf)
812 {
813 	int partscan = (lo->lo_flags & LO_FLAGS_PARTSCAN);
814 
815 	return sprintf(buf, "%s\n", partscan ? "1" : "0");
816 }
817 
loop_attr_dio_show(struct loop_device * lo,char * buf)818 static ssize_t loop_attr_dio_show(struct loop_device *lo, char *buf)
819 {
820 	int dio = (lo->lo_flags & LO_FLAGS_DIRECT_IO);
821 
822 	return sprintf(buf, "%s\n", dio ? "1" : "0");
823 }
824 
825 LOOP_ATTR_RO(backing_file);
826 LOOP_ATTR_RO(offset);
827 LOOP_ATTR_RO(sizelimit);
828 LOOP_ATTR_RO(autoclear);
829 LOOP_ATTR_RO(partscan);
830 LOOP_ATTR_RO(dio);
831 
832 static struct attribute *loop_attrs[] = {
833 	&loop_attr_backing_file.attr,
834 	&loop_attr_offset.attr,
835 	&loop_attr_sizelimit.attr,
836 	&loop_attr_autoclear.attr,
837 	&loop_attr_partscan.attr,
838 	&loop_attr_dio.attr,
839 	NULL,
840 };
841 
842 static struct attribute_group loop_attribute_group = {
843 	.name = "loop",
844 	.attrs= loop_attrs,
845 };
846 
loop_sysfs_init(struct loop_device * lo)847 static void loop_sysfs_init(struct loop_device *lo)
848 {
849 	lo->sysfs_inited = !sysfs_create_group(&disk_to_dev(lo->lo_disk)->kobj,
850 						&loop_attribute_group);
851 }
852 
loop_sysfs_exit(struct loop_device * lo)853 static void loop_sysfs_exit(struct loop_device *lo)
854 {
855 	if (lo->sysfs_inited)
856 		sysfs_remove_group(&disk_to_dev(lo->lo_disk)->kobj,
857 				   &loop_attribute_group);
858 }
859 
loop_config_discard(struct loop_device * lo)860 static void loop_config_discard(struct loop_device *lo)
861 {
862 	struct file *file = lo->lo_backing_file;
863 	struct inode *inode = file->f_mapping->host;
864 	struct request_queue *q = lo->lo_queue;
865 
866 	/*
867 	 * We use punch hole to reclaim the free space used by the
868 	 * image a.k.a. discard. However we do not support discard if
869 	 * encryption is enabled, because it may give an attacker
870 	 * useful information.
871 	 */
872 	if ((!file->f_op->fallocate) ||
873 	    lo->lo_encrypt_key_size) {
874 		q->limits.discard_granularity = 0;
875 		q->limits.discard_alignment = 0;
876 		blk_queue_max_discard_sectors(q, 0);
877 		blk_queue_max_write_zeroes_sectors(q, 0);
878 		blk_queue_flag_clear(QUEUE_FLAG_DISCARD, q);
879 		return;
880 	}
881 
882 	q->limits.discard_granularity = inode->i_sb->s_blocksize;
883 	q->limits.discard_alignment = 0;
884 
885 	blk_queue_max_discard_sectors(q, UINT_MAX >> 9);
886 	blk_queue_max_write_zeroes_sectors(q, UINT_MAX >> 9);
887 	blk_queue_flag_set(QUEUE_FLAG_DISCARD, q);
888 }
889 
loop_unprepare_queue(struct loop_device * lo)890 static void loop_unprepare_queue(struct loop_device *lo)
891 {
892 	kthread_flush_worker(&lo->worker);
893 	kthread_stop(lo->worker_task);
894 }
895 
loop_kthread_worker_fn(void * worker_ptr)896 static int loop_kthread_worker_fn(void *worker_ptr)
897 {
898 	current->flags |= PF_LESS_THROTTLE | PF_MEMALLOC_NOIO;
899 	return kthread_worker_fn(worker_ptr);
900 }
901 
loop_prepare_queue(struct loop_device * lo)902 static int loop_prepare_queue(struct loop_device *lo)
903 {
904 	kthread_init_worker(&lo->worker);
905 	lo->worker_task = kthread_run(loop_kthread_worker_fn,
906 			&lo->worker, "loop%d", lo->lo_number);
907 	if (IS_ERR(lo->worker_task))
908 		return -ENOMEM;
909 	set_user_nice(lo->worker_task, MIN_NICE);
910 	return 0;
911 }
912 
loop_update_rotational(struct loop_device * lo)913 static void loop_update_rotational(struct loop_device *lo)
914 {
915 	struct file *file = lo->lo_backing_file;
916 	struct inode *file_inode = file->f_mapping->host;
917 	struct block_device *file_bdev = file_inode->i_sb->s_bdev;
918 	struct request_queue *q = lo->lo_queue;
919 	bool nonrot = true;
920 
921 	/* not all filesystems (e.g. tmpfs) have a sb->s_bdev */
922 	if (file_bdev)
923 		nonrot = blk_queue_nonrot(bdev_get_queue(file_bdev));
924 
925 	if (nonrot)
926 		blk_queue_flag_set(QUEUE_FLAG_NONROT, q);
927 	else
928 		blk_queue_flag_clear(QUEUE_FLAG_NONROT, q);
929 }
930 
loop_set_fd(struct loop_device * lo,fmode_t mode,struct block_device * bdev,unsigned int arg)931 static int loop_set_fd(struct loop_device *lo, fmode_t mode,
932 		       struct block_device *bdev, unsigned int arg)
933 {
934 	struct file	*file;
935 	struct inode	*inode;
936 	struct address_space *mapping;
937 	struct block_device *claimed_bdev = NULL;
938 	int		lo_flags = 0;
939 	int		error;
940 	loff_t		size;
941 	bool		partscan;
942 
943 	/* This is safe, since we have a reference from open(). */
944 	__module_get(THIS_MODULE);
945 
946 	error = -EBADF;
947 	file = fget(arg);
948 	if (!file)
949 		goto out;
950 
951 	/*
952 	 * If we don't hold exclusive handle for the device, upgrade to it
953 	 * here to avoid changing device under exclusive owner.
954 	 */
955 	if (!(mode & FMODE_EXCL)) {
956 		claimed_bdev = bd_start_claiming(bdev, loop_set_fd);
957 		if (IS_ERR(claimed_bdev)) {
958 			error = PTR_ERR(claimed_bdev);
959 			goto out_putf;
960 		}
961 	}
962 
963 	error = mutex_lock_killable(&loop_ctl_mutex);
964 	if (error)
965 		goto out_bdev;
966 
967 	error = -EBUSY;
968 	if (lo->lo_state != Lo_unbound)
969 		goto out_unlock;
970 
971 	error = loop_validate_file(file, bdev);
972 	if (error)
973 		goto out_unlock;
974 
975 	mapping = file->f_mapping;
976 	inode = mapping->host;
977 
978 	if (!(file->f_mode & FMODE_WRITE) || !(mode & FMODE_WRITE) ||
979 	    !file->f_op->write_iter)
980 		lo_flags |= LO_FLAGS_READ_ONLY;
981 
982 	error = -EFBIG;
983 	size = get_loop_size(lo, file);
984 	if ((loff_t)(sector_t)size != size)
985 		goto out_unlock;
986 	error = loop_prepare_queue(lo);
987 	if (error)
988 		goto out_unlock;
989 
990 	error = 0;
991 
992 	set_device_ro(bdev, (lo_flags & LO_FLAGS_READ_ONLY) != 0);
993 
994 	lo->use_dio = false;
995 	lo->lo_device = bdev;
996 	lo->lo_flags = lo_flags;
997 	lo->lo_backing_file = file;
998 	lo->transfer = NULL;
999 	lo->ioctl = NULL;
1000 	lo->lo_sizelimit = 0;
1001 	lo->old_gfp_mask = mapping_gfp_mask(mapping);
1002 	mapping_set_gfp_mask(mapping, lo->old_gfp_mask & ~(__GFP_IO|__GFP_FS));
1003 
1004 	if (!(lo_flags & LO_FLAGS_READ_ONLY) && file->f_op->fsync)
1005 		blk_queue_write_cache(lo->lo_queue, true, false);
1006 
1007 	if (io_is_direct(lo->lo_backing_file) && inode->i_sb->s_bdev) {
1008 		/* In case of direct I/O, match underlying block size */
1009 		unsigned short bsize = bdev_logical_block_size(
1010 			inode->i_sb->s_bdev);
1011 
1012 		blk_queue_logical_block_size(lo->lo_queue, bsize);
1013 		blk_queue_physical_block_size(lo->lo_queue, bsize);
1014 		blk_queue_io_min(lo->lo_queue, bsize);
1015 	}
1016 
1017 	loop_update_rotational(lo);
1018 	loop_update_dio(lo);
1019 	set_capacity(lo->lo_disk, size);
1020 	bd_set_size(bdev, size << 9);
1021 	loop_sysfs_init(lo);
1022 	/* let user-space know about the new size */
1023 	kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, KOBJ_CHANGE);
1024 
1025 	set_blocksize(bdev, S_ISBLK(inode->i_mode) ?
1026 		      block_size(inode->i_bdev) : PAGE_SIZE);
1027 
1028 	lo->lo_state = Lo_bound;
1029 	if (part_shift)
1030 		lo->lo_flags |= LO_FLAGS_PARTSCAN;
1031 	partscan = lo->lo_flags & LO_FLAGS_PARTSCAN;
1032 
1033 	/* Grab the block_device to prevent its destruction after we
1034 	 * put /dev/loopXX inode. Later in __loop_clr_fd() we bdput(bdev).
1035 	 */
1036 	bdgrab(bdev);
1037 	mutex_unlock(&loop_ctl_mutex);
1038 	if (partscan)
1039 		loop_reread_partitions(lo, bdev);
1040 	if (claimed_bdev)
1041 		bd_abort_claiming(bdev, claimed_bdev, loop_set_fd);
1042 	return 0;
1043 
1044 out_unlock:
1045 	mutex_unlock(&loop_ctl_mutex);
1046 out_bdev:
1047 	if (claimed_bdev)
1048 		bd_abort_claiming(bdev, claimed_bdev, loop_set_fd);
1049 out_putf:
1050 	fput(file);
1051 out:
1052 	/* This is safe: open() is still holding a reference. */
1053 	module_put(THIS_MODULE);
1054 	return error;
1055 }
1056 
1057 static int
loop_release_xfer(struct loop_device * lo)1058 loop_release_xfer(struct loop_device *lo)
1059 {
1060 	int err = 0;
1061 	struct loop_func_table *xfer = lo->lo_encryption;
1062 
1063 	if (xfer) {
1064 		if (xfer->release)
1065 			err = xfer->release(lo);
1066 		lo->transfer = NULL;
1067 		lo->lo_encryption = NULL;
1068 		module_put(xfer->owner);
1069 	}
1070 	return err;
1071 }
1072 
1073 static int
loop_init_xfer(struct loop_device * lo,struct loop_func_table * xfer,const struct loop_info64 * i)1074 loop_init_xfer(struct loop_device *lo, struct loop_func_table *xfer,
1075 	       const struct loop_info64 *i)
1076 {
1077 	int err = 0;
1078 
1079 	if (xfer) {
1080 		struct module *owner = xfer->owner;
1081 
1082 		if (!try_module_get(owner))
1083 			return -EINVAL;
1084 		if (xfer->init)
1085 			err = xfer->init(lo, i);
1086 		if (err)
1087 			module_put(owner);
1088 		else
1089 			lo->lo_encryption = xfer;
1090 	}
1091 	return err;
1092 }
1093 
__loop_clr_fd(struct loop_device * lo,bool release)1094 static int __loop_clr_fd(struct loop_device *lo, bool release)
1095 {
1096 	struct file *filp = NULL;
1097 	gfp_t gfp = lo->old_gfp_mask;
1098 	struct block_device *bdev = lo->lo_device;
1099 	int err = 0;
1100 	bool partscan = false;
1101 	int lo_number;
1102 
1103 	mutex_lock(&loop_ctl_mutex);
1104 	if (WARN_ON_ONCE(lo->lo_state != Lo_rundown)) {
1105 		err = -ENXIO;
1106 		goto out_unlock;
1107 	}
1108 
1109 	filp = lo->lo_backing_file;
1110 	if (filp == NULL) {
1111 		err = -EINVAL;
1112 		goto out_unlock;
1113 	}
1114 
1115 	/* freeze request queue during the transition */
1116 	blk_mq_freeze_queue(lo->lo_queue);
1117 
1118 	spin_lock_irq(&lo->lo_lock);
1119 	lo->lo_backing_file = NULL;
1120 	spin_unlock_irq(&lo->lo_lock);
1121 
1122 	loop_release_xfer(lo);
1123 	lo->transfer = NULL;
1124 	lo->ioctl = NULL;
1125 	lo->lo_device = NULL;
1126 	lo->lo_encryption = NULL;
1127 	lo->lo_offset = 0;
1128 	lo->lo_sizelimit = 0;
1129 	lo->lo_encrypt_key_size = 0;
1130 	memset(lo->lo_encrypt_key, 0, LO_KEY_SIZE);
1131 	memset(lo->lo_crypt_name, 0, LO_NAME_SIZE);
1132 	memset(lo->lo_file_name, 0, LO_NAME_SIZE);
1133 	blk_queue_logical_block_size(lo->lo_queue, 512);
1134 	blk_queue_physical_block_size(lo->lo_queue, 512);
1135 	blk_queue_io_min(lo->lo_queue, 512);
1136 	if (bdev) {
1137 		bdput(bdev);
1138 		invalidate_bdev(bdev);
1139 		bdev->bd_inode->i_mapping->wb_err = 0;
1140 	}
1141 	set_capacity(lo->lo_disk, 0);
1142 	loop_sysfs_exit(lo);
1143 	if (bdev) {
1144 		bd_set_size(bdev, 0);
1145 		/* let user-space know about this change */
1146 		kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, KOBJ_CHANGE);
1147 	}
1148 	mapping_set_gfp_mask(filp->f_mapping, gfp);
1149 	/* This is safe: open() is still holding a reference. */
1150 	module_put(THIS_MODULE);
1151 	blk_mq_unfreeze_queue(lo->lo_queue);
1152 
1153 	partscan = lo->lo_flags & LO_FLAGS_PARTSCAN && bdev;
1154 	lo_number = lo->lo_number;
1155 	loop_unprepare_queue(lo);
1156 out_unlock:
1157 	mutex_unlock(&loop_ctl_mutex);
1158 	if (partscan) {
1159 		/*
1160 		 * bd_mutex has been held already in release path, so don't
1161 		 * acquire it if this function is called in such case.
1162 		 *
1163 		 * If the reread partition isn't from release path, lo_refcnt
1164 		 * must be at least one and it can only become zero when the
1165 		 * current holder is released.
1166 		 */
1167 		if (release)
1168 			err = __blkdev_reread_part(bdev);
1169 		else
1170 			err = blkdev_reread_part(bdev);
1171 		if (err)
1172 			pr_warn("%s: partition scan of loop%d failed (rc=%d)\n",
1173 				__func__, lo_number, err);
1174 		/* Device is gone, no point in returning error */
1175 		err = 0;
1176 	}
1177 
1178 	/*
1179 	 * lo->lo_state is set to Lo_unbound here after above partscan has
1180 	 * finished.
1181 	 *
1182 	 * There cannot be anybody else entering __loop_clr_fd() as
1183 	 * lo->lo_backing_file is already cleared and Lo_rundown state
1184 	 * protects us from all the other places trying to change the 'lo'
1185 	 * device.
1186 	 */
1187 	mutex_lock(&loop_ctl_mutex);
1188 	lo->lo_flags = 0;
1189 	if (!part_shift)
1190 		lo->lo_disk->flags |= GENHD_FL_NO_PART_SCAN;
1191 	lo->lo_state = Lo_unbound;
1192 	mutex_unlock(&loop_ctl_mutex);
1193 
1194 	/*
1195 	 * Need not hold loop_ctl_mutex to fput backing file.
1196 	 * Calling fput holding loop_ctl_mutex triggers a circular
1197 	 * lock dependency possibility warning as fput can take
1198 	 * bd_mutex which is usually taken before loop_ctl_mutex.
1199 	 */
1200 	if (filp)
1201 		fput(filp);
1202 	return err;
1203 }
1204 
loop_clr_fd(struct loop_device * lo)1205 static int loop_clr_fd(struct loop_device *lo)
1206 {
1207 	int err;
1208 
1209 	err = mutex_lock_killable(&loop_ctl_mutex);
1210 	if (err)
1211 		return err;
1212 	if (lo->lo_state != Lo_bound) {
1213 		mutex_unlock(&loop_ctl_mutex);
1214 		return -ENXIO;
1215 	}
1216 	/*
1217 	 * If we've explicitly asked to tear down the loop device,
1218 	 * and it has an elevated reference count, set it for auto-teardown when
1219 	 * the last reference goes away. This stops $!~#$@ udev from
1220 	 * preventing teardown because it decided that it needs to run blkid on
1221 	 * the loopback device whenever they appear. xfstests is notorious for
1222 	 * failing tests because blkid via udev races with a losetup
1223 	 * <dev>/do something like mkfs/losetup -d <dev> causing the losetup -d
1224 	 * command to fail with EBUSY.
1225 	 */
1226 	if (atomic_read(&lo->lo_refcnt) > 1) {
1227 		lo->lo_flags |= LO_FLAGS_AUTOCLEAR;
1228 		mutex_unlock(&loop_ctl_mutex);
1229 		return 0;
1230 	}
1231 	lo->lo_state = Lo_rundown;
1232 	mutex_unlock(&loop_ctl_mutex);
1233 
1234 	return __loop_clr_fd(lo, false);
1235 }
1236 
1237 static int
loop_set_status(struct loop_device * lo,const struct loop_info64 * info)1238 loop_set_status(struct loop_device *lo, const struct loop_info64 *info)
1239 {
1240 	int err;
1241 	struct loop_func_table *xfer;
1242 	kuid_t uid = current_uid();
1243 	struct block_device *bdev;
1244 	bool partscan = false;
1245 
1246 	err = mutex_lock_killable(&loop_ctl_mutex);
1247 	if (err)
1248 		return err;
1249 	if (lo->lo_encrypt_key_size &&
1250 	    !uid_eq(lo->lo_key_owner, uid) &&
1251 	    !capable(CAP_SYS_ADMIN)) {
1252 		err = -EPERM;
1253 		goto out_unlock;
1254 	}
1255 	if (lo->lo_state != Lo_bound) {
1256 		err = -ENXIO;
1257 		goto out_unlock;
1258 	}
1259 	if ((unsigned int) info->lo_encrypt_key_size > LO_KEY_SIZE) {
1260 		err = -EINVAL;
1261 		goto out_unlock;
1262 	}
1263 
1264 	if (lo->lo_offset != info->lo_offset ||
1265 	    lo->lo_sizelimit != info->lo_sizelimit) {
1266 		sync_blockdev(lo->lo_device);
1267 		kill_bdev(lo->lo_device);
1268 	}
1269 
1270 	/* I/O need to be drained during transfer transition */
1271 	blk_mq_freeze_queue(lo->lo_queue);
1272 
1273 	err = loop_release_xfer(lo);
1274 	if (err)
1275 		goto out_unfreeze;
1276 
1277 	if (info->lo_encrypt_type) {
1278 		unsigned int type = info->lo_encrypt_type;
1279 
1280 		if (type >= MAX_LO_CRYPT) {
1281 			err = -EINVAL;
1282 			goto out_unfreeze;
1283 		}
1284 		xfer = xfer_funcs[type];
1285 		if (xfer == NULL) {
1286 			err = -EINVAL;
1287 			goto out_unfreeze;
1288 		}
1289 	} else
1290 		xfer = NULL;
1291 
1292 	err = loop_init_xfer(lo, xfer, info);
1293 	if (err)
1294 		goto out_unfreeze;
1295 
1296 	if (lo->lo_offset != info->lo_offset ||
1297 	    lo->lo_sizelimit != info->lo_sizelimit) {
1298 		/* kill_bdev should have truncated all the pages */
1299 		if (lo->lo_device->bd_inode->i_mapping->nrpages) {
1300 			err = -EAGAIN;
1301 			pr_warn("%s: loop%d (%s) has still dirty pages (nrpages=%lu)\n",
1302 				__func__, lo->lo_number, lo->lo_file_name,
1303 				lo->lo_device->bd_inode->i_mapping->nrpages);
1304 			goto out_unfreeze;
1305 		}
1306 		if (figure_loop_size(lo, info->lo_offset, info->lo_sizelimit)) {
1307 			err = -EFBIG;
1308 			goto out_unfreeze;
1309 		}
1310 	}
1311 
1312 	loop_config_discard(lo);
1313 
1314 	memcpy(lo->lo_file_name, info->lo_file_name, LO_NAME_SIZE);
1315 	memcpy(lo->lo_crypt_name, info->lo_crypt_name, LO_NAME_SIZE);
1316 	lo->lo_file_name[LO_NAME_SIZE-1] = 0;
1317 	lo->lo_crypt_name[LO_NAME_SIZE-1] = 0;
1318 
1319 	if (!xfer)
1320 		xfer = &none_funcs;
1321 	lo->transfer = xfer->transfer;
1322 	lo->ioctl = xfer->ioctl;
1323 
1324 	if ((lo->lo_flags & LO_FLAGS_AUTOCLEAR) !=
1325 	     (info->lo_flags & LO_FLAGS_AUTOCLEAR))
1326 		lo->lo_flags ^= LO_FLAGS_AUTOCLEAR;
1327 
1328 	lo->lo_encrypt_key_size = info->lo_encrypt_key_size;
1329 	lo->lo_init[0] = info->lo_init[0];
1330 	lo->lo_init[1] = info->lo_init[1];
1331 	if (info->lo_encrypt_key_size) {
1332 		memcpy(lo->lo_encrypt_key, info->lo_encrypt_key,
1333 		       info->lo_encrypt_key_size);
1334 		lo->lo_key_owner = uid;
1335 	}
1336 
1337 	/* update dio if lo_offset or transfer is changed */
1338 	__loop_update_dio(lo, lo->use_dio);
1339 
1340 out_unfreeze:
1341 	blk_mq_unfreeze_queue(lo->lo_queue);
1342 
1343 	if (!err && (info->lo_flags & LO_FLAGS_PARTSCAN) &&
1344 	     !(lo->lo_flags & LO_FLAGS_PARTSCAN)) {
1345 		lo->lo_flags |= LO_FLAGS_PARTSCAN;
1346 		lo->lo_disk->flags &= ~GENHD_FL_NO_PART_SCAN;
1347 		bdev = lo->lo_device;
1348 		partscan = true;
1349 	}
1350 out_unlock:
1351 	mutex_unlock(&loop_ctl_mutex);
1352 	if (partscan)
1353 		loop_reread_partitions(lo, bdev);
1354 
1355 	return err;
1356 }
1357 
1358 static int
loop_get_status(struct loop_device * lo,struct loop_info64 * info)1359 loop_get_status(struct loop_device *lo, struct loop_info64 *info)
1360 {
1361 	struct path path;
1362 	struct kstat stat;
1363 	int ret;
1364 
1365 	ret = mutex_lock_killable(&loop_ctl_mutex);
1366 	if (ret)
1367 		return ret;
1368 	if (lo->lo_state != Lo_bound) {
1369 		mutex_unlock(&loop_ctl_mutex);
1370 		return -ENXIO;
1371 	}
1372 
1373 	memset(info, 0, sizeof(*info));
1374 	info->lo_number = lo->lo_number;
1375 	info->lo_offset = lo->lo_offset;
1376 	info->lo_sizelimit = lo->lo_sizelimit;
1377 	info->lo_flags = lo->lo_flags;
1378 	memcpy(info->lo_file_name, lo->lo_file_name, LO_NAME_SIZE);
1379 	memcpy(info->lo_crypt_name, lo->lo_crypt_name, LO_NAME_SIZE);
1380 	info->lo_encrypt_type =
1381 		lo->lo_encryption ? lo->lo_encryption->number : 0;
1382 	if (lo->lo_encrypt_key_size && capable(CAP_SYS_ADMIN)) {
1383 		info->lo_encrypt_key_size = lo->lo_encrypt_key_size;
1384 		memcpy(info->lo_encrypt_key, lo->lo_encrypt_key,
1385 		       lo->lo_encrypt_key_size);
1386 	}
1387 
1388 	/* Drop loop_ctl_mutex while we call into the filesystem. */
1389 	path = lo->lo_backing_file->f_path;
1390 	path_get(&path);
1391 	mutex_unlock(&loop_ctl_mutex);
1392 	ret = vfs_getattr(&path, &stat, STATX_INO, AT_STATX_SYNC_AS_STAT);
1393 	if (!ret) {
1394 		info->lo_device = huge_encode_dev(stat.dev);
1395 		info->lo_inode = stat.ino;
1396 		info->lo_rdevice = huge_encode_dev(stat.rdev);
1397 	}
1398 	path_put(&path);
1399 	return ret;
1400 }
1401 
1402 static void
loop_info64_from_old(const struct loop_info * info,struct loop_info64 * info64)1403 loop_info64_from_old(const struct loop_info *info, struct loop_info64 *info64)
1404 {
1405 	memset(info64, 0, sizeof(*info64));
1406 	info64->lo_number = info->lo_number;
1407 	info64->lo_device = info->lo_device;
1408 	info64->lo_inode = info->lo_inode;
1409 	info64->lo_rdevice = info->lo_rdevice;
1410 	info64->lo_offset = info->lo_offset;
1411 	info64->lo_sizelimit = 0;
1412 	info64->lo_encrypt_type = info->lo_encrypt_type;
1413 	info64->lo_encrypt_key_size = info->lo_encrypt_key_size;
1414 	info64->lo_flags = info->lo_flags;
1415 	info64->lo_init[0] = info->lo_init[0];
1416 	info64->lo_init[1] = info->lo_init[1];
1417 	if (info->lo_encrypt_type == LO_CRYPT_CRYPTOAPI)
1418 		memcpy(info64->lo_crypt_name, info->lo_name, LO_NAME_SIZE);
1419 	else
1420 		memcpy(info64->lo_file_name, info->lo_name, LO_NAME_SIZE);
1421 	memcpy(info64->lo_encrypt_key, info->lo_encrypt_key, LO_KEY_SIZE);
1422 }
1423 
1424 static int
loop_info64_to_old(const struct loop_info64 * info64,struct loop_info * info)1425 loop_info64_to_old(const struct loop_info64 *info64, struct loop_info *info)
1426 {
1427 	memset(info, 0, sizeof(*info));
1428 	info->lo_number = info64->lo_number;
1429 	info->lo_device = info64->lo_device;
1430 	info->lo_inode = info64->lo_inode;
1431 	info->lo_rdevice = info64->lo_rdevice;
1432 	info->lo_offset = info64->lo_offset;
1433 	info->lo_encrypt_type = info64->lo_encrypt_type;
1434 	info->lo_encrypt_key_size = info64->lo_encrypt_key_size;
1435 	info->lo_flags = info64->lo_flags;
1436 	info->lo_init[0] = info64->lo_init[0];
1437 	info->lo_init[1] = info64->lo_init[1];
1438 	if (info->lo_encrypt_type == LO_CRYPT_CRYPTOAPI)
1439 		memcpy(info->lo_name, info64->lo_crypt_name, LO_NAME_SIZE);
1440 	else
1441 		memcpy(info->lo_name, info64->lo_file_name, LO_NAME_SIZE);
1442 	memcpy(info->lo_encrypt_key, info64->lo_encrypt_key, LO_KEY_SIZE);
1443 
1444 	/* error in case values were truncated */
1445 	if (info->lo_device != info64->lo_device ||
1446 	    info->lo_rdevice != info64->lo_rdevice ||
1447 	    info->lo_inode != info64->lo_inode ||
1448 	    info->lo_offset != info64->lo_offset)
1449 		return -EOVERFLOW;
1450 
1451 	return 0;
1452 }
1453 
1454 static int
loop_set_status_old(struct loop_device * lo,const struct loop_info __user * arg)1455 loop_set_status_old(struct loop_device *lo, const struct loop_info __user *arg)
1456 {
1457 	struct loop_info info;
1458 	struct loop_info64 info64;
1459 
1460 	if (copy_from_user(&info, arg, sizeof (struct loop_info)))
1461 		return -EFAULT;
1462 	loop_info64_from_old(&info, &info64);
1463 	return loop_set_status(lo, &info64);
1464 }
1465 
1466 static int
loop_set_status64(struct loop_device * lo,const struct loop_info64 __user * arg)1467 loop_set_status64(struct loop_device *lo, const struct loop_info64 __user *arg)
1468 {
1469 	struct loop_info64 info64;
1470 
1471 	if (copy_from_user(&info64, arg, sizeof (struct loop_info64)))
1472 		return -EFAULT;
1473 	return loop_set_status(lo, &info64);
1474 }
1475 
1476 static int
loop_get_status_old(struct loop_device * lo,struct loop_info __user * arg)1477 loop_get_status_old(struct loop_device *lo, struct loop_info __user *arg) {
1478 	struct loop_info info;
1479 	struct loop_info64 info64;
1480 	int err;
1481 
1482 	if (!arg)
1483 		return -EINVAL;
1484 	err = loop_get_status(lo, &info64);
1485 	if (!err)
1486 		err = loop_info64_to_old(&info64, &info);
1487 	if (!err && copy_to_user(arg, &info, sizeof(info)))
1488 		err = -EFAULT;
1489 
1490 	return err;
1491 }
1492 
1493 static int
loop_get_status64(struct loop_device * lo,struct loop_info64 __user * arg)1494 loop_get_status64(struct loop_device *lo, struct loop_info64 __user *arg) {
1495 	struct loop_info64 info64;
1496 	int err;
1497 
1498 	if (!arg)
1499 		return -EINVAL;
1500 	err = loop_get_status(lo, &info64);
1501 	if (!err && copy_to_user(arg, &info64, sizeof(info64)))
1502 		err = -EFAULT;
1503 
1504 	return err;
1505 }
1506 
loop_set_capacity(struct loop_device * lo)1507 static int loop_set_capacity(struct loop_device *lo)
1508 {
1509 	if (unlikely(lo->lo_state != Lo_bound))
1510 		return -ENXIO;
1511 
1512 	return figure_loop_size(lo, lo->lo_offset, lo->lo_sizelimit);
1513 }
1514 
loop_set_dio(struct loop_device * lo,unsigned long arg)1515 static int loop_set_dio(struct loop_device *lo, unsigned long arg)
1516 {
1517 	int error = -ENXIO;
1518 	if (lo->lo_state != Lo_bound)
1519 		goto out;
1520 
1521 	__loop_update_dio(lo, !!arg);
1522 	if (lo->use_dio == !!arg)
1523 		return 0;
1524 	error = -EINVAL;
1525  out:
1526 	return error;
1527 }
1528 
loop_set_block_size(struct loop_device * lo,unsigned long arg)1529 static int loop_set_block_size(struct loop_device *lo, unsigned long arg)
1530 {
1531 	int err = 0;
1532 
1533 	if (lo->lo_state != Lo_bound)
1534 		return -ENXIO;
1535 
1536 	if (arg < 512 || arg > PAGE_SIZE || !is_power_of_2(arg))
1537 		return -EINVAL;
1538 
1539 	if (lo->lo_queue->limits.logical_block_size != arg) {
1540 		sync_blockdev(lo->lo_device);
1541 		kill_bdev(lo->lo_device);
1542 	}
1543 
1544 	blk_mq_freeze_queue(lo->lo_queue);
1545 
1546 	/* kill_bdev should have truncated all the pages */
1547 	if (lo->lo_queue->limits.logical_block_size != arg &&
1548 			lo->lo_device->bd_inode->i_mapping->nrpages) {
1549 		err = -EAGAIN;
1550 		pr_warn("%s: loop%d (%s) has still dirty pages (nrpages=%lu)\n",
1551 			__func__, lo->lo_number, lo->lo_file_name,
1552 			lo->lo_device->bd_inode->i_mapping->nrpages);
1553 		goto out_unfreeze;
1554 	}
1555 
1556 	blk_queue_logical_block_size(lo->lo_queue, arg);
1557 	blk_queue_physical_block_size(lo->lo_queue, arg);
1558 	blk_queue_io_min(lo->lo_queue, arg);
1559 	loop_update_dio(lo);
1560 out_unfreeze:
1561 	blk_mq_unfreeze_queue(lo->lo_queue);
1562 
1563 	return err;
1564 }
1565 
lo_simple_ioctl(struct loop_device * lo,unsigned int cmd,unsigned long arg)1566 static int lo_simple_ioctl(struct loop_device *lo, unsigned int cmd,
1567 			   unsigned long arg)
1568 {
1569 	int err;
1570 
1571 	err = mutex_lock_killable(&loop_ctl_mutex);
1572 	if (err)
1573 		return err;
1574 	switch (cmd) {
1575 	case LOOP_SET_CAPACITY:
1576 		err = loop_set_capacity(lo);
1577 		break;
1578 	case LOOP_SET_DIRECT_IO:
1579 		err = loop_set_dio(lo, arg);
1580 		break;
1581 	case LOOP_SET_BLOCK_SIZE:
1582 		err = loop_set_block_size(lo, arg);
1583 		break;
1584 	default:
1585 		err = lo->ioctl ? lo->ioctl(lo, cmd, arg) : -EINVAL;
1586 	}
1587 	mutex_unlock(&loop_ctl_mutex);
1588 	return err;
1589 }
1590 
lo_ioctl(struct block_device * bdev,fmode_t mode,unsigned int cmd,unsigned long arg)1591 static int lo_ioctl(struct block_device *bdev, fmode_t mode,
1592 	unsigned int cmd, unsigned long arg)
1593 {
1594 	struct loop_device *lo = bdev->bd_disk->private_data;
1595 	int err;
1596 
1597 	switch (cmd) {
1598 	case LOOP_SET_FD:
1599 		return loop_set_fd(lo, mode, bdev, arg);
1600 	case LOOP_CHANGE_FD:
1601 		return loop_change_fd(lo, bdev, arg);
1602 	case LOOP_CLR_FD:
1603 		return loop_clr_fd(lo);
1604 	case LOOP_SET_STATUS:
1605 		err = -EPERM;
1606 		if ((mode & FMODE_WRITE) || capable(CAP_SYS_ADMIN)) {
1607 			err = loop_set_status_old(lo,
1608 					(struct loop_info __user *)arg);
1609 		}
1610 		break;
1611 	case LOOP_GET_STATUS:
1612 		return loop_get_status_old(lo, (struct loop_info __user *) arg);
1613 	case LOOP_SET_STATUS64:
1614 		err = -EPERM;
1615 		if ((mode & FMODE_WRITE) || capable(CAP_SYS_ADMIN)) {
1616 			err = loop_set_status64(lo,
1617 					(struct loop_info64 __user *) arg);
1618 		}
1619 		break;
1620 	case LOOP_GET_STATUS64:
1621 		return loop_get_status64(lo, (struct loop_info64 __user *) arg);
1622 	case LOOP_SET_CAPACITY:
1623 	case LOOP_SET_DIRECT_IO:
1624 	case LOOP_SET_BLOCK_SIZE:
1625 		if (!(mode & FMODE_WRITE) && !capable(CAP_SYS_ADMIN))
1626 			return -EPERM;
1627 		/* Fall through */
1628 	default:
1629 		err = lo_simple_ioctl(lo, cmd, arg);
1630 		break;
1631 	}
1632 
1633 	return err;
1634 }
1635 
1636 #ifdef CONFIG_COMPAT
1637 struct compat_loop_info {
1638 	compat_int_t	lo_number;      /* ioctl r/o */
1639 	compat_dev_t	lo_device;      /* ioctl r/o */
1640 	compat_ulong_t	lo_inode;       /* ioctl r/o */
1641 	compat_dev_t	lo_rdevice;     /* ioctl r/o */
1642 	compat_int_t	lo_offset;
1643 	compat_int_t	lo_encrypt_type;
1644 	compat_int_t	lo_encrypt_key_size;    /* ioctl w/o */
1645 	compat_int_t	lo_flags;       /* ioctl r/o */
1646 	char		lo_name[LO_NAME_SIZE];
1647 	unsigned char	lo_encrypt_key[LO_KEY_SIZE]; /* ioctl w/o */
1648 	compat_ulong_t	lo_init[2];
1649 	char		reserved[4];
1650 };
1651 
1652 /*
1653  * Transfer 32-bit compatibility structure in userspace to 64-bit loop info
1654  * - noinlined to reduce stack space usage in main part of driver
1655  */
1656 static noinline int
loop_info64_from_compat(const struct compat_loop_info __user * arg,struct loop_info64 * info64)1657 loop_info64_from_compat(const struct compat_loop_info __user *arg,
1658 			struct loop_info64 *info64)
1659 {
1660 	struct compat_loop_info info;
1661 
1662 	if (copy_from_user(&info, arg, sizeof(info)))
1663 		return -EFAULT;
1664 
1665 	memset(info64, 0, sizeof(*info64));
1666 	info64->lo_number = info.lo_number;
1667 	info64->lo_device = info.lo_device;
1668 	info64->lo_inode = info.lo_inode;
1669 	info64->lo_rdevice = info.lo_rdevice;
1670 	info64->lo_offset = info.lo_offset;
1671 	info64->lo_sizelimit = 0;
1672 	info64->lo_encrypt_type = info.lo_encrypt_type;
1673 	info64->lo_encrypt_key_size = info.lo_encrypt_key_size;
1674 	info64->lo_flags = info.lo_flags;
1675 	info64->lo_init[0] = info.lo_init[0];
1676 	info64->lo_init[1] = info.lo_init[1];
1677 	if (info.lo_encrypt_type == LO_CRYPT_CRYPTOAPI)
1678 		memcpy(info64->lo_crypt_name, info.lo_name, LO_NAME_SIZE);
1679 	else
1680 		memcpy(info64->lo_file_name, info.lo_name, LO_NAME_SIZE);
1681 	memcpy(info64->lo_encrypt_key, info.lo_encrypt_key, LO_KEY_SIZE);
1682 	return 0;
1683 }
1684 
1685 /*
1686  * Transfer 64-bit loop info to 32-bit compatibility structure in userspace
1687  * - noinlined to reduce stack space usage in main part of driver
1688  */
1689 static noinline int
loop_info64_to_compat(const struct loop_info64 * info64,struct compat_loop_info __user * arg)1690 loop_info64_to_compat(const struct loop_info64 *info64,
1691 		      struct compat_loop_info __user *arg)
1692 {
1693 	struct compat_loop_info info;
1694 
1695 	memset(&info, 0, sizeof(info));
1696 	info.lo_number = info64->lo_number;
1697 	info.lo_device = info64->lo_device;
1698 	info.lo_inode = info64->lo_inode;
1699 	info.lo_rdevice = info64->lo_rdevice;
1700 	info.lo_offset = info64->lo_offset;
1701 	info.lo_encrypt_type = info64->lo_encrypt_type;
1702 	info.lo_encrypt_key_size = info64->lo_encrypt_key_size;
1703 	info.lo_flags = info64->lo_flags;
1704 	info.lo_init[0] = info64->lo_init[0];
1705 	info.lo_init[1] = info64->lo_init[1];
1706 	if (info.lo_encrypt_type == LO_CRYPT_CRYPTOAPI)
1707 		memcpy(info.lo_name, info64->lo_crypt_name, LO_NAME_SIZE);
1708 	else
1709 		memcpy(info.lo_name, info64->lo_file_name, LO_NAME_SIZE);
1710 	memcpy(info.lo_encrypt_key, info64->lo_encrypt_key, LO_KEY_SIZE);
1711 
1712 	/* error in case values were truncated */
1713 	if (info.lo_device != info64->lo_device ||
1714 	    info.lo_rdevice != info64->lo_rdevice ||
1715 	    info.lo_inode != info64->lo_inode ||
1716 	    info.lo_offset != info64->lo_offset ||
1717 	    info.lo_init[0] != info64->lo_init[0] ||
1718 	    info.lo_init[1] != info64->lo_init[1])
1719 		return -EOVERFLOW;
1720 
1721 	if (copy_to_user(arg, &info, sizeof(info)))
1722 		return -EFAULT;
1723 	return 0;
1724 }
1725 
1726 static int
loop_set_status_compat(struct loop_device * lo,const struct compat_loop_info __user * arg)1727 loop_set_status_compat(struct loop_device *lo,
1728 		       const struct compat_loop_info __user *arg)
1729 {
1730 	struct loop_info64 info64;
1731 	int ret;
1732 
1733 	ret = loop_info64_from_compat(arg, &info64);
1734 	if (ret < 0)
1735 		return ret;
1736 	return loop_set_status(lo, &info64);
1737 }
1738 
1739 static int
loop_get_status_compat(struct loop_device * lo,struct compat_loop_info __user * arg)1740 loop_get_status_compat(struct loop_device *lo,
1741 		       struct compat_loop_info __user *arg)
1742 {
1743 	struct loop_info64 info64;
1744 	int err;
1745 
1746 	if (!arg)
1747 		return -EINVAL;
1748 	err = loop_get_status(lo, &info64);
1749 	if (!err)
1750 		err = loop_info64_to_compat(&info64, arg);
1751 	return err;
1752 }
1753 
lo_compat_ioctl(struct block_device * bdev,fmode_t mode,unsigned int cmd,unsigned long arg)1754 static int lo_compat_ioctl(struct block_device *bdev, fmode_t mode,
1755 			   unsigned int cmd, unsigned long arg)
1756 {
1757 	struct loop_device *lo = bdev->bd_disk->private_data;
1758 	int err;
1759 
1760 	switch(cmd) {
1761 	case LOOP_SET_STATUS:
1762 		err = loop_set_status_compat(lo,
1763 			     (const struct compat_loop_info __user *)arg);
1764 		break;
1765 	case LOOP_GET_STATUS:
1766 		err = loop_get_status_compat(lo,
1767 				     (struct compat_loop_info __user *)arg);
1768 		break;
1769 	case LOOP_SET_CAPACITY:
1770 	case LOOP_CLR_FD:
1771 	case LOOP_GET_STATUS64:
1772 	case LOOP_SET_STATUS64:
1773 		arg = (unsigned long) compat_ptr(arg);
1774 		/* fall through */
1775 	case LOOP_SET_FD:
1776 	case LOOP_CHANGE_FD:
1777 	case LOOP_SET_BLOCK_SIZE:
1778 	case LOOP_SET_DIRECT_IO:
1779 		err = lo_ioctl(bdev, mode, cmd, arg);
1780 		break;
1781 	default:
1782 		err = -ENOIOCTLCMD;
1783 		break;
1784 	}
1785 	return err;
1786 }
1787 #endif
1788 
lo_open(struct block_device * bdev,fmode_t mode)1789 static int lo_open(struct block_device *bdev, fmode_t mode)
1790 {
1791 	struct loop_device *lo;
1792 	int err;
1793 
1794 	err = mutex_lock_killable(&loop_ctl_mutex);
1795 	if (err)
1796 		return err;
1797 	lo = bdev->bd_disk->private_data;
1798 	if (!lo) {
1799 		err = -ENXIO;
1800 		goto out;
1801 	}
1802 
1803 	atomic_inc(&lo->lo_refcnt);
1804 out:
1805 	mutex_unlock(&loop_ctl_mutex);
1806 	return err;
1807 }
1808 
lo_release(struct gendisk * disk,fmode_t mode)1809 static void lo_release(struct gendisk *disk, fmode_t mode)
1810 {
1811 	struct loop_device *lo;
1812 
1813 	mutex_lock(&loop_ctl_mutex);
1814 	lo = disk->private_data;
1815 	if (atomic_dec_return(&lo->lo_refcnt))
1816 		goto out_unlock;
1817 
1818 	if (lo->lo_flags & LO_FLAGS_AUTOCLEAR) {
1819 		if (lo->lo_state != Lo_bound)
1820 			goto out_unlock;
1821 		lo->lo_state = Lo_rundown;
1822 		mutex_unlock(&loop_ctl_mutex);
1823 		/*
1824 		 * In autoclear mode, stop the loop thread
1825 		 * and remove configuration after last close.
1826 		 */
1827 		__loop_clr_fd(lo, true);
1828 		return;
1829 	} else if (lo->lo_state == Lo_bound) {
1830 		/*
1831 		 * Otherwise keep thread (if running) and config,
1832 		 * but flush possible ongoing bios in thread.
1833 		 */
1834 		blk_mq_freeze_queue(lo->lo_queue);
1835 		blk_mq_unfreeze_queue(lo->lo_queue);
1836 	}
1837 
1838 out_unlock:
1839 	mutex_unlock(&loop_ctl_mutex);
1840 }
1841 
1842 static const struct block_device_operations lo_fops = {
1843 	.owner =	THIS_MODULE,
1844 	.open =		lo_open,
1845 	.release =	lo_release,
1846 	.ioctl =	lo_ioctl,
1847 #ifdef CONFIG_COMPAT
1848 	.compat_ioctl =	lo_compat_ioctl,
1849 #endif
1850 };
1851 
1852 /*
1853  * And now the modules code and kernel interface.
1854  */
1855 static int max_loop;
1856 module_param(max_loop, int, 0444);
1857 MODULE_PARM_DESC(max_loop, "Maximum number of loop devices");
1858 module_param(max_part, int, 0444);
1859 MODULE_PARM_DESC(max_part, "Maximum number of partitions per loop device");
1860 MODULE_LICENSE("GPL");
1861 MODULE_ALIAS_BLOCKDEV_MAJOR(LOOP_MAJOR);
1862 
loop_register_transfer(struct loop_func_table * funcs)1863 int loop_register_transfer(struct loop_func_table *funcs)
1864 {
1865 	unsigned int n = funcs->number;
1866 
1867 	if (n >= MAX_LO_CRYPT || xfer_funcs[n])
1868 		return -EINVAL;
1869 	xfer_funcs[n] = funcs;
1870 	return 0;
1871 }
1872 
unregister_transfer_cb(int id,void * ptr,void * data)1873 static int unregister_transfer_cb(int id, void *ptr, void *data)
1874 {
1875 	struct loop_device *lo = ptr;
1876 	struct loop_func_table *xfer = data;
1877 
1878 	mutex_lock(&loop_ctl_mutex);
1879 	if (lo->lo_encryption == xfer)
1880 		loop_release_xfer(lo);
1881 	mutex_unlock(&loop_ctl_mutex);
1882 	return 0;
1883 }
1884 
loop_unregister_transfer(int number)1885 int loop_unregister_transfer(int number)
1886 {
1887 	unsigned int n = number;
1888 	struct loop_func_table *xfer;
1889 
1890 	if (n == 0 || n >= MAX_LO_CRYPT || (xfer = xfer_funcs[n]) == NULL)
1891 		return -EINVAL;
1892 
1893 	xfer_funcs[n] = NULL;
1894 	idr_for_each(&loop_index_idr, &unregister_transfer_cb, xfer);
1895 	return 0;
1896 }
1897 
1898 EXPORT_SYMBOL(loop_register_transfer);
1899 EXPORT_SYMBOL(loop_unregister_transfer);
1900 
loop_queue_rq(struct blk_mq_hw_ctx * hctx,const struct blk_mq_queue_data * bd)1901 static blk_status_t loop_queue_rq(struct blk_mq_hw_ctx *hctx,
1902 		const struct blk_mq_queue_data *bd)
1903 {
1904 	struct request *rq = bd->rq;
1905 	struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
1906 	struct loop_device *lo = rq->q->queuedata;
1907 
1908 	blk_mq_start_request(rq);
1909 
1910 	if (lo->lo_state != Lo_bound)
1911 		return BLK_STS_IOERR;
1912 
1913 	switch (req_op(rq)) {
1914 	case REQ_OP_FLUSH:
1915 	case REQ_OP_DISCARD:
1916 	case REQ_OP_WRITE_ZEROES:
1917 		cmd->use_aio = false;
1918 		break;
1919 	default:
1920 		cmd->use_aio = lo->use_dio;
1921 		break;
1922 	}
1923 
1924 	/* always use the first bio's css */
1925 #ifdef CONFIG_BLK_CGROUP
1926 	if (cmd->use_aio && rq->bio && rq->bio->bi_blkg) {
1927 		cmd->css = &bio_blkcg(rq->bio)->css;
1928 		css_get(cmd->css);
1929 	} else
1930 #endif
1931 		cmd->css = NULL;
1932 	kthread_queue_work(&lo->worker, &cmd->work);
1933 
1934 	return BLK_STS_OK;
1935 }
1936 
loop_handle_cmd(struct loop_cmd * cmd)1937 static void loop_handle_cmd(struct loop_cmd *cmd)
1938 {
1939 	struct request *rq = blk_mq_rq_from_pdu(cmd);
1940 	const bool write = op_is_write(req_op(rq));
1941 	struct loop_device *lo = rq->q->queuedata;
1942 	int ret = 0;
1943 
1944 	if (write && (lo->lo_flags & LO_FLAGS_READ_ONLY)) {
1945 		ret = -EIO;
1946 		goto failed;
1947 	}
1948 
1949 	ret = do_req_filebacked(lo, rq);
1950  failed:
1951 	/* complete non-aio request */
1952 	if (!cmd->use_aio || ret) {
1953 		cmd->ret = ret ? -EIO : 0;
1954 		blk_mq_complete_request(rq);
1955 	}
1956 }
1957 
loop_queue_work(struct kthread_work * work)1958 static void loop_queue_work(struct kthread_work *work)
1959 {
1960 	struct loop_cmd *cmd =
1961 		container_of(work, struct loop_cmd, work);
1962 
1963 	loop_handle_cmd(cmd);
1964 }
1965 
loop_init_request(struct blk_mq_tag_set * set,struct request * rq,unsigned int hctx_idx,unsigned int numa_node)1966 static int loop_init_request(struct blk_mq_tag_set *set, struct request *rq,
1967 		unsigned int hctx_idx, unsigned int numa_node)
1968 {
1969 	struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
1970 
1971 	kthread_init_work(&cmd->work, loop_queue_work);
1972 	return 0;
1973 }
1974 
1975 static const struct blk_mq_ops loop_mq_ops = {
1976 	.queue_rq       = loop_queue_rq,
1977 	.init_request	= loop_init_request,
1978 	.complete	= lo_complete_rq,
1979 };
1980 
loop_add(struct loop_device ** l,int i)1981 static int loop_add(struct loop_device **l, int i)
1982 {
1983 	struct loop_device *lo;
1984 	struct gendisk *disk;
1985 	int err;
1986 
1987 	err = -ENOMEM;
1988 	lo = kzalloc(sizeof(*lo), GFP_KERNEL);
1989 	if (!lo)
1990 		goto out;
1991 
1992 	lo->lo_state = Lo_unbound;
1993 
1994 	/* allocate id, if @id >= 0, we're requesting that specific id */
1995 	if (i >= 0) {
1996 		err = idr_alloc(&loop_index_idr, lo, i, i + 1, GFP_KERNEL);
1997 		if (err == -ENOSPC)
1998 			err = -EEXIST;
1999 	} else {
2000 		err = idr_alloc(&loop_index_idr, lo, 0, 0, GFP_KERNEL);
2001 	}
2002 	if (err < 0)
2003 		goto out_free_dev;
2004 	i = err;
2005 
2006 	err = -ENOMEM;
2007 	lo->tag_set.ops = &loop_mq_ops;
2008 	lo->tag_set.nr_hw_queues = 1;
2009 	lo->tag_set.queue_depth = 128;
2010 	lo->tag_set.numa_node = NUMA_NO_NODE;
2011 	lo->tag_set.cmd_size = sizeof(struct loop_cmd);
2012 	lo->tag_set.flags = BLK_MQ_F_SHOULD_MERGE;
2013 	lo->tag_set.driver_data = lo;
2014 
2015 	err = blk_mq_alloc_tag_set(&lo->tag_set);
2016 	if (err)
2017 		goto out_free_idr;
2018 
2019 	lo->lo_queue = blk_mq_init_queue(&lo->tag_set);
2020 	if (IS_ERR(lo->lo_queue)) {
2021 		err = PTR_ERR(lo->lo_queue);
2022 		goto out_cleanup_tags;
2023 	}
2024 	lo->lo_queue->queuedata = lo;
2025 
2026 	blk_queue_max_hw_sectors(lo->lo_queue, BLK_DEF_MAX_SECTORS);
2027 
2028 	/*
2029 	 * By default, we do buffer IO, so it doesn't make sense to enable
2030 	 * merge because the I/O submitted to backing file is handled page by
2031 	 * page. For directio mode, merge does help to dispatch bigger request
2032 	 * to underlayer disk. We will enable merge once directio is enabled.
2033 	 */
2034 	blk_queue_flag_set(QUEUE_FLAG_NOMERGES, lo->lo_queue);
2035 
2036 	err = -ENOMEM;
2037 	disk = lo->lo_disk = alloc_disk(1 << part_shift);
2038 	if (!disk)
2039 		goto out_free_queue;
2040 
2041 	/*
2042 	 * Disable partition scanning by default. The in-kernel partition
2043 	 * scanning can be requested individually per-device during its
2044 	 * setup. Userspace can always add and remove partitions from all
2045 	 * devices. The needed partition minors are allocated from the
2046 	 * extended minor space, the main loop device numbers will continue
2047 	 * to match the loop minors, regardless of the number of partitions
2048 	 * used.
2049 	 *
2050 	 * If max_part is given, partition scanning is globally enabled for
2051 	 * all loop devices. The minors for the main loop devices will be
2052 	 * multiples of max_part.
2053 	 *
2054 	 * Note: Global-for-all-devices, set-only-at-init, read-only module
2055 	 * parameteters like 'max_loop' and 'max_part' make things needlessly
2056 	 * complicated, are too static, inflexible and may surprise
2057 	 * userspace tools. Parameters like this in general should be avoided.
2058 	 */
2059 	if (!part_shift)
2060 		disk->flags |= GENHD_FL_NO_PART_SCAN;
2061 	disk->flags |= GENHD_FL_EXT_DEVT;
2062 	atomic_set(&lo->lo_refcnt, 0);
2063 	lo->lo_number		= i;
2064 	spin_lock_init(&lo->lo_lock);
2065 	disk->major		= LOOP_MAJOR;
2066 	disk->first_minor	= i << part_shift;
2067 	disk->fops		= &lo_fops;
2068 	disk->private_data	= lo;
2069 	disk->queue		= lo->lo_queue;
2070 	sprintf(disk->disk_name, "loop%d", i);
2071 	add_disk(disk);
2072 	*l = lo;
2073 	return lo->lo_number;
2074 
2075 out_free_queue:
2076 	blk_cleanup_queue(lo->lo_queue);
2077 out_cleanup_tags:
2078 	blk_mq_free_tag_set(&lo->tag_set);
2079 out_free_idr:
2080 	idr_remove(&loop_index_idr, i);
2081 out_free_dev:
2082 	kfree(lo);
2083 out:
2084 	return err;
2085 }
2086 
loop_remove(struct loop_device * lo)2087 static void loop_remove(struct loop_device *lo)
2088 {
2089 	del_gendisk(lo->lo_disk);
2090 	blk_cleanup_queue(lo->lo_queue);
2091 	blk_mq_free_tag_set(&lo->tag_set);
2092 	put_disk(lo->lo_disk);
2093 	kfree(lo);
2094 }
2095 
find_free_cb(int id,void * ptr,void * data)2096 static int find_free_cb(int id, void *ptr, void *data)
2097 {
2098 	struct loop_device *lo = ptr;
2099 	struct loop_device **l = data;
2100 
2101 	if (lo->lo_state == Lo_unbound) {
2102 		*l = lo;
2103 		return 1;
2104 	}
2105 	return 0;
2106 }
2107 
loop_lookup(struct loop_device ** l,int i)2108 static int loop_lookup(struct loop_device **l, int i)
2109 {
2110 	struct loop_device *lo;
2111 	int ret = -ENODEV;
2112 
2113 	if (i < 0) {
2114 		int err;
2115 
2116 		err = idr_for_each(&loop_index_idr, &find_free_cb, &lo);
2117 		if (err == 1) {
2118 			*l = lo;
2119 			ret = lo->lo_number;
2120 		}
2121 		goto out;
2122 	}
2123 
2124 	/* lookup and return a specific i */
2125 	lo = idr_find(&loop_index_idr, i);
2126 	if (lo) {
2127 		*l = lo;
2128 		ret = lo->lo_number;
2129 	}
2130 out:
2131 	return ret;
2132 }
2133 
loop_probe(dev_t dev,int * part,void * data)2134 static struct kobject *loop_probe(dev_t dev, int *part, void *data)
2135 {
2136 	struct loop_device *lo;
2137 	struct kobject *kobj;
2138 	int err;
2139 
2140 	mutex_lock(&loop_ctl_mutex);
2141 	err = loop_lookup(&lo, MINOR(dev) >> part_shift);
2142 	if (err < 0)
2143 		err = loop_add(&lo, MINOR(dev) >> part_shift);
2144 	if (err < 0)
2145 		kobj = NULL;
2146 	else
2147 		kobj = get_disk_and_module(lo->lo_disk);
2148 	mutex_unlock(&loop_ctl_mutex);
2149 
2150 	*part = 0;
2151 	return kobj;
2152 }
2153 
loop_control_ioctl(struct file * file,unsigned int cmd,unsigned long parm)2154 static long loop_control_ioctl(struct file *file, unsigned int cmd,
2155 			       unsigned long parm)
2156 {
2157 	struct loop_device *lo;
2158 	int ret;
2159 
2160 	ret = mutex_lock_killable(&loop_ctl_mutex);
2161 	if (ret)
2162 		return ret;
2163 
2164 	ret = -ENOSYS;
2165 	switch (cmd) {
2166 	case LOOP_CTL_ADD:
2167 		ret = loop_lookup(&lo, parm);
2168 		if (ret >= 0) {
2169 			ret = -EEXIST;
2170 			break;
2171 		}
2172 		ret = loop_add(&lo, parm);
2173 		break;
2174 	case LOOP_CTL_REMOVE:
2175 		ret = loop_lookup(&lo, parm);
2176 		if (ret < 0)
2177 			break;
2178 		if (lo->lo_state != Lo_unbound) {
2179 			ret = -EBUSY;
2180 			break;
2181 		}
2182 		if (atomic_read(&lo->lo_refcnt) > 0) {
2183 			ret = -EBUSY;
2184 			break;
2185 		}
2186 		lo->lo_disk->private_data = NULL;
2187 		idr_remove(&loop_index_idr, lo->lo_number);
2188 		loop_remove(lo);
2189 		break;
2190 	case LOOP_CTL_GET_FREE:
2191 		ret = loop_lookup(&lo, -1);
2192 		if (ret >= 0)
2193 			break;
2194 		ret = loop_add(&lo, -1);
2195 	}
2196 	mutex_unlock(&loop_ctl_mutex);
2197 
2198 	return ret;
2199 }
2200 
2201 static const struct file_operations loop_ctl_fops = {
2202 	.open		= nonseekable_open,
2203 	.unlocked_ioctl	= loop_control_ioctl,
2204 	.compat_ioctl	= loop_control_ioctl,
2205 	.owner		= THIS_MODULE,
2206 	.llseek		= noop_llseek,
2207 };
2208 
2209 static struct miscdevice loop_misc = {
2210 	.minor		= LOOP_CTRL_MINOR,
2211 	.name		= "loop-control",
2212 	.fops		= &loop_ctl_fops,
2213 };
2214 
2215 MODULE_ALIAS_MISCDEV(LOOP_CTRL_MINOR);
2216 MODULE_ALIAS("devname:loop-control");
2217 
loop_init(void)2218 static int __init loop_init(void)
2219 {
2220 	int i, nr;
2221 	unsigned long range;
2222 	struct loop_device *lo;
2223 	int err;
2224 
2225 	part_shift = 0;
2226 	if (max_part > 0) {
2227 		part_shift = fls(max_part);
2228 
2229 		/*
2230 		 * Adjust max_part according to part_shift as it is exported
2231 		 * to user space so that user can decide correct minor number
2232 		 * if [s]he want to create more devices.
2233 		 *
2234 		 * Note that -1 is required because partition 0 is reserved
2235 		 * for the whole disk.
2236 		 */
2237 		max_part = (1UL << part_shift) - 1;
2238 	}
2239 
2240 	if ((1UL << part_shift) > DISK_MAX_PARTS) {
2241 		err = -EINVAL;
2242 		goto err_out;
2243 	}
2244 
2245 	if (max_loop > 1UL << (MINORBITS - part_shift)) {
2246 		err = -EINVAL;
2247 		goto err_out;
2248 	}
2249 
2250 	/*
2251 	 * If max_loop is specified, create that many devices upfront.
2252 	 * This also becomes a hard limit. If max_loop is not specified,
2253 	 * create CONFIG_BLK_DEV_LOOP_MIN_COUNT loop devices at module
2254 	 * init time. Loop devices can be requested on-demand with the
2255 	 * /dev/loop-control interface, or be instantiated by accessing
2256 	 * a 'dead' device node.
2257 	 */
2258 	if (max_loop) {
2259 		nr = max_loop;
2260 		range = max_loop << part_shift;
2261 	} else {
2262 		nr = CONFIG_BLK_DEV_LOOP_MIN_COUNT;
2263 		range = 1UL << MINORBITS;
2264 	}
2265 
2266 	err = misc_register(&loop_misc);
2267 	if (err < 0)
2268 		goto err_out;
2269 
2270 
2271 	if (register_blkdev(LOOP_MAJOR, "loop")) {
2272 		err = -EIO;
2273 		goto misc_out;
2274 	}
2275 
2276 	blk_register_region(MKDEV(LOOP_MAJOR, 0), range,
2277 				  THIS_MODULE, loop_probe, NULL, NULL);
2278 
2279 	/* pre-create number of devices given by config or max_loop */
2280 	mutex_lock(&loop_ctl_mutex);
2281 	for (i = 0; i < nr; i++)
2282 		loop_add(&lo, i);
2283 	mutex_unlock(&loop_ctl_mutex);
2284 
2285 	printk(KERN_INFO "loop: module loaded\n");
2286 	return 0;
2287 
2288 misc_out:
2289 	misc_deregister(&loop_misc);
2290 err_out:
2291 	return err;
2292 }
2293 
loop_exit_cb(int id,void * ptr,void * data)2294 static int loop_exit_cb(int id, void *ptr, void *data)
2295 {
2296 	struct loop_device *lo = ptr;
2297 
2298 	loop_remove(lo);
2299 	return 0;
2300 }
2301 
loop_exit(void)2302 static void __exit loop_exit(void)
2303 {
2304 	unsigned long range;
2305 
2306 	range = max_loop ? max_loop << part_shift : 1UL << MINORBITS;
2307 
2308 	idr_for_each(&loop_index_idr, &loop_exit_cb, NULL);
2309 	idr_destroy(&loop_index_idr);
2310 
2311 	blk_unregister_region(MKDEV(LOOP_MAJOR, 0), range);
2312 	unregister_blkdev(LOOP_MAJOR, "loop");
2313 
2314 	misc_deregister(&loop_misc);
2315 }
2316 
2317 module_init(loop_init);
2318 module_exit(loop_exit);
2319 
2320 #ifndef MODULE
max_loop_setup(char * str)2321 static int __init max_loop_setup(char *str)
2322 {
2323 	max_loop = simple_strtol(str, NULL, 0);
2324 	return 1;
2325 }
2326 
2327 __setup("max_loop=", max_loop_setup);
2328 #endif
2329