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