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