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