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