Whamcloud - gitweb
LU-3059 obdclass: use a dummy structure for lu_ref_link
[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, 2013, 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 <lu_ref.h>
61 #include <libcfs/list.h>
62
63 static void lu_object_free(const struct lu_env *env, struct lu_object *o);
64
65 /**
66  * Decrease reference counter on object. If last reference is freed, return
67  * object to the cache, unless lu_object_is_dying(o) holds. In the latter
68  * case, free object immediately.
69  */
70 void lu_object_put(const struct lu_env *env, struct lu_object *o)
71 {
72         struct lu_site_bkt_data *bkt;
73         struct lu_object_header *top;
74         struct lu_site          *site;
75         struct lu_object        *orig;
76         cfs_hash_bd_t            bd;
77         const struct lu_fid     *fid;
78
79         top  = o->lo_header;
80         site = o->lo_dev->ld_site;
81         orig = o;
82
83         /*
84          * till we have full fids-on-OST implemented anonymous objects
85          * are possible in OSP. such an object isn't listed in the site
86          * so we should not remove it from the site.
87          */
88         fid = lu_object_fid(o);
89         if (fid_is_zero(fid)) {
90                 LASSERT(top->loh_hash.next == NULL
91                         && top->loh_hash.pprev == NULL);
92                 LASSERT(cfs_list_empty(&top->loh_lru));
93                 if (!cfs_atomic_dec_and_test(&top->loh_ref))
94                         return;
95                 cfs_list_for_each_entry_reverse(o, &top->loh_layers, lo_linkage) {
96                         if (o->lo_ops->loo_object_release != NULL)
97                                 o->lo_ops->loo_object_release(env, o);
98                 }
99                 lu_object_free(env, orig);
100                 return;
101         }
102
103         cfs_hash_bd_get(site->ls_obj_hash, &top->loh_fid, &bd);
104         bkt = cfs_hash_bd_extra_get(site->ls_obj_hash, &bd);
105
106         if (!cfs_hash_bd_dec_and_lock(site->ls_obj_hash, &bd, &top->loh_ref)) {
107                 if (lu_object_is_dying(top)) {
108
109                         /*
110                          * somebody may be waiting for this, currently only
111                          * used for cl_object, see cl_object_put_last().
112                          */
113                         cfs_waitq_broadcast(&bkt->lsb_marche_funebre);
114                 }
115                 return;
116         }
117
118         LASSERT(bkt->lsb_busy > 0);
119         bkt->lsb_busy--;
120         /*
121          * When last reference is released, iterate over object
122          * layers, and notify them that object is no longer busy.
123          */
124         cfs_list_for_each_entry_reverse(o, &top->loh_layers, lo_linkage) {
125                 if (o->lo_ops->loo_object_release != NULL)
126                         o->lo_ops->loo_object_release(env, o);
127         }
128
129         if (!lu_object_is_dying(top)) {
130                 LASSERT(cfs_list_empty(&top->loh_lru));
131                 cfs_list_add_tail(&top->loh_lru, &bkt->lsb_lru);
132                 cfs_hash_bd_unlock(site->ls_obj_hash, &bd, 1);
133                 return;
134         }
135
136         /*
137          * If object is dying (will not be cached), removed it
138          * from hash table and LRU.
139          *
140          * This is done with hash table and LRU lists locked. As the only
141          * way to acquire first reference to previously unreferenced
142          * object is through hash-table lookup (lu_object_find()),
143          * or LRU scanning (lu_site_purge()), that are done under hash-table
144          * and LRU lock, no race with concurrent object lookup is possible
145          * and we can safely destroy object below.
146          */
147         if (!test_and_set_bit(LU_OBJECT_UNHASHED, &top->loh_flags))
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, &o->lo_header->loh_flags);
165         return lu_object_put(env, o);
166 }
167 EXPORT_SYMBOL(lu_object_put_nocache);
168
169 /**
170  * Kill the object and take it out of LRU cache.
171  * Currently used by client code for layout change.
172  */
173 void lu_object_unhash(const struct lu_env *env, struct lu_object *o)
174 {
175         struct lu_object_header *top;
176
177         top = o->lo_header;
178         set_bit(LU_OBJECT_HEARD_BANSHEE, &top->loh_flags);
179         if (!test_and_set_bit(LU_OBJECT_UNHASHED, &top->loh_flags)) {
180                 cfs_hash_t *obj_hash = o->lo_dev->ld_site->ls_obj_hash;
181                 cfs_hash_bd_t bd;
182
183                 cfs_hash_bd_get_and_lock(obj_hash, &top->loh_fid, &bd, 1);
184                 cfs_list_del_init(&top->loh_lru);
185                 cfs_hash_bd_del_locked(obj_hash, &bd, &top->loh_hash);
186                 cfs_hash_bd_unlock(obj_hash, &bd, 1);
187         }
188 }
189 EXPORT_SYMBOL(lu_object_unhash);
190
191 /**
192  * Allocate new object.
193  *
194  * This follows object creation protocol, described in the comment within
195  * struct lu_device_operations definition.
196  */
197 static struct lu_object *lu_object_alloc(const struct lu_env *env,
198                                          struct lu_device *dev,
199                                          const struct lu_fid *f,
200                                          const struct lu_object_conf *conf)
201 {
202         struct lu_object *scan;
203         struct lu_object *top;
204         cfs_list_t *layers;
205         int clean;
206         int result;
207         ENTRY;
208
209         /*
210          * Create top-level object slice. This will also create
211          * lu_object_header.
212          */
213         top = dev->ld_ops->ldo_object_alloc(env, NULL, dev);
214         if (top == NULL)
215                 RETURN(ERR_PTR(-ENOMEM));
216         if (IS_ERR(top))
217                 RETURN(top);
218         /*
219          * This is the only place where object fid is assigned. It's constant
220          * after this point.
221          */
222         top->lo_header->loh_fid = *f;
223         layers = &top->lo_header->loh_layers;
224         do {
225                 /*
226                  * Call ->loo_object_init() repeatedly, until no more new
227                  * object slices are created.
228                  */
229                 clean = 1;
230                 cfs_list_for_each_entry(scan, layers, lo_linkage) {
231                         if (scan->lo_flags & LU_OBJECT_ALLOCATED)
232                                 continue;
233                         clean = 0;
234                         scan->lo_header = top->lo_header;
235                         result = scan->lo_ops->loo_object_init(env, scan, conf);
236                         if (result != 0) {
237                                 lu_object_free(env, top);
238                                 RETURN(ERR_PTR(result));
239                         }
240                         scan->lo_flags |= LU_OBJECT_ALLOCATED;
241                 }
242         } while (!clean);
243
244         cfs_list_for_each_entry_reverse(scan, layers, lo_linkage) {
245                 if (scan->lo_ops->loo_object_start != NULL) {
246                         result = scan->lo_ops->loo_object_start(env, scan);
247                         if (result != 0) {
248                                 lu_object_free(env, top);
249                                 RETURN(ERR_PTR(result));
250                         }
251                 }
252         }
253
254         lprocfs_counter_incr(dev->ld_site->ls_stats, LU_SS_CREATED);
255         RETURN(top);
256 }
257
258 /**
259  * Free an object.
260  */
261 static void lu_object_free(const struct lu_env *env, struct lu_object *o)
262 {
263         struct lu_site_bkt_data *bkt;
264         struct lu_site          *site;
265         struct lu_object        *scan;
266         cfs_list_t              *layers;
267         cfs_list_t               splice;
268
269         site   = o->lo_dev->ld_site;
270         layers = &o->lo_header->loh_layers;
271         bkt    = lu_site_bkt_from_fid(site, &o->lo_header->loh_fid);
272         /*
273          * First call ->loo_object_delete() method to release all resources.
274          */
275         cfs_list_for_each_entry_reverse(scan, layers, lo_linkage) {
276                 if (scan->lo_ops->loo_object_delete != NULL)
277                         scan->lo_ops->loo_object_delete(env, scan);
278         }
279
280         /*
281          * Then, splice object layers into stand-alone list, and call
282          * ->loo_object_free() on all layers to free memory. Splice is
283          * necessary, because lu_object_header is freed together with the
284          * top-level slice.
285          */
286         CFS_INIT_LIST_HEAD(&splice);
287         cfs_list_splice_init(layers, &splice);
288         while (!cfs_list_empty(&splice)) {
289                 /*
290                  * Free layers in bottom-to-top order, so that object header
291                  * lives as long as possible and ->loo_object_free() methods
292                  * can look at its contents.
293                  */
294                 o = container_of0(splice.prev, struct lu_object, lo_linkage);
295                 cfs_list_del_init(&o->lo_linkage);
296                 LASSERT(o->lo_ops->loo_object_free != NULL);
297                 o->lo_ops->loo_object_free(env, o);
298         }
299
300         if (cfs_waitq_active(&bkt->lsb_marche_funebre))
301                 cfs_waitq_broadcast(&bkt->lsb_marche_funebre);
302 }
303
304 /**
305  * Free \a nr objects from the cold end of the site LRU list.
306  */
307 int lu_site_purge(const struct lu_env *env, struct lu_site *s, int nr)
308 {
309         struct lu_object_header *h;
310         struct lu_object_header *temp;
311         struct lu_site_bkt_data *bkt;
312         cfs_hash_bd_t            bd;
313         cfs_hash_bd_t            bd2;
314         cfs_list_t               dispose;
315         int                      did_sth;
316         int                      start;
317         int                      count;
318         int                      bnr;
319         int                      i;
320
321         if (OBD_FAIL_CHECK(OBD_FAIL_OBD_NO_LRU))
322                 RETURN(0);
323
324         CFS_INIT_LIST_HEAD(&dispose);
325         /*
326          * Under LRU list lock, scan LRU list and move unreferenced objects to
327          * the dispose list, removing them from LRU and hash table.
328          */
329         start = s->ls_purge_start;
330         bnr = (nr == ~0) ? -1 : nr / CFS_HASH_NBKT(s->ls_obj_hash) + 1;
331  again:
332         did_sth = 0;
333         cfs_hash_for_each_bucket(s->ls_obj_hash, &bd, i) {
334                 if (i < start)
335                         continue;
336                 count = bnr;
337                 cfs_hash_bd_lock(s->ls_obj_hash, &bd, 1);
338                 bkt = cfs_hash_bd_extra_get(s->ls_obj_hash, &bd);
339
340                 cfs_list_for_each_entry_safe(h, temp, &bkt->lsb_lru, loh_lru) {
341                         LASSERT(cfs_atomic_read(&h->loh_ref) == 0);
342
343                         cfs_hash_bd_get(s->ls_obj_hash, &h->loh_fid, &bd2);
344                         LASSERT(bd.bd_bucket == bd2.bd_bucket);
345
346                         cfs_hash_bd_del_locked(s->ls_obj_hash,
347                                                &bd2, &h->loh_hash);
348                         cfs_list_move(&h->loh_lru, &dispose);
349                         if (did_sth == 0)
350                                 did_sth = 1;
351
352                         if (nr != ~0 && --nr == 0)
353                                 break;
354
355                         if (count > 0 && --count == 0)
356                                 break;
357
358                 }
359                 cfs_hash_bd_unlock(s->ls_obj_hash, &bd, 1);
360                 cfs_cond_resched();
361                 /*
362                  * Free everything on the dispose list. This is safe against
363                  * races due to the reasons described in lu_object_put().
364                  */
365                 while (!cfs_list_empty(&dispose)) {
366                         h = container_of0(dispose.next,
367                                           struct lu_object_header, loh_lru);
368                         cfs_list_del_init(&h->loh_lru);
369                         lu_object_free(env, lu_object_top(h));
370                         lprocfs_counter_incr(s->ls_stats, LU_SS_LRU_PURGED);
371                 }
372
373                 if (nr == 0)
374                         break;
375         }
376
377         if (nr != 0 && did_sth && start != 0) {
378                 start = 0; /* restart from the first bucket */
379                 goto again;
380         }
381         /* race on s->ls_purge_start, but nobody cares */
382         s->ls_purge_start = i % CFS_HASH_NBKT(s->ls_obj_hash);
383
384         return nr;
385 }
386 EXPORT_SYMBOL(lu_site_purge);
387
388 /*
389  * Object printing.
390  *
391  * Code below has to jump through certain loops to output object description
392  * into libcfs_debug_msg-based log. The problem is that lu_object_print()
393  * composes object description from strings that are parts of _lines_ of
394  * output (i.e., strings that are not terminated by newline). This doesn't fit
395  * very well into libcfs_debug_msg() interface that assumes that each message
396  * supplied to it is a self-contained output line.
397  *
398  * To work around this, strings are collected in a temporary buffer
399  * (implemented as a value of lu_cdebug_key key), until terminating newline
400  * character is detected.
401  *
402  */
403
404 enum {
405         /**
406          * Maximal line size.
407          *
408          * XXX overflow is not handled correctly.
409          */
410         LU_CDEBUG_LINE = 512
411 };
412
413 struct lu_cdebug_data {
414         /**
415          * Temporary buffer.
416          */
417         char lck_area[LU_CDEBUG_LINE];
418 };
419
420 /* context key constructor/destructor: lu_global_key_init, lu_global_key_fini */
421 LU_KEY_INIT_FINI(lu_global, struct lu_cdebug_data);
422
423 /**
424  * Key, holding temporary buffer. This key is registered very early by
425  * lu_global_init().
426  */
427 struct lu_context_key lu_global_key = {
428         .lct_tags = LCT_MD_THREAD | LCT_DT_THREAD |
429                     LCT_MG_THREAD | LCT_CL_THREAD,
430         .lct_init = lu_global_key_init,
431         .lct_fini = lu_global_key_fini
432 };
433
434 /**
435  * Printer function emitting messages through libcfs_debug_msg().
436  */
437 int lu_cdebug_printer(const struct lu_env *env,
438                       void *cookie, const char *format, ...)
439 {
440         struct libcfs_debug_msg_data *msgdata = cookie;
441         struct lu_cdebug_data        *key;
442         int used;
443         int complete;
444         va_list args;
445
446         va_start(args, format);
447
448         key = lu_context_key_get(&env->le_ctx, &lu_global_key);
449         LASSERT(key != NULL);
450
451         used = strlen(key->lck_area);
452         complete = format[strlen(format) - 1] == '\n';
453         /*
454          * Append new chunk to the buffer.
455          */
456         vsnprintf(key->lck_area + used,
457                   ARRAY_SIZE(key->lck_area) - used, format, args);
458         if (complete) {
459                 if (cfs_cdebug_show(msgdata->msg_mask, msgdata->msg_subsys))
460                         libcfs_debug_msg(msgdata, "%s", key->lck_area);
461                 key->lck_area[0] = 0;
462         }
463         va_end(args);
464         return 0;
465 }
466 EXPORT_SYMBOL(lu_cdebug_printer);
467
468 /**
469  * Print object header.
470  */
471 void lu_object_header_print(const struct lu_env *env, void *cookie,
472                             lu_printer_t printer,
473                             const struct lu_object_header *hdr)
474 {
475         (*printer)(env, cookie, "header@%p[%#lx, %d, "DFID"%s%s%s]",
476                    hdr, hdr->loh_flags, cfs_atomic_read(&hdr->loh_ref),
477                    PFID(&hdr->loh_fid),
478                    cfs_hlist_unhashed(&hdr->loh_hash) ? "" : " hash",
479                    cfs_list_empty((cfs_list_t *)&hdr->loh_lru) ? \
480                    "" : " lru",
481                    hdr->loh_attr & LOHA_EXISTS ? " exist":"");
482 }
483 EXPORT_SYMBOL(lu_object_header_print);
484
485 /**
486  * Print human readable representation of the \a o to the \a printer.
487  */
488 void lu_object_print(const struct lu_env *env, void *cookie,
489                      lu_printer_t printer, const struct lu_object *o)
490 {
491         static const char ruler[] = "........................................";
492         struct lu_object_header *top;
493         int depth;
494
495         top = o->lo_header;
496         lu_object_header_print(env, cookie, printer, top);
497         (*printer)(env, cookie, "{ \n");
498         cfs_list_for_each_entry(o, &top->loh_layers, lo_linkage) {
499                 depth = o->lo_depth + 4;
500
501                 /*
502                  * print `.' \a depth times followed by type name and address
503                  */
504                 (*printer)(env, cookie, "%*.*s%s@%p", depth, depth, ruler,
505                            o->lo_dev->ld_type->ldt_name, o);
506                 if (o->lo_ops->loo_object_print != NULL)
507                         o->lo_ops->loo_object_print(env, cookie, printer, o);
508                 (*printer)(env, cookie, "\n");
509         }
510         (*printer)(env, cookie, "} header@%p\n", top);
511 }
512 EXPORT_SYMBOL(lu_object_print);
513
514 /**
515  * Check object consistency.
516  */
517 int lu_object_invariant(const struct lu_object *o)
518 {
519         struct lu_object_header *top;
520
521         top = o->lo_header;
522         cfs_list_for_each_entry(o, &top->loh_layers, lo_linkage) {
523                 if (o->lo_ops->loo_object_invariant != NULL &&
524                     !o->lo_ops->loo_object_invariant(o))
525                         return 0;
526         }
527         return 1;
528 }
529 EXPORT_SYMBOL(lu_object_invariant);
530
531 static struct lu_object *htable_lookup(struct lu_site *s,
532                                        cfs_hash_bd_t *bd,
533                                        const struct lu_fid *f,
534                                        cfs_waitlink_t *waiter,
535                                        __u64 *version)
536 {
537         struct lu_site_bkt_data *bkt;
538         struct lu_object_header *h;
539         cfs_hlist_node_t        *hnode;
540         __u64  ver = cfs_hash_bd_version_get(bd);
541
542         if (*version == ver)
543                 return NULL;
544
545         *version = ver;
546         bkt = cfs_hash_bd_extra_get(s->ls_obj_hash, bd);
547         /* cfs_hash_bd_peek_locked is a somehow "internal" function
548          * of cfs_hash, it doesn't add refcount on object. */
549         hnode = cfs_hash_bd_peek_locked(s->ls_obj_hash, bd, (void *)f);
550         if (hnode == NULL) {
551                 lprocfs_counter_incr(s->ls_stats, LU_SS_CACHE_MISS);
552                 return NULL;
553         }
554
555         h = container_of0(hnode, struct lu_object_header, loh_hash);
556         if (likely(!lu_object_is_dying(h))) {
557                 cfs_hash_get(s->ls_obj_hash, hnode);
558                 lprocfs_counter_incr(s->ls_stats, LU_SS_CACHE_HIT);
559                 cfs_list_del_init(&h->loh_lru);
560                 return lu_object_top(h);
561         }
562
563         /*
564          * Lookup found an object being destroyed this object cannot be
565          * returned (to assure that references to dying objects are eventually
566          * drained), and moreover, lookup has to wait until object is freed.
567          */
568
569         cfs_waitlink_init(waiter);
570         cfs_waitq_add(&bkt->lsb_marche_funebre, waiter);
571         cfs_set_current_state(CFS_TASK_UNINT);
572         lprocfs_counter_incr(s->ls_stats, LU_SS_CACHE_DEATH_RACE);
573         return ERR_PTR(-EAGAIN);
574 }
575
576 /**
577  * Search cache for an object with the fid \a f. If such object is found,
578  * return it. Otherwise, create new object, insert it into cache and return
579  * it. In any case, additional reference is acquired on the returned object.
580  */
581 struct lu_object *lu_object_find(const struct lu_env *env,
582                                  struct lu_device *dev, const struct lu_fid *f,
583                                  const struct lu_object_conf *conf)
584 {
585         return lu_object_find_at(env, dev->ld_site->ls_top_dev, f, conf);
586 }
587 EXPORT_SYMBOL(lu_object_find);
588
589 static struct lu_object *lu_object_new(const struct lu_env *env,
590                                        struct lu_device *dev,
591                                        const struct lu_fid *f,
592                                        const struct lu_object_conf *conf)
593 {
594         struct lu_object        *o;
595         cfs_hash_t              *hs;
596         cfs_hash_bd_t            bd;
597         struct lu_site_bkt_data *bkt;
598
599         o = lu_object_alloc(env, dev, f, conf);
600         if (unlikely(IS_ERR(o)))
601                 return o;
602
603         hs = dev->ld_site->ls_obj_hash;
604         cfs_hash_bd_get_and_lock(hs, (void *)f, &bd, 1);
605         bkt = cfs_hash_bd_extra_get(hs, &bd);
606         cfs_hash_bd_add_locked(hs, &bd, &o->lo_header->loh_hash);
607         bkt->lsb_busy++;
608         cfs_hash_bd_unlock(hs, &bd, 1);
609         return o;
610 }
611
612 /**
613  * Core logic of lu_object_find*() functions.
614  */
615 static struct lu_object *lu_object_find_try(const struct lu_env *env,
616                                             struct lu_device *dev,
617                                             const struct lu_fid *f,
618                                             const struct lu_object_conf *conf,
619                                             cfs_waitlink_t *waiter)
620 {
621         struct lu_object      *o;
622         struct lu_object      *shadow;
623         struct lu_site        *s;
624         cfs_hash_t            *hs;
625         cfs_hash_bd_t          bd;
626         __u64                  version = 0;
627
628         /*
629          * This uses standard index maintenance protocol:
630          *
631          *     - search index under lock, and return object if found;
632          *     - otherwise, unlock index, allocate new object;
633          *     - lock index and search again;
634          *     - if nothing is found (usual case), insert newly created
635          *       object into index;
636          *     - otherwise (race: other thread inserted object), free
637          *       object just allocated.
638          *     - unlock index;
639          *     - return object.
640          *
641          * For "LOC_F_NEW" case, we are sure the object is new established.
642          * It is unnecessary to perform lookup-alloc-lookup-insert, instead,
643          * just alloc and insert directly.
644          *
645          * If dying object is found during index search, add @waiter to the
646          * site wait-queue and return ERR_PTR(-EAGAIN).
647          */
648         if (conf != NULL && conf->loc_flags & LOC_F_NEW)
649                 return lu_object_new(env, dev, f, conf);
650
651         s  = dev->ld_site;
652         hs = s->ls_obj_hash;
653         cfs_hash_bd_get_and_lock(hs, (void *)f, &bd, 1);
654         o = htable_lookup(s, &bd, f, waiter, &version);
655         cfs_hash_bd_unlock(hs, &bd, 1);
656         if (o != NULL)
657                 return o;
658
659         /*
660          * Allocate new object. This may result in rather complicated
661          * operations, including fld queries, inode loading, etc.
662          */
663         o = lu_object_alloc(env, dev, f, conf);
664         if (unlikely(IS_ERR(o)))
665                 return o;
666
667         LASSERT(lu_fid_eq(lu_object_fid(o), f));
668
669         cfs_hash_bd_lock(hs, &bd, 1);
670
671         shadow = htable_lookup(s, &bd, f, waiter, &version);
672         if (likely(shadow == NULL)) {
673                 struct lu_site_bkt_data *bkt;
674
675                 bkt = cfs_hash_bd_extra_get(hs, &bd);
676                 cfs_hash_bd_add_locked(hs, &bd, &o->lo_header->loh_hash);
677                 bkt->lsb_busy++;
678                 cfs_hash_bd_unlock(hs, &bd, 1);
679                 return o;
680         }
681
682         lprocfs_counter_incr(s->ls_stats, LU_SS_CACHE_RACE);
683         cfs_hash_bd_unlock(hs, &bd, 1);
684         lu_object_free(env, o);
685         return shadow;
686 }
687
688 /**
689  * Much like lu_object_find(), but top level device of object is specifically
690  * \a dev rather than top level device of the site. This interface allows
691  * objects of different "stacking" to be created within the same site.
692  */
693 struct lu_object *lu_object_find_at(const struct lu_env *env,
694                                     struct lu_device *dev,
695                                     const struct lu_fid *f,
696                                     const struct lu_object_conf *conf)
697 {
698         struct lu_site_bkt_data *bkt;
699         struct lu_object        *obj;
700         cfs_waitlink_t           wait;
701
702         while (1) {
703                 obj = lu_object_find_try(env, dev, f, conf, &wait);
704                 if (obj != ERR_PTR(-EAGAIN))
705                         return obj;
706                 /*
707                  * lu_object_find_try() already added waiter into the
708                  * wait queue.
709                  */
710                 cfs_waitq_wait(&wait, CFS_TASK_UNINT);
711                 bkt = lu_site_bkt_from_fid(dev->ld_site, (void *)f);
712                 cfs_waitq_del(&bkt->lsb_marche_funebre, &wait);
713         }
714 }
715 EXPORT_SYMBOL(lu_object_find_at);
716
717 /**
718  * Find object with given fid, and return its slice belonging to given device.
719  */
720 struct lu_object *lu_object_find_slice(const struct lu_env *env,
721                                        struct lu_device *dev,
722                                        const struct lu_fid *f,
723                                        const struct lu_object_conf *conf)
724 {
725         struct lu_object *top;
726         struct lu_object *obj;
727
728         top = lu_object_find(env, dev, f, conf);
729         if (!IS_ERR(top)) {
730                 obj = lu_object_locate(top->lo_header, dev->ld_type);
731                 if (obj == NULL)
732                         lu_object_put(env, top);
733         } else
734                 obj = top;
735         return obj;
736 }
737 EXPORT_SYMBOL(lu_object_find_slice);
738
739 /**
740  * Global list of all device types.
741  */
742 static CFS_LIST_HEAD(lu_device_types);
743
744 int lu_device_type_init(struct lu_device_type *ldt)
745 {
746         int result = 0;
747
748         CFS_INIT_LIST_HEAD(&ldt->ldt_linkage);
749         if (ldt->ldt_ops->ldto_init)
750                 result = ldt->ldt_ops->ldto_init(ldt);
751         if (result == 0)
752                 cfs_list_add(&ldt->ldt_linkage, &lu_device_types);
753         return result;
754 }
755 EXPORT_SYMBOL(lu_device_type_init);
756
757 void lu_device_type_fini(struct lu_device_type *ldt)
758 {
759         cfs_list_del_init(&ldt->ldt_linkage);
760         if (ldt->ldt_ops->ldto_fini)
761                 ldt->ldt_ops->ldto_fini(ldt);
762 }
763 EXPORT_SYMBOL(lu_device_type_fini);
764
765 void lu_types_stop(void)
766 {
767         struct lu_device_type *ldt;
768
769         cfs_list_for_each_entry(ldt, &lu_device_types, ldt_linkage) {
770                 if (ldt->ldt_device_nr == 0 && ldt->ldt_ops->ldto_stop)
771                         ldt->ldt_ops->ldto_stop(ldt);
772         }
773 }
774 EXPORT_SYMBOL(lu_types_stop);
775
776 /**
777  * Global list of all sites on this node
778  */
779 static CFS_LIST_HEAD(lu_sites);
780 static DEFINE_MUTEX(lu_sites_guard);
781
782 /**
783  * Global environment used by site shrinker.
784  */
785 static struct lu_env lu_shrink_env;
786
787 struct lu_site_print_arg {
788         struct lu_env   *lsp_env;
789         void            *lsp_cookie;
790         lu_printer_t     lsp_printer;
791 };
792
793 static int
794 lu_site_obj_print(cfs_hash_t *hs, cfs_hash_bd_t *bd,
795                   cfs_hlist_node_t *hnode, void *data)
796 {
797         struct lu_site_print_arg *arg = (struct lu_site_print_arg *)data;
798         struct lu_object_header  *h;
799
800         h = cfs_hlist_entry(hnode, struct lu_object_header, loh_hash);
801         if (!cfs_list_empty(&h->loh_layers)) {
802                 const struct lu_object *o;
803
804                 o = lu_object_top(h);
805                 lu_object_print(arg->lsp_env, arg->lsp_cookie,
806                                 arg->lsp_printer, o);
807         } else {
808                 lu_object_header_print(arg->lsp_env, arg->lsp_cookie,
809                                        arg->lsp_printer, h);
810         }
811         return 0;
812 }
813
814 /**
815  * Print all objects in \a s.
816  */
817 void lu_site_print(const struct lu_env *env, struct lu_site *s, void *cookie,
818                    lu_printer_t printer)
819 {
820         struct lu_site_print_arg arg = {
821                 .lsp_env     = (struct lu_env *)env,
822                 .lsp_cookie  = cookie,
823                 .lsp_printer = printer,
824         };
825
826         cfs_hash_for_each(s->ls_obj_hash, lu_site_obj_print, &arg);
827 }
828 EXPORT_SYMBOL(lu_site_print);
829
830 enum {
831         LU_CACHE_PERCENT_MAX     = 50,
832         LU_CACHE_PERCENT_DEFAULT = 20
833 };
834
835 static unsigned int lu_cache_percent = LU_CACHE_PERCENT_DEFAULT;
836 CFS_MODULE_PARM(lu_cache_percent, "i", int, 0644,
837                 "Percentage of memory to be used as lu_object cache");
838
839 /**
840  * Return desired hash table order.
841  */
842 static int lu_htable_order(void)
843 {
844         unsigned long cache_size;
845         int bits;
846
847         /*
848          * Calculate hash table size, assuming that we want reasonable
849          * performance when 20% of total memory is occupied by cache of
850          * lu_objects.
851          *
852          * Size of lu_object is (arbitrary) taken as 1K (together with inode).
853          */
854         cache_size = cfs_num_physpages;
855
856 #if BITS_PER_LONG == 32
857         /* limit hashtable size for lowmem systems to low RAM */
858         if (cache_size > 1 << (30 - CFS_PAGE_SHIFT))
859                 cache_size = 1 << (30 - CFS_PAGE_SHIFT) * 3 / 4;
860 #endif
861
862         /* clear off unreasonable cache setting. */
863         if (lu_cache_percent == 0 || lu_cache_percent > LU_CACHE_PERCENT_MAX) {
864                 CWARN("obdclass: invalid lu_cache_percent: %u, it must be in"
865                       " the range of (0, %u]. Will use default value: %u.\n",
866                       lu_cache_percent, LU_CACHE_PERCENT_MAX,
867                       LU_CACHE_PERCENT_DEFAULT);
868
869                 lu_cache_percent = LU_CACHE_PERCENT_DEFAULT;
870         }
871         cache_size = cache_size / 100 * lu_cache_percent *
872                 (CFS_PAGE_SIZE / 1024);
873
874         for (bits = 1; (1 << bits) < cache_size; ++bits) {
875                 ;
876         }
877         return bits;
878 }
879
880 static unsigned lu_obj_hop_hash(cfs_hash_t *hs,
881                                 const void *key, unsigned mask)
882 {
883         struct lu_fid  *fid = (struct lu_fid *)key;
884         __u32           hash;
885
886         hash = fid_flatten32(fid);
887         hash += (hash >> 4) + (hash << 12); /* mixing oid and seq */
888         hash = cfs_hash_long(hash, hs->hs_bkt_bits);
889
890         /* give me another random factor */
891         hash -= cfs_hash_long((unsigned long)hs, fid_oid(fid) % 11 + 3);
892
893         hash <<= hs->hs_cur_bits - hs->hs_bkt_bits;
894         hash |= (fid_seq(fid) + fid_oid(fid)) & (CFS_HASH_NBKT(hs) - 1);
895
896         return hash & mask;
897 }
898
899 static void *lu_obj_hop_object(cfs_hlist_node_t *hnode)
900 {
901         return cfs_hlist_entry(hnode, struct lu_object_header, loh_hash);
902 }
903
904 static void *lu_obj_hop_key(cfs_hlist_node_t *hnode)
905 {
906         struct lu_object_header *h;
907
908         h = cfs_hlist_entry(hnode, struct lu_object_header, loh_hash);
909         return &h->loh_fid;
910 }
911
912 static int lu_obj_hop_keycmp(const void *key, cfs_hlist_node_t *hnode)
913 {
914         struct lu_object_header *h;
915
916         h = cfs_hlist_entry(hnode, struct lu_object_header, loh_hash);
917         return lu_fid_eq(&h->loh_fid, (struct lu_fid *)key);
918 }
919
920 static void lu_obj_hop_get(cfs_hash_t *hs, cfs_hlist_node_t *hnode)
921 {
922         struct lu_object_header *h;
923
924         h = cfs_hlist_entry(hnode, struct lu_object_header, loh_hash);
925         if (cfs_atomic_add_return(1, &h->loh_ref) == 1) {
926                 struct lu_site_bkt_data *bkt;
927                 cfs_hash_bd_t            bd;
928
929                 cfs_hash_bd_get(hs, &h->loh_fid, &bd);
930                 bkt = cfs_hash_bd_extra_get(hs, &bd);
931                 bkt->lsb_busy++;
932         }
933 }
934
935 static void lu_obj_hop_put_locked(cfs_hash_t *hs, cfs_hlist_node_t *hnode)
936 {
937         LBUG(); /* we should never called it */
938 }
939
940 cfs_hash_ops_t lu_site_hash_ops = {
941         .hs_hash        = lu_obj_hop_hash,
942         .hs_key         = lu_obj_hop_key,
943         .hs_keycmp      = lu_obj_hop_keycmp,
944         .hs_object      = lu_obj_hop_object,
945         .hs_get         = lu_obj_hop_get,
946         .hs_put_locked  = lu_obj_hop_put_locked,
947 };
948
949 void lu_dev_add_linkage(struct lu_site *s, struct lu_device *d)
950 {
951         spin_lock(&s->ls_ld_lock);
952         if (cfs_list_empty(&d->ld_linkage))
953                 cfs_list_add(&d->ld_linkage, &s->ls_ld_linkage);
954         spin_unlock(&s->ls_ld_lock);
955 }
956 EXPORT_SYMBOL(lu_dev_add_linkage);
957
958 void lu_dev_del_linkage(struct lu_site *s, struct lu_device *d)
959 {
960         spin_lock(&s->ls_ld_lock);
961         cfs_list_del_init(&d->ld_linkage);
962         spin_unlock(&s->ls_ld_lock);
963 }
964 EXPORT_SYMBOL(lu_dev_del_linkage);
965
966 /**
967  * Initialize site \a s, with \a d as the top level device.
968  */
969 #define LU_SITE_BITS_MIN    12
970 #define LU_SITE_BITS_MAX    24
971 /**
972  * total 256 buckets, we don't want too many buckets because:
973  * - consume too much memory
974  * - avoid unbalanced LRU list
975  */
976 #define LU_SITE_BKT_BITS    8
977
978 int lu_site_init(struct lu_site *s, struct lu_device *top)
979 {
980         struct lu_site_bkt_data *bkt;
981         cfs_hash_bd_t bd;
982         char name[16];
983         int bits;
984         int i;
985         ENTRY;
986
987         memset(s, 0, sizeof *s);
988         bits = lu_htable_order();
989         snprintf(name, 16, "lu_site_%s", top->ld_type->ldt_name);
990         for (bits = min(max(LU_SITE_BITS_MIN, bits), LU_SITE_BITS_MAX);
991              bits >= LU_SITE_BITS_MIN; bits--) {
992                 s->ls_obj_hash = cfs_hash_create(name, bits, bits,
993                                                  bits - LU_SITE_BKT_BITS,
994                                                  sizeof(*bkt), 0, 0,
995                                                  &lu_site_hash_ops,
996                                                  CFS_HASH_SPIN_BKTLOCK |
997                                                  CFS_HASH_NO_ITEMREF |
998                                                  CFS_HASH_DEPTH |
999                                                  CFS_HASH_ASSERT_EMPTY);
1000                 if (s->ls_obj_hash != NULL)
1001                         break;
1002         }
1003
1004         if (s->ls_obj_hash == NULL) {
1005                 CERROR("failed to create lu_site hash with bits: %d\n", bits);
1006                 return -ENOMEM;
1007         }
1008
1009         cfs_hash_for_each_bucket(s->ls_obj_hash, &bd, i) {
1010                 bkt = cfs_hash_bd_extra_get(s->ls_obj_hash, &bd);
1011                 CFS_INIT_LIST_HEAD(&bkt->lsb_lru);
1012                 cfs_waitq_init(&bkt->lsb_marche_funebre);
1013         }
1014
1015         s->ls_stats = lprocfs_alloc_stats(LU_SS_LAST_STAT, 0);
1016         if (s->ls_stats == NULL) {
1017                 cfs_hash_putref(s->ls_obj_hash);
1018                 s->ls_obj_hash = NULL;
1019                 return -ENOMEM;
1020         }
1021
1022         lprocfs_counter_init(s->ls_stats, LU_SS_CREATED,
1023                              0, "created", "created");
1024         lprocfs_counter_init(s->ls_stats, LU_SS_CACHE_HIT,
1025                              0, "cache_hit", "cache_hit");
1026         lprocfs_counter_init(s->ls_stats, LU_SS_CACHE_MISS,
1027                              0, "cache_miss", "cache_miss");
1028         lprocfs_counter_init(s->ls_stats, LU_SS_CACHE_RACE,
1029                              0, "cache_race", "cache_race");
1030         lprocfs_counter_init(s->ls_stats, LU_SS_CACHE_DEATH_RACE,
1031                              0, "cache_death_race", "cache_death_race");
1032         lprocfs_counter_init(s->ls_stats, LU_SS_LRU_PURGED,
1033                              0, "lru_purged", "lru_purged");
1034
1035         CFS_INIT_LIST_HEAD(&s->ls_linkage);
1036         s->ls_top_dev = top;
1037         top->ld_site = s;
1038         lu_device_get(top);
1039         lu_ref_add(&top->ld_reference, "site-top", s);
1040
1041         CFS_INIT_LIST_HEAD(&s->ls_ld_linkage);
1042         spin_lock_init(&s->ls_ld_lock);
1043
1044         lu_dev_add_linkage(s, top);
1045
1046         RETURN(0);
1047 }
1048 EXPORT_SYMBOL(lu_site_init);
1049
1050 /**
1051  * Finalize \a s and release its resources.
1052  */
1053 void lu_site_fini(struct lu_site *s)
1054 {
1055         mutex_lock(&lu_sites_guard);
1056         cfs_list_del_init(&s->ls_linkage);
1057         mutex_unlock(&lu_sites_guard);
1058
1059         if (s->ls_obj_hash != NULL) {
1060                 cfs_hash_putref(s->ls_obj_hash);
1061                 s->ls_obj_hash = NULL;
1062         }
1063
1064         if (s->ls_top_dev != NULL) {
1065                 s->ls_top_dev->ld_site = NULL;
1066                 lu_ref_del(&s->ls_top_dev->ld_reference, "site-top", s);
1067                 lu_device_put(s->ls_top_dev);
1068                 s->ls_top_dev = NULL;
1069         }
1070
1071         if (s->ls_stats != NULL)
1072                 lprocfs_free_stats(&s->ls_stats);
1073 }
1074 EXPORT_SYMBOL(lu_site_fini);
1075
1076 /**
1077  * Called when initialization of stack for this site is completed.
1078  */
1079 int lu_site_init_finish(struct lu_site *s)
1080 {
1081         int result;
1082         mutex_lock(&lu_sites_guard);
1083         result = lu_context_refill(&lu_shrink_env.le_ctx);
1084         if (result == 0)
1085                 cfs_list_add(&s->ls_linkage, &lu_sites);
1086         mutex_unlock(&lu_sites_guard);
1087         return result;
1088 }
1089 EXPORT_SYMBOL(lu_site_init_finish);
1090
1091 /**
1092  * Acquire additional reference on device \a d
1093  */
1094 void lu_device_get(struct lu_device *d)
1095 {
1096         cfs_atomic_inc(&d->ld_ref);
1097 }
1098 EXPORT_SYMBOL(lu_device_get);
1099
1100 /**
1101  * Release reference on device \a d.
1102  */
1103 void lu_device_put(struct lu_device *d)
1104 {
1105         LASSERT(cfs_atomic_read(&d->ld_ref) > 0);
1106         cfs_atomic_dec(&d->ld_ref);
1107 }
1108 EXPORT_SYMBOL(lu_device_put);
1109
1110 /**
1111  * Initialize device \a d of type \a t.
1112  */
1113 int lu_device_init(struct lu_device *d, struct lu_device_type *t)
1114 {
1115         if (t->ldt_device_nr++ == 0 && t->ldt_ops->ldto_start != NULL)
1116                 t->ldt_ops->ldto_start(t);
1117         memset(d, 0, sizeof *d);
1118         cfs_atomic_set(&d->ld_ref, 0);
1119         d->ld_type = t;
1120         lu_ref_init(&d->ld_reference);
1121         CFS_INIT_LIST_HEAD(&d->ld_linkage);
1122         return 0;
1123 }
1124 EXPORT_SYMBOL(lu_device_init);
1125
1126 /**
1127  * Finalize device \a d.
1128  */
1129 void lu_device_fini(struct lu_device *d)
1130 {
1131         struct lu_device_type *t;
1132
1133         t = d->ld_type;
1134         if (d->ld_obd != NULL) {
1135                 d->ld_obd->obd_lu_dev = NULL;
1136                 d->ld_obd = NULL;
1137         }
1138
1139         lu_ref_fini(&d->ld_reference);
1140         LASSERTF(cfs_atomic_read(&d->ld_ref) == 0,
1141                  "Refcount is %u\n", cfs_atomic_read(&d->ld_ref));
1142         LASSERT(t->ldt_device_nr > 0);
1143         if (--t->ldt_device_nr == 0 && t->ldt_ops->ldto_stop != NULL)
1144                 t->ldt_ops->ldto_stop(t);
1145 }
1146 EXPORT_SYMBOL(lu_device_fini);
1147
1148 /**
1149  * Initialize object \a o that is part of compound object \a h and was created
1150  * by device \a d.
1151  */
1152 int lu_object_init(struct lu_object *o, struct lu_object_header *h,
1153                    struct lu_device *d)
1154 {
1155         memset(o, 0, sizeof(*o));
1156         o->lo_header = h;
1157         o->lo_dev = d;
1158         lu_device_get(d);
1159         lu_ref_add_at(&d->ld_reference, &o->lo_dev_ref, "lu_object", o);
1160         CFS_INIT_LIST_HEAD(&o->lo_linkage);
1161
1162         return 0;
1163 }
1164 EXPORT_SYMBOL(lu_object_init);
1165
1166 /**
1167  * Finalize object and release its resources.
1168  */
1169 void lu_object_fini(struct lu_object *o)
1170 {
1171         struct lu_device *dev = o->lo_dev;
1172
1173         LASSERT(cfs_list_empty(&o->lo_linkage));
1174
1175         if (dev != NULL) {
1176                 lu_ref_del_at(&dev->ld_reference, &o->lo_dev_ref,
1177                               "lu_object", o);
1178                 lu_device_put(dev);
1179                 o->lo_dev = NULL;
1180         }
1181 }
1182 EXPORT_SYMBOL(lu_object_fini);
1183
1184 /**
1185  * Add object \a o as first layer of compound object \a h
1186  *
1187  * This is typically called by the ->ldo_object_alloc() method of top-level
1188  * device.
1189  */
1190 void lu_object_add_top(struct lu_object_header *h, struct lu_object *o)
1191 {
1192         cfs_list_move(&o->lo_linkage, &h->loh_layers);
1193 }
1194 EXPORT_SYMBOL(lu_object_add_top);
1195
1196 /**
1197  * Add object \a o as a layer of compound object, going after \a before.
1198  *
1199  * This is typically called by the ->ldo_object_alloc() method of \a
1200  * before->lo_dev.
1201  */
1202 void lu_object_add(struct lu_object *before, struct lu_object *o)
1203 {
1204         cfs_list_move(&o->lo_linkage, &before->lo_linkage);
1205 }
1206 EXPORT_SYMBOL(lu_object_add);
1207
1208 /**
1209  * Initialize compound object.
1210  */
1211 int lu_object_header_init(struct lu_object_header *h)
1212 {
1213         memset(h, 0, sizeof *h);
1214         cfs_atomic_set(&h->loh_ref, 1);
1215         CFS_INIT_HLIST_NODE(&h->loh_hash);
1216         CFS_INIT_LIST_HEAD(&h->loh_lru);
1217         CFS_INIT_LIST_HEAD(&h->loh_layers);
1218         lu_ref_init(&h->loh_reference);
1219         return 0;
1220 }
1221 EXPORT_SYMBOL(lu_object_header_init);
1222
1223 /**
1224  * Finalize compound object.
1225  */
1226 void lu_object_header_fini(struct lu_object_header *h)
1227 {
1228         LASSERT(cfs_list_empty(&h->loh_layers));
1229         LASSERT(cfs_list_empty(&h->loh_lru));
1230         LASSERT(cfs_hlist_unhashed(&h->loh_hash));
1231         lu_ref_fini(&h->loh_reference);
1232 }
1233 EXPORT_SYMBOL(lu_object_header_fini);
1234
1235 /**
1236  * Given a compound object, find its slice, corresponding to the device type
1237  * \a dtype.
1238  */
1239 struct lu_object *lu_object_locate(struct lu_object_header *h,
1240                                    const struct lu_device_type *dtype)
1241 {
1242         struct lu_object *o;
1243
1244         cfs_list_for_each_entry(o, &h->loh_layers, lo_linkage) {
1245                 if (o->lo_dev->ld_type == dtype)
1246                         return o;
1247         }
1248         return NULL;
1249 }
1250 EXPORT_SYMBOL(lu_object_locate);
1251
1252
1253
1254 /**
1255  * Finalize and free devices in the device stack.
1256  *
1257  * Finalize device stack by purging object cache, and calling
1258  * lu_device_type_operations::ldto_device_fini() and
1259  * lu_device_type_operations::ldto_device_free() on all devices in the stack.
1260  */
1261 void lu_stack_fini(const struct lu_env *env, struct lu_device *top)
1262 {
1263         struct lu_site   *site = top->ld_site;
1264         struct lu_device *scan;
1265         struct lu_device *next;
1266
1267         lu_site_purge(env, site, ~0);
1268         for (scan = top; scan != NULL; scan = next) {
1269                 next = scan->ld_type->ldt_ops->ldto_device_fini(env, scan);
1270                 lu_ref_del(&scan->ld_reference, "lu-stack", &lu_site_init);
1271                 lu_device_put(scan);
1272         }
1273
1274         /* purge again. */
1275         lu_site_purge(env, site, ~0);
1276
1277         for (scan = top; scan != NULL; scan = next) {
1278                 const struct lu_device_type *ldt = scan->ld_type;
1279                 struct obd_type             *type;
1280
1281                 next = ldt->ldt_ops->ldto_device_free(env, scan);
1282                 type = ldt->ldt_obd_type;
1283                 if (type != NULL) {
1284                         type->typ_refcnt--;
1285                         class_put_type(type);
1286                 }
1287         }
1288 }
1289 EXPORT_SYMBOL(lu_stack_fini);
1290
1291 enum {
1292         /**
1293          * Maximal number of tld slots.
1294          */
1295         LU_CONTEXT_KEY_NR = 40
1296 };
1297
1298 static struct lu_context_key *lu_keys[LU_CONTEXT_KEY_NR] = { NULL, };
1299
1300 static DEFINE_SPINLOCK(lu_keys_guard);
1301
1302 /**
1303  * Global counter incremented whenever key is registered, unregistered,
1304  * revived or quiesced. This is used to void unnecessary calls to
1305  * lu_context_refill(). No locking is provided, as initialization and shutdown
1306  * are supposed to be externally serialized.
1307  */
1308 static unsigned key_set_version = 0;
1309
1310 /**
1311  * Register new key.
1312  */
1313 int lu_context_key_register(struct lu_context_key *key)
1314 {
1315         int result;
1316         int i;
1317
1318         LASSERT(key->lct_init != NULL);
1319         LASSERT(key->lct_fini != NULL);
1320         LASSERT(key->lct_tags != 0);
1321         LASSERT(key->lct_owner != NULL);
1322
1323         result = -ENFILE;
1324         spin_lock(&lu_keys_guard);
1325         for (i = 0; i < ARRAY_SIZE(lu_keys); ++i) {
1326                 if (lu_keys[i] == NULL) {
1327                         key->lct_index = i;
1328                         cfs_atomic_set(&key->lct_used, 1);
1329                         lu_keys[i] = key;
1330                         lu_ref_init(&key->lct_reference);
1331                         result = 0;
1332                         ++key_set_version;
1333                         break;
1334                 }
1335         }
1336         spin_unlock(&lu_keys_guard);
1337         return result;
1338 }
1339 EXPORT_SYMBOL(lu_context_key_register);
1340
1341 static void key_fini(struct lu_context *ctx, int index)
1342 {
1343         if (ctx->lc_value != NULL && ctx->lc_value[index] != NULL) {
1344                 struct lu_context_key *key;
1345
1346                 key = lu_keys[index];
1347                 LASSERT(key != NULL);
1348                 LASSERT(key->lct_fini != NULL);
1349                 LASSERT(cfs_atomic_read(&key->lct_used) > 1);
1350
1351                 key->lct_fini(ctx, key, ctx->lc_value[index]);
1352                 lu_ref_del(&key->lct_reference, "ctx", ctx);
1353                 cfs_atomic_dec(&key->lct_used);
1354
1355                 LASSERT(key->lct_owner != NULL);
1356                 if ((ctx->lc_tags & LCT_NOREF) == 0) {
1357                         LINVRNT(cfs_module_refcount(key->lct_owner) > 0);
1358                         cfs_module_put(key->lct_owner);
1359                 }
1360                 ctx->lc_value[index] = NULL;
1361         }
1362 }
1363
1364 /**
1365  * Deregister key.
1366  */
1367 void lu_context_key_degister(struct lu_context_key *key)
1368 {
1369         LASSERT(cfs_atomic_read(&key->lct_used) >= 1);
1370         LINVRNT(0 <= key->lct_index && key->lct_index < ARRAY_SIZE(lu_keys));
1371
1372         lu_context_key_quiesce(key);
1373
1374         ++key_set_version;
1375         spin_lock(&lu_keys_guard);
1376         key_fini(&lu_shrink_env.le_ctx, key->lct_index);
1377         if (lu_keys[key->lct_index]) {
1378                 lu_keys[key->lct_index] = NULL;
1379                 lu_ref_fini(&key->lct_reference);
1380         }
1381         spin_unlock(&lu_keys_guard);
1382
1383         LASSERTF(cfs_atomic_read(&key->lct_used) == 1,
1384                  "key has instances: %d\n",
1385                  cfs_atomic_read(&key->lct_used));
1386 }
1387 EXPORT_SYMBOL(lu_context_key_degister);
1388
1389 /**
1390  * Register a number of keys. This has to be called after all keys have been
1391  * initialized by a call to LU_CONTEXT_KEY_INIT().
1392  */
1393 int lu_context_key_register_many(struct lu_context_key *k, ...)
1394 {
1395         struct lu_context_key *key = k;
1396         va_list args;
1397         int result;
1398
1399         va_start(args, k);
1400         do {
1401                 result = lu_context_key_register(key);
1402                 if (result)
1403                         break;
1404                 key = va_arg(args, struct lu_context_key *);
1405         } while (key != NULL);
1406         va_end(args);
1407
1408         if (result != 0) {
1409                 va_start(args, k);
1410                 while (k != key) {
1411                         lu_context_key_degister(k);
1412                         k = va_arg(args, struct lu_context_key *);
1413                 }
1414                 va_end(args);
1415         }
1416
1417         return result;
1418 }
1419 EXPORT_SYMBOL(lu_context_key_register_many);
1420
1421 /**
1422  * De-register a number of keys. This is a dual to
1423  * lu_context_key_register_many().
1424  */
1425 void lu_context_key_degister_many(struct lu_context_key *k, ...)
1426 {
1427         va_list args;
1428
1429         va_start(args, k);
1430         do {
1431                 lu_context_key_degister(k);
1432                 k = va_arg(args, struct lu_context_key*);
1433         } while (k != NULL);
1434         va_end(args);
1435 }
1436 EXPORT_SYMBOL(lu_context_key_degister_many);
1437
1438 /**
1439  * Revive a number of keys.
1440  */
1441 void lu_context_key_revive_many(struct lu_context_key *k, ...)
1442 {
1443         va_list args;
1444
1445         va_start(args, k);
1446         do {
1447                 lu_context_key_revive(k);
1448                 k = va_arg(args, struct lu_context_key*);
1449         } while (k != NULL);
1450         va_end(args);
1451 }
1452 EXPORT_SYMBOL(lu_context_key_revive_many);
1453
1454 /**
1455  * Quiescent a number of keys.
1456  */
1457 void lu_context_key_quiesce_many(struct lu_context_key *k, ...)
1458 {
1459         va_list args;
1460
1461         va_start(args, k);
1462         do {
1463                 lu_context_key_quiesce(k);
1464                 k = va_arg(args, struct lu_context_key*);
1465         } while (k != NULL);
1466         va_end(args);
1467 }
1468 EXPORT_SYMBOL(lu_context_key_quiesce_many);
1469
1470 /**
1471  * Return value associated with key \a key in context \a ctx.
1472  */
1473 void *lu_context_key_get(const struct lu_context *ctx,
1474                          const struct lu_context_key *key)
1475 {
1476         LINVRNT(ctx->lc_state == LCS_ENTERED);
1477         LINVRNT(0 <= key->lct_index && key->lct_index < ARRAY_SIZE(lu_keys));
1478         LASSERT(lu_keys[key->lct_index] == key);
1479         return ctx->lc_value[key->lct_index];
1480 }
1481 EXPORT_SYMBOL(lu_context_key_get);
1482
1483 /**
1484  * List of remembered contexts. XXX document me.
1485  */
1486 static CFS_LIST_HEAD(lu_context_remembered);
1487
1488 /**
1489  * Destroy \a key in all remembered contexts. This is used to destroy key
1490  * values in "shared" contexts (like service threads), when a module owning
1491  * the key is about to be unloaded.
1492  */
1493 void lu_context_key_quiesce(struct lu_context_key *key)
1494 {
1495         struct lu_context *ctx;
1496
1497         if (!(key->lct_tags & LCT_QUIESCENT)) {
1498                 /*
1499                  * XXX layering violation.
1500                  */
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 /**
1955  * Initialization of global lu_* data.
1956  */
1957 int lu_global_init(void)
1958 {
1959         int result;
1960
1961         CDEBUG(D_INFO, "Lustre LU module (%p).\n", &lu_keys);
1962
1963         result = lu_ref_global_init();
1964         if (result != 0)
1965                 return result;
1966
1967         LU_CONTEXT_KEY_INIT(&lu_global_key);
1968         result = lu_context_key_register(&lu_global_key);
1969         if (result != 0)
1970                 return result;
1971
1972         /*
1973          * At this level, we don't know what tags are needed, so allocate them
1974          * conservatively. This should not be too bad, because this
1975          * environment is global.
1976          */
1977         mutex_lock(&lu_sites_guard);
1978         result = lu_env_init(&lu_shrink_env, LCT_SHRINKER);
1979         mutex_unlock(&lu_sites_guard);
1980         if (result != 0)
1981                 return result;
1982
1983         /*
1984          * seeks estimation: 3 seeks to read a record from oi, one to read
1985          * inode, one for ea. Unfortunately setting this high value results in
1986          * lu_object/inode cache consuming all the memory.
1987          */
1988         lu_site_shrinker = cfs_set_shrinker(CFS_DEFAULT_SEEKS, lu_cache_shrink);
1989         if (lu_site_shrinker == NULL)
1990                 return -ENOMEM;
1991
1992         return result;
1993 }
1994
1995 /**
1996  * Dual to lu_global_init().
1997  */
1998 void lu_global_fini(void)
1999 {
2000         if (lu_site_shrinker != NULL) {
2001                 cfs_remove_shrinker(lu_site_shrinker);
2002                 lu_site_shrinker = NULL;
2003         }
2004
2005         lu_context_key_degister(&lu_global_key);
2006
2007         /*
2008          * Tear shrinker environment down _after_ de-registering
2009          * lu_global_key, because the latter has a value in the former.
2010          */
2011         mutex_lock(&lu_sites_guard);
2012         lu_env_fini(&lu_shrink_env);
2013         mutex_unlock(&lu_sites_guard);
2014
2015         lu_ref_global_fini();
2016 }
2017
2018 static __u32 ls_stats_read(struct lprocfs_stats *stats, int idx)
2019 {
2020 #ifdef LPROCFS
2021         struct lprocfs_counter ret;
2022
2023         lprocfs_stats_collect(stats, idx, &ret);
2024         return (__u32)ret.lc_count;
2025 #else
2026         return 0;
2027 #endif
2028 }
2029
2030 /**
2031  * Output site statistical counters into a buffer. Suitable for
2032  * lprocfs_rd_*()-style functions.
2033  */
2034 int lu_site_stats_print(const struct lu_site *s, char *page, int count)
2035 {
2036         lu_site_stats_t stats;
2037
2038         memset(&stats, 0, sizeof(stats));
2039         lu_site_stats_get(s->ls_obj_hash, &stats, 1);
2040
2041         return snprintf(page, count, "%d/%d %d/%d %d %d %d %d %d %d %d\n",
2042                         stats.lss_busy,
2043                         stats.lss_total,
2044                         stats.lss_populated,
2045                         CFS_HASH_NHLIST(s->ls_obj_hash),
2046                         stats.lss_max_search,
2047                         ls_stats_read(s->ls_stats, LU_SS_CREATED),
2048                         ls_stats_read(s->ls_stats, LU_SS_CACHE_HIT),
2049                         ls_stats_read(s->ls_stats, LU_SS_CACHE_MISS),
2050                         ls_stats_read(s->ls_stats, LU_SS_CACHE_RACE),
2051                         ls_stats_read(s->ls_stats, LU_SS_CACHE_DEATH_RACE),
2052                         ls_stats_read(s->ls_stats, LU_SS_LRU_PURGED));
2053 }
2054 EXPORT_SYMBOL(lu_site_stats_print);
2055
2056 /**
2057  * Helper function to initialize a number of kmem slab caches at once.
2058  */
2059 int lu_kmem_init(struct lu_kmem_descr *caches)
2060 {
2061         int result;
2062         struct lu_kmem_descr *iter = caches;
2063
2064         for (result = 0; iter->ckd_cache != NULL; ++iter) {
2065                 *iter->ckd_cache = cfs_mem_cache_create(iter->ckd_name,
2066                                                         iter->ckd_size,
2067                                                         0, 0);
2068                 if (*iter->ckd_cache == NULL) {
2069                         result = -ENOMEM;
2070                         /* free all previously allocated caches */
2071                         lu_kmem_fini(caches);
2072                         break;
2073                 }
2074         }
2075         return result;
2076 }
2077 EXPORT_SYMBOL(lu_kmem_init);
2078
2079 /**
2080  * Helper function to finalize a number of kmem slab cached at once. Dual to
2081  * lu_kmem_init().
2082  */
2083 void lu_kmem_fini(struct lu_kmem_descr *caches)
2084 {
2085         int rc;
2086
2087         for (; caches->ckd_cache != NULL; ++caches) {
2088                 if (*caches->ckd_cache != NULL) {
2089                         rc = cfs_mem_cache_destroy(*caches->ckd_cache);
2090                         LASSERTF(rc == 0, "couldn't destroy %s slab\n",
2091                                  caches->ckd_name);
2092                         *caches->ckd_cache = NULL;
2093                 }
2094         }
2095 }
2096 EXPORT_SYMBOL(lu_kmem_fini);
2097
2098 /**
2099  * Temporary solution to be able to assign fid in ->do_create()
2100  * till we have fully-functional OST fids
2101  */
2102 void lu_object_assign_fid(const struct lu_env *env, struct lu_object *o,
2103                           const struct lu_fid *fid)
2104 {
2105         struct lu_site          *s = o->lo_dev->ld_site;
2106         struct lu_fid           *old = &o->lo_header->loh_fid;
2107         struct lu_site_bkt_data *bkt;
2108         struct lu_object        *shadow;
2109         cfs_waitlink_t           waiter;
2110         cfs_hash_t              *hs;
2111         cfs_hash_bd_t            bd;
2112         __u64                    version = 0;
2113
2114         LASSERT(fid_is_zero(old));
2115
2116         hs = s->ls_obj_hash;
2117         cfs_hash_bd_get_and_lock(hs, (void *)fid, &bd, 1);
2118         shadow = htable_lookup(s, &bd, fid, &waiter, &version);
2119         /* supposed to be unique */
2120         LASSERT(shadow == NULL);
2121         *old = *fid;
2122         bkt = cfs_hash_bd_extra_get(hs, &bd);
2123         cfs_hash_bd_add_locked(hs, &bd, &o->lo_header->loh_hash);
2124         bkt->lsb_busy++;
2125         cfs_hash_bd_unlock(hs, &bd, 1);
2126 }
2127 EXPORT_SYMBOL(lu_object_assign_fid);
2128
2129 /**
2130  * allocates object with 0 (non-assiged) fid
2131  * XXX: temporary solution to be able to assign fid in ->do_create()
2132  *      till we have fully-functional OST fids
2133  */
2134 struct lu_object *lu_object_anon(const struct lu_env *env,
2135                                  struct lu_device *dev,
2136                                  const struct lu_object_conf *conf)
2137 {
2138         struct lu_fid     fid;
2139         struct lu_object *o;
2140
2141         fid_zero(&fid);
2142         o = lu_object_alloc(env, dev, &fid, conf);
2143
2144         return o;
2145 }
2146 EXPORT_SYMBOL(lu_object_anon);
2147
2148 struct lu_buf LU_BUF_NULL = {
2149         .lb_buf = NULL,
2150         .lb_len = 0
2151 };
2152 EXPORT_SYMBOL(LU_BUF_NULL);
2153
2154 void lu_buf_free(struct lu_buf *buf)
2155 {
2156         LASSERT(buf);
2157         if (buf->lb_buf) {
2158                 LASSERT(buf->lb_len > 0);
2159                 OBD_FREE_LARGE(buf->lb_buf, buf->lb_len);
2160                 buf->lb_buf = NULL;
2161                 buf->lb_len = 0;
2162         }
2163 }
2164 EXPORT_SYMBOL(lu_buf_free);
2165
2166 void lu_buf_alloc(struct lu_buf *buf, int size)
2167 {
2168         LASSERT(buf);
2169         LASSERT(buf->lb_buf == NULL);
2170         LASSERT(buf->lb_len == 0);
2171         OBD_ALLOC_LARGE(buf->lb_buf, size);
2172         if (likely(buf->lb_buf))
2173                 buf->lb_len = size;
2174 }
2175 EXPORT_SYMBOL(lu_buf_alloc);
2176
2177 void lu_buf_realloc(struct lu_buf *buf, int size)
2178 {
2179         lu_buf_free(buf);
2180         lu_buf_alloc(buf, size);
2181 }
2182 EXPORT_SYMBOL(lu_buf_realloc);
2183
2184 struct lu_buf *lu_buf_check_and_alloc(struct lu_buf *buf, int len)
2185 {
2186         if (buf->lb_buf == NULL && buf->lb_len == 0)
2187                 lu_buf_alloc(buf, len);
2188
2189         if ((len > buf->lb_len) && (buf->lb_buf != NULL))
2190                 lu_buf_realloc(buf, len);
2191
2192         return buf;
2193 }
2194 EXPORT_SYMBOL(lu_buf_check_and_alloc);
2195
2196 /**
2197  * Increase the size of the \a buf.
2198  * preserves old data in buffer
2199  * old buffer remains unchanged on error
2200  * \retval 0 or -ENOMEM
2201  */
2202 int lu_buf_check_and_grow(struct lu_buf *buf, int len)
2203 {
2204         char *ptr;
2205
2206         if (len <= buf->lb_len)
2207                 return 0;
2208
2209         OBD_ALLOC_LARGE(ptr, len);
2210         if (ptr == NULL)
2211                 return -ENOMEM;
2212
2213         /* Free the old buf */
2214         if (buf->lb_buf != NULL) {
2215                 memcpy(ptr, buf->lb_buf, buf->lb_len);
2216                 OBD_FREE_LARGE(buf->lb_buf, buf->lb_len);
2217         }
2218
2219         buf->lb_buf = ptr;
2220         buf->lb_len = len;
2221         return 0;
2222 }
2223 EXPORT_SYMBOL(lu_buf_check_and_grow);
2224