Whamcloud - gitweb
b=22520 make sure cl_inode_fini() to destroy the cl_object.
[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  2008 Sun Microsystems, Inc. All rights reserved
30  * Use is subject to license terms.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * lustre/obdclass/lu_object.c
37  *
38  * Lustre Object.
39  * These are the only exported functions, they provide some generic
40  * infrastructure for managing object devices
41  *
42  *   Author: Nikita Danilov <nikita.danilov@sun.com>
43  */
44
45 #define DEBUG_SUBSYSTEM S_CLASS
46 #ifndef EXPORT_SYMTAB
47 # define EXPORT_SYMTAB
48 #endif
49
50 #include <libcfs/libcfs.h>
51
52 #ifdef __KERNEL__
53 # include <linux/module.h>
54 #endif
55
56 /* hash_long() */
57 #include <libcfs/libcfs_hash.h>
58 #include <obd_class.h>
59 #include <obd_support.h>
60 #include <lustre_disk.h>
61 #include <lustre_fid.h>
62 #include <lu_object.h>
63 #include <libcfs/list.h>
64 /* lu_time_global_{init,fini}() */
65 #include <lu_time.h>
66
67 static void lu_object_free(const struct lu_env *env, struct lu_object *o);
68
69 /**
70  * Decrease reference counter on object. If last reference is freed, return
71  * object to the cache, unless lu_object_is_dying(o) holds. In the latter
72  * case, free object immediately.
73  */
74 void lu_object_put(const struct lu_env *env, struct lu_object *o)
75 {
76         struct lu_object_header *top;
77         struct lu_site          *site;
78         struct lu_object        *orig;
79         int                      kill_it;
80
81         top = o->lo_header;
82         site = o->lo_dev->ld_site;
83         orig = o;
84         kill_it = 0;
85         cfs_write_lock(&site->ls_guard);
86         if (cfs_atomic_dec_and_test(&top->loh_ref)) {
87                 /*
88                  * When last reference is released, iterate over object
89                  * layers, and notify them that object is no longer busy.
90                  */
91                 cfs_list_for_each_entry_reverse(o, &top->loh_layers,
92                                                 lo_linkage) {
93                         if (o->lo_ops->loo_object_release != NULL)
94                                 o->lo_ops->loo_object_release(env, o);
95                 }
96                 -- site->ls_busy;
97                 if (lu_object_is_dying(top)) {
98                         /*
99                          * If object is dying (will not be cached), removed it
100                          * from hash table and LRU.
101                          *
102                          * This is done with hash table and LRU lists
103                          * locked. As the only way to acquire first reference
104                          * to previously unreferenced object is through
105                          * hash-table lookup (lu_object_find()), or LRU
106                          * scanning (lu_site_purge()), that are done under
107                          * hash-table and LRU lock, no race with concurrent
108                          * object lookup is possible and we can safely destroy
109                          * object below.
110                          */
111                         cfs_hlist_del_init(&top->loh_hash);
112                         cfs_list_del_init(&top->loh_lru);
113                         -- site->ls_total;
114                         kill_it = 1;
115                 }
116         } else if (lu_object_is_dying(top)) {
117                 /*
118                  * somebody may be waiting for this, currently only used
119                  * for cl_object, see cl_object_put_last().
120                  */
121                 cfs_waitq_broadcast(&site->ls_marche_funebre);
122         }
123         cfs_write_unlock(&site->ls_guard);
124         if (kill_it)
125                 /*
126                  * Object was already removed from hash and lru above, can
127                  * kill it.
128                  */
129                 lu_object_free(env, orig);
130 }
131 EXPORT_SYMBOL(lu_object_put);
132
133 /**
134  * Allocate new object.
135  *
136  * This follows object creation protocol, described in the comment within
137  * struct lu_device_operations definition.
138  */
139 static struct lu_object *lu_object_alloc(const struct lu_env *env,
140                                          struct lu_device *dev,
141                                          const struct lu_fid *f,
142                                          const struct lu_object_conf *conf)
143 {
144         struct lu_object *scan;
145         struct lu_object *top;
146         cfs_list_t *layers;
147         int clean;
148         int result;
149         ENTRY;
150
151         /*
152          * Create top-level object slice. This will also create
153          * lu_object_header.
154          */
155         top = dev->ld_ops->ldo_object_alloc(env, NULL, dev);
156         if (top == NULL)
157                 RETURN(ERR_PTR(-ENOMEM));
158         /*
159          * This is the only place where object fid is assigned. It's constant
160          * after this point.
161          */
162         LASSERT(fid_is_igif(f) || fid_ver(f) == 0);
163         top->lo_header->loh_fid  = *f;
164         layers = &top->lo_header->loh_layers;
165         do {
166                 /*
167                  * Call ->loo_object_init() repeatedly, until no more new
168                  * object slices are created.
169                  */
170                 clean = 1;
171                 cfs_list_for_each_entry(scan, layers, lo_linkage) {
172                         if (scan->lo_flags & LU_OBJECT_ALLOCATED)
173                                 continue;
174                         clean = 0;
175                         scan->lo_header = top->lo_header;
176                         result = scan->lo_ops->loo_object_init(env, scan, conf);
177                         if (result != 0) {
178                                 lu_object_free(env, top);
179                                 RETURN(ERR_PTR(result));
180                         }
181                         scan->lo_flags |= LU_OBJECT_ALLOCATED;
182                 }
183         } while (!clean);
184
185         cfs_list_for_each_entry_reverse(scan, layers, lo_linkage) {
186                 if (scan->lo_ops->loo_object_start != NULL) {
187                         result = scan->lo_ops->loo_object_start(env, scan);
188                         if (result != 0) {
189                                 lu_object_free(env, top);
190                                 RETURN(ERR_PTR(result));
191                         }
192                 }
193         }
194
195         dev->ld_site->ls_stats.s_created ++;
196         RETURN(top);
197 }
198
199 /**
200  * Free an object.
201  */
202 static void lu_object_free(const struct lu_env *env, struct lu_object *o)
203 {
204         cfs_list_t            splice;
205         struct lu_object     *scan;
206         struct lu_site       *site;
207         cfs_list_t           *layers;
208
209         site   = o->lo_dev->ld_site;
210         layers = &o->lo_header->loh_layers;
211         /*
212          * First call ->loo_object_delete() method to release all resources.
213          */
214         cfs_list_for_each_entry_reverse(scan, layers, lo_linkage) {
215                 if (scan->lo_ops->loo_object_delete != NULL)
216                         scan->lo_ops->loo_object_delete(env, scan);
217         }
218
219         /*
220          * Then, splice object layers into stand-alone list, and call
221          * ->loo_object_free() on all layers to free memory. Splice is
222          * necessary, because lu_object_header is freed together with the
223          * top-level slice.
224          */
225         CFS_INIT_LIST_HEAD(&splice);
226         cfs_list_splice_init(layers, &splice);
227         while (!cfs_list_empty(&splice)) {
228                 /*
229                  * Free layers in bottom-to-top order, so that object header
230                  * lives as long as possible and ->loo_object_free() methods
231                  * can look at its contents.
232                  */
233                 o = container_of0(splice.prev, struct lu_object, lo_linkage);
234                 cfs_list_del_init(&o->lo_linkage);
235                 LASSERT(o->lo_ops->loo_object_free != NULL);
236                 o->lo_ops->loo_object_free(env, o);
237         }
238         cfs_waitq_broadcast(&site->ls_marche_funebre);
239 }
240
241 /**
242  * Free \a nr objects from the cold end of the site LRU list.
243  */
244 int lu_site_purge(const struct lu_env *env, struct lu_site *s, int nr)
245 {
246         cfs_list_t               dispose;
247         struct lu_object_header *h;
248         struct lu_object_header *temp;
249
250         CFS_INIT_LIST_HEAD(&dispose);
251         /*
252          * Under LRU list lock, scan LRU list and move unreferenced objects to
253          * the dispose list, removing them from LRU and hash table.
254          */
255         cfs_write_lock(&s->ls_guard);
256         cfs_list_for_each_entry_safe(h, temp, &s->ls_lru, loh_lru) {
257                 /*
258                  * Objects are sorted in lru order, and "busy" objects (ones
259                  * with h->loh_ref > 0) naturally tend to live near hot end
260                  * that we scan last. Unfortunately, sites usually have small
261                  * (less then ten) number of busy yet rarely accessed objects
262                  * (some global objects, accessed directly through pointers,
263                  * bypassing hash table). Currently algorithm scans them over
264                  * and over again. Probably we should move busy objects out of
265                  * LRU, or we can live with that.
266                  */
267                 if (nr-- == 0)
268                         break;
269                 if (cfs_atomic_read(&h->loh_ref) > 0)
270                         continue;
271                 cfs_hlist_del_init(&h->loh_hash);
272                 cfs_list_move(&h->loh_lru, &dispose);
273                 s->ls_total --;
274         }
275         cfs_write_unlock(&s->ls_guard);
276         /*
277          * Free everything on the dispose list. This is safe against races due
278          * to the reasons described in lu_object_put().
279          */
280         while (!cfs_list_empty(&dispose)) {
281                 h = container_of0(dispose.next,
282                                  struct lu_object_header, loh_lru);
283                 cfs_list_del_init(&h->loh_lru);
284                 lu_object_free(env, lu_object_top(h));
285                 s->ls_stats.s_lru_purged ++;
286         }
287         return nr;
288 }
289 EXPORT_SYMBOL(lu_site_purge);
290
291 /*
292  * Object printing.
293  *
294  * Code below has to jump through certain loops to output object description
295  * into libcfs_debug_msg-based log. The problem is that lu_object_print()
296  * composes object description from strings that are parts of _lines_ of
297  * output (i.e., strings that are not terminated by newline). This doesn't fit
298  * very well into libcfs_debug_msg() interface that assumes that each message
299  * supplied to it is a self-contained output line.
300  *
301  * To work around this, strings are collected in a temporary buffer
302  * (implemented as a value of lu_cdebug_key key), until terminating newline
303  * character is detected.
304  *
305  */
306
307 enum {
308         /**
309          * Maximal line size.
310          *
311          * XXX overflow is not handled correctly.
312          */
313         LU_CDEBUG_LINE = 256
314 };
315
316 struct lu_cdebug_data {
317         /**
318          * Temporary buffer.
319          */
320         char lck_area[LU_CDEBUG_LINE];
321 };
322
323 /* context key constructor/destructor: lu_global_key_init, lu_global_key_fini */
324 LU_KEY_INIT_FINI(lu_global, struct lu_cdebug_data);
325
326 /**
327  * Key, holding temporary buffer. This key is registered very early by
328  * lu_global_init().
329  */
330 struct lu_context_key lu_global_key = {
331         .lct_tags = LCT_MD_THREAD|LCT_DT_THREAD|LCT_CL_THREAD,
332         .lct_init = lu_global_key_init,
333         .lct_fini = lu_global_key_fini
334 };
335
336 /**
337  * Printer function emitting messages through libcfs_debug_msg().
338  */
339 int lu_cdebug_printer(const struct lu_env *env,
340                       void *cookie, const char *format, ...)
341 {
342         struct lu_cdebug_print_info *info = cookie;
343         struct lu_cdebug_data       *key;
344         int used;
345         int complete;
346         va_list args;
347
348         va_start(args, format);
349
350         key = lu_context_key_get(&env->le_ctx, &lu_global_key);
351         LASSERT(key != NULL);
352
353         used = strlen(key->lck_area);
354         complete = format[strlen(format) - 1] == '\n';
355         /*
356          * Append new chunk to the buffer.
357          */
358         vsnprintf(key->lck_area + used,
359                   ARRAY_SIZE(key->lck_area) - used, format, args);
360         if (complete) {
361                 if (cfs_cdebug_show(info->lpi_mask, info->lpi_subsys))
362                         libcfs_debug_msg(NULL, info->lpi_subsys, info->lpi_mask,
363                                          (char *)info->lpi_file, info->lpi_fn,
364                                          info->lpi_line, "%s", key->lck_area);
365                 key->lck_area[0] = 0;
366         }
367         va_end(args);
368         return 0;
369 }
370 EXPORT_SYMBOL(lu_cdebug_printer);
371
372 /**
373  * Print object header.
374  */
375 void lu_object_header_print(const struct lu_env *env, void *cookie,
376                             lu_printer_t printer,
377                             const struct lu_object_header *hdr)
378 {
379         (*printer)(env, cookie, "header@%p[%#lx, %d, "DFID"%s%s%s]",
380                    hdr, hdr->loh_flags, cfs_atomic_read(&hdr->loh_ref),
381                    PFID(&hdr->loh_fid),
382                    cfs_hlist_unhashed(&hdr->loh_hash) ? "" : " hash",
383                    cfs_list_empty((cfs_list_t *)&hdr->loh_lru) ? \
384                    "" : " lru",
385                    hdr->loh_attr & LOHA_EXISTS ? " exist":"");
386 }
387 EXPORT_SYMBOL(lu_object_header_print);
388
389 /**
390  * Print human readable representation of the \a o to the \a printer.
391  */
392 void lu_object_print(const struct lu_env *env, void *cookie,
393                      lu_printer_t printer, const struct lu_object *o)
394 {
395         static const char ruler[] = "........................................";
396         struct lu_object_header *top;
397         int depth;
398
399         top = o->lo_header;
400         lu_object_header_print(env, cookie, printer, top);
401         (*printer)(env, cookie, "{ \n");
402         cfs_list_for_each_entry(o, &top->loh_layers, lo_linkage) {
403                 depth = o->lo_depth + 4;
404
405                 /*
406                  * print `.' \a depth times followed by type name and address
407                  */
408                 (*printer)(env, cookie, "%*.*s%s@%p", depth, depth, ruler,
409                            o->lo_dev->ld_type->ldt_name, o);
410                 if (o->lo_ops->loo_object_print != NULL)
411                         o->lo_ops->loo_object_print(env, cookie, printer, o);
412                 (*printer)(env, cookie, "\n");
413         }
414         (*printer)(env, cookie, "} header@%p\n", top);
415 }
416 EXPORT_SYMBOL(lu_object_print);
417
418 /**
419  * Check object consistency.
420  */
421 int lu_object_invariant(const struct lu_object *o)
422 {
423         struct lu_object_header *top;
424
425         top = o->lo_header;
426         cfs_list_for_each_entry(o, &top->loh_layers, lo_linkage) {
427                 if (o->lo_ops->loo_object_invariant != NULL &&
428                     !o->lo_ops->loo_object_invariant(o))
429                         return 0;
430         }
431         return 1;
432 }
433 EXPORT_SYMBOL(lu_object_invariant);
434
435 static struct lu_object *htable_lookup(struct lu_site *s,
436                                        const cfs_hlist_head_t *bucket,
437                                        const struct lu_fid *f,
438                                        cfs_waitlink_t *waiter)
439 {
440         struct lu_object_header *h;
441         cfs_hlist_node_t *scan;
442
443         cfs_hlist_for_each_entry(h, scan, bucket, loh_hash) {
444                 s->ls_stats.s_cache_check ++;
445                 if (likely(lu_fid_eq(&h->loh_fid, f))) {
446                         if (unlikely(lu_object_is_dying(h))) {
447                                 /*
448                                  * Lookup found an object being destroyed;
449                                  * this object cannot be returned (to assure
450                                  * that references to dying objects are
451                                  * eventually drained), and moreover, lookup
452                                  * has to wait until object is freed.
453                                  */
454                                 cfs_waitlink_init(waiter);
455                                 cfs_waitq_add(&s->ls_marche_funebre, waiter);
456                                 cfs_set_current_state(CFS_TASK_UNINT);
457                                 s->ls_stats.s_cache_death_race ++;
458                                 return ERR_PTR(-EAGAIN);
459                         }
460                         /* bump reference count... */
461                         if (cfs_atomic_add_return(1, &h->loh_ref) == 1)
462                                 ++ s->ls_busy;
463                         /* and move to the head of the LRU */
464                         /*
465                          * XXX temporary disable this to measure effects of
466                          * read-write locking.
467                          */
468                         /* list_move_tail(&h->loh_lru, &s->ls_lru); */
469                         s->ls_stats.s_cache_hit ++;
470                         return lu_object_top(h);
471                 }
472         }
473         s->ls_stats.s_cache_miss ++;
474         return NULL;
475 }
476
477 static __u32 fid_hash(const struct lu_fid *f, int bits)
478 {
479         /* all objects with same id and different versions will belong to same
480          * collisions list. */
481         return cfs_hash_long(fid_flatten(f), bits);
482 }
483
484 /**
485  * Search cache for an object with the fid \a f. If such object is found,
486  * return it. Otherwise, create new object, insert it into cache and return
487  * it. In any case, additional reference is acquired on the returned object.
488  */
489 struct lu_object *lu_object_find(const struct lu_env *env,
490                                  struct lu_device *dev, const struct lu_fid *f,
491                                  const struct lu_object_conf *conf)
492 {
493         return lu_object_find_at(env, dev->ld_site->ls_top_dev, f, conf);
494 }
495 EXPORT_SYMBOL(lu_object_find);
496
497 /**
498  * Core logic of lu_object_find*() functions.
499  */
500 static struct lu_object *lu_object_find_try(const struct lu_env *env,
501                                             struct lu_device *dev,
502                                             const struct lu_fid *f,
503                                             const struct lu_object_conf *conf,
504                                             cfs_waitlink_t *waiter)
505 {
506         struct lu_site        *s;
507         struct lu_object      *o;
508         struct lu_object      *shadow;
509         cfs_hlist_head_t      *bucket;
510
511         /*
512          * This uses standard index maintenance protocol:
513          *
514          *     - search index under lock, and return object if found;
515          *     - otherwise, unlock index, allocate new object;
516          *     - lock index and search again;
517          *     - if nothing is found (usual case), insert newly created
518          *       object into index;
519          *     - otherwise (race: other thread inserted object), free
520          *       object just allocated.
521          *     - unlock index;
522          *     - return object.
523          *
524          * If dying object is found during index search, add @waiter to the
525          * site wait-queue and return ERR_PTR(-EAGAIN).
526          */
527
528         s = dev->ld_site;
529         bucket = s->ls_hash + fid_hash(f, s->ls_hash_bits);
530
531         cfs_read_lock(&s->ls_guard);
532         o = htable_lookup(s, bucket, f, waiter);
533         cfs_read_unlock(&s->ls_guard);
534
535         if (o != NULL)
536                 return o;
537
538         /*
539          * Allocate new object. This may result in rather complicated
540          * operations, including fld queries, inode loading, etc.
541          */
542         o = lu_object_alloc(env, dev, f, conf);
543         if (unlikely(IS_ERR(o)))
544                 return o;
545
546         LASSERT(lu_fid_eq(lu_object_fid(o), f));
547
548         cfs_write_lock(&s->ls_guard);
549         shadow = htable_lookup(s, bucket, f, waiter);
550         if (likely(shadow == NULL)) {
551                 cfs_hlist_add_head(&o->lo_header->loh_hash, bucket);
552                 cfs_list_add_tail(&o->lo_header->loh_lru, &s->ls_lru);
553                 ++ s->ls_busy;
554                 ++ s->ls_total;
555                 shadow = o;
556                 o = NULL;
557         } else
558                 s->ls_stats.s_cache_race ++;
559         cfs_write_unlock(&s->ls_guard);
560         if (o != NULL)
561                 lu_object_free(env, o);
562         return shadow;
563 }
564
565 /**
566  * Much like lu_object_find(), but top level device of object is specifically
567  * \a dev rather than top level device of the site. This interface allows
568  * objects of different "stacking" to be created within the same site.
569  */
570 struct lu_object *lu_object_find_at(const struct lu_env *env,
571                                     struct lu_device *dev,
572                                     const struct lu_fid *f,
573                                     const struct lu_object_conf *conf)
574 {
575         struct lu_object *obj;
576         cfs_waitlink_t    wait;
577
578         while (1) {
579                 obj = lu_object_find_try(env, dev, f, conf, &wait);
580                 if (obj == ERR_PTR(-EAGAIN)) {
581                         /*
582                          * lu_object_find_try() already added waiter into the
583                          * wait queue.
584                          */
585                         cfs_waitq_wait(&wait, CFS_TASK_UNINT);
586                         cfs_waitq_del(&dev->ld_site->ls_marche_funebre, &wait);
587                 } else
588                         break;
589         }
590         return obj;
591 }
592 EXPORT_SYMBOL(lu_object_find_at);
593
594 /**
595  * Find object with given fid, and return its slice belonging to given device.
596  */
597 struct lu_object *lu_object_find_slice(const struct lu_env *env,
598                                        struct lu_device *dev,
599                                        const struct lu_fid *f,
600                                        const struct lu_object_conf *conf)
601 {
602         struct lu_object *top;
603         struct lu_object *obj;
604
605         top = lu_object_find(env, dev, f, conf);
606         if (!IS_ERR(top)) {
607                 obj = lu_object_locate(top->lo_header, dev->ld_type);
608                 if (obj == NULL)
609                         lu_object_put(env, top);
610         } else
611                 obj = top;
612         return obj;
613 }
614 EXPORT_SYMBOL(lu_object_find_slice);
615
616 /**
617  * Global list of all device types.
618  */
619 static CFS_LIST_HEAD(lu_device_types);
620
621 int lu_device_type_init(struct lu_device_type *ldt)
622 {
623         int result;
624
625         CFS_INIT_LIST_HEAD(&ldt->ldt_linkage);
626         result = ldt->ldt_ops->ldto_init(ldt);
627         if (result == 0)
628                 cfs_list_add(&ldt->ldt_linkage, &lu_device_types);
629         return result;
630 }
631 EXPORT_SYMBOL(lu_device_type_init);
632
633 void lu_device_type_fini(struct lu_device_type *ldt)
634 {
635         cfs_list_del_init(&ldt->ldt_linkage);
636         ldt->ldt_ops->ldto_fini(ldt);
637 }
638 EXPORT_SYMBOL(lu_device_type_fini);
639
640 void lu_types_stop(void)
641 {
642         struct lu_device_type *ldt;
643
644         cfs_list_for_each_entry(ldt, &lu_device_types, ldt_linkage) {
645                 if (ldt->ldt_device_nr == 0)
646                         ldt->ldt_ops->ldto_stop(ldt);
647         }
648 }
649 EXPORT_SYMBOL(lu_types_stop);
650
651 /**
652  * Global list of all sites on this node
653  */
654 static CFS_LIST_HEAD(lu_sites);
655 static CFS_DECLARE_MUTEX(lu_sites_guard);
656
657 /**
658  * Global environment used by site shrinker.
659  */
660 static struct lu_env lu_shrink_env;
661
662 /**
663  * Print all objects in \a s.
664  */
665 void lu_site_print(const struct lu_env *env, struct lu_site *s, void *cookie,
666                    lu_printer_t printer)
667 {
668         int i;
669
670         for (i = 0; i < s->ls_hash_size; ++i) {
671                 struct lu_object_header *h;
672                 cfs_hlist_node_t        *scan;
673
674                 cfs_read_lock(&s->ls_guard);
675                 cfs_hlist_for_each_entry(h, scan, &s->ls_hash[i], loh_hash) {
676
677                         if (!cfs_list_empty(&h->loh_layers)) {
678                                 const struct lu_object *obj;
679
680                                 obj = lu_object_top(h);
681                                 lu_object_print(env, cookie, printer, obj);
682                         } else
683                                 lu_object_header_print(env, cookie, printer, h);
684                 }
685                 cfs_read_unlock(&s->ls_guard);
686         }
687 }
688 EXPORT_SYMBOL(lu_site_print);
689
690 enum {
691         LU_CACHE_PERCENT   = 20,
692 };
693
694 /**
695  * Return desired hash table order.
696  */
697 static int lu_htable_order(void)
698 {
699         unsigned long cache_size;
700         int bits;
701
702         /*
703          * Calculate hash table size, assuming that we want reasonable
704          * performance when 20% of total memory is occupied by cache of
705          * lu_objects.
706          *
707          * Size of lu_object is (arbitrary) taken as 1K (together with inode).
708          */
709         cache_size = cfs_num_physpages;
710
711 #if BITS_PER_LONG == 32
712         /* limit hashtable size for lowmem systems to low RAM */
713         if (cache_size > 1 << (30 - CFS_PAGE_SHIFT))
714                 cache_size = 1 << (30 - CFS_PAGE_SHIFT) * 3 / 4;
715 #endif
716
717         cache_size = cache_size / 100 * LU_CACHE_PERCENT *
718                 (CFS_PAGE_SIZE / 1024);
719
720         for (bits = 1; (1 << bits) < cache_size; ++bits) {
721                 ;
722         }
723         return bits;
724 }
725
726 static cfs_lock_class_key_t lu_site_guard_class;
727
728 /**
729  * Initialize site \a s, with \a d as the top level device.
730  */
731 int lu_site_init(struct lu_site *s, struct lu_device *top)
732 {
733         int bits;
734         int size;
735         int i;
736         ENTRY;
737
738         memset(s, 0, sizeof *s);
739         cfs_rwlock_init(&s->ls_guard);
740         cfs_lockdep_set_class(&s->ls_guard, &lu_site_guard_class);
741         CFS_INIT_LIST_HEAD(&s->ls_lru);
742         CFS_INIT_LIST_HEAD(&s->ls_linkage);
743         cfs_waitq_init(&s->ls_marche_funebre);
744         s->ls_top_dev = top;
745         top->ld_site = s;
746         lu_device_get(top);
747         lu_ref_add(&top->ld_reference, "site-top", s);
748
749         for (bits = lu_htable_order(), size = 1 << bits;
750              (s->ls_hash =
751               cfs_alloc_large(size * sizeof s->ls_hash[0])) == NULL;
752              --bits, size >>= 1) {
753                 /*
754                  * Scale hash table down, until allocation succeeds.
755                  */
756                 ;
757         }
758
759         s->ls_hash_size = size;
760         s->ls_hash_bits = bits;
761         s->ls_hash_mask = size - 1;
762
763         for (i = 0; i < size; i++)
764                 CFS_INIT_HLIST_HEAD(&s->ls_hash[i]);
765
766         RETURN(0);
767 }
768 EXPORT_SYMBOL(lu_site_init);
769
770 /**
771  * Finalize \a s and release its resources.
772  */
773 void lu_site_fini(struct lu_site *s)
774 {
775         LASSERT(cfs_list_empty(&s->ls_lru));
776         LASSERT(s->ls_total == 0);
777
778         cfs_down(&lu_sites_guard);
779         cfs_list_del_init(&s->ls_linkage);
780         cfs_up(&lu_sites_guard);
781
782         if (s->ls_hash != NULL) {
783                 int i;
784                 for (i = 0; i < s->ls_hash_size; i++)
785                         LASSERT(cfs_hlist_empty(&s->ls_hash[i]));
786                 cfs_free_large(s->ls_hash);
787                 s->ls_hash = NULL;
788         }
789         if (s->ls_top_dev != NULL) {
790                 s->ls_top_dev->ld_site = NULL;
791                 lu_ref_del(&s->ls_top_dev->ld_reference, "site-top", s);
792                 lu_device_put(s->ls_top_dev);
793                 s->ls_top_dev = NULL;
794         }
795 }
796 EXPORT_SYMBOL(lu_site_fini);
797
798 /**
799  * Called when initialization of stack for this site is completed.
800  */
801 int lu_site_init_finish(struct lu_site *s)
802 {
803         int result;
804         cfs_down(&lu_sites_guard);
805         result = lu_context_refill(&lu_shrink_env.le_ctx);
806         if (result == 0)
807                 cfs_list_add(&s->ls_linkage, &lu_sites);
808         cfs_up(&lu_sites_guard);
809         return result;
810 }
811 EXPORT_SYMBOL(lu_site_init_finish);
812
813 /**
814  * Acquire additional reference on device \a d
815  */
816 void lu_device_get(struct lu_device *d)
817 {
818         cfs_atomic_inc(&d->ld_ref);
819 }
820 EXPORT_SYMBOL(lu_device_get);
821
822 /**
823  * Release reference on device \a d.
824  */
825 void lu_device_put(struct lu_device *d)
826 {
827         LASSERT(cfs_atomic_read(&d->ld_ref) > 0);
828         cfs_atomic_dec(&d->ld_ref);
829 }
830 EXPORT_SYMBOL(lu_device_put);
831
832 /**
833  * Initialize device \a d of type \a t.
834  */
835 int lu_device_init(struct lu_device *d, struct lu_device_type *t)
836 {
837         if (t->ldt_device_nr++ == 0 && t->ldt_ops->ldto_start != NULL)
838                 t->ldt_ops->ldto_start(t);
839         memset(d, 0, sizeof *d);
840         cfs_atomic_set(&d->ld_ref, 0);
841         d->ld_type = t;
842         lu_ref_init(&d->ld_reference);
843         return 0;
844 }
845 EXPORT_SYMBOL(lu_device_init);
846
847 /**
848  * Finalize device \a d.
849  */
850 void lu_device_fini(struct lu_device *d)
851 {
852         struct lu_device_type *t;
853
854         t = d->ld_type;
855         if (d->ld_obd != NULL) {
856                 d->ld_obd->obd_lu_dev = NULL;
857                 d->ld_obd = NULL;
858         }
859
860         lu_ref_fini(&d->ld_reference);
861         LASSERTF(cfs_atomic_read(&d->ld_ref) == 0,
862                  "Refcount is %u\n", cfs_atomic_read(&d->ld_ref));
863         LASSERT(t->ldt_device_nr > 0);
864         if (--t->ldt_device_nr == 0 && t->ldt_ops->ldto_stop != NULL)
865                 t->ldt_ops->ldto_stop(t);
866 }
867 EXPORT_SYMBOL(lu_device_fini);
868
869 /**
870  * Initialize object \a o that is part of compound object \a h and was created
871  * by device \a d.
872  */
873 int lu_object_init(struct lu_object *o,
874                    struct lu_object_header *h, struct lu_device *d)
875 {
876         memset(o, 0, sizeof *o);
877         o->lo_header = h;
878         o->lo_dev    = d;
879         lu_device_get(d);
880         o->lo_dev_ref = lu_ref_add(&d->ld_reference, "lu_object", o);
881         CFS_INIT_LIST_HEAD(&o->lo_linkage);
882         return 0;
883 }
884 EXPORT_SYMBOL(lu_object_init);
885
886 /**
887  * Finalize object and release its resources.
888  */
889 void lu_object_fini(struct lu_object *o)
890 {
891         struct lu_device *dev = o->lo_dev;
892
893         LASSERT(cfs_list_empty(&o->lo_linkage));
894
895         if (dev != NULL) {
896                 lu_ref_del_at(&dev->ld_reference,
897                               o->lo_dev_ref , "lu_object", o);
898                 lu_device_put(dev);
899                 o->lo_dev = NULL;
900         }
901 }
902 EXPORT_SYMBOL(lu_object_fini);
903
904 /**
905  * Add object \a o as first layer of compound object \a h
906  *
907  * This is typically called by the ->ldo_object_alloc() method of top-level
908  * device.
909  */
910 void lu_object_add_top(struct lu_object_header *h, struct lu_object *o)
911 {
912         cfs_list_move(&o->lo_linkage, &h->loh_layers);
913 }
914 EXPORT_SYMBOL(lu_object_add_top);
915
916 /**
917  * Add object \a o as a layer of compound object, going after \a before.
918  *
919  * This is typically called by the ->ldo_object_alloc() method of \a
920  * before->lo_dev.
921  */
922 void lu_object_add(struct lu_object *before, struct lu_object *o)
923 {
924         cfs_list_move(&o->lo_linkage, &before->lo_linkage);
925 }
926 EXPORT_SYMBOL(lu_object_add);
927
928 /**
929  * Initialize compound object.
930  */
931 int lu_object_header_init(struct lu_object_header *h)
932 {
933         memset(h, 0, sizeof *h);
934         cfs_atomic_set(&h->loh_ref, 1);
935         CFS_INIT_HLIST_NODE(&h->loh_hash);
936         CFS_INIT_LIST_HEAD(&h->loh_lru);
937         CFS_INIT_LIST_HEAD(&h->loh_layers);
938         lu_ref_init(&h->loh_reference);
939         return 0;
940 }
941 EXPORT_SYMBOL(lu_object_header_init);
942
943 /**
944  * Finalize compound object.
945  */
946 void lu_object_header_fini(struct lu_object_header *h)
947 {
948         LASSERT(cfs_list_empty(&h->loh_layers));
949         LASSERT(cfs_list_empty(&h->loh_lru));
950         LASSERT(cfs_hlist_unhashed(&h->loh_hash));
951         lu_ref_fini(&h->loh_reference);
952 }
953 EXPORT_SYMBOL(lu_object_header_fini);
954
955 /**
956  * Given a compound object, find its slice, corresponding to the device type
957  * \a dtype.
958  */
959 struct lu_object *lu_object_locate(struct lu_object_header *h,
960                                    const struct lu_device_type *dtype)
961 {
962         struct lu_object *o;
963
964         cfs_list_for_each_entry(o, &h->loh_layers, lo_linkage) {
965                 if (o->lo_dev->ld_type == dtype)
966                         return o;
967         }
968         return NULL;
969 }
970 EXPORT_SYMBOL(lu_object_locate);
971
972
973
974 /**
975  * Finalize and free devices in the device stack.
976  *
977  * Finalize device stack by purging object cache, and calling
978  * lu_device_type_operations::ldto_device_fini() and
979  * lu_device_type_operations::ldto_device_free() on all devices in the stack.
980  */
981 void lu_stack_fini(const struct lu_env *env, struct lu_device *top)
982 {
983         struct lu_site   *site = top->ld_site;
984         struct lu_device *scan;
985         struct lu_device *next;
986
987         lu_site_purge(env, site, ~0);
988         for (scan = top; scan != NULL; scan = next) {
989                 next = scan->ld_type->ldt_ops->ldto_device_fini(env, scan);
990                 lu_ref_del(&scan->ld_reference, "lu-stack", &lu_site_init);
991                 lu_device_put(scan);
992         }
993
994         /* purge again. */
995         lu_site_purge(env, site, ~0);
996
997         if (!cfs_list_empty(&site->ls_lru) || site->ls_total != 0) {
998                 /*
999                  * Uh-oh, objects still exist.
1000                  */
1001                 static DECLARE_LU_CDEBUG_PRINT_INFO(cookie, D_ERROR);
1002
1003                 lu_site_print(env, site, &cookie, lu_cdebug_printer);
1004         }
1005
1006         for (scan = top; scan != NULL; scan = next) {
1007                 const struct lu_device_type *ldt = scan->ld_type;
1008                 struct obd_type             *type;
1009
1010                 next = ldt->ldt_ops->ldto_device_free(env, scan);
1011                 type = ldt->ldt_obd_type;
1012                 if (type != NULL) {
1013                         type->typ_refcnt--;
1014                         class_put_type(type);
1015                 }
1016         }
1017 }
1018 EXPORT_SYMBOL(lu_stack_fini);
1019
1020 enum {
1021         /**
1022          * Maximal number of tld slots.
1023          */
1024         LU_CONTEXT_KEY_NR = 32
1025 };
1026
1027 static struct lu_context_key *lu_keys[LU_CONTEXT_KEY_NR] = { NULL, };
1028
1029 static cfs_spinlock_t lu_keys_guard = CFS_SPIN_LOCK_UNLOCKED;
1030
1031 /**
1032  * Global counter incremented whenever key is registered, unregistered,
1033  * revived or quiesced. This is used to void unnecessary calls to
1034  * lu_context_refill(). No locking is provided, as initialization and shutdown
1035  * are supposed to be externally serialized.
1036  */
1037 static unsigned key_set_version = 0;
1038
1039 /**
1040  * Register new key.
1041  */
1042 int lu_context_key_register(struct lu_context_key *key)
1043 {
1044         int result;
1045         int i;
1046
1047         LASSERT(key->lct_init != NULL);
1048         LASSERT(key->lct_fini != NULL);
1049         LASSERT(key->lct_tags != 0);
1050         LASSERT(key->lct_owner != NULL);
1051
1052         result = -ENFILE;
1053         cfs_spin_lock(&lu_keys_guard);
1054         for (i = 0; i < ARRAY_SIZE(lu_keys); ++i) {
1055                 if (lu_keys[i] == NULL) {
1056                         key->lct_index = i;
1057                         cfs_atomic_set(&key->lct_used, 1);
1058                         lu_keys[i] = key;
1059                         lu_ref_init(&key->lct_reference);
1060                         result = 0;
1061                         ++key_set_version;
1062                         break;
1063                 }
1064         }
1065         cfs_spin_unlock(&lu_keys_guard);
1066         return result;
1067 }
1068 EXPORT_SYMBOL(lu_context_key_register);
1069
1070 static void key_fini(struct lu_context *ctx, int index)
1071 {
1072         if (ctx->lc_value != NULL && ctx->lc_value[index] != NULL) {
1073                 struct lu_context_key *key;
1074
1075                 key = lu_keys[index];
1076                 LASSERT(key != NULL);
1077                 LASSERT(key->lct_fini != NULL);
1078                 LASSERT(cfs_atomic_read(&key->lct_used) > 1);
1079
1080                 key->lct_fini(ctx, key, ctx->lc_value[index]);
1081                 lu_ref_del(&key->lct_reference, "ctx", ctx);
1082                 cfs_atomic_dec(&key->lct_used);
1083                 LASSERT(key->lct_owner != NULL);
1084                 if (!(ctx->lc_tags & LCT_NOREF)) {
1085                         LASSERT(cfs_module_refcount(key->lct_owner) > 0);
1086                         cfs_module_put(key->lct_owner);
1087                 }
1088                 ctx->lc_value[index] = NULL;
1089         }
1090 }
1091
1092 /**
1093  * Deregister key.
1094  */
1095 void lu_context_key_degister(struct lu_context_key *key)
1096 {
1097         LASSERT(cfs_atomic_read(&key->lct_used) >= 1);
1098         LINVRNT(0 <= key->lct_index && key->lct_index < ARRAY_SIZE(lu_keys));
1099
1100         lu_context_key_quiesce(key);
1101
1102         ++key_set_version;
1103         cfs_spin_lock(&lu_keys_guard);
1104         key_fini(&lu_shrink_env.le_ctx, key->lct_index);
1105         if (lu_keys[key->lct_index]) {
1106                 lu_keys[key->lct_index] = NULL;
1107                 lu_ref_fini(&key->lct_reference);
1108         }
1109         cfs_spin_unlock(&lu_keys_guard);
1110
1111         LASSERTF(cfs_atomic_read(&key->lct_used) == 1,
1112                  "key has instances: %d\n",
1113                  cfs_atomic_read(&key->lct_used));
1114 }
1115 EXPORT_SYMBOL(lu_context_key_degister);
1116
1117 /**
1118  * Register a number of keys. This has to be called after all keys have been
1119  * initialized by a call to LU_CONTEXT_KEY_INIT().
1120  */
1121 int lu_context_key_register_many(struct lu_context_key *k, ...)
1122 {
1123         struct lu_context_key *key = k;
1124         va_list args;
1125         int result;
1126
1127         va_start(args, k);
1128         do {
1129                 result = lu_context_key_register(key);
1130                 if (result)
1131                         break;
1132                 key = va_arg(args, struct lu_context_key *);
1133         } while (key != NULL);
1134         va_end(args);
1135
1136         if (result != 0) {
1137                 va_start(args, k);
1138                 while (k != key) {
1139                         lu_context_key_degister(k);
1140                         k = va_arg(args, struct lu_context_key *);
1141                 }
1142                 va_end(args);
1143         }
1144
1145         return result;
1146 }
1147 EXPORT_SYMBOL(lu_context_key_register_many);
1148
1149 /**
1150  * De-register a number of keys. This is a dual to
1151  * lu_context_key_register_many().
1152  */
1153 void lu_context_key_degister_many(struct lu_context_key *k, ...)
1154 {
1155         va_list args;
1156
1157         va_start(args, k);
1158         do {
1159                 lu_context_key_degister(k);
1160                 k = va_arg(args, struct lu_context_key*);
1161         } while (k != NULL);
1162         va_end(args);
1163 }
1164 EXPORT_SYMBOL(lu_context_key_degister_many);
1165
1166 /**
1167  * Revive a number of keys.
1168  */
1169 void lu_context_key_revive_many(struct lu_context_key *k, ...)
1170 {
1171         va_list args;
1172
1173         va_start(args, k);
1174         do {
1175                 lu_context_key_revive(k);
1176                 k = va_arg(args, struct lu_context_key*);
1177         } while (k != NULL);
1178         va_end(args);
1179 }
1180 EXPORT_SYMBOL(lu_context_key_revive_many);
1181
1182 /**
1183  * Quiescent a number of keys.
1184  */
1185 void lu_context_key_quiesce_many(struct lu_context_key *k, ...)
1186 {
1187         va_list args;
1188
1189         va_start(args, k);
1190         do {
1191                 lu_context_key_quiesce(k);
1192                 k = va_arg(args, struct lu_context_key*);
1193         } while (k != NULL);
1194         va_end(args);
1195 }
1196 EXPORT_SYMBOL(lu_context_key_quiesce_many);
1197
1198 /**
1199  * Return value associated with key \a key in context \a ctx.
1200  */
1201 void *lu_context_key_get(const struct lu_context *ctx,
1202                          const struct lu_context_key *key)
1203 {
1204         LINVRNT(ctx->lc_state == LCS_ENTERED);
1205         LINVRNT(0 <= key->lct_index && key->lct_index < ARRAY_SIZE(lu_keys));
1206         LASSERT(lu_keys[key->lct_index] == key);
1207         return ctx->lc_value[key->lct_index];
1208 }
1209 EXPORT_SYMBOL(lu_context_key_get);
1210
1211 /**
1212  * List of remembered contexts. XXX document me.
1213  */
1214 static CFS_LIST_HEAD(lu_context_remembered);
1215
1216 /**
1217  * Destroy \a key in all remembered contexts. This is used to destroy key
1218  * values in "shared" contexts (like service threads), when a module owning
1219  * the key is about to be unloaded.
1220  */
1221 void lu_context_key_quiesce(struct lu_context_key *key)
1222 {
1223         struct lu_context *ctx;
1224         extern unsigned cl_env_cache_purge(unsigned nr);
1225
1226         if (!(key->lct_tags & LCT_QUIESCENT)) {
1227                 /*
1228                  * XXX layering violation.
1229                  */
1230                 cl_env_cache_purge(~0);
1231                 key->lct_tags |= LCT_QUIESCENT;
1232                 /*
1233                  * XXX memory barrier has to go here.
1234                  */
1235                 cfs_spin_lock(&lu_keys_guard);
1236                 cfs_list_for_each_entry(ctx, &lu_context_remembered,
1237                                         lc_remember)
1238                         key_fini(ctx, key->lct_index);
1239                 cfs_spin_unlock(&lu_keys_guard);
1240                 ++key_set_version;
1241         }
1242 }
1243 EXPORT_SYMBOL(lu_context_key_quiesce);
1244
1245 void lu_context_key_revive(struct lu_context_key *key)
1246 {
1247         key->lct_tags &= ~LCT_QUIESCENT;
1248         ++key_set_version;
1249 }
1250 EXPORT_SYMBOL(lu_context_key_revive);
1251
1252 static void keys_fini(struct lu_context *ctx)
1253 {
1254         int i;
1255
1256         cfs_spin_lock(&lu_keys_guard);
1257         if (ctx->lc_value != NULL) {
1258                 for (i = 0; i < ARRAY_SIZE(lu_keys); ++i)
1259                         key_fini(ctx, i);
1260                 OBD_FREE(ctx->lc_value,
1261                          ARRAY_SIZE(lu_keys) * sizeof ctx->lc_value[0]);
1262                 ctx->lc_value = NULL;
1263         }
1264         cfs_spin_unlock(&lu_keys_guard);
1265 }
1266
1267 static int keys_fill(struct lu_context *ctx)
1268 {
1269         int i;
1270
1271         for (i = 0; i < ARRAY_SIZE(lu_keys); ++i) {
1272                 struct lu_context_key *key;
1273
1274                 key = lu_keys[i];
1275                 if (ctx->lc_value[i] == NULL && key != NULL &&
1276                     (key->lct_tags & ctx->lc_tags) &&
1277                     /*
1278                      * Don't create values for a LCT_QUIESCENT key, as this
1279                      * will pin module owning a key.
1280                      */
1281                     !(key->lct_tags & LCT_QUIESCENT)) {
1282                         void *value;
1283
1284                         LINVRNT(key->lct_init != NULL);
1285                         LINVRNT(key->lct_index == i);
1286
1287                         value = key->lct_init(ctx, key);
1288                         if (unlikely(IS_ERR(value)))
1289                                 return PTR_ERR(value);
1290
1291                         LASSERT(key->lct_owner != NULL);
1292                         if (!(ctx->lc_tags & LCT_NOREF))
1293                                 cfs_try_module_get(key->lct_owner);
1294                         lu_ref_add_atomic(&key->lct_reference, "ctx", ctx);
1295                         cfs_atomic_inc(&key->lct_used);
1296                         /*
1297                          * This is the only place in the code, where an
1298                          * element of ctx->lc_value[] array is set to non-NULL
1299                          * value.
1300                          */
1301                         ctx->lc_value[i] = value;
1302                         if (key->lct_exit != NULL)
1303                                 ctx->lc_tags |= LCT_HAS_EXIT;
1304                 }
1305                 ctx->lc_version = key_set_version;
1306         }
1307         return 0;
1308 }
1309
1310 static int keys_init(struct lu_context *ctx)
1311 {
1312         int result;
1313
1314         OBD_ALLOC(ctx->lc_value, ARRAY_SIZE(lu_keys) * sizeof ctx->lc_value[0]);
1315         if (likely(ctx->lc_value != NULL))
1316                 result = keys_fill(ctx);
1317         else
1318                 result = -ENOMEM;
1319
1320         if (result != 0)
1321                 keys_fini(ctx);
1322         return result;
1323 }
1324
1325 /**
1326  * Initialize context data-structure. Create values for all keys.
1327  */
1328 int lu_context_init(struct lu_context *ctx, __u32 tags)
1329 {
1330         memset(ctx, 0, sizeof *ctx);
1331         ctx->lc_state = LCS_INITIALIZED;
1332         ctx->lc_tags = tags;
1333         if (tags & LCT_REMEMBER) {
1334                 cfs_spin_lock(&lu_keys_guard);
1335                 cfs_list_add(&ctx->lc_remember, &lu_context_remembered);
1336                 cfs_spin_unlock(&lu_keys_guard);
1337         } else
1338                 CFS_INIT_LIST_HEAD(&ctx->lc_remember);
1339         return keys_init(ctx);
1340 }
1341 EXPORT_SYMBOL(lu_context_init);
1342
1343 /**
1344  * Finalize context data-structure. Destroy key values.
1345  */
1346 void lu_context_fini(struct lu_context *ctx)
1347 {
1348         LINVRNT(ctx->lc_state == LCS_INITIALIZED || ctx->lc_state == LCS_LEFT);
1349         ctx->lc_state = LCS_FINALIZED;
1350         keys_fini(ctx);
1351         cfs_spin_lock(&lu_keys_guard);
1352         cfs_list_del_init(&ctx->lc_remember);
1353         cfs_spin_unlock(&lu_keys_guard);
1354 }
1355 EXPORT_SYMBOL(lu_context_fini);
1356
1357 /**
1358  * Called before entering context.
1359  */
1360 void lu_context_enter(struct lu_context *ctx)
1361 {
1362         LINVRNT(ctx->lc_state == LCS_INITIALIZED || ctx->lc_state == LCS_LEFT);
1363         ctx->lc_state = LCS_ENTERED;
1364 }
1365 EXPORT_SYMBOL(lu_context_enter);
1366
1367 /**
1368  * Called after exiting from \a ctx
1369  */
1370 void lu_context_exit(struct lu_context *ctx)
1371 {
1372         int i;
1373
1374         LINVRNT(ctx->lc_state == LCS_ENTERED);
1375         ctx->lc_state = LCS_LEFT;
1376         if (ctx->lc_tags & LCT_HAS_EXIT && ctx->lc_value != NULL) {
1377                 for (i = 0; i < ARRAY_SIZE(lu_keys); ++i) {
1378                         if (ctx->lc_value[i] != NULL) {
1379                                 struct lu_context_key *key;
1380
1381                                 key = lu_keys[i];
1382                                 LASSERT(key != NULL);
1383                                 if (key->lct_exit != NULL)
1384                                         key->lct_exit(ctx,
1385                                                       key, ctx->lc_value[i]);
1386                         }
1387                 }
1388         }
1389 }
1390 EXPORT_SYMBOL(lu_context_exit);
1391
1392 /**
1393  * Allocate for context all missing keys that were registered after context
1394  * creation.
1395  */
1396 int lu_context_refill(struct lu_context *ctx)
1397 {
1398         LINVRNT(ctx->lc_value != NULL);
1399         return ctx->lc_version == key_set_version ? 0 : keys_fill(ctx);
1400 }
1401 EXPORT_SYMBOL(lu_context_refill);
1402
1403 int lu_env_init(struct lu_env *env, __u32 tags)
1404 {
1405         int result;
1406
1407         env->le_ses = NULL;
1408         result = lu_context_init(&env->le_ctx, tags);
1409         if (likely(result == 0))
1410                 lu_context_enter(&env->le_ctx);
1411         return result;
1412 }
1413 EXPORT_SYMBOL(lu_env_init);
1414
1415 void lu_env_fini(struct lu_env *env)
1416 {
1417         lu_context_exit(&env->le_ctx);
1418         lu_context_fini(&env->le_ctx);
1419         env->le_ses = NULL;
1420 }
1421 EXPORT_SYMBOL(lu_env_fini);
1422
1423 int lu_env_refill(struct lu_env *env)
1424 {
1425         int result;
1426
1427         result = lu_context_refill(&env->le_ctx);
1428         if (result == 0 && env->le_ses != NULL)
1429                 result = lu_context_refill(env->le_ses);
1430         return result;
1431 }
1432 EXPORT_SYMBOL(lu_env_refill);
1433
1434 static struct cfs_shrinker *lu_site_shrinker = NULL;
1435
1436 #ifdef __KERNEL__
1437 static int lu_cache_shrink(int nr, unsigned int gfp_mask)
1438 {
1439         struct lu_site *s;
1440         struct lu_site *tmp;
1441         int cached = 0;
1442         int remain = nr;
1443         CFS_LIST_HEAD(splice);
1444
1445         if (nr != 0) {
1446                 if (!(gfp_mask & __GFP_FS))
1447                         return -1;
1448                 CDEBUG(D_INODE, "Shrink %d objects\n", nr);
1449         }
1450
1451         cfs_down(&lu_sites_guard);
1452         cfs_list_for_each_entry_safe(s, tmp, &lu_sites, ls_linkage) {
1453                 if (nr != 0) {
1454                         remain = lu_site_purge(&lu_shrink_env, s, remain);
1455                         /*
1456                          * Move just shrunk site to the tail of site list to
1457                          * assure shrinking fairness.
1458                          */
1459                         cfs_list_move_tail(&s->ls_linkage, &splice);
1460                 }
1461                 cfs_read_lock(&s->ls_guard);
1462                 cached += s->ls_total - s->ls_busy;
1463                 cfs_read_unlock(&s->ls_guard);
1464                 if (nr && remain <= 0)
1465                         break;
1466         }
1467         cfs_list_splice(&splice, lu_sites.prev);
1468         cfs_up(&lu_sites_guard);
1469
1470         cached = (cached / 100) * sysctl_vfs_cache_pressure;
1471         if (nr == 0)
1472                 CDEBUG(D_INODE, "%d objects cached\n", cached);
1473         return cached;
1474 }
1475
1476 /*
1477  * Debugging stuff.
1478  */
1479
1480 /**
1481  * Environment to be used in debugger, contains all tags.
1482  */
1483 struct lu_env lu_debugging_env;
1484
1485 /**
1486  * Debugging printer function using printk().
1487  */
1488 int lu_printk_printer(const struct lu_env *env,
1489                       void *unused, const char *format, ...)
1490 {
1491         va_list args;
1492
1493         va_start(args, format);
1494         vprintk(format, args);
1495         va_end(args);
1496         return 0;
1497 }
1498
1499 void lu_debugging_setup(void)
1500 {
1501         lu_env_init(&lu_debugging_env, ~0);
1502 }
1503
1504 void lu_context_keys_dump(void)
1505 {
1506         int i;
1507
1508         for (i = 0; i < ARRAY_SIZE(lu_keys); ++i) {
1509                 struct lu_context_key *key;
1510
1511                 key = lu_keys[i];
1512                 if (key != NULL) {
1513                         CERROR("[%i]: %p %x (%p,%p,%p) %i %i \"%s\"@%p\n",
1514                                i, key, key->lct_tags,
1515                                key->lct_init, key->lct_fini, key->lct_exit,
1516                                key->lct_index, cfs_atomic_read(&key->lct_used),
1517                                key->lct_owner ? key->lct_owner->name : "",
1518                                key->lct_owner);
1519                         lu_ref_print(&key->lct_reference);
1520                 }
1521         }
1522 }
1523 EXPORT_SYMBOL(lu_context_keys_dump);
1524 #else  /* !__KERNEL__ */
1525 static int lu_cache_shrink(int nr, unsigned int gfp_mask)
1526 {
1527         return 0;
1528 }
1529 #endif /* __KERNEL__ */
1530
1531 int  cl_global_init(void);
1532 void cl_global_fini(void);
1533 int  lu_ref_global_init(void);
1534 void lu_ref_global_fini(void);
1535
1536 int dt_global_init(void);
1537 void dt_global_fini(void);
1538
1539 int llo_global_init(void);
1540 void llo_global_fini(void);
1541
1542 /**
1543  * Initialization of global lu_* data.
1544  */
1545 int lu_global_init(void)
1546 {
1547         int result;
1548
1549         CDEBUG(D_CONSOLE, "Lustre LU module (%p).\n", &lu_keys);
1550
1551         result = lu_ref_global_init();
1552         if (result != 0)
1553                 return result;
1554
1555         LU_CONTEXT_KEY_INIT(&lu_global_key);
1556         result = lu_context_key_register(&lu_global_key);
1557         if (result != 0)
1558                 return result;
1559         /*
1560          * At this level, we don't know what tags are needed, so allocate them
1561          * conservatively. This should not be too bad, because this
1562          * environment is global.
1563          */
1564         cfs_down(&lu_sites_guard);
1565         result = lu_env_init(&lu_shrink_env, LCT_SHRINKER);
1566         cfs_up(&lu_sites_guard);
1567         if (result != 0)
1568                 return result;
1569
1570         /*
1571          * seeks estimation: 3 seeks to read a record from oi, one to read
1572          * inode, one for ea. Unfortunately setting this high value results in
1573          * lu_object/inode cache consuming all the memory.
1574          */
1575         lu_site_shrinker = cfs_set_shrinker(CFS_DEFAULT_SEEKS, lu_cache_shrink);
1576         if (lu_site_shrinker == NULL)
1577                 return -ENOMEM;
1578
1579         result = lu_time_global_init();
1580         if (result)
1581                 GOTO(out, result);
1582
1583 #ifdef __KERNEL__
1584         result = dt_global_init();
1585         if (result)
1586                 GOTO(out, result);
1587
1588         result = llo_global_init();
1589         if (result)
1590                 GOTO(out, result);
1591 #endif
1592         result = cl_global_init();
1593 out:
1594
1595         return result;
1596 }
1597
1598 /**
1599  * Dual to lu_global_init().
1600  */
1601 void lu_global_fini(void)
1602 {
1603         cl_global_fini();
1604 #ifdef __KERNEL__
1605         llo_global_fini();
1606         dt_global_fini();
1607 #endif
1608         lu_time_global_fini();
1609         if (lu_site_shrinker != NULL) {
1610                 cfs_remove_shrinker(lu_site_shrinker);
1611                 lu_site_shrinker = NULL;
1612         }
1613
1614         lu_context_key_degister(&lu_global_key);
1615
1616         /*
1617          * Tear shrinker environment down _after_ de-registering
1618          * lu_global_key, because the latter has a value in the former.
1619          */
1620         cfs_down(&lu_sites_guard);
1621         lu_env_fini(&lu_shrink_env);
1622         cfs_up(&lu_sites_guard);
1623
1624         lu_ref_global_fini();
1625 }
1626
1627 struct lu_buf LU_BUF_NULL = {
1628         .lb_buf = NULL,
1629         .lb_len = 0
1630 };
1631 EXPORT_SYMBOL(LU_BUF_NULL);
1632
1633 /**
1634  * Output site statistical counters into a buffer. Suitable for
1635  * lprocfs_rd_*()-style functions.
1636  */
1637 int lu_site_stats_print(const struct lu_site *s, char *page, int count)
1638 {
1639         int i;
1640         int populated;
1641
1642         /*
1643          * How many hash buckets are not-empty? Don't bother with locks: it's
1644          * an estimation anyway.
1645          */
1646         for (i = 0, populated = 0; i < s->ls_hash_size; i++)
1647                 populated += !cfs_hlist_empty(&s->ls_hash[i]);
1648
1649         return snprintf(page, count, "%d %d %d/%d %d %d %d %d %d %d %d\n",
1650                         s->ls_total,
1651                         s->ls_busy,
1652                         populated,
1653                         s->ls_hash_size,
1654                         s->ls_stats.s_created,
1655                         s->ls_stats.s_cache_hit,
1656                         s->ls_stats.s_cache_miss,
1657                         s->ls_stats.s_cache_check,
1658                         s->ls_stats.s_cache_race,
1659                         s->ls_stats.s_cache_death_race,
1660                         s->ls_stats.s_lru_purged);
1661 }
1662 EXPORT_SYMBOL(lu_site_stats_print);
1663
1664 const char *lu_time_names[LU_TIME_NR] = {
1665         [LU_TIME_FIND_LOOKUP] = "find_lookup",
1666         [LU_TIME_FIND_ALLOC]  = "find_alloc",
1667         [LU_TIME_FIND_INSERT] = "find_insert"
1668 };
1669 EXPORT_SYMBOL(lu_time_names);
1670
1671 /**
1672  * Helper function to initialize a number of kmem slab caches at once.
1673  */
1674 int lu_kmem_init(struct lu_kmem_descr *caches)
1675 {
1676         int result;
1677
1678         for (result = 0; caches->ckd_cache != NULL; ++caches) {
1679                 *caches->ckd_cache = cfs_mem_cache_create(caches->ckd_name,
1680                                                           caches->ckd_size,
1681                                                           0, 0);
1682                 if (*caches->ckd_cache == NULL) {
1683                         result = -ENOMEM;
1684                         break;
1685                 }
1686         }
1687         return result;
1688 }
1689 EXPORT_SYMBOL(lu_kmem_init);
1690
1691 /**
1692  * Helper function to finalize a number of kmem slab cached at once. Dual to
1693  * lu_kmem_init().
1694  */
1695 void lu_kmem_fini(struct lu_kmem_descr *caches)
1696 {
1697         int rc;
1698
1699         for (; caches->ckd_cache != NULL; ++caches) {
1700                 if (*caches->ckd_cache != NULL) {
1701                         rc = cfs_mem_cache_destroy(*caches->ckd_cache);
1702                         LASSERTF(rc == 0, "couldn't destroy %s slab\n",
1703                                  caches->ckd_name);
1704                         *caches->ckd_cache = NULL;
1705                 }
1706         }
1707 }
1708 EXPORT_SYMBOL(lu_kmem_fini);