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