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