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