Whamcloud - gitweb
LU-3335 scrub: purge inconsistenct objects after OI scrub
[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 ERR_PTR(-ENOENT);
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 ERR_PTR(-ENOENT);
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 static struct lu_object *htable_lookup_nowait(struct lu_site *s,
577                                               cfs_hash_bd_t *bd,
578                                               const struct lu_fid *f)
579 {
580         cfs_hlist_node_t        *hnode;
581         struct lu_object_header *h;
582
583         /* cfs_hash_bd_peek_locked is a somehow "internal" function
584          * of cfs_hash, it doesn't add refcount on object. */
585         hnode = cfs_hash_bd_peek_locked(s->ls_obj_hash, bd, (void *)f);
586         if (hnode == NULL) {
587                 lprocfs_counter_incr(s->ls_stats, LU_SS_CACHE_MISS);
588                 return ERR_PTR(-ENOENT);
589         }
590
591         h = container_of0(hnode, struct lu_object_header, loh_hash);
592         if (unlikely(lu_object_is_dying(h)))
593                 return ERR_PTR(-ENOENT);
594
595         cfs_hash_get(s->ls_obj_hash, hnode);
596         lprocfs_counter_incr(s->ls_stats, LU_SS_CACHE_HIT);
597         cfs_list_del_init(&h->loh_lru);
598         return lu_object_top(h);
599 }
600
601 /**
602  * Search cache for an object with the fid \a f. If such object is found,
603  * return it. Otherwise, create new object, insert it into cache and return
604  * it. In any case, additional reference is acquired on the returned object.
605  */
606 struct lu_object *lu_object_find(const struct lu_env *env,
607                                  struct lu_device *dev, const struct lu_fid *f,
608                                  const struct lu_object_conf *conf)
609 {
610         return lu_object_find_at(env, dev->ld_site->ls_top_dev, f, conf);
611 }
612 EXPORT_SYMBOL(lu_object_find);
613
614 static struct lu_object *lu_object_new(const struct lu_env *env,
615                                        struct lu_device *dev,
616                                        const struct lu_fid *f,
617                                        const struct lu_object_conf *conf)
618 {
619         struct lu_object        *o;
620         cfs_hash_t              *hs;
621         cfs_hash_bd_t            bd;
622         struct lu_site_bkt_data *bkt;
623
624         o = lu_object_alloc(env, dev, f, conf);
625         if (unlikely(IS_ERR(o)))
626                 return o;
627
628         hs = dev->ld_site->ls_obj_hash;
629         cfs_hash_bd_get_and_lock(hs, (void *)f, &bd, 1);
630         bkt = cfs_hash_bd_extra_get(hs, &bd);
631         cfs_hash_bd_add_locked(hs, &bd, &o->lo_header->loh_hash);
632         bkt->lsb_busy++;
633         cfs_hash_bd_unlock(hs, &bd, 1);
634         return o;
635 }
636
637 /**
638  * Core logic of lu_object_find*() functions.
639  */
640 static struct lu_object *lu_object_find_try(const struct lu_env *env,
641                                             struct lu_device *dev,
642                                             const struct lu_fid *f,
643                                             const struct lu_object_conf *conf,
644                                             cfs_waitlink_t *waiter)
645 {
646         struct lu_object      *o;
647         struct lu_object      *shadow;
648         struct lu_site        *s;
649         cfs_hash_t            *hs;
650         cfs_hash_bd_t          bd;
651         __u64                  version = 0;
652
653         /*
654          * This uses standard index maintenance protocol:
655          *
656          *     - search index under lock, and return object if found;
657          *     - otherwise, unlock index, allocate new object;
658          *     - lock index and search again;
659          *     - if nothing is found (usual case), insert newly created
660          *       object into index;
661          *     - otherwise (race: other thread inserted object), free
662          *       object just allocated.
663          *     - unlock index;
664          *     - return object.
665          *
666          * For "LOC_F_NEW" case, we are sure the object is new established.
667          * It is unnecessary to perform lookup-alloc-lookup-insert, instead,
668          * just alloc and insert directly.
669          *
670          * If dying object is found during index search, add @waiter to the
671          * site wait-queue and return ERR_PTR(-EAGAIN).
672          */
673         if (conf != NULL && conf->loc_flags & LOC_F_NEW)
674                 return lu_object_new(env, dev, f, conf);
675
676         s  = dev->ld_site;
677         hs = s->ls_obj_hash;
678         cfs_hash_bd_get_and_lock(hs, (void *)f, &bd, 1);
679         o = htable_lookup(s, &bd, f, waiter, &version);
680         cfs_hash_bd_unlock(hs, &bd, 1);
681         if (!IS_ERR(o) || PTR_ERR(o) != -ENOENT)
682                 return o;
683
684         /*
685          * Allocate new object. This may result in rather complicated
686          * operations, including fld queries, inode loading, etc.
687          */
688         o = lu_object_alloc(env, dev, f, conf);
689         if (unlikely(IS_ERR(o)))
690                 return o;
691
692         LASSERT(lu_fid_eq(lu_object_fid(o), f));
693
694         cfs_hash_bd_lock(hs, &bd, 1);
695
696         shadow = htable_lookup(s, &bd, f, waiter, &version);
697         if (likely(IS_ERR(shadow) && PTR_ERR(shadow) == -ENOENT)) {
698                 struct lu_site_bkt_data *bkt;
699
700                 bkt = cfs_hash_bd_extra_get(hs, &bd);
701                 cfs_hash_bd_add_locked(hs, &bd, &o->lo_header->loh_hash);
702                 bkt->lsb_busy++;
703                 cfs_hash_bd_unlock(hs, &bd, 1);
704                 return o;
705         }
706
707         lprocfs_counter_incr(s->ls_stats, LU_SS_CACHE_RACE);
708         cfs_hash_bd_unlock(hs, &bd, 1);
709         lu_object_free(env, o);
710         return shadow;
711 }
712
713 /**
714  * Much like lu_object_find(), but top level device of object is specifically
715  * \a dev rather than top level device of the site. This interface allows
716  * objects of different "stacking" to be created within the same site.
717  */
718 struct lu_object *lu_object_find_at(const struct lu_env *env,
719                                     struct lu_device *dev,
720                                     const struct lu_fid *f,
721                                     const struct lu_object_conf *conf)
722 {
723         struct lu_site_bkt_data *bkt;
724         struct lu_object        *obj;
725         cfs_waitlink_t           wait;
726
727         while (1) {
728                 obj = lu_object_find_try(env, dev, f, conf, &wait);
729                 if (obj != ERR_PTR(-EAGAIN))
730                         return obj;
731                 /*
732                  * lu_object_find_try() already added waiter into the
733                  * wait queue.
734                  */
735                 cfs_waitq_wait(&wait, CFS_TASK_UNINT);
736                 bkt = lu_site_bkt_from_fid(dev->ld_site, (void *)f);
737                 cfs_waitq_del(&bkt->lsb_marche_funebre, &wait);
738         }
739 }
740 EXPORT_SYMBOL(lu_object_find_at);
741
742 /**
743  * Try to find the object in cache without waiting for the dead object
744  * to be released nor allocating object if no cached one was found.
745  *
746  * The found object will be set as LU_OBJECT_HEARD_BANSHEE for purging.
747  */
748 void lu_object_purge(const struct lu_env *env, struct lu_device *dev,
749                      const struct lu_fid *f)
750 {
751         struct lu_site          *s  = dev->ld_site;
752         cfs_hash_t              *hs = s->ls_obj_hash;
753         cfs_hash_bd_t            bd;
754         struct lu_object        *o;
755
756         cfs_hash_bd_get_and_lock(hs, f, &bd, 1);
757         o = htable_lookup_nowait(s, &bd, f);
758         cfs_hash_bd_unlock(hs, &bd, 1);
759         if (!IS_ERR(o)) {
760                 set_bit(LU_OBJECT_HEARD_BANSHEE, &o->lo_header->loh_flags);
761                 lu_object_put(env, o);
762         }
763 }
764 EXPORT_SYMBOL(lu_object_purge);
765
766 /**
767  * Find object with given fid, and return its slice belonging to given device.
768  */
769 struct lu_object *lu_object_find_slice(const struct lu_env *env,
770                                        struct lu_device *dev,
771                                        const struct lu_fid *f,
772                                        const struct lu_object_conf *conf)
773 {
774         struct lu_object *top;
775         struct lu_object *obj;
776
777         top = lu_object_find(env, dev, f, conf);
778         if (!IS_ERR(top)) {
779                 obj = lu_object_locate(top->lo_header, dev->ld_type);
780                 if (obj == NULL)
781                         lu_object_put(env, top);
782         } else
783                 obj = top;
784         return obj;
785 }
786 EXPORT_SYMBOL(lu_object_find_slice);
787
788 /**
789  * Global list of all device types.
790  */
791 static CFS_LIST_HEAD(lu_device_types);
792
793 int lu_device_type_init(struct lu_device_type *ldt)
794 {
795         int result = 0;
796
797         CFS_INIT_LIST_HEAD(&ldt->ldt_linkage);
798         if (ldt->ldt_ops->ldto_init)
799                 result = ldt->ldt_ops->ldto_init(ldt);
800         if (result == 0)
801                 cfs_list_add(&ldt->ldt_linkage, &lu_device_types);
802         return result;
803 }
804 EXPORT_SYMBOL(lu_device_type_init);
805
806 void lu_device_type_fini(struct lu_device_type *ldt)
807 {
808         cfs_list_del_init(&ldt->ldt_linkage);
809         if (ldt->ldt_ops->ldto_fini)
810                 ldt->ldt_ops->ldto_fini(ldt);
811 }
812 EXPORT_SYMBOL(lu_device_type_fini);
813
814 void lu_types_stop(void)
815 {
816         struct lu_device_type *ldt;
817
818         cfs_list_for_each_entry(ldt, &lu_device_types, ldt_linkage) {
819                 if (ldt->ldt_device_nr == 0 && ldt->ldt_ops->ldto_stop)
820                         ldt->ldt_ops->ldto_stop(ldt);
821         }
822 }
823 EXPORT_SYMBOL(lu_types_stop);
824
825 /**
826  * Global list of all sites on this node
827  */
828 static CFS_LIST_HEAD(lu_sites);
829 static DEFINE_MUTEX(lu_sites_guard);
830
831 /**
832  * Global environment used by site shrinker.
833  */
834 static struct lu_env lu_shrink_env;
835
836 struct lu_site_print_arg {
837         struct lu_env   *lsp_env;
838         void            *lsp_cookie;
839         lu_printer_t     lsp_printer;
840 };
841
842 static int
843 lu_site_obj_print(cfs_hash_t *hs, cfs_hash_bd_t *bd,
844                   cfs_hlist_node_t *hnode, void *data)
845 {
846         struct lu_site_print_arg *arg = (struct lu_site_print_arg *)data;
847         struct lu_object_header  *h;
848
849         h = cfs_hlist_entry(hnode, struct lu_object_header, loh_hash);
850         if (!cfs_list_empty(&h->loh_layers)) {
851                 const struct lu_object *o;
852
853                 o = lu_object_top(h);
854                 lu_object_print(arg->lsp_env, arg->lsp_cookie,
855                                 arg->lsp_printer, o);
856         } else {
857                 lu_object_header_print(arg->lsp_env, arg->lsp_cookie,
858                                        arg->lsp_printer, h);
859         }
860         return 0;
861 }
862
863 /**
864  * Print all objects in \a s.
865  */
866 void lu_site_print(const struct lu_env *env, struct lu_site *s, void *cookie,
867                    lu_printer_t printer)
868 {
869         struct lu_site_print_arg arg = {
870                 .lsp_env     = (struct lu_env *)env,
871                 .lsp_cookie  = cookie,
872                 .lsp_printer = printer,
873         };
874
875         cfs_hash_for_each(s->ls_obj_hash, lu_site_obj_print, &arg);
876 }
877 EXPORT_SYMBOL(lu_site_print);
878
879 enum {
880         LU_CACHE_PERCENT_MAX     = 50,
881         LU_CACHE_PERCENT_DEFAULT = 20
882 };
883
884 static unsigned int lu_cache_percent = LU_CACHE_PERCENT_DEFAULT;
885 CFS_MODULE_PARM(lu_cache_percent, "i", int, 0644,
886                 "Percentage of memory to be used as lu_object cache");
887
888 /**
889  * Return desired hash table order.
890  */
891 static int lu_htable_order(void)
892 {
893         unsigned long cache_size;
894         int bits;
895
896         /*
897          * Calculate hash table size, assuming that we want reasonable
898          * performance when 20% of total memory is occupied by cache of
899          * lu_objects.
900          *
901          * Size of lu_object is (arbitrary) taken as 1K (together with inode).
902          */
903         cache_size = num_physpages;
904
905 #if BITS_PER_LONG == 32
906         /* limit hashtable size for lowmem systems to low RAM */
907         if (cache_size > 1 << (30 - PAGE_CACHE_SHIFT))
908                 cache_size = 1 << (30 - PAGE_CACHE_SHIFT) * 3 / 4;
909 #endif
910
911         /* clear off unreasonable cache setting. */
912         if (lu_cache_percent == 0 || lu_cache_percent > LU_CACHE_PERCENT_MAX) {
913                 CWARN("obdclass: invalid lu_cache_percent: %u, it must be in"
914                       " the range of (0, %u]. Will use default value: %u.\n",
915                       lu_cache_percent, LU_CACHE_PERCENT_MAX,
916                       LU_CACHE_PERCENT_DEFAULT);
917
918                 lu_cache_percent = LU_CACHE_PERCENT_DEFAULT;
919         }
920         cache_size = cache_size / 100 * lu_cache_percent *
921                 (PAGE_CACHE_SIZE / 1024);
922
923         for (bits = 1; (1 << bits) < cache_size; ++bits) {
924                 ;
925         }
926         return bits;
927 }
928
929 static unsigned lu_obj_hop_hash(cfs_hash_t *hs,
930                                 const void *key, unsigned mask)
931 {
932         struct lu_fid  *fid = (struct lu_fid *)key;
933         __u32           hash;
934
935         hash = fid_flatten32(fid);
936         hash += (hash >> 4) + (hash << 12); /* mixing oid and seq */
937         hash = cfs_hash_long(hash, hs->hs_bkt_bits);
938
939         /* give me another random factor */
940         hash -= cfs_hash_long((unsigned long)hs, fid_oid(fid) % 11 + 3);
941
942         hash <<= hs->hs_cur_bits - hs->hs_bkt_bits;
943         hash |= (fid_seq(fid) + fid_oid(fid)) & (CFS_HASH_NBKT(hs) - 1);
944
945         return hash & mask;
946 }
947
948 static void *lu_obj_hop_object(cfs_hlist_node_t *hnode)
949 {
950         return cfs_hlist_entry(hnode, struct lu_object_header, loh_hash);
951 }
952
953 static void *lu_obj_hop_key(cfs_hlist_node_t *hnode)
954 {
955         struct lu_object_header *h;
956
957         h = cfs_hlist_entry(hnode, struct lu_object_header, loh_hash);
958         return &h->loh_fid;
959 }
960
961 static int lu_obj_hop_keycmp(const void *key, cfs_hlist_node_t *hnode)
962 {
963         struct lu_object_header *h;
964
965         h = cfs_hlist_entry(hnode, struct lu_object_header, loh_hash);
966         return lu_fid_eq(&h->loh_fid, (struct lu_fid *)key);
967 }
968
969 static void lu_obj_hop_get(cfs_hash_t *hs, cfs_hlist_node_t *hnode)
970 {
971         struct lu_object_header *h;
972
973         h = cfs_hlist_entry(hnode, struct lu_object_header, loh_hash);
974         if (cfs_atomic_add_return(1, &h->loh_ref) == 1) {
975                 struct lu_site_bkt_data *bkt;
976                 cfs_hash_bd_t            bd;
977
978                 cfs_hash_bd_get(hs, &h->loh_fid, &bd);
979                 bkt = cfs_hash_bd_extra_get(hs, &bd);
980                 bkt->lsb_busy++;
981         }
982 }
983
984 static void lu_obj_hop_put_locked(cfs_hash_t *hs, cfs_hlist_node_t *hnode)
985 {
986         LBUG(); /* we should never called it */
987 }
988
989 cfs_hash_ops_t lu_site_hash_ops = {
990         .hs_hash        = lu_obj_hop_hash,
991         .hs_key         = lu_obj_hop_key,
992         .hs_keycmp      = lu_obj_hop_keycmp,
993         .hs_object      = lu_obj_hop_object,
994         .hs_get         = lu_obj_hop_get,
995         .hs_put_locked  = lu_obj_hop_put_locked,
996 };
997
998 void lu_dev_add_linkage(struct lu_site *s, struct lu_device *d)
999 {
1000         spin_lock(&s->ls_ld_lock);
1001         if (cfs_list_empty(&d->ld_linkage))
1002                 cfs_list_add(&d->ld_linkage, &s->ls_ld_linkage);
1003         spin_unlock(&s->ls_ld_lock);
1004 }
1005 EXPORT_SYMBOL(lu_dev_add_linkage);
1006
1007 void lu_dev_del_linkage(struct lu_site *s, struct lu_device *d)
1008 {
1009         spin_lock(&s->ls_ld_lock);
1010         cfs_list_del_init(&d->ld_linkage);
1011         spin_unlock(&s->ls_ld_lock);
1012 }
1013 EXPORT_SYMBOL(lu_dev_del_linkage);
1014
1015 /**
1016  * Initialize site \a s, with \a d as the top level device.
1017  */
1018 #define LU_SITE_BITS_MIN    12
1019 #define LU_SITE_BITS_MAX    24
1020 /**
1021  * total 256 buckets, we don't want too many buckets because:
1022  * - consume too much memory
1023  * - avoid unbalanced LRU list
1024  */
1025 #define LU_SITE_BKT_BITS    8
1026
1027 int lu_site_init(struct lu_site *s, struct lu_device *top)
1028 {
1029         struct lu_site_bkt_data *bkt;
1030         cfs_hash_bd_t bd;
1031         char name[16];
1032         int bits;
1033         int i;
1034         ENTRY;
1035
1036         memset(s, 0, sizeof *s);
1037         bits = lu_htable_order();
1038         snprintf(name, 16, "lu_site_%s", top->ld_type->ldt_name);
1039         for (bits = min(max(LU_SITE_BITS_MIN, bits), LU_SITE_BITS_MAX);
1040              bits >= LU_SITE_BITS_MIN; bits--) {
1041                 s->ls_obj_hash = cfs_hash_create(name, bits, bits,
1042                                                  bits - LU_SITE_BKT_BITS,
1043                                                  sizeof(*bkt), 0, 0,
1044                                                  &lu_site_hash_ops,
1045                                                  CFS_HASH_SPIN_BKTLOCK |
1046                                                  CFS_HASH_NO_ITEMREF |
1047                                                  CFS_HASH_DEPTH |
1048                                                  CFS_HASH_ASSERT_EMPTY);
1049                 if (s->ls_obj_hash != NULL)
1050                         break;
1051         }
1052
1053         if (s->ls_obj_hash == NULL) {
1054                 CERROR("failed to create lu_site hash with bits: %d\n", bits);
1055                 return -ENOMEM;
1056         }
1057
1058         cfs_hash_for_each_bucket(s->ls_obj_hash, &bd, i) {
1059                 bkt = cfs_hash_bd_extra_get(s->ls_obj_hash, &bd);
1060                 CFS_INIT_LIST_HEAD(&bkt->lsb_lru);
1061                 cfs_waitq_init(&bkt->lsb_marche_funebre);
1062         }
1063
1064         s->ls_stats = lprocfs_alloc_stats(LU_SS_LAST_STAT, 0);
1065         if (s->ls_stats == NULL) {
1066                 cfs_hash_putref(s->ls_obj_hash);
1067                 s->ls_obj_hash = NULL;
1068                 return -ENOMEM;
1069         }
1070
1071         lprocfs_counter_init(s->ls_stats, LU_SS_CREATED,
1072                              0, "created", "created");
1073         lprocfs_counter_init(s->ls_stats, LU_SS_CACHE_HIT,
1074                              0, "cache_hit", "cache_hit");
1075         lprocfs_counter_init(s->ls_stats, LU_SS_CACHE_MISS,
1076                              0, "cache_miss", "cache_miss");
1077         lprocfs_counter_init(s->ls_stats, LU_SS_CACHE_RACE,
1078                              0, "cache_race", "cache_race");
1079         lprocfs_counter_init(s->ls_stats, LU_SS_CACHE_DEATH_RACE,
1080                              0, "cache_death_race", "cache_death_race");
1081         lprocfs_counter_init(s->ls_stats, LU_SS_LRU_PURGED,
1082                              0, "lru_purged", "lru_purged");
1083
1084         CFS_INIT_LIST_HEAD(&s->ls_linkage);
1085         s->ls_top_dev = top;
1086         top->ld_site = s;
1087         lu_device_get(top);
1088         lu_ref_add(&top->ld_reference, "site-top", s);
1089
1090         CFS_INIT_LIST_HEAD(&s->ls_ld_linkage);
1091         spin_lock_init(&s->ls_ld_lock);
1092
1093         lu_dev_add_linkage(s, top);
1094
1095         RETURN(0);
1096 }
1097 EXPORT_SYMBOL(lu_site_init);
1098
1099 /**
1100  * Finalize \a s and release its resources.
1101  */
1102 void lu_site_fini(struct lu_site *s)
1103 {
1104         mutex_lock(&lu_sites_guard);
1105         cfs_list_del_init(&s->ls_linkage);
1106         mutex_unlock(&lu_sites_guard);
1107
1108         if (s->ls_obj_hash != NULL) {
1109                 cfs_hash_putref(s->ls_obj_hash);
1110                 s->ls_obj_hash = NULL;
1111         }
1112
1113         if (s->ls_top_dev != NULL) {
1114                 s->ls_top_dev->ld_site = NULL;
1115                 lu_ref_del(&s->ls_top_dev->ld_reference, "site-top", s);
1116                 lu_device_put(s->ls_top_dev);
1117                 s->ls_top_dev = NULL;
1118         }
1119
1120         if (s->ls_stats != NULL)
1121                 lprocfs_free_stats(&s->ls_stats);
1122 }
1123 EXPORT_SYMBOL(lu_site_fini);
1124
1125 /**
1126  * Called when initialization of stack for this site is completed.
1127  */
1128 int lu_site_init_finish(struct lu_site *s)
1129 {
1130         int result;
1131         mutex_lock(&lu_sites_guard);
1132         result = lu_context_refill(&lu_shrink_env.le_ctx);
1133         if (result == 0)
1134                 cfs_list_add(&s->ls_linkage, &lu_sites);
1135         mutex_unlock(&lu_sites_guard);
1136         return result;
1137 }
1138 EXPORT_SYMBOL(lu_site_init_finish);
1139
1140 /**
1141  * Acquire additional reference on device \a d
1142  */
1143 void lu_device_get(struct lu_device *d)
1144 {
1145         cfs_atomic_inc(&d->ld_ref);
1146 }
1147 EXPORT_SYMBOL(lu_device_get);
1148
1149 /**
1150  * Release reference on device \a d.
1151  */
1152 void lu_device_put(struct lu_device *d)
1153 {
1154         LASSERT(cfs_atomic_read(&d->ld_ref) > 0);
1155         cfs_atomic_dec(&d->ld_ref);
1156 }
1157 EXPORT_SYMBOL(lu_device_put);
1158
1159 /**
1160  * Initialize device \a d of type \a t.
1161  */
1162 int lu_device_init(struct lu_device *d, struct lu_device_type *t)
1163 {
1164         if (t->ldt_device_nr++ == 0 && t->ldt_ops->ldto_start != NULL)
1165                 t->ldt_ops->ldto_start(t);
1166         memset(d, 0, sizeof *d);
1167         cfs_atomic_set(&d->ld_ref, 0);
1168         d->ld_type = t;
1169         lu_ref_init(&d->ld_reference);
1170         CFS_INIT_LIST_HEAD(&d->ld_linkage);
1171         return 0;
1172 }
1173 EXPORT_SYMBOL(lu_device_init);
1174
1175 /**
1176  * Finalize device \a d.
1177  */
1178 void lu_device_fini(struct lu_device *d)
1179 {
1180         struct lu_device_type *t;
1181
1182         t = d->ld_type;
1183         if (d->ld_obd != NULL) {
1184                 d->ld_obd->obd_lu_dev = NULL;
1185                 d->ld_obd = NULL;
1186         }
1187
1188         lu_ref_fini(&d->ld_reference);
1189         LASSERTF(cfs_atomic_read(&d->ld_ref) == 0,
1190                  "Refcount is %u\n", cfs_atomic_read(&d->ld_ref));
1191         LASSERT(t->ldt_device_nr > 0);
1192         if (--t->ldt_device_nr == 0 && t->ldt_ops->ldto_stop != NULL)
1193                 t->ldt_ops->ldto_stop(t);
1194 }
1195 EXPORT_SYMBOL(lu_device_fini);
1196
1197 /**
1198  * Initialize object \a o that is part of compound object \a h and was created
1199  * by device \a d.
1200  */
1201 int lu_object_init(struct lu_object *o, struct lu_object_header *h,
1202                    struct lu_device *d)
1203 {
1204         memset(o, 0, sizeof(*o));
1205         o->lo_header = h;
1206         o->lo_dev = d;
1207         lu_device_get(d);
1208         lu_ref_add_at(&d->ld_reference, &o->lo_dev_ref, "lu_object", o);
1209         CFS_INIT_LIST_HEAD(&o->lo_linkage);
1210
1211         return 0;
1212 }
1213 EXPORT_SYMBOL(lu_object_init);
1214
1215 /**
1216  * Finalize object and release its resources.
1217  */
1218 void lu_object_fini(struct lu_object *o)
1219 {
1220         struct lu_device *dev = o->lo_dev;
1221
1222         LASSERT(cfs_list_empty(&o->lo_linkage));
1223
1224         if (dev != NULL) {
1225                 lu_ref_del_at(&dev->ld_reference, &o->lo_dev_ref,
1226                               "lu_object", o);
1227                 lu_device_put(dev);
1228                 o->lo_dev = NULL;
1229         }
1230 }
1231 EXPORT_SYMBOL(lu_object_fini);
1232
1233 /**
1234  * Add object \a o as first layer of compound object \a h
1235  *
1236  * This is typically called by the ->ldo_object_alloc() method of top-level
1237  * device.
1238  */
1239 void lu_object_add_top(struct lu_object_header *h, struct lu_object *o)
1240 {
1241         cfs_list_move(&o->lo_linkage, &h->loh_layers);
1242 }
1243 EXPORT_SYMBOL(lu_object_add_top);
1244
1245 /**
1246  * Add object \a o as a layer of compound object, going after \a before.
1247  *
1248  * This is typically called by the ->ldo_object_alloc() method of \a
1249  * before->lo_dev.
1250  */
1251 void lu_object_add(struct lu_object *before, struct lu_object *o)
1252 {
1253         cfs_list_move(&o->lo_linkage, &before->lo_linkage);
1254 }
1255 EXPORT_SYMBOL(lu_object_add);
1256
1257 /**
1258  * Initialize compound object.
1259  */
1260 int lu_object_header_init(struct lu_object_header *h)
1261 {
1262         memset(h, 0, sizeof *h);
1263         cfs_atomic_set(&h->loh_ref, 1);
1264         CFS_INIT_HLIST_NODE(&h->loh_hash);
1265         CFS_INIT_LIST_HEAD(&h->loh_lru);
1266         CFS_INIT_LIST_HEAD(&h->loh_layers);
1267         lu_ref_init(&h->loh_reference);
1268         return 0;
1269 }
1270 EXPORT_SYMBOL(lu_object_header_init);
1271
1272 /**
1273  * Finalize compound object.
1274  */
1275 void lu_object_header_fini(struct lu_object_header *h)
1276 {
1277         LASSERT(cfs_list_empty(&h->loh_layers));
1278         LASSERT(cfs_list_empty(&h->loh_lru));
1279         LASSERT(cfs_hlist_unhashed(&h->loh_hash));
1280         lu_ref_fini(&h->loh_reference);
1281 }
1282 EXPORT_SYMBOL(lu_object_header_fini);
1283
1284 /**
1285  * Given a compound object, find its slice, corresponding to the device type
1286  * \a dtype.
1287  */
1288 struct lu_object *lu_object_locate(struct lu_object_header *h,
1289                                    const struct lu_device_type *dtype)
1290 {
1291         struct lu_object *o;
1292
1293         cfs_list_for_each_entry(o, &h->loh_layers, lo_linkage) {
1294                 if (o->lo_dev->ld_type == dtype)
1295                         return o;
1296         }
1297         return NULL;
1298 }
1299 EXPORT_SYMBOL(lu_object_locate);
1300
1301
1302
1303 /**
1304  * Finalize and free devices in the device stack.
1305  *
1306  * Finalize device stack by purging object cache, and calling
1307  * lu_device_type_operations::ldto_device_fini() and
1308  * lu_device_type_operations::ldto_device_free() on all devices in the stack.
1309  */
1310 void lu_stack_fini(const struct lu_env *env, struct lu_device *top)
1311 {
1312         struct lu_site   *site = top->ld_site;
1313         struct lu_device *scan;
1314         struct lu_device *next;
1315
1316         lu_site_purge(env, site, ~0);
1317         for (scan = top; scan != NULL; scan = next) {
1318                 next = scan->ld_type->ldt_ops->ldto_device_fini(env, scan);
1319                 lu_ref_del(&scan->ld_reference, "lu-stack", &lu_site_init);
1320                 lu_device_put(scan);
1321         }
1322
1323         /* purge again. */
1324         lu_site_purge(env, site, ~0);
1325
1326         for (scan = top; scan != NULL; scan = next) {
1327                 const struct lu_device_type *ldt = scan->ld_type;
1328                 struct obd_type             *type;
1329
1330                 next = ldt->ldt_ops->ldto_device_free(env, scan);
1331                 type = ldt->ldt_obd_type;
1332                 if (type != NULL) {
1333                         type->typ_refcnt--;
1334                         class_put_type(type);
1335                 }
1336         }
1337 }
1338 EXPORT_SYMBOL(lu_stack_fini);
1339
1340 enum {
1341         /**
1342          * Maximal number of tld slots.
1343          */
1344         LU_CONTEXT_KEY_NR = 40
1345 };
1346
1347 static struct lu_context_key *lu_keys[LU_CONTEXT_KEY_NR] = { NULL, };
1348
1349 static DEFINE_SPINLOCK(lu_keys_guard);
1350
1351 /**
1352  * Global counter incremented whenever key is registered, unregistered,
1353  * revived or quiesced. This is used to void unnecessary calls to
1354  * lu_context_refill(). No locking is provided, as initialization and shutdown
1355  * are supposed to be externally serialized.
1356  */
1357 static unsigned key_set_version = 0;
1358
1359 /**
1360  * Register new key.
1361  */
1362 int lu_context_key_register(struct lu_context_key *key)
1363 {
1364         int result;
1365         int i;
1366
1367         LASSERT(key->lct_init != NULL);
1368         LASSERT(key->lct_fini != NULL);
1369         LASSERT(key->lct_tags != 0);
1370         LASSERT(key->lct_owner != NULL);
1371
1372         result = -ENFILE;
1373         spin_lock(&lu_keys_guard);
1374         for (i = 0; i < ARRAY_SIZE(lu_keys); ++i) {
1375                 if (lu_keys[i] == NULL) {
1376                         key->lct_index = i;
1377                         cfs_atomic_set(&key->lct_used, 1);
1378                         lu_keys[i] = key;
1379                         lu_ref_init(&key->lct_reference);
1380                         result = 0;
1381                         ++key_set_version;
1382                         break;
1383                 }
1384         }
1385         spin_unlock(&lu_keys_guard);
1386         return result;
1387 }
1388 EXPORT_SYMBOL(lu_context_key_register);
1389
1390 static void key_fini(struct lu_context *ctx, int index)
1391 {
1392         if (ctx->lc_value != NULL && ctx->lc_value[index] != NULL) {
1393                 struct lu_context_key *key;
1394
1395                 key = lu_keys[index];
1396                 LASSERT(key != NULL);
1397                 LASSERT(key->lct_fini != NULL);
1398                 LASSERT(cfs_atomic_read(&key->lct_used) > 1);
1399
1400                 key->lct_fini(ctx, key, ctx->lc_value[index]);
1401                 lu_ref_del(&key->lct_reference, "ctx", ctx);
1402                 cfs_atomic_dec(&key->lct_used);
1403
1404                 LASSERT(key->lct_owner != NULL);
1405                 if ((ctx->lc_tags & LCT_NOREF) == 0) {
1406                         LINVRNT(cfs_module_refcount(key->lct_owner) > 0);
1407                         cfs_module_put(key->lct_owner);
1408                 }
1409                 ctx->lc_value[index] = NULL;
1410         }
1411 }
1412
1413 /**
1414  * Deregister key.
1415  */
1416 void lu_context_key_degister(struct lu_context_key *key)
1417 {
1418         LASSERT(cfs_atomic_read(&key->lct_used) >= 1);
1419         LINVRNT(0 <= key->lct_index && key->lct_index < ARRAY_SIZE(lu_keys));
1420
1421         lu_context_key_quiesce(key);
1422
1423         ++key_set_version;
1424         spin_lock(&lu_keys_guard);
1425         key_fini(&lu_shrink_env.le_ctx, key->lct_index);
1426         if (lu_keys[key->lct_index]) {
1427                 lu_keys[key->lct_index] = NULL;
1428                 lu_ref_fini(&key->lct_reference);
1429         }
1430         spin_unlock(&lu_keys_guard);
1431
1432         LASSERTF(cfs_atomic_read(&key->lct_used) == 1,
1433                  "key has instances: %d\n",
1434                  cfs_atomic_read(&key->lct_used));
1435 }
1436 EXPORT_SYMBOL(lu_context_key_degister);
1437
1438 /**
1439  * Register a number of keys. This has to be called after all keys have been
1440  * initialized by a call to LU_CONTEXT_KEY_INIT().
1441  */
1442 int lu_context_key_register_many(struct lu_context_key *k, ...)
1443 {
1444         struct lu_context_key *key = k;
1445         va_list args;
1446         int result;
1447
1448         va_start(args, k);
1449         do {
1450                 result = lu_context_key_register(key);
1451                 if (result)
1452                         break;
1453                 key = va_arg(args, struct lu_context_key *);
1454         } while (key != NULL);
1455         va_end(args);
1456
1457         if (result != 0) {
1458                 va_start(args, k);
1459                 while (k != key) {
1460                         lu_context_key_degister(k);
1461                         k = va_arg(args, struct lu_context_key *);
1462                 }
1463                 va_end(args);
1464         }
1465
1466         return result;
1467 }
1468 EXPORT_SYMBOL(lu_context_key_register_many);
1469
1470 /**
1471  * De-register a number of keys. This is a dual to
1472  * lu_context_key_register_many().
1473  */
1474 void lu_context_key_degister_many(struct lu_context_key *k, ...)
1475 {
1476         va_list args;
1477
1478         va_start(args, k);
1479         do {
1480                 lu_context_key_degister(k);
1481                 k = va_arg(args, struct lu_context_key*);
1482         } while (k != NULL);
1483         va_end(args);
1484 }
1485 EXPORT_SYMBOL(lu_context_key_degister_many);
1486
1487 /**
1488  * Revive a number of keys.
1489  */
1490 void lu_context_key_revive_many(struct lu_context_key *k, ...)
1491 {
1492         va_list args;
1493
1494         va_start(args, k);
1495         do {
1496                 lu_context_key_revive(k);
1497                 k = va_arg(args, struct lu_context_key*);
1498         } while (k != NULL);
1499         va_end(args);
1500 }
1501 EXPORT_SYMBOL(lu_context_key_revive_many);
1502
1503 /**
1504  * Quiescent a number of keys.
1505  */
1506 void lu_context_key_quiesce_many(struct lu_context_key *k, ...)
1507 {
1508         va_list args;
1509
1510         va_start(args, k);
1511         do {
1512                 lu_context_key_quiesce(k);
1513                 k = va_arg(args, struct lu_context_key*);
1514         } while (k != NULL);
1515         va_end(args);
1516 }
1517 EXPORT_SYMBOL(lu_context_key_quiesce_many);
1518
1519 /**
1520  * Return value associated with key \a key in context \a ctx.
1521  */
1522 void *lu_context_key_get(const struct lu_context *ctx,
1523                          const struct lu_context_key *key)
1524 {
1525         LINVRNT(ctx->lc_state == LCS_ENTERED);
1526         LINVRNT(0 <= key->lct_index && key->lct_index < ARRAY_SIZE(lu_keys));
1527         LASSERT(lu_keys[key->lct_index] == key);
1528         return ctx->lc_value[key->lct_index];
1529 }
1530 EXPORT_SYMBOL(lu_context_key_get);
1531
1532 /**
1533  * List of remembered contexts. XXX document me.
1534  */
1535 static CFS_LIST_HEAD(lu_context_remembered);
1536
1537 /**
1538  * Destroy \a key in all remembered contexts. This is used to destroy key
1539  * values in "shared" contexts (like service threads), when a module owning
1540  * the key is about to be unloaded.
1541  */
1542 void lu_context_key_quiesce(struct lu_context_key *key)
1543 {
1544         struct lu_context *ctx;
1545
1546         if (!(key->lct_tags & LCT_QUIESCENT)) {
1547                 /*
1548                  * XXX layering violation.
1549                  */
1550                 key->lct_tags |= LCT_QUIESCENT;
1551                 /*
1552                  * XXX memory barrier has to go here.
1553                  */
1554                 spin_lock(&lu_keys_guard);
1555                 cfs_list_for_each_entry(ctx, &lu_context_remembered,
1556                                         lc_remember)
1557                         key_fini(ctx, key->lct_index);
1558                 spin_unlock(&lu_keys_guard);
1559                 ++key_set_version;
1560         }
1561 }
1562 EXPORT_SYMBOL(lu_context_key_quiesce);
1563
1564 void lu_context_key_revive(struct lu_context_key *key)
1565 {
1566         key->lct_tags &= ~LCT_QUIESCENT;
1567         ++key_set_version;
1568 }
1569 EXPORT_SYMBOL(lu_context_key_revive);
1570
1571 static void keys_fini(struct lu_context *ctx)
1572 {
1573         int     i;
1574
1575         if (ctx->lc_value == NULL)
1576                 return;
1577
1578         for (i = 0; i < ARRAY_SIZE(lu_keys); ++i)
1579                 key_fini(ctx, i);
1580
1581         OBD_FREE(ctx->lc_value, ARRAY_SIZE(lu_keys) * sizeof ctx->lc_value[0]);
1582         ctx->lc_value = NULL;
1583 }
1584
1585 static int keys_fill(struct lu_context *ctx)
1586 {
1587         int i;
1588
1589         LINVRNT(ctx->lc_value != NULL);
1590         for (i = 0; i < ARRAY_SIZE(lu_keys); ++i) {
1591                 struct lu_context_key *key;
1592
1593                 key = lu_keys[i];
1594                 if (ctx->lc_value[i] == NULL && key != NULL &&
1595                     (key->lct_tags & ctx->lc_tags) &&
1596                     /*
1597                      * Don't create values for a LCT_QUIESCENT key, as this
1598                      * will pin module owning a key.
1599                      */
1600                     !(key->lct_tags & LCT_QUIESCENT)) {
1601                         void *value;
1602
1603                         LINVRNT(key->lct_init != NULL);
1604                         LINVRNT(key->lct_index == i);
1605
1606                         value = key->lct_init(ctx, key);
1607                         if (unlikely(IS_ERR(value)))
1608                                 return PTR_ERR(value);
1609
1610                         LASSERT(key->lct_owner != NULL);
1611                         if (!(ctx->lc_tags & LCT_NOREF))
1612                                 cfs_try_module_get(key->lct_owner);
1613                         lu_ref_add_atomic(&key->lct_reference, "ctx", ctx);
1614                         cfs_atomic_inc(&key->lct_used);
1615                         /*
1616                          * This is the only place in the code, where an
1617                          * element of ctx->lc_value[] array is set to non-NULL
1618                          * value.
1619                          */
1620                         ctx->lc_value[i] = value;
1621                         if (key->lct_exit != NULL)
1622                                 ctx->lc_tags |= LCT_HAS_EXIT;
1623                 }
1624                 ctx->lc_version = key_set_version;
1625         }
1626         return 0;
1627 }
1628
1629 static int keys_init(struct lu_context *ctx)
1630 {
1631         OBD_ALLOC(ctx->lc_value, ARRAY_SIZE(lu_keys) * sizeof ctx->lc_value[0]);
1632         if (likely(ctx->lc_value != NULL))
1633                 return keys_fill(ctx);
1634
1635         return -ENOMEM;
1636 }
1637
1638 /**
1639  * Initialize context data-structure. Create values for all keys.
1640  */
1641 int lu_context_init(struct lu_context *ctx, __u32 tags)
1642 {
1643         int     rc;
1644
1645         memset(ctx, 0, sizeof *ctx);
1646         ctx->lc_state = LCS_INITIALIZED;
1647         ctx->lc_tags = tags;
1648         if (tags & LCT_REMEMBER) {
1649                 spin_lock(&lu_keys_guard);
1650                 cfs_list_add(&ctx->lc_remember, &lu_context_remembered);
1651                 spin_unlock(&lu_keys_guard);
1652         } else {
1653                 CFS_INIT_LIST_HEAD(&ctx->lc_remember);
1654         }
1655
1656         rc = keys_init(ctx);
1657         if (rc != 0)
1658                 lu_context_fini(ctx);
1659
1660         return rc;
1661 }
1662 EXPORT_SYMBOL(lu_context_init);
1663
1664 /**
1665  * Finalize context data-structure. Destroy key values.
1666  */
1667 void lu_context_fini(struct lu_context *ctx)
1668 {
1669         LINVRNT(ctx->lc_state == LCS_INITIALIZED || ctx->lc_state == LCS_LEFT);
1670         ctx->lc_state = LCS_FINALIZED;
1671
1672         if ((ctx->lc_tags & LCT_REMEMBER) == 0) {
1673                 LASSERT(cfs_list_empty(&ctx->lc_remember));
1674                 keys_fini(ctx);
1675
1676         } else { /* could race with key degister */
1677                 spin_lock(&lu_keys_guard);
1678                 keys_fini(ctx);
1679                 cfs_list_del_init(&ctx->lc_remember);
1680                 spin_unlock(&lu_keys_guard);
1681         }
1682 }
1683 EXPORT_SYMBOL(lu_context_fini);
1684
1685 /**
1686  * Called before entering context.
1687  */
1688 void lu_context_enter(struct lu_context *ctx)
1689 {
1690         LINVRNT(ctx->lc_state == LCS_INITIALIZED || ctx->lc_state == LCS_LEFT);
1691         ctx->lc_state = LCS_ENTERED;
1692 }
1693 EXPORT_SYMBOL(lu_context_enter);
1694
1695 /**
1696  * Called after exiting from \a ctx
1697  */
1698 void lu_context_exit(struct lu_context *ctx)
1699 {
1700         int i;
1701
1702         LINVRNT(ctx->lc_state == LCS_ENTERED);
1703         ctx->lc_state = LCS_LEFT;
1704         if (ctx->lc_tags & LCT_HAS_EXIT && ctx->lc_value != NULL) {
1705                 for (i = 0; i < ARRAY_SIZE(lu_keys); ++i) {
1706                         if (ctx->lc_value[i] != NULL) {
1707                                 struct lu_context_key *key;
1708
1709                                 key = lu_keys[i];
1710                                 LASSERT(key != NULL);
1711                                 if (key->lct_exit != NULL)
1712                                         key->lct_exit(ctx,
1713                                                       key, ctx->lc_value[i]);
1714                         }
1715                 }
1716         }
1717 }
1718 EXPORT_SYMBOL(lu_context_exit);
1719
1720 /**
1721  * Allocate for context all missing keys that were registered after context
1722  * creation. key_set_version is only changed in rare cases when modules
1723  * are loaded and removed.
1724  */
1725 int lu_context_refill(struct lu_context *ctx)
1726 {
1727         return likely(ctx->lc_version == key_set_version) ? 0 : keys_fill(ctx);
1728 }
1729 EXPORT_SYMBOL(lu_context_refill);
1730
1731 /**
1732  * lu_ctx_tags/lu_ses_tags will be updated if there are new types of
1733  * obd being added. Currently, this is only used on client side, specifically
1734  * for echo device client, for other stack (like ptlrpc threads), context are
1735  * predefined when the lu_device type are registered, during the module probe
1736  * phase.
1737  */
1738 __u32 lu_context_tags_default = 0;
1739 __u32 lu_session_tags_default = 0;
1740
1741 void lu_context_tags_update(__u32 tags)
1742 {
1743         spin_lock(&lu_keys_guard);
1744         lu_context_tags_default |= tags;
1745         key_set_version++;
1746         spin_unlock(&lu_keys_guard);
1747 }
1748 EXPORT_SYMBOL(lu_context_tags_update);
1749
1750 void lu_context_tags_clear(__u32 tags)
1751 {
1752         spin_lock(&lu_keys_guard);
1753         lu_context_tags_default &= ~tags;
1754         key_set_version++;
1755         spin_unlock(&lu_keys_guard);
1756 }
1757 EXPORT_SYMBOL(lu_context_tags_clear);
1758
1759 void lu_session_tags_update(__u32 tags)
1760 {
1761         spin_lock(&lu_keys_guard);
1762         lu_session_tags_default |= tags;
1763         key_set_version++;
1764         spin_unlock(&lu_keys_guard);
1765 }
1766 EXPORT_SYMBOL(lu_session_tags_update);
1767
1768 void lu_session_tags_clear(__u32 tags)
1769 {
1770         spin_lock(&lu_keys_guard);
1771         lu_session_tags_default &= ~tags;
1772         key_set_version++;
1773         spin_unlock(&lu_keys_guard);
1774 }
1775 EXPORT_SYMBOL(lu_session_tags_clear);
1776
1777 int lu_env_init(struct lu_env *env, __u32 tags)
1778 {
1779         int result;
1780
1781         env->le_ses = NULL;
1782         result = lu_context_init(&env->le_ctx, tags);
1783         if (likely(result == 0))
1784                 lu_context_enter(&env->le_ctx);
1785         return result;
1786 }
1787 EXPORT_SYMBOL(lu_env_init);
1788
1789 void lu_env_fini(struct lu_env *env)
1790 {
1791         lu_context_exit(&env->le_ctx);
1792         lu_context_fini(&env->le_ctx);
1793         env->le_ses = NULL;
1794 }
1795 EXPORT_SYMBOL(lu_env_fini);
1796
1797 int lu_env_refill(struct lu_env *env)
1798 {
1799         int result;
1800
1801         result = lu_context_refill(&env->le_ctx);
1802         if (result == 0 && env->le_ses != NULL)
1803                 result = lu_context_refill(env->le_ses);
1804         return result;
1805 }
1806 EXPORT_SYMBOL(lu_env_refill);
1807
1808 /**
1809  * Currently, this API will only be used by echo client.
1810  * Because echo client and normal lustre client will share
1811  * same cl_env cache. So echo client needs to refresh
1812  * the env context after it get one from the cache, especially
1813  * when normal client and echo client co-exist in the same client.
1814  */
1815 int lu_env_refill_by_tags(struct lu_env *env, __u32 ctags,
1816                           __u32 stags)
1817 {
1818         int    result;
1819
1820         if ((env->le_ctx.lc_tags & ctags) != ctags) {
1821                 env->le_ctx.lc_version = 0;
1822                 env->le_ctx.lc_tags |= ctags;
1823         }
1824
1825         if (env->le_ses && (env->le_ses->lc_tags & stags) != stags) {
1826                 env->le_ses->lc_version = 0;
1827                 env->le_ses->lc_tags |= stags;
1828         }
1829
1830         result = lu_env_refill(env);
1831
1832         return result;
1833 }
1834 EXPORT_SYMBOL(lu_env_refill_by_tags);
1835
1836 static struct shrinker *lu_site_shrinker;
1837
1838 typedef struct lu_site_stats{
1839         unsigned        lss_populated;
1840         unsigned        lss_max_search;
1841         unsigned        lss_total;
1842         unsigned        lss_busy;
1843 } lu_site_stats_t;
1844
1845 static void lu_site_stats_get(cfs_hash_t *hs,
1846                               lu_site_stats_t *stats, int populated)
1847 {
1848         cfs_hash_bd_t bd;
1849         int           i;
1850
1851         cfs_hash_for_each_bucket(hs, &bd, i) {
1852                 struct lu_site_bkt_data *bkt = cfs_hash_bd_extra_get(hs, &bd);
1853                 cfs_hlist_head_t        *hhead;
1854
1855                 cfs_hash_bd_lock(hs, &bd, 1);
1856                 stats->lss_busy  += bkt->lsb_busy;
1857                 stats->lss_total += cfs_hash_bd_count_get(&bd);
1858                 stats->lss_max_search = max((int)stats->lss_max_search,
1859                                             cfs_hash_bd_depmax_get(&bd));
1860                 if (!populated) {
1861                         cfs_hash_bd_unlock(hs, &bd, 1);
1862                         continue;
1863                 }
1864
1865                 cfs_hash_bd_for_each_hlist(hs, &bd, hhead) {
1866                         if (!cfs_hlist_empty(hhead))
1867                                 stats->lss_populated++;
1868                 }
1869                 cfs_hash_bd_unlock(hs, &bd, 1);
1870         }
1871 }
1872
1873 #ifdef __KERNEL__
1874
1875 /*
1876  * There exists a potential lock inversion deadlock scenario when using
1877  * Lustre on top of ZFS. This occurs between one of ZFS's
1878  * buf_hash_table.ht_lock's, and Lustre's lu_sites_guard lock. Essentially,
1879  * thread A will take the lu_sites_guard lock and sleep on the ht_lock,
1880  * while thread B will take the ht_lock and sleep on the lu_sites_guard
1881  * lock. Obviously neither thread will wake and drop their respective hold
1882  * on their lock.
1883  *
1884  * To prevent this from happening we must ensure the lu_sites_guard lock is
1885  * not taken while down this code path. ZFS reliably does not set the
1886  * __GFP_FS bit in its code paths, so this can be used to determine if it
1887  * is safe to take the lu_sites_guard lock.
1888  *
1889  * Ideally we should accurately return the remaining number of cached
1890  * objects without taking the  lu_sites_guard lock, but this is not
1891  * possible in the current implementation.
1892  */
1893 static int lu_cache_shrink(SHRINKER_ARGS(sc, nr_to_scan, gfp_mask))
1894 {
1895         lu_site_stats_t stats;
1896         struct lu_site *s;
1897         struct lu_site *tmp;
1898         int cached = 0;
1899         int remain = shrink_param(sc, nr_to_scan);
1900         CFS_LIST_HEAD(splice);
1901
1902         if (!(shrink_param(sc, gfp_mask) & __GFP_FS)) {
1903                 if (remain != 0)
1904                         return -1;
1905                 else
1906                         /* We must not take the lu_sites_guard lock when
1907                          * __GFP_FS is *not* set because of the deadlock
1908                          * possibility detailed above. Additionally,
1909                          * since we cannot determine the number of
1910                          * objects in the cache without taking this
1911                          * lock, we're in a particularly tough spot. As
1912                          * a result, we'll just lie and say our cache is
1913                          * empty. This _should_ be ok, as we can't
1914                          * reclaim objects when __GFP_FS is *not* set
1915                          * anyways.
1916                          */
1917                         return 0;
1918         }
1919
1920         CDEBUG(D_INODE, "Shrink %d objects\n", remain);
1921
1922         mutex_lock(&lu_sites_guard);
1923         cfs_list_for_each_entry_safe(s, tmp, &lu_sites, ls_linkage) {
1924                 if (shrink_param(sc, nr_to_scan) != 0) {
1925                         remain = lu_site_purge(&lu_shrink_env, s, remain);
1926                         /*
1927                          * Move just shrunk site to the tail of site list to
1928                          * assure shrinking fairness.
1929                          */
1930                         cfs_list_move_tail(&s->ls_linkage, &splice);
1931                 }
1932
1933                 memset(&stats, 0, sizeof(stats));
1934                 lu_site_stats_get(s->ls_obj_hash, &stats, 0);
1935                 cached += stats.lss_total - stats.lss_busy;
1936                 if (shrink_param(sc, nr_to_scan) && remain <= 0)
1937                         break;
1938         }
1939         cfs_list_splice(&splice, lu_sites.prev);
1940         mutex_unlock(&lu_sites_guard);
1941
1942         cached = (cached / 100) * sysctl_vfs_cache_pressure;
1943         if (shrink_param(sc, nr_to_scan) == 0)
1944                 CDEBUG(D_INODE, "%d objects cached\n", cached);
1945         return cached;
1946 }
1947
1948 /*
1949  * Debugging stuff.
1950  */
1951
1952 /**
1953  * Environment to be used in debugger, contains all tags.
1954  */
1955 struct lu_env lu_debugging_env;
1956
1957 /**
1958  * Debugging printer function using printk().
1959  */
1960 int lu_printk_printer(const struct lu_env *env,
1961                       void *unused, const char *format, ...)
1962 {
1963         va_list args;
1964
1965         va_start(args, format);
1966         vprintk(format, args);
1967         va_end(args);
1968         return 0;
1969 }
1970
1971 int lu_debugging_setup(void)
1972 {
1973         return lu_env_init(&lu_debugging_env, ~0);
1974 }
1975
1976 void lu_context_keys_dump(void)
1977 {
1978         int i;
1979
1980         for (i = 0; i < ARRAY_SIZE(lu_keys); ++i) {
1981                 struct lu_context_key *key;
1982
1983                 key = lu_keys[i];
1984                 if (key != NULL) {
1985                         CERROR("[%d]: %p %x (%p,%p,%p) %d %d \"%s\"@%p\n",
1986                                i, key, key->lct_tags,
1987                                key->lct_init, key->lct_fini, key->lct_exit,
1988                                key->lct_index, cfs_atomic_read(&key->lct_used),
1989                                key->lct_owner ? key->lct_owner->name : "",
1990                                key->lct_owner);
1991                         lu_ref_print(&key->lct_reference);
1992                 }
1993         }
1994 }
1995 EXPORT_SYMBOL(lu_context_keys_dump);
1996 #else  /* !__KERNEL__ */
1997 static int lu_cache_shrink(int nr, unsigned int gfp_mask)
1998 {
1999         return 0;
2000 }
2001 #endif /* __KERNEL__ */
2002
2003 /**
2004  * Initialization of global lu_* data.
2005  */
2006 int lu_global_init(void)
2007 {
2008         int result;
2009
2010         CDEBUG(D_INFO, "Lustre LU module (%p).\n", &lu_keys);
2011
2012         result = lu_ref_global_init();
2013         if (result != 0)
2014                 return result;
2015
2016         LU_CONTEXT_KEY_INIT(&lu_global_key);
2017         result = lu_context_key_register(&lu_global_key);
2018         if (result != 0)
2019                 return result;
2020
2021         /*
2022          * At this level, we don't know what tags are needed, so allocate them
2023          * conservatively. This should not be too bad, because this
2024          * environment is global.
2025          */
2026         mutex_lock(&lu_sites_guard);
2027         result = lu_env_init(&lu_shrink_env, LCT_SHRINKER);
2028         mutex_unlock(&lu_sites_guard);
2029         if (result != 0)
2030                 return result;
2031
2032         /*
2033          * seeks estimation: 3 seeks to read a record from oi, one to read
2034          * inode, one for ea. Unfortunately setting this high value results in
2035          * lu_object/inode cache consuming all the memory.
2036          */
2037         lu_site_shrinker = set_shrinker(DEFAULT_SEEKS, lu_cache_shrink);
2038         if (lu_site_shrinker == NULL)
2039                 return -ENOMEM;
2040
2041         return result;
2042 }
2043
2044 /**
2045  * Dual to lu_global_init().
2046  */
2047 void lu_global_fini(void)
2048 {
2049         if (lu_site_shrinker != NULL) {
2050                 remove_shrinker(lu_site_shrinker);
2051                 lu_site_shrinker = NULL;
2052         }
2053
2054         lu_context_key_degister(&lu_global_key);
2055
2056         /*
2057          * Tear shrinker environment down _after_ de-registering
2058          * lu_global_key, because the latter has a value in the former.
2059          */
2060         mutex_lock(&lu_sites_guard);
2061         lu_env_fini(&lu_shrink_env);
2062         mutex_unlock(&lu_sites_guard);
2063
2064         lu_ref_global_fini();
2065 }
2066
2067 static __u32 ls_stats_read(struct lprocfs_stats *stats, int idx)
2068 {
2069 #ifdef LPROCFS
2070         struct lprocfs_counter ret;
2071
2072         lprocfs_stats_collect(stats, idx, &ret);
2073         return (__u32)ret.lc_count;
2074 #else
2075         return 0;
2076 #endif
2077 }
2078
2079 /**
2080  * Output site statistical counters into a buffer. Suitable for
2081  * lprocfs_rd_*()-style functions.
2082  */
2083 int lu_site_stats_print(const struct lu_site *s, char *page, int count)
2084 {
2085         lu_site_stats_t stats;
2086
2087         memset(&stats, 0, sizeof(stats));
2088         lu_site_stats_get(s->ls_obj_hash, &stats, 1);
2089
2090         return snprintf(page, count, "%d/%d %d/%d %d %d %d %d %d %d %d\n",
2091                         stats.lss_busy,
2092                         stats.lss_total,
2093                         stats.lss_populated,
2094                         CFS_HASH_NHLIST(s->ls_obj_hash),
2095                         stats.lss_max_search,
2096                         ls_stats_read(s->ls_stats, LU_SS_CREATED),
2097                         ls_stats_read(s->ls_stats, LU_SS_CACHE_HIT),
2098                         ls_stats_read(s->ls_stats, LU_SS_CACHE_MISS),
2099                         ls_stats_read(s->ls_stats, LU_SS_CACHE_RACE),
2100                         ls_stats_read(s->ls_stats, LU_SS_CACHE_DEATH_RACE),
2101                         ls_stats_read(s->ls_stats, LU_SS_LRU_PURGED));
2102 }
2103 EXPORT_SYMBOL(lu_site_stats_print);
2104
2105 /**
2106  * Helper function to initialize a number of kmem slab caches at once.
2107  */
2108 int lu_kmem_init(struct lu_kmem_descr *caches)
2109 {
2110         int result;
2111         struct lu_kmem_descr *iter = caches;
2112
2113         for (result = 0; iter->ckd_cache != NULL; ++iter) {
2114                 *iter->ckd_cache = kmem_cache_create(iter->ckd_name,
2115                                                      iter->ckd_size,
2116                                                      0, 0, NULL);
2117                 if (*iter->ckd_cache == NULL) {
2118                         result = -ENOMEM;
2119                         /* free all previously allocated caches */
2120                         lu_kmem_fini(caches);
2121                         break;
2122                 }
2123         }
2124         return result;
2125 }
2126 EXPORT_SYMBOL(lu_kmem_init);
2127
2128 /**
2129  * Helper function to finalize a number of kmem slab cached at once. Dual to
2130  * lu_kmem_init().
2131  */
2132 void lu_kmem_fini(struct lu_kmem_descr *caches)
2133 {
2134         for (; caches->ckd_cache != NULL; ++caches) {
2135                 if (*caches->ckd_cache != NULL) {
2136                         kmem_cache_destroy(*caches->ckd_cache);
2137                         *caches->ckd_cache = NULL;
2138                 }
2139         }
2140 }
2141 EXPORT_SYMBOL(lu_kmem_fini);
2142
2143 /**
2144  * Temporary solution to be able to assign fid in ->do_create()
2145  * till we have fully-functional OST fids
2146  */
2147 void lu_object_assign_fid(const struct lu_env *env, struct lu_object *o,
2148                           const struct lu_fid *fid)
2149 {
2150         struct lu_site          *s = o->lo_dev->ld_site;
2151         struct lu_fid           *old = &o->lo_header->loh_fid;
2152         struct lu_site_bkt_data *bkt;
2153         struct lu_object        *shadow;
2154         cfs_waitlink_t           waiter;
2155         cfs_hash_t              *hs;
2156         cfs_hash_bd_t            bd;
2157         __u64                    version = 0;
2158
2159         LASSERT(fid_is_zero(old));
2160
2161         hs = s->ls_obj_hash;
2162         cfs_hash_bd_get_and_lock(hs, (void *)fid, &bd, 1);
2163         shadow = htable_lookup(s, &bd, fid, &waiter, &version);
2164         /* supposed to be unique */
2165         LASSERT(IS_ERR(shadow) && PTR_ERR(shadow) == -ENOENT);
2166         *old = *fid;
2167         bkt = cfs_hash_bd_extra_get(hs, &bd);
2168         cfs_hash_bd_add_locked(hs, &bd, &o->lo_header->loh_hash);
2169         bkt->lsb_busy++;
2170         cfs_hash_bd_unlock(hs, &bd, 1);
2171 }
2172 EXPORT_SYMBOL(lu_object_assign_fid);
2173
2174 /**
2175  * allocates object with 0 (non-assiged) fid
2176  * XXX: temporary solution to be able to assign fid in ->do_create()
2177  *      till we have fully-functional OST fids
2178  */
2179 struct lu_object *lu_object_anon(const struct lu_env *env,
2180                                  struct lu_device *dev,
2181                                  const struct lu_object_conf *conf)
2182 {
2183         struct lu_fid     fid;
2184         struct lu_object *o;
2185
2186         fid_zero(&fid);
2187         o = lu_object_alloc(env, dev, &fid, conf);
2188
2189         return o;
2190 }
2191 EXPORT_SYMBOL(lu_object_anon);
2192
2193 struct lu_buf LU_BUF_NULL = {
2194         .lb_buf = NULL,
2195         .lb_len = 0
2196 };
2197 EXPORT_SYMBOL(LU_BUF_NULL);
2198
2199 void lu_buf_free(struct lu_buf *buf)
2200 {
2201         LASSERT(buf);
2202         if (buf->lb_buf) {
2203                 LASSERT(buf->lb_len > 0);
2204                 OBD_FREE_LARGE(buf->lb_buf, buf->lb_len);
2205                 buf->lb_buf = NULL;
2206                 buf->lb_len = 0;
2207         }
2208 }
2209 EXPORT_SYMBOL(lu_buf_free);
2210
2211 void lu_buf_alloc(struct lu_buf *buf, int size)
2212 {
2213         LASSERT(buf);
2214         LASSERT(buf->lb_buf == NULL);
2215         LASSERT(buf->lb_len == 0);
2216         OBD_ALLOC_LARGE(buf->lb_buf, size);
2217         if (likely(buf->lb_buf))
2218                 buf->lb_len = size;
2219 }
2220 EXPORT_SYMBOL(lu_buf_alloc);
2221
2222 void lu_buf_realloc(struct lu_buf *buf, int size)
2223 {
2224         lu_buf_free(buf);
2225         lu_buf_alloc(buf, size);
2226 }
2227 EXPORT_SYMBOL(lu_buf_realloc);
2228
2229 struct lu_buf *lu_buf_check_and_alloc(struct lu_buf *buf, int len)
2230 {
2231         if (buf->lb_buf == NULL && buf->lb_len == 0)
2232                 lu_buf_alloc(buf, len);
2233
2234         if ((len > buf->lb_len) && (buf->lb_buf != NULL))
2235                 lu_buf_realloc(buf, len);
2236
2237         return buf;
2238 }
2239 EXPORT_SYMBOL(lu_buf_check_and_alloc);
2240
2241 /**
2242  * Increase the size of the \a buf.
2243  * preserves old data in buffer
2244  * old buffer remains unchanged on error
2245  * \retval 0 or -ENOMEM
2246  */
2247 int lu_buf_check_and_grow(struct lu_buf *buf, int len)
2248 {
2249         char *ptr;
2250
2251         if (len <= buf->lb_len)
2252                 return 0;
2253
2254         OBD_ALLOC_LARGE(ptr, len);
2255         if (ptr == NULL)
2256                 return -ENOMEM;
2257
2258         /* Free the old buf */
2259         if (buf->lb_buf != NULL) {
2260                 memcpy(ptr, buf->lb_buf, buf->lb_len);
2261                 OBD_FREE_LARGE(buf->lb_buf, buf->lb_len);
2262         }
2263
2264         buf->lb_buf = ptr;
2265         buf->lb_len = len;
2266         return 0;
2267 }
2268 EXPORT_SYMBOL(lu_buf_check_and_grow);
2269