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