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