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