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