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