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