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