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