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