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