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