GNU Linux-libre 4.9-gnu1
[releases.git] / drivers / staging / lustre / lustre / obdclass / lu_object.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) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2015, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  * Lustre is a trademark of Sun Microsystems, Inc.
31  *
32  * lustre/obdclass/lu_object.c
33  *
34  * Lustre Object.
35  * These are the only exported functions, they provide some generic
36  * infrastructure for managing object devices
37  *
38  *   Author: Nikita Danilov <nikita.danilov@sun.com>
39  */
40
41 #define DEBUG_SUBSYSTEM S_CLASS
42
43 #include "../../include/linux/libcfs/libcfs.h"
44
45 # include <linux/module.h>
46
47 /* hash_long() */
48 #include "../../include/linux/libcfs/libcfs_hash.h"
49 #include "../include/obd_class.h"
50 #include "../include/obd_support.h"
51 #include "../include/lustre_disk.h"
52 #include "../include/lustre_fid.h"
53 #include "../include/lu_object.h"
54 #include "../include/cl_object.h"
55 #include "../include/lu_ref.h"
56 #include <linux/list.h>
57
58 enum {
59         LU_CACHE_PERCENT_MAX     = 50,
60         LU_CACHE_PERCENT_DEFAULT = 20
61 };
62
63 #define LU_CACHE_NR_MAX_ADJUST          128
64 #define LU_CACHE_NR_UNLIMITED           -1
65 #define LU_CACHE_NR_DEFAULT             LU_CACHE_NR_UNLIMITED
66 #define LU_CACHE_NR_LDISKFS_LIMIT       LU_CACHE_NR_UNLIMITED
67 #define LU_CACHE_NR_ZFS_LIMIT           256
68
69 #define LU_SITE_BITS_MIN        12
70 #define LU_SITE_BITS_MAX        24
71 /**
72  * total 256 buckets, we don't want too many buckets because:
73  * - consume too much memory
74  * - avoid unbalanced LRU list
75  */
76 #define LU_SITE_BKT_BITS        8
77
78 static unsigned int lu_cache_percent = LU_CACHE_PERCENT_DEFAULT;
79 module_param(lu_cache_percent, int, 0644);
80 MODULE_PARM_DESC(lu_cache_percent, "Percentage of memory to be used as lu_object cache");
81
82 static long lu_cache_nr = LU_CACHE_NR_DEFAULT;
83 module_param(lu_cache_nr, long, 0644);
84 MODULE_PARM_DESC(lu_cache_nr, "Maximum number of objects in lu_object cache");
85
86 static void lu_object_free(const struct lu_env *env, struct lu_object *o);
87 static __u32 ls_stats_read(struct lprocfs_stats *stats, int idx);
88
89 /**
90  * Decrease reference counter on object. If last reference is freed, return
91  * object to the cache, unless lu_object_is_dying(o) holds. In the latter
92  * case, free object immediately.
93  */
94 void lu_object_put(const struct lu_env *env, struct lu_object *o)
95 {
96         struct lu_site_bkt_data *bkt;
97         struct lu_object_header *top;
98         struct lu_site    *site;
99         struct lu_object        *orig;
100         struct cfs_hash_bd          bd;
101         const struct lu_fid     *fid;
102
103         top  = o->lo_header;
104         site = o->lo_dev->ld_site;
105         orig = o;
106
107         /*
108          * till we have full fids-on-OST implemented anonymous objects
109          * are possible in OSP. such an object isn't listed in the site
110          * so we should not remove it from the site.
111          */
112         fid = lu_object_fid(o);
113         if (fid_is_zero(fid)) {
114                 LASSERT(!top->loh_hash.next && !top->loh_hash.pprev);
115                 LASSERT(list_empty(&top->loh_lru));
116                 if (!atomic_dec_and_test(&top->loh_ref))
117                         return;
118                 list_for_each_entry_reverse(o, &top->loh_layers, lo_linkage) {
119                         if (o->lo_ops->loo_object_release)
120                                 o->lo_ops->loo_object_release(env, o);
121                 }
122                 lu_object_free(env, orig);
123                 return;
124         }
125
126         cfs_hash_bd_get(site->ls_obj_hash, &top->loh_fid, &bd);
127         bkt = cfs_hash_bd_extra_get(site->ls_obj_hash, &bd);
128
129         if (!cfs_hash_bd_dec_and_lock(site->ls_obj_hash, &bd, &top->loh_ref)) {
130                 if (lu_object_is_dying(top)) {
131                         /*
132                          * somebody may be waiting for this, currently only
133                          * used for cl_object, see cl_object_put_last().
134                          */
135                         wake_up_all(&bkt->lsb_marche_funebre);
136                 }
137                 return;
138         }
139
140         /*
141          * When last reference is released, iterate over object
142          * layers, and notify them that object is no longer busy.
143          */
144         list_for_each_entry_reverse(o, &top->loh_layers, lo_linkage) {
145                 if (o->lo_ops->loo_object_release)
146                         o->lo_ops->loo_object_release(env, o);
147         }
148
149         if (!lu_object_is_dying(top)) {
150                 LASSERT(list_empty(&top->loh_lru));
151                 list_add_tail(&top->loh_lru, &bkt->lsb_lru);
152                 bkt->lsb_lru_len++;
153                 lprocfs_counter_incr(site->ls_stats, LU_SS_LRU_LEN);
154                 CDEBUG(D_INODE, "Add %p to site lru. hash: %p, bkt: %p, lru_len: %ld\n",
155                        o, site->ls_obj_hash, bkt, bkt->lsb_lru_len);
156                 cfs_hash_bd_unlock(site->ls_obj_hash, &bd, 1);
157                 return;
158         }
159
160         /*
161          * If object is dying (will not be cached), then removed it
162          * from hash table and LRU.
163          *
164          * This is done with hash table and LRU lists locked. As the only
165          * way to acquire first reference to previously unreferenced
166          * object is through hash-table lookup (lu_object_find()),
167          * or LRU scanning (lu_site_purge()), that are done under hash-table
168          * and LRU lock, no race with concurrent object lookup is possible
169          * and we can safely destroy object below.
170          */
171         if (!test_and_set_bit(LU_OBJECT_UNHASHED, &top->loh_flags))
172                 cfs_hash_bd_del_locked(site->ls_obj_hash, &bd, &top->loh_hash);
173         cfs_hash_bd_unlock(site->ls_obj_hash, &bd, 1);
174         /*
175          * Object was already removed from hash and lru above, can
176          * kill it.
177          */
178         lu_object_free(env, orig);
179 }
180 EXPORT_SYMBOL(lu_object_put);
181
182 /**
183  * Kill the object and take it out of LRU cache.
184  * Currently used by client code for layout change.
185  */
186 void lu_object_unhash(const struct lu_env *env, struct lu_object *o)
187 {
188         struct lu_object_header *top;
189
190         top = o->lo_header;
191         set_bit(LU_OBJECT_HEARD_BANSHEE, &top->loh_flags);
192         if (!test_and_set_bit(LU_OBJECT_UNHASHED, &top->loh_flags)) {
193                 struct lu_site *site = o->lo_dev->ld_site;
194                 struct cfs_hash *obj_hash = site->ls_obj_hash;
195                 struct cfs_hash_bd bd;
196
197                 cfs_hash_bd_get_and_lock(obj_hash, &top->loh_fid, &bd, 1);
198                 if (!list_empty(&top->loh_lru)) {
199                         struct lu_site_bkt_data *bkt;
200
201                         list_del_init(&top->loh_lru);
202                         bkt = cfs_hash_bd_extra_get(obj_hash, &bd);
203                         bkt->lsb_lru_len--;
204                         lprocfs_counter_decr(site->ls_stats, LU_SS_LRU_LEN);
205                 }
206                 cfs_hash_bd_del_locked(obj_hash, &bd, &top->loh_hash);
207                 cfs_hash_bd_unlock(obj_hash, &bd, 1);
208         }
209 }
210 EXPORT_SYMBOL(lu_object_unhash);
211
212 /**
213  * Allocate new object.
214  *
215  * This follows object creation protocol, described in the comment within
216  * struct lu_device_operations definition.
217  */
218 static struct lu_object *lu_object_alloc(const struct lu_env *env,
219                                          struct lu_device *dev,
220                                          const struct lu_fid *f,
221                                          const struct lu_object_conf *conf)
222 {
223         struct lu_object *scan;
224         struct lu_object *top;
225         struct list_head *layers;
226         unsigned int init_mask = 0;
227         unsigned int init_flag;
228         int clean;
229         int result;
230
231         /*
232          * Create top-level object slice. This will also create
233          * lu_object_header.
234          */
235         top = dev->ld_ops->ldo_object_alloc(env, NULL, dev);
236         if (!top)
237                 return ERR_PTR(-ENOMEM);
238         if (IS_ERR(top))
239                 return top;
240         /*
241          * This is the only place where object fid is assigned. It's constant
242          * after this point.
243          */
244         top->lo_header->loh_fid = *f;
245         layers = &top->lo_header->loh_layers;
246
247         do {
248                 /*
249                  * Call ->loo_object_init() repeatedly, until no more new
250                  * object slices are created.
251                  */
252                 clean = 1;
253                 init_flag = 1;
254                 list_for_each_entry(scan, layers, lo_linkage) {
255                         if (init_mask & init_flag)
256                                 goto next;
257                         clean = 0;
258                         scan->lo_header = top->lo_header;
259                         result = scan->lo_ops->loo_object_init(env, scan, conf);
260                         if (result != 0) {
261                                 lu_object_free(env, top);
262                                 return ERR_PTR(result);
263                         }
264                         init_mask |= init_flag;
265 next:
266                         init_flag <<= 1;
267                 }
268         } while (!clean);
269
270         list_for_each_entry_reverse(scan, layers, lo_linkage) {
271                 if (scan->lo_ops->loo_object_start) {
272                         result = scan->lo_ops->loo_object_start(env, scan);
273                         if (result != 0) {
274                                 lu_object_free(env, top);
275                                 return ERR_PTR(result);
276                         }
277                 }
278         }
279
280         lprocfs_counter_incr(dev->ld_site->ls_stats, LU_SS_CREATED);
281         return top;
282 }
283
284 /**
285  * Free an object.
286  */
287 static void lu_object_free(const struct lu_env *env, struct lu_object *o)
288 {
289         struct lu_site_bkt_data *bkt;
290         struct lu_site    *site;
291         struct lu_object        *scan;
292         struct list_head              *layers;
293         struct list_head               splice;
294
295         site   = o->lo_dev->ld_site;
296         layers = &o->lo_header->loh_layers;
297         bkt    = lu_site_bkt_from_fid(site, &o->lo_header->loh_fid);
298         /*
299          * First call ->loo_object_delete() method to release all resources.
300          */
301         list_for_each_entry_reverse(scan, layers, lo_linkage) {
302                 if (scan->lo_ops->loo_object_delete)
303                         scan->lo_ops->loo_object_delete(env, scan);
304         }
305
306         /*
307          * Then, splice object layers into stand-alone list, and call
308          * ->loo_object_free() on all layers to free memory. Splice is
309          * necessary, because lu_object_header is freed together with the
310          * top-level slice.
311          */
312         INIT_LIST_HEAD(&splice);
313         list_splice_init(layers, &splice);
314         while (!list_empty(&splice)) {
315                 /*
316                  * Free layers in bottom-to-top order, so that object header
317                  * lives as long as possible and ->loo_object_free() methods
318                  * can look at its contents.
319                  */
320                 o = container_of0(splice.prev, struct lu_object, lo_linkage);
321                 list_del_init(&o->lo_linkage);
322                 o->lo_ops->loo_object_free(env, o);
323         }
324
325         if (waitqueue_active(&bkt->lsb_marche_funebre))
326                 wake_up_all(&bkt->lsb_marche_funebre);
327 }
328
329 /**
330  * Free \a nr objects from the cold end of the site LRU list.
331  */
332 int lu_site_purge(const struct lu_env *env, struct lu_site *s, int nr)
333 {
334         struct lu_object_header *h;
335         struct lu_object_header *temp;
336         struct lu_site_bkt_data *bkt;
337         struct cfs_hash_bd          bd;
338         struct cfs_hash_bd          bd2;
339         struct list_head               dispose;
340         int                   did_sth;
341         unsigned int start;
342         int                   count;
343         int                   bnr;
344         unsigned int i;
345
346         if (OBD_FAIL_CHECK(OBD_FAIL_OBD_NO_LRU))
347                 return 0;
348
349         INIT_LIST_HEAD(&dispose);
350         /*
351          * Under LRU list lock, scan LRU list and move unreferenced objects to
352          * the dispose list, removing them from LRU and hash table.
353          */
354         start = s->ls_purge_start;
355         bnr = (nr == ~0) ? -1 : nr / (int)CFS_HASH_NBKT(s->ls_obj_hash) + 1;
356  again:
357         /*
358          * It doesn't make any sense to make purge threads parallel, that can
359          * only bring troubles to us. See LU-5331.
360          */
361         mutex_lock(&s->ls_purge_mutex);
362         did_sth = 0;
363         cfs_hash_for_each_bucket(s->ls_obj_hash, &bd, i) {
364                 if (i < start)
365                         continue;
366                 count = bnr;
367                 cfs_hash_bd_lock(s->ls_obj_hash, &bd, 1);
368                 bkt = cfs_hash_bd_extra_get(s->ls_obj_hash, &bd);
369
370                 list_for_each_entry_safe(h, temp, &bkt->lsb_lru, loh_lru) {
371                         LASSERT(atomic_read(&h->loh_ref) == 0);
372
373                         cfs_hash_bd_get(s->ls_obj_hash, &h->loh_fid, &bd2);
374                         LASSERT(bd.bd_bucket == bd2.bd_bucket);
375
376                         cfs_hash_bd_del_locked(s->ls_obj_hash,
377                                                &bd2, &h->loh_hash);
378                         list_move(&h->loh_lru, &dispose);
379                         bkt->lsb_lru_len--;
380                         lprocfs_counter_decr(s->ls_stats, LU_SS_LRU_LEN);
381                         if (did_sth == 0)
382                                 did_sth = 1;
383
384                         if (nr != ~0 && --nr == 0)
385                                 break;
386
387                         if (count > 0 && --count == 0)
388                                 break;
389                 }
390                 cfs_hash_bd_unlock(s->ls_obj_hash, &bd, 1);
391                 cond_resched();
392                 /*
393                  * Free everything on the dispose list. This is safe against
394                  * races due to the reasons described in lu_object_put().
395                  */
396                 while (!list_empty(&dispose)) {
397                         h = container_of0(dispose.next,
398                                           struct lu_object_header, loh_lru);
399                         list_del_init(&h->loh_lru);
400                         lu_object_free(env, lu_object_top(h));
401                         lprocfs_counter_incr(s->ls_stats, LU_SS_LRU_PURGED);
402                 }
403
404                 if (nr == 0)
405                         break;
406         }
407         mutex_unlock(&s->ls_purge_mutex);
408
409         if (nr != 0 && did_sth && start != 0) {
410                 start = 0; /* restart from the first bucket */
411                 goto again;
412         }
413         /* race on s->ls_purge_start, but nobody cares */
414         s->ls_purge_start = i % CFS_HASH_NBKT(s->ls_obj_hash);
415
416         return nr;
417 }
418 EXPORT_SYMBOL(lu_site_purge);
419
420 /*
421  * Object printing.
422  *
423  * Code below has to jump through certain loops to output object description
424  * into libcfs_debug_msg-based log. The problem is that lu_object_print()
425  * composes object description from strings that are parts of _lines_ of
426  * output (i.e., strings that are not terminated by newline). This doesn't fit
427  * very well into libcfs_debug_msg() interface that assumes that each message
428  * supplied to it is a self-contained output line.
429  *
430  * To work around this, strings are collected in a temporary buffer
431  * (implemented as a value of lu_cdebug_key key), until terminating newline
432  * character is detected.
433  *
434  */
435
436 enum {
437         /**
438          * Maximal line size.
439          *
440          * XXX overflow is not handled correctly.
441          */
442         LU_CDEBUG_LINE = 512
443 };
444
445 struct lu_cdebug_data {
446         /**
447          * Temporary buffer.
448          */
449         char lck_area[LU_CDEBUG_LINE];
450 };
451
452 /* context key constructor/destructor: lu_global_key_init, lu_global_key_fini */
453 LU_KEY_INIT_FINI(lu_global, struct lu_cdebug_data);
454
455 /**
456  * Key, holding temporary buffer. This key is registered very early by
457  * lu_global_init().
458  */
459 static struct lu_context_key lu_global_key = {
460         .lct_tags = LCT_MD_THREAD | LCT_DT_THREAD |
461                     LCT_MG_THREAD | LCT_CL_THREAD | LCT_LOCAL,
462         .lct_init = lu_global_key_init,
463         .lct_fini = lu_global_key_fini
464 };
465
466 /**
467  * Printer function emitting messages through libcfs_debug_msg().
468  */
469 int lu_cdebug_printer(const struct lu_env *env,
470                       void *cookie, const char *format, ...)
471 {
472         struct libcfs_debug_msg_data *msgdata = cookie;
473         struct lu_cdebug_data   *key;
474         int used;
475         int complete;
476         va_list args;
477
478         va_start(args, format);
479
480         key = lu_context_key_get(&env->le_ctx, &lu_global_key);
481
482         used = strlen(key->lck_area);
483         complete = format[strlen(format) - 1] == '\n';
484         /*
485          * Append new chunk to the buffer.
486          */
487         vsnprintf(key->lck_area + used,
488                   ARRAY_SIZE(key->lck_area) - used, format, args);
489         if (complete) {
490                 if (cfs_cdebug_show(msgdata->msg_mask, msgdata->msg_subsys))
491                         libcfs_debug_msg(msgdata, "%s\n", key->lck_area);
492                 key->lck_area[0] = 0;
493         }
494         va_end(args);
495         return 0;
496 }
497 EXPORT_SYMBOL(lu_cdebug_printer);
498
499 /**
500  * Print object header.
501  */
502 void lu_object_header_print(const struct lu_env *env, void *cookie,
503                             lu_printer_t printer,
504                             const struct lu_object_header *hdr)
505 {
506         (*printer)(env, cookie, "header@%p[%#lx, %d, "DFID"%s%s%s]",
507                    hdr, hdr->loh_flags, atomic_read(&hdr->loh_ref),
508                    PFID(&hdr->loh_fid),
509                    hlist_unhashed(&hdr->loh_hash) ? "" : " hash",
510                    list_empty((struct list_head *)&hdr->loh_lru) ? \
511                    "" : " lru",
512                    hdr->loh_attr & LOHA_EXISTS ? " exist":"");
513 }
514 EXPORT_SYMBOL(lu_object_header_print);
515
516 /**
517  * Print human readable representation of the \a o to the \a printer.
518  */
519 void lu_object_print(const struct lu_env *env, void *cookie,
520                      lu_printer_t printer, const struct lu_object *o)
521 {
522         static const char ruler[] = "........................................";
523         struct lu_object_header *top;
524         int depth = 4;
525
526         top = o->lo_header;
527         lu_object_header_print(env, cookie, printer, top);
528         (*printer)(env, cookie, "{\n");
529
530         list_for_each_entry(o, &top->loh_layers, lo_linkage) {
531                 /*
532                  * print `.' \a depth times followed by type name and address
533                  */
534                 (*printer)(env, cookie, "%*.*s%s@%p", depth, depth, ruler,
535                            o->lo_dev->ld_type->ldt_name, o);
536
537                 if (o->lo_ops->loo_object_print)
538                         (*o->lo_ops->loo_object_print)(env, cookie, printer, o);
539
540                 (*printer)(env, cookie, "\n");
541         }
542
543         (*printer)(env, cookie, "} header@%p\n", top);
544 }
545 EXPORT_SYMBOL(lu_object_print);
546
547 static struct lu_object *htable_lookup(struct lu_site *s,
548                                        struct cfs_hash_bd *bd,
549                                        const struct lu_fid *f,
550                                        wait_queue_t *waiter,
551                                        __u64 *version)
552 {
553         struct lu_site_bkt_data *bkt;
554         struct lu_object_header *h;
555         struct hlist_node       *hnode;
556         __u64  ver = cfs_hash_bd_version_get(bd);
557
558         if (*version == ver)
559                 return ERR_PTR(-ENOENT);
560
561         *version = ver;
562         bkt = cfs_hash_bd_extra_get(s->ls_obj_hash, bd);
563         /* cfs_hash_bd_peek_locked is a somehow "internal" function
564          * of cfs_hash, it doesn't add refcount on object.
565          */
566         hnode = cfs_hash_bd_peek_locked(s->ls_obj_hash, bd, (void *)f);
567         if (!hnode) {
568                 lprocfs_counter_incr(s->ls_stats, LU_SS_CACHE_MISS);
569                 return ERR_PTR(-ENOENT);
570         }
571
572         h = container_of0(hnode, struct lu_object_header, loh_hash);
573         if (likely(!lu_object_is_dying(h))) {
574                 cfs_hash_get(s->ls_obj_hash, hnode);
575                 lprocfs_counter_incr(s->ls_stats, LU_SS_CACHE_HIT);
576                 if (!list_empty(&h->loh_lru)) {
577                         list_del_init(&h->loh_lru);
578                         bkt->lsb_lru_len--;
579                         lprocfs_counter_decr(s->ls_stats, LU_SS_LRU_LEN);
580                 }
581                 return lu_object_top(h);
582         }
583
584         /*
585          * Lookup found an object being destroyed this object cannot be
586          * returned (to assure that references to dying objects are eventually
587          * drained), and moreover, lookup has to wait until object is freed.
588          */
589
590         init_waitqueue_entry(waiter, current);
591         add_wait_queue(&bkt->lsb_marche_funebre, waiter);
592         set_current_state(TASK_UNINTERRUPTIBLE);
593         lprocfs_counter_incr(s->ls_stats, LU_SS_CACHE_DEATH_RACE);
594         return ERR_PTR(-EAGAIN);
595 }
596
597 /**
598  * Search cache for an object with the fid \a f. If such object is found,
599  * return it. Otherwise, create new object, insert it into cache and return
600  * it. In any case, additional reference is acquired on the returned object.
601  */
602 static struct lu_object *lu_object_find(const struct lu_env *env,
603                                         struct lu_device *dev,
604                                         const struct lu_fid *f,
605                                         const struct lu_object_conf *conf)
606 {
607         return lu_object_find_at(env, dev->ld_site->ls_top_dev, f, conf);
608 }
609
610 /*
611  * Limit the lu_object cache to a maximum of lu_cache_nr objects.  Because
612  * the calculation for the number of objects to reclaim is not covered by
613  * a lock the maximum number of objects is capped by LU_CACHE_MAX_ADJUST.
614  * This ensures that many concurrent threads will not accidentally purge
615  * the entire cache.
616  */
617 static void lu_object_limit(const struct lu_env *env, struct lu_device *dev)
618 {
619         __u64 size, nr;
620
621         if (lu_cache_nr == LU_CACHE_NR_UNLIMITED)
622                 return;
623
624         size = cfs_hash_size_get(dev->ld_site->ls_obj_hash);
625         nr = (__u64)lu_cache_nr;
626         if (size > nr)
627                 lu_site_purge(env, dev->ld_site,
628                               min_t(__u64, size - nr, LU_CACHE_NR_MAX_ADJUST));
629 }
630
631 static struct lu_object *lu_object_new(const struct lu_env *env,
632                                        struct lu_device *dev,
633                                        const struct lu_fid *f,
634                                        const struct lu_object_conf *conf)
635 {
636         struct lu_object        *o;
637         struct cfs_hash       *hs;
638         struct cfs_hash_bd          bd;
639
640         o = lu_object_alloc(env, dev, f, conf);
641         if (IS_ERR(o))
642                 return o;
643
644         hs = dev->ld_site->ls_obj_hash;
645         cfs_hash_bd_get_and_lock(hs, (void *)f, &bd, 1);
646         cfs_hash_bd_add_locked(hs, &bd, &o->lo_header->loh_hash);
647         cfs_hash_bd_unlock(hs, &bd, 1);
648
649         lu_object_limit(env, dev);
650
651         return o;
652 }
653
654 /**
655  * Core logic of lu_object_find*() functions.
656  */
657 static struct lu_object *lu_object_find_try(const struct lu_env *env,
658                                             struct lu_device *dev,
659                                             const struct lu_fid *f,
660                                             const struct lu_object_conf *conf,
661                                             wait_queue_t *waiter)
662 {
663         struct lu_object      *o;
664         struct lu_object      *shadow;
665         struct lu_site  *s;
666         struct cfs_hash     *hs;
667         struct cfs_hash_bd        bd;
668         __u64             version = 0;
669
670         /*
671          * This uses standard index maintenance protocol:
672          *
673          *     - search index under lock, and return object if found;
674          *     - otherwise, unlock index, allocate new object;
675          *     - lock index and search again;
676          *     - if nothing is found (usual case), insert newly created
677          *       object into index;
678          *     - otherwise (race: other thread inserted object), free
679          *       object just allocated.
680          *     - unlock index;
681          *     - return object.
682          *
683          * For "LOC_F_NEW" case, we are sure the object is new established.
684          * It is unnecessary to perform lookup-alloc-lookup-insert, instead,
685          * just alloc and insert directly.
686          *
687          * If dying object is found during index search, add @waiter to the
688          * site wait-queue and return ERR_PTR(-EAGAIN).
689          */
690         if (conf && conf->loc_flags & LOC_F_NEW)
691                 return lu_object_new(env, dev, f, conf);
692
693         s  = dev->ld_site;
694         hs = s->ls_obj_hash;
695         cfs_hash_bd_get_and_lock(hs, (void *)f, &bd, 1);
696         o = htable_lookup(s, &bd, f, waiter, &version);
697         cfs_hash_bd_unlock(hs, &bd, 1);
698         if (!IS_ERR(o) || PTR_ERR(o) != -ENOENT)
699                 return o;
700
701         /*
702          * Allocate new object. This may result in rather complicated
703          * operations, including fld queries, inode loading, etc.
704          */
705         o = lu_object_alloc(env, dev, f, conf);
706         if (IS_ERR(o))
707                 return o;
708
709         LASSERT(lu_fid_eq(lu_object_fid(o), f));
710
711         cfs_hash_bd_lock(hs, &bd, 1);
712
713         shadow = htable_lookup(s, &bd, f, waiter, &version);
714         if (likely(PTR_ERR(shadow) == -ENOENT)) {
715                 cfs_hash_bd_add_locked(hs, &bd, &o->lo_header->loh_hash);
716                 cfs_hash_bd_unlock(hs, &bd, 1);
717
718                 lu_object_limit(env, dev);
719
720                 return o;
721         }
722
723         lprocfs_counter_incr(s->ls_stats, LU_SS_CACHE_RACE);
724         cfs_hash_bd_unlock(hs, &bd, 1);
725         lu_object_free(env, o);
726         return shadow;
727 }
728
729 /**
730  * Much like lu_object_find(), but top level device of object is specifically
731  * \a dev rather than top level device of the site. This interface allows
732  * objects of different "stacking" to be created within the same site.
733  */
734 struct lu_object *lu_object_find_at(const struct lu_env *env,
735                                     struct lu_device *dev,
736                                     const struct lu_fid *f,
737                                     const struct lu_object_conf *conf)
738 {
739         struct lu_site_bkt_data *bkt;
740         struct lu_object        *obj;
741         wait_queue_t       wait;
742
743         while (1) {
744                 obj = lu_object_find_try(env, dev, f, conf, &wait);
745                 if (obj != ERR_PTR(-EAGAIN))
746                         return obj;
747                 /*
748                  * lu_object_find_try() already added waiter into the
749                  * wait queue.
750                  */
751                 schedule();
752                 bkt = lu_site_bkt_from_fid(dev->ld_site, (void *)f);
753                 remove_wait_queue(&bkt->lsb_marche_funebre, &wait);
754         }
755 }
756 EXPORT_SYMBOL(lu_object_find_at);
757
758 /**
759  * Find object with given fid, and return its slice belonging to given device.
760  */
761 struct lu_object *lu_object_find_slice(const struct lu_env *env,
762                                        struct lu_device *dev,
763                                        const struct lu_fid *f,
764                                        const struct lu_object_conf *conf)
765 {
766         struct lu_object *top;
767         struct lu_object *obj;
768
769         top = lu_object_find(env, dev, f, conf);
770         if (IS_ERR(top))
771                 return top;
772
773         obj = lu_object_locate(top->lo_header, dev->ld_type);
774         if (unlikely(!obj)) {
775                 lu_object_put(env, top);
776                 obj = ERR_PTR(-ENOENT);
777         }
778
779         return obj;
780 }
781 EXPORT_SYMBOL(lu_object_find_slice);
782
783 /**
784  * Global list of all device types.
785  */
786 static LIST_HEAD(lu_device_types);
787
788 int lu_device_type_init(struct lu_device_type *ldt)
789 {
790         int result = 0;
791
792         atomic_set(&ldt->ldt_device_nr, 0);
793         INIT_LIST_HEAD(&ldt->ldt_linkage);
794         if (ldt->ldt_ops->ldto_init)
795                 result = ldt->ldt_ops->ldto_init(ldt);
796
797         if (!result) {
798                 spin_lock(&obd_types_lock);
799                 list_add(&ldt->ldt_linkage, &lu_device_types);
800                 spin_unlock(&obd_types_lock);
801         }
802
803         return result;
804 }
805 EXPORT_SYMBOL(lu_device_type_init);
806
807 void lu_device_type_fini(struct lu_device_type *ldt)
808 {
809         spin_lock(&obd_types_lock);
810         list_del_init(&ldt->ldt_linkage);
811         spin_unlock(&obd_types_lock);
812         if (ldt->ldt_ops->ldto_fini)
813                 ldt->ldt_ops->ldto_fini(ldt);
814 }
815 EXPORT_SYMBOL(lu_device_type_fini);
816
817 /**
818  * Global list of all sites on this node
819  */
820 static LIST_HEAD(lu_sites);
821 static DEFINE_MUTEX(lu_sites_guard);
822
823 /**
824  * Global environment used by site shrinker.
825  */
826 static struct lu_env lu_shrink_env;
827
828 struct lu_site_print_arg {
829         struct lu_env   *lsp_env;
830         void        *lsp_cookie;
831         lu_printer_t     lsp_printer;
832 };
833
834 static int
835 lu_site_obj_print(struct cfs_hash *hs, struct cfs_hash_bd *bd,
836                   struct hlist_node *hnode, void *data)
837 {
838         struct lu_site_print_arg *arg = (struct lu_site_print_arg *)data;
839         struct lu_object_header  *h;
840
841         h = hlist_entry(hnode, struct lu_object_header, loh_hash);
842         if (!list_empty(&h->loh_layers)) {
843                 const struct lu_object *o;
844
845                 o = lu_object_top(h);
846                 lu_object_print(arg->lsp_env, arg->lsp_cookie,
847                                 arg->lsp_printer, o);
848         } else {
849                 lu_object_header_print(arg->lsp_env, arg->lsp_cookie,
850                                        arg->lsp_printer, h);
851         }
852         return 0;
853 }
854
855 /**
856  * Print all objects in \a s.
857  */
858 void lu_site_print(const struct lu_env *env, struct lu_site *s, void *cookie,
859                    lu_printer_t printer)
860 {
861         struct lu_site_print_arg arg = {
862                 .lsp_env     = (struct lu_env *)env,
863                 .lsp_cookie  = cookie,
864                 .lsp_printer = printer,
865         };
866
867         cfs_hash_for_each(s->ls_obj_hash, lu_site_obj_print, &arg);
868 }
869 EXPORT_SYMBOL(lu_site_print);
870
871 /**
872  * Return desired hash table order.
873  */
874 static unsigned long lu_htable_order(struct lu_device *top)
875 {
876         unsigned long bits_max = LU_SITE_BITS_MAX;
877         unsigned long cache_size;
878         unsigned long bits;
879
880         /*
881          * Calculate hash table size, assuming that we want reasonable
882          * performance when 20% of total memory is occupied by cache of
883          * lu_objects.
884          *
885          * Size of lu_object is (arbitrary) taken as 1K (together with inode).
886          */
887         cache_size = totalram_pages;
888
889 #if BITS_PER_LONG == 32
890         /* limit hashtable size for lowmem systems to low RAM */
891         if (cache_size > 1 << (30 - PAGE_SHIFT))
892                 cache_size = 1 << (30 - PAGE_SHIFT) * 3 / 4;
893 #endif
894
895         /* clear off unreasonable cache setting. */
896         if (lu_cache_percent == 0 || lu_cache_percent > LU_CACHE_PERCENT_MAX) {
897                 CWARN("obdclass: invalid lu_cache_percent: %u, it must be in the range of (0, %u]. Will use default value: %u.\n",
898                       lu_cache_percent, LU_CACHE_PERCENT_MAX,
899                       LU_CACHE_PERCENT_DEFAULT);
900
901                 lu_cache_percent = LU_CACHE_PERCENT_DEFAULT;
902         }
903         cache_size = cache_size / 100 * lu_cache_percent *
904                 (PAGE_SIZE / 1024);
905
906         for (bits = 1; (1 << bits) < cache_size; ++bits) {
907                 ;
908         }
909         return clamp_t(typeof(bits), bits, LU_SITE_BITS_MIN, bits_max);
910 }
911
912 static unsigned lu_obj_hop_hash(struct cfs_hash *hs,
913                                 const void *key, unsigned mask)
914 {
915         struct lu_fid  *fid = (struct lu_fid *)key;
916         __u32      hash;
917
918         hash = fid_flatten32(fid);
919         hash += (hash >> 4) + (hash << 12); /* mixing oid and seq */
920         hash = hash_long(hash, hs->hs_bkt_bits);
921
922         /* give me another random factor */
923         hash -= hash_long((unsigned long)hs, fid_oid(fid) % 11 + 3);
924
925         hash <<= hs->hs_cur_bits - hs->hs_bkt_bits;
926         hash |= (fid_seq(fid) + fid_oid(fid)) & (CFS_HASH_NBKT(hs) - 1);
927
928         return hash & mask;
929 }
930
931 static void *lu_obj_hop_object(struct hlist_node *hnode)
932 {
933         return hlist_entry(hnode, struct lu_object_header, loh_hash);
934 }
935
936 static void *lu_obj_hop_key(struct hlist_node *hnode)
937 {
938         struct lu_object_header *h;
939
940         h = hlist_entry(hnode, struct lu_object_header, loh_hash);
941         return &h->loh_fid;
942 }
943
944 static int lu_obj_hop_keycmp(const void *key, struct hlist_node *hnode)
945 {
946         struct lu_object_header *h;
947
948         h = hlist_entry(hnode, struct lu_object_header, loh_hash);
949         return lu_fid_eq(&h->loh_fid, (struct lu_fid *)key);
950 }
951
952 static void lu_obj_hop_get(struct cfs_hash *hs, struct hlist_node *hnode)
953 {
954         struct lu_object_header *h;
955
956         h = hlist_entry(hnode, struct lu_object_header, loh_hash);
957         atomic_inc(&h->loh_ref);
958 }
959
960 static void lu_obj_hop_put_locked(struct cfs_hash *hs, struct hlist_node *hnode)
961 {
962         LBUG(); /* we should never called it */
963 }
964
965 static struct cfs_hash_ops lu_site_hash_ops = {
966         .hs_hash        = lu_obj_hop_hash,
967         .hs_key         = lu_obj_hop_key,
968         .hs_keycmp      = lu_obj_hop_keycmp,
969         .hs_object      = lu_obj_hop_object,
970         .hs_get         = lu_obj_hop_get,
971         .hs_put_locked  = lu_obj_hop_put_locked,
972 };
973
974 static void lu_dev_add_linkage(struct lu_site *s, struct lu_device *d)
975 {
976         spin_lock(&s->ls_ld_lock);
977         if (list_empty(&d->ld_linkage))
978                 list_add(&d->ld_linkage, &s->ls_ld_linkage);
979         spin_unlock(&s->ls_ld_lock);
980 }
981
982 /**
983  * Initialize site \a s, with \a d as the top level device.
984  */
985 int lu_site_init(struct lu_site *s, struct lu_device *top)
986 {
987         struct lu_site_bkt_data *bkt;
988         struct cfs_hash_bd bd;
989         unsigned long bits;
990         unsigned long i;
991         char name[16];
992
993         memset(s, 0, sizeof(*s));
994         mutex_init(&s->ls_purge_mutex);
995         snprintf(name, sizeof(name), "lu_site_%s", top->ld_type->ldt_name);
996         for (bits = lu_htable_order(top); bits >= LU_SITE_BITS_MIN; bits--) {
997                 s->ls_obj_hash = cfs_hash_create(name, bits, bits,
998                                                  bits - LU_SITE_BKT_BITS,
999                                                  sizeof(*bkt), 0, 0,
1000                                                  &lu_site_hash_ops,
1001                                                  CFS_HASH_SPIN_BKTLOCK |
1002                                                  CFS_HASH_NO_ITEMREF |
1003                                                  CFS_HASH_DEPTH |
1004                                                  CFS_HASH_ASSERT_EMPTY |
1005                                                  CFS_HASH_COUNTER);
1006                 if (s->ls_obj_hash)
1007                         break;
1008         }
1009
1010         if (!s->ls_obj_hash) {
1011                 CERROR("failed to create lu_site hash with bits: %lu\n", bits);
1012                 return -ENOMEM;
1013         }
1014
1015         cfs_hash_for_each_bucket(s->ls_obj_hash, &bd, i) {
1016                 bkt = cfs_hash_bd_extra_get(s->ls_obj_hash, &bd);
1017                 INIT_LIST_HEAD(&bkt->lsb_lru);
1018                 init_waitqueue_head(&bkt->lsb_marche_funebre);
1019         }
1020
1021         s->ls_stats = lprocfs_alloc_stats(LU_SS_LAST_STAT, 0);
1022         if (!s->ls_stats) {
1023                 cfs_hash_putref(s->ls_obj_hash);
1024                 s->ls_obj_hash = NULL;
1025                 return -ENOMEM;
1026         }
1027
1028         lprocfs_counter_init(s->ls_stats, LU_SS_CREATED,
1029                              0, "created", "created");
1030         lprocfs_counter_init(s->ls_stats, LU_SS_CACHE_HIT,
1031                              0, "cache_hit", "cache_hit");
1032         lprocfs_counter_init(s->ls_stats, LU_SS_CACHE_MISS,
1033                              0, "cache_miss", "cache_miss");
1034         lprocfs_counter_init(s->ls_stats, LU_SS_CACHE_RACE,
1035                              0, "cache_race", "cache_race");
1036         lprocfs_counter_init(s->ls_stats, LU_SS_CACHE_DEATH_RACE,
1037                              0, "cache_death_race", "cache_death_race");
1038         lprocfs_counter_init(s->ls_stats, LU_SS_LRU_PURGED,
1039                              0, "lru_purged", "lru_purged");
1040         /*
1041          * Unlike other counters, lru_len can be decremented so
1042          * need lc_sum instead of just lc_count
1043          */
1044         lprocfs_counter_init(s->ls_stats, LU_SS_LRU_LEN,
1045                              LPROCFS_CNTR_AVGMINMAX, "lru_len", "lru_len");
1046
1047         INIT_LIST_HEAD(&s->ls_linkage);
1048         s->ls_top_dev = top;
1049         top->ld_site = s;
1050         lu_device_get(top);
1051         lu_ref_add(&top->ld_reference, "site-top", s);
1052
1053         INIT_LIST_HEAD(&s->ls_ld_linkage);
1054         spin_lock_init(&s->ls_ld_lock);
1055
1056         lu_dev_add_linkage(s, top);
1057
1058         return 0;
1059 }
1060 EXPORT_SYMBOL(lu_site_init);
1061
1062 /**
1063  * Finalize \a s and release its resources.
1064  */
1065 void lu_site_fini(struct lu_site *s)
1066 {
1067         mutex_lock(&lu_sites_guard);
1068         list_del_init(&s->ls_linkage);
1069         mutex_unlock(&lu_sites_guard);
1070
1071         if (s->ls_obj_hash) {
1072                 cfs_hash_putref(s->ls_obj_hash);
1073                 s->ls_obj_hash = NULL;
1074         }
1075
1076         if (s->ls_top_dev) {
1077                 s->ls_top_dev->ld_site = NULL;
1078                 lu_ref_del(&s->ls_top_dev->ld_reference, "site-top", s);
1079                 lu_device_put(s->ls_top_dev);
1080                 s->ls_top_dev = NULL;
1081         }
1082
1083         if (s->ls_stats)
1084                 lprocfs_free_stats(&s->ls_stats);
1085 }
1086 EXPORT_SYMBOL(lu_site_fini);
1087
1088 /**
1089  * Called when initialization of stack for this site is completed.
1090  */
1091 int lu_site_init_finish(struct lu_site *s)
1092 {
1093         int result;
1094
1095         mutex_lock(&lu_sites_guard);
1096         result = lu_context_refill(&lu_shrink_env.le_ctx);
1097         if (result == 0)
1098                 list_add(&s->ls_linkage, &lu_sites);
1099         mutex_unlock(&lu_sites_guard);
1100         return result;
1101 }
1102 EXPORT_SYMBOL(lu_site_init_finish);
1103
1104 /**
1105  * Acquire additional reference on device \a d
1106  */
1107 void lu_device_get(struct lu_device *d)
1108 {
1109         atomic_inc(&d->ld_ref);
1110 }
1111 EXPORT_SYMBOL(lu_device_get);
1112
1113 /**
1114  * Release reference on device \a d.
1115  */
1116 void lu_device_put(struct lu_device *d)
1117 {
1118         LASSERT(atomic_read(&d->ld_ref) > 0);
1119         atomic_dec(&d->ld_ref);
1120 }
1121 EXPORT_SYMBOL(lu_device_put);
1122
1123 /**
1124  * Initialize device \a d of type \a t.
1125  */
1126 int lu_device_init(struct lu_device *d, struct lu_device_type *t)
1127 {
1128         if (atomic_inc_return(&t->ldt_device_nr) == 1 &&
1129             t->ldt_ops->ldto_start)
1130                 t->ldt_ops->ldto_start(t);
1131
1132         memset(d, 0, sizeof(*d));
1133         atomic_set(&d->ld_ref, 0);
1134         d->ld_type = t;
1135         lu_ref_init(&d->ld_reference);
1136         INIT_LIST_HEAD(&d->ld_linkage);
1137         return 0;
1138 }
1139 EXPORT_SYMBOL(lu_device_init);
1140
1141 /**
1142  * Finalize device \a d.
1143  */
1144 void lu_device_fini(struct lu_device *d)
1145 {
1146         struct lu_device_type *t = d->ld_type;
1147
1148         if (d->ld_obd) {
1149                 d->ld_obd->obd_lu_dev = NULL;
1150                 d->ld_obd = NULL;
1151         }
1152
1153         lu_ref_fini(&d->ld_reference);
1154         LASSERTF(atomic_read(&d->ld_ref) == 0,
1155                  "Refcount is %u\n", atomic_read(&d->ld_ref));
1156         LASSERT(atomic_read(&t->ldt_device_nr) > 0);
1157
1158         if (atomic_dec_and_test(&t->ldt_device_nr) &&
1159             t->ldt_ops->ldto_stop)
1160                 t->ldt_ops->ldto_stop(t);
1161 }
1162 EXPORT_SYMBOL(lu_device_fini);
1163
1164 /**
1165  * Initialize object \a o that is part of compound object \a h and was created
1166  * by device \a d.
1167  */
1168 int lu_object_init(struct lu_object *o, struct lu_object_header *h,
1169                    struct lu_device *d)
1170 {
1171         memset(o, 0, sizeof(*o));
1172         o->lo_header = h;
1173         o->lo_dev = d;
1174         lu_device_get(d);
1175         lu_ref_add_at(&d->ld_reference, &o->lo_dev_ref, "lu_object", o);
1176         INIT_LIST_HEAD(&o->lo_linkage);
1177
1178         return 0;
1179 }
1180 EXPORT_SYMBOL(lu_object_init);
1181
1182 /**
1183  * Finalize object and release its resources.
1184  */
1185 void lu_object_fini(struct lu_object *o)
1186 {
1187         struct lu_device *dev = o->lo_dev;
1188
1189         LASSERT(list_empty(&o->lo_linkage));
1190
1191         if (dev) {
1192                 lu_ref_del_at(&dev->ld_reference, &o->lo_dev_ref,
1193                               "lu_object", o);
1194                 lu_device_put(dev);
1195                 o->lo_dev = NULL;
1196         }
1197 }
1198 EXPORT_SYMBOL(lu_object_fini);
1199
1200 /**
1201  * Add object \a o as first layer of compound object \a h
1202  *
1203  * This is typically called by the ->ldo_object_alloc() method of top-level
1204  * device.
1205  */
1206 void lu_object_add_top(struct lu_object_header *h, struct lu_object *o)
1207 {
1208         list_move(&o->lo_linkage, &h->loh_layers);
1209 }
1210 EXPORT_SYMBOL(lu_object_add_top);
1211
1212 /**
1213  * Add object \a o as a layer of compound object, going after \a before.
1214  *
1215  * This is typically called by the ->ldo_object_alloc() method of \a
1216  * before->lo_dev.
1217  */
1218 void lu_object_add(struct lu_object *before, struct lu_object *o)
1219 {
1220         list_move(&o->lo_linkage, &before->lo_linkage);
1221 }
1222 EXPORT_SYMBOL(lu_object_add);
1223
1224 /**
1225  * Initialize compound object.
1226  */
1227 int lu_object_header_init(struct lu_object_header *h)
1228 {
1229         memset(h, 0, sizeof(*h));
1230         atomic_set(&h->loh_ref, 1);
1231         INIT_HLIST_NODE(&h->loh_hash);
1232         INIT_LIST_HEAD(&h->loh_lru);
1233         INIT_LIST_HEAD(&h->loh_layers);
1234         lu_ref_init(&h->loh_reference);
1235         return 0;
1236 }
1237 EXPORT_SYMBOL(lu_object_header_init);
1238
1239 /**
1240  * Finalize compound object.
1241  */
1242 void lu_object_header_fini(struct lu_object_header *h)
1243 {
1244         LASSERT(list_empty(&h->loh_layers));
1245         LASSERT(list_empty(&h->loh_lru));
1246         LASSERT(hlist_unhashed(&h->loh_hash));
1247         lu_ref_fini(&h->loh_reference);
1248 }
1249 EXPORT_SYMBOL(lu_object_header_fini);
1250
1251 /**
1252  * Given a compound object, find its slice, corresponding to the device type
1253  * \a dtype.
1254  */
1255 struct lu_object *lu_object_locate(struct lu_object_header *h,
1256                                    const struct lu_device_type *dtype)
1257 {
1258         struct lu_object *o;
1259
1260         list_for_each_entry(o, &h->loh_layers, lo_linkage) {
1261                 if (o->lo_dev->ld_type == dtype)
1262                         return o;
1263         }
1264         return NULL;
1265 }
1266 EXPORT_SYMBOL(lu_object_locate);
1267
1268 /**
1269  * Finalize and free devices in the device stack.
1270  *
1271  * Finalize device stack by purging object cache, and calling
1272  * lu_device_type_operations::ldto_device_fini() and
1273  * lu_device_type_operations::ldto_device_free() on all devices in the stack.
1274  */
1275 void lu_stack_fini(const struct lu_env *env, struct lu_device *top)
1276 {
1277         struct lu_site   *site = top->ld_site;
1278         struct lu_device *scan;
1279         struct lu_device *next;
1280
1281         lu_site_purge(env, site, ~0);
1282         for (scan = top; scan; scan = next) {
1283                 next = scan->ld_type->ldt_ops->ldto_device_fini(env, scan);
1284                 lu_ref_del(&scan->ld_reference, "lu-stack", &lu_site_init);
1285                 lu_device_put(scan);
1286         }
1287
1288         /* purge again. */
1289         lu_site_purge(env, site, ~0);
1290
1291         for (scan = top; scan; scan = next) {
1292                 const struct lu_device_type *ldt = scan->ld_type;
1293                 struct obd_type      *type;
1294
1295                 next = ldt->ldt_ops->ldto_device_free(env, scan);
1296                 type = ldt->ldt_obd_type;
1297                 if (type) {
1298                         type->typ_refcnt--;
1299                         class_put_type(type);
1300                 }
1301         }
1302 }
1303
1304 enum {
1305         /**
1306          * Maximal number of tld slots.
1307          */
1308         LU_CONTEXT_KEY_NR = 40
1309 };
1310
1311 static struct lu_context_key *lu_keys[LU_CONTEXT_KEY_NR] = { NULL, };
1312
1313 static DEFINE_SPINLOCK(lu_keys_guard);
1314
1315 /**
1316  * Global counter incremented whenever key is registered, unregistered,
1317  * revived or quiesced. This is used to void unnecessary calls to
1318  * lu_context_refill(). No locking is provided, as initialization and shutdown
1319  * are supposed to be externally serialized.
1320  */
1321 static unsigned key_set_version;
1322
1323 /**
1324  * Register new key.
1325  */
1326 int lu_context_key_register(struct lu_context_key *key)
1327 {
1328         int result;
1329         unsigned int i;
1330
1331         LASSERT(key->lct_init);
1332         LASSERT(key->lct_fini);
1333         LASSERT(key->lct_tags != 0);
1334
1335         result = -ENFILE;
1336         spin_lock(&lu_keys_guard);
1337         for (i = 0; i < ARRAY_SIZE(lu_keys); ++i) {
1338                 if (!lu_keys[i]) {
1339                         key->lct_index = i;
1340                         atomic_set(&key->lct_used, 1);
1341                         lu_keys[i] = key;
1342                         lu_ref_init(&key->lct_reference);
1343                         result = 0;
1344                         ++key_set_version;
1345                         break;
1346                 }
1347         }
1348         spin_unlock(&lu_keys_guard);
1349         return result;
1350 }
1351 EXPORT_SYMBOL(lu_context_key_register);
1352
1353 static void key_fini(struct lu_context *ctx, int index)
1354 {
1355         if (ctx->lc_value && ctx->lc_value[index]) {
1356                 struct lu_context_key *key;
1357
1358                 key = lu_keys[index];
1359                 LASSERT(atomic_read(&key->lct_used) > 1);
1360
1361                 key->lct_fini(ctx, key, ctx->lc_value[index]);
1362                 lu_ref_del(&key->lct_reference, "ctx", ctx);
1363                 atomic_dec(&key->lct_used);
1364
1365                 if ((ctx->lc_tags & LCT_NOREF) == 0) {
1366 #ifdef CONFIG_MODULE_UNLOAD
1367                         LINVRNT(module_refcount(key->lct_owner) > 0);
1368 #endif
1369                         module_put(key->lct_owner);
1370                 }
1371                 ctx->lc_value[index] = NULL;
1372         }
1373 }
1374
1375 /**
1376  * Deregister key.
1377  */
1378 void lu_context_key_degister(struct lu_context_key *key)
1379 {
1380         LASSERT(atomic_read(&key->lct_used) >= 1);
1381         LINVRNT(0 <= key->lct_index && key->lct_index < ARRAY_SIZE(lu_keys));
1382
1383         lu_context_key_quiesce(key);
1384
1385         ++key_set_version;
1386         spin_lock(&lu_keys_guard);
1387         key_fini(&lu_shrink_env.le_ctx, key->lct_index);
1388         if (lu_keys[key->lct_index]) {
1389                 lu_keys[key->lct_index] = NULL;
1390                 lu_ref_fini(&key->lct_reference);
1391         }
1392         spin_unlock(&lu_keys_guard);
1393
1394         LASSERTF(atomic_read(&key->lct_used) == 1,
1395                  "key has instances: %d\n",
1396                  atomic_read(&key->lct_used));
1397 }
1398 EXPORT_SYMBOL(lu_context_key_degister);
1399
1400 /**
1401  * Register a number of keys. This has to be called after all keys have been
1402  * initialized by a call to LU_CONTEXT_KEY_INIT().
1403  */
1404 int lu_context_key_register_many(struct lu_context_key *k, ...)
1405 {
1406         struct lu_context_key *key = k;
1407         va_list args;
1408         int result;
1409
1410         va_start(args, k);
1411         do {
1412                 result = lu_context_key_register(key);
1413                 if (result)
1414                         break;
1415                 key = va_arg(args, struct lu_context_key *);
1416         } while (key);
1417         va_end(args);
1418
1419         if (result != 0) {
1420                 va_start(args, k);
1421                 while (k != key) {
1422                         lu_context_key_degister(k);
1423                         k = va_arg(args, struct lu_context_key *);
1424                 }
1425                 va_end(args);
1426         }
1427
1428         return result;
1429 }
1430 EXPORT_SYMBOL(lu_context_key_register_many);
1431
1432 /**
1433  * De-register a number of keys. This is a dual to
1434  * lu_context_key_register_many().
1435  */
1436 void lu_context_key_degister_many(struct lu_context_key *k, ...)
1437 {
1438         va_list args;
1439
1440         va_start(args, k);
1441         do {
1442                 lu_context_key_degister(k);
1443                 k = va_arg(args, struct lu_context_key*);
1444         } while (k);
1445         va_end(args);
1446 }
1447 EXPORT_SYMBOL(lu_context_key_degister_many);
1448
1449 /**
1450  * Revive a number of keys.
1451  */
1452 void lu_context_key_revive_many(struct lu_context_key *k, ...)
1453 {
1454         va_list args;
1455
1456         va_start(args, k);
1457         do {
1458                 lu_context_key_revive(k);
1459                 k = va_arg(args, struct lu_context_key*);
1460         } while (k);
1461         va_end(args);
1462 }
1463 EXPORT_SYMBOL(lu_context_key_revive_many);
1464
1465 /**
1466  * Quiescent a number of keys.
1467  */
1468 void lu_context_key_quiesce_many(struct lu_context_key *k, ...)
1469 {
1470         va_list args;
1471
1472         va_start(args, k);
1473         do {
1474                 lu_context_key_quiesce(k);
1475                 k = va_arg(args, struct lu_context_key*);
1476         } while (k);
1477         va_end(args);
1478 }
1479 EXPORT_SYMBOL(lu_context_key_quiesce_many);
1480
1481 /**
1482  * Return value associated with key \a key in context \a ctx.
1483  */
1484 void *lu_context_key_get(const struct lu_context *ctx,
1485                          const struct lu_context_key *key)
1486 {
1487         LINVRNT(ctx->lc_state == LCS_ENTERED);
1488         LINVRNT(0 <= key->lct_index && key->lct_index < ARRAY_SIZE(lu_keys));
1489         LASSERT(lu_keys[key->lct_index] == key);
1490         return ctx->lc_value[key->lct_index];
1491 }
1492 EXPORT_SYMBOL(lu_context_key_get);
1493
1494 /**
1495  * List of remembered contexts. XXX document me.
1496  */
1497 static LIST_HEAD(lu_context_remembered);
1498
1499 /**
1500  * Destroy \a key in all remembered contexts. This is used to destroy key
1501  * values in "shared" contexts (like service threads), when a module owning
1502  * the key is about to be unloaded.
1503  */
1504 void lu_context_key_quiesce(struct lu_context_key *key)
1505 {
1506         struct lu_context *ctx;
1507
1508         if (!(key->lct_tags & LCT_QUIESCENT)) {
1509                 /*
1510                  * XXX layering violation.
1511                  */
1512                 cl_env_cache_purge(~0);
1513                 key->lct_tags |= LCT_QUIESCENT;
1514                 /*
1515                  * XXX memory barrier has to go here.
1516                  */
1517                 spin_lock(&lu_keys_guard);
1518                 list_for_each_entry(ctx, &lu_context_remembered, lc_remember)
1519                         key_fini(ctx, key->lct_index);
1520                 spin_unlock(&lu_keys_guard);
1521                 ++key_set_version;
1522         }
1523 }
1524
1525 void lu_context_key_revive(struct lu_context_key *key)
1526 {
1527         key->lct_tags &= ~LCT_QUIESCENT;
1528         ++key_set_version;
1529 }
1530
1531 static void keys_fini(struct lu_context *ctx)
1532 {
1533         unsigned int i;
1534
1535         if (!ctx->lc_value)
1536                 return;
1537
1538         for (i = 0; i < ARRAY_SIZE(lu_keys); ++i)
1539                 key_fini(ctx, i);
1540
1541         kfree(ctx->lc_value);
1542         ctx->lc_value = NULL;
1543 }
1544
1545 static int keys_fill(struct lu_context *ctx)
1546 {
1547         unsigned int i;
1548
1549         LINVRNT(ctx->lc_value);
1550         for (i = 0; i < ARRAY_SIZE(lu_keys); ++i) {
1551                 struct lu_context_key *key;
1552
1553                 key = lu_keys[i];
1554                 if (!ctx->lc_value[i] && key &&
1555                     (key->lct_tags & ctx->lc_tags) &&
1556                     /*
1557                      * Don't create values for a LCT_QUIESCENT key, as this
1558                      * will pin module owning a key.
1559                      */
1560                     !(key->lct_tags & LCT_QUIESCENT)) {
1561                         void *value;
1562
1563                         LINVRNT(key->lct_init);
1564                         LINVRNT(key->lct_index == i);
1565
1566                         value = key->lct_init(ctx, key);
1567                         if (IS_ERR(value))
1568                                 return PTR_ERR(value);
1569
1570                         if (!(ctx->lc_tags & LCT_NOREF))
1571                                 try_module_get(key->lct_owner);
1572                         lu_ref_add_atomic(&key->lct_reference, "ctx", ctx);
1573                         atomic_inc(&key->lct_used);
1574                         /*
1575                          * This is the only place in the code, where an
1576                          * element of ctx->lc_value[] array is set to non-NULL
1577                          * value.
1578                          */
1579                         ctx->lc_value[i] = value;
1580                         if (key->lct_exit)
1581                                 ctx->lc_tags |= LCT_HAS_EXIT;
1582                 }
1583                 ctx->lc_version = key_set_version;
1584         }
1585         return 0;
1586 }
1587
1588 static int keys_init(struct lu_context *ctx)
1589 {
1590         ctx->lc_value = kcalloc(ARRAY_SIZE(lu_keys), sizeof(ctx->lc_value[0]),
1591                                 GFP_NOFS);
1592         if (likely(ctx->lc_value))
1593                 return keys_fill(ctx);
1594
1595         return -ENOMEM;
1596 }
1597
1598 /**
1599  * Initialize context data-structure. Create values for all keys.
1600  */
1601 int lu_context_init(struct lu_context *ctx, __u32 tags)
1602 {
1603         int     rc;
1604
1605         memset(ctx, 0, sizeof(*ctx));
1606         ctx->lc_state = LCS_INITIALIZED;
1607         ctx->lc_tags = tags;
1608         if (tags & LCT_REMEMBER) {
1609                 spin_lock(&lu_keys_guard);
1610                 list_add(&ctx->lc_remember, &lu_context_remembered);
1611                 spin_unlock(&lu_keys_guard);
1612         } else {
1613                 INIT_LIST_HEAD(&ctx->lc_remember);
1614         }
1615
1616         rc = keys_init(ctx);
1617         if (rc != 0)
1618                 lu_context_fini(ctx);
1619
1620         return rc;
1621 }
1622 EXPORT_SYMBOL(lu_context_init);
1623
1624 /**
1625  * Finalize context data-structure. Destroy key values.
1626  */
1627 void lu_context_fini(struct lu_context *ctx)
1628 {
1629         LINVRNT(ctx->lc_state == LCS_INITIALIZED || ctx->lc_state == LCS_LEFT);
1630         ctx->lc_state = LCS_FINALIZED;
1631
1632         if ((ctx->lc_tags & LCT_REMEMBER) == 0) {
1633                 LASSERT(list_empty(&ctx->lc_remember));
1634                 keys_fini(ctx);
1635
1636         } else { /* could race with key degister */
1637                 spin_lock(&lu_keys_guard);
1638                 keys_fini(ctx);
1639                 list_del_init(&ctx->lc_remember);
1640                 spin_unlock(&lu_keys_guard);
1641         }
1642 }
1643 EXPORT_SYMBOL(lu_context_fini);
1644
1645 /**
1646  * Called before entering context.
1647  */
1648 void lu_context_enter(struct lu_context *ctx)
1649 {
1650         LINVRNT(ctx->lc_state == LCS_INITIALIZED || ctx->lc_state == LCS_LEFT);
1651         ctx->lc_state = LCS_ENTERED;
1652 }
1653 EXPORT_SYMBOL(lu_context_enter);
1654
1655 /**
1656  * Called after exiting from \a ctx
1657  */
1658 void lu_context_exit(struct lu_context *ctx)
1659 {
1660         unsigned int i;
1661
1662         LINVRNT(ctx->lc_state == LCS_ENTERED);
1663         ctx->lc_state = LCS_LEFT;
1664         if (ctx->lc_tags & LCT_HAS_EXIT && ctx->lc_value) {
1665                 for (i = 0; i < ARRAY_SIZE(lu_keys); ++i) {
1666                         if (ctx->lc_value[i]) {
1667                                 struct lu_context_key *key;
1668
1669                                 key = lu_keys[i];
1670                                 if (key->lct_exit)
1671                                         key->lct_exit(ctx,
1672                                                       key, ctx->lc_value[i]);
1673                         }
1674                 }
1675         }
1676 }
1677 EXPORT_SYMBOL(lu_context_exit);
1678
1679 /**
1680  * Allocate for context all missing keys that were registered after context
1681  * creation. key_set_version is only changed in rare cases when modules
1682  * are loaded and removed.
1683  */
1684 int lu_context_refill(struct lu_context *ctx)
1685 {
1686         return likely(ctx->lc_version == key_set_version) ? 0 : keys_fill(ctx);
1687 }
1688
1689 /**
1690  * lu_ctx_tags/lu_ses_tags will be updated if there are new types of
1691  * obd being added. Currently, this is only used on client side, specifically
1692  * for echo device client, for other stack (like ptlrpc threads), context are
1693  * predefined when the lu_device type are registered, during the module probe
1694  * phase.
1695  */
1696 __u32 lu_context_tags_default;
1697 __u32 lu_session_tags_default;
1698
1699 int lu_env_init(struct lu_env *env, __u32 tags)
1700 {
1701         int result;
1702
1703         env->le_ses = NULL;
1704         result = lu_context_init(&env->le_ctx, tags);
1705         if (likely(result == 0))
1706                 lu_context_enter(&env->le_ctx);
1707         return result;
1708 }
1709 EXPORT_SYMBOL(lu_env_init);
1710
1711 void lu_env_fini(struct lu_env *env)
1712 {
1713         lu_context_exit(&env->le_ctx);
1714         lu_context_fini(&env->le_ctx);
1715         env->le_ses = NULL;
1716 }
1717 EXPORT_SYMBOL(lu_env_fini);
1718
1719 int lu_env_refill(struct lu_env *env)
1720 {
1721         int result;
1722
1723         result = lu_context_refill(&env->le_ctx);
1724         if (result == 0 && env->le_ses)
1725                 result = lu_context_refill(env->le_ses);
1726         return result;
1727 }
1728 EXPORT_SYMBOL(lu_env_refill);
1729
1730 struct lu_site_stats {
1731         unsigned        lss_populated;
1732         unsigned        lss_max_search;
1733         unsigned        lss_total;
1734         unsigned        lss_busy;
1735 };
1736
1737 static void lu_site_stats_get(struct cfs_hash *hs,
1738                               struct lu_site_stats *stats, int populated)
1739 {
1740         struct cfs_hash_bd bd;
1741         unsigned int i;
1742
1743         cfs_hash_for_each_bucket(hs, &bd, i) {
1744                 struct lu_site_bkt_data *bkt = cfs_hash_bd_extra_get(hs, &bd);
1745                 struct hlist_head       *hhead;
1746
1747                 cfs_hash_bd_lock(hs, &bd, 1);
1748                 stats->lss_busy  +=
1749                         cfs_hash_bd_count_get(&bd) - bkt->lsb_lru_len;
1750                 stats->lss_total += cfs_hash_bd_count_get(&bd);
1751                 stats->lss_max_search = max((int)stats->lss_max_search,
1752                                             cfs_hash_bd_depmax_get(&bd));
1753                 if (!populated) {
1754                         cfs_hash_bd_unlock(hs, &bd, 1);
1755                         continue;
1756                 }
1757
1758                 cfs_hash_bd_for_each_hlist(hs, &bd, hhead) {
1759                         if (!hlist_empty(hhead))
1760                                 stats->lss_populated++;
1761                 }
1762                 cfs_hash_bd_unlock(hs, &bd, 1);
1763         }
1764 }
1765
1766 /*
1767  * lu_cache_shrink_count returns the number of cached objects that are
1768  * candidates to be freed by shrink_slab(). A counter, which tracks
1769  * the number of items in the site's lru, is maintained in the per cpu
1770  * stats of each site. The counter is incremented when an object is added
1771  * to a site's lru and decremented when one is removed. The number of
1772  * free-able objects is the sum of all per cpu counters for all sites.
1773  *
1774  * Using a per cpu counter is a compromise solution to concurrent access:
1775  * lu_object_put() can update the counter without locking the site and
1776  * lu_cache_shrink_count can sum the counters without locking each
1777  * ls_obj_hash bucket.
1778  */
1779 static unsigned long lu_cache_shrink_count(struct shrinker *sk,
1780                                            struct shrink_control *sc)
1781 {
1782         struct lu_site *s;
1783         struct lu_site *tmp;
1784         unsigned long cached = 0;
1785
1786         if (!(sc->gfp_mask & __GFP_FS))
1787                 return 0;
1788
1789         mutex_lock(&lu_sites_guard);
1790         list_for_each_entry_safe(s, tmp, &lu_sites, ls_linkage) {
1791                 cached += ls_stats_read(s->ls_stats, LU_SS_LRU_LEN);
1792         }
1793         mutex_unlock(&lu_sites_guard);
1794
1795         cached = (cached / 100) * sysctl_vfs_cache_pressure;
1796         CDEBUG(D_INODE, "%ld objects cached, cache pressure %d\n",
1797                cached, sysctl_vfs_cache_pressure);
1798
1799         return cached;
1800 }
1801
1802 static unsigned long lu_cache_shrink_scan(struct shrinker *sk,
1803                                           struct shrink_control *sc)
1804 {
1805         struct lu_site *s;
1806         struct lu_site *tmp;
1807         unsigned long remain = sc->nr_to_scan, freed = 0;
1808         LIST_HEAD(splice);
1809
1810         if (!(sc->gfp_mask & __GFP_FS))
1811                 /* We must not take the lu_sites_guard lock when
1812                  * __GFP_FS is *not* set because of the deadlock
1813                  * possibility detailed above. Additionally,
1814                  * since we cannot determine the number of
1815                  * objects in the cache without taking this
1816                  * lock, we're in a particularly tough spot. As
1817                  * a result, we'll just lie and say our cache is
1818                  * empty. This _should_ be ok, as we can't
1819                  * reclaim objects when __GFP_FS is *not* set
1820                  * anyways.
1821                  */
1822                 return SHRINK_STOP;
1823
1824         mutex_lock(&lu_sites_guard);
1825         list_for_each_entry_safe(s, tmp, &lu_sites, ls_linkage) {
1826                 freed = lu_site_purge(&lu_shrink_env, s, remain);
1827                 remain -= freed;
1828                 /*
1829                  * Move just shrunk site to the tail of site list to
1830                  * assure shrinking fairness.
1831                  */
1832                 list_move_tail(&s->ls_linkage, &splice);
1833         }
1834         list_splice(&splice, lu_sites.prev);
1835         mutex_unlock(&lu_sites_guard);
1836
1837         return sc->nr_to_scan - remain;
1838 }
1839
1840 /**
1841  * Debugging printer function using printk().
1842  */
1843 static struct shrinker lu_site_shrinker = {
1844         .count_objects  = lu_cache_shrink_count,
1845         .scan_objects   = lu_cache_shrink_scan,
1846         .seeks          = DEFAULT_SEEKS,
1847 };
1848
1849 /**
1850  * Initialization of global lu_* data.
1851  */
1852 int lu_global_init(void)
1853 {
1854         int result;
1855
1856         CDEBUG(D_INFO, "Lustre LU module (%p).\n", &lu_keys);
1857
1858         result = lu_ref_global_init();
1859         if (result != 0)
1860                 return result;
1861
1862         LU_CONTEXT_KEY_INIT(&lu_global_key);
1863         result = lu_context_key_register(&lu_global_key);
1864         if (result != 0)
1865                 return result;
1866
1867         /*
1868          * At this level, we don't know what tags are needed, so allocate them
1869          * conservatively. This should not be too bad, because this
1870          * environment is global.
1871          */
1872         mutex_lock(&lu_sites_guard);
1873         result = lu_env_init(&lu_shrink_env, LCT_SHRINKER);
1874         mutex_unlock(&lu_sites_guard);
1875         if (result != 0)
1876                 return result;
1877
1878         /*
1879          * seeks estimation: 3 seeks to read a record from oi, one to read
1880          * inode, one for ea. Unfortunately setting this high value results in
1881          * lu_object/inode cache consuming all the memory.
1882          */
1883         register_shrinker(&lu_site_shrinker);
1884
1885         return result;
1886 }
1887
1888 /**
1889  * Dual to lu_global_init().
1890  */
1891 void lu_global_fini(void)
1892 {
1893         unregister_shrinker(&lu_site_shrinker);
1894         lu_context_key_degister(&lu_global_key);
1895
1896         /*
1897          * Tear shrinker environment down _after_ de-registering
1898          * lu_global_key, because the latter has a value in the former.
1899          */
1900         mutex_lock(&lu_sites_guard);
1901         lu_env_fini(&lu_shrink_env);
1902         mutex_unlock(&lu_sites_guard);
1903
1904         lu_ref_global_fini();
1905 }
1906
1907 static __u32 ls_stats_read(struct lprocfs_stats *stats, int idx)
1908 {
1909         struct lprocfs_counter ret;
1910
1911         lprocfs_stats_collect(stats, idx, &ret);
1912         if (idx == LU_SS_LRU_LEN)
1913                 /*
1914                  * protect against counter on cpu A being decremented
1915                  * before counter is incremented on cpu B; unlikely
1916                  */
1917                 return (__u32)((ret.lc_sum > 0) ? ret.lc_sum : 0);
1918
1919         return (__u32)ret.lc_count;
1920 }
1921
1922 /**
1923  * Output site statistical counters into a buffer. Suitable for
1924  * lprocfs_rd_*()-style functions.
1925  */
1926 int lu_site_stats_print(const struct lu_site *s, struct seq_file *m)
1927 {
1928         struct lu_site_stats stats;
1929
1930         memset(&stats, 0, sizeof(stats));
1931         lu_site_stats_get(s->ls_obj_hash, &stats, 1);
1932
1933         seq_printf(m, "%d/%d %d/%d %d %d %d %d %d %d %d %d\n",
1934                    stats.lss_busy,
1935                    stats.lss_total,
1936                    stats.lss_populated,
1937                    CFS_HASH_NHLIST(s->ls_obj_hash),
1938                    stats.lss_max_search,
1939                    ls_stats_read(s->ls_stats, LU_SS_CREATED),
1940                    ls_stats_read(s->ls_stats, LU_SS_CACHE_HIT),
1941                    ls_stats_read(s->ls_stats, LU_SS_CACHE_MISS),
1942                    ls_stats_read(s->ls_stats, LU_SS_CACHE_RACE),
1943                    ls_stats_read(s->ls_stats, LU_SS_CACHE_DEATH_RACE),
1944                    ls_stats_read(s->ls_stats, LU_SS_LRU_PURGED),
1945                    ls_stats_read(s->ls_stats, LU_SS_LRU_LEN));
1946         return 0;
1947 }
1948 EXPORT_SYMBOL(lu_site_stats_print);
1949
1950 /**
1951  * Helper function to initialize a number of kmem slab caches at once.
1952  */
1953 int lu_kmem_init(struct lu_kmem_descr *caches)
1954 {
1955         int result;
1956         struct lu_kmem_descr *iter = caches;
1957
1958         for (result = 0; iter->ckd_cache; ++iter) {
1959                 *iter->ckd_cache = kmem_cache_create(iter->ckd_name,
1960                                                         iter->ckd_size,
1961                                                         0, 0, NULL);
1962                 if (!*iter->ckd_cache) {
1963                         result = -ENOMEM;
1964                         /* free all previously allocated caches */
1965                         lu_kmem_fini(caches);
1966                         break;
1967                 }
1968         }
1969         return result;
1970 }
1971 EXPORT_SYMBOL(lu_kmem_init);
1972
1973 /**
1974  * Helper function to finalize a number of kmem slab cached at once. Dual to
1975  * lu_kmem_init().
1976  */
1977 void lu_kmem_fini(struct lu_kmem_descr *caches)
1978 {
1979         for (; caches->ckd_cache; ++caches) {
1980                 kmem_cache_destroy(*caches->ckd_cache);
1981                 *caches->ckd_cache = NULL;
1982         }
1983 }
1984 EXPORT_SYMBOL(lu_kmem_fini);
1985
1986 void lu_buf_free(struct lu_buf *buf)
1987 {
1988         LASSERT(buf);
1989         if (buf->lb_buf) {
1990                 LASSERT(buf->lb_len > 0);
1991                 kvfree(buf->lb_buf);
1992                 buf->lb_buf = NULL;
1993                 buf->lb_len = 0;
1994         }
1995 }
1996 EXPORT_SYMBOL(lu_buf_free);
1997
1998 void lu_buf_alloc(struct lu_buf *buf, size_t size)
1999 {
2000         LASSERT(buf);
2001         LASSERT(!buf->lb_buf);
2002         LASSERT(!buf->lb_len);
2003         buf->lb_buf = libcfs_kvzalloc(size, GFP_NOFS);
2004         if (likely(buf->lb_buf))
2005                 buf->lb_len = size;
2006 }
2007 EXPORT_SYMBOL(lu_buf_alloc);
2008
2009 void lu_buf_realloc(struct lu_buf *buf, size_t size)
2010 {
2011         lu_buf_free(buf);
2012         lu_buf_alloc(buf, size);
2013 }
2014 EXPORT_SYMBOL(lu_buf_realloc);
2015
2016 struct lu_buf *lu_buf_check_and_alloc(struct lu_buf *buf, size_t len)
2017 {
2018         if (!buf->lb_buf && !buf->lb_len)
2019                 lu_buf_alloc(buf, len);
2020
2021         if ((len > buf->lb_len) && buf->lb_buf)
2022                 lu_buf_realloc(buf, len);
2023
2024         return buf;
2025 }
2026 EXPORT_SYMBOL(lu_buf_check_and_alloc);
2027
2028 /**
2029  * Increase the size of the \a buf.
2030  * preserves old data in buffer
2031  * old buffer remains unchanged on error
2032  * \retval 0 or -ENOMEM
2033  */
2034 int lu_buf_check_and_grow(struct lu_buf *buf, size_t len)
2035 {
2036         char *ptr;
2037
2038         if (len <= buf->lb_len)
2039                 return 0;
2040
2041         ptr = libcfs_kvzalloc(len, GFP_NOFS);
2042         if (!ptr)
2043                 return -ENOMEM;
2044
2045         /* Free the old buf */
2046         if (buf->lb_buf) {
2047                 memcpy(ptr, buf->lb_buf, buf->lb_len);
2048                 kvfree(buf->lb_buf);
2049         }
2050
2051         buf->lb_buf = ptr;
2052         buf->lb_len = len;
2053         return 0;
2054 }