GNU Linux-libre 4.9.317-gnu1
[releases.git] / drivers / staging / lustre / lustre / include / lu_object.h
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 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
33 #ifndef __LUSTRE_LU_OBJECT_H
34 #define __LUSTRE_LU_OBJECT_H
35
36 #include <stdarg.h>
37 #include "../../include/linux/libcfs/libcfs.h"
38 #include "lustre/lustre_idl.h"
39 #include "lu_ref.h"
40
41 struct seq_file;
42 struct lustre_cfg;
43 struct lprocfs_stats;
44
45 /** \defgroup lu lu
46  * lu_* data-types represent server-side entities shared by data and meta-data
47  * stacks.
48  *
49  * Design goals:
50  *
51  * -# support for layering.
52  *
53  *     Server side object is split into layers, one per device in the
54  *     corresponding device stack. Individual layer is represented by struct
55  *     lu_object. Compound layered object --- by struct lu_object_header. Most
56  *     interface functions take lu_object as an argument and operate on the
57  *     whole compound object. This decision was made due to the following
58  *     reasons:
59  *
60  *      - it's envisaged that lu_object will be used much more often than
61  *      lu_object_header;
62  *
63  *      - we want lower (non-top) layers to be able to initiate operations
64  *      on the whole object.
65  *
66  *     Generic code supports layering more complex than simple stacking, e.g.,
67  *     it is possible that at some layer object "spawns" multiple sub-objects
68  *     on the lower layer.
69  *
70  * -# fid-based identification.
71  *
72  *     Compound object is uniquely identified by its fid. Objects are indexed
73  *     by their fids (hash table is used for index).
74  *
75  * -# caching and life-cycle management.
76  *
77  *     Object's life-time is controlled by reference counting. When reference
78  *     count drops to 0, object is returned to cache. Cached objects still
79  *     retain their identity (i.e., fid), and can be recovered from cache.
80  *
81  *     Objects are kept in the global LRU list, and lu_site_purge() function
82  *     can be used to reclaim given number of unused objects from the tail of
83  *     the LRU.
84  *
85  * -# avoiding recursion.
86  *
87  *     Generic code tries to replace recursion through layers by iterations
88  *     where possible. Additionally to the end of reducing stack consumption,
89  *     data, when practically possible, are allocated through lu_context_key
90  *     interface rather than on stack.
91  * @{
92  */
93
94 struct lu_site;
95 struct lu_object;
96 struct lu_device;
97 struct lu_object_header;
98 struct lu_context;
99 struct lu_env;
100
101 /**
102  * Operations common for data and meta-data devices.
103  */
104 struct lu_device_operations {
105         /**
106          * Allocate object for the given device (without lower-layer
107          * parts). This is called by lu_object_operations::loo_object_init()
108          * from the parent layer, and should setup at least lu_object::lo_dev
109          * and lu_object::lo_ops fields of resulting lu_object.
110          *
111          * Object creation protocol.
112          *
113          * Due to design goal of avoiding recursion, object creation (see
114          * lu_object_alloc()) is somewhat involved:
115          *
116          *  - first, lu_device_operations::ldo_object_alloc() method of the
117          *  top-level device in the stack is called. It should allocate top
118          *  level object (including lu_object_header), but without any
119          *  lower-layer sub-object(s).
120          *
121          *  - then lu_object_alloc() sets fid in the header of newly created
122          *  object.
123          *
124          *  - then lu_object_operations::loo_object_init() is called. It has
125          *  to allocate lower-layer object(s). To do this,
126          *  lu_object_operations::loo_object_init() calls ldo_object_alloc()
127          *  of the lower-layer device(s).
128          *
129          *  - for all new objects allocated by
130          *  lu_object_operations::loo_object_init() (and inserted into object
131          *  stack), lu_object_operations::loo_object_init() is called again
132          *  repeatedly, until no new objects are created.
133          *
134          * \post ergo(!IS_ERR(result), result->lo_dev == d &&
135          *                           result->lo_ops != NULL);
136          */
137         struct lu_object *(*ldo_object_alloc)(const struct lu_env *env,
138                                               const struct lu_object_header *h,
139                                               struct lu_device *d);
140         /**
141          * process config specific for device.
142          */
143         int (*ldo_process_config)(const struct lu_env *env,
144                                   struct lu_device *, struct lustre_cfg *);
145         int (*ldo_recovery_complete)(const struct lu_env *,
146                                      struct lu_device *);
147
148         /**
149          * initialize local objects for device. this method called after layer has
150          * been initialized (after LCFG_SETUP stage) and before it starts serving
151          * user requests.
152          */
153
154         int (*ldo_prepare)(const struct lu_env *,
155                            struct lu_device *parent,
156                            struct lu_device *dev);
157
158 };
159
160 /**
161  * For lu_object_conf flags
162  */
163 enum loc_flags {
164         /* This is a new object to be allocated, or the file
165          * corresponding to the object does not exists.
166          */
167         LOC_F_NEW       = 0x00000001,
168 };
169
170 /**
171  * Object configuration, describing particulars of object being created. On
172  * server this is not used, as server objects are full identified by fid. On
173  * client configuration contains struct lustre_md.
174  */
175 struct lu_object_conf {
176         /**
177          * Some hints for obj find and alloc.
178          */
179         enum loc_flags     loc_flags;
180 };
181
182 /**
183  * Type of "printer" function used by lu_object_operations::loo_object_print()
184  * method.
185  *
186  * Printer function is needed to provide some flexibility in (semi-)debugging
187  * output: possible implementations: printk, CDEBUG, sysfs/seq_file
188  */
189 typedef int (*lu_printer_t)(const struct lu_env *env,
190                             void *cookie, const char *format, ...)
191         __printf(3, 4);
192
193 /**
194  * Operations specific for particular lu_object.
195  */
196 struct lu_object_operations {
197         /**
198          * Allocate lower-layer parts of the object by calling
199          * lu_device_operations::ldo_object_alloc() of the corresponding
200          * underlying device.
201          *
202          * This method is called once for each object inserted into object
203          * stack. It's responsibility of this method to insert lower-layer
204          * object(s) it create into appropriate places of object stack.
205          */
206         int (*loo_object_init)(const struct lu_env *env,
207                                struct lu_object *o,
208                                const struct lu_object_conf *conf);
209         /**
210          * Called (in top-to-bottom order) during object allocation after all
211          * layers were allocated and initialized. Can be used to perform
212          * initialization depending on lower layers.
213          */
214         int (*loo_object_start)(const struct lu_env *env,
215                                 struct lu_object *o);
216         /**
217          * Called before lu_object_operations::loo_object_free() to signal
218          * that object is being destroyed. Dual to
219          * lu_object_operations::loo_object_init().
220          */
221         void (*loo_object_delete)(const struct lu_env *env,
222                                   struct lu_object *o);
223         /**
224          * Dual to lu_device_operations::ldo_object_alloc(). Called when
225          * object is removed from memory.
226          */
227         void (*loo_object_free)(const struct lu_env *env,
228                                 struct lu_object *o);
229         /**
230          * Called when last active reference to the object is released (and
231          * object returns to the cache). This method is optional.
232          */
233         void (*loo_object_release)(const struct lu_env *env,
234                                    struct lu_object *o);
235         /**
236          * Optional debugging helper. Print given object.
237          */
238         int (*loo_object_print)(const struct lu_env *env, void *cookie,
239                                 lu_printer_t p, const struct lu_object *o);
240         /**
241          * Optional debugging method. Returns true iff method is internally
242          * consistent.
243          */
244         int (*loo_object_invariant)(const struct lu_object *o);
245 };
246
247 /**
248  * Type of lu_device.
249  */
250 struct lu_device_type;
251
252 /**
253  * Device: a layer in the server side abstraction stacking.
254  */
255 struct lu_device {
256         /**
257          * reference count. This is incremented, in particular, on each object
258          * created at this layer.
259          *
260          * \todo XXX which means that atomic_t is probably too small.
261          */
262         atomic_t                       ld_ref;
263         /**
264          * Pointer to device type. Never modified once set.
265          */
266         struct lu_device_type       *ld_type;
267         /**
268          * Operation vector for this device.
269          */
270         const struct lu_device_operations *ld_ops;
271         /**
272          * Stack this device belongs to.
273          */
274         struct lu_site              *ld_site;
275
276         /** \todo XXX: temporary back pointer into obd. */
277         struct obd_device                *ld_obd;
278         /**
279          * A list of references to this object, for debugging.
280          */
281         struct lu_ref                 ld_reference;
282         /**
283          * Link the device to the site.
284          **/
285         struct list_head                         ld_linkage;
286 };
287
288 struct lu_device_type_operations;
289
290 /**
291  * Tag bits for device type. They are used to distinguish certain groups of
292  * device types.
293  */
294 enum lu_device_tag {
295         /** this is meta-data device */
296         LU_DEVICE_MD = (1 << 0),
297         /** this is data device */
298         LU_DEVICE_DT = (1 << 1),
299         /** data device in the client stack */
300         LU_DEVICE_CL = (1 << 2)
301 };
302
303 /**
304  * Type of device.
305  */
306 struct lu_device_type {
307         /**
308          * Tag bits. Taken from enum lu_device_tag. Never modified once set.
309          */
310         __u32                              ldt_tags;
311         /**
312          * Name of this class. Unique system-wide. Never modified once set.
313          */
314         char                               *ldt_name;
315         /**
316          * Operations for this type.
317          */
318         const struct lu_device_type_operations *ldt_ops;
319         /**
320          * \todo XXX: temporary pointer to associated obd_type.
321          */
322         struct obd_type                 *ldt_obd_type;
323         /**
324          * \todo XXX: temporary: context tags used by obd_*() calls.
325          */
326         __u32                              ldt_ctx_tags;
327         /**
328          * Number of existing device type instances.
329          */
330         atomic_t                                ldt_device_nr;
331         /**
332          * Linkage into a global list of all device types.
333          *
334          * \see lu_device_types.
335          */
336         struct list_head                              ldt_linkage;
337 };
338
339 /**
340  * Operations on a device type.
341  */
342 struct lu_device_type_operations {
343         /**
344          * Allocate new device.
345          */
346         struct lu_device *(*ldto_device_alloc)(const struct lu_env *env,
347                                                struct lu_device_type *t,
348                                                struct lustre_cfg *lcfg);
349         /**
350          * Free device. Dual to
351          * lu_device_type_operations::ldto_device_alloc(). Returns pointer to
352          * the next device in the stack.
353          */
354         struct lu_device *(*ldto_device_free)(const struct lu_env *,
355                                               struct lu_device *);
356
357         /**
358          * Initialize the devices after allocation
359          */
360         int  (*ldto_device_init)(const struct lu_env *env,
361                                  struct lu_device *, const char *,
362                                  struct lu_device *);
363         /**
364          * Finalize device. Dual to
365          * lu_device_type_operations::ldto_device_init(). Returns pointer to
366          * the next device in the stack.
367          */
368         struct lu_device *(*ldto_device_fini)(const struct lu_env *env,
369                                               struct lu_device *);
370         /**
371          * Initialize device type. This is called on module load.
372          */
373         int  (*ldto_init)(struct lu_device_type *t);
374         /**
375          * Finalize device type. Dual to
376          * lu_device_type_operations::ldto_init(). Called on module unload.
377          */
378         void (*ldto_fini)(struct lu_device_type *t);
379         /**
380          * Called when the first device is created.
381          */
382         void (*ldto_start)(struct lu_device_type *t);
383         /**
384          * Called when number of devices drops to 0.
385          */
386         void (*ldto_stop)(struct lu_device_type *t);
387 };
388
389 static inline int lu_device_is_md(const struct lu_device *d)
390 {
391         return ergo(d, d->ld_type->ldt_tags & LU_DEVICE_MD);
392 }
393
394 /**
395  * Common object attributes.
396  */
397 struct lu_attr {
398         /** size in bytes */
399         __u64     la_size;
400         /** modification time in seconds since Epoch */
401         s64       la_mtime;
402         /** access time in seconds since Epoch */
403         s64       la_atime;
404         /** change time in seconds since Epoch */
405         s64       la_ctime;
406         /** 512-byte blocks allocated to object */
407         __u64     la_blocks;
408         /** permission bits and file type */
409         __u32     la_mode;
410         /** owner id */
411         __u32     la_uid;
412         /** group id */
413         __u32     la_gid;
414         /** object flags */
415         __u32     la_flags;
416         /** number of persistent references to this object */
417         __u32     la_nlink;
418         /** blk bits of the object*/
419         __u32     la_blkbits;
420         /** blk size of the object*/
421         __u32     la_blksize;
422         /** real device */
423         __u32     la_rdev;
424         /**
425          * valid bits
426          *
427          * \see enum la_valid
428          */
429         __u64     la_valid;
430 };
431
432 /** Bit-mask of valid attributes */
433 enum la_valid {
434         LA_ATIME = 1 << 0,
435         LA_MTIME = 1 << 1,
436         LA_CTIME = 1 << 2,
437         LA_SIZE  = 1 << 3,
438         LA_MODE  = 1 << 4,
439         LA_UID   = 1 << 5,
440         LA_GID   = 1 << 6,
441         LA_BLOCKS = 1 << 7,
442         LA_TYPE   = 1 << 8,
443         LA_FLAGS  = 1 << 9,
444         LA_NLINK  = 1 << 10,
445         LA_RDEV   = 1 << 11,
446         LA_BLKSIZE = 1 << 12,
447         LA_KILL_SUID = 1 << 13,
448         LA_KILL_SGID = 1 << 14,
449 };
450
451 /**
452  * Layer in the layered object.
453  */
454 struct lu_object {
455         /**
456          * Header for this object.
457          */
458         struct lu_object_header    *lo_header;
459         /**
460          * Device for this layer.
461          */
462         struct lu_device                  *lo_dev;
463         /**
464          * Operations for this object.
465          */
466         const struct lu_object_operations *lo_ops;
467         /**
468          * Linkage into list of all layers.
469          */
470         struct list_head                         lo_linkage;
471         /**
472          * Link to the device, for debugging.
473          */
474         struct lu_ref_link                 lo_dev_ref;
475 };
476
477 enum lu_object_header_flags {
478         /**
479          * Don't keep this object in cache. Object will be destroyed as soon
480          * as last reference to it is released. This flag cannot be cleared
481          * once set.
482          */
483         LU_OBJECT_HEARD_BANSHEE = 0,
484         /**
485          * Mark this object has already been taken out of cache.
486          */
487         LU_OBJECT_UNHASHED = 1,
488 };
489
490 enum lu_object_header_attr {
491         LOHA_EXISTS   = 1 << 0,
492         LOHA_REMOTE   = 1 << 1,
493         /**
494          * UNIX file type is stored in S_IFMT bits.
495          */
496         LOHA_FT_START = 001 << 12, /**< S_IFIFO */
497         LOHA_FT_END   = 017 << 12, /**< S_IFMT */
498 };
499
500 /**
501  * "Compound" object, consisting of multiple layers.
502  *
503  * Compound object with given fid is unique with given lu_site.
504  *
505  * Note, that object does *not* necessary correspond to the real object in the
506  * persistent storage: object is an anchor for locking and method calling, so
507  * it is created for things like not-yet-existing child created by mkdir or
508  * create calls. lu_object_operations::loo_exists() can be used to check
509  * whether object is backed by persistent storage entity.
510  */
511 struct lu_object_header {
512         /**
513          * Fid, uniquely identifying this object.
514          */
515         struct lu_fid           loh_fid;
516         /**
517          * Object flags from enum lu_object_header_flags. Set and checked
518          * atomically.
519          */
520         unsigned long     loh_flags;
521         /**
522          * Object reference count. Protected by lu_site::ls_guard.
523          */
524         atomic_t           loh_ref;
525         /**
526          * Common object attributes, cached for efficiency. From enum
527          * lu_object_header_attr.
528          */
529         __u32             loh_attr;
530         /**
531          * Linkage into per-site hash table. Protected by lu_site::ls_guard.
532          */
533         struct hlist_node       loh_hash;
534         /**
535          * Linkage into per-site LRU list. Protected by lu_site::ls_guard.
536          */
537         struct list_head             loh_lru;
538         /**
539          * Linkage into list of layers. Never modified once set (except lately
540          * during object destruction). No locking is necessary.
541          */
542         struct list_head             loh_layers;
543         /**
544          * A list of references to this object, for debugging.
545          */
546         struct lu_ref     loh_reference;
547 };
548
549 struct fld;
550
551 struct lu_site_bkt_data {
552         /**
553          * number of object in this bucket on the lsb_lru list.
554          */
555         long                    lsb_lru_len;
556         /**
557          * LRU list, updated on each access to object. Protected by
558          * bucket lock of lu_site::ls_obj_hash.
559          *
560          * "Cold" end of LRU is lu_site::ls_lru.next. Accessed object are
561          * moved to the lu_site::ls_lru.prev (this is due to the non-existence
562          * of list_for_each_entry_safe_reverse()).
563          */
564         struct list_head                lsb_lru;
565         /**
566          * Wait-queue signaled when an object in this site is ultimately
567          * destroyed (lu_object_free()). It is used by lu_object_find() to
568          * wait before re-trying when object in the process of destruction is
569          * found in the hash table.
570          *
571          * \see htable_lookup().
572          */
573         wait_queue_head_t              lsb_marche_funebre;
574 };
575
576 enum {
577         LU_SS_CREATED    = 0,
578         LU_SS_CACHE_HIT,
579         LU_SS_CACHE_MISS,
580         LU_SS_CACHE_RACE,
581         LU_SS_CACHE_DEATH_RACE,
582         LU_SS_LRU_PURGED,
583         LU_SS_LRU_LEN,  /* # of objects in lsb_lru lists */
584         LU_SS_LAST_STAT
585 };
586
587 /**
588  * lu_site is a "compartment" within which objects are unique, and LRU
589  * discipline is maintained.
590  *
591  * lu_site exists so that multiple layered stacks can co-exist in the same
592  * address space.
593  *
594  * lu_site has the same relation to lu_device as lu_object_header to
595  * lu_object.
596  */
597 struct lu_site {
598         /**
599          * objects hash table
600          */
601         struct cfs_hash        *ls_obj_hash;
602         /**
603          * index of bucket on hash table while purging
604          */
605         unsigned int            ls_purge_start;
606         /**
607          * Top-level device for this stack.
608          */
609         struct lu_device         *ls_top_dev;
610         /**
611          * Bottom-level device for this stack
612          */
613         struct lu_device        *ls_bottom_dev;
614         /**
615          * Linkage into global list of sites.
616          */
617         struct list_head                ls_linkage;
618         /**
619          * List for lu device for this site, protected
620          * by ls_ld_lock.
621          **/
622         struct list_head                ls_ld_linkage;
623         spinlock_t              ls_ld_lock;
624
625         /**
626          * Lock to serialize site purge.
627          */
628         struct mutex            ls_purge_mutex;
629
630         /**
631          * lu_site stats
632          */
633         struct lprocfs_stats    *ls_stats;
634         /**
635          * XXX: a hack! fld has to find md_site via site, remove when possible
636          */
637         struct seq_server_site  *ld_seq_site;
638 };
639
640 static inline struct lu_site_bkt_data *
641 lu_site_bkt_from_fid(struct lu_site *site, struct lu_fid *fid)
642 {
643         struct cfs_hash_bd bd;
644
645         cfs_hash_bd_get(site->ls_obj_hash, fid, &bd);
646         return cfs_hash_bd_extra_get(site->ls_obj_hash, &bd);
647 }
648
649 static inline struct seq_server_site *lu_site2seq(const struct lu_site *s)
650 {
651         return s->ld_seq_site;
652 }
653
654 /** \name ctors
655  * Constructors/destructors.
656  * @{
657  */
658
659 int lu_site_init(struct lu_site *s, struct lu_device *d);
660 void lu_site_fini(struct lu_site *s);
661 int lu_site_init_finish(struct lu_site *s);
662 void lu_stack_fini(const struct lu_env *env, struct lu_device *top);
663 void lu_device_get(struct lu_device *d);
664 void lu_device_put(struct lu_device *d);
665 int lu_device_init(struct lu_device *d, struct lu_device_type *t);
666 void lu_device_fini(struct lu_device *d);
667 int lu_object_header_init(struct lu_object_header *h);
668 void lu_object_header_fini(struct lu_object_header *h);
669 int lu_object_init(struct lu_object *o,
670                    struct lu_object_header *h, struct lu_device *d);
671 void lu_object_fini(struct lu_object *o);
672 void lu_object_add_top(struct lu_object_header *h, struct lu_object *o);
673 void lu_object_add(struct lu_object *before, struct lu_object *o);
674
675 /**
676  * Helpers to initialize and finalize device types.
677  */
678
679 int  lu_device_type_init(struct lu_device_type *ldt);
680 void lu_device_type_fini(struct lu_device_type *ldt);
681
682 /** @} ctors */
683
684 /** \name caching
685  * Caching and reference counting.
686  * @{
687  */
688
689 /**
690  * Acquire additional reference to the given object. This function is used to
691  * attain additional reference. To acquire initial reference use
692  * lu_object_find().
693  */
694 static inline void lu_object_get(struct lu_object *o)
695 {
696         LASSERT(atomic_read(&o->lo_header->loh_ref) > 0);
697         atomic_inc(&o->lo_header->loh_ref);
698 }
699
700 /**
701  * Return true of object will not be cached after last reference to it is
702  * released.
703  */
704 static inline int lu_object_is_dying(const struct lu_object_header *h)
705 {
706         return test_bit(LU_OBJECT_HEARD_BANSHEE, &h->loh_flags);
707 }
708
709 void lu_object_put(const struct lu_env *env, struct lu_object *o);
710 void lu_object_unhash(const struct lu_env *env, struct lu_object *o);
711
712 int lu_site_purge(const struct lu_env *env, struct lu_site *s, int nr);
713
714 void lu_site_print(const struct lu_env *env, struct lu_site *s, void *cookie,
715                    lu_printer_t printer);
716 struct lu_object *lu_object_find_at(const struct lu_env *env,
717                                     struct lu_device *dev,
718                                     const struct lu_fid *f,
719                                     const struct lu_object_conf *conf);
720 struct lu_object *lu_object_find_slice(const struct lu_env *env,
721                                        struct lu_device *dev,
722                                        const struct lu_fid *f,
723                                        const struct lu_object_conf *conf);
724 /** @} caching */
725
726 /** \name helpers
727  * Helpers.
728  * @{
729  */
730
731 /**
732  * First (topmost) sub-object of given compound object
733  */
734 static inline struct lu_object *lu_object_top(struct lu_object_header *h)
735 {
736         LASSERT(!list_empty(&h->loh_layers));
737         return container_of0(h->loh_layers.next, struct lu_object, lo_linkage);
738 }
739
740 /**
741  * Next sub-object in the layering
742  */
743 static inline struct lu_object *lu_object_next(const struct lu_object *o)
744 {
745         return container_of0(o->lo_linkage.next, struct lu_object, lo_linkage);
746 }
747
748 /**
749  * Pointer to the fid of this object.
750  */
751 static inline const struct lu_fid *lu_object_fid(const struct lu_object *o)
752 {
753         return &o->lo_header->loh_fid;
754 }
755
756 /**
757  * return device operations vector for this object
758  */
759 static inline const struct lu_device_operations *
760 lu_object_ops(const struct lu_object *o)
761 {
762         return o->lo_dev->ld_ops;
763 }
764
765 /**
766  * Given a compound object, find its slice, corresponding to the device type
767  * \a dtype.
768  */
769 struct lu_object *lu_object_locate(struct lu_object_header *h,
770                                    const struct lu_device_type *dtype);
771
772 /**
773  * Printer function emitting messages through libcfs_debug_msg().
774  */
775 int lu_cdebug_printer(const struct lu_env *env,
776                       void *cookie, const char *format, ...);
777
778 /**
779  * Print object description followed by a user-supplied message.
780  */
781 #define LU_OBJECT_DEBUG(mask, env, object, format, ...)            \
782 do {                                                                  \
783         if (cfs_cdebug_show(mask, DEBUG_SUBSYSTEM)) {                \
784                 LIBCFS_DEBUG_MSG_DATA_DECL(msgdata, mask, NULL);                \
785                 lu_object_print(env, &msgdata, lu_cdebug_printer, object);\
786                 CDEBUG(mask, format "\n", ## __VA_ARGS__);                  \
787         }                                                                \
788 } while (0)
789
790 /**
791  * Print short object description followed by a user-supplied message.
792  */
793 #define LU_OBJECT_HEADER(mask, env, object, format, ...)                \
794 do {                                                                \
795         if (cfs_cdebug_show(mask, DEBUG_SUBSYSTEM)) {              \
796                 LIBCFS_DEBUG_MSG_DATA_DECL(msgdata, mask, NULL);                \
797                 lu_object_header_print(env, &msgdata, lu_cdebug_printer,\
798                                        (object)->lo_header);        \
799                 lu_cdebug_printer(env, &msgdata, "\n");          \
800                 CDEBUG(mask, format, ## __VA_ARGS__);             \
801         }                                                              \
802 } while (0)
803
804 void lu_object_print       (const struct lu_env *env, void *cookie,
805                             lu_printer_t printer, const struct lu_object *o);
806 void lu_object_header_print(const struct lu_env *env, void *cookie,
807                             lu_printer_t printer,
808                             const struct lu_object_header *hdr);
809
810 /**
811  * Check object consistency.
812  */
813 int lu_object_invariant(const struct lu_object *o);
814
815 /**
816  * Check whether object exists, no matter on local or remote storage.
817  * Note: LOHA_EXISTS will be set once some one created the object,
818  * and it does not needs to be committed to storage.
819  */
820 #define lu_object_exists(o) ((o)->lo_header->loh_attr & LOHA_EXISTS)
821
822 /**
823  * Check whether object on the remote storage.
824  */
825 #define lu_object_remote(o) unlikely((o)->lo_header->loh_attr & LOHA_REMOTE)
826
827 static inline int lu_object_assert_exists(const struct lu_object *o)
828 {
829         return lu_object_exists(o);
830 }
831
832 static inline int lu_object_assert_not_exists(const struct lu_object *o)
833 {
834         return !lu_object_exists(o);
835 }
836
837 /**
838  * Attr of this object.
839  */
840 static inline __u32 lu_object_attr(const struct lu_object *o)
841 {
842         LASSERT(lu_object_exists(o) != 0);
843         return o->lo_header->loh_attr;
844 }
845
846 static inline void lu_object_ref_add(struct lu_object *o,
847                                      const char *scope,
848                                      const void *source)
849 {
850         lu_ref_add(&o->lo_header->loh_reference, scope, source);
851 }
852
853 static inline void lu_object_ref_add_at(struct lu_object *o,
854                                         struct lu_ref_link *link,
855                                         const char *scope,
856                                         const void *source)
857 {
858         lu_ref_add_at(&o->lo_header->loh_reference, link, scope, source);
859 }
860
861 static inline void lu_object_ref_del(struct lu_object *o,
862                                      const char *scope, const void *source)
863 {
864         lu_ref_del(&o->lo_header->loh_reference, scope, source);
865 }
866
867 static inline void lu_object_ref_del_at(struct lu_object *o,
868                                         struct lu_ref_link *link,
869                                         const char *scope, const void *source)
870 {
871         lu_ref_del_at(&o->lo_header->loh_reference, link, scope, source);
872 }
873
874 /** input params, should be filled out by mdt */
875 struct lu_rdpg {
876         /** hash */
877         __u64              rp_hash;
878         /** count in bytes */
879         unsigned int        rp_count;
880         /** number of pages */
881         unsigned int        rp_npages;
882         /** requested attr */
883         __u32              rp_attrs;
884         /** pointers to pages */
885         struct page        **rp_pages;
886 };
887
888 enum lu_xattr_flags {
889         LU_XATTR_REPLACE = (1 << 0),
890         LU_XATTR_CREATE  = (1 << 1)
891 };
892
893 /** @} helpers */
894
895 /** \name lu_context
896  * @{
897  */
898
899 /** For lu_context health-checks */
900 enum lu_context_state {
901         LCS_INITIALIZED = 1,
902         LCS_ENTERED,
903         LCS_LEFT,
904         LCS_FINALIZED
905 };
906
907 /**
908  * lu_context. Execution context for lu_object methods. Currently associated
909  * with thread.
910  *
911  * All lu_object methods, except device and device type methods (called during
912  * system initialization and shutdown) are executed "within" some
913  * lu_context. This means, that pointer to some "current" lu_context is passed
914  * as an argument to all methods.
915  *
916  * All service ptlrpc threads create lu_context as part of their
917  * initialization. It is possible to create "stand-alone" context for other
918  * execution environments (like system calls).
919  *
920  * lu_object methods mainly use lu_context through lu_context_key interface
921  * that allows each layer to associate arbitrary pieces of data with each
922  * context (see pthread_key_create(3) for similar interface).
923  *
924  * On a client, lu_context is bound to a thread, see cl_env_get().
925  *
926  * \see lu_context_key
927  */
928 struct lu_context {
929         /**
930          * lu_context is used on the client side too. Yet we don't want to
931          * allocate values of server-side keys for the client contexts and
932          * vice versa.
933          *
934          * To achieve this, set of tags in introduced. Contexts and keys are
935          * marked with tags. Key value are created only for context whose set
936          * of tags has non-empty intersection with one for key. Tags are taken
937          * from enum lu_context_tag.
938          */
939         __u32             lc_tags;
940         enum lu_context_state  lc_state;
941         /**
942          * Pointer to the home service thread. NULL for other execution
943          * contexts.
944          */
945         struct ptlrpc_thread  *lc_thread;
946         /**
947          * Pointer to an array with key values. Internal implementation
948          * detail.
949          */
950         void             **lc_value;
951         /**
952          * Linkage into a list of all remembered contexts. Only
953          * `non-transient' contexts, i.e., ones created for service threads
954          * are placed here.
955          */
956         struct list_head             lc_remember;
957         /**
958          * Version counter used to skip calls to lu_context_refill() when no
959          * keys were registered.
960          */
961         unsigned               lc_version;
962         /**
963          * Debugging cookie.
964          */
965         unsigned               lc_cookie;
966 };
967
968 /**
969  * lu_context_key interface. Similar to pthread_key.
970  */
971
972 enum lu_context_tag {
973         /**
974          * Thread on md server
975          */
976         LCT_MD_THREAD = 1 << 0,
977         /**
978          * Thread on dt server
979          */
980         LCT_DT_THREAD = 1 << 1,
981         /**
982          * Context for transaction handle
983          */
984         LCT_TX_HANDLE = 1 << 2,
985         /**
986          * Thread on client
987          */
988         LCT_CL_THREAD = 1 << 3,
989         /**
990          * A per-request session on a server, and a per-system-call session on
991          * a client.
992          */
993         LCT_SESSION   = 1 << 4,
994         /**
995          * A per-request data on OSP device
996          */
997         LCT_OSP_THREAD = 1 << 5,
998         /**
999          * MGS device thread
1000          */
1001         LCT_MG_THREAD = 1 << 6,
1002         /**
1003          * Context for local operations
1004          */
1005         LCT_LOCAL = 1 << 7,
1006         /**
1007          * session for server thread
1008          **/
1009         LCT_SERVER_SESSION = BIT(8),
1010         /**
1011          * Set when at least one of keys, having values in this context has
1012          * non-NULL lu_context_key::lct_exit() method. This is used to
1013          * optimize lu_context_exit() call.
1014          */
1015         LCT_HAS_EXIT  = 1 << 28,
1016         /**
1017          * Don't add references for modules creating key values in that context.
1018          * This is only for contexts used internally by lu_object framework.
1019          */
1020         LCT_NOREF     = 1 << 29,
1021         /**
1022          * Key is being prepared for retiring, don't create new values for it.
1023          */
1024         LCT_QUIESCENT = 1 << 30,
1025         /**
1026          * Context should be remembered.
1027          */
1028         LCT_REMEMBER  = 1 << 31,
1029         /**
1030          * Contexts usable in cache shrinker thread.
1031          */
1032         LCT_SHRINKER  = LCT_MD_THREAD | LCT_DT_THREAD | LCT_CL_THREAD |
1033                         LCT_NOREF
1034 };
1035
1036 /**
1037  * Key. Represents per-context value slot.
1038  *
1039  * Keys are usually registered when module owning the key is initialized, and
1040  * de-registered when module is unloaded. Once key is registered, all new
1041  * contexts with matching tags, will get key value. "Old" contexts, already
1042  * initialized at the time of key registration, can be forced to get key value
1043  * by calling lu_context_refill().
1044  *
1045  * Every key value is counted in lu_context_key::lct_used and acquires a
1046  * reference on an owning module. This means, that all key values have to be
1047  * destroyed before module can be unloaded. This is usually achieved by
1048  * stopping threads started by the module, that created contexts in their
1049  * entry functions. Situation is complicated by the threads shared by multiple
1050  * modules, like ptlrpcd daemon on a client. To work around this problem,
1051  * contexts, created in such threads, are `remembered' (see
1052  * LCT_REMEMBER)---i.e., added into a global list. When module is preparing
1053  * for unloading it does the following:
1054  *
1055  *     - marks its keys as `quiescent' (lu_context_tag::LCT_QUIESCENT)
1056  *       preventing new key values from being allocated in the new contexts,
1057  *       and
1058  *
1059  *     - scans a list of remembered contexts, destroying values of module
1060  *       keys, thus releasing references to the module.
1061  *
1062  * This is done by lu_context_key_quiesce(). If module is re-activated
1063  * before key has been de-registered, lu_context_key_revive() call clears
1064  * `quiescent' marker.
1065  *
1066  * lu_context code doesn't provide any internal synchronization for these
1067  * activities---it's assumed that startup (including threads start-up) and
1068  * shutdown are serialized by some external means.
1069  *
1070  * \see lu_context
1071  */
1072 struct lu_context_key {
1073         /**
1074          * Set of tags for which values of this key are to be instantiated.
1075          */
1076         __u32 lct_tags;
1077         /**
1078          * Value constructor. This is called when new value is created for a
1079          * context. Returns pointer to new value of error pointer.
1080          */
1081         void  *(*lct_init)(const struct lu_context *ctx,
1082                            struct lu_context_key *key);
1083         /**
1084          * Value destructor. Called when context with previously allocated
1085          * value of this slot is destroyed. \a data is a value that was returned
1086          * by a matching call to lu_context_key::lct_init().
1087          */
1088         void   (*lct_fini)(const struct lu_context *ctx,
1089                            struct lu_context_key *key, void *data);
1090         /**
1091          * Optional method called on lu_context_exit() for all allocated
1092          * keys. Can be used by debugging code checking that locks are
1093          * released, etc.
1094          */
1095         void   (*lct_exit)(const struct lu_context *ctx,
1096                            struct lu_context_key *key, void *data);
1097         /**
1098          * Internal implementation detail: index within lu_context::lc_value[]
1099          * reserved for this key.
1100          */
1101         int      lct_index;
1102         /**
1103          * Internal implementation detail: number of values created for this
1104          * key.
1105          */
1106         atomic_t lct_used;
1107         /**
1108          * Internal implementation detail: module for this key.
1109          */
1110         struct module *lct_owner;
1111         /**
1112          * References to this key. For debugging.
1113          */
1114         struct lu_ref  lct_reference;
1115 };
1116
1117 #define LU_KEY_INIT(mod, type)                              \
1118         static void *mod##_key_init(const struct lu_context *ctx, \
1119                                     struct lu_context_key *key)   \
1120         {                                                        \
1121                 type *value;                                  \
1122                                                                   \
1123                 CLASSERT(PAGE_SIZE >= sizeof(*value));        \
1124                                                                   \
1125                 value = kzalloc(sizeof(*value), GFP_NOFS);      \
1126                 if (!value)                             \
1127                         value = ERR_PTR(-ENOMEM);                \
1128                                                                   \
1129                 return value;                                \
1130         }                                                        \
1131         struct __##mod##__dummy_init {; } /* semicolon catcher */
1132
1133 #define LU_KEY_FINI(mod, type)                                        \
1134         static void mod##_key_fini(const struct lu_context *ctx,            \
1135                                     struct lu_context_key *key, void *data) \
1136         {                                                                  \
1137                 type *info = data;                                        \
1138                                                                             \
1139                 kfree(info);                                     \
1140         }                                                                  \
1141         struct __##mod##__dummy_fini {; } /* semicolon catcher */
1142
1143 #define LU_KEY_INIT_FINI(mod, type)   \
1144         LU_KEY_INIT(mod, type); \
1145         LU_KEY_FINI(mod, type)
1146
1147 #define LU_CONTEXT_KEY_DEFINE(mod, tags)                \
1148         struct lu_context_key mod##_thread_key = {      \
1149                 .lct_tags = tags,                      \
1150                 .lct_init = mod##_key_init,          \
1151                 .lct_fini = mod##_key_fini            \
1152         }
1153
1154 #define LU_CONTEXT_KEY_INIT(key)                        \
1155 do {                                                \
1156         (key)->lct_owner = THIS_MODULE;          \
1157 } while (0)
1158
1159 int lu_context_key_register(struct lu_context_key *key);
1160 void lu_context_key_degister(struct lu_context_key *key);
1161 void *lu_context_key_get(const struct lu_context *ctx,
1162                          const struct lu_context_key *key);
1163 void lu_context_key_quiesce(struct lu_context_key *key);
1164 void lu_context_key_revive(struct lu_context_key *key);
1165
1166 /*
1167  * LU_KEY_INIT_GENERIC() has to be a macro to correctly determine an
1168  * owning module.
1169  */
1170
1171 #define LU_KEY_INIT_GENERIC(mod)                                        \
1172         static void mod##_key_init_generic(struct lu_context_key *k, ...) \
1173         {                                                              \
1174                 struct lu_context_key *key = k;                  \
1175                 va_list args;                                      \
1176                                                                         \
1177                 va_start(args, k);                                    \
1178                 do {                                                \
1179                         LU_CONTEXT_KEY_INIT(key);                      \
1180                         key = va_arg(args, struct lu_context_key *);    \
1181                 } while (key);                            \
1182                 va_end(args);                                      \
1183         }
1184
1185 #define LU_TYPE_INIT(mod, ...)                                    \
1186         LU_KEY_INIT_GENERIC(mod)                                        \
1187         static int mod##_type_init(struct lu_device_type *t)        \
1188         {                                                              \
1189                 mod##_key_init_generic(__VA_ARGS__, NULL);            \
1190                 return lu_context_key_register_many(__VA_ARGS__, NULL); \
1191         }                                                              \
1192         struct __##mod##_dummy_type_init {; }
1193
1194 #define LU_TYPE_FINI(mod, ...)                                    \
1195         static void mod##_type_fini(struct lu_device_type *t)      \
1196         {                                                              \
1197                 lu_context_key_degister_many(__VA_ARGS__, NULL);        \
1198         }                                                              \
1199         struct __##mod##_dummy_type_fini {; }
1200
1201 #define LU_TYPE_START(mod, ...)                          \
1202         static void mod##_type_start(struct lu_device_type *t)  \
1203         {                                                      \
1204                 lu_context_key_revive_many(__VA_ARGS__, NULL);  \
1205         }                                                      \
1206         struct __##mod##_dummy_type_start {; }
1207
1208 #define LU_TYPE_STOP(mod, ...)                            \
1209         static void mod##_type_stop(struct lu_device_type *t)   \
1210         {                                                      \
1211                 lu_context_key_quiesce_many(__VA_ARGS__, NULL); \
1212         }                                                      \
1213         struct __##mod##_dummy_type_stop {; }
1214
1215 #define LU_TYPE_INIT_FINI(mod, ...)          \
1216         LU_TYPE_INIT(mod, __VA_ARGS__);  \
1217         LU_TYPE_FINI(mod, __VA_ARGS__);  \
1218         LU_TYPE_START(mod, __VA_ARGS__);        \
1219         LU_TYPE_STOP(mod, __VA_ARGS__)
1220
1221 int lu_context_init(struct lu_context *ctx, __u32 tags);
1222 void lu_context_fini(struct lu_context *ctx);
1223 void lu_context_enter(struct lu_context *ctx);
1224 void lu_context_exit(struct lu_context *ctx);
1225 int lu_context_refill(struct lu_context *ctx);
1226
1227 /*
1228  * Helper functions to operate on multiple keys. These are used by the default
1229  * device type operations, defined by LU_TYPE_INIT_FINI().
1230  */
1231
1232 int lu_context_key_register_many(struct lu_context_key *k, ...);
1233 void lu_context_key_degister_many(struct lu_context_key *k, ...);
1234 void lu_context_key_revive_many(struct lu_context_key *k, ...);
1235 void lu_context_key_quiesce_many(struct lu_context_key *k, ...);
1236
1237 /**
1238  * Environment.
1239  */
1240 struct lu_env {
1241         /**
1242          * "Local" context, used to store data instead of stack.
1243          */
1244         struct lu_context  le_ctx;
1245         /**
1246          * "Session" context for per-request data.
1247          */
1248         struct lu_context *le_ses;
1249 };
1250
1251 int lu_env_init(struct lu_env *env, __u32 tags);
1252 void lu_env_fini(struct lu_env *env);
1253 int lu_env_refill(struct lu_env *env);
1254
1255 /** @} lu_context */
1256
1257 /**
1258  * Output site statistical counters into a buffer. Suitable for
1259  * ll_rd_*()-style functions.
1260  */
1261 int lu_site_stats_print(const struct lu_site *s, struct seq_file *m);
1262
1263 /**
1264  * Common name structure to be passed around for various name related methods.
1265  */
1266 struct lu_name {
1267         const char    *ln_name;
1268         int         ln_namelen;
1269 };
1270
1271 /**
1272  * Validate names (path components)
1273  *
1274  * To be valid \a name must be non-empty, '\0' terminated of length \a
1275  * name_len, and not contain '/'. The maximum length of a name (before
1276  * say -ENAMETOOLONG will be returned) is really controlled by llite
1277  * and the server. We only check for something insane coming from bad
1278  * integer handling here.
1279  */
1280 static inline bool lu_name_is_valid_2(const char *name, size_t name_len)
1281 {
1282         return name && name_len > 0 && name_len < INT_MAX &&
1283                name[name_len] == '\0' && strlen(name) == name_len &&
1284                !memchr(name, '/', name_len);
1285 }
1286
1287 /**
1288  * Common buffer structure to be passed around for various xattr_{s,g}et()
1289  * methods.
1290  */
1291 struct lu_buf {
1292         void   *lb_buf;
1293         size_t  lb_len;
1294 };
1295
1296 #define DLUBUF "(%p %zu)"
1297 #define PLUBUF(buf) (buf)->lb_buf, (buf)->lb_len
1298 /**
1299  * One-time initializers, called at obdclass module initialization, not
1300  * exported.
1301  */
1302
1303 /**
1304  * Initialization of global lu_* data.
1305  */
1306 int lu_global_init(void);
1307
1308 /**
1309  * Dual to lu_global_init().
1310  */
1311 void lu_global_fini(void);
1312
1313 struct lu_kmem_descr {
1314         struct kmem_cache **ckd_cache;
1315         const char       *ckd_name;
1316         const size_t      ckd_size;
1317 };
1318
1319 int  lu_kmem_init(struct lu_kmem_descr *caches);
1320 void lu_kmem_fini(struct lu_kmem_descr *caches);
1321
1322 void lu_buf_free(struct lu_buf *buf);
1323 void lu_buf_alloc(struct lu_buf *buf, size_t size);
1324 void lu_buf_realloc(struct lu_buf *buf, size_t size);
1325
1326 int lu_buf_check_and_grow(struct lu_buf *buf, size_t len);
1327 struct lu_buf *lu_buf_check_and_alloc(struct lu_buf *buf, size_t len);
1328
1329 /** @} lu */
1330 #endif /* __LUSTRE_LU_OBJECT_H */