Whamcloud - gitweb
730deb95ca24441cd89158cb70696517ff7087a4
[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.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, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  * Lustre is a trademark of Sun Microsystems, Inc.
31  *
32  * 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 <linux/list.h>
50 #include <libcfs/libcfs.h>
51 #include <obd_class.h>
52 #include <obd_support.h>
53 #include <lustre_fid.h>
54 #include <libcfs/libcfs_hash.h> /* for cfs_hash stuff */
55 #include <cl_object.h>
56 #include <lu_object.h>
57 #include "cl_internal.h"
58
59 static struct kmem_cache *cl_env_kmem;
60 struct kmem_cache *cl_dio_aio_kmem;
61 struct kmem_cache *cl_page_kmem_array[16];
62 unsigned short cl_page_kmem_size_array[16];
63
64 /** Lock class of cl_object_header::coh_attr_guard */
65 static struct lock_class_key cl_attr_guard_class;
66
67 /**
68  * Initialize cl_object_header.
69  */
70 int cl_object_header_init(struct cl_object_header *h)
71 {
72         int result;
73
74         ENTRY;
75         result = lu_object_header_init(&h->coh_lu);
76         if (result == 0) {
77                 spin_lock_init(&h->coh_attr_guard);
78                 lockdep_set_class(&h->coh_attr_guard, &cl_attr_guard_class);
79                 h->coh_page_bufsize = 0;
80         }
81         RETURN(result);
82 }
83 EXPORT_SYMBOL(cl_object_header_init);
84
85 /**
86  * Finalize cl_object_header.
87  */
88 void cl_object_header_fini(struct cl_object_header *h)
89 {
90         lu_object_header_fini(&h->coh_lu);
91 }
92
93 /**
94  * Returns a cl_object with a given \a fid.
95  *
96  * Returns either cached or newly created object. Additional reference on the
97  * returned object is acquired.
98  *
99  * \see lu_object_find(), cl_page_find(), cl_lock_find()
100  */
101 struct cl_object *cl_object_find(const struct lu_env *env,
102                                  struct cl_device *cd, const struct lu_fid *fid,
103                                  const struct cl_object_conf *c)
104 {
105         might_sleep();
106         return lu2cl(lu_object_find_slice(env, cl2lu_dev(cd), fid, &c->coc_lu));
107 }
108 EXPORT_SYMBOL(cl_object_find);
109
110 /**
111  * Releases a reference on \a o.
112  *
113  * When last reference is released object is returned to the cache, unless
114  * lu_object_header_flags::LU_OBJECT_HEARD_BANSHEE bit is set in its header.
115  *
116  * \see cl_page_put(), cl_lock_put().
117  */
118 void cl_object_put(const struct lu_env *env, struct cl_object *o)
119 {
120         lu_object_put(env, &o->co_lu);
121 }
122 EXPORT_SYMBOL(cl_object_put);
123
124 /**
125  * Acquire an additional reference to the object \a o.
126  *
127  * This can only be used to acquire _additional_ reference, i.e., caller
128  * already has to possess at least one reference to \a o before calling this.
129  *
130  * \see cl_page_get(), cl_lock_get().
131  */
132 void cl_object_get(struct cl_object *o)
133 {
134         lu_object_get(&o->co_lu);
135 }
136 EXPORT_SYMBOL(cl_object_get);
137
138 /**
139  * Returns the top-object for a given \a o.
140  *
141  * \see cl_io_top()
142  */
143 struct cl_object *cl_object_top(struct cl_object *o)
144 {
145         struct cl_object_header *hdr = cl_object_header(o);
146         struct cl_object *top;
147
148         while (hdr->coh_parent != NULL)
149                 hdr = hdr->coh_parent;
150
151         top = lu2cl(lu_object_top(&hdr->coh_lu));
152         CDEBUG(D_TRACE, "%p -> %p\n", o, top);
153         return top;
154 }
155 EXPORT_SYMBOL(cl_object_top);
156
157 /**
158  * Returns pointer to the lock protecting data-attributes for the given object
159  * \a o.
160  *
161  * Data-attributes are protected by the cl_object_header::coh_attr_guard
162  * spin-lock in the top-object.
163  *
164  * \see cl_attr, cl_object_attr_lock(), cl_object_operations::coo_attr_get().
165  */
166 static spinlock_t *cl_object_attr_guard(struct cl_object *o)
167 {
168         return &cl_object_header(cl_object_top(o))->coh_attr_guard;
169 }
170
171 /**
172  * Locks data-attributes.
173  *
174  * Prevents data-attributes from changing, until lock is released by
175  * cl_object_attr_unlock(). This has to be called before calls to
176  * cl_object_attr_get(), cl_object_attr_update().
177  */
178 void cl_object_attr_lock(struct cl_object *o)
179 __acquires(cl_object_attr_guard(o))
180 {
181         spin_lock(cl_object_attr_guard(o));
182 }
183 EXPORT_SYMBOL(cl_object_attr_lock);
184
185 /**
186  * Releases data-attributes lock, acquired by cl_object_attr_lock().
187  */
188 void cl_object_attr_unlock(struct cl_object *o)
189 __releases(cl_object_attr_guard(o))
190 {
191         spin_unlock(cl_object_attr_guard(o));
192 }
193 EXPORT_SYMBOL(cl_object_attr_unlock);
194
195 /**
196  * Returns data-attributes of an object \a obj.
197  *
198  * Every layer is asked (by calling cl_object_operations::coo_attr_get())
199  * top-to-bottom to fill in parts of \a attr that this layer is responsible
200  * for.
201  */
202 int cl_object_attr_get(const struct lu_env *env, struct cl_object *obj,
203                         struct cl_attr *attr)
204 {
205         struct lu_object_header *top;
206         int result;
207
208         assert_spin_locked(cl_object_attr_guard(obj));
209         ENTRY;
210
211         top = obj->co_lu.lo_header;
212         result = 0;
213         list_for_each_entry(obj, &top->loh_layers, co_lu.lo_linkage) {
214                 if (obj->co_ops->coo_attr_get != NULL) {
215                         result = obj->co_ops->coo_attr_get(env, obj, attr);
216                         if (result != 0) {
217                                 if (result > 0)
218                                         result = 0;
219                                 break;
220                         }
221                 }
222         }
223         RETURN(result);
224 }
225 EXPORT_SYMBOL(cl_object_attr_get);
226
227 /**
228  * Updates data-attributes of an object \a obj.
229  *
230  * Only attributes, mentioned in a validness bit-mask \a v are
231  * updated. Calls cl_object_operations::coo_upd_attr() on every layer, bottom
232  * to top.
233  */
234 int cl_object_attr_update(const struct lu_env *env, struct cl_object *obj,
235                           const struct cl_attr *attr, unsigned v)
236 {
237         struct lu_object_header *top;
238         int result;
239
240         assert_spin_locked(cl_object_attr_guard(obj));
241         ENTRY;
242
243         top = obj->co_lu.lo_header;
244         result = 0;
245         list_for_each_entry_reverse(obj, &top->loh_layers, co_lu.lo_linkage) {
246                 if (obj->co_ops->coo_attr_update != NULL) {
247                         result = obj->co_ops->coo_attr_update(env, obj, attr,
248                                                               v);
249                         if (result != 0) {
250                                 if (result > 0)
251                                         result = 0;
252                                 break;
253                         }
254                 }
255         }
256         RETURN(result);
257 }
258 EXPORT_SYMBOL(cl_object_attr_update);
259
260 /**
261  * Notifies layers (bottom-to-top) that glimpse AST was received.
262  *
263  * Layers have to fill \a lvb fields with information that will be shipped
264  * back to glimpse issuer.
265  *
266  * \see cl_lock_operations::clo_glimpse()
267  */
268 int cl_object_glimpse(const struct lu_env *env, struct cl_object *obj,
269                       struct ost_lvb *lvb)
270 {
271         struct lu_object_header *top;
272         int result;
273
274         ENTRY;
275         top = obj->co_lu.lo_header;
276         result = 0;
277         list_for_each_entry_reverse(obj, &top->loh_layers, co_lu.lo_linkage) {
278                 if (obj->co_ops->coo_glimpse != NULL) {
279                         result = obj->co_ops->coo_glimpse(env, obj, lvb);
280                         if (result != 0)
281                                 break;
282                 }
283         }
284         LU_OBJECT_HEADER(D_DLMTRACE, env, lu_object_top(top),
285                          "size: %llu mtime: %llu atime: %llu "
286                          "ctime: %llu blocks: %llu\n",
287                          lvb->lvb_size, lvb->lvb_mtime, lvb->lvb_atime,
288                          lvb->lvb_ctime, lvb->lvb_blocks);
289         RETURN(result);
290 }
291 EXPORT_SYMBOL(cl_object_glimpse);
292
293 /**
294  * Updates a configuration of an object \a obj.
295  */
296 int cl_conf_set(const struct lu_env *env, struct cl_object *obj,
297                 const struct cl_object_conf *conf)
298 {
299         struct lu_object_header *top;
300         int result;
301
302         ENTRY;
303         top = obj->co_lu.lo_header;
304         result = 0;
305         list_for_each_entry(obj, &top->loh_layers, co_lu.lo_linkage) {
306                 if (obj->co_ops->coo_conf_set != NULL) {
307                         result = obj->co_ops->coo_conf_set(env, obj, conf);
308                         if (result != 0)
309                                 break;
310                 }
311         }
312         RETURN(result);
313 }
314 EXPORT_SYMBOL(cl_conf_set);
315
316 /**
317  * Prunes caches of pages and locks for this object.
318  */
319 int cl_object_prune(const struct lu_env *env, struct cl_object *obj)
320 {
321         struct lu_object_header *top;
322         struct cl_object *o;
323         int result;
324         ENTRY;
325
326         top = obj->co_lu.lo_header;
327         result = 0;
328         list_for_each_entry(o, &top->loh_layers, co_lu.lo_linkage) {
329                 if (o->co_ops->coo_prune != NULL) {
330                         result = o->co_ops->coo_prune(env, o);
331                         if (result != 0)
332                                 break;
333                 }
334         }
335
336         RETURN(result);
337 }
338 EXPORT_SYMBOL(cl_object_prune);
339
340 /**
341  * Get stripe information of this object.
342  */
343 int cl_object_getstripe(const struct lu_env *env, struct cl_object *obj,
344                         struct lov_user_md __user *uarg, size_t size)
345 {
346         struct lu_object_header *top;
347         int                     result = 0;
348         ENTRY;
349
350         top = obj->co_lu.lo_header;
351         list_for_each_entry(obj, &top->loh_layers, co_lu.lo_linkage) {
352                 if (obj->co_ops->coo_getstripe != NULL) {
353                         result = obj->co_ops->coo_getstripe(env, obj, uarg,
354                                                             size);
355                         if (result != 0)
356                                 break;
357                 }
358         }
359         RETURN(result);
360 }
361 EXPORT_SYMBOL(cl_object_getstripe);
362
363 /**
364  * Get fiemap extents from file object.
365  *
366  * \param env [in]      lustre environment
367  * \param obj [in]      file object
368  * \param key [in]      fiemap request argument
369  * \param fiemap [out]  fiemap extents mapping retrived
370  * \param buflen [in]   max buffer length of @fiemap
371  *
372  * \retval 0    success
373  * \retval < 0  error
374  */
375 int cl_object_fiemap(const struct lu_env *env, struct cl_object *obj,
376                      struct ll_fiemap_info_key *key,
377                      struct fiemap *fiemap, size_t *buflen)
378 {
379         struct lu_object_header *top;
380         int                     result = 0;
381         ENTRY;
382
383         top = obj->co_lu.lo_header;
384         list_for_each_entry(obj, &top->loh_layers, co_lu.lo_linkage) {
385                 if (obj->co_ops->coo_fiemap != NULL) {
386                         result = obj->co_ops->coo_fiemap(env, obj, key, fiemap,
387                                                          buflen);
388                         if (result != 0)
389                                 break;
390                 }
391         }
392         RETURN(result);
393 }
394 EXPORT_SYMBOL(cl_object_fiemap);
395
396 int cl_object_layout_get(const struct lu_env *env, struct cl_object *obj,
397                          struct cl_layout *cl)
398 {
399         struct lu_object_header *top = obj->co_lu.lo_header;
400         ENTRY;
401
402         list_for_each_entry(obj, &top->loh_layers, co_lu.lo_linkage) {
403                 if (obj->co_ops->coo_layout_get != NULL)
404                         return obj->co_ops->coo_layout_get(env, obj, cl);
405         }
406
407         RETURN(-EOPNOTSUPP);
408 }
409 EXPORT_SYMBOL(cl_object_layout_get);
410
411 loff_t cl_object_maxbytes(struct cl_object *obj)
412 {
413         struct lu_object_header *top = obj->co_lu.lo_header;
414         loff_t maxbytes = LLONG_MAX;
415         ENTRY;
416
417         list_for_each_entry(obj, &top->loh_layers, co_lu.lo_linkage) {
418                 if (obj->co_ops->coo_maxbytes != NULL)
419                         maxbytes = min_t(loff_t, obj->co_ops->coo_maxbytes(obj),
420                                          maxbytes);
421         }
422
423         RETURN(maxbytes);
424 }
425 EXPORT_SYMBOL(cl_object_maxbytes);
426
427 int cl_object_flush(const struct lu_env *env, struct cl_object *obj,
428                          struct ldlm_lock *lock)
429 {
430         struct lu_object_header *top = obj->co_lu.lo_header;
431         int rc = 0;
432         ENTRY;
433
434         list_for_each_entry(obj, &top->loh_layers, co_lu.lo_linkage) {
435                 if (obj->co_ops->coo_object_flush) {
436                         rc = obj->co_ops->coo_object_flush(env, obj, lock);
437                         if (rc)
438                                 break;
439                 }
440         }
441         RETURN(rc);
442 }
443 EXPORT_SYMBOL(cl_object_flush);
444
445 /**
446  * Helper function removing all object locks, and marking object for
447  * deletion. All object pages must have been deleted at this point.
448  *
449  * This is called by cl_inode_fini() and lov_object_delete() to destroy top-
450  * and sub- objects respectively.
451  */
452 void cl_object_kill(const struct lu_env *env, struct cl_object *obj)
453 {
454         struct cl_object_header *hdr = cl_object_header(obj);
455
456         set_bit(LU_OBJECT_HEARD_BANSHEE, &hdr->coh_lu.loh_flags);
457 }
458 EXPORT_SYMBOL(cl_object_kill);
459
460 void cache_stats_init(struct cache_stats *cs, const char *name)
461 {
462         int i;
463
464         cs->cs_name = name;
465         for (i = 0; i < CS_NR; i++)
466                 atomic_set(&cs->cs_stats[i], 0);
467 }
468
469 static int cache_stats_print(const struct cache_stats *cs,
470                              struct seq_file *m, int h)
471 {
472         int i;
473
474         /*
475          *   lookup    hit    total  cached create
476          * env: ...... ...... ...... ...... ......
477          */
478         if (h) {
479                 const char *names[CS_NR] = CS_NAMES;
480
481                 seq_printf(m, "%6s", " ");
482                 for (i = 0; i < CS_NR; i++)
483                         seq_printf(m, "%8s", names[i]);
484                 seq_printf(m, "\n");
485         }
486
487         seq_printf(m, "%5.5s:", cs->cs_name);
488         for (i = 0; i < CS_NR; i++)
489                 seq_printf(m, "%8u", atomic_read(&cs->cs_stats[i]));
490         return 0;
491 }
492
493 static void cl_env_percpu_refill(void);
494
495 /**
496  * Initialize client site.
497  *
498  * Perform common initialization (lu_site_init()), and initialize statistical
499  * counters. Also perform global initializations on the first call.
500  */
501 int cl_site_init(struct cl_site *s, struct cl_device *d)
502 {
503         size_t i;
504         int result;
505
506         result = lu_site_init(&s->cs_lu, &d->cd_lu_dev);
507         if (result == 0) {
508                 cache_stats_init(&s->cs_pages, "pages");
509                 for (i = 0; i < ARRAY_SIZE(s->cs_pages_state); ++i)
510                         atomic_set(&s->cs_pages_state[0], 0);
511                 cl_env_percpu_refill();
512         }
513         return result;
514 }
515 EXPORT_SYMBOL(cl_site_init);
516
517 /**
518  * Finalize client site. Dual to cl_site_init().
519  */
520 void cl_site_fini(struct cl_site *s)
521 {
522         lu_site_fini(&s->cs_lu);
523 }
524 EXPORT_SYMBOL(cl_site_fini);
525
526 static struct cache_stats cl_env_stats = {
527         .cs_name    = "envs",
528         .cs_stats = { ATOMIC_INIT(0), }
529 };
530
531 /**
532  * Outputs client site statistical counters into a buffer. Suitable for
533  * ll_rd_*()-style functions.
534  */
535 int cl_site_stats_print(const struct cl_site *site, struct seq_file *m)
536 {
537         static const char *pstate[] = {
538                 [CPS_CACHED]    = "c",
539                 [CPS_OWNED]     = "o",
540                 [CPS_PAGEOUT]   = "w",
541                 [CPS_PAGEIN]    = "r",
542                 [CPS_FREEING]   = "f"
543         };
544         size_t i;
545
546 /*
547        lookup    hit  total   busy create
548 pages: ...... ...... ...... ...... ...... [...... ...... ...... ......]
549 locks: ...... ...... ...... ...... ...... [...... ...... ...... ...... ......]
550   env: ...... ...... ...... ...... ......
551  */
552         lu_site_stats_seq_print(&site->cs_lu, m);
553         cache_stats_print(&site->cs_pages, m, 1);
554         seq_printf(m, " [");
555         for (i = 0; i < ARRAY_SIZE(site->cs_pages_state); ++i)
556                 seq_printf(m, "%s: %u ", pstate[i],
557                            atomic_read(&site->cs_pages_state[i]));
558         seq_printf(m, "]\n");
559         cache_stats_print(&cl_env_stats, m, 0);
560         seq_printf(m, "\n");
561         return 0;
562 }
563 EXPORT_SYMBOL(cl_site_stats_print);
564
565 /*****************************************************************************
566  *
567  * lu_env handling on client.
568  *
569  */
570
571 /**
572  * The most efficient way is to store cl_env pointer in task specific
573  * structures. On Linux, it isn't easy to use task_struct->journal_info
574  * because Lustre code may call into other fs during memory reclaim, which
575  * has certain assumptions about journal_info. There are not currently any
576  * fields in task_struct that can be used for this purpose.
577  * \note As long as we use task_struct to store cl_env, we assume that once
578  * called into Lustre, we'll never call into the other part of the kernel
579  * which will use those fields in task_struct without explicitly exiting
580  * Lustre.
581  *
582  * Since there's no space in task_struct is available, hash will be used.
583  * bz20044, bz22683.
584  */
585
586 static unsigned cl_envs_cached_max = 32; /* XXX: prototype: arbitrary limit
587                                           * for now. */
588 static struct cl_env_cache {
589         rwlock_t                cec_guard;
590         unsigned                cec_count;
591         struct list_head        cec_envs;
592 } *cl_envs = NULL;
593
594 struct cl_env {
595         void             *ce_magic;
596         struct lu_env     ce_lu;
597         struct lu_context ce_ses;
598
599         /*
600          * Linkage into global list of all client environments. Used for
601          * garbage collection.
602          */
603         struct list_head  ce_linkage;
604         /*
605          *
606          */
607         int               ce_ref;
608         /*
609          * Debugging field: address of the caller who made original
610          * allocation.
611          */
612         void             *ce_debug;
613 };
614
615 static void cl_env_inc(enum cache_stats_item item)
616 {
617 #ifdef CONFIG_DEBUG_PAGESTATE_TRACKING
618         atomic_inc(&cl_env_stats.cs_stats[item]);
619 #endif
620 }
621
622 static void cl_env_dec(enum cache_stats_item item)
623 {
624 #ifdef CONFIG_DEBUG_PAGESTATE_TRACKING
625         LASSERT(atomic_read(&cl_env_stats.cs_stats[item]) > 0);
626         atomic_dec(&cl_env_stats.cs_stats[item]);
627 #endif
628 }
629
630 static void cl_env_init0(struct cl_env *cle, void *debug)
631 {
632         LASSERT(cle->ce_ref == 0);
633         LASSERT(cle->ce_magic == &cl_env_init0);
634         LASSERT(cle->ce_debug == NULL);
635
636         cle->ce_ref = 1;
637         cle->ce_debug = debug;
638         cl_env_inc(CS_busy);
639 }
640
641 static struct lu_env *cl_env_new(__u32 ctx_tags, __u32 ses_tags, void *debug)
642 {
643         struct lu_env *env;
644         struct cl_env *cle;
645
646         OBD_SLAB_ALLOC_PTR_GFP(cle, cl_env_kmem, GFP_NOFS);
647         if (cle != NULL) {
648                 int rc;
649
650                 INIT_LIST_HEAD(&cle->ce_linkage);
651                 cle->ce_magic = &cl_env_init0;
652                 env = &cle->ce_lu;
653                 rc = lu_env_init(env, LCT_CL_THREAD|ctx_tags);
654                 if (rc == 0) {
655                         rc = lu_context_init(&cle->ce_ses,
656                                              LCT_SESSION | ses_tags);
657                         if (rc == 0) {
658                                 lu_context_enter(&cle->ce_ses);
659                                 env->le_ses = &cle->ce_ses;
660                                 cl_env_init0(cle, debug);
661                         } else
662                                 lu_env_fini(env);
663                 }
664                 if (rc != 0) {
665                         OBD_SLAB_FREE_PTR(cle, cl_env_kmem);
666                         env = ERR_PTR(rc);
667                 } else {
668                         cl_env_inc(CS_create);
669                         cl_env_inc(CS_total);
670                 }
671         } else
672                 env = ERR_PTR(-ENOMEM);
673         return env;
674 }
675
676 static void cl_env_fini(struct cl_env *cle)
677 {
678         cl_env_dec(CS_total);
679         lu_context_fini(&cle->ce_lu.le_ctx);
680         lu_context_fini(&cle->ce_ses);
681         OBD_SLAB_FREE_PTR(cle, cl_env_kmem);
682 }
683
684 static struct lu_env *cl_env_obtain(void *debug)
685 {
686         struct cl_env *cle;
687         struct lu_env *env;
688         int cpu = get_cpu();
689
690         ENTRY;
691
692         read_lock(&cl_envs[cpu].cec_guard);
693         LASSERT(equi(cl_envs[cpu].cec_count == 0,
694                 list_empty(&cl_envs[cpu].cec_envs)));
695         if (cl_envs[cpu].cec_count > 0) {
696                 int rc;
697
698                 cle = container_of(cl_envs[cpu].cec_envs.next, struct cl_env,
699                                    ce_linkage);
700                 list_del_init(&cle->ce_linkage);
701                 cl_envs[cpu].cec_count--;
702                 read_unlock(&cl_envs[cpu].cec_guard);
703                 put_cpu();
704
705                 env = &cle->ce_lu;
706                 rc = lu_env_refill(env);
707                 if (rc == 0) {
708                         cl_env_init0(cle, debug);
709                         lu_context_enter(&env->le_ctx);
710                         lu_context_enter(&cle->ce_ses);
711                 } else {
712                         cl_env_fini(cle);
713                         env = ERR_PTR(rc);
714                 }
715         } else {
716                 read_unlock(&cl_envs[cpu].cec_guard);
717                 put_cpu();
718                 env = cl_env_new(lu_context_tags_default,
719                                  lu_session_tags_default, debug);
720         }
721         RETURN(env);
722 }
723
724 static inline struct cl_env *cl_env_container(struct lu_env *env)
725 {
726         return container_of(env, struct cl_env, ce_lu);
727 }
728
729 /**
730  * Returns lu_env: if there already is an environment associated with the
731  * current thread, it is returned, otherwise, new environment is allocated.
732  *
733  * Allocations are amortized through the global cache of environments.
734  *
735  * \param refcheck pointer to a counter used to detect environment leaks. In
736  * the usual case cl_env_get() and cl_env_put() are called in the same lexical
737  * scope and pointer to the same integer is passed as \a refcheck. This is
738  * used to detect missed cl_env_put().
739  *
740  * \see cl_env_put()
741  */
742 struct lu_env *cl_env_get(__u16 *refcheck)
743 {
744         struct lu_env *env;
745
746         env = cl_env_obtain(__builtin_return_address(0));
747         if (!IS_ERR(env)) {
748                 struct cl_env *cle;
749
750                 cle = cl_env_container(env);
751                 *refcheck = cle->ce_ref;
752                 CDEBUG(D_OTHER, "%d@%p\n", cle->ce_ref, cle);
753         }
754         return env;
755 }
756 EXPORT_SYMBOL(cl_env_get);
757
758 /**
759  * Forces an allocation of a fresh environment with given tags.
760  *
761  * \see cl_env_get()
762  */
763 struct lu_env *cl_env_alloc(__u16 *refcheck, __u32 tags)
764 {
765         struct lu_env *env;
766
767         env = cl_env_new(tags, tags, __builtin_return_address(0));
768         if (!IS_ERR(env)) {
769                 struct cl_env *cle;
770
771                 cle = cl_env_container(env);
772                 *refcheck = cle->ce_ref;
773                 CDEBUG(D_OTHER, "%d@%p\n", cle->ce_ref, cle);
774         }
775         return env;
776 }
777 EXPORT_SYMBOL(cl_env_alloc);
778
779 static void cl_env_exit(struct cl_env *cle)
780 {
781         lu_context_exit(&cle->ce_lu.le_ctx);
782         lu_context_exit(&cle->ce_ses);
783 }
784
785 /**
786  * Finalizes and frees a given number of cached environments. This is done to
787  * (1) free some memory (not currently hooked into VM), or (2) release
788  * references to modules.
789  */
790 unsigned cl_env_cache_purge(unsigned nr)
791 {
792         struct cl_env *cle;
793         unsigned i;
794
795         ENTRY;
796         for_each_possible_cpu(i) {
797                 write_lock(&cl_envs[i].cec_guard);
798                 for (; !list_empty(&cl_envs[i].cec_envs) && nr > 0; --nr) {
799                         cle = container_of(cl_envs[i].cec_envs.next,
800                                            struct cl_env, ce_linkage);
801                         list_del_init(&cle->ce_linkage);
802                         LASSERT(cl_envs[i].cec_count > 0);
803                         cl_envs[i].cec_count--;
804                         write_unlock(&cl_envs[i].cec_guard);
805
806                         cl_env_fini(cle);
807                         write_lock(&cl_envs[i].cec_guard);
808                 }
809                 LASSERT(equi(cl_envs[i].cec_count == 0,
810                         list_empty(&cl_envs[i].cec_envs)));
811                 write_unlock(&cl_envs[i].cec_guard);
812         }
813         RETURN(nr);
814 }
815 EXPORT_SYMBOL(cl_env_cache_purge);
816
817 /**
818  * Release an environment.
819  *
820  * Decrement \a env reference counter. When counter drops to 0, nothing in
821  * this thread is using environment and it is returned to the allocation
822  * cache, or freed straight away, if cache is large enough.
823  */
824 void cl_env_put(struct lu_env *env, __u16 *refcheck)
825 {
826         struct cl_env *cle;
827
828         cle = cl_env_container(env);
829
830         LASSERT(cle->ce_ref > 0);
831         LASSERT(ergo(refcheck != NULL, cle->ce_ref == *refcheck));
832
833         CDEBUG(D_OTHER, "%d@%p\n", cle->ce_ref, cle);
834         if (--cle->ce_ref == 0) {
835                 int cpu = get_cpu();
836
837                 cl_env_dec(CS_busy);
838                 cle->ce_debug = NULL;
839                 cl_env_exit(cle);
840                 /*
841                  * Don't bother to take a lock here.
842                  *
843                  * Return environment to the cache only when it was allocated
844                  * with the standard tags.
845                  */
846                 if (cl_envs[cpu].cec_count < cl_envs_cached_max &&
847                     (env->le_ctx.lc_tags & ~LCT_HAS_EXIT) == lu_context_tags_default &&
848                     (env->le_ses->lc_tags & ~LCT_HAS_EXIT) == lu_session_tags_default) {
849                         read_lock(&cl_envs[cpu].cec_guard);
850                         list_add(&cle->ce_linkage, &cl_envs[cpu].cec_envs);
851                         cl_envs[cpu].cec_count++;
852                         read_unlock(&cl_envs[cpu].cec_guard);
853                 } else
854                         cl_env_fini(cle);
855                 put_cpu();
856         }
857 }
858 EXPORT_SYMBOL(cl_env_put);
859
860 /**
861  * Converts struct cl_attr to struct ost_lvb.
862  *
863  * \see cl_lvb2attr
864  */
865 void cl_attr2lvb(struct ost_lvb *lvb, const struct cl_attr *attr)
866 {
867         lvb->lvb_size   = attr->cat_size;
868         lvb->lvb_mtime  = attr->cat_mtime;
869         lvb->lvb_atime  = attr->cat_atime;
870         lvb->lvb_ctime  = attr->cat_ctime;
871         lvb->lvb_blocks = attr->cat_blocks;
872 }
873
874 /**
875  * Converts struct ost_lvb to struct cl_attr.
876  *
877  * \see cl_attr2lvb
878  */
879 void cl_lvb2attr(struct cl_attr *attr, const struct ost_lvb *lvb)
880 {
881         attr->cat_size   = lvb->lvb_size;
882         attr->cat_mtime  = lvb->lvb_mtime;
883         attr->cat_atime  = lvb->lvb_atime;
884         attr->cat_ctime  = lvb->lvb_ctime;
885         attr->cat_blocks = lvb->lvb_blocks;
886 }
887 EXPORT_SYMBOL(cl_lvb2attr);
888
889 static struct cl_env cl_env_percpu[NR_CPUS];
890
891 static int cl_env_percpu_init(void)
892 {
893         struct cl_env *cle;
894         int tags = LCT_REMEMBER | LCT_NOREF;
895         int i, j;
896         int rc = 0;
897
898         for_each_possible_cpu(i) {
899                 struct lu_env *env;
900
901                 rwlock_init(&cl_envs[i].cec_guard);
902                 INIT_LIST_HEAD(&cl_envs[i].cec_envs);
903                 cl_envs[i].cec_count = 0;
904
905                 cle = &cl_env_percpu[i];
906                 env = &cle->ce_lu;
907
908                 INIT_LIST_HEAD(&cle->ce_linkage);
909                 cle->ce_magic = &cl_env_init0;
910                 rc = lu_env_init(env, LCT_CL_THREAD | tags);
911                 if (rc == 0) {
912                         rc = lu_context_init(&cle->ce_ses, LCT_SESSION | tags);
913                         if (rc == 0) {
914                                 lu_context_enter(&cle->ce_ses);
915                                 env->le_ses = &cle->ce_ses;
916                         } else {
917                                 lu_env_fini(env);
918                         }
919                 }
920                 if (rc != 0)
921                         break;
922         }
923         if (rc != 0) {
924                 /* Indices 0 to i (excluding i) were correctly initialized,
925                  * thus we must uninitialize up to i, the rest are undefined. */
926                 for (j = 0; j < i; j++) {
927                         cle = &cl_env_percpu[j];
928                         lu_context_exit(&cle->ce_ses);
929                         lu_context_fini(&cle->ce_ses);
930                         lu_env_fini(&cle->ce_lu);
931                 }
932         }
933
934         return rc;
935 }
936
937 static void cl_env_percpu_fini(void)
938 {
939         int i;
940
941         for_each_possible_cpu(i) {
942                 struct cl_env *cle = &cl_env_percpu[i];
943
944                 lu_context_exit(&cle->ce_ses);
945                 lu_context_fini(&cle->ce_ses);
946                 lu_env_fini(&cle->ce_lu);
947         }
948 }
949
950 static void cl_env_percpu_refill(void)
951 {
952         int i;
953
954         for_each_possible_cpu(i)
955                 lu_env_refill(&cl_env_percpu[i].ce_lu);
956 }
957
958 void cl_env_percpu_put(struct lu_env *env)
959 {
960         struct cl_env *cle;
961         int cpu;
962
963         cpu = smp_processor_id();
964         cle = cl_env_container(env);
965         LASSERT(cle == &cl_env_percpu[cpu]);
966
967         cle->ce_ref--;
968         LASSERT(cle->ce_ref == 0);
969
970         cl_env_dec(CS_busy);
971         cle->ce_debug = NULL;
972
973         put_cpu();
974 }
975 EXPORT_SYMBOL(cl_env_percpu_put);
976
977 struct lu_env *cl_env_percpu_get(void)
978 {
979         struct cl_env *cle;
980
981         cle = &cl_env_percpu[get_cpu()];
982         cl_env_init0(cle, __builtin_return_address(0));
983
984         return &cle->ce_lu;
985 }
986 EXPORT_SYMBOL(cl_env_percpu_get);
987
988 /*****************************************************************************
989  *
990  * Temporary prototype thing: mirror obd-devices into cl devices.
991  *
992  */
993
994 struct cl_device *cl_type_setup(const struct lu_env *env, struct lu_site *site,
995                                 struct lu_device_type *ldt,
996                                 struct lu_device *next)
997 {
998         const char       *typename;
999         struct lu_device *d;
1000
1001         LASSERT(ldt != NULL);
1002
1003         typename = ldt->ldt_name;
1004         d = ldt->ldt_ops->ldto_device_alloc(env, ldt, NULL);
1005         if (!IS_ERR(d)) {
1006                 int rc;
1007
1008                 if (site != NULL)
1009                         d->ld_site = site;
1010                 rc = ldt->ldt_ops->ldto_device_init(env, d, typename, next);
1011                 if (rc == 0) {
1012                         lu_device_get(d);
1013                         lu_ref_add(&d->ld_reference,
1014                                    "lu-stack", &lu_site_init);
1015                 } else {
1016                         ldt->ldt_ops->ldto_device_free(env, d);
1017                         CERROR("can't init device '%s', %d\n", typename, rc);
1018                         d = ERR_PTR(rc);
1019                 }
1020         } else
1021                 CERROR("Cannot allocate device: '%s'\n", typename);
1022         return lu2cl_dev(d);
1023 }
1024 EXPORT_SYMBOL(cl_type_setup);
1025
1026 /**
1027  * Finalize device stack by calling lu_stack_fini().
1028  */
1029 void cl_stack_fini(const struct lu_env *env, struct cl_device *cl)
1030 {
1031         lu_stack_fini(env, cl2lu_dev(cl));
1032 }
1033 EXPORT_SYMBOL(cl_stack_fini);
1034
1035 static struct lu_context_key cl_key;
1036
1037 struct cl_thread_info *cl_env_info(const struct lu_env *env)
1038 {
1039         return lu_context_key_get(&env->le_ctx, &cl_key);
1040 }
1041
1042 /* defines cl_key_{init,fini}() */
1043 LU_KEY_INIT_FINI(cl, struct cl_thread_info);
1044
1045 static struct lu_context_key cl_key = {
1046         .lct_tags = LCT_CL_THREAD,
1047         .lct_init = cl_key_init,
1048         .lct_fini = cl_key_fini,
1049 };
1050
1051 static struct lu_kmem_descr cl_object_caches[] = {
1052         {
1053                 .ckd_cache = &cl_env_kmem,
1054                 .ckd_name  = "cl_env_kmem",
1055                 .ckd_size  = sizeof(struct cl_env)
1056         },
1057         {
1058                 .ckd_cache = &cl_dio_aio_kmem,
1059                 .ckd_name  = "cl_dio_aio_kmem",
1060                 .ckd_size  = sizeof(struct cl_dio_aio)
1061         },
1062         {
1063                 .ckd_cache = NULL
1064         }
1065 };
1066
1067 /**
1068  * Global initialization of cl-data. Create kmem caches, register
1069  * lu_context_key's, etc.
1070  *
1071  * \see cl_global_fini()
1072  */
1073 int cl_global_init(void)
1074 {
1075         int result;
1076
1077         OBD_ALLOC_PTR_ARRAY(cl_envs, num_possible_cpus());
1078         if (cl_envs == NULL)
1079                 GOTO(out, result = -ENOMEM);
1080
1081         result = lu_kmem_init(cl_object_caches);
1082         if (result)
1083                 GOTO(out_envs, result);
1084
1085         LU_CONTEXT_KEY_INIT(&cl_key);
1086         result = lu_context_key_register(&cl_key);
1087         if (result)
1088                 GOTO(out_kmem, result);
1089
1090         result = cl_env_percpu_init();
1091         if (result) /* no cl_env_percpu_fini on error */
1092                 GOTO(out_keys, result);
1093
1094         return 0;
1095
1096 out_keys:
1097         lu_context_key_degister(&cl_key);
1098 out_kmem:
1099         lu_kmem_fini(cl_object_caches);
1100 out_envs:
1101         OBD_FREE_PTR_ARRAY(cl_envs, num_possible_cpus());
1102 out:
1103         return result;
1104 }
1105
1106 /**
1107  * Finalization of global cl-data. Dual to cl_global_init().
1108  */
1109 void cl_global_fini(void)
1110 {
1111         int i;
1112
1113         for (i = 0; i < ARRAY_SIZE(cl_page_kmem_array); i++) {
1114                 if (cl_page_kmem_array[i]) {
1115                         kmem_cache_destroy(cl_page_kmem_array[i]);
1116                         cl_page_kmem_array[i] = NULL;
1117                 }
1118         }
1119         cl_env_percpu_fini();
1120         lu_context_key_degister(&cl_key);
1121         lu_kmem_fini(cl_object_caches);
1122         OBD_FREE_PTR_ARRAY(cl_envs, num_possible_cpus());
1123 }