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