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