Whamcloud - gitweb
59ce8ded73cac48e2dfe56af90c52e236b4ec287
[fs/lustre-release.git] / lustre / obdclass / cl_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.sun.com/software/products/lustre/docs/GPLv2.pdf
19  *
20  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
21  * CA 95054 USA or visit www.sun.com if you need additional information or
22  * have any questions.
23  *
24  * GPL HEADER END
25  */
26 /*
27  * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2011, 2014, Intel Corporation.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * Client Lustre Object.
37  *
38  *   Author: Nikita Danilov <nikita.danilov@sun.com>
39  *   Author: Jinshan Xiong <jinshan.xiong@intel.com>
40  */
41
42 /*
43  * Locking.
44  *
45  *  i_mutex
46  *      PG_locked
47  *          ->coh_attr_guard
48  *          ->ls_guard
49  */
50
51 #define DEBUG_SUBSYSTEM S_CLASS
52
53 #include <libcfs/libcfs.h>
54 /* class_put_type() */
55 #include <obd_class.h>
56 #include <obd_support.h>
57 #include <lustre_fid.h>
58 #include <libcfs/list.h>
59 #include <libcfs/libcfs_hash.h> /* for cfs_hash stuff */
60 #include <cl_object.h>
61 #include <lu_object.h>
62 #include "cl_internal.h"
63
64 static struct kmem_cache *cl_env_kmem;
65
66 /** Lock class of cl_object_header::coh_attr_guard */
67 static struct lock_class_key cl_attr_guard_class;
68
69 /**
70  * Initialize cl_object_header.
71  */
72 int cl_object_header_init(struct cl_object_header *h)
73 {
74         int result;
75
76         ENTRY;
77         result = lu_object_header_init(&h->coh_lu);
78         if (result == 0) {
79                 spin_lock_init(&h->coh_attr_guard);
80                 lockdep_set_class(&h->coh_attr_guard, &cl_attr_guard_class);
81                 h->coh_page_bufsize = 0;
82         }
83         RETURN(result);
84 }
85 EXPORT_SYMBOL(cl_object_header_init);
86
87 /**
88  * Finalize cl_object_header.
89  */
90 void cl_object_header_fini(struct cl_object_header *h)
91 {
92         lu_object_header_fini(&h->coh_lu);
93 }
94
95 /**
96  * Returns a cl_object with a given \a fid.
97  *
98  * Returns either cached or newly created object. Additional reference on the
99  * returned object is acquired.
100  *
101  * \see lu_object_find(), cl_page_find(), cl_lock_find()
102  */
103 struct cl_object *cl_object_find(const struct lu_env *env,
104                                  struct cl_device *cd, const struct lu_fid *fid,
105                                  const struct cl_object_conf *c)
106 {
107         might_sleep();
108         return lu2cl(lu_object_find_slice(env, cl2lu_dev(cd), fid, &c->coc_lu));
109 }
110 EXPORT_SYMBOL(cl_object_find);
111
112 /**
113  * Releases a reference on \a o.
114  *
115  * When last reference is released object is returned to the cache, unless
116  * lu_object_header_flags::LU_OBJECT_HEARD_BANSHEE bit is set in its header.
117  *
118  * \see cl_page_put(), cl_lock_put().
119  */
120 void cl_object_put(const struct lu_env *env, struct cl_object *o)
121 {
122         lu_object_put(env, &o->co_lu);
123 }
124 EXPORT_SYMBOL(cl_object_put);
125
126 /**
127  * Acquire an additional reference to the object \a o.
128  *
129  * This can only be used to acquire _additional_ reference, i.e., caller
130  * already has to possess at least one reference to \a o before calling this.
131  *
132  * \see cl_page_get(), cl_lock_get().
133  */
134 void cl_object_get(struct cl_object *o)
135 {
136         lu_object_get(&o->co_lu);
137 }
138 EXPORT_SYMBOL(cl_object_get);
139
140 /**
141  * Returns the top-object for a given \a o.
142  *
143  * \see cl_io_top()
144  */
145 struct cl_object *cl_object_top(struct cl_object *o)
146 {
147         struct cl_object_header *hdr = cl_object_header(o);
148         struct cl_object *top;
149
150         while (hdr->coh_parent != NULL)
151                 hdr = hdr->coh_parent;
152
153         top = lu2cl(lu_object_top(&hdr->coh_lu));
154         CDEBUG(D_TRACE, "%p -> %p\n", o, top);
155         return top;
156 }
157 EXPORT_SYMBOL(cl_object_top);
158
159 /**
160  * Returns pointer to the lock protecting data-attributes for the given object
161  * \a o.
162  *
163  * Data-attributes are protected by the cl_object_header::coh_attr_guard
164  * spin-lock in the top-object.
165  *
166  * \see cl_attr, cl_object_attr_lock(), cl_object_operations::coo_attr_get().
167  */
168 static spinlock_t *cl_object_attr_guard(struct cl_object *o)
169 {
170         return &cl_object_header(cl_object_top(o))->coh_attr_guard;
171 }
172
173 /**
174  * Locks data-attributes.
175  *
176  * Prevents data-attributes from changing, until lock is released by
177  * cl_object_attr_unlock(). This has to be called before calls to
178  * cl_object_attr_get(), cl_object_attr_update().
179  */
180 void cl_object_attr_lock(struct cl_object *o)
181 __acquires(cl_object_attr_guard(o))
182 {
183         spin_lock(cl_object_attr_guard(o));
184 }
185 EXPORT_SYMBOL(cl_object_attr_lock);
186
187 /**
188  * Releases data-attributes lock, acquired by cl_object_attr_lock().
189  */
190 void cl_object_attr_unlock(struct cl_object *o)
191 __releases(cl_object_attr_guard(o))
192 {
193         spin_unlock(cl_object_attr_guard(o));
194 }
195 EXPORT_SYMBOL(cl_object_attr_unlock);
196
197 /**
198  * Returns data-attributes of an object \a obj.
199  *
200  * Every layer is asked (by calling cl_object_operations::coo_attr_get())
201  * top-to-bottom to fill in parts of \a attr that this layer is responsible
202  * for.
203  */
204 int cl_object_attr_get(const struct lu_env *env, struct cl_object *obj,
205                        struct cl_attr *attr)
206 {
207         struct lu_object_header *top;
208         int result;
209
210         assert_spin_locked(cl_object_attr_guard(obj));
211         ENTRY;
212
213         top = obj->co_lu.lo_header;
214         result = 0;
215         list_for_each_entry(obj, &top->loh_layers, co_lu.lo_linkage) {
216                 if (obj->co_ops->coo_attr_get != NULL) {
217                         result = obj->co_ops->coo_attr_get(env, obj, attr);
218                         if (result != 0) {
219                                 if (result > 0)
220                                         result = 0;
221                                 break;
222                         }
223                 }
224         }
225         RETURN(result);
226 }
227 EXPORT_SYMBOL(cl_object_attr_get);
228
229 /**
230  * Updates data-attributes of an object \a obj.
231  *
232  * Only attributes, mentioned in a validness bit-mask \a v are
233  * updated. Calls cl_object_operations::coo_upd_attr() on every layer, bottom
234  * to top.
235  */
236 int cl_object_attr_update(const struct lu_env *env, struct cl_object *obj,
237                           const struct cl_attr *attr, unsigned v)
238 {
239         struct lu_object_header *top;
240         int result;
241
242         assert_spin_locked(cl_object_attr_guard(obj));
243         ENTRY;
244
245         top = obj->co_lu.lo_header;
246         result = 0;
247         list_for_each_entry_reverse(obj, &top->loh_layers, co_lu.lo_linkage) {
248                 if (obj->co_ops->coo_attr_update != NULL) {
249                         result = obj->co_ops->coo_attr_update(env, obj, attr,
250                                                               v);
251                         if (result != 0) {
252                                 if (result > 0)
253                                         result = 0;
254                                 break;
255                         }
256                 }
257         }
258         RETURN(result);
259 }
260 EXPORT_SYMBOL(cl_object_attr_update);
261
262 /**
263  * Notifies layers (bottom-to-top) that glimpse AST was received.
264  *
265  * Layers have to fill \a lvb fields with information that will be shipped
266  * back to glimpse issuer.
267  *
268  * \see cl_lock_operations::clo_glimpse()
269  */
270 int cl_object_glimpse(const struct lu_env *env, struct cl_object *obj,
271                       struct ost_lvb *lvb)
272 {
273         struct lu_object_header *top;
274         int result;
275
276         ENTRY;
277         top = obj->co_lu.lo_header;
278         result = 0;
279         list_for_each_entry_reverse(obj, &top->loh_layers, co_lu.lo_linkage) {
280                 if (obj->co_ops->coo_glimpse != NULL) {
281                         result = obj->co_ops->coo_glimpse(env, obj, lvb);
282                         if (result != 0)
283                                 break;
284                 }
285         }
286         LU_OBJECT_HEADER(D_DLMTRACE, env, lu_object_top(top),
287                          "size: "LPU64" mtime: "LPU64" atime: "LPU64" "
288                          "ctime: "LPU64" blocks: "LPU64"\n",
289                          lvb->lvb_size, lvb->lvb_mtime, lvb->lvb_atime,
290                          lvb->lvb_ctime, lvb->lvb_blocks);
291         RETURN(result);
292 }
293 EXPORT_SYMBOL(cl_object_glimpse);
294
295 /**
296  * Updates a configuration of an object \a obj.
297  */
298 int cl_conf_set(const struct lu_env *env, struct cl_object *obj,
299                 const struct cl_object_conf *conf)
300 {
301         struct lu_object_header *top;
302         int result;
303
304         ENTRY;
305         top = obj->co_lu.lo_header;
306         result = 0;
307         list_for_each_entry(obj, &top->loh_layers, co_lu.lo_linkage) {
308                 if (obj->co_ops->coo_conf_set != NULL) {
309                         result = obj->co_ops->coo_conf_set(env, obj, conf);
310                         if (result != 0)
311                                 break;
312                 }
313         }
314         RETURN(result);
315 }
316 EXPORT_SYMBOL(cl_conf_set);
317
318 /**
319  * Prunes caches of pages and locks for this object.
320  */
321 int cl_object_prune(const struct lu_env *env, struct cl_object *obj)
322 {
323         struct lu_object_header *top;
324         struct cl_object *o;
325         int result;
326         ENTRY;
327
328         top = obj->co_lu.lo_header;
329         result = 0;
330         list_for_each_entry(o, &top->loh_layers, co_lu.lo_linkage) {
331                 if (o->co_ops->coo_prune != NULL) {
332                         result = o->co_ops->coo_prune(env, o);
333                         if (result != 0)
334                                 break;
335                 }
336         }
337
338         RETURN(result);
339 }
340 EXPORT_SYMBOL(cl_object_prune);
341
342 /**
343  * Get stripe information of this object.
344  */
345 int cl_object_getstripe(const struct lu_env *env, struct cl_object *obj,
346                         struct lov_user_md __user *uarg)
347 {
348         struct lu_object_header *top;
349         int                     result = 0;
350         ENTRY;
351
352         top = obj->co_lu.lo_header;
353         list_for_each_entry(obj, &top->loh_layers, co_lu.lo_linkage) {
354                 if (obj->co_ops->coo_getstripe != NULL) {
355                         result = obj->co_ops->coo_getstripe(env, obj, uarg);
356                         if (result != 0)
357                                 break;
358                 }
359         }
360         RETURN(result);
361 }
362 EXPORT_SYMBOL(cl_object_getstripe);
363
364 /**
365  * Find whether there is any callback data (ldlm lock) attached upon this
366  * object.
367  */
368 int cl_object_find_cbdata(const struct lu_env *env, struct cl_object *obj,
369                            ldlm_iterator_t iter, void *data)
370 {
371         struct lu_object_header *top;
372         int                     result = 0;
373         ENTRY;
374
375         top = obj->co_lu.lo_header;
376         list_for_each_entry(obj, &top->loh_layers, co_lu.lo_linkage) {
377                 if (obj->co_ops->coo_find_cbdata != NULL) {
378                         result = obj->co_ops->coo_find_cbdata(env, obj, iter,
379                                                               data);
380                         if (result != 0)
381                                 break;
382                 }
383         }
384         RETURN(result);
385 }
386 EXPORT_SYMBOL(cl_object_find_cbdata);
387
388 /**
389  * Get fiemap extents from file object.
390  *
391  * \param env [in]      lustre environment
392  * \param obj [in]      file object
393  * \param key [in]      fiemap request argument
394  * \param fiemap [out]  fiemap extents mapping retrived
395  * \param buflen [in]   max buffer length of @fiemap
396  *
397  * \retval 0    success
398  * \retval < 0  error
399  */
400 int cl_object_fiemap(const struct lu_env *env, struct cl_object *obj,
401                      struct ll_fiemap_info_key *key,
402                      struct fiemap *fiemap, size_t *buflen)
403 {
404         struct lu_object_header *top;
405         int                     result = 0;
406         ENTRY;
407
408         top = obj->co_lu.lo_header;
409         list_for_each_entry(obj, &top->loh_layers, co_lu.lo_linkage) {
410                 if (obj->co_ops->coo_fiemap != NULL) {
411                         result = obj->co_ops->coo_fiemap(env, obj, key, fiemap,
412                                                          buflen);
413                         if (result != 0)
414                                 break;
415                 }
416         }
417         RETURN(result);
418 }
419 EXPORT_SYMBOL(cl_object_fiemap);
420
421 /**
422  * Helper function removing all object locks, and marking object for
423  * deletion. All object pages must have been deleted at this point.
424  *
425  * This is called by cl_inode_fini() and lov_object_delete() to destroy top-
426  * and sub- objects respectively.
427  */
428 void cl_object_kill(const struct lu_env *env, struct cl_object *obj)
429 {
430         struct cl_object_header *hdr = cl_object_header(obj);
431
432         set_bit(LU_OBJECT_HEARD_BANSHEE, &hdr->coh_lu.loh_flags);
433 }
434 EXPORT_SYMBOL(cl_object_kill);
435
436 void cache_stats_init(struct cache_stats *cs, const char *name)
437 {
438         int i;
439
440         cs->cs_name = name;
441         for (i = 0; i < CS_NR; i++)
442                 atomic_set(&cs->cs_stats[i], 0);
443 }
444
445 static int cache_stats_print(const struct cache_stats *cs,
446                              struct seq_file *m, int h)
447 {
448         int i;
449
450         /*
451          *   lookup    hit    total  cached create
452          * env: ...... ...... ...... ...... ......
453          */
454         if (h) {
455                 const char *names[CS_NR] = CS_NAMES;
456
457                 seq_printf(m, "%6s", " ");
458                 for (i = 0; i < CS_NR; i++)
459                         seq_printf(m, "%8s", names[i]);
460                 seq_printf(m, "\n");
461         }
462
463         seq_printf(m, "%5.5s:", cs->cs_name);
464         for (i = 0; i < CS_NR; i++)
465                 seq_printf(m, "%8u", atomic_read(&cs->cs_stats[i]));
466         return 0;
467 }
468
469 static void cl_env_percpu_refill(void);
470
471 /**
472  * Initialize client site.
473  *
474  * Perform common initialization (lu_site_init()), and initialize statistical
475  * counters. Also perform global initializations on the first call.
476  */
477 int cl_site_init(struct cl_site *s, struct cl_device *d)
478 {
479         size_t i;
480         int result;
481
482         result = lu_site_init(&s->cs_lu, &d->cd_lu_dev);
483         if (result == 0) {
484                 cache_stats_init(&s->cs_pages, "pages");
485                 for (i = 0; i < ARRAY_SIZE(s->cs_pages_state); ++i)
486                         atomic_set(&s->cs_pages_state[0], 0);
487                 cl_env_percpu_refill();
488         }
489         return result;
490 }
491 EXPORT_SYMBOL(cl_site_init);
492
493 /**
494  * Finalize client site. Dual to cl_site_init().
495  */
496 void cl_site_fini(struct cl_site *s)
497 {
498         lu_site_fini(&s->cs_lu);
499 }
500 EXPORT_SYMBOL(cl_site_fini);
501
502 static struct cache_stats cl_env_stats = {
503         .cs_name    = "envs",
504         .cs_stats = { ATOMIC_INIT(0), }
505 };
506
507 /**
508  * Outputs client site statistical counters into a buffer. Suitable for
509  * ll_rd_*()-style functions.
510  */
511 int cl_site_stats_print(const struct cl_site *site, struct seq_file *m)
512 {
513         static const char *pstate[] = {
514                 [CPS_CACHED]    = "c",
515                 [CPS_OWNED]     = "o",
516                 [CPS_PAGEOUT]   = "w",
517                 [CPS_PAGEIN]    = "r",
518                 [CPS_FREEING]   = "f"
519         };
520         size_t i;
521
522 /*
523        lookup    hit  total   busy create
524 pages: ...... ...... ...... ...... ...... [...... ...... ...... ......]
525 locks: ...... ...... ...... ...... ...... [...... ...... ...... ...... ......]
526   env: ...... ...... ...... ...... ......
527  */
528         lu_site_stats_seq_print(&site->cs_lu, m);
529         cache_stats_print(&site->cs_pages, m, 1);
530         seq_printf(m, " [");
531         for (i = 0; i < ARRAY_SIZE(site->cs_pages_state); ++i)
532                 seq_printf(m, "%s: %u ", pstate[i],
533                            atomic_read(&site->cs_pages_state[i]));
534         seq_printf(m, "]\n");
535         cache_stats_print(&cl_env_stats, m, 0);
536         seq_printf(m, "\n");
537         return 0;
538 }
539 EXPORT_SYMBOL(cl_site_stats_print);
540
541 /*****************************************************************************
542  *
543  * lu_env handling on client.
544  *
545  */
546
547 /**
548  * The most efficient way is to store cl_env pointer in task specific
549  * structures. On Linux, it wont' be easy to use task_struct->journal_info
550  * because Lustre code may call into other fs which has certain assumptions
551  * about journal_info. Currently following fields in task_struct are identified
552  * can be used for this purpose:
553  *  - cl_env: for liblustre.
554  *  - tux_info: ony on RedHat kernel.
555  *  - ...
556  * \note As long as we use task_struct to store cl_env, we assume that once
557  * called into Lustre, we'll never call into the other part of the kernel
558  * which will use those fields in task_struct without explicitly exiting
559  * Lustre.
560  *
561  * If there's no space in task_struct is available, hash will be used.
562  * bz20044, bz22683.
563  */
564
565 static struct list_head cl_envs;
566 static unsigned cl_envs_cached_nr  = 0;
567 static unsigned cl_envs_cached_max = 128; /* XXX: prototype: arbitrary limit
568                                            * for now. */
569 static DEFINE_SPINLOCK(cl_envs_guard);
570
571 struct cl_env {
572         void             *ce_magic;
573         struct lu_env     ce_lu;
574         struct lu_context ce_ses;
575
576 #ifdef LL_TASK_CL_ENV
577         void             *ce_prev;
578 #else
579         /**
580          * This allows cl_env to be entered into cl_env_hash which implements
581          * the current thread -> client environment lookup.
582          */
583         struct hlist_node  ce_node;
584 #endif
585         /**
586          * Owner for the current cl_env.
587          *
588          * If LL_TASK_CL_ENV is defined, this point to the owning current,
589          * only for debugging purpose ;
590          * Otherwise hash is used, and this is the key for cfs_hash.
591          * Now current thread pid is stored. Note using thread pointer would
592          * lead to unbalanced hash because of its specific allocation locality
593          * and could be varied for different platforms and OSes, even different
594          * OS versions.
595          */
596         void             *ce_owner;
597
598         /*
599          * Linkage into global list of all client environments. Used for
600          * garbage collection.
601          */
602         struct list_head  ce_linkage;
603         /*
604          *
605          */
606         int               ce_ref;
607         /*
608          * Debugging field: address of the caller who made original
609          * allocation.
610          */
611         void             *ce_debug;
612 };
613
614 #ifdef CONFIG_DEBUG_PAGESTATE_TRACKING
615 #define CL_ENV_INC(counter) atomic_inc(&cl_env_stats.cs_stats[CS_##counter])
616
617 #define CL_ENV_DEC(counter) do {                                              \
618         LASSERT(atomic_read(&cl_env_stats.cs_stats[CS_##counter]) > 0);   \
619         atomic_dec(&cl_env_stats.cs_stats[CS_##counter]);                 \
620 } while (0)
621 #else
622 #define CL_ENV_INC(counter)
623 #define CL_ENV_DEC(counter)
624 #endif
625
626 static void cl_env_init0(struct cl_env *cle, void *debug)
627 {
628         LASSERT(cle->ce_ref == 0);
629         LASSERT(cle->ce_magic == &cl_env_init0);
630         LASSERT(cle->ce_debug == NULL && cle->ce_owner == NULL);
631
632         cle->ce_ref = 1;
633         cle->ce_debug = debug;
634         CL_ENV_INC(busy);
635 }
636
637
638 #ifndef LL_TASK_CL_ENV
639 /*
640  * The implementation of using hash table to connect cl_env and thread
641  */
642
643 static cfs_hash_t *cl_env_hash;
644
645 static unsigned cl_env_hops_hash(cfs_hash_t *lh,
646                                  const void *key, unsigned mask)
647 {
648 #if BITS_PER_LONG == 64
649         return cfs_hash_u64_hash((__u64)key, mask);
650 #else
651         return cfs_hash_u32_hash((__u32)key, mask);
652 #endif
653 }
654
655 static void *cl_env_hops_obj(struct hlist_node *hn)
656 {
657         struct cl_env *cle = hlist_entry(hn, struct cl_env, ce_node);
658
659         LASSERT(cle->ce_magic == &cl_env_init0);
660         return (void *)cle;
661 }
662
663 static int cl_env_hops_keycmp(const void *key, struct hlist_node *hn)
664 {
665         struct cl_env *cle = cl_env_hops_obj(hn);
666
667         LASSERT(cle->ce_owner != NULL);
668         return (key == cle->ce_owner);
669 }
670
671 static void cl_env_hops_noop(cfs_hash_t *hs, struct hlist_node *hn)
672 {
673         struct cl_env *cle = hlist_entry(hn, struct cl_env, ce_node);
674         LASSERT(cle->ce_magic == &cl_env_init0);
675 }
676
677 static cfs_hash_ops_t cl_env_hops = {
678         .hs_hash        = cl_env_hops_hash,
679         .hs_key         = cl_env_hops_obj,
680         .hs_keycmp      = cl_env_hops_keycmp,
681         .hs_object      = cl_env_hops_obj,
682         .hs_get         = cl_env_hops_noop,
683         .hs_put_locked  = cl_env_hops_noop,
684 };
685
686 static inline struct cl_env *cl_env_fetch(void)
687 {
688         struct cl_env *cle;
689
690         cle = cfs_hash_lookup(cl_env_hash, (void *) (long) current->pid);
691         LASSERT(ergo(cle, cle->ce_magic == &cl_env_init0));
692         return cle;
693 }
694
695 static inline void cl_env_attach(struct cl_env *cle)
696 {
697         if (cle) {
698                 int rc;
699
700                 LASSERT(cle->ce_owner == NULL);
701                 cle->ce_owner = (void *) (long) current->pid;
702                 rc = cfs_hash_add_unique(cl_env_hash, cle->ce_owner,
703                                          &cle->ce_node);
704                 LASSERT(rc == 0);
705         }
706 }
707
708 static inline void cl_env_do_detach(struct cl_env *cle)
709 {
710         void *cookie;
711
712         LASSERT(cle->ce_owner == (void *) (long) current->pid);
713         cookie = cfs_hash_del(cl_env_hash, cle->ce_owner,
714                               &cle->ce_node);
715         LASSERT(cookie == cle);
716         cle->ce_owner = NULL;
717 }
718
719 static int cl_env_store_init(void) {
720         cl_env_hash = cfs_hash_create("cl_env",
721                                       HASH_CL_ENV_BITS, HASH_CL_ENV_BITS,
722                                       HASH_CL_ENV_BKT_BITS, 0,
723                                       CFS_HASH_MIN_THETA,
724                                       CFS_HASH_MAX_THETA,
725                                       &cl_env_hops,
726                                       CFS_HASH_RW_BKTLOCK);
727         return cl_env_hash != NULL ? 0 :-ENOMEM;
728 }
729
730 static void cl_env_store_fini(void) {
731         cfs_hash_putref(cl_env_hash);
732 }
733
734 #else /* LL_TASK_CL_ENV */
735 /*
736  * The implementation of store cl_env directly in thread structure.
737  */
738
739 static inline struct cl_env *cl_env_fetch(void)
740 {
741         struct cl_env *cle;
742
743         cle = current->LL_TASK_CL_ENV;
744         if (cle && cle->ce_magic != &cl_env_init0)
745                 cle = NULL;
746         return cle;
747 }
748
749 static inline void cl_env_attach(struct cl_env *cle)
750 {
751         if (cle) {
752                 LASSERT(cle->ce_owner == NULL);
753                 cle->ce_owner = current;
754                 cle->ce_prev = current->LL_TASK_CL_ENV;
755                 current->LL_TASK_CL_ENV = cle;
756         }
757 }
758
759 static inline void cl_env_do_detach(struct cl_env *cle)
760 {
761         LASSERT(cle->ce_owner == current);
762         LASSERT(current->LL_TASK_CL_ENV == cle);
763         current->LL_TASK_CL_ENV = cle->ce_prev;
764         cle->ce_owner = NULL;
765 }
766
767 static int cl_env_store_init(void) { return 0; }
768 static void cl_env_store_fini(void) { }
769
770 #endif /* LL_TASK_CL_ENV */
771
772 static inline struct cl_env *cl_env_detach(struct cl_env *cle)
773 {
774         if (cle == NULL)
775                 cle = cl_env_fetch();
776
777         if (cle && cle->ce_owner)
778                 cl_env_do_detach(cle);
779
780         return cle;
781 }
782
783 static struct lu_env *cl_env_new(__u32 ctx_tags, __u32 ses_tags, void *debug)
784 {
785         struct lu_env *env;
786         struct cl_env *cle;
787
788         OBD_SLAB_ALLOC_PTR_GFP(cle, cl_env_kmem, GFP_NOFS);
789         if (cle != NULL) {
790                 int rc;
791
792                 INIT_LIST_HEAD(&cle->ce_linkage);
793                 cle->ce_magic = &cl_env_init0;
794                 env = &cle->ce_lu;
795                 rc = lu_env_init(env, LCT_CL_THREAD|ctx_tags);
796                 if (rc == 0) {
797                         rc = lu_context_init(&cle->ce_ses,
798                                              LCT_SESSION | ses_tags);
799                         if (rc == 0) {
800                                 lu_context_enter(&cle->ce_ses);
801                                 env->le_ses = &cle->ce_ses;
802                                 cl_env_init0(cle, debug);
803                         } else
804                                 lu_env_fini(env);
805                 }
806                 if (rc != 0) {
807                         OBD_SLAB_FREE_PTR(cle, cl_env_kmem);
808                         env = ERR_PTR(rc);
809                 } else {
810                         CL_ENV_INC(create);
811                         CL_ENV_INC(total);
812                 }
813         } else
814                 env = ERR_PTR(-ENOMEM);
815         return env;
816 }
817
818 static void cl_env_fini(struct cl_env *cle)
819 {
820         CL_ENV_DEC(total);
821         lu_context_fini(&cle->ce_lu.le_ctx);
822         lu_context_fini(&cle->ce_ses);
823         OBD_SLAB_FREE_PTR(cle, cl_env_kmem);
824 }
825
826 static struct lu_env *cl_env_obtain(void *debug)
827 {
828         struct cl_env *cle;
829         struct lu_env *env;
830
831         ENTRY;
832         spin_lock(&cl_envs_guard);
833         LASSERT(equi(cl_envs_cached_nr == 0, list_empty(&cl_envs)));
834         if (cl_envs_cached_nr > 0) {
835                 int rc;
836
837                 cle = container_of(cl_envs.next, struct cl_env, ce_linkage);
838                 list_del_init(&cle->ce_linkage);
839                 cl_envs_cached_nr--;
840                 spin_unlock(&cl_envs_guard);
841
842                 env = &cle->ce_lu;
843                 rc = lu_env_refill(env);
844                 if (rc == 0) {
845                         cl_env_init0(cle, debug);
846                         lu_context_enter(&env->le_ctx);
847                         lu_context_enter(&cle->ce_ses);
848                 } else {
849                         cl_env_fini(cle);
850                         env = ERR_PTR(rc);
851                 }
852         } else {
853                 spin_unlock(&cl_envs_guard);
854                 env = cl_env_new(lu_context_tags_default,
855                                  lu_session_tags_default, debug);
856         }
857         RETURN(env);
858 }
859
860 static inline struct cl_env *cl_env_container(struct lu_env *env)
861 {
862         return container_of(env, struct cl_env, ce_lu);
863 }
864
865 struct lu_env *cl_env_peek(int *refcheck)
866 {
867         struct lu_env *env;
868         struct cl_env *cle;
869
870         CL_ENV_INC(lookup);
871
872         /* check that we don't go far from untrusted pointer */
873         CLASSERT(offsetof(struct cl_env, ce_magic) == 0);
874
875         env = NULL;
876         cle = cl_env_fetch();
877         if (cle != NULL) {
878                 CL_ENV_INC(hit);
879                 env = &cle->ce_lu;
880                 *refcheck = ++cle->ce_ref;
881         }
882         CDEBUG(D_OTHER, "%d@%p\n", cle ? cle->ce_ref : 0, cle);
883         return env;
884 }
885
886 /**
887  * Returns lu_env: if there already is an environment associated with the
888  * current thread, it is returned, otherwise, new environment is allocated.
889  *
890  * Allocations are amortized through the global cache of environments.
891  *
892  * \param refcheck pointer to a counter used to detect environment leaks. In
893  * the usual case cl_env_get() and cl_env_put() are called in the same lexical
894  * scope and pointer to the same integer is passed as \a refcheck. This is
895  * used to detect missed cl_env_put().
896  *
897  * \see cl_env_put()
898  */
899 struct lu_env *cl_env_get(int *refcheck)
900 {
901         struct lu_env *env;
902
903         env = cl_env_peek(refcheck);
904         if (env == NULL) {
905                 env = cl_env_obtain(__builtin_return_address(0));
906                 if (!IS_ERR(env)) {
907                         struct cl_env *cle;
908
909                         cle = cl_env_container(env);
910                         cl_env_attach(cle);
911                         *refcheck = cle->ce_ref;
912                         CDEBUG(D_OTHER, "%d@%p\n", cle->ce_ref, cle);
913                 }
914         }
915         return env;
916 }
917 EXPORT_SYMBOL(cl_env_get);
918
919 /**
920  * Forces an allocation of a fresh environment with given tags.
921  *
922  * \see cl_env_get()
923  */
924 struct lu_env *cl_env_alloc(int *refcheck, __u32 tags)
925 {
926         struct lu_env *env;
927
928         LASSERT(cl_env_peek(refcheck) == NULL);
929         env = cl_env_new(tags, tags, __builtin_return_address(0));
930         if (!IS_ERR(env)) {
931                 struct cl_env *cle;
932
933                 cle = cl_env_container(env);
934                 *refcheck = cle->ce_ref;
935                 CDEBUG(D_OTHER, "%d@%p\n", cle->ce_ref, cle);
936         }
937         return env;
938 }
939 EXPORT_SYMBOL(cl_env_alloc);
940
941 static void cl_env_exit(struct cl_env *cle)
942 {
943         LASSERT(cle->ce_owner == NULL);
944         lu_context_exit(&cle->ce_lu.le_ctx);
945         lu_context_exit(&cle->ce_ses);
946 }
947
948 /**
949  * Finalizes and frees a given number of cached environments. This is done to
950  * (1) free some memory (not currently hooked into VM), or (2) release
951  * references to modules.
952  */
953 unsigned cl_env_cache_purge(unsigned nr)
954 {
955         struct cl_env *cle;
956
957         ENTRY;
958         spin_lock(&cl_envs_guard);
959         for (; !list_empty(&cl_envs) && nr > 0; --nr) {
960                 cle = container_of(cl_envs.next, struct cl_env, ce_linkage);
961                 list_del_init(&cle->ce_linkage);
962                 LASSERT(cl_envs_cached_nr > 0);
963                 cl_envs_cached_nr--;
964                 spin_unlock(&cl_envs_guard);
965
966                 cl_env_fini(cle);
967                 spin_lock(&cl_envs_guard);
968         }
969         LASSERT(equi(cl_envs_cached_nr == 0, list_empty(&cl_envs)));
970         spin_unlock(&cl_envs_guard);
971         RETURN(nr);
972 }
973 EXPORT_SYMBOL(cl_env_cache_purge);
974
975 /**
976  * Release an environment.
977  *
978  * Decrement \a env reference counter. When counter drops to 0, nothing in
979  * this thread is using environment and it is returned to the allocation
980  * cache, or freed straight away, if cache is large enough.
981  */
982 void cl_env_put(struct lu_env *env, int *refcheck)
983 {
984         struct cl_env *cle;
985
986         cle = cl_env_container(env);
987
988         LASSERT(cle->ce_ref > 0);
989         LASSERT(ergo(refcheck != NULL, cle->ce_ref == *refcheck));
990
991         CDEBUG(D_OTHER, "%d@%p\n", cle->ce_ref, cle);
992         if (--cle->ce_ref == 0) {
993                 CL_ENV_DEC(busy);
994                 cl_env_detach(cle);
995                 cle->ce_debug = NULL;
996                 cl_env_exit(cle);
997                 /*
998                  * Don't bother to take a lock here.
999                  *
1000                  * Return environment to the cache only when it was allocated
1001                  * with the standard tags.
1002                  */
1003                 if (cl_envs_cached_nr < cl_envs_cached_max &&
1004                     (env->le_ctx.lc_tags & ~LCT_HAS_EXIT) == LCT_CL_THREAD &&
1005                     (env->le_ses->lc_tags & ~LCT_HAS_EXIT) == LCT_SESSION) {
1006                         spin_lock(&cl_envs_guard);
1007                         list_add(&cle->ce_linkage, &cl_envs);
1008                         cl_envs_cached_nr++;
1009                         spin_unlock(&cl_envs_guard);
1010                 } else
1011                         cl_env_fini(cle);
1012         }
1013 }
1014 EXPORT_SYMBOL(cl_env_put);
1015
1016 /**
1017  * Declares a point of re-entrancy.
1018  *
1019  * \see cl_env_reexit()
1020  */
1021 void *cl_env_reenter(void)
1022 {
1023         return cl_env_detach(NULL);
1024 }
1025 EXPORT_SYMBOL(cl_env_reenter);
1026
1027 /**
1028  * Exits re-entrancy.
1029  */
1030 void cl_env_reexit(void *cookie)
1031 {
1032         cl_env_detach(NULL);
1033         cl_env_attach(cookie);
1034 }
1035 EXPORT_SYMBOL(cl_env_reexit);
1036
1037 /**
1038  * Setup user-supplied \a env as a current environment. This is to be used to
1039  * guaranteed that environment exists even when cl_env_get() fails. It is up
1040  * to user to ensure proper concurrency control.
1041  *
1042  * \see cl_env_unplant()
1043  */
1044 void cl_env_implant(struct lu_env *env, int *refcheck)
1045 {
1046         struct cl_env *cle = cl_env_container(env);
1047
1048         LASSERT(cle->ce_ref > 0);
1049
1050         cl_env_attach(cle);
1051         cl_env_get(refcheck);
1052         CDEBUG(D_OTHER, "%d@%p\n", cle->ce_ref, cle);
1053 }
1054 EXPORT_SYMBOL(cl_env_implant);
1055
1056 /**
1057  * Detach environment installed earlier by cl_env_implant().
1058  */
1059 void cl_env_unplant(struct lu_env *env, int *refcheck)
1060 {
1061         struct cl_env *cle = cl_env_container(env);
1062
1063         LASSERT(cle->ce_ref > 1);
1064
1065         CDEBUG(D_OTHER, "%d@%p\n", cle->ce_ref, cle);
1066
1067         cl_env_detach(cle);
1068         cl_env_put(env, refcheck);
1069 }
1070 EXPORT_SYMBOL(cl_env_unplant);
1071
1072 struct lu_env *cl_env_nested_get(struct cl_env_nest *nest)
1073 {
1074         struct lu_env *env;
1075
1076         nest->cen_cookie = NULL;
1077         env = cl_env_peek(&nest->cen_refcheck);
1078         if (env != NULL) {
1079                 if (!cl_io_is_going(env))
1080                         return env;
1081                 else {
1082                         cl_env_put(env, &nest->cen_refcheck);
1083                         nest->cen_cookie = cl_env_reenter();
1084                 }
1085         }
1086         env = cl_env_get(&nest->cen_refcheck);
1087         if (IS_ERR(env)) {
1088                 cl_env_reexit(nest->cen_cookie);
1089                 return env;
1090         }
1091
1092         LASSERT(!cl_io_is_going(env));
1093         return env;
1094 }
1095 EXPORT_SYMBOL(cl_env_nested_get);
1096
1097 void cl_env_nested_put(struct cl_env_nest *nest, struct lu_env *env)
1098 {
1099         cl_env_put(env, &nest->cen_refcheck);
1100         cl_env_reexit(nest->cen_cookie);
1101 }
1102 EXPORT_SYMBOL(cl_env_nested_put);
1103
1104 /**
1105  * Converts struct cl_attr to struct ost_lvb.
1106  *
1107  * \see cl_lvb2attr
1108  */
1109 void cl_attr2lvb(struct ost_lvb *lvb, const struct cl_attr *attr)
1110 {
1111         ENTRY;
1112         lvb->lvb_size   = attr->cat_size;
1113         lvb->lvb_mtime  = attr->cat_mtime;
1114         lvb->lvb_atime  = attr->cat_atime;
1115         lvb->lvb_ctime  = attr->cat_ctime;
1116         lvb->lvb_blocks = attr->cat_blocks;
1117         EXIT;
1118 }
1119
1120 /**
1121  * Converts struct ost_lvb to struct cl_attr.
1122  *
1123  * \see cl_attr2lvb
1124  */
1125 void cl_lvb2attr(struct cl_attr *attr, const struct ost_lvb *lvb)
1126 {
1127         ENTRY;
1128         attr->cat_size   = lvb->lvb_size;
1129         attr->cat_mtime  = lvb->lvb_mtime;
1130         attr->cat_atime  = lvb->lvb_atime;
1131         attr->cat_ctime  = lvb->lvb_ctime;
1132         attr->cat_blocks = lvb->lvb_blocks;
1133         EXIT;
1134 }
1135 EXPORT_SYMBOL(cl_lvb2attr);
1136
1137 static struct cl_env cl_env_percpu[NR_CPUS];
1138
1139 static int cl_env_percpu_init(void)
1140 {
1141         struct cl_env *cle;
1142         int tags = LCT_REMEMBER | LCT_NOREF;
1143         int i, j;
1144         int rc = 0;
1145
1146         for_each_possible_cpu(i) {
1147                 struct lu_env *env;
1148
1149                 cle = &cl_env_percpu[i];
1150                 env = &cle->ce_lu;
1151
1152                 INIT_LIST_HEAD(&cle->ce_linkage);
1153                 cle->ce_magic = &cl_env_init0;
1154                 rc = lu_env_init(env, LCT_CL_THREAD | tags);
1155                 if (rc == 0) {
1156                         rc = lu_context_init(&cle->ce_ses, LCT_SESSION | tags);
1157                         if (rc == 0) {
1158                                 lu_context_enter(&cle->ce_ses);
1159                                 env->le_ses = &cle->ce_ses;
1160                         } else {
1161                                 lu_env_fini(env);
1162                         }
1163                 }
1164                 if (rc != 0)
1165                         break;
1166         }
1167         if (rc != 0) {
1168                 /* Indices 0 to i (excluding i) were correctly initialized,
1169                  * thus we must uninitialize up to i, the rest are undefined. */
1170                 for (j = 0; j < i; j++) {
1171                         cle = &cl_env_percpu[i];
1172                         lu_context_exit(&cle->ce_ses);
1173                         lu_context_fini(&cle->ce_ses);
1174                         lu_env_fini(&cle->ce_lu);
1175                 }
1176         }
1177
1178         return rc;
1179 }
1180
1181 static void cl_env_percpu_fini(void)
1182 {
1183         int i;
1184
1185         for_each_possible_cpu(i) {
1186                 struct cl_env *cle = &cl_env_percpu[i];
1187
1188                 lu_context_exit(&cle->ce_ses);
1189                 lu_context_fini(&cle->ce_ses);
1190                 lu_env_fini(&cle->ce_lu);
1191         }
1192 }
1193
1194 static void cl_env_percpu_refill(void)
1195 {
1196         int i;
1197
1198         for_each_possible_cpu(i)
1199                 lu_env_refill(&cl_env_percpu[i].ce_lu);
1200 }
1201
1202 void cl_env_percpu_put(struct lu_env *env)
1203 {
1204         struct cl_env *cle;
1205         int cpu;
1206
1207         cpu = smp_processor_id();
1208         cle = cl_env_container(env);
1209         LASSERT(cle == &cl_env_percpu[cpu]);
1210
1211         cle->ce_ref--;
1212         LASSERT(cle->ce_ref == 0);
1213
1214         CL_ENV_DEC(busy);
1215         cl_env_detach(cle);
1216         cle->ce_debug = NULL;
1217
1218         put_cpu();
1219 }
1220 EXPORT_SYMBOL(cl_env_percpu_put);
1221
1222 struct lu_env *cl_env_percpu_get()
1223 {
1224         struct cl_env *cle;
1225
1226         cle = &cl_env_percpu[get_cpu()];
1227         cl_env_init0(cle, __builtin_return_address(0));
1228
1229         cl_env_attach(cle);
1230         return &cle->ce_lu;
1231 }
1232 EXPORT_SYMBOL(cl_env_percpu_get);
1233
1234 /*****************************************************************************
1235  *
1236  * Temporary prototype thing: mirror obd-devices into cl devices.
1237  *
1238  */
1239
1240 struct cl_device *cl_type_setup(const struct lu_env *env, struct lu_site *site,
1241                                 struct lu_device_type *ldt,
1242                                 struct lu_device *next)
1243 {
1244         const char       *typename;
1245         struct lu_device *d;
1246
1247         LASSERT(ldt != NULL);
1248
1249         typename = ldt->ldt_name;
1250         d = ldt->ldt_ops->ldto_device_alloc(env, ldt, NULL);
1251         if (!IS_ERR(d)) {
1252                 int rc;
1253
1254                 if (site != NULL)
1255                         d->ld_site = site;
1256                 rc = ldt->ldt_ops->ldto_device_init(env, d, typename, next);
1257                 if (rc == 0) {
1258                         lu_device_get(d);
1259                         lu_ref_add(&d->ld_reference,
1260                                    "lu-stack", &lu_site_init);
1261                 } else {
1262                         ldt->ldt_ops->ldto_device_free(env, d);
1263                         CERROR("can't init device '%s', %d\n", typename, rc);
1264                         d = ERR_PTR(rc);
1265                 }
1266         } else
1267                 CERROR("Cannot allocate device: '%s'\n", typename);
1268         return lu2cl_dev(d);
1269 }
1270 EXPORT_SYMBOL(cl_type_setup);
1271
1272 /**
1273  * Finalize device stack by calling lu_stack_fini().
1274  */
1275 void cl_stack_fini(const struct lu_env *env, struct cl_device *cl)
1276 {
1277         lu_stack_fini(env, cl2lu_dev(cl));
1278 }
1279 EXPORT_SYMBOL(cl_stack_fini);
1280
1281 static struct lu_context_key cl_key;
1282
1283 struct cl_thread_info *cl_env_info(const struct lu_env *env)
1284 {
1285         return lu_context_key_get(&env->le_ctx, &cl_key);
1286 }
1287
1288 /* defines cl0_key_{init,fini}() */
1289 LU_KEY_INIT_FINI(cl0, struct cl_thread_info);
1290
1291 static void *cl_key_init(const struct lu_context *ctx,
1292                          struct lu_context_key *key)
1293 {
1294         struct cl_thread_info *info;
1295
1296         info = cl0_key_init(ctx, key);
1297         if (!IS_ERR(info)) {
1298                 size_t i;
1299
1300                 for (i = 0; i < ARRAY_SIZE(info->clt_counters); ++i)
1301                         lu_ref_init(&info->clt_counters[i].ctc_locks_locked);
1302         }
1303         return info;
1304 }
1305
1306 static void cl_key_fini(const struct lu_context *ctx,
1307                         struct lu_context_key *key, void *data)
1308 {
1309         struct cl_thread_info *info;
1310         size_t i;
1311
1312         info = data;
1313         for (i = 0; i < ARRAY_SIZE(info->clt_counters); ++i)
1314                 lu_ref_fini(&info->clt_counters[i].ctc_locks_locked);
1315         cl0_key_fini(ctx, key, data);
1316 }
1317
1318 static void cl_key_exit(const struct lu_context *ctx,
1319                         struct lu_context_key *key, void *data)
1320 {
1321         struct cl_thread_info *info = data;
1322         size_t i;
1323
1324         for (i = 0; i < ARRAY_SIZE(info->clt_counters); ++i) {
1325                 LASSERT(info->clt_counters[i].ctc_nr_held == 0);
1326                 LASSERT(info->clt_counters[i].ctc_nr_used == 0);
1327                 LASSERT(info->clt_counters[i].ctc_nr_locks_acquired == 0);
1328                 LASSERT(info->clt_counters[i].ctc_nr_locks_locked == 0);
1329                 lu_ref_fini(&info->clt_counters[i].ctc_locks_locked);
1330                 lu_ref_init(&info->clt_counters[i].ctc_locks_locked);
1331         }
1332 }
1333
1334 static struct lu_context_key cl_key = {
1335         .lct_tags = LCT_CL_THREAD,
1336         .lct_init = cl_key_init,
1337         .lct_fini = cl_key_fini,
1338         .lct_exit = cl_key_exit
1339 };
1340
1341 static struct lu_kmem_descr cl_object_caches[] = {
1342         {
1343                 .ckd_cache = &cl_env_kmem,
1344                 .ckd_name  = "cl_env_kmem",
1345                 .ckd_size  = sizeof (struct cl_env)
1346         },
1347         {
1348                 .ckd_cache = NULL
1349         }
1350 };
1351
1352 /**
1353  * Global initialization of cl-data. Create kmem caches, register
1354  * lu_context_key's, etc.
1355  *
1356  * \see cl_global_fini()
1357  */
1358 int cl_global_init(void)
1359 {
1360         int result;
1361
1362         INIT_LIST_HEAD(&cl_envs);
1363
1364         result = cl_env_store_init();
1365         if (result)
1366                 return result;
1367
1368         result = lu_kmem_init(cl_object_caches);
1369         if (result)
1370                 goto out_store;
1371
1372         LU_CONTEXT_KEY_INIT(&cl_key);
1373         result = lu_context_key_register(&cl_key);
1374         if (result)
1375                 goto out_kmem;
1376
1377         result = cl_env_percpu_init();
1378         if (result)
1379                 /* no cl_env_percpu_fini on error */
1380                 goto out_context;
1381
1382         return 0;
1383
1384 out_context:
1385         lu_context_key_degister(&cl_key);
1386 out_kmem:
1387         lu_kmem_fini(cl_object_caches);
1388 out_store:
1389         cl_env_store_fini();
1390         return result;
1391 }
1392
1393 /**
1394  * Finalization of global cl-data. Dual to cl_global_init().
1395  */
1396 void cl_global_fini(void)
1397 {
1398         cl_env_percpu_fini();
1399         lu_context_key_degister(&cl_key);
1400         lu_kmem_fini(cl_object_caches);
1401         cl_env_store_fini();
1402 }