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