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