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