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