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