Whamcloud - gitweb
LU-14543 target: prevent overflowing of tgd->tgd_tot_granted
[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, 2017, 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_CLASS
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, time64_t 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 (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                 osfs->os_namelen = min_t(__u32, osfs->os_namelen, NAME_MAX);
317
318                 spin_lock(&tgd->tgd_grant_lock);
319                 spin_lock(&tgd->tgd_osfs_lock);
320                 /* calculate how much space was written while we released the
321                  * tgd_osfs_lock */
322                 unstable = tgd->tgd_osfs_inflight - unstable;
323                 tgd->tgd_osfs_unstable = 0;
324                 if (unstable) {
325                         /* some writes committed while we were running statfs
326                          * w/o the tgd_osfs_lock. Those ones got added to
327                          * the cached statfs data that we are about to crunch.
328                          * Take them into account in the new statfs data */
329                         osfs->os_bavail -= min_t(u64, osfs->os_bavail,
330                                                unstable >> tgd->tgd_blockbits);
331                         /* However, we don't really know if those writes got
332                          * accounted in the statfs call, so tell
333                          * tgt_grant_space_left() there is some uncertainty
334                          * on the accounting of those writes.
335                          * The purpose is to prevent spurious error messages in
336                          * tgt_grant_space_left() since those writes might be
337                          * accounted twice. */
338                         tgd->tgd_osfs_unstable += unstable;
339                 }
340                 /* similarly, there is some uncertainty on write requests
341                  * between prepare & commit */
342                 tgd->tgd_osfs_unstable += tgd->tgd_tot_pending;
343                 spin_unlock(&tgd->tgd_grant_lock);
344
345                 /* finally udpate cached statfs data */
346                 tgd->tgd_osfs = *osfs;
347                 tgd->tgd_osfs_age = ktime_get_seconds();
348
349                 tgd->tgd_statfs_inflight--; /* stop tracking */
350                 if (tgd->tgd_statfs_inflight == 0)
351                         tgd->tgd_osfs_inflight = 0;
352                 spin_unlock(&tgd->tgd_osfs_lock);
353
354                 if (from_cache)
355                         *from_cache = 0;
356         } else {
357                 /* use cached statfs data */
358                 *osfs = tgd->tgd_osfs;
359                 spin_unlock(&tgd->tgd_osfs_lock);
360                 if (from_cache)
361                         *from_cache = 1;
362         }
363         GOTO(out, rc);
364
365 out:
366         return rc;
367 }
368 EXPORT_SYMBOL(tgt_statfs_internal);
369
370 /**
371  * Update cached statfs information from the OSD layer
372  *
373  * Refresh statfs information cached in tgd::tgd_osfs if the cache is older
374  * than 1s or if force is set. The OSD layer is in charge of estimating data &
375  * metadata overhead.
376  * This function can sleep so it should not be called with any spinlock held.
377  *
378  * \param[in] env               LU environment passed by the caller
379  * \param[in] exp               export used to print client info in debug
380  *                              messages
381  * \param[in] force             force a refresh of statfs information
382  * \param[out] from_cache       returns whether the statfs information are
383  *                              taken from cache
384  */
385 static void tgt_grant_statfs(const struct lu_env *env, struct obd_export *exp,
386                              int force, int *from_cache)
387 {
388         struct obd_device       *obd = exp->exp_obd;
389         struct lu_target        *lut = obd->u.obt.obt_lut;
390         struct tg_grants_data   *tgd = &lut->lut_tgd;
391         struct tgt_thread_info  *tti;
392         struct obd_statfs       *osfs;
393         time64_t max_age;
394         int rc;
395
396         if (force)
397                 max_age = 0; /* get fresh statfs data */
398         else
399                 max_age = ktime_get_seconds() - OBD_STATFS_CACHE_SECONDS;
400
401         tti = tgt_th_info(env);
402         osfs = &tti->tti_u.osfs;
403         rc = tgt_statfs_internal(env, lut, osfs, max_age, from_cache);
404         if (unlikely(rc)) {
405                 if (from_cache)
406                         *from_cache = 0;
407                 return;
408         }
409
410         CDEBUG(D_CACHE, "%s: cli %s/%p free: %llu avail: %llu\n",
411                obd->obd_name, exp->exp_client_uuid.uuid, exp,
412                osfs->os_bfree << tgd->tgd_blockbits,
413                osfs->os_bavail << tgd->tgd_blockbits);
414 }
415
416 /**
417  * Figure out how much space is available on the backend filesystem after
418  * removing grant space already booked by clients.
419  *
420  * This is done by accessing cached statfs data previously populated by
421  * tgt_grant_statfs(), from which we withdraw the space already granted to
422  * clients and the reserved space.
423  * Caller must hold tgd_grant_lock spinlock.
424  *
425  * \param[in] exp       export associated with the device for which the amount
426  *                      of available space is requested
427  * \retval              amount of non-allocated space, in bytes
428  */
429 static u64 tgt_grant_space_left(struct obd_export *exp)
430 {
431         struct obd_device       *obd = exp->exp_obd;
432         struct lu_target        *lut = obd->u.obt.obt_lut;
433         struct tg_grants_data   *tgd = &lut->lut_tgd;
434         u64                      tot_granted;
435         u64                      left;
436         u64                      avail;
437         u64                      unstable;
438         u64                      reserved;
439
440         ENTRY;
441         assert_spin_locked(&tgd->tgd_grant_lock);
442
443         spin_lock(&tgd->tgd_osfs_lock);
444         /* get available space from cached statfs data */
445         left = tgd->tgd_osfs.os_bavail << tgd->tgd_blockbits;
446         unstable = tgd->tgd_osfs_unstable; /* those might be accounted twice */
447         spin_unlock(&tgd->tgd_osfs_lock);
448
449         reserved = left * tgd->tgd_reserved_pcnt / 100;
450         tot_granted = tgd->tgd_tot_granted + reserved;
451
452         if (left < tot_granted) {
453                 int mask = (left + unstable <
454                             tot_granted - tgd->tgd_tot_pending) ?
455                             D_ERROR : D_CACHE;
456
457                 /* the below message is checked in sanityn.sh test_15 */
458                 CDEBUG_LIMIT(mask,
459                              "%s: cli %s/%p left=%llu < tot_grant=%llu unstable=%llu pending=%llu dirty=%llu\n",
460                              obd->obd_name, exp->exp_client_uuid.uuid, exp,
461                              left, tot_granted, unstable,
462                              tgd->tgd_tot_pending,
463                              tgd->tgd_tot_dirty);
464                 RETURN(0);
465         }
466
467         avail = left;
468         /* Withdraw space already granted to clients */
469         left -= tot_granted;
470
471         /* Align left on block size */
472         left &= ~((1ULL << tgd->tgd_blockbits) - 1);
473
474         CDEBUG(D_CACHE,
475                "%s: cli %s/%p avail=%llu left=%llu unstable=%llu tot_grant=%llu pending=%llu\n",
476                obd->obd_name, exp->exp_client_uuid.uuid, exp, avail, left,
477                unstable, tot_granted, tgd->tgd_tot_pending);
478
479         RETURN(left);
480 }
481
482 /**
483  * Process grant information from obdo structure packed in incoming BRW
484  * and inflate grant counters if required.
485  *
486  * Grab the dirty and seen grant announcements from the incoming obdo and
487  * inflate all grant counters passed in the request if the client does not
488  * support the grant parameters.
489  * We will later calculate the client's new grant and return it.
490  * Caller must hold tgd_grant_lock spinlock.
491  *
492  * \param[in] env       LU environment supplying osfs storage
493  * \param[in] exp       export for which we received the request
494  * \param[in,out] oa    incoming obdo sent by the client
495  */
496 static void tgt_grant_incoming(const struct lu_env *env, struct obd_export *exp,
497                                struct obdo *oa, long chunk)
498 {
499         struct tg_export_data   *ted = &exp->exp_target_data;
500         struct obd_device       *obd = exp->exp_obd;
501         struct tg_grants_data   *tgd = &obd->u.obt.obt_lut->lut_tgd;
502         long long                dirty, dropped;
503         ENTRY;
504
505         assert_spin_locked(&tgd->tgd_grant_lock);
506
507         if ((oa->o_valid & (OBD_MD_FLBLOCKS|OBD_MD_FLGRANT)) !=
508                                         (OBD_MD_FLBLOCKS|OBD_MD_FLGRANT)) {
509                 oa->o_valid &= ~OBD_MD_FLGRANT;
510                 RETURN_EXIT;
511         }
512
513         /* Add some margin, since there is a small race if other RPCs arrive
514          * out-or-order and have already consumed some grant.  We want to
515          * leave this here in case there is a large error in accounting. */
516         CDEBUG(D_CACHE,
517                "%s: cli %s/%p reports grant %llu dropped %u, local %lu\n",
518                obd->obd_name, exp->exp_client_uuid.uuid, exp, oa->o_grant,
519                oa->o_dropped, ted->ted_grant);
520
521         if ((long long)oa->o_dirty < 0)
522                 oa->o_dirty = 0;
523
524         /* inflate grant counters if required */
525         if (!exp_grant_param_supp(exp)) {
526                 u64 tmp;
527                 oa->o_grant     = tgt_grant_inflate(tgd, oa->o_grant);
528                 oa->o_dirty     = tgt_grant_inflate(tgd, oa->o_dirty);
529                 /* inflation can bump client's wish to >4GB which doesn't fit
530                  * 32bit o_undirty, limit that ..  */
531                 tmp = tgt_grant_inflate(tgd, oa->o_undirty);
532                 if (tmp >= OBD_MAX_GRANT)
533                         tmp = OBD_MAX_GRANT & ~(1ULL << tgd->tgd_blockbits);
534                 oa->o_undirty = tmp;
535                 tmp = tgt_grant_inflate(tgd, oa->o_dropped);
536                 if (tmp >= OBD_MAX_GRANT)
537                         tmp = OBD_MAX_GRANT & ~(1ULL << tgd->tgd_blockbits);
538                 oa->o_dropped = tmp;
539         }
540
541         dirty = oa->o_dirty;
542         dropped = oa->o_dropped;
543
544         /* Update our accounting now so that statfs takes it into account.
545          * Note that ted_dirty is only approximate and can become incorrect
546          * if RPCs arrive out-of-order.  No important calculations depend
547          * on ted_dirty however, but we must check sanity to not assert. */
548         if (dirty > ted->ted_grant + 4 * chunk)
549                 dirty = ted->ted_grant + 4 * chunk;
550         tgd->tgd_tot_dirty += dirty - ted->ted_dirty;
551         if (ted->ted_grant < dropped) {
552                 CDEBUG(D_CACHE,
553                        "%s: cli %s/%p reports %llu dropped > grant %lu\n",
554                        obd->obd_name, exp->exp_client_uuid.uuid, exp, dropped,
555                        ted->ted_grant);
556                 dropped = 0;
557         }
558         if (tgd->tgd_tot_granted < dropped) {
559                 CERROR("%s: cli %s/%p reports %llu dropped > tot_grant %llu\n",
560                        obd->obd_name, exp->exp_client_uuid.uuid, exp,
561                        dropped, tgd->tgd_tot_granted);
562                 dropped = 0;
563         }
564         tgd->tgd_tot_granted -= dropped;
565         ted->ted_grant -= dropped;
566         ted->ted_dirty = dirty;
567
568         if (ted->ted_dirty < 0 || ted->ted_grant < 0 || ted->ted_pending < 0) {
569                 CERROR("%s: cli %s/%p dirty %ld pend %ld grant %ld\n",
570                        obd->obd_name, exp->exp_client_uuid.uuid, exp,
571                        ted->ted_dirty, ted->ted_pending, ted->ted_grant);
572                 spin_unlock(&tgd->tgd_grant_lock);
573                 LBUG();
574         }
575         EXIT;
576 }
577
578 /**
579  * Grant shrink request handler.
580  *
581  * Client nodes can explicitly release grant space (i.e. process called grant
582  * shrinking). This function proceeds with the shrink request when there is
583  * less ungranted space remaining than the amount all of the connected clients
584  * would consume if they used their full grant.
585  * Caller must hold tgd_grant_lock spinlock.
586  *
587  * \param[in] exp               export releasing grant space
588  * \param[in,out] oa            incoming obdo sent by the client
589  * \param[in] left_space        remaining free space with space already granted
590  *                              taken out
591  */
592 static void tgt_grant_shrink(struct obd_export *exp, struct obdo *oa,
593                              u64 left_space)
594 {
595         struct tg_export_data   *ted = &exp->exp_target_data;
596         struct obd_device       *obd = exp->exp_obd;
597         struct tg_grants_data   *tgd = &obd->u.obt.obt_lut->lut_tgd;
598         long                     grant_shrink;
599
600         assert_spin_locked(&tgd->tgd_grant_lock);
601         LASSERT(exp);
602         if (left_space >= tgd->tgd_tot_granted_clients *
603                           TGT_GRANT_SHRINK_LIMIT(exp))
604                 return;
605
606         grant_shrink = oa->o_grant;
607
608         if (ted->ted_grant < grant_shrink) {
609                 CDEBUG(D_CACHE,
610                        "%s: cli %s/%p wants %lu shrinked > grant %lu\n",
611                        obd->obd_name, exp->exp_client_uuid.uuid, exp,
612                        grant_shrink, ted->ted_grant);
613                 grant_shrink = ted->ted_grant;
614         }
615
616         ted->ted_grant -= grant_shrink;
617         tgd->tgd_tot_granted -= grant_shrink;
618
619         CDEBUG(D_CACHE, "%s: cli %s/%p shrink %ld ted_grant %ld total %llu\n",
620                obd->obd_name, exp->exp_client_uuid.uuid, exp, grant_shrink,
621                ted->ted_grant, tgd->tgd_tot_granted);
622
623         /* client has just released some grant, don't grant any space back */
624         oa->o_grant = 0;
625 }
626
627 /**
628  * Calculate how much space is required to write a given network buffer
629  *
630  * This function takes block alignment into account to estimate how much on-disk
631  * space will be required to successfully write the whole niobuf.
632  * Estimated space is inflated if the export does not support
633  * OBD_CONNECT_GRANT_PARAM and if the backend filesystem has a block size
634  * larger than the minimal supported page size (i.e. 4KB).
635  *
636  * \param[in] exp       export associated which the write request
637  *                      if NULL, then size estimate is done for server-side
638  *                      grant allocation.
639  * \param[in] lut       LU target handling the request
640  * \param[in] rnb       network buffer to estimate size of
641  *
642  * \retval              space (in bytes) that will be consumed to write the
643  *                      network buffer
644  */
645 static inline u64 tgt_grant_rnb_size(struct obd_export *exp,
646                                      struct lu_target *lut,
647                                      struct niobuf_remote *rnb)
648 {
649         struct tg_grants_data *tgd = &lut->lut_tgd;
650         u64 blksize;
651         u64 bytes;
652         u64 end;
653
654         if (exp && !exp_grant_param_supp(exp) &&
655             tgd->tgd_blockbits > COMPAT_BSIZE_SHIFT)
656                 blksize = 1ULL << COMPAT_BSIZE_SHIFT;
657         else
658                 blksize = 1ULL << tgd->tgd_blockbits;
659
660         /* The network buffer might span several blocks, align it on block
661          * boundaries */
662         bytes  = rnb->rnb_offset & (blksize - 1);
663         bytes += rnb->rnb_len;
664         end    = bytes & (blksize - 1);
665         if (end)
666                 bytes += blksize - end;
667
668         if (exp == NULL || exp_grant_param_supp(exp)) {
669                 /* add per-extent insertion cost */
670                 u64 max_ext;
671                 int nr_ext;
672
673                 max_ext = blksize * lut->lut_dt_conf.ddp_max_extent_blks;
674                 nr_ext = (bytes + max_ext - 1) / max_ext;
675                 bytes += nr_ext * lut->lut_dt_conf.ddp_extent_tax;
676         } else {
677                 /* Inflate grant space if client does not support extent-based
678                  * grant allocation */
679                 bytes = tgt_grant_inflate(tgd, (u64)bytes);
680         }
681
682         return bytes;
683 }
684
685 /**
686  * Validate grant accounting for each incoming remote network buffer.
687  *
688  * When clients have dirtied as much space as they've been granted they
689  * fall through to sync writes. These sync writes haven't been expressed
690  * in grants and need to error with ENOSPC when there isn't room in the
691  * filesystem for them after grants are taken into account. However,
692  * writeback of the dirty data that was already granted space can write
693  * right on through.
694  * The OBD_BRW_GRANTED flag will be set in the rnb_flags of each network
695  * buffer which has been granted enough space to proceed. Buffers without
696  * this flag will fail to be written with -ENOSPC (see tgt_preprw_write().
697  * Caller must hold tgd_grant_lock spinlock.
698  *
699  * \param[in] env       LU environment passed by the caller
700  * \param[in] exp       export identifying the client which sent the RPC
701  * \param[in] oa        incoming obdo in which we should return the pack the
702  *                      additional grant
703  * \param[in,out] rnb   the list of network buffers
704  * \param[in] niocount  the number of network buffers in the list
705  * \param[in] left      the remaining free space with space already granted
706  *                      taken out
707  */
708 static void tgt_grant_check(const struct lu_env *env, struct obd_export *exp,
709                             struct obdo *oa, struct niobuf_remote *rnb,
710                             int niocount, u64 *left)
711 {
712         struct tg_export_data   *ted = &exp->exp_target_data;
713         struct obd_device       *obd = exp->exp_obd;
714         struct lu_target        *lut = obd->u.obt.obt_lut;
715         struct tg_grants_data   *tgd = &lut->lut_tgd;
716         unsigned long            ungranted = 0;
717         unsigned long            granted = 0;
718         int                      i;
719         bool                     skip = false;
720
721         ENTRY;
722
723         assert_spin_locked(&tgd->tgd_grant_lock);
724
725         if (obd->obd_recovering) {
726                 /* Replaying write. Grant info have been processed already so no
727                  * need to do any enforcement here. It is worth noting that only
728                  * bulk writes with all rnbs having OBD_BRW_FROM_GRANT can be
729                  * replayed. If one page hasn't OBD_BRW_FROM_GRANT set, then
730                  * the whole bulk is written synchronously */
731                 skip = true;
732                 CDEBUG(D_CACHE, "Replaying write, skipping accounting\n");
733         } else if ((oa->o_valid & OBD_MD_FLFLAGS) &&
734                    (oa->o_flags & OBD_FL_RECOV_RESEND)) {
735                 /* Recoverable resend, grant info have already been processed as
736                  * well */
737                 skip = true;
738                 CDEBUG(D_CACHE, "Recoverable resend arrived, skipping "
739                                 "accounting\n");
740         } else if (exp_grant_param_supp(exp) && oa->o_grant_used > 0) {
741                 /* Client supports the new grant parameters and is telling us
742                  * how much grant space it consumed for this bulk write.
743                  * Although all rnbs are supposed to have the OBD_BRW_FROM_GRANT
744                  * flag set, we will scan the rnb list and looks for non-cache
745                  * I/O in case it changes in the future */
746                 if (ted->ted_grant >= oa->o_grant_used) {
747                         /* skip grant accounting for rnbs with
748                          * OBD_BRW_FROM_GRANT and just used grant consumption
749                          * claimed in the request */
750                         granted = oa->o_grant_used;
751                         skip = true;
752                 } else {
753                         /* client has used more grants for this request that
754                          * it owns ... */
755                         CERROR("%s: cli %s claims %lu GRANT, real grant %lu\n",
756                                exp->exp_obd->obd_name,
757                                exp->exp_client_uuid.uuid,
758                                (unsigned long)oa->o_grant_used, ted->ted_grant);
759
760                         /* check whether we can fill the gap with unallocated
761                          * grant */
762                         if (*left > (oa->o_grant_used - ted->ted_grant)) {
763                                 /* ouf .. we are safe for now */
764                                 granted = ted->ted_grant;
765                                 ungranted = oa->o_grant_used - granted;
766                                 *left -= ungranted;
767                                 skip = true;
768                         }
769                         /* too bad, but we cannot afford to blow up our grant
770                          * accounting. The loop below will handle each rnb in
771                          * case by case. */
772                 }
773         }
774
775         for (i = 0; i < niocount; i++) {
776                 int bytes;
777
778                 if ((rnb[i].rnb_flags & OBD_BRW_FROM_GRANT)) {
779                         if (skip) {
780                                 rnb[i].rnb_flags |= OBD_BRW_GRANTED;
781                                 continue;
782                         }
783
784                         /* compute how much grant space is actually needed for
785                          * this rnb, inflate grant if required */
786                         bytes = tgt_grant_rnb_size(exp, lut, &rnb[i]);
787                         if (ted->ted_grant >= granted + bytes) {
788                                 granted += bytes;
789                                 rnb[i].rnb_flags |= OBD_BRW_GRANTED;
790                                 continue;
791                         }
792
793                         CDEBUG(D_CACHE, "%s: cli %s/%p claims %ld+%d GRANT, "
794                                "real grant %lu idx %d\n", obd->obd_name,
795                                exp->exp_client_uuid.uuid, exp, granted, bytes,
796                                ted->ted_grant, i);
797                 }
798
799                 if (obd->obd_recovering)
800                         CERROR("%s: cli %s is replaying OST_WRITE while one rnb"
801                                " hasn't OBD_BRW_FROM_GRANT set (0x%x)\n",
802                                obd->obd_name, exp->exp_client_uuid.uuid,
803                                rnb[i].rnb_flags);
804
805                 /* Consume grant space on the server.
806                  * Unlike above, tgt_grant_rnb_size() is called with exp = NULL
807                  * so that the required grant space isn't inflated. This is
808                  * done on purpose since the server can deal with large block
809                  * size, unlike some clients */
810                 bytes = tgt_grant_rnb_size(NULL, lut, &rnb[i]);
811                 if (*left > bytes) {
812                         /* if enough space, pretend it was granted */
813                         ungranted += bytes;
814                         *left -= bytes;
815                         rnb[i].rnb_flags |= OBD_BRW_GRANTED;
816                         continue;
817                 }
818
819                 /* We can't check for already-mapped blocks here (make sense
820                  * when backend filesystem does not use COW) as it requires
821                  * dropping the grant lock.
822                  * Instead, we clear OBD_BRW_GRANTED and in that case we need
823                  * to go through and verify if all of the blocks not marked
824                  *  BRW_GRANTED are already mapped and we can ignore this error.
825                  */
826                 rnb[i].rnb_flags &= ~OBD_BRW_GRANTED;
827                 CDEBUG(D_CACHE, "%s: cli %s/%p idx %d no space for %d\n",
828                        obd->obd_name, exp->exp_client_uuid.uuid, exp, i, bytes);
829         }
830
831         /* record in o_grant_used the actual space reserved for the I/O, will be
832          * used later in tgt_grant_commmit() */
833         oa->o_grant_used = granted + ungranted;
834
835         /* record space used for the I/O, will be used in tgt_grant_commmit() */
836         /* Now substract what the clients has used already.  We don't subtract
837          * this from the tot_granted yet, so that other client's can't grab
838          * that space before we have actually allocated our blocks. That
839          * happens in tgt_grant_commit() after the writes are done. */
840         ted->ted_grant -= granted;
841         ted->ted_pending += oa->o_grant_used;
842         tgd->tgd_tot_granted += ungranted;
843         tgd->tgd_tot_pending += oa->o_grant_used;
844
845         CDEBUG(D_CACHE,
846                "%s: cli %s/%p granted: %lu ungranted: %lu grant: %lu dirty: %lu"
847                "\n", obd->obd_name, exp->exp_client_uuid.uuid, exp,
848                granted, ungranted, ted->ted_grant, ted->ted_dirty);
849
850         if (obd->obd_recovering || (oa->o_valid & OBD_MD_FLGRANT) == 0)
851                 /* don't update dirty accounting during recovery or
852                  * if grant information got discarded (e.g. during resend) */
853                 RETURN_EXIT;
854
855         if (ted->ted_dirty < granted) {
856                 CWARN("%s: cli %s/%p claims granted %lu > ted_dirty %lu\n",
857                        obd->obd_name, exp->exp_client_uuid.uuid, exp,
858                        granted, ted->ted_dirty);
859                 granted = ted->ted_dirty;
860         }
861         tgd->tgd_tot_dirty -= granted;
862         ted->ted_dirty -= granted;
863
864         if (ted->ted_dirty < 0 || ted->ted_grant < 0 || ted->ted_pending < 0) {
865                 CERROR("%s: cli %s/%p dirty %ld pend %ld grant %ld\n",
866                        obd->obd_name, exp->exp_client_uuid.uuid, exp,
867                        ted->ted_dirty, ted->ted_pending, ted->ted_grant);
868                 spin_unlock(&tgd->tgd_grant_lock);
869                 LBUG();
870         }
871         EXIT;
872 }
873
874 /**
875  * Allocate additional grant space to a client
876  *
877  * Calculate how much grant space to return to client, based on how much space
878  * is currently free and how much of that is already granted.
879  * Caller must hold tgd_grant_lock spinlock.
880  *
881  * \param[in] exp               export of the client which sent the request
882  * \param[in] curgrant          current grant claimed by the client
883  * \param[in] want              how much grant space the client would like to
884  *                              have
885  * \param[in] left              remaining free space with granted space taken
886  *                              out
887  * \param[in] chunk             grant allocation unit
888  * \param[in] conservative      if set to true, the server should be cautious
889  *                              and limit how much space is granted back to the
890  *                              client. Otherwise, the server should try hard to
891  *                              satisfy the client request.
892  *
893  * \retval                      amount of grant space allocated
894  */
895 static long tgt_grant_alloc(struct obd_export *exp, u64 curgrant,
896                             u64 want, u64 left, long chunk,
897                             bool conservative)
898 {
899         struct obd_device       *obd = exp->exp_obd;
900         struct tg_grants_data   *tgd = &obd->u.obt.obt_lut->lut_tgd;
901         struct tg_export_data   *ted = &exp->exp_target_data;
902         u64                      grant;
903
904         ENTRY;
905
906         if (OBD_FAIL_CHECK(OBD_FAIL_TGT_NO_GRANT))
907                 RETURN(0);
908
909         /* When tgd_grant_compat_disable is set, we don't grant any space to
910          * clients not supporting OBD_CONNECT_GRANT_PARAM.
911          * Otherwise, space granted to such a client is inflated since it
912          * consumes PAGE_SIZE of grant space per block */
913         if ((obd->obd_self_export != exp && !exp_grant_param_supp(exp) &&
914              tgd->tgd_grant_compat_disable) || left == 0 || exp->exp_failed)
915                 RETURN(0);
916
917         if (want > OBD_MAX_GRANT) {
918                 CERROR("%s: client %s/%p requesting > max (%lu), %llu\n",
919                        obd->obd_name, exp->exp_client_uuid.uuid, exp,
920                        OBD_MAX_GRANT, want);
921                 RETURN(0);
922         }
923
924         /* Grant some fraction of the client's requested grant space so that
925          * they are not always waiting for write credits (not all of it to
926          * avoid overgranting in face of multiple RPCs in flight).  This
927          * essentially will be able to control the OSC_MAX_RIF for a client.
928          *
929          * If we do have a large disparity between what the client thinks it
930          * has and what we think it has, don't grant very much and let the
931          * client consume its grant first.  Either it just has lots of RPCs
932          * in flight, or it was evicted and its grants will soon be used up. */
933         if (curgrant >= want || curgrant >= ted->ted_grant + chunk)
934                 RETURN(0);
935
936         if (obd->obd_recovering)
937                 conservative = false;
938
939         if (conservative)
940                 /* don't grant more than 1/8th of the remaining free space in
941                  * one chunk */
942                 left >>= 3;
943         grant = min(want - curgrant, left);
944         /* round grant up to the next block size */
945         grant = (grant + (1 << tgd->tgd_blockbits) - 1) &
946                 ~((1ULL << tgd->tgd_blockbits) - 1);
947
948         if (!grant)
949                 RETURN(0);
950
951         /* Limit to grant_chunk if not reconnect/recovery */
952         if ((grant > chunk) && conservative)
953                 grant = chunk;
954
955         /*
956          * Limit grant so that export' grant does not exceed what the
957          * client would like to have by more than grants for 2 full
958          * RPCs
959          */
960         if (want + chunk <= ted->ted_grant)
961                 RETURN(0);
962         if (ted->ted_grant + grant > want + chunk)
963                 grant = want + chunk - ted->ted_grant;
964
965         tgd->tgd_tot_granted += grant;
966         ted->ted_grant += grant;
967
968         if (unlikely(ted->ted_grant < 0 || ted->ted_grant > want + chunk)) {
969                 CERROR("%s: cli %s/%p grant %ld want %llu current %llu\n",
970                        obd->obd_name, exp->exp_client_uuid.uuid, exp,
971                        ted->ted_grant, want, curgrant);
972                 spin_unlock(&tgd->tgd_grant_lock);
973                 if (tgd->tgd_lbug_on_grant_miscount)
974                         LBUG();
975         }
976
977         CDEBUG(D_CACHE,
978                "%s: cli %s/%p wants: %llu current grant %llu"
979                " granting: %llu\n", obd->obd_name, exp->exp_client_uuid.uuid,
980                exp, want, curgrant, grant);
981         CDEBUG(D_CACHE,
982                "%s: cli %s/%p tot cached:%llu granted:%llu"
983                " num_exports: %d\n", obd->obd_name, exp->exp_client_uuid.uuid,
984                exp, tgd->tgd_tot_dirty, tgd->tgd_tot_granted,
985                obd->obd_num_exports);
986
987         RETURN(grant);
988 }
989
990 /**
991  * Handle grant space allocation on client connection & reconnection.
992  *
993  * A new non-readonly connection gets an initial grant allocation equals to
994  * tgt_grant_chunk() (i.e. twice the max BRW size in most of the cases).
995  * On reconnection, grant counters between client & target are resynchronized
996  * and additional space might be granted back if possible.
997  *
998  * \param[in] env       LU environment provided by the caller
999  * \param[in] exp       client's export which is (re)connecting
1000  * \param[in,out] data  obd_connect_data structure sent by the client in the
1001  *                      connect request
1002  * \param[in] new_conn  must set to true if this is a new connection and false
1003  *                      for a reconnection
1004  */
1005 void tgt_grant_connect(const struct lu_env *env, struct obd_export *exp,
1006                        struct obd_connect_data *data, bool new_conn)
1007 {
1008         struct lu_target        *lut = exp->exp_obd->u.obt.obt_lut;
1009         struct tg_grants_data   *tgd = &lut->lut_tgd;
1010         struct tg_export_data   *ted = &exp->exp_target_data;
1011         u64                      left = 0;
1012         u64                      want;
1013         long                     chunk;
1014         int                      from_cache;
1015         int                      force = 0; /* can use cached data */
1016
1017         /* don't grant space to client with read-only access */
1018         if (OCD_HAS_FLAG(data, RDONLY) ||
1019             (!OCD_HAS_FLAG(data, GRANT_PARAM) &&
1020              tgd->tgd_grant_compat_disable)) {
1021                 data->ocd_grant = 0;
1022                 data->ocd_connect_flags &= ~(OBD_CONNECT_GRANT |
1023                                              OBD_CONNECT_GRANT_PARAM);
1024                 RETURN_EXIT;
1025         }
1026
1027         if (OCD_HAS_FLAG(data, GRANT_PARAM))
1028                 want = data->ocd_grant;
1029         else
1030                 want = tgt_grant_inflate(tgd, data->ocd_grant);
1031         chunk = tgt_grant_chunk(exp, lut, data);
1032 refresh:
1033         tgt_grant_statfs(env, exp, force, &from_cache);
1034
1035         spin_lock(&tgd->tgd_grant_lock);
1036
1037         /* Grab free space from cached info and take out space already granted
1038          * to clients as well as reserved space */
1039         left = tgt_grant_space_left(exp);
1040
1041         /* get fresh statfs data if we are short in ungranted space */
1042         if (from_cache && left < 32 * chunk) {
1043                 spin_unlock(&tgd->tgd_grant_lock);
1044                 CDEBUG(D_CACHE, "fs has no space left and statfs too old\n");
1045                 force = 1;
1046                 goto refresh;
1047         }
1048
1049         tgt_grant_alloc(exp, (u64)ted->ted_grant, want, left, chunk, new_conn);
1050
1051         /* return to client its current grant */
1052         if (OCD_HAS_FLAG(data, GRANT_PARAM))
1053                 data->ocd_grant = ted->ted_grant;
1054         else
1055                 /* deflate grant */
1056                 data->ocd_grant = tgt_grant_deflate(tgd, (u64)ted->ted_grant);
1057
1058         /* reset dirty accounting */
1059         tgd->tgd_tot_dirty -= ted->ted_dirty;
1060         ted->ted_dirty = 0;
1061
1062         if (new_conn && OCD_HAS_FLAG(data, GRANT))
1063                 tgd->tgd_tot_granted_clients++;
1064
1065         spin_unlock(&tgd->tgd_grant_lock);
1066
1067         CDEBUG(D_CACHE, "%s: cli %s/%p ocd_grant: %d want: %llu left: %llu\n",
1068                exp->exp_obd->obd_name, exp->exp_client_uuid.uuid,
1069                exp, data->ocd_grant, want, left);
1070
1071         EXIT;
1072 }
1073 EXPORT_SYMBOL(tgt_grant_connect);
1074
1075 /**
1076  * Release all grant space attached to a given export.
1077  *
1078  * Remove a client from the grant accounting totals.  We also remove
1079  * the export from the obd device under the osfs and dev locks to ensure
1080  * that the tgt_grant_sanity_check() calculations are always valid.
1081  * The client should do something similar when it invalidates its import.
1082  *
1083  * \param[in] exp       client's export to remove from grant accounting
1084  */
1085 void tgt_grant_discard(struct obd_export *exp)
1086 {
1087         struct obd_device       *obd = exp->exp_obd;
1088         struct lu_target        *lut = class_exp2tgt(exp);
1089         struct tg_export_data   *ted = &exp->exp_target_data;
1090         struct tg_grants_data   *tgd;
1091
1092         if (!lut)
1093                 return;
1094
1095         tgd = &lut->lut_tgd;
1096         spin_lock(&tgd->tgd_grant_lock);
1097         if (unlikely(tgd->tgd_tot_granted < ted->ted_grant ||
1098                      tgd->tgd_tot_dirty < ted->ted_dirty)) {
1099                 struct obd_export *e;
1100                 u64 ttg = 0;
1101                 u64 ttd = 0;
1102
1103                 list_for_each_entry(e, &obd->obd_exports, exp_obd_chain) {
1104                         LASSERT(exp != e);
1105                         ttg += e->exp_target_data.ted_grant;
1106                         ttg += e->exp_target_data.ted_pending;
1107                         ttd += e->exp_target_data.ted_dirty;
1108                 }
1109                 if (tgd->tgd_tot_granted < ted->ted_grant)
1110                         CERROR("%s: cli %s/%p: tot_granted %llu < ted_grant %ld, corrected to %llu",
1111                                obd->obd_name,  exp->exp_client_uuid.uuid, exp,
1112                                tgd->tgd_tot_granted, ted->ted_grant, ttg);
1113                 if (tgd->tgd_tot_dirty < ted->ted_dirty)
1114                         CERROR("%s: cli %s/%p: tot_dirty %llu < ted_dirty %ld, corrected to %llu",
1115                                obd->obd_name, exp->exp_client_uuid.uuid, exp,
1116                                tgd->tgd_tot_dirty, ted->ted_dirty, ttd);
1117                 tgd->tgd_tot_granted = ttg;
1118                 tgd->tgd_tot_dirty = ttd;
1119         } else {
1120                 tgd->tgd_tot_granted -= ted->ted_grant;
1121                 tgd->tgd_tot_dirty -= ted->ted_dirty;
1122         }
1123         ted->ted_grant = 0;
1124         ted->ted_dirty = 0;
1125
1126         if (tgd->tgd_tot_pending < ted->ted_pending) {
1127                 CERROR("%s: tot_pending %llu < cli %s/%p ted_pending %ld\n",
1128                        obd->obd_name, tgd->tgd_tot_pending,
1129                        exp->exp_client_uuid.uuid, exp, ted->ted_pending);
1130         }
1131         /* tgd_tot_pending is handled in tgt_grant_commit as bulk
1132          * commmits */
1133         spin_unlock(&tgd->tgd_grant_lock);
1134 }
1135 EXPORT_SYMBOL(tgt_grant_discard);
1136
1137 /**
1138  * Process grant information from incoming bulk read request.
1139  *
1140  * Extract grant information packed in obdo structure (OBD_MD_FLGRANT set in
1141  * o_valid). Bulk reads usually comes with grant announcements (number of dirty
1142  * blocks, remaining amount of grant space, ...) and could also include a grant
1143  * shrink request. Unlike bulk write, no additional grant space is returned on
1144  * bulk read request.
1145  *
1146  * \param[in] env       is the lu environment provided by the caller
1147  * \param[in] exp       is the export of the client which sent the request
1148  * \param[in,out] oa    is the incoming obdo sent by the client
1149  */
1150 void tgt_grant_prepare_read(const struct lu_env *env,
1151                             struct obd_export *exp, struct obdo *oa)
1152 {
1153         struct lu_target        *lut = exp->exp_obd->u.obt.obt_lut;
1154         struct tg_grants_data   *tgd = &lut->lut_tgd;
1155         int                      do_shrink;
1156         u64                      left = 0;
1157
1158         ENTRY;
1159
1160         if (!oa)
1161                 RETURN_EXIT;
1162
1163         if ((oa->o_valid & OBD_MD_FLGRANT) == 0)
1164                 /* The read request does not contain any grant
1165                  * information */
1166                 RETURN_EXIT;
1167
1168         if ((oa->o_valid & OBD_MD_FLFLAGS) &&
1169             (oa->o_flags & OBD_FL_SHRINK_GRANT)) {
1170                 /* To process grant shrink request, we need to know how much
1171                  * available space remains on the backend filesystem.
1172                  * Shrink requests are not so common, we always get fresh
1173                  * statfs information. */
1174                 tgt_grant_statfs(env, exp, 1, NULL);
1175
1176                 /* protect all grant counters */
1177                 spin_lock(&tgd->tgd_grant_lock);
1178
1179                 /* Grab free space from cached statfs data and take out space
1180                  * already granted to clients as well as reserved space */
1181                 left = tgt_grant_space_left(exp);
1182
1183                 /* all set now to proceed with shrinking */
1184                 do_shrink = 1;
1185         } else {
1186                 /* no grant shrinking request packed in the obdo and
1187                  * since we don't grant space back on reads, no point
1188                  * in running statfs, so just skip it and process
1189                  * incoming grant data directly. */
1190                 spin_lock(&tgd->tgd_grant_lock);
1191                 do_shrink = 0;
1192         }
1193
1194         /* extract incoming grant information provided by the client and
1195          * inflate grant counters if required */
1196         tgt_grant_incoming(env, exp, oa, tgt_grant_chunk(exp, lut, NULL));
1197
1198         /* unlike writes, we don't return grants back on reads unless a grant
1199          * shrink request was packed and we decided to turn it down. */
1200         if (do_shrink)
1201                 tgt_grant_shrink(exp, oa, left);
1202         else
1203                 oa->o_grant = 0;
1204
1205         if (!exp_grant_param_supp(exp))
1206                 oa->o_grant = tgt_grant_deflate(tgd, oa->o_grant);
1207         spin_unlock(&tgd->tgd_grant_lock);
1208         EXIT;
1209 }
1210 EXPORT_SYMBOL(tgt_grant_prepare_read);
1211
1212 /**
1213  * Process grant information from incoming bulk write request.
1214  *
1215  * This function extracts client's grant announcements from incoming bulk write
1216  * request and attempts to allocate grant space for network buffers that need it
1217  * (i.e. OBD_BRW_FROM_GRANT not set in rnb_fags).
1218  * Network buffers which aren't granted the OBD_BRW_GRANTED flag should not
1219  * proceed further and should fail with -ENOSPC.
1220  * Whenever possible, additional grant space will be returned to the client
1221  * in the bulk write reply.
1222  * tgt_grant_prepare_write() must be called before writting any buffers to
1223  * the backend storage. This function works in pair with tgt_grant_commit()
1224  * which must be invoked once all buffers have been written to disk in order
1225  * to release space from the pending grant counter.
1226  *
1227  * \param[in] env       LU environment provided by the caller
1228  * \param[in] exp       export of the client which sent the request
1229  * \param[in] oa        incoming obdo sent by the client
1230  * \param[in] rnb       list of network buffers
1231  * \param[in] niocount  number of network buffers in the list
1232  */
1233 void tgt_grant_prepare_write(const struct lu_env *env,
1234                              struct obd_export *exp, struct obdo *oa,
1235                              struct niobuf_remote *rnb, int niocount)
1236 {
1237         struct obd_device       *obd = exp->exp_obd;
1238         struct lu_target        *lut = obd->u.obt.obt_lut;
1239         struct tg_grants_data   *tgd = &lut->lut_tgd;
1240         u64                      left;
1241         int                      from_cache;
1242         int                      force = 0; /* can use cached data intially */
1243         long                     chunk = tgt_grant_chunk(exp, lut, NULL);
1244
1245         ENTRY;
1246
1247 refresh:
1248         /* get statfs information from OSD layer */
1249         tgt_grant_statfs(env, exp, force, &from_cache);
1250
1251         spin_lock(&tgd->tgd_grant_lock); /* protect all grant counters */
1252
1253         /* Grab free space from cached statfs data and take out space already
1254          * granted to clients as well as reserved space */
1255         left = tgt_grant_space_left(exp);
1256
1257         /* Get fresh statfs data if we are short in ungranted space */
1258         if (from_cache && left < 32 * chunk) {
1259                 spin_unlock(&tgd->tgd_grant_lock);
1260                 CDEBUG(D_CACHE, "%s: fs has no space left and statfs too old\n",
1261                        obd->obd_name);
1262                 force = 1;
1263                 goto refresh;
1264         }
1265
1266         /* When close to free space exhaustion, trigger a sync to force
1267          * writeback cache to consume required space immediately and release as
1268          * much space as possible. */
1269         if (!obd->obd_recovering && force != 2 && left < chunk) {
1270                 bool from_grant = true;
1271                 int  i;
1272
1273                 /* That said, it is worth running a sync only if some pages did
1274                  * not consume grant space on the client and could thus fail
1275                  * with ENOSPC later in tgt_grant_check() */
1276                 for (i = 0; i < niocount; i++)
1277                         if (!(rnb[i].rnb_flags & OBD_BRW_FROM_GRANT))
1278                                 from_grant = false;
1279
1280                 if (!from_grant) {
1281                         /* at least one network buffer requires acquiring grant
1282                          * space on the server */
1283                         spin_unlock(&tgd->tgd_grant_lock);
1284                         /* discard errors, at least we tried ... */
1285                         dt_sync(env, lut->lut_bottom);
1286                         force = 2;
1287                         goto refresh;
1288                 }
1289         }
1290
1291         /* extract incoming grant information provided by the client,
1292          * and inflate grant counters if required */
1293         tgt_grant_incoming(env, exp, oa, chunk);
1294
1295         /* check limit */
1296         tgt_grant_check(env, exp, oa, rnb, niocount, &left);
1297
1298         if (!(oa->o_valid & OBD_MD_FLGRANT)) {
1299                 spin_unlock(&tgd->tgd_grant_lock);
1300                 RETURN_EXIT;
1301         }
1302
1303         /* if OBD_FL_SHRINK_GRANT is set, the client is willing to release some
1304          * grant space. */
1305         if ((oa->o_valid & OBD_MD_FLFLAGS) &&
1306             (oa->o_flags & OBD_FL_SHRINK_GRANT))
1307                 tgt_grant_shrink(exp, oa, left);
1308         else
1309                 /* grant more space back to the client if possible */
1310                 oa->o_grant = tgt_grant_alloc(exp, oa->o_grant, oa->o_undirty,
1311                                               left, chunk, true);
1312
1313         if (!exp_grant_param_supp(exp))
1314                 oa->o_grant = tgt_grant_deflate(tgd, oa->o_grant);
1315         spin_unlock(&tgd->tgd_grant_lock);
1316         EXIT;
1317 }
1318 EXPORT_SYMBOL(tgt_grant_prepare_write);
1319
1320 /**
1321  * Consume grant space reserved for object creation.
1322  *
1323  * Grant space is allocated to the local self export for object precreation.
1324  * This is required to prevent object precreation from consuming grant space
1325  * allocated to client nodes for the data writeback cache.
1326  * This function consumes enough space to create \a nr objects and allocates
1327  * more grant space to the self export for future precreation requests, if
1328  * possible.
1329  *
1330  * \param[in] env       LU environment provided by the caller
1331  * \param[in] exp       export holding the grant space for precreation (= self
1332  *                      export currently)
1333  * \param[in] nr        number of objects to be created
1334  *
1335  * \retval >= 0         amount of grant space allocated to the precreate request
1336  * \retval -ENOSPC      on failure
1337  */
1338 long tgt_grant_create(const struct lu_env *env, struct obd_export *exp, s64 *nr)
1339 {
1340         struct lu_target        *lut = exp->exp_obd->u.obt.obt_lut;
1341         struct tg_grants_data   *tgd = &lut->lut_tgd;
1342         struct tg_export_data   *ted = &exp->exp_target_data;
1343         u64                      left = 0;
1344         unsigned long            wanted;
1345         unsigned long            granted;
1346         ENTRY;
1347
1348         if (exp->exp_obd->obd_recovering ||
1349             lut->lut_dt_conf.ddp_inodespace == 0)
1350                 /* don't enforce grant during recovery */
1351                 RETURN(0);
1352
1353         /* Update statfs data if required */
1354         tgt_grant_statfs(env, exp, 1, NULL);
1355
1356         /* protect all grant counters */
1357         spin_lock(&tgd->tgd_grant_lock);
1358
1359         /* fail precreate request if there is not enough blocks available for
1360          * writing */
1361         if (tgd->tgd_osfs.os_bavail - (ted->ted_grant >> tgd->tgd_blockbits) <
1362             (tgd->tgd_osfs.os_blocks >> 10)) {
1363                 spin_unlock(&tgd->tgd_grant_lock);
1364                 CDEBUG(D_RPCTRACE, "%s: not enough space for create %llu\n",
1365                        exp->exp_obd->obd_name,
1366                        tgd->tgd_osfs.os_bavail * tgd->tgd_osfs.os_blocks);
1367                 RETURN(-ENOSPC);
1368         }
1369
1370         /* Grab free space from cached statfs data and take out space
1371          * already granted to clients as well as reserved space */
1372         left = tgt_grant_space_left(exp);
1373
1374         /* compute how much space is required to handle the precreation
1375          * request */
1376         wanted = *nr * lut->lut_dt_conf.ddp_inodespace;
1377         if (wanted > ted->ted_grant + left) {
1378                 /* that's beyond what remains, adjust the number of objects that
1379                  * can be safely precreated */
1380                 wanted = ted->ted_grant + left;
1381                 *nr = wanted / lut->lut_dt_conf.ddp_inodespace;
1382                 if (*nr == 0) {
1383                         /* we really have no space any more for precreation,
1384                          * fail the precreate request with ENOSPC */
1385                         spin_unlock(&tgd->tgd_grant_lock);
1386                         RETURN(-ENOSPC);
1387                 }
1388                 /* compute space needed for the new number of creations */
1389                 wanted = *nr * lut->lut_dt_conf.ddp_inodespace;
1390         }
1391         LASSERT(wanted <= ted->ted_grant + left);
1392
1393         if (wanted <= ted->ted_grant) {
1394                 /* we've enough grant space to handle this precreate request */
1395                 ted->ted_grant -= wanted;
1396         } else {
1397                 /* we need to take some space from the ungranted pool */
1398                 tgd->tgd_tot_granted += wanted - ted->ted_grant;
1399                 left -= wanted - ted->ted_grant;
1400                 ted->ted_grant = 0;
1401         }
1402         granted = wanted;
1403         ted->ted_pending += granted;
1404         tgd->tgd_tot_pending += granted;
1405
1406         /* grant more space for precreate purpose if possible. */
1407         wanted = OST_MAX_PRECREATE * lut->lut_dt_conf.ddp_inodespace / 2;
1408         if (wanted > ted->ted_grant) {
1409                 long chunk;
1410
1411                 /* always try to book enough space to handle a large precreate
1412                  * request */
1413                 chunk = tgt_grant_chunk(exp, lut, NULL);
1414                 wanted -= ted->ted_grant;
1415                 tgt_grant_alloc(exp, ted->ted_grant, wanted, left, chunk,
1416                                 false);
1417         }
1418         spin_unlock(&tgd->tgd_grant_lock);
1419         RETURN(granted);
1420 }
1421 EXPORT_SYMBOL(tgt_grant_create);
1422
1423 /**
1424  * Release grant space added to the pending counter by tgt_grant_prepare_write()
1425  *
1426  * Update pending grant counter once buffers have been written to the disk.
1427  *
1428  * \param[in] exp       export of the client which sent the request
1429  * \param[in] pending   amount of reserved space to be released
1430  * \param[in] rc        return code of pre-commit operations
1431  */
1432 void tgt_grant_commit(struct obd_export *exp, unsigned long pending,
1433                       int rc)
1434 {
1435         struct tg_grants_data *tgd = &exp->exp_obd->u.obt.obt_lut->lut_tgd;
1436
1437         ENTRY;
1438
1439         /* get space accounted in tot_pending for the I/O, set in
1440          * tgt_grant_check() */
1441         if (pending == 0)
1442                 RETURN_EXIT;
1443
1444         spin_lock(&tgd->tgd_grant_lock);
1445         /* Don't update statfs data for errors raised before commit (e.g.
1446          * bulk transfer failed, ...) since we know those writes have not been
1447          * processed. For other errors hit during commit, we cannot really tell
1448          * whether or not something was written, so we update statfs data.
1449          * In any case, this should not be fatal since we always get fresh
1450          * statfs data before failing a request with ENOSPC */
1451         if (rc == 0) {
1452                 spin_lock(&tgd->tgd_osfs_lock);
1453                 /* Take pending out of cached statfs data */
1454                 tgd->tgd_osfs.os_bavail -= min_t(u64,
1455                                                  tgd->tgd_osfs.os_bavail,
1456                                                  pending >> tgd->tgd_blockbits);
1457                 if (tgd->tgd_statfs_inflight)
1458                         /* someone is running statfs and want to be notified of
1459                          * writes happening meanwhile */
1460                         tgd->tgd_osfs_inflight += pending;
1461                 spin_unlock(&tgd->tgd_osfs_lock);
1462         }
1463
1464         if (exp->exp_target_data.ted_pending < pending) {
1465                 CERROR("%s: cli %s/%p ted_pending(%lu) < grant_used(%lu)\n",
1466                        exp->exp_obd->obd_name, exp->exp_client_uuid.uuid, exp,
1467                        exp->exp_target_data.ted_pending, pending);
1468                 spin_unlock(&tgd->tgd_grant_lock);
1469                 LBUG();
1470         }
1471         exp->exp_target_data.ted_pending -= pending;
1472
1473         if (tgd->tgd_tot_granted < pending) {
1474                 CERROR("%s: cli %s/%p tot_granted(%llu) < grant_used(%lu)\n",
1475                        exp->exp_obd->obd_name, exp->exp_client_uuid.uuid, exp,
1476                        tgd->tgd_tot_granted, pending);
1477                 spin_unlock(&tgd->tgd_grant_lock);
1478                 LBUG();
1479         }
1480         tgd->tgd_tot_granted -= pending;
1481
1482         if (tgd->tgd_tot_pending < pending) {
1483                 CERROR("%s: cli %s/%p tot_pending(%llu) < grant_used(%lu)\n",
1484                        exp->exp_obd->obd_name, exp->exp_client_uuid.uuid, exp,
1485                        tgd->tgd_tot_pending, pending);
1486                 spin_unlock(&tgd->tgd_grant_lock);
1487                 LBUG();
1488         }
1489         tgd->tgd_tot_pending -= pending;
1490         spin_unlock(&tgd->tgd_grant_lock);
1491         EXIT;
1492 }
1493 EXPORT_SYMBOL(tgt_grant_commit);
1494
1495 struct tgt_grant_cb {
1496         /* commit callback structure */
1497         struct dt_txn_commit_cb  tgc_cb;
1498         /* export associated with the bulk write */
1499         struct obd_export       *tgc_exp;
1500         /* pending grant to be released */
1501         unsigned long            tgc_granted;
1502 };
1503
1504 /**
1505  * Callback function for grant releasing
1506  *
1507  * Release grant space reserved by the client node.
1508  *
1509  * \param[in] env       execution environment
1510  * \param[in] th        transaction handle
1511  * \param[in] cb        callback data
1512  * \param[in] err       error code
1513  */
1514 static void tgt_grant_commit_cb(struct lu_env *env, struct thandle *th,
1515                                 struct dt_txn_commit_cb *cb, int err)
1516 {
1517         struct tgt_grant_cb *tgc;
1518
1519         tgc = container_of(cb, struct tgt_grant_cb, tgc_cb);
1520
1521         tgt_grant_commit(tgc->tgc_exp, tgc->tgc_granted, err);
1522         class_export_cb_put(tgc->tgc_exp);
1523         OBD_FREE_PTR(tgc);
1524 }
1525
1526 /**
1527  * Add callback for grant releasing
1528  *
1529  * Register a commit callback to release grant space.
1530  *
1531  * \param[in] th        transaction handle
1532  * \param[in] exp       OBD export of client
1533  * \param[in] granted   amount of grant space to be released upon commit
1534  *
1535  * \retval              0 on successful callback adding
1536  * \retval              negative value on error
1537  */
1538 int tgt_grant_commit_cb_add(struct thandle *th, struct obd_export *exp,
1539                             unsigned long granted)
1540 {
1541         struct tgt_grant_cb     *tgc;
1542         struct dt_txn_commit_cb *dcb;
1543         int                      rc;
1544         ENTRY;
1545
1546         OBD_ALLOC_PTR(tgc);
1547         if (tgc == NULL)
1548                 RETURN(-ENOMEM);
1549
1550         tgc->tgc_exp = class_export_cb_get(exp);
1551         tgc->tgc_granted = granted;
1552
1553         dcb = &tgc->tgc_cb;
1554         dcb->dcb_func = tgt_grant_commit_cb;
1555         INIT_LIST_HEAD(&dcb->dcb_linkage);
1556         strlcpy(dcb->dcb_name, "tgt_grant_commit_cb", sizeof(dcb->dcb_name));
1557
1558         rc = dt_trans_cb_add(th, dcb);
1559         if (rc) {
1560                 class_export_cb_put(tgc->tgc_exp);
1561                 OBD_FREE_PTR(tgc);
1562         }
1563
1564         RETURN(rc);
1565 }
1566 EXPORT_SYMBOL(tgt_grant_commit_cb_add);
1567
1568 /**
1569  * Show estimate of total amount of dirty data on clients.
1570  *
1571  * @kobj                kobject embedded in obd_device
1572  * @attr                unused
1573  * @buf                 buf used by sysfs to print out data
1574  *
1575  * Return:              0 on success
1576  *                      negative value on error
1577  */
1578 ssize_t tot_dirty_show(struct kobject *kobj, struct attribute *attr,
1579                        char *buf)
1580 {
1581         struct obd_device *obd = container_of(kobj, struct obd_device,
1582                                               obd_kset.kobj);
1583         struct tg_grants_data *tgd;
1584
1585         tgd = &obd->u.obt.obt_lut->lut_tgd;
1586         return scnprintf(buf, PAGE_SIZE, "%llu\n", tgd->tgd_tot_dirty);
1587 }
1588 EXPORT_SYMBOL(tot_dirty_show);
1589
1590 /**
1591  * Show total amount of space granted to clients.
1592  *
1593  * @kobj                kobject embedded in obd_device
1594  * @attr                unused
1595  * @buf                 buf used by sysfs to print out data
1596  *
1597  * Return:              0 on success
1598  *                      negative value on error
1599  */
1600 ssize_t tot_granted_show(struct kobject *kobj, struct attribute *attr,
1601                          char *buf)
1602 {
1603         struct obd_device *obd = container_of(kobj, struct obd_device,
1604                                               obd_kset.kobj);
1605         struct tg_grants_data *tgd;
1606
1607         tgd = &obd->u.obt.obt_lut->lut_tgd;
1608         return scnprintf(buf, PAGE_SIZE, "%llu\n", tgd->tgd_tot_granted);
1609 }
1610 EXPORT_SYMBOL(tot_granted_show);
1611
1612 /**
1613  * Show total amount of space used by IO in progress.
1614  *
1615  * @kobj                kobject embedded in obd_device
1616  * @attr                unused
1617  * @buf                 buf used by sysfs to print out data
1618  *
1619  * Return:              0 on success
1620  *                      negative value on error
1621  */
1622 ssize_t tot_pending_show(struct kobject *kobj, struct attribute *attr,
1623                          char *buf)
1624 {
1625         struct obd_device *obd = container_of(kobj, struct obd_device,
1626                                               obd_kset.kobj);
1627         struct tg_grants_data *tgd;
1628
1629         tgd = &obd->u.obt.obt_lut->lut_tgd;
1630         return scnprintf(buf, PAGE_SIZE, "%llu\n", tgd->tgd_tot_pending);
1631 }
1632 EXPORT_SYMBOL(tot_pending_show);
1633
1634 /**
1635  * Show if grants compatibility mode is disabled.
1636  *
1637  * When tgd_grant_compat_disable is set, we don't grant any space to clients
1638  * not supporting OBD_CONNECT_GRANT_PARAM. Otherwise, space granted to such
1639  * a client is inflated since it consumes PAGE_SIZE of grant space per
1640  * block, (i.e. typically 4kB units), but underlaying file system might have
1641  * block size bigger than page size, e.g. ZFS. See LU-2049 for details.
1642  *
1643  * @kobj                kobject embedded in obd_device
1644  * @attr                unused
1645  * @buf                 buf used by sysfs to print out data
1646  *
1647  * Return:              string length of @buf output on success
1648  */
1649 ssize_t grant_compat_disable_show(struct kobject *kobj, struct attribute *attr,
1650                                   char *buf)
1651 {
1652         struct obd_device *obd = container_of(kobj, struct obd_device,
1653                                               obd_kset.kobj);
1654         struct tg_grants_data *tgd = &obd->u.obt.obt_lut->lut_tgd;
1655
1656         return scnprintf(buf, PAGE_SIZE, "%u\n", tgd->tgd_grant_compat_disable);
1657 }
1658 EXPORT_SYMBOL(grant_compat_disable_show);
1659
1660 /**
1661  * Change grant compatibility mode.
1662  *
1663  * Setting tgd_grant_compat_disable prohibit any space granting to clients
1664  * not supporting OBD_CONNECT_GRANT_PARAM. See details above.
1665  *
1666  * @kobj        kobject embedded in obd_device
1667  * @attr        unused
1668  * @buffer      string which represents mode
1669  *              1: disable compatibility mode
1670  *              0: enable compatibility mode
1671  * @count       @buffer length
1672  *
1673  * Return:      @count on success
1674  *              negative number on error
1675  */
1676 ssize_t grant_compat_disable_store(struct kobject *kobj,
1677                                    struct attribute *attr,
1678                                    const char *buffer, size_t count)
1679 {
1680         struct obd_device *obd = container_of(kobj, struct obd_device,
1681                                               obd_kset.kobj);
1682         struct tg_grants_data *tgd = &obd->u.obt.obt_lut->lut_tgd;
1683         bool val;
1684         int rc;
1685
1686         rc = kstrtobool(buffer, &val);
1687         if (rc)
1688                 return rc;
1689
1690         tgd->tgd_grant_compat_disable = val;
1691
1692         return count;
1693 }
1694 EXPORT_SYMBOL(grant_compat_disable_store);
1695
1696 /**
1697  * Show lbug_on_grant_miscount mode.
1698  *
1699  * @kobj                kobject embedded in obd_device
1700  * @attr                unused
1701  * @buf                 buf used by sysfs to print out data
1702  *
1703  * Return:              string length of @buf output on success
1704  */
1705 ssize_t lbug_on_grant_miscount_show(struct kobject *kobj,
1706                                     struct attribute *attr, char *buf)
1707 {
1708         struct obd_device *obd = container_of(kobj, struct obd_device,
1709                                               obd_kset.kobj);
1710         struct tg_grants_data *tgd = &obd->u.obt.obt_lut->lut_tgd;
1711
1712         return scnprintf(buf, PAGE_SIZE, "%u\n",
1713                          tgd->tgd_lbug_on_grant_miscount);
1714 }
1715 EXPORT_SYMBOL(lbug_on_grant_miscount_show);
1716
1717 /**
1718  * Change lbug on grant miscount mode.
1719  *
1720  * Setting tgd_lbug_on_grant_miscount to 1 makes tgt_alloc_grant() to
1721  * LBUG on apparently wrong ted->ted_grant
1722  *
1723  * @kobj        kobject embedded in obd_device
1724  * @attr        unused
1725  * @buffer      string which represents mode
1726  *              1: use LBUG on grant miscount
1727  *              0: use CERROR on grant miscount
1728  * @count       @buffer length
1729  *
1730  * Return:      @count on success
1731  *              negative number on error
1732  */
1733 ssize_t lbug_on_grant_miscount_store(struct kobject *kobj,
1734                                      struct attribute *attr,
1735                                      const char *buffer, size_t count)
1736 {
1737         struct obd_device *obd = container_of(kobj, struct obd_device,
1738                                               obd_kset.kobj);
1739         struct tg_grants_data *tgd = &obd->u.obt.obt_lut->lut_tgd;
1740         bool val;
1741         int rc;
1742
1743         rc = kstrtobool(buffer, &val);
1744         if (rc)
1745                 return rc;
1746
1747         tgd->tgd_lbug_on_grant_miscount = val;
1748
1749         return count;
1750 }
1751 EXPORT_SYMBOL(lbug_on_grant_miscount_store);