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