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