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