Whamcloud - gitweb
d2789ce4a3f658b676f4762145a0e30acbae7bc7
[fs/lustre-release.git] / lustre / quota / qmt_handler.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; if not, write to the
18  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19  * Boston, MA 021110-1307, USA
20  *
21  * GPL HEADER END
22  */
23 /*
24  * Copyright (c) 2012, 2017, Intel Corporation.
25  * Use is subject to license terms.
26  *
27  * Author: Johann Lombardi <johann.lombardi@intel.com>
28  * Author: Niu    Yawei    <yawei.niu@intel.com>
29  */
30
31 #define DEBUG_SUBSYSTEM S_LQUOTA
32
33 #include <obd_class.h>
34 #include "qmt_internal.h"
35
36 /*
37  * Retrieve quota settings for a given identifier.
38  *
39  * \param env     - is the environment passed by the caller
40  * \param qmt     - is the quota master target
41  * \param restype - is the pool type, either block (i.e. LQUOTA_RES_DT) or inode
42  *                  (i.e. LQUOTA_RES_MD)
43  * \param qtype   - is the quota type
44  * \param id      - is the quota indentifier for which we want to acces quota
45  *                  settings.
46  * \param hard    - is the output variable where to copy the hard limit
47  * \param soft    - is the output variable where to copy the soft limit
48  * \param time    - is the output variable where to copy the grace time
49  */
50 static int qmt_get(const struct lu_env *env, struct qmt_device *qmt,
51                    __u8 restype, __u8 qtype, union lquota_id *id,
52                    __u64 *hard, __u64 *soft, __u64 *time, bool is_default,
53                    char *pool_name)
54 {
55         struct lquota_entry     *lqe;
56         ENTRY;
57
58         LASSERT(!is_default || id->qid_uid == 0);
59         if (pool_name && !strnlen(pool_name, LOV_MAXPOOLNAME))
60                 pool_name = NULL;
61
62         /* look-up lqe structure containing quota settings */
63         lqe = qmt_pool_lqe_lookup(env, qmt, restype, qtype, id, pool_name);
64         if (IS_ERR(lqe))
65                 RETURN(PTR_ERR(lqe));
66
67         /* copy quota settings */
68         lqe_read_lock(lqe);
69         LQUOTA_DEBUG(lqe, "fetch settings");
70         if (hard != NULL)
71                 *hard = lqe->lqe_hardlimit;
72         if (soft != NULL)
73                 *soft = lqe->lqe_softlimit;
74         if (time != NULL) {
75                 *time = lqe->lqe_gracetime;
76                 if (lqe->lqe_is_default)
77                         *time |= (__u64)LQUOTA_FLAG_DEFAULT <<
78                                                         LQUOTA_GRACE_BITS;
79         }
80         lqe_read_unlock(lqe);
81
82         lqe_putref(lqe);
83         RETURN(0);
84 }
85
86 struct qmt_entry_iter_data {
87         const struct lu_env *qeid_env;
88         struct qmt_device   *qeid_qmt;
89 };
90
91 static int qmt_entry_iter_cb(struct cfs_hash *hs, struct cfs_hash_bd *bd,
92                              struct hlist_node *hnode, void *d)
93 {
94         struct qmt_entry_iter_data *iter = (struct qmt_entry_iter_data *)d;
95         struct lquota_entry     *lqe;
96
97         lqe = hlist_entry(hnode, struct lquota_entry, lqe_hash);
98         LASSERT(atomic_read(&lqe->lqe_ref) > 0);
99
100         if (lqe->lqe_id.qid_uid == 0 || !lqe->lqe_is_default)
101                 return 0;
102
103         return qmt_set_with_lqe(iter->qeid_env, iter->qeid_qmt, lqe, 0, 0, 0, 0,
104                                 true, true);
105 }
106
107 static void qmt_set_id_notify(const struct lu_env *env, struct qmt_device *qmt,
108                               struct lquota_entry *lqe)
109 {
110         struct lquota_entry *lqe_gl;
111         int rc;
112
113         lqe_gl = lqe->lqe_is_global ? lqe : NULL;
114         rc = qmt_pool_lqes_lookup_spec(env, qmt, lqe_rtype(lqe),
115                                        lqe_qtype(lqe), &lqe->lqe_id);
116         if (!qti_lqes_cnt(env))
117                 GOTO(lqes_fini, rc);
118
119         if (!lqe_gl && qti_lqes_glbl(env)->lqe_is_global)
120                 lqe_gl = qti_lqes_glbl(env);
121
122         if (!lqe_gl)
123                 GOTO(lqes_fini, rc);
124
125         mutex_lock(&lqe_gl->lqe_glbl_data_lock);
126         if (lqe_gl->lqe_glbl_data)
127                 qmt_seed_glbe(env, lqe_gl->lqe_glbl_data);
128         mutex_unlock(&lqe_gl->lqe_glbl_data_lock);
129
130         /* Even if slaves haven't enqueued quota lock yet,
131          * it is needed to set lqe_revoke_time in qmt_id_lock_glimpse
132          * in case of reaching qpi_least_qunit */
133         qmt_id_lock_notify(qmt, lqe_gl);
134 lqes_fini:
135         qti_lqes_fini(env);
136 }
137
138 /*
139  * Update quota settings for a given lqe.
140  *
141  * \param env        - is the environment passed by the caller
142  * \param qmt        - is the quota master target
143  * \param lqe        - is the lquota_entry for which we want to modify quota
144  *                     settings.
145  * \param hard       - is the new hard limit
146  * \param soft       - is the new soft limit
147  * \param time       - is the new grace time
148  * \param valid      - is the list of settings to change
149  * \param is_default - true for default quota setting
150  * \param is_updated - true if the lqe is updated and no need to write back
151  */
152
153 int qmt_set_with_lqe(const struct lu_env *env, struct qmt_device *qmt,
154                      struct lquota_entry *lqe, __u64 hard, __u64 soft,
155                      __u64 time, __u32 valid, bool is_default, bool is_updated)
156 {
157         struct thandle *th = NULL;
158         time64_t now = 0;
159         __u64 ver;
160         bool dirtied = false;
161         int rc = 0;
162         bool need_id_notify = false;
163         ENTRY;
164
165         /* need to write back to global quota file? */
166         if (!is_updated) {
167                 /* By default we should have here only 1 lqe,
168                  * so no allocations should be done. */
169                 if (qti_lqes_restore_init(env))
170                         GOTO(out_nolock, rc = -ENOMEM);
171                 /* allocate & start transaction with enough credits to update
172                  * quota  settings in the global index file */
173                 th = qmt_trans_start(env, lqe);
174                 if (IS_ERR(th))
175                         GOTO(out_nolock, rc = PTR_ERR(th));
176         }
177
178         now = ktime_get_real_seconds();
179
180         lqe_write_lock(lqe);
181         LQUOTA_DEBUG(lqe,
182                      "changing quota settings valid:%x hard:%llu soft:%llu time:%llu",
183                      valid, hard, soft, time);
184
185         if (is_default && lqe->lqe_id.qid_uid != 0) {
186                 LQUOTA_DEBUG(lqe, "set qid %llu to use default quota setting",
187                              lqe->lqe_id.qid_uid);
188
189                 qmt_lqe_set_default(env, lqe->lqe_site->lqs_parent, lqe, false);
190                 GOTO(quota_set, 0);
191         }
192
193         if ((valid & QIF_TIMES) != 0 && lqe->lqe_gracetime != time) {
194                 /* change time settings */
195                 lqe->lqe_gracetime = time;
196                 dirtied            = true;
197         }
198
199         if ((valid & QIF_LIMITS) != 0 &&
200             (lqe->lqe_hardlimit != hard || lqe->lqe_softlimit != soft)) {
201                 rc = qmt_validate_limits(lqe, hard, soft);
202                 if (rc)
203                         GOTO(out, rc);
204
205                 /* change quota limits */
206                 lqe->lqe_hardlimit = hard;
207                 lqe->lqe_softlimit = soft;
208
209 quota_set:
210                 /* recompute qunit in case it was never initialized */
211                 if (qmt_revalidate(env, lqe))
212                         need_id_notify = true;
213
214                 /* clear grace time */
215                 if (lqe->lqe_softlimit == 0 ||
216                     lqe->lqe_granted <= lqe->lqe_softlimit)
217                         /* no soft limit or below soft limit, let's clear grace
218                          * time */
219                         lqe->lqe_gracetime = 0;
220                 else if ((valid & QIF_TIMES) == 0)
221                         /* set grace only if user hasn't provided his own */
222                          lqe->lqe_gracetime = now + qmt_lqe_grace(lqe);
223
224                 /* change enforced status based on new parameters */
225                 if (lqe->lqe_id.qid_uid == 0 || (lqe->lqe_hardlimit == 0 &&
226                     lqe->lqe_softlimit == 0)) {
227                         if (lqe->lqe_enforced) {
228                                 lqe->lqe_enforced = false;
229                                 /* Clear qunit and edquot as lqe_adjust_edquot
230                                  * does not handle not enforced lqes */
231                                 lqe->lqe_edquot = 0;
232                                 lqe->lqe_qunit = 0;
233                                 need_id_notify = true;
234                         }
235                 } else {
236                         lqe->lqe_enforced = true;
237                 }
238
239                 dirtied = true;
240         }
241
242         if (!is_default && lqe->lqe_is_default) {
243                 LQUOTA_DEBUG(lqe, "the qid %llu has been set quota"
244                              " explicitly, clear the default flag",
245                              lqe->lqe_id.qid_uid);
246
247                 qmt_lqe_clear_default(lqe);
248                 dirtied = true;
249         }
250
251         if (dirtied) {
252                 if (!is_updated) {
253                         /* write new quota settings to disk */
254                         rc = qmt_glb_write(env, th, lqe, LQUOTA_BUMP_VER, &ver);
255                         if (rc) {
256                                 /* restore initial quota settings */
257                                 qmt_restore(lqe, &qti_lqes_rstr(env)[0]);
258                                 GOTO(out, rc);
259                         }
260                 } else {
261                         ver = dt_version_get(env, LQE_GLB_OBJ(lqe));
262                 }
263
264                 /* compute new qunit value now that we have modified the quota
265                  * settings or clear/set edquot flag if needed */
266                 need_id_notify |= qmt_adjust_qunit(env, lqe);
267                 need_id_notify |= qmt_adjust_edquot(lqe, now);
268         }
269         EXIT;
270 out:
271         lqe_write_unlock(lqe);
272
273 out_nolock:
274         if (!is_updated) {
275                 if (th != NULL && !IS_ERR(th))
276                         dt_trans_stop(env, qmt->qmt_child, th);
277                 qti_lqes_restore_fini(env);
278         }
279
280         if (rc == 0 && dirtied) {
281                 qmt_glb_lock_notify(env, lqe, ver);
282                 if (lqe->lqe_id.qid_uid == 0) {
283                         struct qmt_entry_iter_data iter_data;
284
285                         LQUOTA_DEBUG(lqe, "notify all lqe with default quota");
286                         iter_data.qeid_env = env;
287                         iter_data.qeid_qmt = qmt;
288                         cfs_hash_for_each(lqe->lqe_site->lqs_hash,
289                                                qmt_entry_iter_cb, &iter_data);
290                         /* Always notify slaves with default values. Don't
291                          * care about overhead as will be sent only not changed
292                          * values(see qmt_id_lock_cb for details).*/
293                         need_id_notify = true;
294                 }
295                 /* qti_lqes_inited > 0 means we came here from another
296                  * qmt_pool_lqes_lookup(qmt_dqacq, intent_policy ...). Thus
297                  * we can't init and add new lqes to don't overwrite already
298                  * added.
299                  */
300                 if (!qti_lqes_inited(env) && need_id_notify)
301                         qmt_set_id_notify(env, qmt, lqe);
302         }
303
304         return rc;
305 }
306
307 /*
308  * Update quota settings for a given identifier.
309  *
310  * \param env        - is the environment passed by the caller
311  * \param qmt        - is the quota master target
312  * \param restype    - is the pool type, either block (i.e. LQUOTA_RES_DT) or
313  *                     inode (i.e. LQUOTA_RES_MD)
314  * \param qtype      - is the quota type
315  * \param id         - is the quota indentifier for which we want to modify
316  *                     quota settings.
317  * \param hard       - is the new hard limit
318  * \param soft       - is the new soft limit
319  * \param time       - is the new grace time
320  * \param valid      - is the list of settings to change
321  * \param is_default - true for default quota setting
322  * \param is_updated - true if the lqe is updated and no need to write back
323  */
324 static int qmt_set(const struct lu_env *env, struct qmt_device *qmt,
325                    __u8 restype, __u8 qtype, union lquota_id *id,
326                    __u64 hard, __u64 soft, __u64 time, __u32 valid,
327                    bool is_default, bool is_updated, char *pool_name)
328 {
329         struct lquota_entry *lqe;
330         int rc;
331         ENTRY;
332
333         if (pool_name && !strnlen(pool_name, LOV_MAXPOOLNAME))
334                 pool_name = NULL;
335
336         /* look-up quota entry associated with this ID */
337         lqe = qmt_pool_lqe_lookup(env, qmt, restype, qtype, id, pool_name);
338         if (IS_ERR(lqe))
339                         RETURN(PTR_ERR(lqe));
340
341         lqe->lqe_is_deleted = 0;
342         rc = qmt_set_with_lqe(env, qmt, lqe, hard, soft, time, valid,
343                               is_default, is_updated);
344         if (rc == 0)
345                 lqe->lqe_is_deleted = 0;
346
347         lqe_putref(lqe);
348         RETURN(rc);
349 }
350
351 /*
352  * Delete the quota setting of the specified quota ID
353  *
354  * \param env        - is the environment passed by the caller
355  * \param qmt        - is the quota master target
356  * \param restype    - is the pool type, either block (i.e. LQUOTA_RES_DT) or
357  *                     inode (i.e. LQUOTA_RES_MD)
358  * \param qtype      - is the quota type
359  * \param qid        - is the quota indentifier for which we want to delete its
360  *                     quota settings.
361  */
362 static int qmt_delete_qid(const struct lu_env *env, struct qmt_device *qmt,
363                           __u8 restype, __u8 qtype, __u64 qid)
364 {
365         struct qmt_thread_info *qti = qmt_info(env);
366         union lquota_id *quota_id = &qti->qti_id;
367         struct thandle *th = NULL;
368         struct qmt_pool_info *qpi = NULL;
369         struct lquota_entry *lqe = NULL;
370         __u64 ver = 0;
371         int rc;
372
373         ENTRY;
374
375         quota_id->qid_uid = qid;
376         lqe = qmt_pool_lqe_lookup(env, qmt, restype, qtype, quota_id, NULL);
377         if (IS_ERR(lqe))
378                 RETURN(PTR_ERR(lqe));
379
380         lqe_write_lock(lqe);
381
382         qpi = qmt_pool_lookup_glb(env, qmt, restype);
383         if (IS_ERR(qpi))
384                 GOTO(out, rc = -ENOMEM);
385
386         th = qmt_trans_start(env, lqe);
387         if (IS_ERR(th))
388                 GOTO(out, rc = PTR_ERR(th));
389
390         rc = lquota_disk_delete(env, th,
391                                 qpi->qpi_glb_obj[qtype], qid, &ver);
392
393         dt_trans_stop(env, qmt->qmt_child, th);
394
395         if (rc == 0) {
396                 lqe_set_deleted(lqe);
397                 qmt_glb_lock_notify(env, lqe, ver);
398         } else if (rc == -ENOENT) {
399                 rc = 0;
400         }
401
402 out:
403         if (!IS_ERR_OR_NULL(qpi))
404                 qpi_putref(env, qpi);
405
406         lqe_write_unlock(lqe);
407         lqe_putref(lqe);
408
409         RETURN(rc);
410 }
411
412 /*
413  * Handle quotactl request.
414  *
415  * \param env   - is the environment passed by the caller
416  * \param ld    - is the lu device associated with the qmt
417  * \param oqctl - is the quotactl request
418  */
419 static int qmt_quotactl(const struct lu_env *env, struct lu_device *ld,
420                         struct obd_quotactl *oqctl)
421 {
422         struct qmt_thread_info *qti = qmt_info(env);
423         union lquota_id *id  = &qti->qti_id;
424         struct qmt_device *qmt = lu2qmt_dev(ld);
425         struct obd_dqblk *dqb = &oqctl->qc_dqblk;
426         char *poolname;
427         int rc = 0;
428         bool is_default = false;
429         ENTRY;
430
431         LASSERT(qmt != NULL);
432
433         if (oqctl->qc_type >= LL_MAXQUOTAS)
434                 /* invalid quota type */
435                 RETURN(-EINVAL);
436
437         poolname = LUSTRE_Q_CMD_IS_POOL(oqctl->qc_cmd) ?
438                         oqctl->qc_poolname : NULL;
439
440         switch (oqctl->qc_cmd) {
441
442         case Q_GETINFO:  /* read grace times */
443         case LUSTRE_Q_GETINFOPOOL:
444                 /* Global grace time is stored in quota settings of ID 0. */
445                 id->qid_uid = 0;
446
447                 /* read inode grace time */
448                 rc = qmt_get(env, qmt, LQUOTA_RES_MD, oqctl->qc_type, id, NULL,
449                              NULL, &oqctl->qc_dqinfo.dqi_igrace,
450                              false, poolname);
451                 /* There could be no MD pool, so try to find DT pool */
452                 if (rc && rc != -ENOENT)
453                         break;
454
455                 /* read block grace time */
456                 rc = qmt_get(env, qmt, LQUOTA_RES_DT, oqctl->qc_type, id, NULL,
457                              NULL, &oqctl->qc_dqinfo.dqi_bgrace,
458                              false, poolname);
459                 break;
460
461         case Q_SETINFO:  /* modify grace times */
462         case LUSTRE_Q_SETINFOPOOL:
463                 /* setinfo should be using dqi->dqi_valid, but lfs incorrectly
464                  * sets the valid flags in dqb->dqb_valid instead, try to live
465                  * with that ... */
466
467                 /* Global grace time is stored in quota settings of ID 0. */
468                 id->qid_uid = 0;
469
470                 if ((dqb->dqb_valid & QIF_ITIME) != 0) {
471                         /* set inode grace time */
472                         rc = qmt_set(env, qmt, LQUOTA_RES_MD, oqctl->qc_type,
473                                      id, 0, 0, oqctl->qc_dqinfo.dqi_igrace,
474                                      QIF_TIMES, false, false,
475                                      poolname);
476                         if (rc)
477                                 break;
478                 }
479
480                 if ((dqb->dqb_valid & QIF_BTIME) != 0)
481                         /* set block grace time */
482                         rc = qmt_set(env, qmt, LQUOTA_RES_DT, oqctl->qc_type,
483                                      id, 0, 0, oqctl->qc_dqinfo.dqi_bgrace,
484                                      QIF_TIMES, false, false,
485                                      poolname);
486                 break;
487
488         case LUSTRE_Q_GETDEFAULT:
489         case LUSTRE_Q_GETDEFAULT_POOL:
490                 is_default = true;
491                 fallthrough;
492
493         case Q_GETQUOTA: /* consult quota limit */
494         case LUSTRE_Q_GETQUOTAPOOL:
495                 /* extract quota ID from quotactl request */
496                 id->qid_uid = oqctl->qc_id;
497
498                 /* look-up inode quota settings */
499                 rc = qmt_get(env, qmt, LQUOTA_RES_MD, oqctl->qc_type, id,
500                              &dqb->dqb_ihardlimit, &dqb->dqb_isoftlimit,
501                              &dqb->dqb_itime, is_default, poolname);
502                 /* There could be no MD pool, so try to find DT pool */
503                 if (rc && rc != -ENOENT)
504                         break;
505                 else
506                         dqb->dqb_valid |= QIF_ILIMITS | QIF_ITIME;
507
508                 /* master isn't aware of actual inode usage */
509                 dqb->dqb_curinodes = 0;
510
511                 /* look-up block quota settings */
512                 rc = qmt_get(env, qmt, LQUOTA_RES_DT, oqctl->qc_type, id,
513                              &dqb->dqb_bhardlimit, &dqb->dqb_bsoftlimit,
514                              &dqb->dqb_btime, is_default, poolname);
515                 if (rc)
516                         break;
517
518                 dqb->dqb_valid |= QIF_BLIMITS | QIF_BTIME;
519                 /* master doesn't know the actual block usage */
520                 dqb->dqb_curspace = 0;
521                 break;
522
523         case LUSTRE_Q_SETDEFAULT:
524         case LUSTRE_Q_SETDEFAULT_POOL:
525                 is_default = true;
526                 fallthrough;
527
528         case Q_SETQUOTA: /* change quota limits */
529         case LUSTRE_Q_SETQUOTAPOOL:
530                 /* extract quota ID from quotactl request */
531                 id->qid_uid = oqctl->qc_id;
532
533                 if ((dqb->dqb_valid & QIF_IFLAGS) != 0) {
534                         /* update inode quota settings */
535                         rc = qmt_set(env, qmt, LQUOTA_RES_MD, oqctl->qc_type,
536                                      id, dqb->dqb_ihardlimit,
537                                      dqb->dqb_isoftlimit, dqb->dqb_itime,
538                                      dqb->dqb_valid & QIF_IFLAGS, is_default,
539                                      false, poolname);
540                         if (rc)
541                                 break;
542                 }
543
544                 if ((dqb->dqb_valid & QIF_BFLAGS) != 0)
545                         /* update block quota settings */
546                         rc = qmt_set(env, qmt, LQUOTA_RES_DT, oqctl->qc_type,
547                                      id, dqb->dqb_bhardlimit,
548                                      dqb->dqb_bsoftlimit, dqb->dqb_btime,
549                                      dqb->dqb_valid & QIF_BFLAGS, is_default,
550                                      false, poolname);
551                 break;
552
553         case LUSTRE_Q_DELETEQID:
554                 rc = qmt_delete_qid(env, qmt, LQUOTA_RES_MD, oqctl->qc_type,
555                                     oqctl->qc_id);
556                 if (rc)
557                         break;
558
559                 rc = qmt_delete_qid(env, qmt, LQUOTA_RES_DT, oqctl->qc_type,
560                                     oqctl->qc_id);
561                 break;
562
563         default:
564                 CERROR("%s: unsupported quotactl command: %d\n",
565                        qmt->qmt_svname, oqctl->qc_cmd);
566                 RETURN(-ENOTSUPP);
567         }
568
569         RETURN(rc);
570 }
571
572 static inline
573 void qmt_grant_lqes(const struct lu_env *env, __u64 *slv, __u64 cnt)
574 {
575         int i;
576
577         for (i = 0; i < qti_lqes_cnt(env); i++)
578                 qti_lqe_granted(env, i) += cnt;
579
580         *slv += cnt;
581 }
582
583 static inline bool qmt_lqes_can_rel(const struct lu_env *env, __u64 cnt)
584 {
585         bool can_release = true;
586         int i;
587
588         for (i = 0; i < qti_lqes_cnt(env); i++) {
589                 if (cnt > qti_lqe_granted(env, i)) {
590                         LQUOTA_ERROR(qti_lqes(env)[i],
591                                      "Can't release %llu that is larger than lqe_granted.\n",
592                                      cnt);
593                         can_release = false;
594                 }
595         }
596         return can_release;
597 }
598
599 static inline void qmt_rel_lqes(const struct lu_env *env, __u64 *slv, __u64 cnt)
600 {
601         int i;
602
603         for (i = 0; i < qti_lqes_cnt(env); i++)
604                 qti_lqe_granted(env, i) -= cnt;
605
606         *slv -= cnt;
607 }
608
609 static inline bool qmt_lqes_cannot_grant(const struct lu_env *env, __u64 cnt)
610 {
611         bool cannot_grant = false;
612         int i;
613
614         for (i = 0; i < qti_lqes_cnt(env); i++) {
615                 if (qti_lqe_hard(env, i) != 0 &&
616                     qti_lqe_granted(env, i) + cnt > qti_lqe_hard(env, i)) {
617                         cannot_grant = true;
618                         break;
619                 }
620         }
621         return cannot_grant;
622 }
623
624 static inline __u64 qmt_lqes_grant_some_quota(const struct lu_env *env)
625 {
626         __u64 min_count, tmp;
627         bool flag = false;
628         int i;
629
630         for (i = 0, min_count = 0; i < qti_lqes_cnt(env); i++) {
631                 if (!qti_lqes(env)[i]->lqe_enforced &&
632                     !qti_lqes(env)[i]->lqe_is_global)
633                         continue;
634
635                 tmp = qti_lqe_hard(env, i) - qti_lqe_granted(env, i);
636                 if (flag) {
637                         min_count = tmp < min_count ? tmp : min_count;
638                 } else {
639                         flag = true;
640                         min_count = tmp;
641                 }
642         }
643         return min_count;
644 }
645
646 static inline __u64 qmt_lqes_alloc_expand(const struct lu_env *env,
647                                           __u64 slv_granted, __u64 spare)
648 {
649         __u64 min_count, tmp;
650         bool flag = false;
651         int i;
652
653         for (i = 0, min_count = 0; i < qti_lqes_cnt(env); i++) {
654                 /* Don't take into account not enforced lqes that belong
655                  * to non global pool. These lqes present in array to
656                  * support actual lqe_granted even for lqes without limits. */
657                 if (!qti_lqes(env)[i]->lqe_enforced &&
658                     !qti_lqes(env)[i]->lqe_is_global)
659                         continue;
660
661                 tmp = qmt_alloc_expand(qti_lqes(env)[i], slv_granted, spare);
662                 if (flag) {
663                         min_count = tmp < min_count ? tmp : min_count;
664                 } else {
665                         flag = true;
666                         min_count = tmp;
667                 }
668         }
669         return min_count;
670 }
671
672 static inline void qmt_lqes_tune_grace(const struct lu_env *env, __u64 now)
673 {
674         int i;
675
676         for (i = 0; i < qti_lqes_cnt(env); i++) {
677                 struct lquota_entry *lqe;
678
679                 lqe = qti_lqes(env)[i];
680                 if (lqe->lqe_softlimit != 0) {
681                         if (lqe->lqe_granted > lqe->lqe_softlimit &&
682                             lqe->lqe_gracetime == 0) {
683                                 /* First time over soft limit, let's start grace
684                                  * timer */
685                                 lqe->lqe_gracetime = now + qmt_lqe_grace(lqe);
686                         } else if (lqe->lqe_granted <= lqe->lqe_softlimit &&
687                                    lqe->lqe_gracetime != 0) {
688                                 /* Clear grace timer */
689                                 lqe->lqe_gracetime = 0;
690                         }
691                 }
692         }
693 }
694
695 /*
696  * Helper function to handle quota request from slave.
697  *
698  * \param env     - is the environment passed by the caller
699  * \param qmt     - is the master device
700  * \param uuid    - is the uuid associated with the slave
701  * \param qb_flags - are the quota request flags as packed in the quota_body
702  * \param qb_count - is the amount of quota space the slave wants to
703  *                   acquire/release
704  * \param qb_usage - is the current space usage on the slave
705  * \param repbody - is the quota_body of reply
706  *
707  * \retval 0            : success
708  * \retval -EDQUOT      : out of quota
709  *         -EINPROGRESS : inform client to retry write/create
710  *         -ve          : other appropriate errors
711  */
712 int qmt_dqacq0(const struct lu_env *env, struct qmt_device *qmt,
713                struct obd_uuid *uuid, __u32 qb_flags, __u64 qb_count,
714                __u64 qb_usage, struct quota_body *repbody)
715 {
716         __u64                    now, count;
717         struct dt_object        *slv_obj = NULL;
718         __u64                    slv_granted, slv_granted_bck;
719         struct thandle          *th = NULL;
720         int                      rc, ret;
721         struct lquota_entry *lqe = qti_lqes_glbl(env);
722         ENTRY;
723
724         LASSERT(uuid != NULL);
725
726         /* initialize reply */
727         memset(repbody, 0, sizeof(*repbody));
728         memcpy(&repbody->qb_id, &lqe->lqe_id, sizeof(repbody->qb_id));
729
730         if (OBD_FAIL_CHECK(OBD_FAIL_QUOTA_RECOVERABLE_ERR))
731                 RETURN(-cfs_fail_val);
732
733         if (OBD_FAIL_CHECK(OBD_FAIL_QUOTA_PREACQ) &&
734            (req_is_preacq(qb_flags) || req_is_rel(qb_flags)))
735                 RETURN(-EAGAIN);
736
737         if (qti_lqes_restore_init(env))
738                 RETURN(-ENOMEM);
739
740         /* look-up index file associated with acquiring slave */
741         slv_obj = lquota_disk_slv_find(env, qmt->qmt_child, LQE_ROOT(lqe),
742                                        lu_object_fid(&LQE_GLB_OBJ(lqe)->do_lu),
743                                        uuid);
744         if (IS_ERR(slv_obj))
745                 GOTO(out, rc = PTR_ERR(slv_obj));
746
747         /* pack slave fid in reply just for sanity check */
748         memcpy(&repbody->qb_slv_fid, lu_object_fid(&slv_obj->do_lu),
749                sizeof(struct lu_fid));
750
751         /* allocate & start transaction with enough credits to update
752          * global & slave indexes */
753         th = qmt_trans_start_with_slv(env, NULL, slv_obj, false);
754         if (IS_ERR(th))
755                 GOTO(out, rc = PTR_ERR(th));
756
757         qti_lqes_write_lock(env);
758
759         LQUOTA_DEBUG_LQES(env, "dqacq starts uuid:%s flags:0x%x wanted:%llu"
760                      " usage:%llu", obd_uuid2str(uuid), qb_flags, qb_count,
761                      qb_usage);
762
763         /* Legal race, limits have been removed on master, but slave didn't
764          * receive the change yet. Just return EINPROGRESS until the slave gets
765          * notified. */
766         if (!lqe->lqe_enforced && !req_is_rel(qb_flags))
767                 GOTO(out_locked, rc = -ESRCH);
768
769         /* recompute qunit in case it was never initialized */
770         qmt_revalidate_lqes(env, qmt, qb_flags);
771
772         /* slave just wants to acquire per-ID lock */
773         if (req_is_acq(qb_flags) && qb_count == 0)
774                 GOTO(out_locked, rc = 0);
775
776         /* fetch how much quota space is already granted to this slave */
777         rc = qmt_slv_read(env, &lqe->lqe_id, slv_obj, &slv_granted);
778         if (rc) {
779                 LQUOTA_ERROR(lqe, "Failed to get granted for slave %s, rc=%d",
780                              obd_uuid2str(uuid), rc);
781                 GOTO(out_locked, rc);
782         }
783         /* recall how much space this slave currently owns in order to restore
784          * it in case of failure */
785         slv_granted_bck = slv_granted;
786
787         /* record current time for soft limit & grace time management */
788         now = ktime_get_real_seconds();
789
790         if (req_is_rel(qb_flags)) {
791                 /* Slave would like to release quota space */
792                 if (slv_granted < qb_count ||
793                     !qmt_lqes_can_rel(env, qb_count)) {
794                         /* can't release more than granted */
795                         LQUOTA_ERROR_LQES(env,
796                                           "Release too much! uuid:%s release: %llu granted:%llu, total:%llu",
797                                           obd_uuid2str(uuid), qb_count,
798                                           slv_granted, lqe->lqe_granted);
799                         GOTO(out_locked, rc = -EINVAL);
800                 }
801
802                 repbody->qb_count = qb_count;
803                 /* put released space back to global pool */
804                 qmt_rel_lqes(env, &slv_granted, qb_count);
805                 GOTO(out_write, rc = 0);
806         }
807
808         if (req_has_rep(qb_flags) && slv_granted < qb_usage) {
809                 /* Slave is reporting space usage in quota request and it turns
810                  * out to be using more quota space than owned, so we adjust
811                  * granted space regardless of the current state of affairs */
812                 repbody->qb_count = qb_usage - slv_granted;
813                 qmt_grant_lqes(env, &slv_granted, repbody->qb_count);
814         }
815
816         if (!req_is_acq(qb_flags) && !req_is_preacq(qb_flags))
817                 GOTO(out_write, rc = 0);
818
819         qmt_adjust_edquot_notify(env, qmt, now, qb_flags);
820         if (qti_lqes_edquot(env))
821                 /* no hope to claim further space back */
822                 GOTO(out_write, rc = -EDQUOT);
823
824         if (qmt_space_exhausted_lqes(env, now)) {
825                 /* might have some free space once rebalancing is completed */
826                 rc = req_is_acq(qb_flags) ? -EINPROGRESS : -EDQUOT;
827                 GOTO(out_write, rc);
828         }
829
830         if (req_is_preacq(qb_flags)) {
831                 /* slave would like to pre-acquire quota space. To do so, it
832                  * reports in qb_count how much spare quota space it owns and we
833                  * can grant back quota space which is consistent with qunit
834                  * value. */
835                 if (qb_count >= qti_lqes_min_qunit(env))
836                         /* slave already own the maximum it should */
837                         GOTO(out_write, rc = 0);
838
839                 count = qmt_lqes_alloc_expand(env, slv_granted, qb_count);
840                 if (count == 0)
841                         GOTO(out_write, rc = -EDQUOT);
842
843                 repbody->qb_count += count;
844                 qmt_grant_lqes(env, &slv_granted, count);
845                 GOTO(out_write, rc = 0);
846         }
847
848         /* processing acquire request with clients waiting */
849         if (qmt_lqes_cannot_grant(env, qb_count)) {
850                 /* cannot grant as much as asked, but can still afford to grant
851                  * some quota space back */
852                 count = qmt_lqes_grant_some_quota(env);
853                 repbody->qb_count += count;
854                 qmt_grant_lqes(env, &slv_granted, count);
855                 GOTO(out_write, rc = 0);
856         }
857
858         /* Whouhou! we can satisfy the slave request! */
859         repbody->qb_count += qb_count;
860         qmt_grant_lqes(env, &slv_granted, qb_count);
861
862         /* Try to expand the acquired count for DQACQ */
863         count = qmt_lqes_alloc_expand(env, slv_granted, 0);
864         if (count != 0) {
865                 /* can even grant more than asked, it is like xmas ... */
866                 repbody->qb_count += count;
867                 qmt_grant_lqes(env, &slv_granted, count);
868                 GOTO(out_write, rc = 0);
869         }
870
871         GOTO(out_write, rc = 0);
872 out_write:
873         if (repbody->qb_count == 0)
874                 GOTO(out_locked, rc);
875
876         /* start/stop grace timer if required */
877         qmt_lqes_tune_grace(env, now);
878
879         /* Update slave index first since it is easier to roll back */
880         ret = qmt_slv_write(env, th, lqe, slv_obj, LQUOTA_BUMP_VER,
881                             &repbody->qb_slv_ver, slv_granted);
882         if (ret) {
883                 /* restore initial quota settings */
884                 qmt_restore_lqes(env);
885                 /* reset qb_count */
886                 repbody->qb_count = 0;
887                 GOTO(out_locked, rc = ret);
888         }
889
890         /* Update global index, no version bump needed */
891         ret = qmt_glb_write_lqes(env, th, 0, NULL);
892         if (ret) {
893                 rc = ret;
894                 /* restore initial quota settings */
895                 qmt_restore_lqes(env);
896                 /* reset qb_count */
897                 repbody->qb_count = 0;
898
899                 /* restore previous granted value */
900                 ret = qmt_slv_write(env, th, lqe, slv_obj, 0, NULL,
901                                     slv_granted_bck);
902                 if (ret) {
903                         LQUOTA_ERROR(lqe, "failed to restore initial slave "
904                                      "value rc:%d ret%d", rc, ret);
905                         LBUG();
906                 }
907                 qmt_adjust_edquot_notify(env, qmt, now, qb_flags);
908                 GOTO(out_locked, rc);
909         }
910
911         /* Total granted has been changed, let's try to adjust the qunit
912          * size according to the total granted & limits. */
913
914         /* clear/set edquot flag and notify slaves via glimpse if needed */
915         qmt_adjust_and_notify(env, qmt, now, qb_flags);
916 out_locked:
917         LQUOTA_DEBUG_LQES(env, "dqacq ends count:%llu ver:%llu rc:%d",
918                      repbody->qb_count, repbody->qb_slv_ver, rc);
919         qti_lqes_write_unlock(env);
920 out:
921         qti_lqes_restore_fini(env);
922
923         if (th != NULL && !IS_ERR(th))
924                 dt_trans_stop(env, qmt->qmt_child, th);
925
926         if (slv_obj != NULL && !IS_ERR(slv_obj))
927                 dt_object_put(env, slv_obj);
928
929         if ((req_is_acq(qb_flags) || req_is_preacq(qb_flags)) &&
930             OBD_FAIL_CHECK(OBD_FAIL_QUOTA_EDQUOT)) {
931                 /* introduce inconsistency between granted value in slave index
932                  * and slave index copy of slave */
933                 repbody->qb_count = 0;
934                 rc = -EDQUOT;
935         }
936
937         RETURN(rc);
938 }
939
940 /*
941  * Extract index from uuid or quota index file name.
942  *
943  * \param[in] uuid      uuid or quota index name(0x1020000-OST0001_UUID)
944  * \param[out] idx      pointer to save index
945  *
946  * \retval              slave type(QMT_STYPE_MDT or QMT_STYPE_OST)
947  * \retval -EINVAL      wrong uuid
948  */
949 int qmt_uuid2idx(struct obd_uuid *uuid, int *idx)
950 {
951         char *uuid_str, *name, *dash;
952         int rc = -EINVAL;
953
954         uuid_str = (char *)uuid->uuid;
955
956         if (strnlen(uuid_str, UUID_MAX) >= UUID_MAX) {
957                 CERROR("quota: UUID '%.*s' missing trailing NUL: rc = %d\n",
958                        UUID_MAX, uuid_str, rc);
959                 return rc;
960         }
961
962         dash = strrchr(uuid_str, '-');
963         name = dash + 1;
964         /* Going to get index from MDTXXXX/OSTXXXX. Thus uuid should
965          * have at least 8 bytes after '-': 3 for MDT/OST, 4 for index
966          * and 1 byte for null character. */
967         if (*dash != '-' || ((uuid_str + UUID_MAX - name) < 8)) {
968                 CERROR("quota: wrong UUID format '%s': rc = %d\n",
969                        uuid_str, rc);
970                 return rc;
971         }
972
973         rc = target_name2index(name, idx, NULL);
974         switch (rc) {
975         case LDD_F_SV_TYPE_MDT:
976                 rc = QMT_STYPE_MDT;
977                 break;
978         case LDD_F_SV_TYPE_OST:
979                 rc = QMT_STYPE_OST;
980                 break;
981         default:
982                 CERROR("quota: wrong UUID type '%s': rc = %d\n", uuid_str, rc);
983                 rc = -EINVAL;
984         }
985
986         RETURN(rc);
987 }
988
989 /*
990  * Handle quota request from slave.
991  *
992  * \param env  - is the environment passed by the caller
993  * \param ld   - is the lu device associated with the qmt
994  * \param req  - is the quota acquire request
995  */
996 static int qmt_dqacq(const struct lu_env *env, struct lu_device *ld,
997                      struct ptlrpc_request *req)
998 {
999         struct qmt_device *qmt = lu2qmt_dev(ld);
1000         struct quota_body *qbody, *repbody;
1001         struct obd_uuid *uuid;
1002         struct ldlm_lock *lock;
1003         int rtype, qtype;
1004         int rc, idx, stype;
1005         ENTRY;
1006
1007         qbody = req_capsule_client_get(&req->rq_pill, &RMF_QUOTA_BODY);
1008         if (qbody == NULL)
1009                 RETURN(err_serious(-EPROTO));
1010
1011         repbody = req_capsule_server_get(&req->rq_pill, &RMF_QUOTA_BODY);
1012         if (repbody == NULL)
1013                 RETURN(err_serious(-EFAULT));
1014
1015         /* verify if global lock is stale */
1016         if (!lustre_handle_is_used(&qbody->qb_glb_lockh))
1017                 RETURN(-ENOLCK);
1018
1019         lock = ldlm_handle2lock(&qbody->qb_glb_lockh);
1020         if (lock == NULL)
1021                 RETURN(-ENOLCK);
1022         LDLM_LOCK_PUT(lock);
1023
1024         uuid = &req->rq_export->exp_client_uuid;
1025         stype = qmt_uuid2idx(uuid, &idx);
1026         if (stype < 0)
1027                 RETURN(stype);
1028
1029         if (req_is_rel(qbody->qb_flags) + req_is_acq(qbody->qb_flags) +
1030             req_is_preacq(qbody->qb_flags) > 1) {
1031                 CERROR("%s: malformed quota request with conflicting flags set "
1032                        "(%x) from slave %s\n", qmt->qmt_svname,
1033                        qbody->qb_flags, obd_uuid2str(uuid));
1034                 RETURN(-EPROTO);
1035         }
1036
1037         if (req_is_acq(qbody->qb_flags) || req_is_preacq(qbody->qb_flags)) {
1038                 /* acquire and pre-acquire should use a valid ID lock */
1039
1040                 if (!lustre_handle_is_used(&qbody->qb_lockh))
1041                         RETURN(-ENOLCK);
1042
1043                 lock = ldlm_handle2lock(&qbody->qb_lockh);
1044                 if (lock == NULL)
1045                         /* no lock associated with this handle */
1046                         RETURN(-ENOLCK);
1047
1048                 LDLM_DEBUG(lock, "%sacquire request",
1049                            req_is_preacq(qbody->qb_flags) ? "pre" : "");
1050
1051                 if (!obd_uuid_equals(&lock->l_export->exp_client_uuid, uuid)) {
1052                         /* sorry, no way to cheat ... */
1053                         LDLM_LOCK_PUT(lock);
1054                         RETURN(-ENOLCK);
1055                 }
1056
1057                 if (ldlm_is_ast_sent(lock)) {
1058                         struct ptlrpc_service_part *svc;
1059                         timeout_t timeout;
1060
1061                         svc = req->rq_rqbd->rqbd_svcpt;
1062                         timeout = at_est2timeout(at_get(&svc->scp_at_estimate));
1063                         timeout += (ldlm_bl_timeout(lock) >> 1);
1064
1065                         /* lock is being cancelled, prolong timeout */
1066                         ldlm_refresh_waiting_lock(lock, timeout);
1067                 }
1068                 LDLM_LOCK_PUT(lock);
1069         }
1070
1071         /* extract quota information from global index FID packed in the
1072          * request */
1073         rc = lquota_extract_fid(&qbody->qb_fid, &rtype, &qtype);
1074         if (rc)
1075                 RETURN(-EINVAL);
1076
1077         /* Find the quota entry associated with the quota id */
1078         rc = qmt_pool_lqes_lookup(env, qmt, rtype, stype, qtype,
1079                                   &qbody->qb_id, NULL, idx);
1080         if (rc)
1081                 RETURN(rc);
1082
1083         rc = qmt_dqacq0(env, qmt, uuid, qbody->qb_flags,
1084                         qbody->qb_count, qbody->qb_usage, repbody);
1085
1086         if (lustre_handle_is_used(&qbody->qb_lockh))
1087                 /* return current qunit value only to slaves owning an per-ID
1088                  * quota lock. For enqueue, the qunit value will be returned in
1089                  * the LVB */
1090                 repbody->qb_qunit = qti_lqes_min_qunit(env);
1091         CDEBUG(D_QUOTA, "qmt_dqacq return qb_qunit %llu qb_count %llu\n",
1092                repbody->qb_qunit, repbody->qb_count);
1093         qti_lqes_fini(env);
1094         RETURN(rc);
1095 }
1096
1097 /* Vector of quota request handlers. This vector is used by the MDT to forward
1098  * requests to the quota master. */
1099 struct qmt_handlers qmt_hdls = {
1100         /* quota request handlers */
1101         .qmth_quotactl          = qmt_quotactl,
1102         .qmth_dqacq             = qmt_dqacq,
1103
1104         /* ldlm handlers */
1105         .qmth_intent_policy     = qmt_intent_policy,
1106         .qmth_lvbo_init         = qmt_lvbo_init,
1107         .qmth_lvbo_update       = qmt_lvbo_update,
1108         .qmth_lvbo_size         = qmt_lvbo_size,
1109         .qmth_lvbo_fill         = qmt_lvbo_fill,
1110         .qmth_lvbo_free         = qmt_lvbo_free,
1111 };
1112 EXPORT_SYMBOL(qmt_hdls);