linux/fs/quota/dquot.c
<<
>>
Prefs
   1// SPDX-License-Identifier: GPL-2.0
   2/*
   3 * Implementation of the diskquota system for the LINUX operating system. QUOTA
   4 * is implemented using the BSD system call interface as the means of
   5 * communication with the user level. This file contains the generic routines
   6 * called by the different filesystems on allocation of an inode or block.
   7 * These routines take care of the administration needed to have a consistent
   8 * diskquota tracking system. The ideas of both user and group quotas are based
   9 * on the Melbourne quota system as used on BSD derived systems. The internal
  10 * implementation is based on one of the several variants of the LINUX
  11 * inode-subsystem with added complexity of the diskquota system.
  12 * 
  13 * Author:      Marco van Wieringen <mvw@planets.elm.net>
  14 *
  15 * Fixes:   Dmitry Gorodchanin <pgmdsg@ibi.com>, 11 Feb 96
  16 *
  17 *              Revised list management to avoid races
  18 *              -- Bill Hawes, <whawes@star.net>, 9/98
  19 *
  20 *              Fixed races in dquot_transfer(), dqget() and dquot_alloc_...().
  21 *              As the consequence the locking was moved from dquot_decr_...(),
  22 *              dquot_incr_...() to calling functions.
  23 *              invalidate_dquots() now writes modified dquots.
  24 *              Serialized quota_off() and quota_on() for mount point.
  25 *              Fixed a few bugs in grow_dquots().
  26 *              Fixed deadlock in write_dquot() - we no longer account quotas on
  27 *              quota files
  28 *              remove_dquot_ref() moved to inode.c - it now traverses through inodes
  29 *              add_dquot_ref() restarts after blocking
  30 *              Added check for bogus uid and fixed check for group in quotactl.
  31 *              Jan Kara, <jack@suse.cz>, sponsored by SuSE CR, 10-11/99
  32 *
  33 *              Used struct list_head instead of own list struct
  34 *              Invalidation of referenced dquots is no longer possible
  35 *              Improved free_dquots list management
  36 *              Quota and i_blocks are now updated in one place to avoid races
  37 *              Warnings are now delayed so we won't block in critical section
  38 *              Write updated not to require dquot lock
  39 *              Jan Kara, <jack@suse.cz>, 9/2000
  40 *
  41 *              Added dynamic quota structure allocation
  42 *              Jan Kara <jack@suse.cz> 12/2000
  43 *
  44 *              Rewritten quota interface. Implemented new quota format and
  45 *              formats registering.
  46 *              Jan Kara, <jack@suse.cz>, 2001,2002
  47 *
  48 *              New SMP locking.
  49 *              Jan Kara, <jack@suse.cz>, 10/2002
  50 *
  51 *              Added journalled quota support, fix lock inversion problems
  52 *              Jan Kara, <jack@suse.cz>, 2003,2004
  53 *
  54 * (C) Copyright 1994 - 1997 Marco van Wieringen 
  55 */
  56
  57#include <linux/errno.h>
  58#include <linux/kernel.h>
  59#include <linux/fs.h>
  60#include <linux/mount.h>
  61#include <linux/mm.h>
  62#include <linux/time.h>
  63#include <linux/types.h>
  64#include <linux/string.h>
  65#include <linux/fcntl.h>
  66#include <linux/stat.h>
  67#include <linux/tty.h>
  68#include <linux/file.h>
  69#include <linux/slab.h>
  70#include <linux/sysctl.h>
  71#include <linux/init.h>
  72#include <linux/module.h>
  73#include <linux/proc_fs.h>
  74#include <linux/security.h>
  75#include <linux/sched.h>
  76#include <linux/cred.h>
  77#include <linux/kmod.h>
  78#include <linux/namei.h>
  79#include <linux/capability.h>
  80#include <linux/quotaops.h>
  81#include "../internal.h" /* ugh */
  82
  83#include <linux/uaccess.h>
  84
  85/*
  86 * There are five quota SMP locks:
  87 * * dq_list_lock protects all lists with quotas and quota formats.
  88 * * dquot->dq_dqb_lock protects data from dq_dqb
  89 * * inode->i_lock protects inode->i_blocks, i_bytes and also guards
  90 *   consistency of dquot->dq_dqb with inode->i_blocks, i_bytes so that
  91 *   dquot_transfer() can stabilize amount it transfers
  92 * * dq_data_lock protects mem_dqinfo structures and modifications of dquot
  93 *   pointers in the inode
  94 * * dq_state_lock protects modifications of quota state (on quotaon and
  95 *   quotaoff) and readers who care about latest values take it as well.
  96 *
  97 * The spinlock ordering is hence:
  98 *   dq_data_lock > dq_list_lock > i_lock > dquot->dq_dqb_lock,
  99 *   dq_list_lock > dq_state_lock
 100 *
 101 * Note that some things (eg. sb pointer, type, id) doesn't change during
 102 * the life of the dquot structure and so needn't to be protected by a lock
 103 *
 104 * Operation accessing dquots via inode pointers are protected by dquot_srcu.
 105 * Operation of reading pointer needs srcu_read_lock(&dquot_srcu), and
 106 * synchronize_srcu(&dquot_srcu) is called after clearing pointers from
 107 * inode and before dropping dquot references to avoid use of dquots after
 108 * they are freed. dq_data_lock is used to serialize the pointer setting and
 109 * clearing operations.
 110 * Special care needs to be taken about S_NOQUOTA inode flag (marking that
 111 * inode is a quota file). Functions adding pointers from inode to dquots have
 112 * to check this flag under dq_data_lock and then (if S_NOQUOTA is not set) they
 113 * have to do all pointer modifications before dropping dq_data_lock. This makes
 114 * sure they cannot race with quotaon which first sets S_NOQUOTA flag and
 115 * then drops all pointers to dquots from an inode.
 116 *
 117 * Each dquot has its dq_lock mutex.  Dquot is locked when it is being read to
 118 * memory (or space for it is being allocated) on the first dqget(), when it is
 119 * being written out, and when it is being released on the last dqput(). The
 120 * allocation and release operations are serialized by the dq_lock and by
 121 * checking the use count in dquot_release().
 122 *
 123 * Lock ordering (including related VFS locks) is the following:
 124 *   s_umount > i_mutex > journal_lock > dquot->dq_lock > dqio_sem
 125 */
 126
 127static __cacheline_aligned_in_smp DEFINE_SPINLOCK(dq_list_lock);
 128static __cacheline_aligned_in_smp DEFINE_SPINLOCK(dq_state_lock);
 129__cacheline_aligned_in_smp DEFINE_SPINLOCK(dq_data_lock);
 130EXPORT_SYMBOL(dq_data_lock);
 131DEFINE_STATIC_SRCU(dquot_srcu);
 132
 133static DECLARE_WAIT_QUEUE_HEAD(dquot_ref_wq);
 134
 135void __quota_error(struct super_block *sb, const char *func,
 136                   const char *fmt, ...)
 137{
 138        if (printk_ratelimit()) {
 139                va_list args;
 140                struct va_format vaf;
 141
 142                va_start(args, fmt);
 143
 144                vaf.fmt = fmt;
 145                vaf.va = &args;
 146
 147                printk(KERN_ERR "Quota error (device %s): %s: %pV\n",
 148                       sb->s_id, func, &vaf);
 149
 150                va_end(args);
 151        }
 152}
 153EXPORT_SYMBOL(__quota_error);
 154
 155#if defined(CONFIG_QUOTA_DEBUG) || defined(CONFIG_PRINT_QUOTA_WARNING)
 156static char *quotatypes[] = INITQFNAMES;
 157#endif
 158static struct quota_format_type *quota_formats; /* List of registered formats */
 159static struct quota_module_name module_names[] = INIT_QUOTA_MODULE_NAMES;
 160
 161/* SLAB cache for dquot structures */
 162static struct kmem_cache *dquot_cachep;
 163
 164int register_quota_format(struct quota_format_type *fmt)
 165{
 166        spin_lock(&dq_list_lock);
 167        fmt->qf_next = quota_formats;
 168        quota_formats = fmt;
 169        spin_unlock(&dq_list_lock);
 170        return 0;
 171}
 172EXPORT_SYMBOL(register_quota_format);
 173
 174void unregister_quota_format(struct quota_format_type *fmt)
 175{
 176        struct quota_format_type **actqf;
 177
 178        spin_lock(&dq_list_lock);
 179        for (actqf = &quota_formats; *actqf && *actqf != fmt;
 180             actqf = &(*actqf)->qf_next)
 181                ;
 182        if (*actqf)
 183                *actqf = (*actqf)->qf_next;
 184        spin_unlock(&dq_list_lock);
 185}
 186EXPORT_SYMBOL(unregister_quota_format);
 187
 188static struct quota_format_type *find_quota_format(int id)
 189{
 190        struct quota_format_type *actqf;
 191
 192        spin_lock(&dq_list_lock);
 193        for (actqf = quota_formats; actqf && actqf->qf_fmt_id != id;
 194             actqf = actqf->qf_next)
 195                ;
 196        if (!actqf || !try_module_get(actqf->qf_owner)) {
 197                int qm;
 198
 199                spin_unlock(&dq_list_lock);
 200                
 201                for (qm = 0; module_names[qm].qm_fmt_id &&
 202                             module_names[qm].qm_fmt_id != id; qm++)
 203                        ;
 204                if (!module_names[qm].qm_fmt_id ||
 205                    request_module(module_names[qm].qm_mod_name))
 206                        return NULL;
 207
 208                spin_lock(&dq_list_lock);
 209                for (actqf = quota_formats; actqf && actqf->qf_fmt_id != id;
 210                     actqf = actqf->qf_next)
 211                        ;
 212                if (actqf && !try_module_get(actqf->qf_owner))
 213                        actqf = NULL;
 214        }
 215        spin_unlock(&dq_list_lock);
 216        return actqf;
 217}
 218
 219static void put_quota_format(struct quota_format_type *fmt)
 220{
 221        module_put(fmt->qf_owner);
 222}
 223
 224/*
 225 * Dquot List Management:
 226 * The quota code uses three lists for dquot management: the inuse_list,
 227 * free_dquots, and dquot_hash[] array. A single dquot structure may be
 228 * on all three lists, depending on its current state.
 229 *
 230 * All dquots are placed to the end of inuse_list when first created, and this
 231 * list is used for invalidate operation, which must look at every dquot.
 232 *
 233 * Unused dquots (dq_count == 0) are added to the free_dquots list when freed,
 234 * and this list is searched whenever we need an available dquot.  Dquots are
 235 * removed from the list as soon as they are used again, and
 236 * dqstats.free_dquots gives the number of dquots on the list. When
 237 * dquot is invalidated it's completely released from memory.
 238 *
 239 * Dquots with a specific identity (device, type and id) are placed on
 240 * one of the dquot_hash[] hash chains. The provides an efficient search
 241 * mechanism to locate a specific dquot.
 242 */
 243
 244static LIST_HEAD(inuse_list);
 245static LIST_HEAD(free_dquots);
 246static unsigned int dq_hash_bits, dq_hash_mask;
 247static struct hlist_head *dquot_hash;
 248
 249struct dqstats dqstats;
 250EXPORT_SYMBOL(dqstats);
 251
 252static qsize_t inode_get_rsv_space(struct inode *inode);
 253static qsize_t __inode_get_rsv_space(struct inode *inode);
 254static int __dquot_initialize(struct inode *inode, int type);
 255
 256static inline unsigned int
 257hashfn(const struct super_block *sb, struct kqid qid)
 258{
 259        unsigned int id = from_kqid(&init_user_ns, qid);
 260        int type = qid.type;
 261        unsigned long tmp;
 262
 263        tmp = (((unsigned long)sb>>L1_CACHE_SHIFT) ^ id) * (MAXQUOTAS - type);
 264        return (tmp + (tmp >> dq_hash_bits)) & dq_hash_mask;
 265}
 266
 267/*
 268 * Following list functions expect dq_list_lock to be held
 269 */
 270static inline void insert_dquot_hash(struct dquot *dquot)
 271{
 272        struct hlist_head *head;
 273        head = dquot_hash + hashfn(dquot->dq_sb, dquot->dq_id);
 274        hlist_add_head(&dquot->dq_hash, head);
 275}
 276
 277static inline void remove_dquot_hash(struct dquot *dquot)
 278{
 279        hlist_del_init(&dquot->dq_hash);
 280}
 281
 282static struct dquot *find_dquot(unsigned int hashent, struct super_block *sb,
 283                                struct kqid qid)
 284{
 285        struct hlist_node *node;
 286        struct dquot *dquot;
 287
 288        hlist_for_each (node, dquot_hash+hashent) {
 289                dquot = hlist_entry(node, struct dquot, dq_hash);
 290                if (dquot->dq_sb == sb && qid_eq(dquot->dq_id, qid))
 291                        return dquot;
 292        }
 293        return NULL;
 294}
 295
 296/* Add a dquot to the tail of the free list */
 297static inline void put_dquot_last(struct dquot *dquot)
 298{
 299        list_add_tail(&dquot->dq_free, &free_dquots);
 300        dqstats_inc(DQST_FREE_DQUOTS);
 301}
 302
 303static inline void remove_free_dquot(struct dquot *dquot)
 304{
 305        if (list_empty(&dquot->dq_free))
 306                return;
 307        list_del_init(&dquot->dq_free);
 308        dqstats_dec(DQST_FREE_DQUOTS);
 309}
 310
 311static inline void put_inuse(struct dquot *dquot)
 312{
 313        /* We add to the back of inuse list so we don't have to restart
 314         * when traversing this list and we block */
 315        list_add_tail(&dquot->dq_inuse, &inuse_list);
 316        dqstats_inc(DQST_ALLOC_DQUOTS);
 317}
 318
 319static inline void remove_inuse(struct dquot *dquot)
 320{
 321        dqstats_dec(DQST_ALLOC_DQUOTS);
 322        list_del(&dquot->dq_inuse);
 323}
 324/*
 325 * End of list functions needing dq_list_lock
 326 */
 327
 328static void wait_on_dquot(struct dquot *dquot)
 329{
 330        mutex_lock(&dquot->dq_lock);
 331        mutex_unlock(&dquot->dq_lock);
 332}
 333
 334static inline int dquot_dirty(struct dquot *dquot)
 335{
 336        return test_bit(DQ_MOD_B, &dquot->dq_flags);
 337}
 338
 339static inline int mark_dquot_dirty(struct dquot *dquot)
 340{
 341        return dquot->dq_sb->dq_op->mark_dirty(dquot);
 342}
 343
 344/* Mark dquot dirty in atomic manner, and return it's old dirty flag state */
 345int dquot_mark_dquot_dirty(struct dquot *dquot)
 346{
 347        int ret = 1;
 348
 349        if (!test_bit(DQ_ACTIVE_B, &dquot->dq_flags))
 350                return 0;
 351
 352        if (sb_dqopt(dquot->dq_sb)->flags & DQUOT_NOLIST_DIRTY)
 353                return test_and_set_bit(DQ_MOD_B, &dquot->dq_flags);
 354
 355        /* If quota is dirty already, we don't have to acquire dq_list_lock */
 356        if (test_bit(DQ_MOD_B, &dquot->dq_flags))
 357                return 1;
 358
 359        spin_lock(&dq_list_lock);
 360        if (!test_and_set_bit(DQ_MOD_B, &dquot->dq_flags)) {
 361                list_add(&dquot->dq_dirty, &sb_dqopt(dquot->dq_sb)->
 362                                info[dquot->dq_id.type].dqi_dirty_list);
 363                ret = 0;
 364        }
 365        spin_unlock(&dq_list_lock);
 366        return ret;
 367}
 368EXPORT_SYMBOL(dquot_mark_dquot_dirty);
 369
 370/* Dirtify all the dquots - this can block when journalling */
 371static inline int mark_all_dquot_dirty(struct dquot * const *dquot)
 372{
 373        int ret, err, cnt;
 374
 375        ret = err = 0;
 376        for (cnt = 0; cnt < MAXQUOTAS; cnt++) {
 377                if (dquot[cnt])
 378                        /* Even in case of error we have to continue */
 379                        ret = mark_dquot_dirty(dquot[cnt]);
 380                if (!err)
 381                        err = ret;
 382        }
 383        return err;
 384}
 385
 386static inline void dqput_all(struct dquot **dquot)
 387{
 388        unsigned int cnt;
 389
 390        for (cnt = 0; cnt < MAXQUOTAS; cnt++)
 391                dqput(dquot[cnt]);
 392}
 393
 394static inline int clear_dquot_dirty(struct dquot *dquot)
 395{
 396        if (sb_dqopt(dquot->dq_sb)->flags & DQUOT_NOLIST_DIRTY)
 397                return test_and_clear_bit(DQ_MOD_B, &dquot->dq_flags);
 398
 399        spin_lock(&dq_list_lock);
 400        if (!test_and_clear_bit(DQ_MOD_B, &dquot->dq_flags)) {
 401                spin_unlock(&dq_list_lock);
 402                return 0;
 403        }
 404        list_del_init(&dquot->dq_dirty);
 405        spin_unlock(&dq_list_lock);
 406        return 1;
 407}
 408
 409void mark_info_dirty(struct super_block *sb, int type)
 410{
 411        spin_lock(&dq_data_lock);
 412        sb_dqopt(sb)->info[type].dqi_flags |= DQF_INFO_DIRTY;
 413        spin_unlock(&dq_data_lock);
 414}
 415EXPORT_SYMBOL(mark_info_dirty);
 416
 417/*
 418 *      Read dquot from disk and alloc space for it
 419 */
 420
 421int dquot_acquire(struct dquot *dquot)
 422{
 423        int ret = 0, ret2 = 0;
 424        struct quota_info *dqopt = sb_dqopt(dquot->dq_sb);
 425
 426        mutex_lock(&dquot->dq_lock);
 427        if (!test_bit(DQ_READ_B, &dquot->dq_flags))
 428                ret = dqopt->ops[dquot->dq_id.type]->read_dqblk(dquot);
 429        if (ret < 0)
 430                goto out_iolock;
 431        /* Make sure flags update is visible after dquot has been filled */
 432        smp_mb__before_atomic();
 433        set_bit(DQ_READ_B, &dquot->dq_flags);
 434        /* Instantiate dquot if needed */
 435        if (!test_bit(DQ_ACTIVE_B, &dquot->dq_flags) && !dquot->dq_off) {
 436                ret = dqopt->ops[dquot->dq_id.type]->commit_dqblk(dquot);
 437                /* Write the info if needed */
 438                if (info_dirty(&dqopt->info[dquot->dq_id.type])) {
 439                        ret2 = dqopt->ops[dquot->dq_id.type]->write_file_info(
 440                                        dquot->dq_sb, dquot->dq_id.type);
 441                }
 442                if (ret < 0)
 443                        goto out_iolock;
 444                if (ret2 < 0) {
 445                        ret = ret2;
 446                        goto out_iolock;
 447                }
 448        }
 449        /*
 450         * Make sure flags update is visible after on-disk struct has been
 451         * allocated. Paired with smp_rmb() in dqget().
 452         */
 453        smp_mb__before_atomic();
 454        set_bit(DQ_ACTIVE_B, &dquot->dq_flags);
 455out_iolock:
 456        mutex_unlock(&dquot->dq_lock);
 457        return ret;
 458}
 459EXPORT_SYMBOL(dquot_acquire);
 460
 461/*
 462 *      Write dquot to disk
 463 */
 464int dquot_commit(struct dquot *dquot)
 465{
 466        int ret = 0;
 467        struct quota_info *dqopt = sb_dqopt(dquot->dq_sb);
 468
 469        mutex_lock(&dquot->dq_lock);
 470        if (!clear_dquot_dirty(dquot))
 471                goto out_lock;
 472        /* Inactive dquot can be only if there was error during read/init
 473         * => we have better not writing it */
 474        if (test_bit(DQ_ACTIVE_B, &dquot->dq_flags))
 475                ret = dqopt->ops[dquot->dq_id.type]->commit_dqblk(dquot);
 476        else
 477                ret = -EIO;
 478out_lock:
 479        mutex_unlock(&dquot->dq_lock);
 480        return ret;
 481}
 482EXPORT_SYMBOL(dquot_commit);
 483
 484/*
 485 *      Release dquot
 486 */
 487int dquot_release(struct dquot *dquot)
 488{
 489        int ret = 0, ret2 = 0;
 490        struct quota_info *dqopt = sb_dqopt(dquot->dq_sb);
 491
 492        mutex_lock(&dquot->dq_lock);
 493        /* Check whether we are not racing with some other dqget() */
 494        if (atomic_read(&dquot->dq_count) > 1)
 495                goto out_dqlock;
 496        if (dqopt->ops[dquot->dq_id.type]->release_dqblk) {
 497                ret = dqopt->ops[dquot->dq_id.type]->release_dqblk(dquot);
 498                /* Write the info */
 499                if (info_dirty(&dqopt->info[dquot->dq_id.type])) {
 500                        ret2 = dqopt->ops[dquot->dq_id.type]->write_file_info(
 501                                                dquot->dq_sb, dquot->dq_id.type);
 502                }
 503                if (ret >= 0)
 504                        ret = ret2;
 505        }
 506        clear_bit(DQ_ACTIVE_B, &dquot->dq_flags);
 507out_dqlock:
 508        mutex_unlock(&dquot->dq_lock);
 509        return ret;
 510}
 511EXPORT_SYMBOL(dquot_release);
 512
 513void dquot_destroy(struct dquot *dquot)
 514{
 515        kmem_cache_free(dquot_cachep, dquot);
 516}
 517EXPORT_SYMBOL(dquot_destroy);
 518
 519static inline void do_destroy_dquot(struct dquot *dquot)
 520{
 521        dquot->dq_sb->dq_op->destroy_dquot(dquot);
 522}
 523
 524/* Invalidate all dquots on the list. Note that this function is called after
 525 * quota is disabled and pointers from inodes removed so there cannot be new
 526 * quota users. There can still be some users of quotas due to inodes being
 527 * just deleted or pruned by prune_icache() (those are not attached to any
 528 * list) or parallel quotactl call. We have to wait for such users.
 529 */
 530static void invalidate_dquots(struct super_block *sb, int type)
 531{
 532        struct dquot *dquot, *tmp;
 533
 534restart:
 535        spin_lock(&dq_list_lock);
 536        list_for_each_entry_safe(dquot, tmp, &inuse_list, dq_inuse) {
 537                if (dquot->dq_sb != sb)
 538                        continue;
 539                if (dquot->dq_id.type != type)
 540                        continue;
 541                /* Wait for dquot users */
 542                if (atomic_read(&dquot->dq_count)) {
 543                        dqgrab(dquot);
 544                        spin_unlock(&dq_list_lock);
 545                        /*
 546                         * Once dqput() wakes us up, we know it's time to free
 547                         * the dquot.
 548                         * IMPORTANT: we rely on the fact that there is always
 549                         * at most one process waiting for dquot to free.
 550                         * Otherwise dq_count would be > 1 and we would never
 551                         * wake up.
 552                         */
 553                        wait_event(dquot_ref_wq,
 554                                   atomic_read(&dquot->dq_count) == 1);
 555                        dqput(dquot);
 556                        /* At this moment dquot() need not exist (it could be
 557                         * reclaimed by prune_dqcache(). Hence we must
 558                         * restart. */
 559                        goto restart;
 560                }
 561                /*
 562                 * Quota now has no users and it has been written on last
 563                 * dqput()
 564                 */
 565                remove_dquot_hash(dquot);
 566                remove_free_dquot(dquot);
 567                remove_inuse(dquot);
 568                do_destroy_dquot(dquot);
 569        }
 570        spin_unlock(&dq_list_lock);
 571}
 572
 573/* Call callback for every active dquot on given filesystem */
 574int dquot_scan_active(struct super_block *sb,
 575                      int (*fn)(struct dquot *dquot, unsigned long priv),
 576                      unsigned long priv)
 577{
 578        struct dquot *dquot, *old_dquot = NULL;
 579        int ret = 0;
 580
 581        WARN_ON_ONCE(!rwsem_is_locked(&sb->s_umount));
 582
 583        spin_lock(&dq_list_lock);
 584        list_for_each_entry(dquot, &inuse_list, dq_inuse) {
 585                if (!test_bit(DQ_ACTIVE_B, &dquot->dq_flags))
 586                        continue;
 587                if (dquot->dq_sb != sb)
 588                        continue;
 589                /* Now we have active dquot so we can just increase use count */
 590                atomic_inc(&dquot->dq_count);
 591                spin_unlock(&dq_list_lock);
 592                dqstats_inc(DQST_LOOKUPS);
 593                dqput(old_dquot);
 594                old_dquot = dquot;
 595                /*
 596                 * ->release_dquot() can be racing with us. Our reference
 597                 * protects us from new calls to it so just wait for any
 598                 * outstanding call and recheck the DQ_ACTIVE_B after that.
 599                 */
 600                wait_on_dquot(dquot);
 601                if (test_bit(DQ_ACTIVE_B, &dquot->dq_flags)) {
 602                        ret = fn(dquot, priv);
 603                        if (ret < 0)
 604                                goto out;
 605                }
 606                spin_lock(&dq_list_lock);
 607                /* We are safe to continue now because our dquot could not
 608                 * be moved out of the inuse list while we hold the reference */
 609        }
 610        spin_unlock(&dq_list_lock);
 611out:
 612        dqput(old_dquot);
 613        return ret;
 614}
 615EXPORT_SYMBOL(dquot_scan_active);
 616
 617/* Write all dquot structures to quota files */
 618int dquot_writeback_dquots(struct super_block *sb, int type)
 619{
 620        struct list_head *dirty;
 621        struct dquot *dquot;
 622        struct quota_info *dqopt = sb_dqopt(sb);
 623        int cnt;
 624        int err, ret = 0;
 625
 626        WARN_ON_ONCE(!rwsem_is_locked(&sb->s_umount));
 627
 628        for (cnt = 0; cnt < MAXQUOTAS; cnt++) {
 629                if (type != -1 && cnt != type)
 630                        continue;
 631                if (!sb_has_quota_active(sb, cnt))
 632                        continue;
 633                spin_lock(&dq_list_lock);
 634                dirty = &dqopt->info[cnt].dqi_dirty_list;
 635                while (!list_empty(dirty)) {
 636                        dquot = list_first_entry(dirty, struct dquot,
 637                                                 dq_dirty);
 638
 639                        WARN_ON(!test_bit(DQ_ACTIVE_B, &dquot->dq_flags));
 640
 641                        /* Now we have active dquot from which someone is
 642                         * holding reference so we can safely just increase
 643                         * use count */
 644                        dqgrab(dquot);
 645                        spin_unlock(&dq_list_lock);
 646                        dqstats_inc(DQST_LOOKUPS);
 647                        err = sb->dq_op->write_dquot(dquot);
 648                        if (err) {
 649                                /*
 650                                 * Clear dirty bit anyway to avoid infinite
 651                                 * loop here.
 652                                 */
 653                                clear_dquot_dirty(dquot);
 654                                if (!ret)
 655                                        ret = err;
 656                        }
 657                        dqput(dquot);
 658                        spin_lock(&dq_list_lock);
 659                }
 660                spin_unlock(&dq_list_lock);
 661        }
 662
 663        for (cnt = 0; cnt < MAXQUOTAS; cnt++)
 664                if ((cnt == type || type == -1) && sb_has_quota_active(sb, cnt)
 665                    && info_dirty(&dqopt->info[cnt]))
 666                        sb->dq_op->write_info(sb, cnt);
 667        dqstats_inc(DQST_SYNCS);
 668
 669        return ret;
 670}
 671EXPORT_SYMBOL(dquot_writeback_dquots);
 672
 673/* Write all dquot structures to disk and make them visible from userspace */
 674int dquot_quota_sync(struct super_block *sb, int type)
 675{
 676        struct quota_info *dqopt = sb_dqopt(sb);
 677        int cnt;
 678        int ret;
 679
 680        ret = dquot_writeback_dquots(sb, type);
 681        if (ret)
 682                return ret;
 683        if (dqopt->flags & DQUOT_QUOTA_SYS_FILE)
 684                return 0;
 685
 686        /* This is not very clever (and fast) but currently I don't know about
 687         * any other simple way of getting quota data to disk and we must get
 688         * them there for userspace to be visible... */
 689        if (sb->s_op->sync_fs)
 690                sb->s_op->sync_fs(sb, 1);
 691        sync_blockdev(sb->s_bdev);
 692
 693        /*
 694         * Now when everything is written we can discard the pagecache so
 695         * that userspace sees the changes.
 696         */
 697        for (cnt = 0; cnt < MAXQUOTAS; cnt++) {
 698                if (type != -1 && cnt != type)
 699                        continue;
 700                if (!sb_has_quota_active(sb, cnt))
 701                        continue;
 702                inode_lock(dqopt->files[cnt]);
 703                truncate_inode_pages(&dqopt->files[cnt]->i_data, 0);
 704                inode_unlock(dqopt->files[cnt]);
 705        }
 706
 707        return 0;
 708}
 709EXPORT_SYMBOL(dquot_quota_sync);
 710
 711static unsigned long
 712dqcache_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
 713{
 714        struct dquot *dquot;
 715        unsigned long freed = 0;
 716
 717        spin_lock(&dq_list_lock);
 718        while (!list_empty(&free_dquots) && sc->nr_to_scan) {
 719                dquot = list_first_entry(&free_dquots, struct dquot, dq_free);
 720                remove_dquot_hash(dquot);
 721                remove_free_dquot(dquot);
 722                remove_inuse(dquot);
 723                do_destroy_dquot(dquot);
 724                sc->nr_to_scan--;
 725                freed++;
 726        }
 727        spin_unlock(&dq_list_lock);
 728        return freed;
 729}
 730
 731static unsigned long
 732dqcache_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
 733{
 734        return vfs_pressure_ratio(
 735        percpu_counter_read_positive(&dqstats.counter[DQST_FREE_DQUOTS]));
 736}
 737
 738static struct shrinker dqcache_shrinker = {
 739        .count_objects = dqcache_shrink_count,
 740        .scan_objects = dqcache_shrink_scan,
 741        .seeks = DEFAULT_SEEKS,
 742};
 743
 744/*
 745 * Put reference to dquot
 746 */
 747void dqput(struct dquot *dquot)
 748{
 749        int ret;
 750
 751        if (!dquot)
 752                return;
 753#ifdef CONFIG_QUOTA_DEBUG
 754        if (!atomic_read(&dquot->dq_count)) {
 755                quota_error(dquot->dq_sb, "trying to free free dquot of %s %d",
 756                            quotatypes[dquot->dq_id.type],
 757                            from_kqid(&init_user_ns, dquot->dq_id));
 758                BUG();
 759        }
 760#endif
 761        dqstats_inc(DQST_DROPS);
 762we_slept:
 763        spin_lock(&dq_list_lock);
 764        if (atomic_read(&dquot->dq_count) > 1) {
 765                /* We have more than one user... nothing to do */
 766                atomic_dec(&dquot->dq_count);
 767                /* Releasing dquot during quotaoff phase? */
 768                if (!sb_has_quota_active(dquot->dq_sb, dquot->dq_id.type) &&
 769                    atomic_read(&dquot->dq_count) == 1)
 770                        wake_up(&dquot_ref_wq);
 771                spin_unlock(&dq_list_lock);
 772                return;
 773        }
 774        /* Need to release dquot? */
 775        if (dquot_dirty(dquot)) {
 776                spin_unlock(&dq_list_lock);
 777                /* Commit dquot before releasing */
 778                ret = dquot->dq_sb->dq_op->write_dquot(dquot);
 779                if (ret < 0) {
 780                        quota_error(dquot->dq_sb, "Can't write quota structure"
 781                                    " (error %d). Quota may get out of sync!",
 782                                    ret);
 783                        /*
 784                         * We clear dirty bit anyway, so that we avoid
 785                         * infinite loop here
 786                         */
 787                        clear_dquot_dirty(dquot);
 788                }
 789                goto we_slept;
 790        }
 791        if (test_bit(DQ_ACTIVE_B, &dquot->dq_flags)) {
 792                spin_unlock(&dq_list_lock);
 793                dquot->dq_sb->dq_op->release_dquot(dquot);
 794                goto we_slept;
 795        }
 796        atomic_dec(&dquot->dq_count);
 797#ifdef CONFIG_QUOTA_DEBUG
 798        /* sanity check */
 799        BUG_ON(!list_empty(&dquot->dq_free));
 800#endif
 801        put_dquot_last(dquot);
 802        spin_unlock(&dq_list_lock);
 803}
 804EXPORT_SYMBOL(dqput);
 805
 806struct dquot *dquot_alloc(struct super_block *sb, int type)
 807{
 808        return kmem_cache_zalloc(dquot_cachep, GFP_NOFS);
 809}
 810EXPORT_SYMBOL(dquot_alloc);
 811
 812static struct dquot *get_empty_dquot(struct super_block *sb, int type)
 813{
 814        struct dquot *dquot;
 815
 816        dquot = sb->dq_op->alloc_dquot(sb, type);
 817        if(!dquot)
 818                return NULL;
 819
 820        mutex_init(&dquot->dq_lock);
 821        INIT_LIST_HEAD(&dquot->dq_free);
 822        INIT_LIST_HEAD(&dquot->dq_inuse);
 823        INIT_HLIST_NODE(&dquot->dq_hash);
 824        INIT_LIST_HEAD(&dquot->dq_dirty);
 825        dquot->dq_sb = sb;
 826        dquot->dq_id = make_kqid_invalid(type);
 827        atomic_set(&dquot->dq_count, 1);
 828        spin_lock_init(&dquot->dq_dqb_lock);
 829
 830        return dquot;
 831}
 832
 833/*
 834 * Get reference to dquot
 835 *
 836 * Locking is slightly tricky here. We are guarded from parallel quotaoff()
 837 * destroying our dquot by:
 838 *   a) checking for quota flags under dq_list_lock and
 839 *   b) getting a reference to dquot before we release dq_list_lock
 840 */
 841struct dquot *dqget(struct super_block *sb, struct kqid qid)
 842{
 843        unsigned int hashent = hashfn(sb, qid);
 844        struct dquot *dquot, *empty = NULL;
 845
 846        if (!qid_has_mapping(sb->s_user_ns, qid))
 847                return ERR_PTR(-EINVAL);
 848
 849        if (!sb_has_quota_active(sb, qid.type))
 850                return ERR_PTR(-ESRCH);
 851we_slept:
 852        spin_lock(&dq_list_lock);
 853        spin_lock(&dq_state_lock);
 854        if (!sb_has_quota_active(sb, qid.type)) {
 855                spin_unlock(&dq_state_lock);
 856                spin_unlock(&dq_list_lock);
 857                dquot = ERR_PTR(-ESRCH);
 858                goto out;
 859        }
 860        spin_unlock(&dq_state_lock);
 861
 862        dquot = find_dquot(hashent, sb, qid);
 863        if (!dquot) {
 864                if (!empty) {
 865                        spin_unlock(&dq_list_lock);
 866                        empty = get_empty_dquot(sb, qid.type);
 867                        if (!empty)
 868                                schedule();     /* Try to wait for a moment... */
 869                        goto we_slept;
 870                }
 871                dquot = empty;
 872                empty = NULL;
 873                dquot->dq_id = qid;
 874                /* all dquots go on the inuse_list */
 875                put_inuse(dquot);
 876                /* hash it first so it can be found */
 877                insert_dquot_hash(dquot);
 878                spin_unlock(&dq_list_lock);
 879                dqstats_inc(DQST_LOOKUPS);
 880        } else {
 881                if (!atomic_read(&dquot->dq_count))
 882                        remove_free_dquot(dquot);
 883                atomic_inc(&dquot->dq_count);
 884                spin_unlock(&dq_list_lock);
 885                dqstats_inc(DQST_CACHE_HITS);
 886                dqstats_inc(DQST_LOOKUPS);
 887        }
 888        /* Wait for dq_lock - after this we know that either dquot_release() is
 889         * already finished or it will be canceled due to dq_count > 1 test */
 890        wait_on_dquot(dquot);
 891        /* Read the dquot / allocate space in quota file */
 892        if (!test_bit(DQ_ACTIVE_B, &dquot->dq_flags)) {
 893                int err;
 894
 895                err = sb->dq_op->acquire_dquot(dquot);
 896                if (err < 0) {
 897                        dqput(dquot);
 898                        dquot = ERR_PTR(err);
 899                        goto out;
 900                }
 901        }
 902        /*
 903         * Make sure following reads see filled structure - paired with
 904         * smp_mb__before_atomic() in dquot_acquire().
 905         */
 906        smp_rmb();
 907#ifdef CONFIG_QUOTA_DEBUG
 908        BUG_ON(!dquot->dq_sb);  /* Has somebody invalidated entry under us? */
 909#endif
 910out:
 911        if (empty)
 912                do_destroy_dquot(empty);
 913
 914        return dquot;
 915}
 916EXPORT_SYMBOL(dqget);
 917
 918static inline struct dquot **i_dquot(struct inode *inode)
 919{
 920        return inode->i_sb->s_op->get_dquots(inode);
 921}
 922
 923static int dqinit_needed(struct inode *inode, int type)
 924{
 925        struct dquot * const *dquots;
 926        int cnt;
 927
 928        if (IS_NOQUOTA(inode))
 929                return 0;
 930
 931        dquots = i_dquot(inode);
 932        if (type != -1)
 933                return !dquots[type];
 934        for (cnt = 0; cnt < MAXQUOTAS; cnt++)
 935                if (!dquots[cnt])
 936                        return 1;
 937        return 0;
 938}
 939
 940/* This routine is guarded by s_umount semaphore */
 941static int add_dquot_ref(struct super_block *sb, int type)
 942{
 943        struct inode *inode, *old_inode = NULL;
 944#ifdef CONFIG_QUOTA_DEBUG
 945        int reserved = 0;
 946#endif
 947        int err = 0;
 948
 949        spin_lock(&sb->s_inode_list_lock);
 950        list_for_each_entry(inode, &sb->s_inodes, i_sb_list) {
 951                spin_lock(&inode->i_lock);
 952                if ((inode->i_state & (I_FREEING|I_WILL_FREE|I_NEW)) ||
 953                    !atomic_read(&inode->i_writecount) ||
 954                    !dqinit_needed(inode, type)) {
 955                        spin_unlock(&inode->i_lock);
 956                        continue;
 957                }
 958                __iget(inode);
 959                spin_unlock(&inode->i_lock);
 960                spin_unlock(&sb->s_inode_list_lock);
 961
 962#ifdef CONFIG_QUOTA_DEBUG
 963                if (unlikely(inode_get_rsv_space(inode) > 0))
 964                        reserved = 1;
 965#endif
 966                iput(old_inode);
 967                err = __dquot_initialize(inode, type);
 968                if (err) {
 969                        iput(inode);
 970                        goto out;
 971                }
 972
 973                /*
 974                 * We hold a reference to 'inode' so it couldn't have been
 975                 * removed from s_inodes list while we dropped the
 976                 * s_inode_list_lock. We cannot iput the inode now as we can be
 977                 * holding the last reference and we cannot iput it under
 978                 * s_inode_list_lock. So we keep the reference and iput it
 979                 * later.
 980                 */
 981                old_inode = inode;
 982                spin_lock(&sb->s_inode_list_lock);
 983        }
 984        spin_unlock(&sb->s_inode_list_lock);
 985        iput(old_inode);
 986out:
 987#ifdef CONFIG_QUOTA_DEBUG
 988        if (reserved) {
 989                quota_error(sb, "Writes happened before quota was turned on "
 990                        "thus quota information is probably inconsistent. "
 991                        "Please run quotacheck(8)");
 992        }
 993#endif
 994        return err;
 995}
 996
 997/*
 998 * Remove references to dquots from inode and add dquot to list for freeing
 999 * if we have the last reference to dquot
1000 */
1001static void remove_inode_dquot_ref(struct inode *inode, int type,
1002                                   struct list_head *tofree_head)
1003{
1004        struct dquot **dquots = i_dquot(inode);
1005        struct dquot *dquot = dquots[type];
1006
1007        if (!dquot)
1008                return;
1009
1010        dquots[type] = NULL;
1011        if (list_empty(&dquot->dq_free)) {
1012                /*
1013                 * The inode still has reference to dquot so it can't be in the
1014                 * free list
1015                 */
1016                spin_lock(&dq_list_lock);
1017                list_add(&dquot->dq_free, tofree_head);
1018                spin_unlock(&dq_list_lock);
1019        } else {
1020                /*
1021                 * Dquot is already in a list to put so we won't drop the last
1022                 * reference here.
1023                 */
1024                dqput(dquot);
1025        }
1026}
1027
1028/*
1029 * Free list of dquots
1030 * Dquots are removed from inodes and no new references can be got so we are
1031 * the only ones holding reference
1032 */
1033static void put_dquot_list(struct list_head *tofree_head)
1034{
1035        struct list_head *act_head;
1036        struct dquot *dquot;
1037
1038        act_head = tofree_head->next;
1039        while (act_head != tofree_head) {
1040                dquot = list_entry(act_head, struct dquot, dq_free);
1041                act_head = act_head->next;
1042                /* Remove dquot from the list so we won't have problems... */
1043                list_del_init(&dquot->dq_free);
1044                dqput(dquot);
1045        }
1046}
1047
1048static void remove_dquot_ref(struct super_block *sb, int type,
1049                struct list_head *tofree_head)
1050{
1051        struct inode *inode;
1052        int reserved = 0;
1053
1054        spin_lock(&sb->s_inode_list_lock);
1055        list_for_each_entry(inode, &sb->s_inodes, i_sb_list) {
1056                /*
1057                 *  We have to scan also I_NEW inodes because they can already
1058                 *  have quota pointer initialized. Luckily, we need to touch
1059                 *  only quota pointers and these have separate locking
1060                 *  (dq_data_lock).
1061                 */
1062                spin_lock(&dq_data_lock);
1063                if (!IS_NOQUOTA(inode)) {
1064                        if (unlikely(inode_get_rsv_space(inode) > 0))
1065                                reserved = 1;
1066                        remove_inode_dquot_ref(inode, type, tofree_head);
1067                }
1068                spin_unlock(&dq_data_lock);
1069        }
1070        spin_unlock(&sb->s_inode_list_lock);
1071#ifdef CONFIG_QUOTA_DEBUG
1072        if (reserved) {
1073                printk(KERN_WARNING "VFS (%s): Writes happened after quota"
1074                        " was disabled thus quota information is probably "
1075                        "inconsistent. Please run quotacheck(8).\n", sb->s_id);
1076        }
1077#endif
1078}
1079
1080/* Gather all references from inodes and drop them */
1081static void drop_dquot_ref(struct super_block *sb, int type)
1082{
1083        LIST_HEAD(tofree_head);
1084
1085        if (sb->dq_op) {
1086                remove_dquot_ref(sb, type, &tofree_head);
1087                synchronize_srcu(&dquot_srcu);
1088                put_dquot_list(&tofree_head);
1089        }
1090}
1091
1092static inline
1093void dquot_free_reserved_space(struct dquot *dquot, qsize_t number)
1094{
1095        if (dquot->dq_dqb.dqb_rsvspace >= number)
1096                dquot->dq_dqb.dqb_rsvspace -= number;
1097        else {
1098                WARN_ON_ONCE(1);
1099                dquot->dq_dqb.dqb_rsvspace = 0;
1100        }
1101        if (dquot->dq_dqb.dqb_curspace + dquot->dq_dqb.dqb_rsvspace <=
1102            dquot->dq_dqb.dqb_bsoftlimit)
1103                dquot->dq_dqb.dqb_btime = (time64_t) 0;
1104        clear_bit(DQ_BLKS_B, &dquot->dq_flags);
1105}
1106
1107static void dquot_decr_inodes(struct dquot *dquot, qsize_t number)
1108{
1109        if (sb_dqopt(dquot->dq_sb)->flags & DQUOT_NEGATIVE_USAGE ||
1110            dquot->dq_dqb.dqb_curinodes >= number)
1111                dquot->dq_dqb.dqb_curinodes -= number;
1112        else
1113                dquot->dq_dqb.dqb_curinodes = 0;
1114        if (dquot->dq_dqb.dqb_curinodes <= dquot->dq_dqb.dqb_isoftlimit)
1115                dquot->dq_dqb.dqb_itime = (time64_t) 0;
1116        clear_bit(DQ_INODES_B, &dquot->dq_flags);
1117}
1118
1119static void dquot_decr_space(struct dquot *dquot, qsize_t number)
1120{
1121        if (sb_dqopt(dquot->dq_sb)->flags & DQUOT_NEGATIVE_USAGE ||
1122            dquot->dq_dqb.dqb_curspace >= number)
1123                dquot->dq_dqb.dqb_curspace -= number;
1124        else
1125                dquot->dq_dqb.dqb_curspace = 0;
1126        if (dquot->dq_dqb.dqb_curspace + dquot->dq_dqb.dqb_rsvspace <=
1127            dquot->dq_dqb.dqb_bsoftlimit)
1128                dquot->dq_dqb.dqb_btime = (time64_t) 0;
1129        clear_bit(DQ_BLKS_B, &dquot->dq_flags);
1130}
1131
1132struct dquot_warn {
1133        struct super_block *w_sb;
1134        struct kqid w_dq_id;
1135        short w_type;
1136};
1137
1138static int warning_issued(struct dquot *dquot, const int warntype)
1139{
1140        int flag = (warntype == QUOTA_NL_BHARDWARN ||
1141                warntype == QUOTA_NL_BSOFTLONGWARN) ? DQ_BLKS_B :
1142                ((warntype == QUOTA_NL_IHARDWARN ||
1143                warntype == QUOTA_NL_ISOFTLONGWARN) ? DQ_INODES_B : 0);
1144
1145        if (!flag)
1146                return 0;
1147        return test_and_set_bit(flag, &dquot->dq_flags);
1148}
1149
1150#ifdef CONFIG_PRINT_QUOTA_WARNING
1151static int flag_print_warnings = 1;
1152
1153static int need_print_warning(struct dquot_warn *warn)
1154{
1155        if (!flag_print_warnings)
1156                return 0;
1157
1158        switch (warn->w_dq_id.type) {
1159                case USRQUOTA:
1160                        return uid_eq(current_fsuid(), warn->w_dq_id.uid);
1161                case GRPQUOTA:
1162                        return in_group_p(warn->w_dq_id.gid);
1163                case PRJQUOTA:
1164                        return 1;
1165        }
1166        return 0;
1167}
1168
1169/* Print warning to user which exceeded quota */
1170static void print_warning(struct dquot_warn *warn)
1171{
1172        char *msg = NULL;
1173        struct tty_struct *tty;
1174        int warntype = warn->w_type;
1175
1176        if (warntype == QUOTA_NL_IHARDBELOW ||
1177            warntype == QUOTA_NL_ISOFTBELOW ||
1178            warntype == QUOTA_NL_BHARDBELOW ||
1179            warntype == QUOTA_NL_BSOFTBELOW || !need_print_warning(warn))
1180                return;
1181
1182        tty = get_current_tty();
1183        if (!tty)
1184                return;
1185        tty_write_message(tty, warn->w_sb->s_id);
1186        if (warntype == QUOTA_NL_ISOFTWARN || warntype == QUOTA_NL_BSOFTWARN)
1187                tty_write_message(tty, ": warning, ");
1188        else
1189                tty_write_message(tty, ": write failed, ");
1190        tty_write_message(tty, quotatypes[warn->w_dq_id.type]);
1191        switch (warntype) {
1192                case QUOTA_NL_IHARDWARN:
1193                        msg = " file limit reached.\r\n";
1194                        break;
1195                case QUOTA_NL_ISOFTLONGWARN:
1196                        msg = " file quota exceeded too long.\r\n";
1197                        break;
1198                case QUOTA_NL_ISOFTWARN:
1199                        msg = " file quota exceeded.\r\n";
1200                        break;
1201                case QUOTA_NL_BHARDWARN:
1202                        msg = " block limit reached.\r\n";
1203                        break;
1204                case QUOTA_NL_BSOFTLONGWARN:
1205                        msg = " block quota exceeded too long.\r\n";
1206                        break;
1207                case QUOTA_NL_BSOFTWARN:
1208                        msg = " block quota exceeded.\r\n";
1209                        break;
1210        }
1211        tty_write_message(tty, msg);
1212        tty_kref_put(tty);
1213}
1214#endif
1215
1216static void prepare_warning(struct dquot_warn *warn, struct dquot *dquot,
1217                            int warntype)
1218{
1219        if (warning_issued(dquot, warntype))
1220                return;
1221        warn->w_type = warntype;
1222        warn->w_sb = dquot->dq_sb;
1223        warn->w_dq_id = dquot->dq_id;
1224}
1225
1226/*
1227 * Write warnings to the console and send warning messages over netlink.
1228 *
1229 * Note that this function can call into tty and networking code.
1230 */
1231static void flush_warnings(struct dquot_warn *warn)
1232{
1233        int i;
1234
1235        for (i = 0; i < MAXQUOTAS; i++) {
1236                if (warn[i].w_type == QUOTA_NL_NOWARN)
1237                        continue;
1238#ifdef CONFIG_PRINT_QUOTA_WARNING
1239                print_warning(&warn[i]);
1240#endif
1241                quota_send_warning(warn[i].w_dq_id,
1242                                   warn[i].w_sb->s_dev, warn[i].w_type);
1243        }
1244}
1245
1246static int ignore_hardlimit(struct dquot *dquot)
1247{
1248        struct mem_dqinfo *info = &sb_dqopt(dquot->dq_sb)->info[dquot->dq_id.type];
1249
1250        return capable(CAP_SYS_RESOURCE) &&
1251               (info->dqi_format->qf_fmt_id != QFMT_VFS_OLD ||
1252                !(info->dqi_flags & DQF_ROOT_SQUASH));
1253}
1254
1255static int dquot_add_inodes(struct dquot *dquot, qsize_t inodes,
1256                            struct dquot_warn *warn)
1257{
1258        qsize_t newinodes;
1259        int ret = 0;
1260
1261        spin_lock(&dquot->dq_dqb_lock);
1262        newinodes = dquot->dq_dqb.dqb_curinodes + inodes;
1263        if (!sb_has_quota_limits_enabled(dquot->dq_sb, dquot->dq_id.type) ||
1264            test_bit(DQ_FAKE_B, &dquot->dq_flags))
1265                goto add;
1266
1267        if (dquot->dq_dqb.dqb_ihardlimit &&
1268            newinodes > dquot->dq_dqb.dqb_ihardlimit &&
1269            !ignore_hardlimit(dquot)) {
1270                prepare_warning(warn, dquot, QUOTA_NL_IHARDWARN);
1271                ret = -EDQUOT;
1272                goto out;
1273        }
1274
1275        if (dquot->dq_dqb.dqb_isoftlimit &&
1276            newinodes > dquot->dq_dqb.dqb_isoftlimit &&
1277            dquot->dq_dqb.dqb_itime &&
1278            ktime_get_real_seconds() >= dquot->dq_dqb.dqb_itime &&
1279            !ignore_hardlimit(dquot)) {
1280                prepare_warning(warn, dquot, QUOTA_NL_ISOFTLONGWARN);
1281                ret = -EDQUOT;
1282                goto out;
1283        }
1284
1285        if (dquot->dq_dqb.dqb_isoftlimit &&
1286            newinodes > dquot->dq_dqb.dqb_isoftlimit &&
1287            dquot->dq_dqb.dqb_itime == 0) {
1288                prepare_warning(warn, dquot, QUOTA_NL_ISOFTWARN);
1289                dquot->dq_dqb.dqb_itime = ktime_get_real_seconds() +
1290                    sb_dqopt(dquot->dq_sb)->info[dquot->dq_id.type].dqi_igrace;
1291        }
1292add:
1293        dquot->dq_dqb.dqb_curinodes = newinodes;
1294
1295out:
1296        spin_unlock(&dquot->dq_dqb_lock);
1297        return ret;
1298}
1299
1300static int dquot_add_space(struct dquot *dquot, qsize_t space,
1301                           qsize_t rsv_space, unsigned int flags,
1302                           struct dquot_warn *warn)
1303{
1304        qsize_t tspace;
1305        struct super_block *sb = dquot->dq_sb;
1306        int ret = 0;
1307
1308        spin_lock(&dquot->dq_dqb_lock);
1309        if (!sb_has_quota_limits_enabled(sb, dquot->dq_id.type) ||
1310            test_bit(DQ_FAKE_B, &dquot->dq_flags))
1311                goto finish;
1312
1313        tspace = dquot->dq_dqb.dqb_curspace + dquot->dq_dqb.dqb_rsvspace
1314                + space + rsv_space;
1315
1316        if (dquot->dq_dqb.dqb_bhardlimit &&
1317            tspace > dquot->dq_dqb.dqb_bhardlimit &&
1318            !ignore_hardlimit(dquot)) {
1319                if (flags & DQUOT_SPACE_WARN)
1320                        prepare_warning(warn, dquot, QUOTA_NL_BHARDWARN);
1321                ret = -EDQUOT;
1322                goto finish;
1323        }
1324
1325        if (dquot->dq_dqb.dqb_bsoftlimit &&
1326            tspace > dquot->dq_dqb.dqb_bsoftlimit &&
1327            dquot->dq_dqb.dqb_btime &&
1328            ktime_get_real_seconds() >= dquot->dq_dqb.dqb_btime &&
1329            !ignore_hardlimit(dquot)) {
1330                if (flags & DQUOT_SPACE_WARN)
1331                        prepare_warning(warn, dquot, QUOTA_NL_BSOFTLONGWARN);
1332                ret = -EDQUOT;
1333                goto finish;
1334        }
1335
1336        if (dquot->dq_dqb.dqb_bsoftlimit &&
1337            tspace > dquot->dq_dqb.dqb_bsoftlimit &&
1338            dquot->dq_dqb.dqb_btime == 0) {
1339                if (flags & DQUOT_SPACE_WARN) {
1340                        prepare_warning(warn, dquot, QUOTA_NL_BSOFTWARN);
1341                        dquot->dq_dqb.dqb_btime = ktime_get_real_seconds() +
1342                            sb_dqopt(sb)->info[dquot->dq_id.type].dqi_bgrace;
1343                } else {
1344                        /*
1345                         * We don't allow preallocation to exceed softlimit so exceeding will
1346                         * be always printed
1347                         */
1348                        ret = -EDQUOT;
1349                        goto finish;
1350                }
1351        }
1352finish:
1353        /*
1354         * We have to be careful and go through warning generation & grace time
1355         * setting even if DQUOT_SPACE_NOFAIL is set. That's why we check it
1356         * only here...
1357         */
1358        if (flags & DQUOT_SPACE_NOFAIL)
1359                ret = 0;
1360        if (!ret) {
1361                dquot->dq_dqb.dqb_rsvspace += rsv_space;
1362                dquot->dq_dqb.dqb_curspace += space;
1363        }
1364        spin_unlock(&dquot->dq_dqb_lock);
1365        return ret;
1366}
1367
1368static int info_idq_free(struct dquot *dquot, qsize_t inodes)
1369{
1370        qsize_t newinodes;
1371
1372        if (test_bit(DQ_FAKE_B, &dquot->dq_flags) ||
1373            dquot->dq_dqb.dqb_curinodes <= dquot->dq_dqb.dqb_isoftlimit ||
1374            !sb_has_quota_limits_enabled(dquot->dq_sb, dquot->dq_id.type))
1375                return QUOTA_NL_NOWARN;
1376
1377        newinodes = dquot->dq_dqb.dqb_curinodes - inodes;
1378        if (newinodes <= dquot->dq_dqb.dqb_isoftlimit)
1379                return QUOTA_NL_ISOFTBELOW;
1380        if (dquot->dq_dqb.dqb_curinodes >= dquot->dq_dqb.dqb_ihardlimit &&
1381            newinodes < dquot->dq_dqb.dqb_ihardlimit)
1382                return QUOTA_NL_IHARDBELOW;
1383        return QUOTA_NL_NOWARN;
1384}
1385
1386static int info_bdq_free(struct dquot *dquot, qsize_t space)
1387{
1388        qsize_t tspace;
1389
1390        tspace = dquot->dq_dqb.dqb_curspace + dquot->dq_dqb.dqb_rsvspace;
1391
1392        if (test_bit(DQ_FAKE_B, &dquot->dq_flags) ||
1393            tspace <= dquot->dq_dqb.dqb_bsoftlimit)
1394                return QUOTA_NL_NOWARN;
1395
1396        if (tspace - space <= dquot->dq_dqb.dqb_bsoftlimit)
1397                return QUOTA_NL_BSOFTBELOW;
1398        if (tspace >= dquot->dq_dqb.dqb_bhardlimit &&
1399            tspace - space < dquot->dq_dqb.dqb_bhardlimit)
1400                return QUOTA_NL_BHARDBELOW;
1401        return QUOTA_NL_NOWARN;
1402}
1403
1404static int dquot_active(const struct inode *inode)
1405{
1406        struct super_block *sb = inode->i_sb;
1407
1408        if (IS_NOQUOTA(inode))
1409                return 0;
1410        return sb_any_quota_loaded(sb) & ~sb_any_quota_suspended(sb);
1411}
1412
1413/*
1414 * Initialize quota pointers in inode
1415 *
1416 * It is better to call this function outside of any transaction as it
1417 * might need a lot of space in journal for dquot structure allocation.
1418 */
1419static int __dquot_initialize(struct inode *inode, int type)
1420{
1421        int cnt, init_needed = 0;
1422        struct dquot **dquots, *got[MAXQUOTAS] = {};
1423        struct super_block *sb = inode->i_sb;
1424        qsize_t rsv;
1425        int ret = 0;
1426
1427        if (!dquot_active(inode))
1428                return 0;
1429
1430        dquots = i_dquot(inode);
1431
1432        /* First get references to structures we might need. */
1433        for (cnt = 0; cnt < MAXQUOTAS; cnt++) {
1434                struct kqid qid;
1435                kprojid_t projid;
1436                int rc;
1437                struct dquot *dquot;
1438
1439                if (type != -1 && cnt != type)
1440                        continue;
1441                /*
1442                 * The i_dquot should have been initialized in most cases,
1443                 * we check it without locking here to avoid unnecessary
1444                 * dqget()/dqput() calls.
1445                 */
1446                if (dquots[cnt])
1447                        continue;
1448
1449                if (!sb_has_quota_active(sb, cnt))
1450                        continue;
1451
1452                init_needed = 1;
1453
1454                switch (cnt) {
1455                case USRQUOTA:
1456                        qid = make_kqid_uid(inode->i_uid);
1457                        break;
1458                case GRPQUOTA:
1459                        qid = make_kqid_gid(inode->i_gid);
1460                        break;
1461                case PRJQUOTA:
1462                        rc = inode->i_sb->dq_op->get_projid(inode, &projid);
1463                        if (rc)
1464                                continue;
1465                        qid = make_kqid_projid(projid);
1466                        break;
1467                }
1468                dquot = dqget(sb, qid);
1469                if (IS_ERR(dquot)) {
1470                        /* We raced with somebody turning quotas off... */
1471                        if (PTR_ERR(dquot) != -ESRCH) {
1472                                ret = PTR_ERR(dquot);
1473                                goto out_put;
1474                        }
1475                        dquot = NULL;
1476                }
1477                got[cnt] = dquot;
1478        }
1479
1480        /* All required i_dquot has been initialized */
1481        if (!init_needed)
1482                return 0;
1483
1484        spin_lock(&dq_data_lock);
1485        if (IS_NOQUOTA(inode))
1486                goto out_lock;
1487        for (cnt = 0; cnt < MAXQUOTAS; cnt++) {
1488                if (type != -1 && cnt != type)
1489                        continue;
1490                /* Avoid races with quotaoff() */
1491                if (!sb_has_quota_active(sb, cnt))
1492                        continue;
1493                /* We could race with quotaon or dqget() could have failed */
1494                if (!got[cnt])
1495                        continue;
1496                if (!dquots[cnt]) {
1497                        dquots[cnt] = got[cnt];
1498                        got[cnt] = NULL;
1499                        /*
1500                         * Make quota reservation system happy if someone
1501                         * did a write before quota was turned on
1502                         */
1503                        rsv = inode_get_rsv_space(inode);
1504                        if (unlikely(rsv)) {
1505                                spin_lock(&inode->i_lock);
1506                                /* Get reservation again under proper lock */
1507                                rsv = __inode_get_rsv_space(inode);
1508                                spin_lock(&dquots[cnt]->dq_dqb_lock);
1509                                dquots[cnt]->dq_dqb.dqb_rsvspace += rsv;
1510                                spin_unlock(&dquots[cnt]->dq_dqb_lock);
1511                                spin_unlock(&inode->i_lock);
1512                        }
1513                }
1514        }
1515out_lock:
1516        spin_unlock(&dq_data_lock);
1517out_put:
1518        /* Drop unused references */
1519        dqput_all(got);
1520
1521        return ret;
1522}
1523
1524int dquot_initialize(struct inode *inode)
1525{
1526        return __dquot_initialize(inode, -1);
1527}
1528EXPORT_SYMBOL(dquot_initialize);
1529
1530bool dquot_initialize_needed(struct inode *inode)
1531{
1532        struct dquot **dquots;
1533        int i;
1534
1535        if (!dquot_active(inode))
1536                return false;
1537
1538        dquots = i_dquot(inode);
1539        for (i = 0; i < MAXQUOTAS; i++)
1540                if (!dquots[i] && sb_has_quota_active(inode->i_sb, i))
1541                        return true;
1542        return false;
1543}
1544EXPORT_SYMBOL(dquot_initialize_needed);
1545
1546/*
1547 * Release all quotas referenced by inode.
1548 *
1549 * This function only be called on inode free or converting
1550 * a file to quota file, no other users for the i_dquot in
1551 * both cases, so we needn't call synchronize_srcu() after
1552 * clearing i_dquot.
1553 */
1554static void __dquot_drop(struct inode *inode)
1555{
1556        int cnt;
1557        struct dquot **dquots = i_dquot(inode);
1558        struct dquot *put[MAXQUOTAS];
1559
1560        spin_lock(&dq_data_lock);
1561        for (cnt = 0; cnt < MAXQUOTAS; cnt++) {
1562                put[cnt] = dquots[cnt];
1563                dquots[cnt] = NULL;
1564        }
1565        spin_unlock(&dq_data_lock);
1566        dqput_all(put);
1567}
1568
1569void dquot_drop(struct inode *inode)
1570{
1571        struct dquot * const *dquots;
1572        int cnt;
1573
1574        if (IS_NOQUOTA(inode))
1575                return;
1576
1577        /*
1578         * Test before calling to rule out calls from proc and such
1579         * where we are not allowed to block. Note that this is
1580         * actually reliable test even without the lock - the caller
1581         * must assure that nobody can come after the DQUOT_DROP and
1582         * add quota pointers back anyway.
1583         */
1584        dquots = i_dquot(inode);
1585        for (cnt = 0; cnt < MAXQUOTAS; cnt++) {
1586                if (dquots[cnt])
1587                        break;
1588        }
1589
1590        if (cnt < MAXQUOTAS)
1591                __dquot_drop(inode);
1592}
1593EXPORT_SYMBOL(dquot_drop);
1594
1595/*
1596 * inode_reserved_space is managed internally by quota, and protected by
1597 * i_lock similar to i_blocks+i_bytes.
1598 */
1599static qsize_t *inode_reserved_space(struct inode * inode)
1600{
1601        /* Filesystem must explicitly define it's own method in order to use
1602         * quota reservation interface */
1603        BUG_ON(!inode->i_sb->dq_op->get_reserved_space);
1604        return inode->i_sb->dq_op->get_reserved_space(inode);
1605}
1606
1607static qsize_t __inode_get_rsv_space(struct inode *inode)
1608{
1609        if (!inode->i_sb->dq_op->get_reserved_space)
1610                return 0;
1611        return *inode_reserved_space(inode);
1612}
1613
1614static qsize_t inode_get_rsv_space(struct inode *inode)
1615{
1616        qsize_t ret;
1617
1618        if (!inode->i_sb->dq_op->get_reserved_space)
1619                return 0;
1620        spin_lock(&inode->i_lock);
1621        ret = __inode_get_rsv_space(inode);
1622        spin_unlock(&inode->i_lock);
1623        return ret;
1624}
1625
1626/*
1627 * This functions updates i_blocks+i_bytes fields and quota information
1628 * (together with appropriate checks).
1629 *
1630 * NOTE: We absolutely rely on the fact that caller dirties the inode
1631 * (usually helpers in quotaops.h care about this) and holds a handle for
1632 * the current transaction so that dquot write and inode write go into the
1633 * same transaction.
1634 */
1635
1636/*
1637 * This operation can block, but only after everything is updated
1638 */
1639int __dquot_alloc_space(struct inode *inode, qsize_t number, int flags)
1640{
1641        int cnt, ret = 0, index;
1642        struct dquot_warn warn[MAXQUOTAS];
1643        int reserve = flags & DQUOT_SPACE_RESERVE;
1644        struct dquot **dquots;
1645
1646        if (!dquot_active(inode)) {
1647                if (reserve) {
1648                        spin_lock(&inode->i_lock);
1649                        *inode_reserved_space(inode) += number;
1650                        spin_unlock(&inode->i_lock);
1651                } else {
1652                        inode_add_bytes(inode, number);
1653                }
1654                goto out;
1655        }
1656
1657        for (cnt = 0; cnt < MAXQUOTAS; cnt++)
1658                warn[cnt].w_type = QUOTA_NL_NOWARN;
1659
1660        dquots = i_dquot(inode);
1661        index = srcu_read_lock(&dquot_srcu);
1662        spin_lock(&inode->i_lock);
1663        for (cnt = 0; cnt < MAXQUOTAS; cnt++) {
1664                if (!dquots[cnt])
1665                        continue;
1666                if (flags & DQUOT_SPACE_RESERVE) {
1667                        ret = dquot_add_space(dquots[cnt], 0, number, flags,
1668                                              &warn[cnt]);
1669                } else {
1670                        ret = dquot_add_space(dquots[cnt], number, 0, flags,
1671                                              &warn[cnt]);
1672                }
1673                if (ret) {
1674                        /* Back out changes we already did */
1675                        for (cnt--; cnt >= 0; cnt--) {
1676                                if (!dquots[cnt])
1677                                        continue;
1678                                spin_lock(&dquots[cnt]->dq_dqb_lock);
1679                                if (flags & DQUOT_SPACE_RESERVE) {
1680                                        dquots[cnt]->dq_dqb.dqb_rsvspace -=
1681                                                                        number;
1682                                } else {
1683                                        dquots[cnt]->dq_dqb.dqb_curspace -=
1684                                                                        number;
1685                                }
1686                                spin_unlock(&dquots[cnt]->dq_dqb_lock);
1687                        }
1688                        spin_unlock(&inode->i_lock);
1689                        goto out_flush_warn;
1690                }
1691        }
1692        if (reserve)
1693                *inode_reserved_space(inode) += number;
1694        else
1695                __inode_add_bytes(inode, number);
1696        spin_unlock(&inode->i_lock);
1697
1698        if (reserve)
1699                goto out_flush_warn;
1700        mark_all_dquot_dirty(dquots);
1701out_flush_warn:
1702        srcu_read_unlock(&dquot_srcu, index);
1703        flush_warnings(warn);
1704out:
1705        return ret;
1706}
1707EXPORT_SYMBOL(__dquot_alloc_space);
1708
1709/*
1710 * This operation can block, but only after everything is updated
1711 */
1712int dquot_alloc_inode(struct inode *inode)
1713{
1714        int cnt, ret = 0, index;
1715        struct dquot_warn warn[MAXQUOTAS];
1716        struct dquot * const *dquots;
1717
1718        if (!dquot_active(inode))
1719                return 0;
1720        for (cnt = 0; cnt < MAXQUOTAS; cnt++)
1721                warn[cnt].w_type = QUOTA_NL_NOWARN;
1722
1723        dquots = i_dquot(inode);
1724        index = srcu_read_lock(&dquot_srcu);
1725        spin_lock(&inode->i_lock);
1726        for (cnt = 0; cnt < MAXQUOTAS; cnt++) {
1727                if (!dquots[cnt])
1728                        continue;
1729                ret = dquot_add_inodes(dquots[cnt], 1, &warn[cnt]);
1730                if (ret) {
1731                        for (cnt--; cnt >= 0; cnt--) {
1732                                if (!dquots[cnt])
1733                                        continue;
1734                                /* Back out changes we already did */
1735                                spin_lock(&dquots[cnt]->dq_dqb_lock);
1736                                dquots[cnt]->dq_dqb.dqb_curinodes--;
1737                                spin_unlock(&dquots[cnt]->dq_dqb_lock);
1738                        }
1739                        goto warn_put_all;
1740                }
1741        }
1742
1743warn_put_all:
1744        spin_unlock(&inode->i_lock);
1745        if (ret == 0)
1746                mark_all_dquot_dirty(dquots);
1747        srcu_read_unlock(&dquot_srcu, index);
1748        flush_warnings(warn);
1749        return ret;
1750}
1751EXPORT_SYMBOL(dquot_alloc_inode);
1752
1753/*
1754 * Convert in-memory reserved quotas to real consumed quotas
1755 */
1756int dquot_claim_space_nodirty(struct inode *inode, qsize_t number)
1757{
1758        struct dquot **dquots;
1759        int cnt, index;
1760
1761        if (!dquot_active(inode)) {
1762                spin_lock(&inode->i_lock);
1763                *inode_reserved_space(inode) -= number;
1764                __inode_add_bytes(inode, number);
1765                spin_unlock(&inode->i_lock);
1766                return 0;
1767        }
1768
1769        dquots = i_dquot(inode);
1770        index = srcu_read_lock(&dquot_srcu);
1771        spin_lock(&inode->i_lock);
1772        /* Claim reserved quotas to allocated quotas */
1773        for (cnt = 0; cnt < MAXQUOTAS; cnt++) {
1774                if (dquots[cnt]) {
1775                        struct dquot *dquot = dquots[cnt];
1776
1777                        spin_lock(&dquot->dq_dqb_lock);
1778                        if (WARN_ON_ONCE(dquot->dq_dqb.dqb_rsvspace < number))
1779                                number = dquot->dq_dqb.dqb_rsvspace;
1780                        dquot->dq_dqb.dqb_curspace += number;
1781                        dquot->dq_dqb.dqb_rsvspace -= number;
1782                        spin_unlock(&dquot->dq_dqb_lock);
1783                }
1784        }
1785        /* Update inode bytes */
1786        *inode_reserved_space(inode) -= number;
1787        __inode_add_bytes(inode, number);
1788        spin_unlock(&inode->i_lock);
1789        mark_all_dquot_dirty(dquots);
1790        srcu_read_unlock(&dquot_srcu, index);
1791        return 0;
1792}
1793EXPORT_SYMBOL(dquot_claim_space_nodirty);
1794
1795/*
1796 * Convert allocated space back to in-memory reserved quotas
1797 */
1798void dquot_reclaim_space_nodirty(struct inode *inode, qsize_t number)
1799{
1800        struct dquot **dquots;
1801        int cnt, index;
1802
1803        if (!dquot_active(inode)) {
1804                spin_lock(&inode->i_lock);
1805                *inode_reserved_space(inode) += number;
1806                __inode_sub_bytes(inode, number);
1807                spin_unlock(&inode->i_lock);
1808                return;
1809        }
1810
1811        dquots = i_dquot(inode);
1812        index = srcu_read_lock(&dquot_srcu);
1813        spin_lock(&inode->i_lock);
1814        /* Claim reserved quotas to allocated quotas */
1815        for (cnt = 0; cnt < MAXQUOTAS; cnt++) {
1816                if (dquots[cnt]) {
1817                        struct dquot *dquot = dquots[cnt];
1818
1819                        spin_lock(&dquot->dq_dqb_lock);
1820                        if (WARN_ON_ONCE(dquot->dq_dqb.dqb_curspace < number))
1821                                number = dquot->dq_dqb.dqb_curspace;
1822                        dquot->dq_dqb.dqb_rsvspace += number;
1823                        dquot->dq_dqb.dqb_curspace -= number;
1824                        spin_unlock(&dquot->dq_dqb_lock);
1825                }
1826        }
1827        /* Update inode bytes */
1828        *inode_reserved_space(inode) += number;
1829        __inode_sub_bytes(inode, number);
1830        spin_unlock(&inode->i_lock);
1831        mark_all_dquot_dirty(dquots);
1832        srcu_read_unlock(&dquot_srcu, index);
1833        return;
1834}
1835EXPORT_SYMBOL(dquot_reclaim_space_nodirty);
1836
1837/*
1838 * This operation can block, but only after everything is updated
1839 */
1840void __dquot_free_space(struct inode *inode, qsize_t number, int flags)
1841{
1842        unsigned int cnt;
1843        struct dquot_warn warn[MAXQUOTAS];
1844        struct dquot **dquots;
1845        int reserve = flags & DQUOT_SPACE_RESERVE, index;
1846
1847        if (!dquot_active(inode)) {
1848                if (reserve) {
1849                        spin_lock(&inode->i_lock);
1850                        *inode_reserved_space(inode) -= number;
1851                        spin_unlock(&inode->i_lock);
1852                } else {
1853                        inode_sub_bytes(inode, number);
1854                }
1855                return;
1856        }
1857
1858        dquots = i_dquot(inode);
1859        index = srcu_read_lock(&dquot_srcu);
1860        spin_lock(&inode->i_lock);
1861        for (cnt = 0; cnt < MAXQUOTAS; cnt++) {
1862                int wtype;
1863
1864                warn[cnt].w_type = QUOTA_NL_NOWARN;
1865                if (!dquots[cnt])
1866                        continue;
1867                spin_lock(&dquots[cnt]->dq_dqb_lock);
1868                wtype = info_bdq_free(dquots[cnt], number);
1869                if (wtype != QUOTA_NL_NOWARN)
1870                        prepare_warning(&warn[cnt], dquots[cnt], wtype);
1871                if (reserve)
1872                        dquot_free_reserved_space(dquots[cnt], number);
1873                else
1874                        dquot_decr_space(dquots[cnt], number);
1875                spin_unlock(&dquots[cnt]->dq_dqb_lock);
1876        }
1877        if (reserve)
1878                *inode_reserved_space(inode) -= number;
1879        else
1880                __inode_sub_bytes(inode, number);
1881        spin_unlock(&inode->i_lock);
1882
1883        if (reserve)
1884                goto out_unlock;
1885        mark_all_dquot_dirty(dquots);
1886out_unlock:
1887        srcu_read_unlock(&dquot_srcu, index);
1888        flush_warnings(warn);
1889}
1890EXPORT_SYMBOL(__dquot_free_space);
1891
1892/*
1893 * This operation can block, but only after everything is updated
1894 */
1895void dquot_free_inode(struct inode *inode)
1896{
1897        unsigned int cnt;
1898        struct dquot_warn warn[MAXQUOTAS];
1899        struct dquot * const *dquots;
1900        int index;
1901
1902        if (!dquot_active(inode))
1903                return;
1904
1905        dquots = i_dquot(inode);
1906        index = srcu_read_lock(&dquot_srcu);
1907        spin_lock(&inode->i_lock);
1908        for (cnt = 0; cnt < MAXQUOTAS; cnt++) {
1909                int wtype;
1910
1911                warn[cnt].w_type = QUOTA_NL_NOWARN;
1912                if (!dquots[cnt])
1913                        continue;
1914                spin_lock(&dquots[cnt]->dq_dqb_lock);
1915                wtype = info_idq_free(dquots[cnt], 1);
1916                if (wtype != QUOTA_NL_NOWARN)
1917                        prepare_warning(&warn[cnt], dquots[cnt], wtype);
1918                dquot_decr_inodes(dquots[cnt], 1);
1919                spin_unlock(&dquots[cnt]->dq_dqb_lock);
1920        }
1921        spin_unlock(&inode->i_lock);
1922        mark_all_dquot_dirty(dquots);
1923        srcu_read_unlock(&dquot_srcu, index);
1924        flush_warnings(warn);
1925}
1926EXPORT_SYMBOL(dquot_free_inode);
1927
1928/*
1929 * Transfer the number of inode and blocks from one diskquota to an other.
1930 * On success, dquot references in transfer_to are consumed and references
1931 * to original dquots that need to be released are placed there. On failure,
1932 * references are kept untouched.
1933 *
1934 * This operation can block, but only after everything is updated
1935 * A transaction must be started when entering this function.
1936 *
1937 * We are holding reference on transfer_from & transfer_to, no need to
1938 * protect them by srcu_read_lock().
1939 */
1940int __dquot_transfer(struct inode *inode, struct dquot **transfer_to)
1941{
1942        qsize_t cur_space;
1943        qsize_t rsv_space = 0;
1944        qsize_t inode_usage = 1;
1945        struct dquot *transfer_from[MAXQUOTAS] = {};
1946        int cnt, ret = 0;
1947        char is_valid[MAXQUOTAS] = {};
1948        struct dquot_warn warn_to[MAXQUOTAS];
1949        struct dquot_warn warn_from_inodes[MAXQUOTAS];
1950        struct dquot_warn warn_from_space[MAXQUOTAS];
1951
1952        if (IS_NOQUOTA(inode))
1953                return 0;
1954
1955        if (inode->i_sb->dq_op->get_inode_usage) {
1956                ret = inode->i_sb->dq_op->get_inode_usage(inode, &inode_usage);
1957                if (ret)
1958                        return ret;
1959        }
1960
1961        /* Initialize the arrays */
1962        for (cnt = 0; cnt < MAXQUOTAS; cnt++) {
1963                warn_to[cnt].w_type = QUOTA_NL_NOWARN;
1964                warn_from_inodes[cnt].w_type = QUOTA_NL_NOWARN;
1965                warn_from_space[cnt].w_type = QUOTA_NL_NOWARN;
1966        }
1967
1968        spin_lock(&dq_data_lock);
1969        spin_lock(&inode->i_lock);
1970        if (IS_NOQUOTA(inode)) {        /* File without quota accounting? */
1971                spin_unlock(&inode->i_lock);
1972                spin_unlock(&dq_data_lock);
1973                return 0;
1974        }
1975        cur_space = __inode_get_bytes(inode);
1976        rsv_space = __inode_get_rsv_space(inode);
1977        /*
1978         * Build the transfer_from list, check limits, and update usage in
1979         * the target structures.
1980         */
1981        for (cnt = 0; cnt < MAXQUOTAS; cnt++) {
1982                /*
1983                 * Skip changes for same uid or gid or for turned off quota-type.
1984                 */
1985                if (!transfer_to[cnt])
1986                        continue;
1987                /* Avoid races with quotaoff() */
1988                if (!sb_has_quota_active(inode->i_sb, cnt))
1989                        continue;
1990                is_valid[cnt] = 1;
1991                transfer_from[cnt] = i_dquot(inode)[cnt];
1992                ret = dquot_add_inodes(transfer_to[cnt], inode_usage,
1993                                       &warn_to[cnt]);
1994                if (ret)
1995                        goto over_quota;
1996                ret = dquot_add_space(transfer_to[cnt], cur_space, rsv_space, 0,
1997                                      &warn_to[cnt]);
1998                if (ret) {
1999                        spin_lock(&transfer_to[cnt]->dq_dqb_lock);
2000                        dquot_decr_inodes(transfer_to[cnt], inode_usage);
2001                        spin_unlock(&transfer_to[cnt]->dq_dqb_lock);
2002                        goto over_quota;
2003                }
2004        }
2005
2006        /* Decrease usage for source structures and update quota pointers */
2007        for (cnt = 0; cnt < MAXQUOTAS; cnt++) {
2008                if (!is_valid[cnt])
2009                        continue;
2010                /* Due to IO error we might not have transfer_from[] structure */
2011                if (transfer_from[cnt]) {
2012                        int wtype;
2013
2014                        spin_lock(&transfer_from[cnt]->dq_dqb_lock);
2015                        wtype = info_idq_free(transfer_from[cnt], inode_usage);
2016                        if (wtype != QUOTA_NL_NOWARN)
2017                                prepare_warning(&warn_from_inodes[cnt],
2018                                                transfer_from[cnt], wtype);
2019                        wtype = info_bdq_free(transfer_from[cnt],
2020                                              cur_space + rsv_space);
2021                        if (wtype != QUOTA_NL_NOWARN)
2022                                prepare_warning(&warn_from_space[cnt],
2023                                                transfer_from[cnt], wtype);
2024                        dquot_decr_inodes(transfer_from[cnt], inode_usage);
2025                        dquot_decr_space(transfer_from[cnt], cur_space);
2026                        dquot_free_reserved_space(transfer_from[cnt],
2027                                                  rsv_space);
2028                        spin_unlock(&transfer_from[cnt]->dq_dqb_lock);
2029                }
2030                i_dquot(inode)[cnt] = transfer_to[cnt];
2031        }
2032        spin_unlock(&inode->i_lock);
2033        spin_unlock(&dq_data_lock);
2034
2035        mark_all_dquot_dirty(transfer_from);
2036        mark_all_dquot_dirty(transfer_to);
2037        flush_warnings(warn_to);
2038        flush_warnings(warn_from_inodes);
2039        flush_warnings(warn_from_space);
2040        /* Pass back references to put */
2041        for (cnt = 0; cnt < MAXQUOTAS; cnt++)
2042                if (is_valid[cnt])
2043                        transfer_to[cnt] = transfer_from[cnt];
2044        return 0;
2045over_quota:
2046        /* Back out changes we already did */
2047        for (cnt--; cnt >= 0; cnt--) {
2048                if (!is_valid[cnt])
2049                        continue;
2050                spin_lock(&transfer_to[cnt]->dq_dqb_lock);
2051                dquot_decr_inodes(transfer_to[cnt], inode_usage);
2052                dquot_decr_space(transfer_to[cnt], cur_space);
2053                dquot_free_reserved_space(transfer_to[cnt], rsv_space);
2054                spin_unlock(&transfer_to[cnt]->dq_dqb_lock);
2055        }
2056        spin_unlock(&inode->i_lock);
2057        spin_unlock(&dq_data_lock);
2058        flush_warnings(warn_to);
2059        return ret;
2060}
2061EXPORT_SYMBOL(__dquot_transfer);
2062
2063/* Wrapper for transferring ownership of an inode for uid/gid only
2064 * Called from FSXXX_setattr()
2065 */
2066int dquot_transfer(struct inode *inode, struct iattr *iattr)
2067{
2068        struct dquot *transfer_to[MAXQUOTAS] = {};
2069        struct dquot *dquot;
2070        struct super_block *sb = inode->i_sb;
2071        int ret;
2072
2073        if (!dquot_active(inode))
2074                return 0;
2075
2076        if (iattr->ia_valid & ATTR_UID && !uid_eq(iattr->ia_uid, inode->i_uid)){
2077                dquot = dqget(sb, make_kqid_uid(iattr->ia_uid));
2078                if (IS_ERR(dquot)) {
2079                        if (PTR_ERR(dquot) != -ESRCH) {
2080                                ret = PTR_ERR(dquot);
2081                                goto out_put;
2082                        }
2083                        dquot = NULL;
2084                }
2085                transfer_to[USRQUOTA] = dquot;
2086        }
2087        if (iattr->ia_valid & ATTR_GID && !gid_eq(iattr->ia_gid, inode->i_gid)){
2088                dquot = dqget(sb, make_kqid_gid(iattr->ia_gid));
2089                if (IS_ERR(dquot)) {
2090                        if (PTR_ERR(dquot) != -ESRCH) {
2091                                ret = PTR_ERR(dquot);
2092                                goto out_put;
2093                        }
2094                        dquot = NULL;
2095                }
2096                transfer_to[GRPQUOTA] = dquot;
2097        }
2098        ret = __dquot_transfer(inode, transfer_to);
2099out_put:
2100        dqput_all(transfer_to);
2101        return ret;
2102}
2103EXPORT_SYMBOL(dquot_transfer);
2104
2105/*
2106 * Write info of quota file to disk
2107 */
2108int dquot_commit_info(struct super_block *sb, int type)
2109{
2110        struct quota_info *dqopt = sb_dqopt(sb);
2111
2112        return dqopt->ops[type]->write_file_info(sb, type);
2113}
2114EXPORT_SYMBOL(dquot_commit_info);
2115
2116int dquot_get_next_id(struct super_block *sb, struct kqid *qid)
2117{
2118        struct quota_info *dqopt = sb_dqopt(sb);
2119
2120        if (!sb_has_quota_active(sb, qid->type))
2121                return -ESRCH;
2122        if (!dqopt->ops[qid->type]->get_next_id)
2123                return -ENOSYS;
2124        return dqopt->ops[qid->type]->get_next_id(sb, qid);
2125}
2126EXPORT_SYMBOL(dquot_get_next_id);
2127
2128/*
2129 * Definitions of diskquota operations.
2130 */
2131const struct dquot_operations dquot_operations = {
2132        .write_dquot    = dquot_commit,
2133        .acquire_dquot  = dquot_acquire,
2134        .release_dquot  = dquot_release,
2135        .mark_dirty     = dquot_mark_dquot_dirty,
2136        .write_info     = dquot_commit_info,
2137        .alloc_dquot    = dquot_alloc,
2138        .destroy_dquot  = dquot_destroy,
2139        .get_next_id    = dquot_get_next_id,
2140};
2141EXPORT_SYMBOL(dquot_operations);
2142
2143/*
2144 * Generic helper for ->open on filesystems supporting disk quotas.
2145 */
2146int dquot_file_open(struct inode *inode, struct file *file)
2147{
2148        int error;
2149
2150        error = generic_file_open(inode, file);
2151        if (!error && (file->f_mode & FMODE_WRITE))
2152                error = dquot_initialize(inode);
2153        return error;
2154}
2155EXPORT_SYMBOL(dquot_file_open);
2156
2157/*
2158 * Turn quota off on a device. type == -1 ==> quotaoff for all types (umount)
2159 */
2160int dquot_disable(struct super_block *sb, int type, unsigned int flags)
2161{
2162        int cnt, ret = 0;
2163        struct quota_info *dqopt = sb_dqopt(sb);
2164        struct inode *toputinode[MAXQUOTAS];
2165
2166        /* s_umount should be held in exclusive mode */
2167        if (WARN_ON_ONCE(down_read_trylock(&sb->s_umount)))
2168                up_read(&sb->s_umount);
2169
2170        /* Cannot turn off usage accounting without turning off limits, or
2171         * suspend quotas and simultaneously turn quotas off. */
2172        if ((flags & DQUOT_USAGE_ENABLED && !(flags & DQUOT_LIMITS_ENABLED))
2173            || (flags & DQUOT_SUSPENDED && flags & (DQUOT_LIMITS_ENABLED |
2174            DQUOT_USAGE_ENABLED)))
2175                return -EINVAL;
2176
2177        /*
2178         * Skip everything if there's nothing to do. We have to do this because
2179         * sometimes we are called when fill_super() failed and calling
2180         * sync_fs() in such cases does no good.
2181         */
2182        if (!sb_any_quota_loaded(sb))
2183                return 0;
2184
2185        for (cnt = 0; cnt < MAXQUOTAS; cnt++) {
2186                toputinode[cnt] = NULL;
2187                if (type != -1 && cnt != type)
2188                        continue;
2189                if (!sb_has_quota_loaded(sb, cnt))
2190                        continue;
2191
2192                if (flags & DQUOT_SUSPENDED) {
2193                        spin_lock(&dq_state_lock);
2194                        dqopt->flags |=
2195                                dquot_state_flag(DQUOT_SUSPENDED, cnt);
2196                        spin_unlock(&dq_state_lock);
2197                } else {
2198                        spin_lock(&dq_state_lock);
2199                        dqopt->flags &= ~dquot_state_flag(flags, cnt);
2200                        /* Turning off suspended quotas? */
2201                        if (!sb_has_quota_loaded(sb, cnt) &&
2202                            sb_has_quota_suspended(sb, cnt)) {
2203                                dqopt->flags &= ~dquot_state_flag(
2204                                                        DQUOT_SUSPENDED, cnt);
2205                                spin_unlock(&dq_state_lock);
2206                                iput(dqopt->files[cnt]);
2207                                dqopt->files[cnt] = NULL;
2208                                continue;
2209                        }
2210                        spin_unlock(&dq_state_lock);
2211                }
2212
2213                /* We still have to keep quota loaded? */
2214                if (sb_has_quota_loaded(sb, cnt) && !(flags & DQUOT_SUSPENDED))
2215                        continue;
2216
2217                /* Note: these are blocking operations */
2218                drop_dquot_ref(sb, cnt);
2219                invalidate_dquots(sb, cnt);
2220                /*
2221                 * Now all dquots should be invalidated, all writes done so we
2222                 * should be only users of the info. No locks needed.
2223                 */
2224                if (info_dirty(&dqopt->info[cnt]))
2225                        sb->dq_op->write_info(sb, cnt);
2226                if (dqopt->ops[cnt]->free_file_info)
2227                        dqopt->ops[cnt]->free_file_info(sb, cnt);
2228                put_quota_format(dqopt->info[cnt].dqi_format);
2229
2230                toputinode[cnt] = dqopt->files[cnt];
2231                if (!sb_has_quota_loaded(sb, cnt))
2232                        dqopt->files[cnt] = NULL;
2233                dqopt->info[cnt].dqi_flags = 0;
2234                dqopt->info[cnt].dqi_igrace = 0;
2235                dqopt->info[cnt].dqi_bgrace = 0;
2236                dqopt->ops[cnt] = NULL;
2237        }
2238
2239        /* Skip syncing and setting flags if quota files are hidden */
2240        if (dqopt->flags & DQUOT_QUOTA_SYS_FILE)
2241                goto put_inodes;
2242
2243        /* Sync the superblock so that buffers with quota data are written to
2244         * disk (and so userspace sees correct data afterwards). */
2245        if (sb->s_op->sync_fs)
2246                sb->s_op->sync_fs(sb, 1);
2247        sync_blockdev(sb->s_bdev);
2248        /* Now the quota files are just ordinary files and we can set the
2249         * inode flags back. Moreover we discard the pagecache so that
2250         * userspace sees the writes we did bypassing the pagecache. We
2251         * must also discard the blockdev buffers so that we see the
2252         * changes done by userspace on the next quotaon() */
2253        for (cnt = 0; cnt < MAXQUOTAS; cnt++)
2254                /* This can happen when suspending quotas on remount-ro... */
2255                if (toputinode[cnt] && !sb_has_quota_loaded(sb, cnt)) {
2256                        inode_lock(toputinode[cnt]);
2257                        toputinode[cnt]->i_flags &= ~S_NOQUOTA;
2258                        truncate_inode_pages(&toputinode[cnt]->i_data, 0);
2259                        inode_unlock(toputinode[cnt]);
2260                        mark_inode_dirty_sync(toputinode[cnt]);
2261                }
2262        if (sb->s_bdev)
2263                invalidate_bdev(sb->s_bdev);
2264put_inodes:
2265        for (cnt = 0; cnt < MAXQUOTAS; cnt++)
2266                if (toputinode[cnt]) {
2267                        /* On remount RO, we keep the inode pointer so that we
2268                         * can reenable quota on the subsequent remount RW. We
2269                         * have to check 'flags' variable and not use sb_has_
2270                         * function because another quotaon / quotaoff could
2271                         * change global state before we got here. We refuse
2272                         * to suspend quotas when there is pending delete on
2273                         * the quota file... */
2274                        if (!(flags & DQUOT_SUSPENDED))
2275                                iput(toputinode[cnt]);
2276                        else if (!toputinode[cnt]->i_nlink)
2277                                ret = -EBUSY;
2278                }
2279        return ret;
2280}
2281EXPORT_SYMBOL(dquot_disable);
2282
2283int dquot_quota_off(struct super_block *sb, int type)
2284{
2285        return dquot_disable(sb, type,
2286                             DQUOT_USAGE_ENABLED | DQUOT_LIMITS_ENABLED);
2287}
2288EXPORT_SYMBOL(dquot_quota_off);
2289
2290/*
2291 *      Turn quotas on on a device
2292 */
2293
2294/*
2295 * Helper function to turn quotas on when we already have the inode of
2296 * quota file and no quota information is loaded.
2297 */
2298static int vfs_load_quota_inode(struct inode *inode, int type, int format_id,
2299        unsigned int flags)
2300{
2301        struct quota_format_type *fmt = find_quota_format(format_id);
2302        struct super_block *sb = inode->i_sb;
2303        struct quota_info *dqopt = sb_dqopt(sb);
2304        int error;
2305
2306        if (!fmt)
2307                return -ESRCH;
2308        if (!S_ISREG(inode->i_mode)) {
2309                error = -EACCES;
2310                goto out_fmt;
2311        }
2312        if (IS_RDONLY(inode)) {
2313                error = -EROFS;
2314                goto out_fmt;
2315        }
2316        if (!sb->s_op->quota_write || !sb->s_op->quota_read ||
2317            (type == PRJQUOTA && sb->dq_op->get_projid == NULL)) {
2318                error = -EINVAL;
2319                goto out_fmt;
2320        }
2321        /* Filesystems outside of init_user_ns not yet supported */
2322        if (sb->s_user_ns != &init_user_ns) {
2323                error = -EINVAL;
2324                goto out_fmt;
2325        }
2326        /* Usage always has to be set... */
2327        if (!(flags & DQUOT_USAGE_ENABLED)) {
2328                error = -EINVAL;
2329                goto out_fmt;
2330        }
2331        if (sb_has_quota_loaded(sb, type)) {
2332                error = -EBUSY;
2333                goto out_fmt;
2334        }
2335
2336        if (!(dqopt->flags & DQUOT_QUOTA_SYS_FILE)) {
2337                /* As we bypass the pagecache we must now flush all the
2338                 * dirty data and invalidate caches so that kernel sees
2339                 * changes from userspace. It is not enough to just flush
2340                 * the quota file since if blocksize < pagesize, invalidation
2341                 * of the cache could fail because of other unrelated dirty
2342                 * data */
2343                sync_filesystem(sb);
2344                invalidate_bdev(sb->s_bdev);
2345        }
2346
2347        if (!(dqopt->flags & DQUOT_QUOTA_SYS_FILE)) {
2348                /* We don't want quota and atime on quota files (deadlocks
2349                 * possible) Also nobody should write to the file - we use
2350                 * special IO operations which ignore the immutable bit. */
2351                inode_lock(inode);
2352                inode->i_flags |= S_NOQUOTA;
2353                inode_unlock(inode);
2354                /*
2355                 * When S_NOQUOTA is set, remove dquot references as no more
2356                 * references can be added
2357                 */
2358                __dquot_drop(inode);
2359        }
2360
2361        error = -EIO;
2362        dqopt->files[type] = igrab(inode);
2363        if (!dqopt->files[type])
2364                goto out_file_flags;
2365        error = -EINVAL;
2366        if (!fmt->qf_ops->check_quota_file(sb, type))
2367                goto out_file_init;
2368
2369        dqopt->ops[type] = fmt->qf_ops;
2370        dqopt->info[type].dqi_format = fmt;
2371        dqopt->info[type].dqi_fmt_id = format_id;
2372        INIT_LIST_HEAD(&dqopt->info[type].dqi_dirty_list);
2373        error = dqopt->ops[type]->read_file_info(sb, type);
2374        if (error < 0)
2375                goto out_file_init;
2376        if (dqopt->flags & DQUOT_QUOTA_SYS_FILE) {
2377                spin_lock(&dq_data_lock);
2378                dqopt->info[type].dqi_flags |= DQF_SYS_FILE;
2379                spin_unlock(&dq_data_lock);
2380        }
2381        spin_lock(&dq_state_lock);
2382        dqopt->flags |= dquot_state_flag(flags, type);
2383        spin_unlock(&dq_state_lock);
2384
2385        error = add_dquot_ref(sb, type);
2386        if (error)
2387                dquot_disable(sb, type, flags);
2388
2389        return error;
2390out_file_init:
2391        dqopt->files[type] = NULL;
2392        iput(inode);
2393out_file_flags:
2394        inode_lock(inode);
2395        inode->i_flags &= ~S_NOQUOTA;
2396        inode_unlock(inode);
2397out_fmt:
2398        put_quota_format(fmt);
2399
2400        return error; 
2401}
2402
2403/* Reenable quotas on remount RW */
2404int dquot_resume(struct super_block *sb, int type)
2405{
2406        struct quota_info *dqopt = sb_dqopt(sb);
2407        struct inode *inode;
2408        int ret = 0, cnt;
2409        unsigned int flags;
2410
2411        /* s_umount should be held in exclusive mode */
2412        if (WARN_ON_ONCE(down_read_trylock(&sb->s_umount)))
2413                up_read(&sb->s_umount);
2414
2415        for (cnt = 0; cnt < MAXQUOTAS; cnt++) {
2416                if (type != -1 && cnt != type)
2417                        continue;
2418                if (!sb_has_quota_suspended(sb, cnt))
2419                        continue;
2420
2421                inode = dqopt->files[cnt];
2422                dqopt->files[cnt] = NULL;
2423                spin_lock(&dq_state_lock);
2424                flags = dqopt->flags & dquot_state_flag(DQUOT_USAGE_ENABLED |
2425                                                        DQUOT_LIMITS_ENABLED,
2426                                                        cnt);
2427                dqopt->flags &= ~dquot_state_flag(DQUOT_STATE_FLAGS, cnt);
2428                spin_unlock(&dq_state_lock);
2429
2430                flags = dquot_generic_flag(flags, cnt);
2431                ret = vfs_load_quota_inode(inode, cnt,
2432                                dqopt->info[cnt].dqi_fmt_id, flags);
2433                iput(inode);
2434        }
2435
2436        return ret;
2437}
2438EXPORT_SYMBOL(dquot_resume);
2439
2440int dquot_quota_on(struct super_block *sb, int type, int format_id,
2441                   const struct path *path)
2442{
2443        int error = security_quota_on(path->dentry);
2444        if (error)
2445                return error;
2446        /* Quota file not on the same filesystem? */
2447        if (path->dentry->d_sb != sb)
2448                error = -EXDEV;
2449        else
2450                error = vfs_load_quota_inode(d_inode(path->dentry), type,
2451                                             format_id, DQUOT_USAGE_ENABLED |
2452                                             DQUOT_LIMITS_ENABLED);
2453        return error;
2454}
2455EXPORT_SYMBOL(dquot_quota_on);
2456
2457/*
2458 * More powerful function for turning on quotas allowing setting
2459 * of individual quota flags
2460 */
2461int dquot_enable(struct inode *inode, int type, int format_id,
2462                 unsigned int flags)
2463{
2464        struct super_block *sb = inode->i_sb;
2465
2466        /* Just unsuspend quotas? */
2467        BUG_ON(flags & DQUOT_SUSPENDED);
2468        /* s_umount should be held in exclusive mode */
2469        if (WARN_ON_ONCE(down_read_trylock(&sb->s_umount)))
2470                up_read(&sb->s_umount);
2471
2472        if (!flags)
2473                return 0;
2474        /* Just updating flags needed? */
2475        if (sb_has_quota_loaded(sb, type)) {
2476                if (flags & DQUOT_USAGE_ENABLED &&
2477                    sb_has_quota_usage_enabled(sb, type))
2478                        return -EBUSY;
2479                if (flags & DQUOT_LIMITS_ENABLED &&
2480                    sb_has_quota_limits_enabled(sb, type))
2481                        return -EBUSY;
2482                spin_lock(&dq_state_lock);
2483                sb_dqopt(sb)->flags |= dquot_state_flag(flags, type);
2484                spin_unlock(&dq_state_lock);
2485                return 0;
2486        }
2487
2488        return vfs_load_quota_inode(inode, type, format_id, flags);
2489}
2490EXPORT_SYMBOL(dquot_enable);
2491
2492/*
2493 * This function is used when filesystem needs to initialize quotas
2494 * during mount time.
2495 */
2496int dquot_quota_on_mount(struct super_block *sb, char *qf_name,
2497                int format_id, int type)
2498{
2499        struct dentry *dentry;
2500        int error;
2501
2502        dentry = lookup_one_len_unlocked(qf_name, sb->s_root, strlen(qf_name));
2503        if (IS_ERR(dentry))
2504                return PTR_ERR(dentry);
2505
2506        if (d_really_is_negative(dentry)) {
2507                error = -ENOENT;
2508                goto out;
2509        }
2510
2511        error = security_quota_on(dentry);
2512        if (!error)
2513                error = vfs_load_quota_inode(d_inode(dentry), type, format_id,
2514                                DQUOT_USAGE_ENABLED | DQUOT_LIMITS_ENABLED);
2515
2516out:
2517        dput(dentry);
2518        return error;
2519}
2520EXPORT_SYMBOL(dquot_quota_on_mount);
2521
2522static int dquot_quota_enable(struct super_block *sb, unsigned int flags)
2523{
2524        int ret;
2525        int type;
2526        struct quota_info *dqopt = sb_dqopt(sb);
2527
2528        if (!(dqopt->flags & DQUOT_QUOTA_SYS_FILE))
2529                return -ENOSYS;
2530        /* Accounting cannot be turned on while fs is mounted */
2531        flags &= ~(FS_QUOTA_UDQ_ACCT | FS_QUOTA_GDQ_ACCT | FS_QUOTA_PDQ_ACCT);
2532        if (!flags)
2533                return -EINVAL;
2534        for (type = 0; type < MAXQUOTAS; type++) {
2535                if (!(flags & qtype_enforce_flag(type)))
2536                        continue;
2537                /* Can't enforce without accounting */
2538                if (!sb_has_quota_usage_enabled(sb, type))
2539                        return -EINVAL;
2540                ret = dquot_enable(dqopt->files[type], type,
2541                                   dqopt->info[type].dqi_fmt_id,
2542                                   DQUOT_LIMITS_ENABLED);
2543                if (ret < 0)
2544                        goto out_err;
2545        }
2546        return 0;
2547out_err:
2548        /* Backout enforcement enablement we already did */
2549        for (type--; type >= 0; type--)  {
2550                if (flags & qtype_enforce_flag(type))
2551                        dquot_disable(sb, type, DQUOT_LIMITS_ENABLED);
2552        }
2553        /* Error code translation for better compatibility with XFS */
2554        if (ret == -EBUSY)
2555                ret = -EEXIST;
2556        return ret;
2557}
2558
2559static int dquot_quota_disable(struct super_block *sb, unsigned int flags)
2560{
2561        int ret;
2562        int type;
2563        struct quota_info *dqopt = sb_dqopt(sb);
2564
2565        if (!(dqopt->flags & DQUOT_QUOTA_SYS_FILE))
2566                return -ENOSYS;
2567        /*
2568         * We don't support turning off accounting via quotactl. In principle
2569         * quota infrastructure can do this but filesystems don't expect
2570         * userspace to be able to do it.
2571         */
2572        if (flags &
2573                  (FS_QUOTA_UDQ_ACCT | FS_QUOTA_GDQ_ACCT | FS_QUOTA_PDQ_ACCT))
2574                return -EOPNOTSUPP;
2575
2576        /* Filter out limits not enabled */
2577        for (type = 0; type < MAXQUOTAS; type++)
2578                if (!sb_has_quota_limits_enabled(sb, type))
2579                        flags &= ~qtype_enforce_flag(type);
2580        /* Nothing left? */
2581        if (!flags)
2582                return -EEXIST;
2583        for (type = 0; type < MAXQUOTAS; type++) {
2584                if (flags & qtype_enforce_flag(type)) {
2585                        ret = dquot_disable(sb, type, DQUOT_LIMITS_ENABLED);
2586                        if (ret < 0)
2587                                goto out_err;
2588                }
2589        }
2590        return 0;
2591out_err:
2592        /* Backout enforcement disabling we already did */
2593        for (type--; type >= 0; type--)  {
2594                if (flags & qtype_enforce_flag(type))
2595                        dquot_enable(dqopt->files[type], type,
2596                                     dqopt->info[type].dqi_fmt_id,
2597                                     DQUOT_LIMITS_ENABLED);
2598        }
2599        return ret;
2600}
2601
2602/* Generic routine for getting common part of quota structure */
2603static void do_get_dqblk(struct dquot *dquot, struct qc_dqblk *di)
2604{
2605        struct mem_dqblk *dm = &dquot->dq_dqb;
2606
2607        memset(di, 0, sizeof(*di));
2608        spin_lock(&dquot->dq_dqb_lock);
2609        di->d_spc_hardlimit = dm->dqb_bhardlimit;
2610        di->d_spc_softlimit = dm->dqb_bsoftlimit;
2611        di->d_ino_hardlimit = dm->dqb_ihardlimit;
2612        di->d_ino_softlimit = dm->dqb_isoftlimit;
2613        di->d_space = dm->dqb_curspace + dm->dqb_rsvspace;
2614        di->d_ino_count = dm->dqb_curinodes;
2615        di->d_spc_timer = dm->dqb_btime;
2616        di->d_ino_timer = dm->dqb_itime;
2617        spin_unlock(&dquot->dq_dqb_lock);
2618}
2619
2620int dquot_get_dqblk(struct super_block *sb, struct kqid qid,
2621                    struct qc_dqblk *di)
2622{
2623        struct dquot *dquot;
2624
2625        dquot = dqget(sb, qid);
2626        if (IS_ERR(dquot))
2627                return PTR_ERR(dquot);
2628        do_get_dqblk(dquot, di);
2629        dqput(dquot);
2630
2631        return 0;
2632}
2633EXPORT_SYMBOL(dquot_get_dqblk);
2634
2635int dquot_get_next_dqblk(struct super_block *sb, struct kqid *qid,
2636                         struct qc_dqblk *di)
2637{
2638        struct dquot *dquot;
2639        int err;
2640
2641        if (!sb->dq_op->get_next_id)
2642                return -ENOSYS;
2643        err = sb->dq_op->get_next_id(sb, qid);
2644        if (err < 0)
2645                return err;
2646        dquot = dqget(sb, *qid);
2647        if (IS_ERR(dquot))
2648                return PTR_ERR(dquot);
2649        do_get_dqblk(dquot, di);
2650        dqput(dquot);
2651
2652        return 0;
2653}
2654EXPORT_SYMBOL(dquot_get_next_dqblk);
2655
2656#define VFS_QC_MASK \
2657        (QC_SPACE | QC_SPC_SOFT | QC_SPC_HARD | \
2658         QC_INO_COUNT | QC_INO_SOFT | QC_INO_HARD | \
2659         QC_SPC_TIMER | QC_INO_TIMER)
2660
2661/* Generic routine for setting common part of quota structure */
2662static int do_set_dqblk(struct dquot *dquot, struct qc_dqblk *di)
2663{
2664        struct mem_dqblk *dm = &dquot->dq_dqb;
2665        int check_blim = 0, check_ilim = 0;
2666        struct mem_dqinfo *dqi = &sb_dqopt(dquot->dq_sb)->info[dquot->dq_id.type];
2667
2668        if (di->d_fieldmask & ~VFS_QC_MASK)
2669                return -EINVAL;
2670
2671        if (((di->d_fieldmask & QC_SPC_SOFT) &&
2672             di->d_spc_softlimit > dqi->dqi_max_spc_limit) ||
2673            ((di->d_fieldmask & QC_SPC_HARD) &&
2674             di->d_spc_hardlimit > dqi->dqi_max_spc_limit) ||
2675            ((di->d_fieldmask & QC_INO_SOFT) &&
2676             (di->d_ino_softlimit > dqi->dqi_max_ino_limit)) ||
2677            ((di->d_fieldmask & QC_INO_HARD) &&
2678             (di->d_ino_hardlimit > dqi->dqi_max_ino_limit)))
2679                return -ERANGE;
2680
2681        spin_lock(&dquot->dq_dqb_lock);
2682        if (di->d_fieldmask & QC_SPACE) {
2683                dm->dqb_curspace = di->d_space - dm->dqb_rsvspace;
2684                check_blim = 1;
2685                set_bit(DQ_LASTSET_B + QIF_SPACE_B, &dquot->dq_flags);
2686        }
2687
2688        if (di->d_fieldmask & QC_SPC_SOFT)
2689                dm->dqb_bsoftlimit = di->d_spc_softlimit;
2690        if (di->d_fieldmask & QC_SPC_HARD)
2691                dm->dqb_bhardlimit = di->d_spc_hardlimit;
2692        if (di->d_fieldmask & (QC_SPC_SOFT | QC_SPC_HARD)) {
2693                check_blim = 1;
2694                set_bit(DQ_LASTSET_B + QIF_BLIMITS_B, &dquot->dq_flags);
2695        }
2696
2697        if (di->d_fieldmask & QC_INO_COUNT) {
2698                dm->dqb_curinodes = di->d_ino_count;
2699                check_ilim = 1;
2700                set_bit(DQ_LASTSET_B + QIF_INODES_B, &dquot->dq_flags);
2701        }
2702
2703        if (di->d_fieldmask & QC_INO_SOFT)
2704                dm->dqb_isoftlimit = di->d_ino_softlimit;
2705        if (di->d_fieldmask & QC_INO_HARD)
2706                dm->dqb_ihardlimit = di->d_ino_hardlimit;
2707        if (di->d_fieldmask & (QC_INO_SOFT | QC_INO_HARD)) {
2708                check_ilim = 1;
2709                set_bit(DQ_LASTSET_B + QIF_ILIMITS_B, &dquot->dq_flags);
2710        }
2711
2712        if (di->d_fieldmask & QC_SPC_TIMER) {
2713                dm->dqb_btime = di->d_spc_timer;
2714                check_blim = 1;
2715                set_bit(DQ_LASTSET_B + QIF_BTIME_B, &dquot->dq_flags);
2716        }
2717
2718        if (di->d_fieldmask & QC_INO_TIMER) {
2719                dm->dqb_itime = di->d_ino_timer;
2720                check_ilim = 1;
2721                set_bit(DQ_LASTSET_B + QIF_ITIME_B, &dquot->dq_flags);
2722        }
2723
2724        if (check_blim) {
2725                if (!dm->dqb_bsoftlimit ||
2726                    dm->dqb_curspace + dm->dqb_rsvspace < dm->dqb_bsoftlimit) {
2727                        dm->dqb_btime = 0;
2728                        clear_bit(DQ_BLKS_B, &dquot->dq_flags);
2729                } else if (!(di->d_fieldmask & QC_SPC_TIMER))
2730                        /* Set grace only if user hasn't provided his own... */
2731                        dm->dqb_btime = ktime_get_real_seconds() + dqi->dqi_bgrace;
2732        }
2733        if (check_ilim) {
2734                if (!dm->dqb_isoftlimit ||
2735                    dm->dqb_curinodes < dm->dqb_isoftlimit) {
2736                        dm->dqb_itime = 0;
2737                        clear_bit(DQ_INODES_B, &dquot->dq_flags);
2738                } else if (!(di->d_fieldmask & QC_INO_TIMER))
2739                        /* Set grace only if user hasn't provided his own... */
2740                        dm->dqb_itime = ktime_get_real_seconds() + dqi->dqi_igrace;
2741        }
2742        if (dm->dqb_bhardlimit || dm->dqb_bsoftlimit || dm->dqb_ihardlimit ||
2743            dm->dqb_isoftlimit)
2744                clear_bit(DQ_FAKE_B, &dquot->dq_flags);
2745        else
2746                set_bit(DQ_FAKE_B, &dquot->dq_flags);
2747        spin_unlock(&dquot->dq_dqb_lock);
2748        mark_dquot_dirty(dquot);
2749
2750        return 0;
2751}
2752
2753int dquot_set_dqblk(struct super_block *sb, struct kqid qid,
2754                  struct qc_dqblk *di)
2755{
2756        struct dquot *dquot;
2757        int rc;
2758
2759        dquot = dqget(sb, qid);
2760        if (IS_ERR(dquot)) {
2761                rc = PTR_ERR(dquot);
2762                goto out;
2763        }
2764        rc = do_set_dqblk(dquot, di);
2765        dqput(dquot);
2766out:
2767        return rc;
2768}
2769EXPORT_SYMBOL(dquot_set_dqblk);
2770
2771/* Generic routine for getting common part of quota file information */
2772int dquot_get_state(struct super_block *sb, struct qc_state *state)
2773{
2774        struct mem_dqinfo *mi;
2775        struct qc_type_state *tstate;
2776        struct quota_info *dqopt = sb_dqopt(sb);
2777        int type;
2778  
2779        memset(state, 0, sizeof(*state));
2780        for (type = 0; type < MAXQUOTAS; type++) {
2781                if (!sb_has_quota_active(sb, type))
2782                        continue;
2783                tstate = state->s_state + type;
2784                mi = sb_dqopt(sb)->info + type;
2785                tstate->flags = QCI_ACCT_ENABLED;
2786                spin_lock(&dq_data_lock);
2787                if (mi->dqi_flags & DQF_SYS_FILE)
2788                        tstate->flags |= QCI_SYSFILE;
2789                if (mi->dqi_flags & DQF_ROOT_SQUASH)
2790                        tstate->flags |= QCI_ROOT_SQUASH;
2791                if (sb_has_quota_limits_enabled(sb, type))
2792                        tstate->flags |= QCI_LIMITS_ENFORCED;
2793                tstate->spc_timelimit = mi->dqi_bgrace;
2794                tstate->ino_timelimit = mi->dqi_igrace;
2795                tstate->ino = dqopt->files[type]->i_ino;
2796                tstate->blocks = dqopt->files[type]->i_blocks;
2797                tstate->nextents = 1;   /* We don't know... */
2798                spin_unlock(&dq_data_lock);
2799        }
2800        return 0;
2801}
2802EXPORT_SYMBOL(dquot_get_state);
2803
2804/* Generic routine for setting common part of quota file information */
2805int dquot_set_dqinfo(struct super_block *sb, int type, struct qc_info *ii)
2806{
2807        struct mem_dqinfo *mi;
2808        int err = 0;
2809
2810        if ((ii->i_fieldmask & QC_WARNS_MASK) ||
2811            (ii->i_fieldmask & QC_RT_SPC_TIMER))
2812                return -EINVAL;
2813        if (!sb_has_quota_active(sb, type))
2814                return -ESRCH;
2815        mi = sb_dqopt(sb)->info + type;
2816        if (ii->i_fieldmask & QC_FLAGS) {
2817                if ((ii->i_flags & QCI_ROOT_SQUASH &&
2818                     mi->dqi_format->qf_fmt_id != QFMT_VFS_OLD))
2819                        return -EINVAL;
2820        }
2821        spin_lock(&dq_data_lock);
2822        if (ii->i_fieldmask & QC_SPC_TIMER)
2823                mi->dqi_bgrace = ii->i_spc_timelimit;
2824        if (ii->i_fieldmask & QC_INO_TIMER)
2825                mi->dqi_igrace = ii->i_ino_timelimit;
2826        if (ii->i_fieldmask & QC_FLAGS) {
2827                if (ii->i_flags & QCI_ROOT_SQUASH)
2828                        mi->dqi_flags |= DQF_ROOT_SQUASH;
2829                else
2830                        mi->dqi_flags &= ~DQF_ROOT_SQUASH;
2831        }
2832        spin_unlock(&dq_data_lock);
2833        mark_info_dirty(sb, type);
2834        /* Force write to disk */
2835        sb->dq_op->write_info(sb, type);
2836        return err;
2837}
2838EXPORT_SYMBOL(dquot_set_dqinfo);
2839
2840const struct quotactl_ops dquot_quotactl_sysfile_ops = {
2841        .quota_enable   = dquot_quota_enable,
2842        .quota_disable  = dquot_quota_disable,
2843        .quota_sync     = dquot_quota_sync,
2844        .get_state      = dquot_get_state,
2845        .set_info       = dquot_set_dqinfo,
2846        .get_dqblk      = dquot_get_dqblk,
2847        .get_nextdqblk  = dquot_get_next_dqblk,
2848        .set_dqblk      = dquot_set_dqblk
2849};
2850EXPORT_SYMBOL(dquot_quotactl_sysfile_ops);
2851
2852static int do_proc_dqstats(struct ctl_table *table, int write,
2853                     void __user *buffer, size_t *lenp, loff_t *ppos)
2854{
2855        unsigned int type = (int *)table->data - dqstats.stat;
2856
2857        /* Update global table */
2858        dqstats.stat[type] =
2859                        percpu_counter_sum_positive(&dqstats.counter[type]);
2860        return proc_dointvec(table, write, buffer, lenp, ppos);
2861}
2862
2863static struct ctl_table fs_dqstats_table[] = {
2864        {
2865                .procname       = "lookups",
2866                .data           = &dqstats.stat[DQST_LOOKUPS],
2867                .maxlen         = sizeof(int),
2868                .mode           = 0444,
2869                .proc_handler   = do_proc_dqstats,
2870        },
2871        {
2872                .procname       = "drops",
2873                .data           = &dqstats.stat[DQST_DROPS],
2874                .maxlen         = sizeof(int),
2875                .mode           = 0444,
2876                .proc_handler   = do_proc_dqstats,
2877        },
2878        {
2879                .procname       = "reads",
2880                .data           = &dqstats.stat[DQST_READS],
2881                .maxlen         = sizeof(int),
2882                .mode           = 0444,
2883                .proc_handler   = do_proc_dqstats,
2884        },
2885        {
2886                .procname       = "writes",
2887                .data           = &dqstats.stat[DQST_WRITES],
2888                .maxlen         = sizeof(int),
2889                .mode           = 0444,
2890                .proc_handler   = do_proc_dqstats,
2891        },
2892        {
2893                .procname       = "cache_hits",
2894                .data           = &dqstats.stat[DQST_CACHE_HITS],
2895                .maxlen         = sizeof(int),
2896                .mode           = 0444,
2897                .proc_handler   = do_proc_dqstats,
2898        },
2899        {
2900                .procname       = "allocated_dquots",
2901                .data           = &dqstats.stat[DQST_ALLOC_DQUOTS],
2902                .maxlen         = sizeof(int),
2903                .mode           = 0444,
2904                .proc_handler   = do_proc_dqstats,
2905        },
2906        {
2907                .procname       = "free_dquots",
2908                .data           = &dqstats.stat[DQST_FREE_DQUOTS],
2909                .maxlen         = sizeof(int),
2910                .mode           = 0444,
2911                .proc_handler   = do_proc_dqstats,
2912        },
2913        {
2914                .procname       = "syncs",
2915                .data           = &dqstats.stat[DQST_SYNCS],
2916                .maxlen         = sizeof(int),
2917                .mode           = 0444,
2918                .proc_handler   = do_proc_dqstats,
2919        },
2920#ifdef CONFIG_PRINT_QUOTA_WARNING
2921        {
2922                .procname       = "warnings",
2923                .data           = &flag_print_warnings,
2924                .maxlen         = sizeof(int),
2925                .mode           = 0644,
2926                .proc_handler   = proc_dointvec,
2927        },
2928#endif
2929        { },
2930};
2931
2932static struct ctl_table fs_table[] = {
2933        {
2934                .procname       = "quota",
2935                .mode           = 0555,
2936                .child          = fs_dqstats_table,
2937        },
2938        { },
2939};
2940
2941static struct ctl_table sys_table[] = {
2942        {
2943                .procname       = "fs",
2944                .mode           = 0555,
2945                .child          = fs_table,
2946        },
2947        { },
2948};
2949
2950static int __init dquot_init(void)
2951{
2952        int i, ret;
2953        unsigned long nr_hash, order;
2954
2955        printk(KERN_NOTICE "VFS: Disk quotas %s\n", __DQUOT_VERSION__);
2956
2957        register_sysctl_table(sys_table);
2958
2959        dquot_cachep = kmem_cache_create("dquot",
2960                        sizeof(struct dquot), sizeof(unsigned long) * 4,
2961                        (SLAB_HWCACHE_ALIGN|SLAB_RECLAIM_ACCOUNT|
2962                                SLAB_MEM_SPREAD|SLAB_PANIC),
2963                        NULL);
2964
2965        order = 0;
2966        dquot_hash = (struct hlist_head *)__get_free_pages(GFP_KERNEL, order);
2967        if (!dquot_hash)
2968                panic("Cannot create dquot hash table");
2969
2970        for (i = 0; i < _DQST_DQSTAT_LAST; i++) {
2971                ret = percpu_counter_init(&dqstats.counter[i], 0, GFP_KERNEL);
2972                if (ret)
2973                        panic("Cannot create dquot stat counters");
2974        }
2975
2976        /* Find power-of-two hlist_heads which can fit into allocation */
2977        nr_hash = (1UL << order) * PAGE_SIZE / sizeof(struct hlist_head);
2978        dq_hash_bits = 0;
2979        do {
2980                dq_hash_bits++;
2981        } while (nr_hash >> dq_hash_bits);
2982        dq_hash_bits--;
2983
2984        nr_hash = 1UL << dq_hash_bits;
2985        dq_hash_mask = nr_hash - 1;
2986        for (i = 0; i < nr_hash; i++)
2987                INIT_HLIST_HEAD(dquot_hash + i);
2988
2989        pr_info("VFS: Dquot-cache hash table entries: %ld (order %ld,"
2990                " %ld bytes)\n", nr_hash, order, (PAGE_SIZE << order));
2991
2992        if (register_shrinker(&dqcache_shrinker))
2993                panic("Cannot register dquot shrinker");
2994
2995        return 0;
2996}
2997fs_initcall(dquot_init);
2998