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