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