Whamcloud - gitweb
LU-11834 llite: fix temporary instance buffer size
[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 atomic_t lu_key_initing_cnt = ATOMIC_INIT(0);
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 unsigned key_set_version = 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                         ++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_set_version;
1419         key_fini(&lu_shrink_env.le_ctx, key->lct_index);
1420
1421         /**
1422          * Wait until all transient contexts referencing this key have
1423          * run lu_context_key::lct_fini() method.
1424          */
1425         while (atomic_read(&key->lct_used) > 1) {
1426                 write_unlock(&lu_keys_guard);
1427                 CDEBUG(D_INFO, "lu_context_key_degister: \"%s\" %p, %d\n",
1428                        key->lct_owner ? key->lct_owner->name : "", key,
1429                        atomic_read(&key->lct_used));
1430                 schedule();
1431                 write_lock(&lu_keys_guard);
1432         }
1433         if (lu_keys[key->lct_index]) {
1434                 lu_keys[key->lct_index] = NULL;
1435                 lu_ref_fini(&key->lct_reference);
1436         }
1437         write_unlock(&lu_keys_guard);
1438
1439         LASSERTF(atomic_read(&key->lct_used) == 1,
1440                  "key has instances: %d\n",
1441                  atomic_read(&key->lct_used));
1442 }
1443 EXPORT_SYMBOL(lu_context_key_degister);
1444
1445 /**
1446  * Register a number of keys. This has to be called after all keys have been
1447  * initialized by a call to LU_CONTEXT_KEY_INIT().
1448  */
1449 int lu_context_key_register_many(struct lu_context_key *k, ...)
1450 {
1451         struct lu_context_key *key = k;
1452         va_list args;
1453         int result;
1454
1455         va_start(args, k);
1456         do {
1457                 result = lu_context_key_register(key);
1458                 if (result)
1459                         break;
1460                 key = va_arg(args, struct lu_context_key *);
1461         } while (key != NULL);
1462         va_end(args);
1463
1464         if (result != 0) {
1465                 va_start(args, k);
1466                 while (k != key) {
1467                         lu_context_key_degister(k);
1468                         k = va_arg(args, struct lu_context_key *);
1469                 }
1470                 va_end(args);
1471         }
1472
1473         return result;
1474 }
1475 EXPORT_SYMBOL(lu_context_key_register_many);
1476
1477 /**
1478  * De-register a number of keys. This is a dual to
1479  * lu_context_key_register_many().
1480  */
1481 void lu_context_key_degister_many(struct lu_context_key *k, ...)
1482 {
1483         va_list args;
1484
1485         va_start(args, k);
1486         do {
1487                 lu_context_key_degister(k);
1488                 k = va_arg(args, struct lu_context_key*);
1489         } while (k != NULL);
1490         va_end(args);
1491 }
1492 EXPORT_SYMBOL(lu_context_key_degister_many);
1493
1494 /**
1495  * Revive a number of keys.
1496  */
1497 void lu_context_key_revive_many(struct lu_context_key *k, ...)
1498 {
1499         va_list args;
1500
1501         va_start(args, k);
1502         do {
1503                 lu_context_key_revive(k);
1504                 k = va_arg(args, struct lu_context_key*);
1505         } while (k != NULL);
1506         va_end(args);
1507 }
1508 EXPORT_SYMBOL(lu_context_key_revive_many);
1509
1510 /**
1511  * Quiescent a number of keys.
1512  */
1513 void lu_context_key_quiesce_many(struct lu_context_key *k, ...)
1514 {
1515         va_list args;
1516
1517         va_start(args, k);
1518         do {
1519                 lu_context_key_quiesce(k);
1520                 k = va_arg(args, struct lu_context_key*);
1521         } while (k != NULL);
1522         va_end(args);
1523 }
1524 EXPORT_SYMBOL(lu_context_key_quiesce_many);
1525
1526 /**
1527  * Return value associated with key \a key in context \a ctx.
1528  */
1529 void *lu_context_key_get(const struct lu_context *ctx,
1530                          const struct lu_context_key *key)
1531 {
1532         LINVRNT(ctx->lc_state == LCS_ENTERED);
1533         LINVRNT(0 <= key->lct_index && key->lct_index < ARRAY_SIZE(lu_keys));
1534         LASSERT(lu_keys[key->lct_index] == key);
1535         return ctx->lc_value[key->lct_index];
1536 }
1537 EXPORT_SYMBOL(lu_context_key_get);
1538
1539 /**
1540  * List of remembered contexts. XXX document me.
1541  */
1542 static LIST_HEAD(lu_context_remembered);
1543
1544 /**
1545  * Destroy \a key in all remembered contexts. This is used to destroy key
1546  * values in "shared" contexts (like service threads), when a module owning
1547  * the key is about to be unloaded.
1548  */
1549 void lu_context_key_quiesce(struct lu_context_key *key)
1550 {
1551         struct lu_context *ctx;
1552
1553         if (!(key->lct_tags & LCT_QUIESCENT)) {
1554                 /*
1555                  * XXX memory barrier has to go here.
1556                  */
1557                 write_lock(&lu_keys_guard);
1558                 key->lct_tags |= LCT_QUIESCENT;
1559
1560                 /**
1561                  * Wait until all lu_context_key::lct_init() methods
1562                  * have completed.
1563                  */
1564                 while (atomic_read(&lu_key_initing_cnt) > 0) {
1565                         write_unlock(&lu_keys_guard);
1566                         CDEBUG(D_INFO, "lu_context_key_quiesce: \"%s\""
1567                                " %p, %d (%d)\n",
1568                                key->lct_owner ? key->lct_owner->name : "",
1569                                key, atomic_read(&key->lct_used),
1570                                atomic_read(&lu_key_initing_cnt));
1571                         schedule();
1572                         write_lock(&lu_keys_guard);
1573                 }
1574
1575                 list_for_each_entry(ctx, &lu_context_remembered,
1576                                     lc_remember)
1577                         key_fini(ctx, key->lct_index);
1578
1579                 ++key_set_version;
1580                 write_unlock(&lu_keys_guard);
1581         }
1582 }
1583
1584 void lu_context_key_revive(struct lu_context_key *key)
1585 {
1586         write_lock(&lu_keys_guard);
1587         key->lct_tags &= ~LCT_QUIESCENT;
1588         ++key_set_version;
1589         write_unlock(&lu_keys_guard);
1590 }
1591
1592 static void keys_fini(struct lu_context *ctx)
1593 {
1594         unsigned int i;
1595
1596         if (ctx->lc_value == NULL)
1597                 return;
1598
1599         for (i = 0; i < ARRAY_SIZE(lu_keys); ++i)
1600                 key_fini(ctx, i);
1601
1602         OBD_FREE(ctx->lc_value, ARRAY_SIZE(lu_keys) * sizeof ctx->lc_value[0]);
1603         ctx->lc_value = NULL;
1604 }
1605
1606 static int keys_fill(struct lu_context *ctx)
1607 {
1608         unsigned int i;
1609         unsigned pre_version;
1610
1611         /*
1612          * A serialisation with lu_context_key_quiesce() is needed, but some
1613          * "key->lct_init()" are calling kernel memory allocation routine and
1614          * can't be called while holding a spin_lock.
1615          * "lu_keys_guard" is held while incrementing "lu_key_initing_cnt"
1616          * to ensure the start of the serialisation.
1617          * An atomic_t variable is still used, in order not to reacquire the
1618          * lock when decrementing the counter.
1619          */
1620         read_lock(&lu_keys_guard);
1621         atomic_inc(&lu_key_initing_cnt);
1622         pre_version = key_set_version;
1623         read_unlock(&lu_keys_guard);
1624
1625 refill:
1626         LINVRNT(ctx->lc_value != NULL);
1627         for (i = 0; i < ARRAY_SIZE(lu_keys); ++i) {
1628                 struct lu_context_key *key;
1629
1630                 key = lu_keys[i];
1631                 if (ctx->lc_value[i] == NULL && key != NULL &&
1632                     (key->lct_tags & ctx->lc_tags) &&
1633                     /*
1634                      * Don't create values for a LCT_QUIESCENT key, as this
1635                      * will pin module owning a key.
1636                      */
1637                     !(key->lct_tags & LCT_QUIESCENT)) {
1638                         void *value;
1639
1640                         LINVRNT(key->lct_init != NULL);
1641                         LINVRNT(key->lct_index == i);
1642
1643                         LASSERT(key->lct_owner != NULL);
1644                         if (!(ctx->lc_tags & LCT_NOREF) &&
1645                             try_module_get(key->lct_owner) == 0) {
1646                                 /* module is unloading, skip this key */
1647                                 continue;
1648                         }
1649
1650                         value = key->lct_init(ctx, key);
1651                         if (unlikely(IS_ERR(value))) {
1652                                 atomic_dec(&lu_key_initing_cnt);
1653                                 return PTR_ERR(value);
1654                         }
1655
1656                         lu_ref_add_atomic(&key->lct_reference, "ctx", ctx);
1657                         atomic_inc(&key->lct_used);
1658                         /*
1659                          * This is the only place in the code, where an
1660                          * element of ctx->lc_value[] array is set to non-NULL
1661                          * value.
1662                          */
1663                         ctx->lc_value[i] = value;
1664                         if (key->lct_exit != NULL)
1665                                 ctx->lc_tags |= LCT_HAS_EXIT;
1666                 }
1667         }
1668
1669         read_lock(&lu_keys_guard);
1670         if (pre_version != key_set_version) {
1671                 pre_version = key_set_version;
1672                 read_unlock(&lu_keys_guard);
1673                 goto refill;
1674         }
1675
1676         ctx->lc_version = key_set_version;
1677
1678         atomic_dec(&lu_key_initing_cnt);
1679         read_unlock(&lu_keys_guard);
1680         return 0;
1681 }
1682
1683 static int keys_init(struct lu_context *ctx)
1684 {
1685         OBD_ALLOC(ctx->lc_value, ARRAY_SIZE(lu_keys) * sizeof ctx->lc_value[0]);
1686         if (likely(ctx->lc_value != NULL))
1687                 return keys_fill(ctx);
1688
1689         return -ENOMEM;
1690 }
1691
1692 /**
1693  * Initialize context data-structure. Create values for all keys.
1694  */
1695 int lu_context_init(struct lu_context *ctx, __u32 tags)
1696 {
1697         int     rc;
1698
1699         memset(ctx, 0, sizeof *ctx);
1700         ctx->lc_state = LCS_INITIALIZED;
1701         ctx->lc_tags = tags;
1702         if (tags & LCT_REMEMBER) {
1703                 write_lock(&lu_keys_guard);
1704                 list_add(&ctx->lc_remember, &lu_context_remembered);
1705                 write_unlock(&lu_keys_guard);
1706         } else {
1707                 INIT_LIST_HEAD(&ctx->lc_remember);
1708         }
1709
1710         rc = keys_init(ctx);
1711         if (rc != 0)
1712                 lu_context_fini(ctx);
1713
1714         return rc;
1715 }
1716 EXPORT_SYMBOL(lu_context_init);
1717
1718 /**
1719  * Finalize context data-structure. Destroy key values.
1720  */
1721 void lu_context_fini(struct lu_context *ctx)
1722 {
1723         LINVRNT(ctx->lc_state == LCS_INITIALIZED || ctx->lc_state == LCS_LEFT);
1724         ctx->lc_state = LCS_FINALIZED;
1725
1726         if ((ctx->lc_tags & LCT_REMEMBER) == 0) {
1727                 LASSERT(list_empty(&ctx->lc_remember));
1728                 keys_fini(ctx);
1729
1730         } else { /* could race with key degister */
1731                 write_lock(&lu_keys_guard);
1732                 keys_fini(ctx);
1733                 list_del_init(&ctx->lc_remember);
1734                 write_unlock(&lu_keys_guard);
1735         }
1736 }
1737 EXPORT_SYMBOL(lu_context_fini);
1738
1739 /**
1740  * Called before entering context.
1741  */
1742 void lu_context_enter(struct lu_context *ctx)
1743 {
1744         LINVRNT(ctx->lc_state == LCS_INITIALIZED || ctx->lc_state == LCS_LEFT);
1745         ctx->lc_state = LCS_ENTERED;
1746 }
1747 EXPORT_SYMBOL(lu_context_enter);
1748
1749 /**
1750  * Called after exiting from \a ctx
1751  */
1752 void lu_context_exit(struct lu_context *ctx)
1753 {
1754         unsigned int i;
1755
1756         LINVRNT(ctx->lc_state == LCS_ENTERED);
1757         ctx->lc_state = LCS_LEFT;
1758         if (ctx->lc_tags & LCT_HAS_EXIT && ctx->lc_value != NULL) {
1759                 /* could race with key quiescency */
1760                 if (ctx->lc_tags & LCT_REMEMBER)
1761                         read_lock(&lu_keys_guard);
1762
1763                 for (i = 0; i < ARRAY_SIZE(lu_keys); ++i) {
1764                         if (ctx->lc_value[i] != NULL) {
1765                                 struct lu_context_key *key;
1766
1767                                 key = lu_keys[i];
1768                                 LASSERT(key != NULL);
1769                                 if (key->lct_exit != NULL)
1770                                         key->lct_exit(ctx,
1771                                                       key, ctx->lc_value[i]);
1772                         }
1773                 }
1774
1775                 if (ctx->lc_tags & LCT_REMEMBER)
1776                         read_unlock(&lu_keys_guard);
1777         }
1778 }
1779 EXPORT_SYMBOL(lu_context_exit);
1780
1781 /**
1782  * Allocate for context all missing keys that were registered after context
1783  * creation. key_set_version is only changed in rare cases when modules
1784  * are loaded and removed.
1785  */
1786 int lu_context_refill(struct lu_context *ctx)
1787 {
1788         read_lock(&lu_keys_guard);
1789         if (likely(ctx->lc_version == key_set_version)) {
1790                 read_unlock(&lu_keys_guard);
1791                 return 0;
1792         }
1793
1794         read_unlock(&lu_keys_guard);
1795         return keys_fill(ctx);
1796 }
1797
1798 /**
1799  * lu_ctx_tags/lu_ses_tags will be updated if there are new types of
1800  * obd being added. Currently, this is only used on client side, specifically
1801  * for echo device client, for other stack (like ptlrpc threads), context are
1802  * predefined when the lu_device type are registered, during the module probe
1803  * phase.
1804  */
1805 __u32 lu_context_tags_default = 0;
1806 __u32 lu_session_tags_default = 0;
1807
1808 void lu_context_tags_update(__u32 tags)
1809 {
1810         write_lock(&lu_keys_guard);
1811         lu_context_tags_default |= tags;
1812         key_set_version++;
1813         write_unlock(&lu_keys_guard);
1814 }
1815 EXPORT_SYMBOL(lu_context_tags_update);
1816
1817 void lu_context_tags_clear(__u32 tags)
1818 {
1819         write_lock(&lu_keys_guard);
1820         lu_context_tags_default &= ~tags;
1821         key_set_version++;
1822         write_unlock(&lu_keys_guard);
1823 }
1824 EXPORT_SYMBOL(lu_context_tags_clear);
1825
1826 void lu_session_tags_update(__u32 tags)
1827 {
1828         write_lock(&lu_keys_guard);
1829         lu_session_tags_default |= tags;
1830         key_set_version++;
1831         write_unlock(&lu_keys_guard);
1832 }
1833 EXPORT_SYMBOL(lu_session_tags_update);
1834
1835 void lu_session_tags_clear(__u32 tags)
1836 {
1837         write_lock(&lu_keys_guard);
1838         lu_session_tags_default &= ~tags;
1839         key_set_version++;
1840         write_unlock(&lu_keys_guard);
1841 }
1842 EXPORT_SYMBOL(lu_session_tags_clear);
1843
1844 int lu_env_init(struct lu_env *env, __u32 tags)
1845 {
1846         int result;
1847
1848         env->le_ses = NULL;
1849         result = lu_context_init(&env->le_ctx, tags);
1850         if (likely(result == 0))
1851                 lu_context_enter(&env->le_ctx);
1852         return result;
1853 }
1854 EXPORT_SYMBOL(lu_env_init);
1855
1856 void lu_env_fini(struct lu_env *env)
1857 {
1858         lu_context_exit(&env->le_ctx);
1859         lu_context_fini(&env->le_ctx);
1860         env->le_ses = NULL;
1861 }
1862 EXPORT_SYMBOL(lu_env_fini);
1863
1864 int lu_env_refill(struct lu_env *env)
1865 {
1866         int result;
1867
1868         result = lu_context_refill(&env->le_ctx);
1869         if (result == 0 && env->le_ses != NULL)
1870                 result = lu_context_refill(env->le_ses);
1871         return result;
1872 }
1873 EXPORT_SYMBOL(lu_env_refill);
1874
1875 /**
1876  * Currently, this API will only be used by echo client.
1877  * Because echo client and normal lustre client will share
1878  * same cl_env cache. So echo client needs to refresh
1879  * the env context after it get one from the cache, especially
1880  * when normal client and echo client co-exist in the same client.
1881  */
1882 int lu_env_refill_by_tags(struct lu_env *env, __u32 ctags,
1883                           __u32 stags)
1884 {
1885         int    result;
1886
1887         if ((env->le_ctx.lc_tags & ctags) != ctags) {
1888                 env->le_ctx.lc_version = 0;
1889                 env->le_ctx.lc_tags |= ctags;
1890         }
1891
1892         if (env->le_ses && (env->le_ses->lc_tags & stags) != stags) {
1893                 env->le_ses->lc_version = 0;
1894                 env->le_ses->lc_tags |= stags;
1895         }
1896
1897         result = lu_env_refill(env);
1898
1899         return result;
1900 }
1901 EXPORT_SYMBOL(lu_env_refill_by_tags);
1902
1903 static struct shrinker *lu_site_shrinker;
1904
1905 typedef struct lu_site_stats{
1906         unsigned        lss_populated;
1907         unsigned        lss_max_search;
1908         unsigned        lss_total;
1909         unsigned        lss_busy;
1910 } lu_site_stats_t;
1911
1912 static void lu_site_stats_get(const struct lu_site *s,
1913                               lu_site_stats_t *stats, int populated)
1914 {
1915         struct cfs_hash *hs = s->ls_obj_hash;
1916         struct cfs_hash_bd bd;
1917         unsigned int i;
1918         /*
1919          * percpu_counter_sum_positive() won't accept a const pointer
1920          * as it does modify the struct by taking a spinlock
1921          */
1922         struct lu_site *s2 = (struct lu_site *)s;
1923
1924         stats->lss_busy += cfs_hash_size_get(hs) -
1925                 percpu_counter_sum_positive(&s2->ls_lru_len_counter);
1926         cfs_hash_for_each_bucket(hs, &bd, i) {
1927                 struct hlist_head *hhead;
1928
1929                 cfs_hash_bd_lock(hs, &bd, 1);
1930                 stats->lss_total += cfs_hash_bd_count_get(&bd);
1931                 stats->lss_max_search = max((int)stats->lss_max_search,
1932                                             cfs_hash_bd_depmax_get(&bd));
1933                 if (!populated) {
1934                         cfs_hash_bd_unlock(hs, &bd, 1);
1935                         continue;
1936                 }
1937
1938                 cfs_hash_bd_for_each_hlist(hs, &bd, hhead) {
1939                         if (!hlist_empty(hhead))
1940                                 stats->lss_populated++;
1941                 }
1942                 cfs_hash_bd_unlock(hs, &bd, 1);
1943         }
1944 }
1945
1946
1947 /*
1948  * lu_cache_shrink_count() returns an approximate number of cached objects
1949  * that can be freed by shrink_slab(). A counter, which tracks the
1950  * number of items in the site's lru, is maintained in a percpu_counter
1951  * for each site. The percpu values are incremented and decremented as
1952  * objects are added or removed from the lru. The percpu values are summed
1953  * and saved whenever a percpu value exceeds a threshold. Thus the saved,
1954  * summed value at any given time may not accurately reflect the current
1955  * lru length. But this value is sufficiently accurate for the needs of
1956  * a shrinker.
1957  *
1958  * Using a per cpu counter is a compromise solution to concurrent access:
1959  * lu_object_put() can update the counter without locking the site and
1960  * lu_cache_shrink_count can sum the counters without locking each
1961  * ls_obj_hash bucket.
1962  */
1963 static unsigned long lu_cache_shrink_count(struct shrinker *sk,
1964                                            struct shrink_control *sc)
1965 {
1966         struct lu_site *s;
1967         struct lu_site *tmp;
1968         unsigned long cached = 0;
1969
1970         if (!(sc->gfp_mask & __GFP_FS))
1971                 return 0;
1972
1973         down_read(&lu_sites_guard);
1974         list_for_each_entry_safe(s, tmp, &lu_sites, ls_linkage)
1975                 cached += percpu_counter_read_positive(&s->ls_lru_len_counter);
1976         up_read(&lu_sites_guard);
1977
1978         cached = (cached / 100) * sysctl_vfs_cache_pressure;
1979         CDEBUG(D_INODE, "%ld objects cached, cache pressure %d\n",
1980                cached, sysctl_vfs_cache_pressure);
1981
1982         return cached;
1983 }
1984
1985 static unsigned long lu_cache_shrink_scan(struct shrinker *sk,
1986                                           struct shrink_control *sc)
1987 {
1988         struct lu_site *s;
1989         struct lu_site *tmp;
1990         unsigned long remain = sc->nr_to_scan;
1991         LIST_HEAD(splice);
1992
1993         if (!(sc->gfp_mask & __GFP_FS))
1994                 /* We must not take the lu_sites_guard lock when
1995                  * __GFP_FS is *not* set because of the deadlock
1996                  * possibility detailed above. Additionally,
1997                  * since we cannot determine the number of
1998                  * objects in the cache without taking this
1999                  * lock, we're in a particularly tough spot. As
2000                  * a result, we'll just lie and say our cache is
2001                  * empty. This _should_ be ok, as we can't
2002                  * reclaim objects when __GFP_FS is *not* set
2003                  * anyways.
2004                  */
2005                 return SHRINK_STOP;
2006
2007         down_write(&lu_sites_guard);
2008         list_for_each_entry_safe(s, tmp, &lu_sites, ls_linkage) {
2009                 remain = lu_site_purge(&lu_shrink_env, s, remain);
2010                 /*
2011                  * Move just shrunk site to the tail of site list to
2012                  * assure shrinking fairness.
2013                  */
2014                 list_move_tail(&s->ls_linkage, &splice);
2015         }
2016         list_splice(&splice, lu_sites.prev);
2017         up_write(&lu_sites_guard);
2018
2019         return sc->nr_to_scan - remain;
2020 }
2021
2022 #ifndef HAVE_SHRINKER_COUNT
2023 /*
2024  * There exists a potential lock inversion deadlock scenario when using
2025  * Lustre on top of ZFS. This occurs between one of ZFS's
2026  * buf_hash_table.ht_lock's, and Lustre's lu_sites_guard lock. Essentially,
2027  * thread A will take the lu_sites_guard lock and sleep on the ht_lock,
2028  * while thread B will take the ht_lock and sleep on the lu_sites_guard
2029  * lock. Obviously neither thread will wake and drop their respective hold
2030  * on their lock.
2031  *
2032  * To prevent this from happening we must ensure the lu_sites_guard lock is
2033  * not taken while down this code path. ZFS reliably does not set the
2034  * __GFP_FS bit in its code paths, so this can be used to determine if it
2035  * is safe to take the lu_sites_guard lock.
2036  *
2037  * Ideally we should accurately return the remaining number of cached
2038  * objects without taking the lu_sites_guard lock, but this is not
2039  * possible in the current implementation.
2040  */
2041 static int lu_cache_shrink(SHRINKER_ARGS(sc, nr_to_scan, gfp_mask))
2042 {
2043         int cached = 0;
2044         struct shrink_control scv = {
2045                  .nr_to_scan = shrink_param(sc, nr_to_scan),
2046                  .gfp_mask   = shrink_param(sc, gfp_mask)
2047         };
2048 #if !defined(HAVE_SHRINKER_WANT_SHRINK_PTR) && !defined(HAVE_SHRINK_CONTROL)
2049         struct shrinker* shrinker = NULL;
2050 #endif
2051
2052
2053         CDEBUG(D_INODE, "Shrink %lu objects\n", scv.nr_to_scan);
2054
2055         if (scv.nr_to_scan != 0)
2056                 lu_cache_shrink_scan(shrinker, &scv);
2057
2058         cached = lu_cache_shrink_count(shrinker, &scv);
2059         return cached;
2060 }
2061
2062 #endif /* HAVE_SHRINKER_COUNT */
2063
2064
2065 /*
2066  * Debugging stuff.
2067  */
2068
2069 /**
2070  * Environment to be used in debugger, contains all tags.
2071  */
2072 static struct lu_env lu_debugging_env;
2073
2074 /**
2075  * Debugging printer function using printk().
2076  */
2077 int lu_printk_printer(const struct lu_env *env,
2078                       void *unused, const char *format, ...)
2079 {
2080         va_list args;
2081
2082         va_start(args, format);
2083         vprintk(format, args);
2084         va_end(args);
2085         return 0;
2086 }
2087
2088 int lu_debugging_setup(void)
2089 {
2090         return lu_env_init(&lu_debugging_env, ~0);
2091 }
2092
2093 void lu_context_keys_dump(void)
2094 {
2095         unsigned int i;
2096
2097         for (i = 0; i < ARRAY_SIZE(lu_keys); ++i) {
2098                 struct lu_context_key *key;
2099
2100                 key = lu_keys[i];
2101                 if (key != NULL) {
2102                         CERROR("[%d]: %p %x (%p,%p,%p) %d %d \"%s\"@%p\n",
2103                                i, key, key->lct_tags,
2104                                key->lct_init, key->lct_fini, key->lct_exit,
2105                                key->lct_index, atomic_read(&key->lct_used),
2106                                key->lct_owner ? key->lct_owner->name : "",
2107                                key->lct_owner);
2108                         lu_ref_print(&key->lct_reference);
2109                 }
2110         }
2111 }
2112
2113 /**
2114  * Initialization of global lu_* data.
2115  */
2116 int lu_global_init(void)
2117 {
2118         int result;
2119         DEF_SHRINKER_VAR(shvar, lu_cache_shrink,
2120                          lu_cache_shrink_count, lu_cache_shrink_scan);
2121
2122         CDEBUG(D_INFO, "Lustre LU module (%p).\n", &lu_keys);
2123
2124         result = lu_ref_global_init();
2125         if (result != 0)
2126                 return result;
2127
2128         LU_CONTEXT_KEY_INIT(&lu_global_key);
2129         result = lu_context_key_register(&lu_global_key);
2130         if (result != 0)
2131                 return result;
2132
2133         /*
2134          * At this level, we don't know what tags are needed, so allocate them
2135          * conservatively. This should not be too bad, because this
2136          * environment is global.
2137          */
2138         down_write(&lu_sites_guard);
2139         result = lu_env_init(&lu_shrink_env, LCT_SHRINKER);
2140         up_write(&lu_sites_guard);
2141         if (result != 0)
2142                 return result;
2143
2144         /*
2145          * seeks estimation: 3 seeks to read a record from oi, one to read
2146          * inode, one for ea. Unfortunately setting this high value results in
2147          * lu_object/inode cache consuming all the memory.
2148          */
2149         lu_site_shrinker = set_shrinker(DEFAULT_SEEKS, &shvar);
2150         if (lu_site_shrinker == NULL)
2151                 return -ENOMEM;
2152
2153         return result;
2154 }
2155
2156 /**
2157  * Dual to lu_global_init().
2158  */
2159 void lu_global_fini(void)
2160 {
2161         if (lu_site_shrinker != NULL) {
2162                 remove_shrinker(lu_site_shrinker);
2163                 lu_site_shrinker = NULL;
2164         }
2165
2166         lu_context_key_degister(&lu_global_key);
2167
2168         /*
2169          * Tear shrinker environment down _after_ de-registering
2170          * lu_global_key, because the latter has a value in the former.
2171          */
2172         down_write(&lu_sites_guard);
2173         lu_env_fini(&lu_shrink_env);
2174         up_write(&lu_sites_guard);
2175
2176         lu_ref_global_fini();
2177 }
2178
2179 static __u32 ls_stats_read(struct lprocfs_stats *stats, int idx)
2180 {
2181 #ifdef CONFIG_PROC_FS
2182         struct lprocfs_counter ret;
2183
2184         lprocfs_stats_collect(stats, idx, &ret);
2185         return (__u32)ret.lc_count;
2186 #else
2187         return 0;
2188 #endif
2189 }
2190
2191 /**
2192  * Output site statistical counters into a buffer. Suitable for
2193  * lprocfs_rd_*()-style functions.
2194  */
2195 int lu_site_stats_seq_print(const struct lu_site *s, struct seq_file *m)
2196 {
2197         lu_site_stats_t stats;
2198
2199         memset(&stats, 0, sizeof(stats));
2200         lu_site_stats_get(s, &stats, 1);
2201
2202         seq_printf(m, "%d/%d %d/%d %d %d %d %d %d %d %d\n",
2203                    stats.lss_busy,
2204                    stats.lss_total,
2205                    stats.lss_populated,
2206                    CFS_HASH_NHLIST(s->ls_obj_hash),
2207                    stats.lss_max_search,
2208                    ls_stats_read(s->ls_stats, LU_SS_CREATED),
2209                    ls_stats_read(s->ls_stats, LU_SS_CACHE_HIT),
2210                    ls_stats_read(s->ls_stats, LU_SS_CACHE_MISS),
2211                    ls_stats_read(s->ls_stats, LU_SS_CACHE_RACE),
2212                    ls_stats_read(s->ls_stats, LU_SS_CACHE_DEATH_RACE),
2213                    ls_stats_read(s->ls_stats, LU_SS_LRU_PURGED));
2214         return 0;
2215 }
2216 EXPORT_SYMBOL(lu_site_stats_seq_print);
2217
2218 /**
2219  * Helper function to initialize a number of kmem slab caches at once.
2220  */
2221 int lu_kmem_init(struct lu_kmem_descr *caches)
2222 {
2223         int result;
2224         struct lu_kmem_descr *iter = caches;
2225
2226         for (result = 0; iter->ckd_cache != NULL; ++iter) {
2227                 *iter->ckd_cache = kmem_cache_create(iter->ckd_name,
2228                                                      iter->ckd_size,
2229                                                      0, 0, NULL);
2230                 if (*iter->ckd_cache == NULL) {
2231                         result = -ENOMEM;
2232                         /* free all previously allocated caches */
2233                         lu_kmem_fini(caches);
2234                         break;
2235                 }
2236         }
2237         return result;
2238 }
2239 EXPORT_SYMBOL(lu_kmem_init);
2240
2241 /**
2242  * Helper function to finalize a number of kmem slab cached at once. Dual to
2243  * lu_kmem_init().
2244  */
2245 void lu_kmem_fini(struct lu_kmem_descr *caches)
2246 {
2247         for (; caches->ckd_cache != NULL; ++caches) {
2248                 if (*caches->ckd_cache != NULL) {
2249                         kmem_cache_destroy(*caches->ckd_cache);
2250                         *caches->ckd_cache = NULL;
2251                 }
2252         }
2253 }
2254 EXPORT_SYMBOL(lu_kmem_fini);
2255
2256 /**
2257  * Temporary solution to be able to assign fid in ->do_create()
2258  * till we have fully-functional OST fids
2259  */
2260 void lu_object_assign_fid(const struct lu_env *env, struct lu_object *o,
2261                           const struct lu_fid *fid)
2262 {
2263         struct lu_site          *s = o->lo_dev->ld_site;
2264         struct lu_fid           *old = &o->lo_header->loh_fid;
2265         struct cfs_hash         *hs;
2266         struct cfs_hash_bd       bd;
2267
2268         LASSERT(fid_is_zero(old));
2269
2270         /* supposed to be unique */
2271         hs = s->ls_obj_hash;
2272         cfs_hash_bd_get_and_lock(hs, (void *)fid, &bd, 1);
2273 #ifdef CONFIG_LUSTRE_DEBUG_EXPENSIVE_CHECK
2274         {
2275                 __u64 version = 0;
2276                 struct lu_object *shadow;
2277
2278                 shadow = htable_lookup(s, &bd, fid, &version);
2279                 /* supposed to be unique */
2280                 LASSERT(IS_ERR(shadow) && PTR_ERR(shadow) == -ENOENT);
2281         }
2282 #endif
2283         *old = *fid;
2284         cfs_hash_bd_add_locked(hs, &bd, &o->lo_header->loh_hash);
2285         cfs_hash_bd_unlock(hs, &bd, 1);
2286 }
2287 EXPORT_SYMBOL(lu_object_assign_fid);
2288
2289 /**
2290  * allocates object with 0 (non-assiged) fid
2291  * XXX: temporary solution to be able to assign fid in ->do_create()
2292  *      till we have fully-functional OST fids
2293  */
2294 struct lu_object *lu_object_anon(const struct lu_env *env,
2295                                  struct lu_device *dev,
2296                                  const struct lu_object_conf *conf)
2297 {
2298         struct lu_fid     fid;
2299         struct lu_object *o;
2300
2301         fid_zero(&fid);
2302         o = lu_object_alloc(env, dev, &fid, conf);
2303
2304         return o;
2305 }
2306 EXPORT_SYMBOL(lu_object_anon);
2307
2308 struct lu_buf LU_BUF_NULL = {
2309         .lb_buf = NULL,
2310         .lb_len = 0
2311 };
2312 EXPORT_SYMBOL(LU_BUF_NULL);
2313
2314 void lu_buf_free(struct lu_buf *buf)
2315 {
2316         LASSERT(buf);
2317         if (buf->lb_buf) {
2318                 LASSERT(buf->lb_len > 0);
2319                 OBD_FREE_LARGE(buf->lb_buf, buf->lb_len);
2320                 buf->lb_buf = NULL;
2321                 buf->lb_len = 0;
2322         }
2323 }
2324 EXPORT_SYMBOL(lu_buf_free);
2325
2326 void lu_buf_alloc(struct lu_buf *buf, size_t size)
2327 {
2328         LASSERT(buf);
2329         LASSERT(buf->lb_buf == NULL);
2330         LASSERT(buf->lb_len == 0);
2331         OBD_ALLOC_LARGE(buf->lb_buf, size);
2332         if (likely(buf->lb_buf))
2333                 buf->lb_len = size;
2334 }
2335 EXPORT_SYMBOL(lu_buf_alloc);
2336
2337 void lu_buf_realloc(struct lu_buf *buf, size_t size)
2338 {
2339         lu_buf_free(buf);
2340         lu_buf_alloc(buf, size);
2341 }
2342 EXPORT_SYMBOL(lu_buf_realloc);
2343
2344 struct lu_buf *lu_buf_check_and_alloc(struct lu_buf *buf, size_t len)
2345 {
2346         if (buf->lb_buf == NULL && buf->lb_len == 0)
2347                 lu_buf_alloc(buf, len);
2348
2349         if ((len > buf->lb_len) && (buf->lb_buf != NULL))
2350                 lu_buf_realloc(buf, len);
2351
2352         return buf;
2353 }
2354 EXPORT_SYMBOL(lu_buf_check_and_alloc);
2355
2356 /**
2357  * Increase the size of the \a buf.
2358  * preserves old data in buffer
2359  * old buffer remains unchanged on error
2360  * \retval 0 or -ENOMEM
2361  */
2362 int lu_buf_check_and_grow(struct lu_buf *buf, size_t len)
2363 {
2364         char *ptr;
2365
2366         if (len <= buf->lb_len)
2367                 return 0;
2368
2369         OBD_ALLOC_LARGE(ptr, len);
2370         if (ptr == NULL)
2371                 return -ENOMEM;
2372
2373         /* Free the old buf */
2374         if (buf->lb_buf != NULL) {
2375                 memcpy(ptr, buf->lb_buf, buf->lb_len);
2376                 OBD_FREE_LARGE(buf->lb_buf, buf->lb_len);
2377         }
2378
2379         buf->lb_buf = ptr;
2380         buf->lb_len = len;
2381         return 0;
2382 }
2383 EXPORT_SYMBOL(lu_buf_check_and_grow);