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