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