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