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