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