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