Whamcloud - gitweb
78876235dcfd711f28968ca365ec3710c1661dee
[fs/lustre-release.git] / lustre / target / tgt_grant.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, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2012, 2016, Intel Corporation.
27  */
28 /*
29  * lustre/target/tgt_grant.c
30  *
31  * This file provides code related to grant space management on Lustre Targets
32  * (OSTs and MDTs). Grant is a mechanism used by client nodes to reserve disk
33  * space on a target for the data writeback cache. The Lustre client is thus
34  * assured that enough space will be available when flushing dirty pages
35  * asynchronously. Each client node is granted an initial amount of reserved
36  * space at connect time and gets additional space back from target in bulk
37  * write reply.
38  *
39  * We actually support three different cases:
40  * - The client supports the new grant parameters (i.e. OBD_CONNECT_GRANT_PARAM)
41  *   which means that all grant overhead calculation happens on the client side.
42  *   The server reports at connect time the backend filesystem block size, the
43  *   maximum extent size as well as the extent insertion cost and it is then up
44  *   to the osc layer to the track dirty extents and consume grant accordingly
45  *   (see osc_cache.c). In each bulk write request, the client provides how much
46  *   grant space was consumed for this RPC.
47  * - The client does not support OBD_CONNECT_GRANT_PARAM and always assumes a
48  *   a backend file system block size of 4KB. We then have two cases:
49  *   - If the block size is really 4KB, then the client can deal with grant
50  *     allocation for partial block writes, but won't take extent insertion cost
51  *     into account. For such clients, we inflate grant by 100% on the server
52  *     side. It means that when 32MB of grant is hold by the client, 64MB of
53  *     grant space is actually reserved on the server. All grant counters
54  *     provided by such a client are inflated by 100%.
55  *   - The backend filesystem block size is bigger than 4KB, which isn't
56  *     supported by the client. In this case, we emulate a 4KB block size and
57  *     consume one block size on the server for each 4KB of grant returned to
58  *     client. With a 128KB blocksize, it means that 32MB dirty pages of 4KB
59  *     on the client will actually consume 1GB of grant on the server.
60  *     All grant counters provided by such a client are inflated by the block
61  *     size ratio.
62  *
63  * This file handles the core logic for:
64  * - grant allocation strategy
65  * - maintaining per-client as well as global grant space accounting
66  * - processing grant information packed in incoming requests
67  * - allocating server-side grant space for synchronous write RPCs which did not
68  *   consume grant on the client side (OBD_BRW_FROM_GRANT flag not set). If not
69  *   enough space is available, such RPCs fail with ENOSPC
70  *
71  * Author: Johann Lombardi <johann.lombardi@intel.com>
72  */
73
74 #define DEBUG_SUBSYSTEM S_FILTER
75
76 #include <obd.h>
77 #include <obd_class.h>
78
79 #include "tgt_internal.h"
80
81 /* Clients typically hold 2x their max_rpcs_in_flight of grant space */
82 #define TGT_GRANT_SHRINK_LIMIT(exp)     (2ULL * 8 * exp_max_brw_size(exp))
83
84 /* Helpers to inflate/deflate grants for clients that do not support the grant
85  * parameters */
86 static inline u64 tgt_grant_inflate(struct tg_grants_data *tgd, u64 val)
87 {
88         if (tgd->tgd_blockbits > COMPAT_BSIZE_SHIFT)
89                 /* Client does not support such large block size, grant
90                  * is thus inflated. We already significantly overestimate
91                  * overhead, no need to add the extent tax in this case */
92                 return val << (tgd->tgd_blockbits - COMPAT_BSIZE_SHIFT);
93         return val;
94 }
95
96 /* Companion of tgt_grant_inflate() */
97 static inline u64 tgt_grant_deflate(struct tg_grants_data *tgd, u64 val)
98 {
99         if (tgd->tgd_blockbits > COMPAT_BSIZE_SHIFT)
100                 return val >> (tgd->tgd_blockbits - COMPAT_BSIZE_SHIFT);
101         return val;
102 }
103
104 /* Grant chunk is used as a unit for grant allocation. It should be inflated
105  * if the client does not support the grant paramaters.
106  * Check connection flag against \a data if not NULL. This is used during
107  * connection creation where exp->exp_connect_data isn't populated yet */
108 static inline u64 tgt_grant_chunk(struct obd_export *exp,
109                                   struct lu_target *lut,
110                                   struct obd_connect_data *data)
111 {
112         struct tg_grants_data *tgd = &lut->lut_tgd;
113         u64 chunk = exp_max_brw_size(exp);
114         u64 tax;
115
116         if (exp->exp_obd->obd_self_export == exp)
117                 /* Grant enough space to handle a big precreate request */
118                 return OST_MAX_PRECREATE * lut->lut_dt_conf.ddp_inodespace / 2;
119
120         if ((data == NULL && !(exp_grant_param_supp(exp))) ||
121             (data != NULL && !OCD_HAS_FLAG(data, GRANT_PARAM)))
122                 /* Try to grant enough space to send 2 full-size RPCs */
123                 return tgt_grant_inflate(tgd, chunk) << 1;
124
125         /* Try to return enough to send two full-size RPCs
126          * = 2 * (BRW_size + #extents_in_BRW * grant_tax) */
127         tax = 1ULL << tgd->tgd_blockbits;            /* block size */
128         tax *= lut->lut_dt_conf.ddp_max_extent_blks; /* max extent size */
129         tax = (chunk + tax - 1) / tax;               /* #extents in a RPC */
130         tax *= lut->lut_dt_conf.ddp_extent_tax;      /* extent tax for a RPC */
131         chunk = (chunk + tax) * 2;                   /* we said two full RPCs */
132         return chunk;
133 }
134
135 static int tgt_check_export_grants(struct obd_export *exp, u64 *dirty,
136                                    u64 *pending, u64 *granted, u64 maxsize)
137 {
138         struct tg_export_data *ted = &exp->exp_target_data;
139         int level = D_CACHE;
140
141         if (ted->ted_grant < 0 || ted->ted_pending < 0 || ted->ted_dirty < 0)
142                 level = D_ERROR;
143         CDEBUG_LIMIT(level, "%s: cli %s/%p dirty %ld pend %ld grant %ld\n",
144                      exp->exp_obd->obd_name, exp->exp_client_uuid.uuid, exp,
145                      ted->ted_dirty, ted->ted_pending, ted->ted_grant);
146
147         if (ted->ted_grant + ted->ted_pending > maxsize) {
148                 CERROR("%s: cli %s/%p ted_grant(%ld) + ted_pending(%ld)"
149                         " > maxsize(%llu)\n", exp->exp_obd->obd_name,
150                         exp->exp_client_uuid.uuid, exp, ted->ted_grant,
151                         ted->ted_pending, maxsize);
152                 return -EFAULT;
153         }
154         if (ted->ted_dirty > maxsize) {
155                 CERROR("%s: cli %s/%p ted_dirty(%ld) > maxsize(%llu)\n",
156                         exp->exp_obd->obd_name, exp->exp_client_uuid.uuid,
157                         exp, ted->ted_dirty, maxsize);
158                 return -EFAULT;
159         }
160         *granted += ted->ted_grant + ted->ted_pending;
161         *pending += ted->ted_pending;
162         *dirty += ted->ted_dirty;
163         return 0;
164 }
165
166 /**
167  * Perform extra sanity checks for grant accounting.
168  *
169  * This function scans the export list, sanity checks per-export grant counters
170  * and verifies accuracy of global grant accounting. If an inconsistency is
171  * found, a CERROR is printed with the function name \func that was passed as
172  * argument. LBUG is only called in case of serious counter corruption (i.e.
173  * value larger than the device size).
174  * Those sanity checks can be pretty expensive and are disabled if the OBD
175  * device has more than 100 connected exports.
176  *
177  * \param[in] obd       OBD device for which grant accounting should be
178  *                      verified
179  * \param[in] func      caller's function name
180  */
181 void tgt_grant_sanity_check(struct obd_device *obd, const char *func)
182 {
183         struct lu_target *lut = obd->u.obt.obt_lut;
184         struct tg_grants_data *tgd = &lut->lut_tgd;
185         struct obd_export *exp;
186         struct tg_export_data *ted;
187         u64                maxsize;
188         u64                tot_dirty = 0;
189         u64                tot_pending = 0;
190         u64                tot_granted = 0;
191         u64                fo_tot_granted;
192         u64                fo_tot_pending;
193         u64                fo_tot_dirty;
194         int                error;
195
196         if (list_empty(&obd->obd_exports))
197                 return;
198
199         /* We don't want to do this for large machines that do lots of
200          * mounts or unmounts.  It burns... */
201         if (obd->obd_num_exports > 100)
202                 return;
203
204         maxsize = tgd->tgd_osfs.os_blocks << tgd->tgd_blockbits;
205
206         spin_lock(&obd->obd_dev_lock);
207         spin_lock(&tgd->tgd_grant_lock);
208         exp = obd->obd_self_export;
209         ted = &exp->exp_target_data;
210         CDEBUG(D_CACHE, "%s: processing self export: %ld %ld "
211                "%ld\n", obd->obd_name, ted->ted_grant,
212                ted->ted_pending, ted->ted_dirty);
213         tot_granted += ted->ted_grant + ted->ted_pending;
214         tot_pending += ted->ted_pending;
215         tot_dirty += ted->ted_dirty;
216
217         list_for_each_entry(exp, &obd->obd_exports, exp_obd_chain) {
218                 error = tgt_check_export_grants(exp, &tot_dirty, &tot_pending,
219                                                 &tot_granted, maxsize);
220                 if (error < 0) {
221                         spin_unlock(&obd->obd_dev_lock);
222                         spin_unlock(&tgd->tgd_grant_lock);
223                         LBUG();
224                 }
225         }
226
227         /* exports about to be unlinked should also be taken into account since
228          * they might still hold pending grant space to be released at
229          * commit time */
230         list_for_each_entry(exp, &obd->obd_unlinked_exports, exp_obd_chain) {
231                 error = tgt_check_export_grants(exp, &tot_dirty, &tot_pending,
232                                                 &tot_granted, maxsize);
233                 if (error < 0) {
234                         spin_unlock(&obd->obd_dev_lock);
235                         spin_unlock(&tgd->tgd_grant_lock);
236                         LBUG();
237                 }
238         }
239
240         fo_tot_granted = tgd->tgd_tot_granted;
241         fo_tot_pending = tgd->tgd_tot_pending;
242         fo_tot_dirty = tgd->tgd_tot_dirty;
243         spin_unlock(&obd->obd_dev_lock);
244         spin_unlock(&tgd->tgd_grant_lock);
245
246         if (tot_granted != fo_tot_granted)
247                 CERROR("%s: tot_granted %llu != fo_tot_granted %llu\n",
248                        func, tot_granted, fo_tot_granted);
249         if (tot_pending != fo_tot_pending)
250                 CERROR("%s: tot_pending %llu != fo_tot_pending %llu\n",
251                        func, tot_pending, fo_tot_pending);
252         if (tot_dirty != fo_tot_dirty)
253                 CERROR("%s: tot_dirty %llu != fo_tot_dirty %llu\n",
254                        func, tot_dirty, fo_tot_dirty);
255         if (tot_pending > tot_granted)
256                 CERROR("%s: tot_pending %llu > tot_granted %llu\n",
257                        func, tot_pending, tot_granted);
258         if (tot_granted > maxsize)
259                 CERROR("%s: tot_granted %llu > maxsize %llu\n",
260                        func, tot_granted, maxsize);
261         if (tot_dirty > maxsize)
262                 CERROR("%s: tot_dirty %llu > maxsize %llu\n",
263                        func, tot_dirty, maxsize);
264 }
265 EXPORT_SYMBOL(tgt_grant_sanity_check);
266
267 /**
268  * Get file system statistics of target.
269  *
270  * Helper function for statfs(), also used by grant code.
271  * Implements caching for statistics to avoid calling OSD device each time.
272  *
273  * \param[in]  env        execution environment
274  * \param[in]  lut        LU target
275  * \param[out] osfs       statistic data to return
276  * \param[in]  max_age    maximum age for cached data
277  * \param[in]  from_cache show that data was get from cache or not
278  *
279  * \retval              0 if successful
280  * \retval              negative value on error
281  */
282 int tgt_statfs_internal(const struct lu_env *env, struct lu_target *lut,
283                         struct obd_statfs *osfs, __u64 max_age, int *from_cache)
284 {
285         struct tg_grants_data *tgd = &lut->lut_tgd;
286         int rc = 0;
287         ENTRY;
288
289         spin_lock(&tgd->tgd_osfs_lock);
290         if (cfs_time_before_64(tgd->tgd_osfs_age, max_age) || max_age == 0) {
291                 u64 unstable;
292
293                 /* statfs data are too old, get up-to-date one.
294                  * we must be cautious here since multiple threads might be
295                  * willing to update statfs data concurrently and we must
296                  * grant that cached statfs data are always consistent */
297
298                 if (tgd->tgd_statfs_inflight == 0)
299                         /* clear inflight counter if no users, although it would
300                          * take a while to overflow this 64-bit counter ... */
301                         tgd->tgd_osfs_inflight = 0;
302                 /* notify tgt_grant_commit() that we want to track writes
303                  * completed as of now */
304                 tgd->tgd_statfs_inflight++;
305                 /* record value of inflight counter before running statfs to
306                  * compute the diff once statfs is completed */
307                 unstable = tgd->tgd_osfs_inflight;
308                 spin_unlock(&tgd->tgd_osfs_lock);
309
310                 /* statfs can sleep ... hopefully not for too long since we can
311                  * call it fairly often as space fills up */
312                 rc = dt_statfs(env, lut->lut_bottom, osfs);
313                 if (unlikely(rc))
314                         GOTO(out, rc);
315
316                 spin_lock(&tgd->tgd_grant_lock);
317                 spin_lock(&tgd->tgd_osfs_lock);
318                 /* calculate how much space was written while we released the
319                  * tgd_osfs_lock */
320                 unstable = tgd->tgd_osfs_inflight - unstable;
321                 tgd->tgd_osfs_unstable = 0;
322                 if (unstable) {
323                         /* some writes committed while we were running statfs
324                          * w/o the tgd_osfs_lock. Those ones got added to
325                          * the cached statfs data that we are about to crunch.
326                          * Take them into account in the new statfs data */
327                         osfs->os_bavail -= min_t(u64, osfs->os_bavail,
328                                                unstable >> tgd->tgd_blockbits);
329                         /* However, we don't really know if those writes got
330                          * accounted in the statfs call, so tell
331                          * tgt_grant_space_left() there is some uncertainty
332                          * on the accounting of those writes.
333                          * The purpose is to prevent spurious error messages in
334                          * tgt_grant_space_left() since those writes might be
335                          * accounted twice. */
336                         tgd->tgd_osfs_unstable += unstable;
337                 }
338                 /* similarly, there is some uncertainty on write requests
339                  * between prepare & commit */
340                 tgd->tgd_osfs_unstable += tgd->tgd_tot_pending;
341                 spin_unlock(&tgd->tgd_grant_lock);
342
343                 /* finally udpate cached statfs data */
344                 tgd->tgd_osfs = *osfs;
345                 tgd->tgd_osfs_age = cfs_time_current_64();
346
347                 tgd->tgd_statfs_inflight--; /* stop tracking */
348                 if (tgd->tgd_statfs_inflight == 0)
349                         tgd->tgd_osfs_inflight = 0;
350                 spin_unlock(&tgd->tgd_osfs_lock);
351
352                 if (from_cache)
353                         *from_cache = 0;
354         } else {
355                 /* use cached statfs data */
356                 *osfs = tgd->tgd_osfs;
357                 spin_unlock(&tgd->tgd_osfs_lock);
358                 if (from_cache)
359                         *from_cache = 1;
360         }
361         GOTO(out, rc);
362
363 out:
364         return rc;
365 }
366 EXPORT_SYMBOL(tgt_statfs_internal);
367
368 /**
369  * Update cached statfs information from the OSD layer
370  *
371  * Refresh statfs information cached in tgd::tgd_osfs if the cache is older
372  * than 1s or if force is set. The OSD layer is in charge of estimating data &
373  * metadata overhead.
374  * This function can sleep so it should not be called with any spinlock held.
375  *
376  * \param[in] env               LU environment passed by the caller
377  * \param[in] exp               export used to print client info in debug
378  *                              messages
379  * \param[in] force             force a refresh of statfs information
380  * \param[out] from_cache       returns whether the statfs information are
381  *                              taken from cache
382  */
383 static void tgt_grant_statfs(const struct lu_env *env, struct obd_export *exp,
384                              int force, int *from_cache)
385 {
386         struct obd_device       *obd = exp->exp_obd;
387         struct lu_target        *lut = obd->u.obt.obt_lut;
388         struct tg_grants_data   *tgd = &lut->lut_tgd;
389         struct tgt_thread_info  *tti;
390         struct obd_statfs       *osfs;
391         __u64                    max_age;
392         int                      rc;
393
394         if (force)
395                 max_age = 0; /* get fresh statfs data */
396         else
397                 max_age = cfs_time_shift_64(-OBD_STATFS_CACHE_SECONDS);
398
399         tti = tgt_th_info(env);
400         osfs = &tti->tti_u.osfs;
401         rc = tgt_statfs_internal(env, lut, osfs, max_age, from_cache);
402         if (unlikely(rc)) {
403                 if (from_cache)
404                         *from_cache = 0;
405                 return;
406         }
407
408         CDEBUG(D_CACHE, "%s: cli %s/%p free: %llu avail: %llu\n",
409                obd->obd_name, exp->exp_client_uuid.uuid, exp,
410                osfs->os_bfree << tgd->tgd_blockbits,
411                osfs->os_bavail << tgd->tgd_blockbits);
412 }
413
414 /**
415  * Figure out how much space is available on the backend filesystem after
416  * removing grant space already booked by clients.
417  *
418  * This is done by accessing cached statfs data previously populated by
419  * tgt_grant_statfs(), from which we withdraw the space already granted to
420  * clients and the reserved space.
421  * Caller must hold tgd_grant_lock spinlock.
422  *
423  * \param[in] exp       export associated with the device for which the amount
424  *                      of available space is requested
425  * \retval              amount of non-allocated space, in bytes
426  */
427 static u64 tgt_grant_space_left(struct obd_export *exp)
428 {
429         struct obd_device       *obd = exp->exp_obd;
430         struct lu_target        *lut = obd->u.obt.obt_lut;
431         struct tg_grants_data   *tgd = &lut->lut_tgd;
432         u64                      tot_granted;
433         u64                      left;
434         u64                      avail;
435         u64                      unstable;
436
437         ENTRY;
438         assert_spin_locked(&tgd->tgd_grant_lock);
439
440         spin_lock(&tgd->tgd_osfs_lock);
441         /* get available space from cached statfs data */
442         left = tgd->tgd_osfs.os_bavail << tgd->tgd_blockbits;
443         unstable = tgd->tgd_osfs_unstable; /* those might be accounted twice */
444         spin_unlock(&tgd->tgd_osfs_lock);
445
446         tot_granted = tgd->tgd_tot_granted;
447
448         if (left < tot_granted) {
449                 int mask = (left + unstable <
450                             tot_granted - tgd->tgd_tot_pending) ?
451                             D_ERROR : D_CACHE;
452
453                 CDEBUG_LIMIT(mask, "%s: cli %s/%p left %llu < tot_grant "
454                              "%llu unstable %llu pending %llu "
455                              "dirty %llu\n",
456                              obd->obd_name, exp->exp_client_uuid.uuid, exp,
457                              left, tot_granted, unstable,
458                              tgd->tgd_tot_pending,
459                              tgd->tgd_tot_dirty);
460                 RETURN(0);
461         }
462
463         avail = left;
464         /* Withdraw space already granted to clients */
465         left -= tot_granted;
466
467         /* Align left on block size */
468         left &= ~((1ULL << tgd->tgd_blockbits) - 1);
469
470         CDEBUG(D_CACHE, "%s: cli %s/%p avail %llu left %llu unstable "
471                "%llu tot_grant %llu pending %llu\n", obd->obd_name,
472                exp->exp_client_uuid.uuid, exp, avail, left, unstable,
473                tot_granted, tgd->tgd_tot_pending);
474
475         RETURN(left);
476 }
477
478 /**
479  * Process grant information from obdo structure packed in incoming BRW
480  * and inflate grant counters if required.
481  *
482  * Grab the dirty and seen grant announcements from the incoming obdo and
483  * inflate all grant counters passed in the request if the client does not
484  * support the grant parameters.
485  * We will later calculate the client's new grant and return it.
486  * Caller must hold tgd_grant_lock spinlock.
487  *
488  * \param[in] env       LU environment supplying osfs storage
489  * \param[in] exp       export for which we received the request
490  * \param[in,out] oa    incoming obdo sent by the client
491  */
492 static void tgt_grant_incoming(const struct lu_env *env, struct obd_export *exp,
493                                struct obdo *oa, long chunk)
494 {
495         struct tg_export_data   *ted = &exp->exp_target_data;
496         struct obd_device       *obd = exp->exp_obd;
497         struct tg_grants_data   *tgd = &obd->u.obt.obt_lut->lut_tgd;
498         long                     dirty;
499         long                     dropped;
500         ENTRY;
501
502         assert_spin_locked(&tgd->tgd_grant_lock);
503
504         if ((oa->o_valid & (OBD_MD_FLBLOCKS|OBD_MD_FLGRANT)) !=
505                                         (OBD_MD_FLBLOCKS|OBD_MD_FLGRANT)) {
506                 oa->o_valid &= ~OBD_MD_FLGRANT;
507                 RETURN_EXIT;
508         }
509
510         /* Add some margin, since there is a small race if other RPCs arrive
511          * out-or-order and have already consumed some grant.  We want to
512          * leave this here in case there is a large error in accounting. */
513         CDEBUG(D_CACHE,
514                "%s: cli %s/%p reports grant %llu dropped %u, local %lu\n",
515                obd->obd_name, exp->exp_client_uuid.uuid, exp, oa->o_grant,
516                oa->o_dropped, ted->ted_grant);
517
518         if ((long long)oa->o_dirty < 0)
519                 oa->o_dirty = 0;
520
521         /* inflate grant counters if required */
522         if (!exp_grant_param_supp(exp)) {
523                 oa->o_grant     = tgt_grant_inflate(tgd, oa->o_grant);
524                 oa->o_dirty     = tgt_grant_inflate(tgd, oa->o_dirty);
525                 oa->o_dropped   = tgt_grant_inflate(tgd, (u64)oa->o_dropped);
526                 oa->o_undirty   = tgt_grant_inflate(tgd, oa->o_undirty);
527         }
528
529         dirty = oa->o_dirty;
530         dropped = oa->o_dropped;
531
532         /* Update our accounting now so that statfs takes it into account.
533          * Note that ted_dirty is only approximate and can become incorrect
534          * if RPCs arrive out-of-order.  No important calculations depend
535          * on ted_dirty however, but we must check sanity to not assert. */
536         if (dirty > ted->ted_grant + 4 * chunk)
537                 dirty = ted->ted_grant + 4 * chunk;
538         tgd->tgd_tot_dirty += dirty - ted->ted_dirty;
539         if (ted->ted_grant < dropped) {
540                 CDEBUG(D_CACHE,
541                        "%s: cli %s/%p reports %lu dropped > grant %lu\n",
542                        obd->obd_name, exp->exp_client_uuid.uuid, exp, dropped,
543                        ted->ted_grant);
544                 dropped = 0;
545         }
546         if (tgd->tgd_tot_granted < dropped) {
547                 CERROR("%s: cli %s/%p reports %lu dropped > tot_grant %llu\n",
548                        obd->obd_name, exp->exp_client_uuid.uuid, exp,
549                        dropped, tgd->tgd_tot_granted);
550                 dropped = 0;
551         }
552         tgd->tgd_tot_granted -= dropped;
553         ted->ted_grant -= dropped;
554         ted->ted_dirty = dirty;
555
556         if (ted->ted_dirty < 0 || ted->ted_grant < 0 || ted->ted_pending < 0) {
557                 CERROR("%s: cli %s/%p dirty %ld pend %ld grant %ld\n",
558                        obd->obd_name, exp->exp_client_uuid.uuid, exp,
559                        ted->ted_dirty, ted->ted_pending, ted->ted_grant);
560                 spin_unlock(&tgd->tgd_grant_lock);
561                 LBUG();
562         }
563         EXIT;
564 }
565
566 /**
567  * Grant shrink request handler.
568  *
569  * Client nodes can explicitly release grant space (i.e. process called grant
570  * shrinking). This function proceeds with the shrink request when there is
571  * less ungranted space remaining than the amount all of the connected clients
572  * would consume if they used their full grant.
573  * Caller must hold tgd_grant_lock spinlock.
574  *
575  * \param[in] exp               export releasing grant space
576  * \param[in,out] oa            incoming obdo sent by the client
577  * \param[in] left_space        remaining free space with space already granted
578  *                              taken out
579  */
580 static void tgt_grant_shrink(struct obd_export *exp, struct obdo *oa,
581                              u64 left_space)
582 {
583         struct tg_export_data   *ted = &exp->exp_target_data;
584         struct obd_device       *obd = exp->exp_obd;
585         struct tg_grants_data   *tgd = &obd->u.obt.obt_lut->lut_tgd;
586         long                     grant_shrink;
587
588         assert_spin_locked(&tgd->tgd_grant_lock);
589         LASSERT(exp);
590         if (left_space >= tgd->tgd_tot_granted_clients *
591                           TGT_GRANT_SHRINK_LIMIT(exp))
592                 return;
593
594         grant_shrink = oa->o_grant;
595
596         ted->ted_grant -= grant_shrink;
597         tgd->tgd_tot_granted -= grant_shrink;
598
599         CDEBUG(D_CACHE, "%s: cli %s/%p shrink %ld ted_grant %ld total %llu\n",
600                obd->obd_name, exp->exp_client_uuid.uuid, exp, grant_shrink,
601                ted->ted_grant, tgd->tgd_tot_granted);
602
603         /* client has just released some grant, don't grant any space back */
604         oa->o_grant = 0;
605 }
606
607 /**
608  * Calculate how much space is required to write a given network buffer
609  *
610  * This function takes block alignment into account to estimate how much on-disk
611  * space will be required to successfully write the whole niobuf.
612  * Estimated space is inflated if the export does not support
613  * OBD_CONNECT_GRANT_PARAM and if the backend filesystem has a block size
614  * larger than the minimal supported page size (i.e. 4KB).
615  *
616  * \param[in] exp       export associated which the write request
617  *                      if NULL, then size estimate is done for server-side
618  *                      grant allocation.
619  * \param[in] lut       LU target handling the request
620  * \param[in] rnb       network buffer to estimate size of
621  *
622  * \retval              space (in bytes) that will be consumed to write the
623  *                      network buffer
624  */
625 static inline u64 tgt_grant_rnb_size(struct obd_export *exp,
626                                      struct lu_target *lut,
627                                      struct niobuf_remote *rnb)
628 {
629         struct tg_grants_data *tgd = &lut->lut_tgd;
630         u64 blksize;
631         u64 bytes;
632         u64 end;
633
634         if (exp && !exp_grant_param_supp(exp) &&
635             tgd->tgd_blockbits > COMPAT_BSIZE_SHIFT)
636                 blksize = 1ULL << COMPAT_BSIZE_SHIFT;
637         else
638                 blksize = 1ULL << tgd->tgd_blockbits;
639
640         /* The network buffer might span several blocks, align it on block
641          * boundaries */
642         bytes  = rnb->rnb_offset & (blksize - 1);
643         bytes += rnb->rnb_len;
644         end    = bytes & (blksize - 1);
645         if (end)
646                 bytes += blksize - end;
647
648         if (exp == NULL || exp_grant_param_supp(exp)) {
649                 /* add per-extent insertion cost */
650                 u64 max_ext;
651                 int nr_ext;
652
653                 max_ext = blksize * lut->lut_dt_conf.ddp_max_extent_blks;
654                 nr_ext = (bytes + max_ext - 1) / max_ext;
655                 bytes += nr_ext * lut->lut_dt_conf.ddp_extent_tax;
656         } else {
657                 /* Inflate grant space if client does not support extent-based
658                  * grant allocation */
659                 bytes = tgt_grant_inflate(tgd, (u64)bytes);
660         }
661
662         return bytes;
663 }
664
665 /**
666  * Validate grant accounting for each incoming remote network buffer.
667  *
668  * When clients have dirtied as much space as they've been granted they
669  * fall through to sync writes. These sync writes haven't been expressed
670  * in grants and need to error with ENOSPC when there isn't room in the
671  * filesystem for them after grants are taken into account. However,
672  * writeback of the dirty data that was already granted space can write
673  * right on through.
674  * The OBD_BRW_GRANTED flag will be set in the rnb_flags of each network
675  * buffer which has been granted enough space to proceed. Buffers without
676  * this flag will fail to be written with -ENOSPC (see tgt_preprw_write().
677  * Caller must hold tgd_grant_lock spinlock.
678  *
679  * \param[in] env       LU environment passed by the caller
680  * \param[in] exp       export identifying the client which sent the RPC
681  * \param[in] oa        incoming obdo in which we should return the pack the
682  *                      additional grant
683  * \param[in,out] rnb   the list of network buffers
684  * \param[in] niocount  the number of network buffers in the list
685  * \param[in] left      the remaining free space with space already granted
686  *                      taken out
687  */
688 static void tgt_grant_check(const struct lu_env *env, struct obd_export *exp,
689                             struct obdo *oa, struct niobuf_remote *rnb,
690                             int niocount, u64 *left)
691 {
692         struct tg_export_data   *ted = &exp->exp_target_data;
693         struct obd_device       *obd = exp->exp_obd;
694         struct lu_target        *lut = obd->u.obt.obt_lut;
695         struct tg_grants_data   *tgd = &lut->lut_tgd;
696         unsigned long            ungranted = 0;
697         unsigned long            granted = 0;
698         int                      i;
699         bool                     skip = false;
700
701         ENTRY;
702
703         assert_spin_locked(&tgd->tgd_grant_lock);
704
705         if (obd->obd_recovering) {
706                 /* Replaying write. Grant info have been processed already so no
707                  * need to do any enforcement here. It is worth noting that only
708                  * bulk writes with all rnbs having OBD_BRW_FROM_GRANT can be
709                  * replayed. If one page hasn't OBD_BRW_FROM_GRANT set, then
710                  * the whole bulk is written synchronously */
711                 skip = true;
712                 CDEBUG(D_CACHE, "Replaying write, skipping accounting\n");
713         } else if ((oa->o_valid & OBD_MD_FLFLAGS) &&
714                    (oa->o_flags & OBD_FL_RECOV_RESEND)) {
715                 /* Recoverable resend, grant info have already been processed as
716                  * well */
717                 skip = true;
718                 CDEBUG(D_CACHE, "Recoverable resend arrived, skipping "
719                                 "accounting\n");
720         } else if (exp_grant_param_supp(exp) && oa->o_grant_used > 0) {
721                 /* Client supports the new grant parameters and is telling us
722                  * how much grant space it consumed for this bulk write.
723                  * Although all rnbs are supposed to have the OBD_BRW_FROM_GRANT
724                  * flag set, we will scan the rnb list and looks for non-cache
725                  * I/O in case it changes in the future */
726                 if (ted->ted_grant >= oa->o_grant_used) {
727                         /* skip grant accounting for rnbs with
728                          * OBD_BRW_FROM_GRANT and just used grant consumption
729                          * claimed in the request */
730                         granted = oa->o_grant_used;
731                         skip = true;
732                 } else {
733                         /* client has used more grants for this request that
734                          * it owns ... */
735                         CERROR("%s: cli %s claims %lu GRANT, real grant %lu\n",
736                                exp->exp_obd->obd_name,
737                                exp->exp_client_uuid.uuid,
738                                (unsigned long)oa->o_grant_used, ted->ted_grant);
739
740                         /* check whether we can fill the gap with unallocated
741                          * grant */
742                         if (*left > (oa->o_grant_used - ted->ted_grant)) {
743                                 /* ouf .. we are safe for now */
744                                 granted = ted->ted_grant;
745                                 ungranted = oa->o_grant_used - granted;
746                                 *left -= ungranted;
747                                 skip = true;
748                         }
749                         /* too bad, but we cannot afford to blow up our grant
750                          * accounting. The loop below will handle each rnb in
751                          * case by case. */
752                 }
753         }
754
755         for (i = 0; i < niocount; i++) {
756                 int bytes;
757
758                 if ((rnb[i].rnb_flags & OBD_BRW_FROM_GRANT)) {
759                         if (skip) {
760                                 rnb[i].rnb_flags |= OBD_BRW_GRANTED;
761                                 continue;
762                         }
763
764                         /* compute how much grant space is actually needed for
765                          * this rnb, inflate grant if required */
766                         bytes = tgt_grant_rnb_size(exp, lut, &rnb[i]);
767                         if (ted->ted_grant >= granted + bytes) {
768                                 granted += bytes;
769                                 rnb[i].rnb_flags |= OBD_BRW_GRANTED;
770                                 continue;
771                         }
772
773                         CDEBUG(D_CACHE, "%s: cli %s/%p claims %ld+%d GRANT, "
774                                "real grant %lu idx %d\n", obd->obd_name,
775                                exp->exp_client_uuid.uuid, exp, granted, bytes,
776                                ted->ted_grant, i);
777                 }
778
779                 if (obd->obd_recovering)
780                         CERROR("%s: cli %s is replaying OST_WRITE while one rnb"
781                                " hasn't OBD_BRW_FROM_GRANT set (0x%x)\n",
782                                obd->obd_name, exp->exp_client_uuid.uuid,
783                                rnb[i].rnb_flags);
784
785                 /* Consume grant space on the server.
786                  * Unlike above, tgt_grant_rnb_size() is called with exp = NULL
787                  * so that the required grant space isn't inflated. This is
788                  * done on purpose since the server can deal with large block
789                  * size, unlike some clients */
790                 bytes = tgt_grant_rnb_size(NULL, lut, &rnb[i]);
791                 if (*left > bytes) {
792                         /* if enough space, pretend it was granted */
793                         ungranted += bytes;
794                         *left -= bytes;
795                         rnb[i].rnb_flags |= OBD_BRW_GRANTED;
796                         continue;
797                 }
798
799                 /* We can't check for already-mapped blocks here (make sense
800                  * when backend filesystem does not use COW) as it requires
801                  * dropping the grant lock.
802                  * Instead, we clear OBD_BRW_GRANTED and in that case we need
803                  * to go through and verify if all of the blocks not marked
804                  *  BRW_GRANTED are already mapped and we can ignore this error.
805                  */
806                 rnb[i].rnb_flags &= ~OBD_BRW_GRANTED;
807                 CDEBUG(D_CACHE, "%s: cli %s/%p idx %d no space for %d\n",
808                        obd->obd_name, exp->exp_client_uuid.uuid, exp, i, bytes);
809         }
810
811         /* record in o_grant_used the actual space reserved for the I/O, will be
812          * used later in tgt_grant_commmit() */
813         oa->o_grant_used = granted + ungranted;
814
815         /* record space used for the I/O, will be used in tgt_grant_commmit() */
816         /* Now substract what the clients has used already.  We don't subtract
817          * this from the tot_granted yet, so that other client's can't grab
818          * that space before we have actually allocated our blocks. That
819          * happens in tgt_grant_commit() after the writes are done. */
820         ted->ted_grant -= granted;
821         ted->ted_pending += oa->o_grant_used;
822         tgd->tgd_tot_granted += ungranted;
823         tgd->tgd_tot_pending += oa->o_grant_used;
824
825         CDEBUG(D_CACHE,
826                "%s: cli %s/%p granted: %lu ungranted: %lu grant: %lu dirty: %lu"
827                "\n", obd->obd_name, exp->exp_client_uuid.uuid, exp,
828                granted, ungranted, ted->ted_grant, ted->ted_dirty);
829
830         if (obd->obd_recovering || (oa->o_valid & OBD_MD_FLGRANT) == 0)
831                 /* don't update dirty accounting during recovery or
832                  * if grant information got discarded (e.g. during resend) */
833                 RETURN_EXIT;
834
835         if (ted->ted_dirty < granted) {
836                 CWARN("%s: cli %s/%p claims granted %lu > ted_dirty %lu\n",
837                        obd->obd_name, exp->exp_client_uuid.uuid, exp,
838                        granted, ted->ted_dirty);
839                 granted = ted->ted_dirty;
840         }
841         tgd->tgd_tot_dirty -= granted;
842         ted->ted_dirty -= granted;
843
844         if (ted->ted_dirty < 0 || ted->ted_grant < 0 || ted->ted_pending < 0) {
845                 CERROR("%s: cli %s/%p dirty %ld pend %ld grant %ld\n",
846                        obd->obd_name, exp->exp_client_uuid.uuid, exp,
847                        ted->ted_dirty, ted->ted_pending, ted->ted_grant);
848                 spin_unlock(&tgd->tgd_grant_lock);
849                 LBUG();
850         }
851         EXIT;
852 }
853
854 /**
855  * Allocate additional grant space to a client
856  *
857  * Calculate how much grant space to return to client, based on how much space
858  * is currently free and how much of that is already granted.
859  * Caller must hold tgd_grant_lock spinlock.
860  *
861  * \param[in] exp               export of the client which sent the request
862  * \param[in] curgrant          current grant claimed by the client
863  * \param[in] want              how much grant space the client would like to
864  *                              have
865  * \param[in] left              remaining free space with granted space taken
866  *                              out
867  * \param[in] conservative      if set to true, the server should be cautious
868  *                              and limit how much space is granted back to the
869  *                              client. Otherwise, the server should try hard to
870  *                              satisfy the client request.
871  *
872  * \retval                      amount of grant space allocated
873  */
874 static long tgt_grant_alloc(struct obd_export *exp, u64 curgrant,
875                             u64 want, u64 left, long chunk,
876                             bool conservative)
877 {
878         struct obd_device       *obd = exp->exp_obd;
879         struct tg_grants_data   *tgd = &obd->u.obt.obt_lut->lut_tgd;
880         struct tg_export_data   *ted = &exp->exp_target_data;
881         u64                      grant;
882
883         ENTRY;
884
885         /* When tgd_grant_compat_disable is set, we don't grant any space to
886          * clients not supporting OBD_CONNECT_GRANT_PARAM.
887          * Otherwise, space granted to such a client is inflated since it
888          * consumes PAGE_SIZE of grant space per block */
889         if ((obd->obd_self_export != exp && !exp_grant_param_supp(exp) &&
890              tgd->tgd_grant_compat_disable) || left == 0 || exp->exp_failed)
891                 RETURN(0);
892
893         if (want > 0x7fffffff) {
894                 CERROR("%s: client %s/%p requesting > 2GB grant %llu\n",
895                        obd->obd_name, exp->exp_client_uuid.uuid, exp, want);
896                 RETURN(0);
897         }
898
899         /* Grant some fraction of the client's requested grant space so that
900          * they are not always waiting for write credits (not all of it to
901          * avoid overgranting in face of multiple RPCs in flight).  This
902          * essentially will be able to control the OSC_MAX_RIF for a client.
903          *
904          * If we do have a large disparity between what the client thinks it
905          * has and what we think it has, don't grant very much and let the
906          * client consume its grant first.  Either it just has lots of RPCs
907          * in flight, or it was evicted and its grants will soon be used up. */
908         if (curgrant >= want || curgrant >= ted->ted_grant + chunk)
909                 RETURN(0);
910
911         if (obd->obd_recovering)
912                 conservative = false;
913
914         if (conservative)
915                 /* don't grant more than 1/8th of the remaining free space in
916                  * one chunk */
917                 left >>= 3;
918         grant = min(want - curgrant, left);
919         /* round grant up to the next block size */
920         grant = (grant + (1 << tgd->tgd_blockbits) - 1) &
921                 ~((1ULL << tgd->tgd_blockbits) - 1);
922
923         if (!grant)
924                 RETURN(0);
925
926         /* Limit to grant_chunk if not reconnect/recovery */
927         if ((grant > chunk) && conservative)
928                 grant = chunk;
929
930         tgd->tgd_tot_granted += grant;
931         ted->ted_grant += grant;
932
933         if (ted->ted_grant < 0) {
934                 CERROR("%s: cli %s/%p grant %ld want %llu current %llu\n",
935                        obd->obd_name, exp->exp_client_uuid.uuid, exp,
936                        ted->ted_grant, want, curgrant);
937                 spin_unlock(&tgd->tgd_grant_lock);
938                 LBUG();
939         }
940
941         CDEBUG(D_CACHE,
942                "%s: cli %s/%p wants: %llu current grant %llu"
943                " granting: %llu\n", obd->obd_name, exp->exp_client_uuid.uuid,
944                exp, want, curgrant, grant);
945         CDEBUG(D_CACHE,
946                "%s: cli %s/%p tot cached:%llu granted:%llu"
947                " num_exports: %d\n", obd->obd_name, exp->exp_client_uuid.uuid,
948                exp, tgd->tgd_tot_dirty, tgd->tgd_tot_granted,
949                obd->obd_num_exports);
950
951         RETURN(grant);
952 }
953
954 /**
955  * Handle grant space allocation on client connection & reconnection.
956  *
957  * A new non-readonly connection gets an initial grant allocation equals to
958  * tgt_grant_chunk() (i.e. twice the max BRW size in most of the cases).
959  * On reconnection, grant counters between client & target are resynchronized
960  * and additional space might be granted back if possible.
961  *
962  * \param[in] env       LU environment provided by the caller
963  * \param[in] exp       client's export which is (re)connecting
964  * \param[in,out] data  obd_connect_data structure sent by the client in the
965  *                      connect request
966  * \param[in] new_conn  must set to true if this is a new connection and false
967  *                      for a reconnection
968  */
969 void tgt_grant_connect(const struct lu_env *env, struct obd_export *exp,
970                        struct obd_connect_data *data, bool new_conn)
971 {
972         struct lu_target        *lut = exp->exp_obd->u.obt.obt_lut;
973         struct tg_grants_data   *tgd = &lut->lut_tgd;
974         struct tg_export_data   *ted = &exp->exp_target_data;
975         u64                      left = 0;
976         u64                      want;
977         long                     chunk;
978         int                      from_cache;
979         int                      force = 0; /* can use cached data */
980
981         /* don't grant space to client with read-only access */
982         if (OCD_HAS_FLAG(data, RDONLY) ||
983             (!OCD_HAS_FLAG(data, GRANT_PARAM) &&
984              tgd->tgd_grant_compat_disable)) {
985                 data->ocd_grant = 0;
986                 data->ocd_connect_flags &= ~(OBD_CONNECT_GRANT |
987                                              OBD_CONNECT_GRANT_PARAM);
988                 RETURN_EXIT;
989         }
990
991         if (OCD_HAS_FLAG(data, GRANT_PARAM))
992                 want = data->ocd_grant;
993         else
994                 want = tgt_grant_inflate(tgd, data->ocd_grant);
995         chunk = tgt_grant_chunk(exp, lut, data);
996 refresh:
997         tgt_grant_statfs(env, exp, force, &from_cache);
998
999         spin_lock(&tgd->tgd_grant_lock);
1000
1001         /* Grab free space from cached info and take out space already granted
1002          * to clients as well as reserved space */
1003         left = tgt_grant_space_left(exp);
1004
1005         /* get fresh statfs data if we are short in ungranted space */
1006         if (from_cache && left < 32 * chunk) {
1007                 spin_unlock(&tgd->tgd_grant_lock);
1008                 CDEBUG(D_CACHE, "fs has no space left and statfs too old\n");
1009                 force = 1;
1010                 goto refresh;
1011         }
1012
1013         tgt_grant_alloc(exp, (u64)ted->ted_grant, want, left, chunk, new_conn);
1014
1015         /* return to client its current grant */
1016         if (OCD_HAS_FLAG(data, GRANT_PARAM))
1017                 data->ocd_grant = ted->ted_grant;
1018         else
1019                 /* deflate grant */
1020                 data->ocd_grant = tgt_grant_deflate(tgd, (u64)ted->ted_grant);
1021
1022         /* reset dirty accounting */
1023         tgd->tgd_tot_dirty -= ted->ted_dirty;
1024         ted->ted_dirty = 0;
1025
1026         if (new_conn && OCD_HAS_FLAG(data, GRANT))
1027                 tgd->tgd_tot_granted_clients++;
1028
1029         spin_unlock(&tgd->tgd_grant_lock);
1030
1031         CDEBUG(D_CACHE, "%s: cli %s/%p ocd_grant: %d want: %llu left: %llu\n",
1032                exp->exp_obd->obd_name, exp->exp_client_uuid.uuid,
1033                exp, data->ocd_grant, want, left);
1034
1035         EXIT;
1036 }
1037 EXPORT_SYMBOL(tgt_grant_connect);
1038
1039 /**
1040  * Release all grant space attached to a given export.
1041  *
1042  * Remove a client from the grant accounting totals.  We also remove
1043  * the export from the obd device under the osfs and dev locks to ensure
1044  * that the tgt_grant_sanity_check() calculations are always valid.
1045  * The client should do something similar when it invalidates its import.
1046  *
1047  * \param[in] exp       client's export to remove from grant accounting
1048  */
1049 void tgt_grant_discard(struct obd_export *exp)
1050 {
1051         struct obd_device       *obd = exp->exp_obd;
1052         struct tg_grants_data   *tgd = &obd->u.obt.obt_lut->lut_tgd;
1053         struct tg_export_data   *ted = &exp->exp_target_data;
1054
1055         spin_lock(&tgd->tgd_grant_lock);
1056         LASSERTF(tgd->tgd_tot_granted >= ted->ted_grant,
1057                  "%s: tot_granted %llu cli %s/%p ted_grant %ld\n",
1058                  obd->obd_name, tgd->tgd_tot_granted,
1059                  exp->exp_client_uuid.uuid, exp, ted->ted_grant);
1060         tgd->tgd_tot_granted -= ted->ted_grant;
1061         ted->ted_grant = 0;
1062         LASSERTF(tgd->tgd_tot_pending >= ted->ted_pending,
1063                  "%s: tot_pending %llu cli %s/%p ted_pending %ld\n",
1064                  obd->obd_name, tgd->tgd_tot_pending,
1065                  exp->exp_client_uuid.uuid, exp, ted->ted_pending);
1066         /* tgd_tot_pending is handled in tgt_grant_commit as bulk
1067          * commmits */
1068         LASSERTF(tgd->tgd_tot_dirty >= ted->ted_dirty,
1069                  "%s: tot_dirty %llu cli %s/%p ted_dirty %ld\n",
1070                  obd->obd_name, tgd->tgd_tot_dirty,
1071                  exp->exp_client_uuid.uuid, exp, ted->ted_dirty);
1072         tgd->tgd_tot_dirty -= ted->ted_dirty;
1073         ted->ted_dirty = 0;
1074         spin_unlock(&tgd->tgd_grant_lock);
1075 }
1076 EXPORT_SYMBOL(tgt_grant_discard);
1077
1078 /**
1079  * Process grant information from incoming bulk read request.
1080  *
1081  * Extract grant information packed in obdo structure (OBD_MD_FLGRANT set in
1082  * o_valid). Bulk reads usually comes with grant announcements (number of dirty
1083  * blocks, remaining amount of grant space, ...) and could also include a grant
1084  * shrink request. Unlike bulk write, no additional grant space is returned on
1085  * bulk read request.
1086  *
1087  * \param[in] env       is the lu environment provided by the caller
1088  * \param[in] exp       is the export of the client which sent the request
1089  * \param[in,out] oa    is the incoming obdo sent by the client
1090  */
1091 void tgt_grant_prepare_read(const struct lu_env *env,
1092                             struct obd_export *exp, struct obdo *oa)
1093 {
1094         struct lu_target        *lut = exp->exp_obd->u.obt.obt_lut;
1095         struct tg_grants_data   *tgd = &lut->lut_tgd;
1096         int                      do_shrink;
1097         u64                      left = 0;
1098
1099         ENTRY;
1100
1101         if (!oa)
1102                 RETURN_EXIT;
1103
1104         if ((oa->o_valid & OBD_MD_FLGRANT) == 0)
1105                 /* The read request does not contain any grant
1106                  * information */
1107                 RETURN_EXIT;
1108
1109         if ((oa->o_valid & OBD_MD_FLFLAGS) &&
1110             (oa->o_flags & OBD_FL_SHRINK_GRANT)) {
1111                 /* To process grant shrink request, we need to know how much
1112                  * available space remains on the backend filesystem.
1113                  * Shrink requests are not so common, we always get fresh
1114                  * statfs information. */
1115                 tgt_grant_statfs(env, exp, 1, NULL);
1116
1117                 /* protect all grant counters */
1118                 spin_lock(&tgd->tgd_grant_lock);
1119
1120                 /* Grab free space from cached statfs data and take out space
1121                  * already granted to clients as well as reserved space */
1122                 left = tgt_grant_space_left(exp);
1123
1124                 /* all set now to proceed with shrinking */
1125                 do_shrink = 1;
1126         } else {
1127                 /* no grant shrinking request packed in the obdo and
1128                  * since we don't grant space back on reads, no point
1129                  * in running statfs, so just skip it and process
1130                  * incoming grant data directly. */
1131                 spin_lock(&tgd->tgd_grant_lock);
1132                 do_shrink = 0;
1133         }
1134
1135         /* extract incoming grant information provided by the client and
1136          * inflate grant counters if required */
1137         tgt_grant_incoming(env, exp, oa, tgt_grant_chunk(exp, lut, NULL));
1138
1139         /* unlike writes, we don't return grants back on reads unless a grant
1140          * shrink request was packed and we decided to turn it down. */
1141         if (do_shrink)
1142                 tgt_grant_shrink(exp, oa, left);
1143         else
1144                 oa->o_grant = 0;
1145
1146         if (!exp_grant_param_supp(exp))
1147                 oa->o_grant = tgt_grant_deflate(tgd, oa->o_grant);
1148         spin_unlock(&tgd->tgd_grant_lock);
1149         EXIT;
1150 }
1151 EXPORT_SYMBOL(tgt_grant_prepare_read);
1152
1153 /**
1154  * Process grant information from incoming bulk write request.
1155  *
1156  * This function extracts client's grant announcements from incoming bulk write
1157  * request and attempts to allocate grant space for network buffers that need it
1158  * (i.e. OBD_BRW_FROM_GRANT not set in rnb_fags).
1159  * Network buffers which aren't granted the OBD_BRW_GRANTED flag should not
1160  * proceed further and should fail with -ENOSPC.
1161  * Whenever possible, additional grant space will be returned to the client
1162  * in the bulk write reply.
1163  * tgt_grant_prepare_write() must be called before writting any buffers to
1164  * the backend storage. This function works in pair with tgt_grant_commit()
1165  * which must be invoked once all buffers have been written to disk in order
1166  * to release space from the pending grant counter.
1167  *
1168  * \param[in] env       LU environment provided by the caller
1169  * \param[in] exp       export of the client which sent the request
1170  * \param[in] oa        incoming obdo sent by the client
1171  * \param[in] rnb       list of network buffers
1172  * \param[in] niocount  number of network buffers in the list
1173  */
1174 void tgt_grant_prepare_write(const struct lu_env *env,
1175                              struct obd_export *exp, struct obdo *oa,
1176                              struct niobuf_remote *rnb, int niocount)
1177 {
1178         struct obd_device       *obd = exp->exp_obd;
1179         struct lu_target        *lut = obd->u.obt.obt_lut;
1180         struct tg_grants_data   *tgd = &lut->lut_tgd;
1181         u64                      left;
1182         int                      from_cache;
1183         int                      force = 0; /* can use cached data intially */
1184         long                     chunk = tgt_grant_chunk(exp, lut, NULL);
1185
1186         ENTRY;
1187
1188 refresh:
1189         /* get statfs information from OSD layer */
1190         tgt_grant_statfs(env, exp, force, &from_cache);
1191
1192         spin_lock(&tgd->tgd_grant_lock); /* protect all grant counters */
1193
1194         /* Grab free space from cached statfs data and take out space already
1195          * granted to clients as well as reserved space */
1196         left = tgt_grant_space_left(exp);
1197
1198         /* Get fresh statfs data if we are short in ungranted space */
1199         if (from_cache && left < 32 * chunk) {
1200                 spin_unlock(&tgd->tgd_grant_lock);
1201                 CDEBUG(D_CACHE, "%s: fs has no space left and statfs too old\n",
1202                        obd->obd_name);
1203                 force = 1;
1204                 goto refresh;
1205         }
1206
1207         /* When close to free space exhaustion, trigger a sync to force
1208          * writeback cache to consume required space immediately and release as
1209          * much space as possible. */
1210         if (!obd->obd_recovering && force != 2 && left < chunk) {
1211                 bool from_grant = true;
1212                 int  i;
1213
1214                 /* That said, it is worth running a sync only if some pages did
1215                  * not consume grant space on the client and could thus fail
1216                  * with ENOSPC later in tgt_grant_check() */
1217                 for (i = 0; i < niocount; i++)
1218                         if (!(rnb[i].rnb_flags & OBD_BRW_FROM_GRANT))
1219                                 from_grant = false;
1220
1221                 if (!from_grant) {
1222                         /* at least one network buffer requires acquiring grant
1223                          * space on the server */
1224                         spin_unlock(&tgd->tgd_grant_lock);
1225                         /* discard errors, at least we tried ... */
1226                         dt_sync(env, lut->lut_bottom);
1227                         force = 2;
1228                         goto refresh;
1229                 }
1230         }
1231
1232         /* extract incoming grant information provided by the client,
1233          * and inflate grant counters if required */
1234         tgt_grant_incoming(env, exp, oa, chunk);
1235
1236         /* check limit */
1237         tgt_grant_check(env, exp, oa, rnb, niocount, &left);
1238
1239         if (!(oa->o_valid & OBD_MD_FLGRANT)) {
1240                 spin_unlock(&tgd->tgd_grant_lock);
1241                 RETURN_EXIT;
1242         }
1243
1244         /* if OBD_FL_SHRINK_GRANT is set, the client is willing to release some
1245          * grant space. */
1246         if ((oa->o_valid & OBD_MD_FLFLAGS) &&
1247             (oa->o_flags & OBD_FL_SHRINK_GRANT))
1248                 tgt_grant_shrink(exp, oa, left);
1249         else
1250                 /* grant more space back to the client if possible */
1251                 oa->o_grant = tgt_grant_alloc(exp, oa->o_grant, oa->o_undirty,
1252                                               left, chunk, true);
1253
1254         if (!exp_grant_param_supp(exp))
1255                 oa->o_grant = tgt_grant_deflate(tgd, oa->o_grant);
1256         spin_unlock(&tgd->tgd_grant_lock);
1257         EXIT;
1258 }
1259 EXPORT_SYMBOL(tgt_grant_prepare_write);
1260
1261 /**
1262  * Consume grant space reserved for object creation.
1263  *
1264  * Grant space is allocated to the local self export for object precreation.
1265  * This is required to prevent object precreation from consuming grant space
1266  * allocated to client nodes for the data writeback cache.
1267  * This function consumes enough space to create \a nr objects and allocates
1268  * more grant space to the self export for future precreation requests, if
1269  * possible.
1270  *
1271  * \param[in] env       LU environment provided by the caller
1272  * \param[in] exp       export holding the grant space for precreation (= self
1273  *                      export currently)
1274  * \param[in] nr        number of objects to be created
1275  *
1276  * \retval >= 0         amount of grant space allocated to the precreate request
1277  * \retval -ENOSPC      on failure
1278  */
1279 long tgt_grant_create(const struct lu_env *env, struct obd_export *exp, s64 *nr)
1280 {
1281         struct lu_target        *lut = exp->exp_obd->u.obt.obt_lut;
1282         struct tg_grants_data   *tgd = &lut->lut_tgd;
1283         struct tg_export_data   *ted = &exp->exp_target_data;
1284         u64                      left = 0;
1285         unsigned long            wanted;
1286         unsigned long            granted;
1287         ENTRY;
1288
1289         if (exp->exp_obd->obd_recovering ||
1290             lut->lut_dt_conf.ddp_inodespace == 0)
1291                 /* don't enforce grant during recovery */
1292                 RETURN(0);
1293
1294         /* Update statfs data if required */
1295         tgt_grant_statfs(env, exp, 1, NULL);
1296
1297         /* protect all grant counters */
1298         spin_lock(&tgd->tgd_grant_lock);
1299
1300         /* fail precreate request if there is not enough blocks available for
1301          * writing */
1302         if (tgd->tgd_osfs.os_bavail - (ted->ted_grant >> tgd->tgd_blockbits) <
1303             (tgd->tgd_osfs.os_blocks >> 10)) {
1304                 spin_unlock(&tgd->tgd_grant_lock);
1305                 CDEBUG(D_RPCTRACE, "%s: not enough space for create %llu\n",
1306                        exp->exp_obd->obd_name,
1307                        tgd->tgd_osfs.os_bavail * tgd->tgd_osfs.os_blocks);
1308                 RETURN(-ENOSPC);
1309         }
1310
1311         /* Grab free space from cached statfs data and take out space
1312          * already granted to clients as well as reserved space */
1313         left = tgt_grant_space_left(exp);
1314
1315         /* compute how much space is required to handle the precreation
1316          * request */
1317         wanted = *nr * lut->lut_dt_conf.ddp_inodespace;
1318         if (wanted > ted->ted_grant + left) {
1319                 /* that's beyond what remains, adjust the number of objects that
1320                  * can be safely precreated */
1321                 wanted = ted->ted_grant + left;
1322                 *nr = wanted / lut->lut_dt_conf.ddp_inodespace;
1323                 if (*nr == 0) {
1324                         /* we really have no space any more for precreation,
1325                          * fail the precreate request with ENOSPC */
1326                         spin_unlock(&tgd->tgd_grant_lock);
1327                         RETURN(-ENOSPC);
1328                 }
1329                 /* compute space needed for the new number of creations */
1330                 wanted = *nr * lut->lut_dt_conf.ddp_inodespace;
1331         }
1332         LASSERT(wanted <= ted->ted_grant + left);
1333
1334         if (wanted <= ted->ted_grant) {
1335                 /* we've enough grant space to handle this precreate request */
1336                 ted->ted_grant -= wanted;
1337         } else {
1338                 /* we need to take some space from the ungranted pool */
1339                 tgd->tgd_tot_granted += wanted - ted->ted_grant;
1340                 left -= wanted - ted->ted_grant;
1341                 ted->ted_grant = 0;
1342         }
1343         granted = wanted;
1344         ted->ted_pending += granted;
1345         tgd->tgd_tot_pending += granted;
1346
1347         /* grant more space for precreate purpose if possible. */
1348         wanted = OST_MAX_PRECREATE * lut->lut_dt_conf.ddp_inodespace / 2;
1349         if (wanted > ted->ted_grant) {
1350                 long chunk;
1351
1352                 /* always try to book enough space to handle a large precreate
1353                  * request */
1354                 chunk = tgt_grant_chunk(exp, lut, NULL);
1355                 wanted -= ted->ted_grant;
1356                 tgt_grant_alloc(exp, ted->ted_grant, wanted, left, chunk,
1357                                 false);
1358         }
1359         spin_unlock(&tgd->tgd_grant_lock);
1360         RETURN(granted);
1361 }
1362 EXPORT_SYMBOL(tgt_grant_create);
1363
1364 /**
1365  * Release grant space added to the pending counter by tgt_grant_prepare_write()
1366  *
1367  * Update pending grant counter once buffers have been written to the disk.
1368  *
1369  * \param[in] exp       export of the client which sent the request
1370  * \param[in] pending   amount of reserved space to be released
1371  * \param[in] rc        return code of pre-commit operations
1372  */
1373 void tgt_grant_commit(struct obd_export *exp, unsigned long pending,
1374                       int rc)
1375 {
1376         struct tg_grants_data *tgd = &exp->exp_obd->u.obt.obt_lut->lut_tgd;
1377
1378         ENTRY;
1379
1380         /* get space accounted in tot_pending for the I/O, set in
1381          * tgt_grant_check() */
1382         if (pending == 0)
1383                 RETURN_EXIT;
1384
1385         spin_lock(&tgd->tgd_grant_lock);
1386         /* Don't update statfs data for errors raised before commit (e.g.
1387          * bulk transfer failed, ...) since we know those writes have not been
1388          * processed. For other errors hit during commit, we cannot really tell
1389          * whether or not something was written, so we update statfs data.
1390          * In any case, this should not be fatal since we always get fresh
1391          * statfs data before failing a request with ENOSPC */
1392         if (rc == 0) {
1393                 spin_lock(&tgd->tgd_osfs_lock);
1394                 /* Take pending out of cached statfs data */
1395                 tgd->tgd_osfs.os_bavail -= min_t(u64,
1396                                                  tgd->tgd_osfs.os_bavail,
1397                                                  pending >> tgd->tgd_blockbits);
1398                 if (tgd->tgd_statfs_inflight)
1399                         /* someone is running statfs and want to be notified of
1400                          * writes happening meanwhile */
1401                         tgd->tgd_osfs_inflight += pending;
1402                 spin_unlock(&tgd->tgd_osfs_lock);
1403         }
1404
1405         if (exp->exp_target_data.ted_pending < pending) {
1406                 CERROR("%s: cli %s/%p ted_pending(%lu) < grant_used(%lu)\n",
1407                        exp->exp_obd->obd_name, exp->exp_client_uuid.uuid, exp,
1408                        exp->exp_target_data.ted_pending, pending);
1409                 spin_unlock(&tgd->tgd_grant_lock);
1410                 LBUG();
1411         }
1412         exp->exp_target_data.ted_pending -= pending;
1413
1414         if (tgd->tgd_tot_granted < pending) {
1415                 CERROR("%s: cli %s/%p tot_granted(%llu) < grant_used(%lu)\n",
1416                        exp->exp_obd->obd_name, exp->exp_client_uuid.uuid, exp,
1417                        tgd->tgd_tot_granted, pending);
1418                 spin_unlock(&tgd->tgd_grant_lock);
1419                 LBUG();
1420         }
1421         tgd->tgd_tot_granted -= pending;
1422
1423         if (tgd->tgd_tot_pending < pending) {
1424                 CERROR("%s: cli %s/%p tot_pending(%llu) < grant_used(%lu)\n",
1425                        exp->exp_obd->obd_name, exp->exp_client_uuid.uuid, exp,
1426                        tgd->tgd_tot_pending, pending);
1427                 spin_unlock(&tgd->tgd_grant_lock);
1428                 LBUG();
1429         }
1430         tgd->tgd_tot_pending -= pending;
1431         spin_unlock(&tgd->tgd_grant_lock);
1432         EXIT;
1433 }
1434 EXPORT_SYMBOL(tgt_grant_commit);
1435
1436 struct tgt_grant_cb {
1437         /* commit callback structure */
1438         struct dt_txn_commit_cb  tgc_cb;
1439         /* export associated with the bulk write */
1440         struct obd_export       *tgc_exp;
1441         /* pending grant to be released */
1442         unsigned long            tgc_granted;
1443 };
1444
1445 /**
1446  * Callback function for grant releasing
1447  *
1448  * Release grant space reserved by the client node.
1449  *
1450  * \param[in] env       execution environment
1451  * \param[in] th        transaction handle
1452  * \param[in] cb        callback data
1453  * \param[in] err       error code
1454  */
1455 static void tgt_grant_commit_cb(struct lu_env *env, struct thandle *th,
1456                                 struct dt_txn_commit_cb *cb, int err)
1457 {
1458         struct tgt_grant_cb *tgc;
1459
1460         tgc = container_of(cb, struct tgt_grant_cb, tgc_cb);
1461
1462         tgt_grant_commit(tgc->tgc_exp, tgc->tgc_granted, err);
1463         class_export_cb_put(tgc->tgc_exp);
1464         OBD_FREE_PTR(tgc);
1465 }
1466
1467 /**
1468  * Add callback for grant releasing
1469  *
1470  * Register a commit callback to release grant space.
1471  *
1472  * \param[in] th        transaction handle
1473  * \param[in] exp       OBD export of client
1474  * \param[in] granted   amount of grant space to be released upon commit
1475  *
1476  * \retval              0 on successful callback adding
1477  * \retval              negative value on error
1478  */
1479 int tgt_grant_commit_cb_add(struct thandle *th, struct obd_export *exp,
1480                             unsigned long granted)
1481 {
1482         struct tgt_grant_cb     *tgc;
1483         struct dt_txn_commit_cb *dcb;
1484         int                      rc;
1485         ENTRY;
1486
1487         OBD_ALLOC_PTR(tgc);
1488         if (tgc == NULL)
1489                 RETURN(-ENOMEM);
1490
1491         tgc->tgc_exp = class_export_cb_get(exp);
1492         tgc->tgc_granted = granted;
1493
1494         dcb = &tgc->tgc_cb;
1495         dcb->dcb_func = tgt_grant_commit_cb;
1496         INIT_LIST_HEAD(&dcb->dcb_linkage);
1497         strlcpy(dcb->dcb_name, "tgt_grant_commit_cb", sizeof(dcb->dcb_name));
1498
1499         rc = dt_trans_cb_add(th, dcb);
1500         if (rc) {
1501                 class_export_cb_put(tgc->tgc_exp);
1502                 OBD_FREE_PTR(tgc);
1503         }
1504
1505         RETURN(rc);
1506 }
1507 EXPORT_SYMBOL(tgt_grant_commit_cb_add);