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