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