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