Whamcloud - gitweb
296564f2fff7ccbb82dc06339c24551957162246
[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, 2016, 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         atomic_dec(&lu_key_initing_cnt);
1670         read_unlock(&lu_keys_guard);
1671         return 0;
1672 }
1673
1674 static int keys_init(struct lu_context *ctx)
1675 {
1676         OBD_ALLOC(ctx->lc_value, ARRAY_SIZE(lu_keys) * sizeof ctx->lc_value[0]);
1677         if (likely(ctx->lc_value != NULL))
1678                 return keys_fill(ctx);
1679
1680         return -ENOMEM;
1681 }
1682
1683 /**
1684  * Initialize context data-structure. Create values for all keys.
1685  */
1686 int lu_context_init(struct lu_context *ctx, __u32 tags)
1687 {
1688         int     rc;
1689
1690         memset(ctx, 0, sizeof *ctx);
1691         ctx->lc_state = LCS_INITIALIZED;
1692         ctx->lc_tags = tags;
1693         if (tags & LCT_REMEMBER) {
1694                 write_lock(&lu_keys_guard);
1695                 list_add(&ctx->lc_remember, &lu_context_remembered);
1696                 write_unlock(&lu_keys_guard);
1697         } else {
1698                 INIT_LIST_HEAD(&ctx->lc_remember);
1699         }
1700
1701         rc = keys_init(ctx);
1702         if (rc != 0)
1703                 lu_context_fini(ctx);
1704
1705         return rc;
1706 }
1707 EXPORT_SYMBOL(lu_context_init);
1708
1709 /**
1710  * Finalize context data-structure. Destroy key values.
1711  */
1712 void lu_context_fini(struct lu_context *ctx)
1713 {
1714         LINVRNT(ctx->lc_state == LCS_INITIALIZED || ctx->lc_state == LCS_LEFT);
1715         ctx->lc_state = LCS_FINALIZED;
1716
1717         if ((ctx->lc_tags & LCT_REMEMBER) == 0) {
1718                 LASSERT(list_empty(&ctx->lc_remember));
1719                 keys_fini(ctx);
1720
1721         } else { /* could race with key degister */
1722                 write_lock(&lu_keys_guard);
1723                 keys_fini(ctx);
1724                 list_del_init(&ctx->lc_remember);
1725                 write_unlock(&lu_keys_guard);
1726         }
1727 }
1728 EXPORT_SYMBOL(lu_context_fini);
1729
1730 /**
1731  * Called before entering context.
1732  */
1733 void lu_context_enter(struct lu_context *ctx)
1734 {
1735         LINVRNT(ctx->lc_state == LCS_INITIALIZED || ctx->lc_state == LCS_LEFT);
1736         ctx->lc_state = LCS_ENTERED;
1737 }
1738 EXPORT_SYMBOL(lu_context_enter);
1739
1740 /**
1741  * Called after exiting from \a ctx
1742  */
1743 void lu_context_exit(struct lu_context *ctx)
1744 {
1745         unsigned int i;
1746
1747         LINVRNT(ctx->lc_state == LCS_ENTERED);
1748         ctx->lc_state = LCS_LEFT;
1749         if (ctx->lc_tags & LCT_HAS_EXIT && ctx->lc_value != NULL) {
1750                 /* could race with key quiescency */
1751                 if (ctx->lc_tags & LCT_REMEMBER)
1752                         read_lock(&lu_keys_guard);
1753
1754                 for (i = 0; i < ARRAY_SIZE(lu_keys); ++i) {
1755                         if (ctx->lc_value[i] != NULL) {
1756                                 struct lu_context_key *key;
1757
1758                                 key = lu_keys[i];
1759                                 LASSERT(key != NULL);
1760                                 if (key->lct_exit != NULL)
1761                                         key->lct_exit(ctx,
1762                                                       key, ctx->lc_value[i]);
1763                         }
1764                 }
1765
1766                 if (ctx->lc_tags & LCT_REMEMBER)
1767                         read_unlock(&lu_keys_guard);
1768         }
1769 }
1770 EXPORT_SYMBOL(lu_context_exit);
1771
1772 /**
1773  * Allocate for context all missing keys that were registered after context
1774  * creation. key_set_version is only changed in rare cases when modules
1775  * are loaded and removed.
1776  */
1777 int lu_context_refill(struct lu_context *ctx)
1778 {
1779         return likely(ctx->lc_version == key_set_version) ? 0 : keys_fill(ctx);
1780 }
1781
1782 /**
1783  * lu_ctx_tags/lu_ses_tags will be updated if there are new types of
1784  * obd being added. Currently, this is only used on client side, specifically
1785  * for echo device client, for other stack (like ptlrpc threads), context are
1786  * predefined when the lu_device type are registered, during the module probe
1787  * phase.
1788  */
1789 __u32 lu_context_tags_default = 0;
1790 __u32 lu_session_tags_default = 0;
1791
1792 void lu_context_tags_update(__u32 tags)
1793 {
1794         write_lock(&lu_keys_guard);
1795         lu_context_tags_default |= tags;
1796         key_set_version++;
1797         write_unlock(&lu_keys_guard);
1798 }
1799 EXPORT_SYMBOL(lu_context_tags_update);
1800
1801 void lu_context_tags_clear(__u32 tags)
1802 {
1803         write_lock(&lu_keys_guard);
1804         lu_context_tags_default &= ~tags;
1805         key_set_version++;
1806         write_unlock(&lu_keys_guard);
1807 }
1808 EXPORT_SYMBOL(lu_context_tags_clear);
1809
1810 void lu_session_tags_update(__u32 tags)
1811 {
1812         write_lock(&lu_keys_guard);
1813         lu_session_tags_default |= tags;
1814         key_set_version++;
1815         write_unlock(&lu_keys_guard);
1816 }
1817 EXPORT_SYMBOL(lu_session_tags_update);
1818
1819 void lu_session_tags_clear(__u32 tags)
1820 {
1821         write_lock(&lu_keys_guard);
1822         lu_session_tags_default &= ~tags;
1823         key_set_version++;
1824         write_unlock(&lu_keys_guard);
1825 }
1826 EXPORT_SYMBOL(lu_session_tags_clear);
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(struct cfs_hash *hs,
1897                               lu_site_stats_t *stats, int populated)
1898 {
1899         struct cfs_hash_bd bd;
1900         unsigned int  i;
1901
1902         cfs_hash_for_each_bucket(hs, &bd, i) {
1903                 struct lu_site_bkt_data *bkt = cfs_hash_bd_extra_get(hs, &bd);
1904                 struct hlist_head       *hhead;
1905
1906                 cfs_hash_bd_lock(hs, &bd, 1);
1907                 stats->lss_busy  +=
1908                         cfs_hash_bd_count_get(&bd) - bkt->lsb_lru_len;
1909                 stats->lss_total += cfs_hash_bd_count_get(&bd);
1910                 stats->lss_max_search = max((int)stats->lss_max_search,
1911                                             cfs_hash_bd_depmax_get(&bd));
1912                 if (!populated) {
1913                         cfs_hash_bd_unlock(hs, &bd, 1);
1914                         continue;
1915                 }
1916
1917                 cfs_hash_bd_for_each_hlist(hs, &bd, hhead) {
1918                         if (!hlist_empty(hhead))
1919                                 stats->lss_populated++;
1920                 }
1921                 cfs_hash_bd_unlock(hs, &bd, 1);
1922         }
1923 }
1924
1925
1926 /*
1927  * lu_cache_shrink_count() returns an approximate number of cached objects
1928  * that can be freed by shrink_slab(). A counter, which tracks the
1929  * number of items in the site's lru, is maintained in a percpu_counter
1930  * for each site. The percpu values are incremented and decremented as
1931  * objects are added or removed from the lru. The percpu values are summed
1932  * and saved whenever a percpu value exceeds a threshold. Thus the saved,
1933  * summed value at any given time may not accurately reflect the current
1934  * lru length. But this value is sufficiently accurate for the needs of
1935  * a shrinker.
1936  *
1937  * Using a per cpu counter is a compromise solution to concurrent access:
1938  * lu_object_put() can update the counter without locking the site and
1939  * lu_cache_shrink_count can sum the counters without locking each
1940  * ls_obj_hash bucket.
1941  */
1942 static unsigned long lu_cache_shrink_count(struct shrinker *sk,
1943                                            struct shrink_control *sc)
1944 {
1945         struct lu_site *s;
1946         struct lu_site *tmp;
1947         unsigned long cached = 0;
1948
1949         if (!(sc->gfp_mask & __GFP_FS))
1950                 return 0;
1951
1952         down_read(&lu_sites_guard);
1953         list_for_each_entry_safe(s, tmp, &lu_sites, ls_linkage)
1954                 cached += percpu_counter_read_positive(&s->ls_lru_len_counter);
1955         up_read(&lu_sites_guard);
1956
1957         cached = (cached / 100) * sysctl_vfs_cache_pressure;
1958         CDEBUG(D_INODE, "%ld objects cached, cache pressure %d\n",
1959                cached, sysctl_vfs_cache_pressure);
1960
1961         return cached;
1962 }
1963
1964 static unsigned long lu_cache_shrink_scan(struct shrinker *sk,
1965                                           struct shrink_control *sc)
1966 {
1967         struct lu_site *s;
1968         struct lu_site *tmp;
1969         unsigned long remain = sc->nr_to_scan;
1970         LIST_HEAD(splice);
1971
1972         if (!(sc->gfp_mask & __GFP_FS))
1973                 /* We must not take the lu_sites_guard lock when
1974                  * __GFP_FS is *not* set because of the deadlock
1975                  * possibility detailed above. Additionally,
1976                  * since we cannot determine the number of
1977                  * objects in the cache without taking this
1978                  * lock, we're in a particularly tough spot. As
1979                  * a result, we'll just lie and say our cache is
1980                  * empty. This _should_ be ok, as we can't
1981                  * reclaim objects when __GFP_FS is *not* set
1982                  * anyways.
1983                  */
1984                 return SHRINK_STOP;
1985
1986         down_write(&lu_sites_guard);
1987         list_for_each_entry_safe(s, tmp, &lu_sites, ls_linkage) {
1988                 remain = lu_site_purge(&lu_shrink_env, s, remain);
1989                 /*
1990                  * Move just shrunk site to the tail of site list to
1991                  * assure shrinking fairness.
1992                  */
1993                 list_move_tail(&s->ls_linkage, &splice);
1994         }
1995         list_splice(&splice, lu_sites.prev);
1996         up_write(&lu_sites_guard);
1997
1998         return sc->nr_to_scan - remain;
1999 }
2000
2001 #ifndef HAVE_SHRINKER_COUNT
2002 /*
2003  * There exists a potential lock inversion deadlock scenario when using
2004  * Lustre on top of ZFS. This occurs between one of ZFS's
2005  * buf_hash_table.ht_lock's, and Lustre's lu_sites_guard lock. Essentially,
2006  * thread A will take the lu_sites_guard lock and sleep on the ht_lock,
2007  * while thread B will take the ht_lock and sleep on the lu_sites_guard
2008  * lock. Obviously neither thread will wake and drop their respective hold
2009  * on their lock.
2010  *
2011  * To prevent this from happening we must ensure the lu_sites_guard lock is
2012  * not taken while down this code path. ZFS reliably does not set the
2013  * __GFP_FS bit in its code paths, so this can be used to determine if it
2014  * is safe to take the lu_sites_guard lock.
2015  *
2016  * Ideally we should accurately return the remaining number of cached
2017  * objects without taking the lu_sites_guard lock, but this is not
2018  * possible in the current implementation.
2019  */
2020 static int lu_cache_shrink(SHRINKER_ARGS(sc, nr_to_scan, gfp_mask))
2021 {
2022         int cached = 0;
2023         struct shrink_control scv = {
2024                  .nr_to_scan = shrink_param(sc, nr_to_scan),
2025                  .gfp_mask   = shrink_param(sc, gfp_mask)
2026         };
2027 #if !defined(HAVE_SHRINKER_WANT_SHRINK_PTR) && !defined(HAVE_SHRINK_CONTROL)
2028         struct shrinker* shrinker = NULL;
2029 #endif
2030
2031
2032         CDEBUG(D_INODE, "Shrink %lu objects\n", scv.nr_to_scan);
2033
2034         if (scv.nr_to_scan != 0)
2035                 lu_cache_shrink_scan(shrinker, &scv);
2036
2037         cached = lu_cache_shrink_count(shrinker, &scv);
2038         return cached;
2039 }
2040
2041 #endif /* HAVE_SHRINKER_COUNT */
2042
2043
2044 /*
2045  * Debugging stuff.
2046  */
2047
2048 /**
2049  * Environment to be used in debugger, contains all tags.
2050  */
2051 static struct lu_env lu_debugging_env;
2052
2053 /**
2054  * Debugging printer function using printk().
2055  */
2056 int lu_printk_printer(const struct lu_env *env,
2057                       void *unused, const char *format, ...)
2058 {
2059         va_list args;
2060
2061         va_start(args, format);
2062         vprintk(format, args);
2063         va_end(args);
2064         return 0;
2065 }
2066
2067 int lu_debugging_setup(void)
2068 {
2069         return lu_env_init(&lu_debugging_env, ~0);
2070 }
2071
2072 void lu_context_keys_dump(void)
2073 {
2074         unsigned int i;
2075
2076         for (i = 0; i < ARRAY_SIZE(lu_keys); ++i) {
2077                 struct lu_context_key *key;
2078
2079                 key = lu_keys[i];
2080                 if (key != NULL) {
2081                         CERROR("[%d]: %p %x (%p,%p,%p) %d %d \"%s\"@%p\n",
2082                                i, key, key->lct_tags,
2083                                key->lct_init, key->lct_fini, key->lct_exit,
2084                                key->lct_index, atomic_read(&key->lct_used),
2085                                key->lct_owner ? key->lct_owner->name : "",
2086                                key->lct_owner);
2087                         lu_ref_print(&key->lct_reference);
2088                 }
2089         }
2090 }
2091
2092 /**
2093  * Initialization of global lu_* data.
2094  */
2095 int lu_global_init(void)
2096 {
2097         int result;
2098         DEF_SHRINKER_VAR(shvar, lu_cache_shrink,
2099                          lu_cache_shrink_count, lu_cache_shrink_scan);
2100
2101         CDEBUG(D_INFO, "Lustre LU module (%p).\n", &lu_keys);
2102
2103         result = lu_ref_global_init();
2104         if (result != 0)
2105                 return result;
2106
2107         LU_CONTEXT_KEY_INIT(&lu_global_key);
2108         result = lu_context_key_register(&lu_global_key);
2109         if (result != 0)
2110                 return result;
2111
2112         /*
2113          * At this level, we don't know what tags are needed, so allocate them
2114          * conservatively. This should not be too bad, because this
2115          * environment is global.
2116          */
2117         down_write(&lu_sites_guard);
2118         result = lu_env_init(&lu_shrink_env, LCT_SHRINKER);
2119         up_write(&lu_sites_guard);
2120         if (result != 0)
2121                 return result;
2122
2123         /*
2124          * seeks estimation: 3 seeks to read a record from oi, one to read
2125          * inode, one for ea. Unfortunately setting this high value results in
2126          * lu_object/inode cache consuming all the memory.
2127          */
2128         lu_site_shrinker = set_shrinker(DEFAULT_SEEKS, &shvar);
2129         if (lu_site_shrinker == NULL)
2130                 return -ENOMEM;
2131
2132         return result;
2133 }
2134
2135 /**
2136  * Dual to lu_global_init().
2137  */
2138 void lu_global_fini(void)
2139 {
2140         if (lu_site_shrinker != NULL) {
2141                 remove_shrinker(lu_site_shrinker);
2142                 lu_site_shrinker = NULL;
2143         }
2144
2145         lu_context_key_degister(&lu_global_key);
2146
2147         /*
2148          * Tear shrinker environment down _after_ de-registering
2149          * lu_global_key, because the latter has a value in the former.
2150          */
2151         down_write(&lu_sites_guard);
2152         lu_env_fini(&lu_shrink_env);
2153         up_write(&lu_sites_guard);
2154
2155         lu_ref_global_fini();
2156 }
2157
2158 static __u32 ls_stats_read(struct lprocfs_stats *stats, int idx)
2159 {
2160 #ifdef CONFIG_PROC_FS
2161         struct lprocfs_counter ret;
2162
2163         lprocfs_stats_collect(stats, idx, &ret);
2164         return (__u32)ret.lc_count;
2165 #else
2166         return 0;
2167 #endif
2168 }
2169
2170 /**
2171  * Output site statistical counters into a buffer. Suitable for
2172  * lprocfs_rd_*()-style functions.
2173  */
2174 int lu_site_stats_seq_print(const struct lu_site *s, struct seq_file *m)
2175 {
2176         lu_site_stats_t stats;
2177
2178         memset(&stats, 0, sizeof(stats));
2179         lu_site_stats_get(s->ls_obj_hash, &stats, 1);
2180
2181         seq_printf(m, "%d/%d %d/%d %d %d %d %d %d %d %d\n",
2182                    stats.lss_busy,
2183                    stats.lss_total,
2184                    stats.lss_populated,
2185                    CFS_HASH_NHLIST(s->ls_obj_hash),
2186                    stats.lss_max_search,
2187                    ls_stats_read(s->ls_stats, LU_SS_CREATED),
2188                    ls_stats_read(s->ls_stats, LU_SS_CACHE_HIT),
2189                    ls_stats_read(s->ls_stats, LU_SS_CACHE_MISS),
2190                    ls_stats_read(s->ls_stats, LU_SS_CACHE_RACE),
2191                    ls_stats_read(s->ls_stats, LU_SS_CACHE_DEATH_RACE),
2192                    ls_stats_read(s->ls_stats, LU_SS_LRU_PURGED));
2193         return 0;
2194 }
2195 EXPORT_SYMBOL(lu_site_stats_seq_print);
2196
2197 /**
2198  * Helper function to initialize a number of kmem slab caches at once.
2199  */
2200 int lu_kmem_init(struct lu_kmem_descr *caches)
2201 {
2202         int result;
2203         struct lu_kmem_descr *iter = caches;
2204
2205         for (result = 0; iter->ckd_cache != NULL; ++iter) {
2206                 *iter->ckd_cache = kmem_cache_create(iter->ckd_name,
2207                                                      iter->ckd_size,
2208                                                      0, 0, NULL);
2209                 if (*iter->ckd_cache == NULL) {
2210                         result = -ENOMEM;
2211                         /* free all previously allocated caches */
2212                         lu_kmem_fini(caches);
2213                         break;
2214                 }
2215         }
2216         return result;
2217 }
2218 EXPORT_SYMBOL(lu_kmem_init);
2219
2220 /**
2221  * Helper function to finalize a number of kmem slab cached at once. Dual to
2222  * lu_kmem_init().
2223  */
2224 void lu_kmem_fini(struct lu_kmem_descr *caches)
2225 {
2226         for (; caches->ckd_cache != NULL; ++caches) {
2227                 if (*caches->ckd_cache != NULL) {
2228                         kmem_cache_destroy(*caches->ckd_cache);
2229                         *caches->ckd_cache = NULL;
2230                 }
2231         }
2232 }
2233 EXPORT_SYMBOL(lu_kmem_fini);
2234
2235 /**
2236  * Temporary solution to be able to assign fid in ->do_create()
2237  * till we have fully-functional OST fids
2238  */
2239 void lu_object_assign_fid(const struct lu_env *env, struct lu_object *o,
2240                           const struct lu_fid *fid)
2241 {
2242         struct lu_site          *s = o->lo_dev->ld_site;
2243         struct lu_fid           *old = &o->lo_header->loh_fid;
2244         struct cfs_hash         *hs;
2245         struct cfs_hash_bd       bd;
2246
2247         LASSERT(fid_is_zero(old));
2248
2249         /* supposed to be unique */
2250         hs = s->ls_obj_hash;
2251         cfs_hash_bd_get_and_lock(hs, (void *)fid, &bd, 1);
2252 #ifdef CONFIG_LUSTRE_DEBUG_EXPENSIVE_CHECK
2253         {
2254                 __u64 version = 0;
2255                 struct lu_object *shadow;
2256
2257                 shadow = htable_lookup(s, &bd, fid, &version);
2258                 /* supposed to be unique */
2259                 LASSERT(IS_ERR(shadow) && PTR_ERR(shadow) == -ENOENT);
2260         }
2261 #endif
2262         *old = *fid;
2263         cfs_hash_bd_add_locked(hs, &bd, &o->lo_header->loh_hash);
2264         cfs_hash_bd_unlock(hs, &bd, 1);
2265 }
2266 EXPORT_SYMBOL(lu_object_assign_fid);
2267
2268 /**
2269  * allocates object with 0 (non-assiged) fid
2270  * XXX: temporary solution to be able to assign fid in ->do_create()
2271  *      till we have fully-functional OST fids
2272  */
2273 struct lu_object *lu_object_anon(const struct lu_env *env,
2274                                  struct lu_device *dev,
2275                                  const struct lu_object_conf *conf)
2276 {
2277         struct lu_fid     fid;
2278         struct lu_object *o;
2279
2280         fid_zero(&fid);
2281         o = lu_object_alloc(env, dev, &fid, conf);
2282
2283         return o;
2284 }
2285 EXPORT_SYMBOL(lu_object_anon);
2286
2287 struct lu_buf LU_BUF_NULL = {
2288         .lb_buf = NULL,
2289         .lb_len = 0
2290 };
2291 EXPORT_SYMBOL(LU_BUF_NULL);
2292
2293 void lu_buf_free(struct lu_buf *buf)
2294 {
2295         LASSERT(buf);
2296         if (buf->lb_buf) {
2297                 LASSERT(buf->lb_len > 0);
2298                 OBD_FREE_LARGE(buf->lb_buf, buf->lb_len);
2299                 buf->lb_buf = NULL;
2300                 buf->lb_len = 0;
2301         }
2302 }
2303 EXPORT_SYMBOL(lu_buf_free);
2304
2305 void lu_buf_alloc(struct lu_buf *buf, size_t size)
2306 {
2307         LASSERT(buf);
2308         LASSERT(buf->lb_buf == NULL);
2309         LASSERT(buf->lb_len == 0);
2310         OBD_ALLOC_LARGE(buf->lb_buf, size);
2311         if (likely(buf->lb_buf))
2312                 buf->lb_len = size;
2313 }
2314 EXPORT_SYMBOL(lu_buf_alloc);
2315
2316 void lu_buf_realloc(struct lu_buf *buf, size_t size)
2317 {
2318         lu_buf_free(buf);
2319         lu_buf_alloc(buf, size);
2320 }
2321 EXPORT_SYMBOL(lu_buf_realloc);
2322
2323 struct lu_buf *lu_buf_check_and_alloc(struct lu_buf *buf, size_t len)
2324 {
2325         if (buf->lb_buf == NULL && buf->lb_len == 0)
2326                 lu_buf_alloc(buf, len);
2327
2328         if ((len > buf->lb_len) && (buf->lb_buf != NULL))
2329                 lu_buf_realloc(buf, len);
2330
2331         return buf;
2332 }
2333 EXPORT_SYMBOL(lu_buf_check_and_alloc);
2334
2335 /**
2336  * Increase the size of the \a buf.
2337  * preserves old data in buffer
2338  * old buffer remains unchanged on error
2339  * \retval 0 or -ENOMEM
2340  */
2341 int lu_buf_check_and_grow(struct lu_buf *buf, size_t len)
2342 {
2343         char *ptr;
2344
2345         if (len <= buf->lb_len)
2346                 return 0;
2347
2348         OBD_ALLOC_LARGE(ptr, len);
2349         if (ptr == NULL)
2350                 return -ENOMEM;
2351
2352         /* Free the old buf */
2353         if (buf->lb_buf != NULL) {
2354                 memcpy(ptr, buf->lb_buf, buf->lb_len);
2355                 OBD_FREE_LARGE(buf->lb_buf, buf->lb_len);
2356         }
2357
2358         buf->lb_buf = ptr;
2359         buf->lb_len = len;
2360         return 0;
2361 }
2362 EXPORT_SYMBOL(lu_buf_check_and_grow);