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