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