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