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