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_flags & LO_FLAGS_DIRECT_IO) && !lo_can_use_dio(lo)) 215 lo->lo_flags &= ~LO_FLAGS_DIRECT_IO; 216 217 /* flush dirty pages before starting to issue direct I/O */ 218 if ((lo->lo_flags & LO_FLAGS_DIRECT_IO) && !dio_in_use) 219 vfs_fsync(lo->lo_backing_file, 0); 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 void loop_reread_partitions(struct loop_device *lo) 531 { 532 int rc; 533 534 mutex_lock(&lo->lo_disk->open_mutex); 535 rc = bdev_disk_changed(lo->lo_disk, false); 536 mutex_unlock(&lo->lo_disk->open_mutex); 537 if (rc) 538 pr_warn("%s: partition scan of loop%d (%s) failed (rc=%d)\n", 539 __func__, lo->lo_number, lo->lo_file_name, rc); 540 } 541 542 static inline int is_loop_device(struct file *file) 543 { 544 struct inode *i = file->f_mapping->host; 545 546 return i && S_ISBLK(i->i_mode) && imajor(i) == LOOP_MAJOR; 547 } 548 549 static int loop_validate_file(struct file *file, struct block_device *bdev) 550 { 551 struct inode *inode = file->f_mapping->host; 552 struct file *f = file; 553 554 /* Avoid recursion */ 555 while (is_loop_device(f)) { 556 struct loop_device *l; 557 558 lockdep_assert_held(&loop_validate_mutex); 559 if (f->f_mapping->host->i_rdev == bdev->bd_dev) 560 return -EBADF; 561 562 l = I_BDEV(f->f_mapping->host)->bd_disk->private_data; 563 if (l->lo_state != Lo_bound) 564 return -EINVAL; 565 /* Order wrt setting lo->lo_backing_file in loop_configure(). */ 566 rmb(); 567 f = l->lo_backing_file; 568 } 569 if (!S_ISREG(inode->i_mode) && !S_ISBLK(inode->i_mode)) 570 return -EINVAL; 571 return 0; 572 } 573 574 static void loop_assign_backing_file(struct loop_device *lo, struct file *file) 575 { 576 lo->lo_backing_file = file; 577 lo->old_gfp_mask = mapping_gfp_mask(file->f_mapping); 578 mapping_set_gfp_mask(file->f_mapping, 579 lo->old_gfp_mask & ~(__GFP_IO | __GFP_FS)); 580 if (lo->lo_backing_file->f_flags & O_DIRECT) 581 lo->lo_flags |= LO_FLAGS_DIRECT_IO; 582 } 583 584 /* 585 * loop_change_fd switched the backing store of a loopback device to 586 * a new file. This is useful for operating system installers to free up 587 * the original file and in High Availability environments to switch to 588 * an alternative location for the content in case of server meltdown. 589 * This can only work if the loop device is used read-only, and if the 590 * new backing store is the same size and type as the old backing store. 591 */ 592 static int loop_change_fd(struct loop_device *lo, struct block_device *bdev, 593 unsigned int arg) 594 { 595 struct file *file = fget(arg); 596 struct file *old_file; 597 unsigned int memflags; 598 int error; 599 bool partscan; 600 bool is_loop; 601 602 if (!file) 603 return -EBADF; 604 605 /* suppress uevents while reconfiguring the device */ 606 dev_set_uevent_suppress(disk_to_dev(lo->lo_disk), 1); 607 608 is_loop = is_loop_device(file); 609 error = loop_global_lock_killable(lo, is_loop); 610 if (error) 611 goto out_putf; 612 error = -ENXIO; 613 if (lo->lo_state != Lo_bound) 614 goto out_err; 615 616 /* the loop device has to be read-only */ 617 error = -EINVAL; 618 if (!(lo->lo_flags & LO_FLAGS_READ_ONLY)) 619 goto out_err; 620 621 error = loop_validate_file(file, bdev); 622 if (error) 623 goto out_err; 624 625 old_file = lo->lo_backing_file; 626 627 error = -EINVAL; 628 629 /* size of the new backing store needs to be the same */ 630 if (get_loop_size(lo, file) != get_loop_size(lo, old_file)) 631 goto out_err; 632 633 /* and ... switch */ 634 disk_force_media_change(lo->lo_disk); 635 memflags = blk_mq_freeze_queue(lo->lo_queue); 636 mapping_set_gfp_mask(old_file->f_mapping, lo->old_gfp_mask); 637 loop_assign_backing_file(lo, file); 638 loop_update_dio(lo); 639 blk_mq_unfreeze_queue(lo->lo_queue, memflags); 640 partscan = lo->lo_flags & LO_FLAGS_PARTSCAN; 641 loop_global_unlock(lo, is_loop); 642 643 /* 644 * Flush loop_validate_file() before fput(), for l->lo_backing_file 645 * might be pointing at old_file which might be the last reference. 646 */ 647 if (!is_loop) { 648 mutex_lock(&loop_validate_mutex); 649 mutex_unlock(&loop_validate_mutex); 650 } 651 /* 652 * We must drop file reference outside of lo_mutex as dropping 653 * the file ref can take open_mutex which creates circular locking 654 * dependency. 655 */ 656 fput(old_file); 657 if (partscan) 658 loop_reread_partitions(lo); 659 660 error = 0; 661 done: 662 /* enable and uncork uevent now that we are done */ 663 dev_set_uevent_suppress(disk_to_dev(lo->lo_disk), 0); 664 return error; 665 666 out_err: 667 loop_global_unlock(lo, is_loop); 668 out_putf: 669 fput(file); 670 goto done; 671 } 672 673 /* loop sysfs attributes */ 674 675 static ssize_t loop_attr_show(struct device *dev, char *page, 676 ssize_t (*callback)(struct loop_device *, char *)) 677 { 678 struct gendisk *disk = dev_to_disk(dev); 679 struct loop_device *lo = disk->private_data; 680 681 return callback(lo, page); 682 } 683 684 #define LOOP_ATTR_RO(_name) \ 685 static ssize_t loop_attr_##_name##_show(struct loop_device *, char *); \ 686 static ssize_t loop_attr_do_show_##_name(struct device *d, \ 687 struct device_attribute *attr, char *b) \ 688 { \ 689 return loop_attr_show(d, b, loop_attr_##_name##_show); \ 690 } \ 691 static struct device_attribute loop_attr_##_name = \ 692 __ATTR(_name, 0444, loop_attr_do_show_##_name, NULL); 693 694 static ssize_t loop_attr_backing_file_show(struct loop_device *lo, char *buf) 695 { 696 ssize_t ret; 697 char *p = NULL; 698 699 spin_lock_irq(&lo->lo_lock); 700 if (lo->lo_backing_file) 701 p = file_path(lo->lo_backing_file, buf, PAGE_SIZE - 1); 702 spin_unlock_irq(&lo->lo_lock); 703 704 if (IS_ERR_OR_NULL(p)) 705 ret = PTR_ERR(p); 706 else { 707 ret = strlen(p); 708 memmove(buf, p, ret); 709 buf[ret++] = '\n'; 710 buf[ret] = 0; 711 } 712 713 return ret; 714 } 715 716 static ssize_t loop_attr_offset_show(struct loop_device *lo, char *buf) 717 { 718 return sysfs_emit(buf, "%llu\n", (unsigned long long)lo->lo_offset); 719 } 720 721 static ssize_t loop_attr_sizelimit_show(struct loop_device *lo, char *buf) 722 { 723 return sysfs_emit(buf, "%llu\n", (unsigned long long)lo->lo_sizelimit); 724 } 725 726 static ssize_t loop_attr_autoclear_show(struct loop_device *lo, char *buf) 727 { 728 int autoclear = (lo->lo_flags & LO_FLAGS_AUTOCLEAR); 729 730 return sysfs_emit(buf, "%s\n", autoclear ? "1" : "0"); 731 } 732 733 static ssize_t loop_attr_partscan_show(struct loop_device *lo, char *buf) 734 { 735 int partscan = (lo->lo_flags & LO_FLAGS_PARTSCAN); 736 737 return sysfs_emit(buf, "%s\n", partscan ? "1" : "0"); 738 } 739 740 static ssize_t loop_attr_dio_show(struct loop_device *lo, char *buf) 741 { 742 int dio = (lo->lo_flags & LO_FLAGS_DIRECT_IO); 743 744 return sysfs_emit(buf, "%s\n", dio ? "1" : "0"); 745 } 746 747 LOOP_ATTR_RO(backing_file); 748 LOOP_ATTR_RO(offset); 749 LOOP_ATTR_RO(sizelimit); 750 LOOP_ATTR_RO(autoclear); 751 LOOP_ATTR_RO(partscan); 752 LOOP_ATTR_RO(dio); 753 754 static struct attribute *loop_attrs[] = { 755 &loop_attr_backing_file.attr, 756 &loop_attr_offset.attr, 757 &loop_attr_sizelimit.attr, 758 &loop_attr_autoclear.attr, 759 &loop_attr_partscan.attr, 760 &loop_attr_dio.attr, 761 NULL, 762 }; 763 764 static struct attribute_group loop_attribute_group = { 765 .name = "loop", 766 .attrs= loop_attrs, 767 }; 768 769 static void loop_sysfs_init(struct loop_device *lo) 770 { 771 lo->sysfs_inited = !sysfs_create_group(&disk_to_dev(lo->lo_disk)->kobj, 772 &loop_attribute_group); 773 } 774 775 static void loop_sysfs_exit(struct loop_device *lo) 776 { 777 if (lo->sysfs_inited) 778 sysfs_remove_group(&disk_to_dev(lo->lo_disk)->kobj, 779 &loop_attribute_group); 780 } 781 782 static void loop_get_discard_config(struct loop_device *lo, 783 u32 *granularity, u32 *max_discard_sectors) 784 { 785 struct file *file = lo->lo_backing_file; 786 struct inode *inode = file->f_mapping->host; 787 struct kstatfs sbuf; 788 789 /* 790 * If the backing device is a block device, mirror its zeroing 791 * capability. Set the discard sectors to the block device's zeroing 792 * capabilities because loop discards result in blkdev_issue_zeroout(), 793 * not blkdev_issue_discard(). This maintains consistent behavior with 794 * file-backed loop devices: discarded regions read back as zero. 795 */ 796 if (S_ISBLK(inode->i_mode)) { 797 struct block_device *bdev = I_BDEV(inode); 798 799 *max_discard_sectors = bdev_write_zeroes_sectors(bdev); 800 *granularity = bdev_discard_granularity(bdev); 801 802 /* 803 * We use punch hole to reclaim the free space used by the 804 * image a.k.a. discard. 805 */ 806 } else if (file->f_op->fallocate && !vfs_statfs(&file->f_path, &sbuf)) { 807 *max_discard_sectors = UINT_MAX >> 9; 808 *granularity = sbuf.f_bsize; 809 } 810 } 811 812 struct loop_worker { 813 struct rb_node rb_node; 814 struct work_struct work; 815 struct list_head cmd_list; 816 struct list_head idle_list; 817 struct loop_device *lo; 818 struct cgroup_subsys_state *blkcg_css; 819 unsigned long last_ran_at; 820 }; 821 822 static void loop_workfn(struct work_struct *work); 823 824 #ifdef CONFIG_BLK_CGROUP 825 static inline int queue_on_root_worker(struct cgroup_subsys_state *css) 826 { 827 return !css || css == blkcg_root_css; 828 } 829 #else 830 static inline int queue_on_root_worker(struct cgroup_subsys_state *css) 831 { 832 return !css; 833 } 834 #endif 835 836 static void loop_queue_work(struct loop_device *lo, struct loop_cmd *cmd) 837 { 838 struct rb_node **node, *parent = NULL; 839 struct loop_worker *cur_worker, *worker = NULL; 840 struct work_struct *work; 841 struct list_head *cmd_list; 842 843 spin_lock_irq(&lo->lo_work_lock); 844 845 if (queue_on_root_worker(cmd->blkcg_css)) 846 goto queue_work; 847 848 node = &lo->worker_tree.rb_node; 849 850 while (*node) { 851 parent = *node; 852 cur_worker = container_of(*node, struct loop_worker, rb_node); 853 if (cur_worker->blkcg_css == cmd->blkcg_css) { 854 worker = cur_worker; 855 break; 856 } else if ((long)cur_worker->blkcg_css < (long)cmd->blkcg_css) { 857 node = &(*node)->rb_left; 858 } else { 859 node = &(*node)->rb_right; 860 } 861 } 862 if (worker) 863 goto queue_work; 864 865 worker = kzalloc(sizeof(struct loop_worker), GFP_NOWAIT | __GFP_NOWARN); 866 /* 867 * In the event we cannot allocate a worker, just queue on the 868 * rootcg worker and issue the I/O as the rootcg 869 */ 870 if (!worker) { 871 cmd->blkcg_css = NULL; 872 if (cmd->memcg_css) 873 css_put(cmd->memcg_css); 874 cmd->memcg_css = NULL; 875 goto queue_work; 876 } 877 878 worker->blkcg_css = cmd->blkcg_css; 879 css_get(worker->blkcg_css); 880 INIT_WORK(&worker->work, loop_workfn); 881 INIT_LIST_HEAD(&worker->cmd_list); 882 INIT_LIST_HEAD(&worker->idle_list); 883 worker->lo = lo; 884 rb_link_node(&worker->rb_node, parent, node); 885 rb_insert_color(&worker->rb_node, &lo->worker_tree); 886 queue_work: 887 if (worker) { 888 /* 889 * We need to remove from the idle list here while 890 * holding the lock so that the idle timer doesn't 891 * free the worker 892 */ 893 if (!list_empty(&worker->idle_list)) 894 list_del_init(&worker->idle_list); 895 work = &worker->work; 896 cmd_list = &worker->cmd_list; 897 } else { 898 work = &lo->rootcg_work; 899 cmd_list = &lo->rootcg_cmd_list; 900 } 901 list_add_tail(&cmd->list_entry, cmd_list); 902 queue_work(lo->workqueue, work); 903 spin_unlock_irq(&lo->lo_work_lock); 904 } 905 906 static void loop_set_timer(struct loop_device *lo) 907 { 908 timer_reduce(&lo->timer, jiffies + LOOP_IDLE_WORKER_TIMEOUT); 909 } 910 911 static void loop_free_idle_workers(struct loop_device *lo, bool delete_all) 912 { 913 struct loop_worker *pos, *worker; 914 915 spin_lock_irq(&lo->lo_work_lock); 916 list_for_each_entry_safe(worker, pos, &lo->idle_worker_list, 917 idle_list) { 918 if (!delete_all && 919 time_is_after_jiffies(worker->last_ran_at + 920 LOOP_IDLE_WORKER_TIMEOUT)) 921 break; 922 list_del(&worker->idle_list); 923 rb_erase(&worker->rb_node, &lo->worker_tree); 924 css_put(worker->blkcg_css); 925 kfree(worker); 926 } 927 if (!list_empty(&lo->idle_worker_list)) 928 loop_set_timer(lo); 929 spin_unlock_irq(&lo->lo_work_lock); 930 } 931 932 static void loop_free_idle_workers_timer(struct timer_list *timer) 933 { 934 struct loop_device *lo = container_of(timer, struct loop_device, timer); 935 936 return loop_free_idle_workers(lo, false); 937 } 938 939 /** 940 * loop_set_status_from_info - configure device from loop_info 941 * @lo: struct loop_device to configure 942 * @info: struct loop_info64 to configure the device with 943 * 944 * Configures the loop device parameters according to the passed 945 * in loop_info64 configuration. 946 */ 947 static int 948 loop_set_status_from_info(struct loop_device *lo, 949 const struct loop_info64 *info) 950 { 951 if ((unsigned int) info->lo_encrypt_key_size > LO_KEY_SIZE) 952 return -EINVAL; 953 954 switch (info->lo_encrypt_type) { 955 case LO_CRYPT_NONE: 956 break; 957 case LO_CRYPT_XOR: 958 pr_warn("support for the xor transformation has been removed.\n"); 959 return -EINVAL; 960 case LO_CRYPT_CRYPTOAPI: 961 pr_warn("support for cryptoloop has been removed. Use dm-crypt instead.\n"); 962 return -EINVAL; 963 default: 964 return -EINVAL; 965 } 966 967 /* Avoid assigning overflow values */ 968 if (info->lo_offset > LLONG_MAX || info->lo_sizelimit > LLONG_MAX) 969 return -EOVERFLOW; 970 971 lo->lo_offset = info->lo_offset; 972 lo->lo_sizelimit = info->lo_sizelimit; 973 974 memcpy(lo->lo_file_name, info->lo_file_name, LO_NAME_SIZE); 975 lo->lo_file_name[LO_NAME_SIZE-1] = 0; 976 return 0; 977 } 978 979 static unsigned int loop_default_blocksize(struct loop_device *lo, 980 struct block_device *backing_bdev) 981 { 982 /* In case of direct I/O, match underlying block size */ 983 if ((lo->lo_flags & LO_FLAGS_DIRECT_IO) && backing_bdev) 984 return bdev_logical_block_size(backing_bdev); 985 return SECTOR_SIZE; 986 } 987 988 static void loop_update_limits(struct loop_device *lo, struct queue_limits *lim, 989 unsigned int bsize) 990 { 991 struct file *file = lo->lo_backing_file; 992 struct inode *inode = file->f_mapping->host; 993 struct block_device *backing_bdev = NULL; 994 u32 granularity = 0, max_discard_sectors = 0; 995 996 if (S_ISBLK(inode->i_mode)) 997 backing_bdev = I_BDEV(inode); 998 else if (inode->i_sb->s_bdev) 999 backing_bdev = inode->i_sb->s_bdev; 1000 1001 if (!bsize) 1002 bsize = loop_default_blocksize(lo, backing_bdev); 1003 1004 loop_get_discard_config(lo, &granularity, &max_discard_sectors); 1005 1006 lim->logical_block_size = bsize; 1007 lim->physical_block_size = bsize; 1008 lim->io_min = bsize; 1009 lim->features &= ~(BLK_FEAT_WRITE_CACHE | BLK_FEAT_ROTATIONAL); 1010 if (file->f_op->fsync && !(lo->lo_flags & LO_FLAGS_READ_ONLY)) 1011 lim->features |= BLK_FEAT_WRITE_CACHE; 1012 if (backing_bdev && !bdev_nonrot(backing_bdev)) 1013 lim->features |= BLK_FEAT_ROTATIONAL; 1014 lim->max_hw_discard_sectors = max_discard_sectors; 1015 lim->max_write_zeroes_sectors = max_discard_sectors; 1016 if (max_discard_sectors) 1017 lim->discard_granularity = granularity; 1018 else 1019 lim->discard_granularity = 0; 1020 } 1021 1022 static int loop_configure(struct loop_device *lo, blk_mode_t mode, 1023 struct block_device *bdev, 1024 const struct loop_config *config) 1025 { 1026 struct file *file = fget(config->fd); 1027 struct queue_limits lim; 1028 int error; 1029 loff_t size; 1030 bool partscan; 1031 bool is_loop; 1032 1033 if (!file) 1034 return -EBADF; 1035 is_loop = is_loop_device(file); 1036 1037 /* This is safe, since we have a reference from open(). */ 1038 __module_get(THIS_MODULE); 1039 1040 /* 1041 * If we don't hold exclusive handle for the device, upgrade to it 1042 * here to avoid changing device under exclusive owner. 1043 */ 1044 if (!(mode & BLK_OPEN_EXCL)) { 1045 error = bd_prepare_to_claim(bdev, loop_configure, NULL); 1046 if (error) 1047 goto out_putf; 1048 } 1049 1050 error = loop_global_lock_killable(lo, is_loop); 1051 if (error) 1052 goto out_bdev; 1053 1054 error = -EBUSY; 1055 if (lo->lo_state != Lo_unbound) 1056 goto out_unlock; 1057 1058 error = loop_validate_file(file, bdev); 1059 if (error) 1060 goto out_unlock; 1061 1062 if ((config->info.lo_flags & ~LOOP_CONFIGURE_SETTABLE_FLAGS) != 0) { 1063 error = -EINVAL; 1064 goto out_unlock; 1065 } 1066 1067 error = loop_set_status_from_info(lo, &config->info); 1068 if (error) 1069 goto out_unlock; 1070 lo->lo_flags = config->info.lo_flags; 1071 1072 if (!(file->f_mode & FMODE_WRITE) || !(mode & BLK_OPEN_WRITE) || 1073 !file->f_op->write_iter) 1074 lo->lo_flags |= LO_FLAGS_READ_ONLY; 1075 1076 if (!lo->workqueue) { 1077 lo->workqueue = alloc_workqueue("loop%d", 1078 WQ_UNBOUND | WQ_FREEZABLE, 1079 0, lo->lo_number); 1080 if (!lo->workqueue) { 1081 error = -ENOMEM; 1082 goto out_unlock; 1083 } 1084 } 1085 1086 /* suppress uevents while reconfiguring the device */ 1087 dev_set_uevent_suppress(disk_to_dev(lo->lo_disk), 1); 1088 1089 disk_force_media_change(lo->lo_disk); 1090 set_disk_ro(lo->lo_disk, (lo->lo_flags & LO_FLAGS_READ_ONLY) != 0); 1091 1092 lo->lo_device = bdev; 1093 loop_assign_backing_file(lo, file); 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