Whamcloud - gitweb
LU-11971 utils: Send file creation time to clients
[fs/lustre-release.git] / 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, 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
33 #ifndef __LUSTRE_LU_OBJECT_H
34 #define __LUSTRE_LU_OBJECT_H
35
36 #include <stdarg.h>
37 #include <libcfs/libcfs.h>
38 #include <uapi/linux/lustre/lustre_idl.h>
39 #include <lu_ref.h>
40 #include <linux/percpu_counter.h>
41 #include <linux/ctype.h>
42 #include <obd_target.h>
43
44 struct seq_file;
45 struct proc_dir_entry;
46 struct lustre_cfg;
47 struct lprocfs_stats;
48 struct obd_type;
49
50 /** \defgroup lu lu
51  * lu_* data-types represent server-side entities shared by data and meta-data
52  * stacks.
53  *
54  * Design goals:
55  *
56  * -# support for layering.
57  *
58  *     Server side object is split into layers, one per device in the
59  *     corresponding device stack. Individual layer is represented by struct
60  *     lu_object. Compound layered object --- by struct lu_object_header. Most
61  *     interface functions take lu_object as an argument and operate on the
62  *     whole compound object. This decision was made due to the following
63  *     reasons:
64  *
65  *        - it's envisaged that lu_object will be used much more often than
66  *        lu_object_header;
67  *
68  *        - we want lower (non-top) layers to be able to initiate operations
69  *        on the whole object.
70  *
71  *     Generic code supports layering more complex than simple stacking, e.g.,
72  *     it is possible that at some layer object "spawns" multiple sub-objects
73  *     on the lower layer.
74  *
75  * -# fid-based identification.
76  *
77  *     Compound object is uniquely identified by its fid. Objects are indexed
78  *     by their fids (hash table is used for index).
79  *
80  * -# caching and life-cycle management.
81  *
82  *     Object's life-time is controlled by reference counting. When reference
83  *     count drops to 0, object is returned to cache. Cached objects still
84  *     retain their identity (i.e., fid), and can be recovered from cache.
85  *
86  *     Objects are kept in the global LRU list, and lu_site_purge() function
87  *     can be used to reclaim given number of unused objects from the tail of
88  *     the LRU.
89  *
90  * -# avoiding recursion.
91  *
92  *     Generic code tries to replace recursion through layers by iterations
93  *     where possible. Additionally to the end of reducing stack consumption,
94  *     data, when practically possible, are allocated through lu_context_key
95  *     interface rather than on stack.
96  * @{
97  */
98
99 struct lu_site;
100 struct lu_object;
101 struct lu_device;
102 struct lu_object_header;
103 struct lu_context;
104 struct lu_env;
105
106 /**
107  * Operations common for data and meta-data devices.
108  */
109 struct lu_device_operations {
110         /**
111          * Allocate object for the given device (without lower-layer
112          * parts). This is called by lu_object_operations::loo_object_init()
113          * from the parent layer, and should setup at least lu_object::lo_dev
114          * and lu_object::lo_ops fields of resulting lu_object.
115          *
116          * Object creation protocol.
117          *
118          * Due to design goal of avoiding recursion, object creation (see
119          * lu_object_alloc()) is somewhat involved:
120          *
121          *  - first, lu_device_operations::ldo_object_alloc() method of the
122          *  top-level device in the stack is called. It should allocate top
123          *  level object (including lu_object_header), but without any
124          *  lower-layer sub-object(s).
125          *
126          *  - then lu_object_alloc() sets fid in the header of newly created
127          *  object.
128          *
129          *  - then lu_object_operations::loo_object_init() is called. It has
130          *  to allocate lower-layer object(s). To do this,
131          *  lu_object_operations::loo_object_init() calls ldo_object_alloc()
132          *  of the lower-layer device(s).
133          *
134          *  - for all new objects allocated by
135          *  lu_object_operations::loo_object_init() (and inserted into object
136          *  stack), lu_object_operations::loo_object_init() is called again
137          *  repeatedly, until no new objects are created.
138          *
139          * \post ergo(!IS_ERR(result), result->lo_dev == d &&
140          *                             result->lo_ops != NULL);
141          */
142         struct lu_object *(*ldo_object_alloc)(const struct lu_env *env,
143                                               const struct lu_object_header *h,
144                                               struct lu_device *d);
145         /**
146          * process config specific for device.
147          */
148         int (*ldo_process_config)(const struct lu_env *env,
149                                   struct lu_device *, struct lustre_cfg *);
150         int (*ldo_recovery_complete)(const struct lu_env *,
151                                      struct lu_device *);
152
153         /**
154          * initialize local objects for device. this method called after layer has
155          * been initialized (after LCFG_SETUP stage) and before it starts serving
156          * user requests.
157          */
158
159         int (*ldo_prepare)(const struct lu_env *,
160                            struct lu_device *parent,
161                            struct lu_device *dev);
162
163 };
164
165 /**
166  * For lu_object_conf flags
167  */
168 typedef enum {
169         /* This is a new object to be allocated, or the file
170          * corresponding to the object does not exists. */
171         LOC_F_NEW       = 0x00000001,
172 } loc_flags_t;
173
174 /**
175  * Object configuration, describing particulars of object being created. On
176  * server this is not used, as server objects are full identified by fid. On
177  * client configuration contains struct lustre_md.
178  */
179 struct lu_object_conf {
180         /**
181          * Some hints for obj find and alloc.
182          */
183         loc_flags_t     loc_flags;
184 };
185
186 /**
187  * Type of "printer" function used by lu_object_operations::loo_object_print()
188  * method.
189  *
190  * Printer function is needed to provide some flexibility in (semi-)debugging
191  * output: possible implementations: printk, CDEBUG, sysfs/seq_file
192  */
193 typedef int (*lu_printer_t)(const struct lu_env *env,
194                             void *cookie, const char *format, ...)
195         __attribute__ ((format (printf, 3, 4)));
196
197 /**
198  * Operations specific for particular lu_object.
199  */
200 struct lu_object_operations {
201
202         /**
203          * Allocate lower-layer parts of the object by calling
204          * lu_device_operations::ldo_object_alloc() of the corresponding
205          * underlying device.
206          *
207          * This method is called once for each object inserted into object
208          * stack. It's responsibility of this method to insert lower-layer
209          * object(s) it create into appropriate places of object stack.
210          */
211         int (*loo_object_init)(const struct lu_env *env,
212                                struct lu_object *o,
213                                const struct lu_object_conf *conf);
214         /**
215          * Called (in top-to-bottom order) during object allocation after all
216          * layers were allocated and initialized. Can be used to perform
217          * initialization depending on lower layers.
218          */
219         int (*loo_object_start)(const struct lu_env *env,
220                                 struct lu_object *o);
221         /**
222          * Called before lu_object_operations::loo_object_free() to signal
223          * that object is being destroyed. Dual to
224          * lu_object_operations::loo_object_init().
225          */
226         void (*loo_object_delete)(const struct lu_env *env,
227                                   struct lu_object *o);
228         /**
229          * Dual to lu_device_operations::ldo_object_alloc(). Called when
230          * object is removed from memory.  Must use call_rcu or kfree_rcu
231          * if the object contains an lu_object_header.
232          */
233         void (*loo_object_free)(const struct lu_env *env,
234                                 struct lu_object *o);
235         /**
236          * Called when last active reference to the object is released (and
237          * object returns to the cache). This method is optional.
238          */
239         void (*loo_object_release)(const struct lu_env *env,
240                                    struct lu_object *o);
241         /**
242          * Optional debugging helper. Print given object.
243          */
244         int (*loo_object_print)(const struct lu_env *env, void *cookie,
245                                 lu_printer_t p, const struct lu_object *o);
246         /**
247          * Optional debugging method. Returns true iff method is internally
248          * consistent.
249          */
250         int (*loo_object_invariant)(const struct lu_object *o);
251 };
252
253 /**
254  * Type of lu_device.
255  */
256 struct lu_device_type;
257
258 /**
259  * Device: a layer in the server side abstraction stacking.
260  */
261 struct lu_device {
262         /**
263          * reference count. This is incremented, in particular, on each object
264          * created at this layer.
265          *
266          * \todo XXX which means that atomic_t is probably too small.
267          */
268         atomic_t                           ld_ref;
269         /**
270          * Pointer to device type. Never modified once set.
271          */
272         struct lu_device_type             *ld_type;
273         /**
274          * Operation vector for this device.
275          */
276         const struct lu_device_operations *ld_ops;
277         /**
278          * Stack this device belongs to.
279          */
280         struct lu_site                    *ld_site;
281         struct proc_dir_entry             *ld_proc_entry;
282
283         /** \todo XXX: temporary back pointer into obd. */
284         struct obd_device                 *ld_obd;
285         /**
286          * A list of references to this object, for debugging.
287          */
288         struct lu_ref                      ld_reference;
289         /**
290          * Link the device to the site.
291          **/
292         struct list_head                   ld_linkage;
293 };
294
295 struct lu_device_type_operations;
296
297 /**
298  * Tag bits for device type. They are used to distinguish certain groups of
299  * device types.
300  */
301 enum lu_device_tag {
302         /** this is meta-data device */
303         LU_DEVICE_MD = (1 << 0),
304         /** this is data device */
305         LU_DEVICE_DT = (1 << 1),
306         /** data device in the client stack */
307         LU_DEVICE_CL = (1 << 2)
308 };
309
310 /**
311  * Type of device.
312  */
313 struct lu_device_type {
314         /**
315          * Tag bits. Taken from enum lu_device_tag. Never modified once set.
316          */
317         __u32                                   ldt_tags;
318         /**
319          * Name of this class. Unique system-wide. Never modified once set.
320          */
321         char                                   *ldt_name;
322         /**
323          * Operations for this type.
324          */
325         const struct lu_device_type_operations *ldt_ops;
326         /**
327          * \todo XXX: temporary: context tags used by obd_*() calls.
328          */
329         __u32                                   ldt_ctx_tags;
330         /**
331          * Number of existing device type instances.
332          */
333         atomic_t                                ldt_device_nr;
334 };
335
336 /**
337  * Operations on a device type.
338  */
339 struct lu_device_type_operations {
340         /**
341          * Allocate new device.
342          */
343         struct lu_device *(*ldto_device_alloc)(const struct lu_env *env,
344                                                struct lu_device_type *t,
345                                                struct lustre_cfg *lcfg);
346         /**
347          * Free device. Dual to
348          * lu_device_type_operations::ldto_device_alloc(). Returns pointer to
349          * the next device in the stack.
350          */
351         struct lu_device *(*ldto_device_free)(const struct lu_env *,
352                                               struct lu_device *);
353
354         /**
355          * Initialize the devices after allocation
356          */
357         int  (*ldto_device_init)(const struct lu_env *env,
358                                  struct lu_device *, const char *,
359                                  struct lu_device *);
360         /**
361          * Finalize device. Dual to
362          * lu_device_type_operations::ldto_device_init(). Returns pointer to
363          * the next device in the stack.
364          */
365         struct lu_device *(*ldto_device_fini)(const struct lu_env *env,
366                                               struct lu_device *);
367         /**
368          * Initialize device type. This is called on module load.
369          */
370         int  (*ldto_init)(struct lu_device_type *t);
371         /**
372          * Finalize device type. Dual to
373          * lu_device_type_operations::ldto_init(). Called on module unload.
374          */
375         void (*ldto_fini)(struct lu_device_type *t);
376         /**
377          * Called when the first device is created.
378          */
379         void (*ldto_start)(struct lu_device_type *t);
380         /**
381          * Called when number of devices drops to 0.
382          */
383         void (*ldto_stop)(struct lu_device_type *t);
384 };
385
386 static inline int lu_device_is_md(const struct lu_device *d)
387 {
388         return ergo(d != NULL, d->ld_type->ldt_tags & LU_DEVICE_MD);
389 }
390
391 /**
392  * Common object attributes.
393  */
394 struct lu_attr {
395         /**
396          * valid bits
397          *
398          * \see enum la_valid
399          */
400         __u64           la_valid;
401         /** size in bytes */
402         __u64           la_size;
403         /** modification time in seconds since Epoch */
404         s64             la_mtime;
405         /** access time in seconds since Epoch */
406         s64             la_atime;
407         /** change time in seconds since Epoch */
408         s64             la_ctime;
409         /** create time in seconds since Epoch */
410         s64             la_btime;
411         /** 512-byte blocks allocated to object */
412         __u64           la_blocks;
413         /** permission bits and file type */
414         __u32           la_mode;
415         /** owner id */
416         __u32           la_uid;
417         /** group id */
418         __u32           la_gid;
419         /** object flags */
420         __u32           la_flags;
421         /** number of persistent references to this object */
422         __u32           la_nlink;
423         /** blk bits of the object*/
424         __u32           la_blkbits;
425         /** blk size of the object*/
426         __u32           la_blksize;
427         /** real device */
428         __u32           la_rdev;
429         /** project id */
430         __u32           la_projid;
431         /** set layout version to OST objects. */
432         __u32           la_layout_version;
433 };
434
435 /**
436  * Layer in the layered object.
437  */
438 struct lu_object {
439         /**
440          * Header for this object.
441          */
442         struct lu_object_header           *lo_header;
443         /**
444          * Device for this layer.
445          */
446         struct lu_device                  *lo_dev;
447         /**
448          * Operations for this object.
449          */
450         const struct lu_object_operations *lo_ops;
451         /**
452          * Linkage into list of all layers.
453          */
454         struct list_head                   lo_linkage;
455         /**
456          * Link to the device, for debugging.
457          */
458         struct lu_ref_link                 lo_dev_ref;
459 };
460
461 enum lu_object_header_flags {
462         /**
463          * Don't keep this object in cache. Object will be destroyed as soon
464          * as last reference to it is released. This flag cannot be cleared
465          * once set.
466          */
467         LU_OBJECT_HEARD_BANSHEE = 0,
468         /**
469          * Mark this object has already been taken out of cache.
470          */
471         LU_OBJECT_UNHASHED      = 1,
472         /**
473          * Object is initialized, when object is found in cache, it may not be
474          * intialized yet, the object allocator will initialize it.
475          */
476         LU_OBJECT_INITED        = 2,
477         /**
478          * Object is being purged, so mustn't be returned by
479          * htable_lookup()
480          */
481         LU_OBJECT_PURGING       = 3,
482 };
483
484 enum lu_object_header_attr {
485         LOHA_EXISTS             = 1 << 0,
486         LOHA_REMOTE             = 1 << 1,
487         LOHA_HAS_AGENT_ENTRY    = 1 << 2,
488         /**
489          * UNIX file type is stored in S_IFMT bits.
490          */
491         LOHA_FT_START           = 001 << 12, /**< S_IFIFO */
492         LOHA_FT_END             = 017 << 12, /**< S_IFMT */
493 };
494
495 /**
496  * "Compound" object, consisting of multiple layers.
497  *
498  * Compound object with given fid is unique with given lu_site.
499  *
500  * Note, that object does *not* necessary correspond to the real object in the
501  * persistent storage: object is an anchor for locking and method calling, so
502  * it is created for things like not-yet-existing child created by mkdir or
503  * create calls. lu_object_operations::loo_exists() can be used to check
504  * whether object is backed by persistent storage entity.
505  */
506 struct lu_object_header {
507         /**
508          * Fid, uniquely identifying this object.
509          */
510         struct lu_fid           loh_fid;
511         /**
512          * Object flags from enum lu_object_header_flags. Set and checked
513          * atomically.
514          */
515         unsigned long           loh_flags;
516         /**
517          * Object reference count. Protected by lu_site::ls_guard.
518          */
519         atomic_t                loh_ref;
520         /**
521          * Common object attributes, cached for efficiency. From enum
522          * lu_object_header_attr.
523          */
524         __u32                   loh_attr;
525         /**
526          * Linkage into per-site hash table. Protected by lu_site::ls_guard.
527          */
528         struct hlist_node       loh_hash;
529         /**
530          * Linkage into per-site LRU list. Protected by lu_site::ls_guard.
531          */
532         struct list_head        loh_lru;
533         /**
534          * Linkage into list of layers. Never modified once set (except lately
535          * during object destruction). No locking is necessary.
536          */
537         struct list_head        loh_layers;
538         /**
539          * A list of references to this object, for debugging.
540          */
541         struct lu_ref           loh_reference;
542         /*
543          * Handle used for kfree_rcu() or similar.
544          */
545         struct rcu_head         loh_rcu;
546 };
547
548 struct fld;
549
550 enum {
551         LU_SS_CREATED           = 0,
552         LU_SS_CACHE_HIT,
553         LU_SS_CACHE_MISS,
554         LU_SS_CACHE_RACE,
555         LU_SS_CACHE_DEATH_RACE,
556         LU_SS_LRU_PURGED,
557         LU_SS_LAST_STAT
558 };
559
560 /**
561  * lu_site is a "compartment" within which objects are unique, and LRU
562  * discipline is maintained.
563  *
564  * lu_site exists so that multiple layered stacks can co-exist in the same
565  * address space.
566  *
567  * lu_site has the same relation to lu_device as lu_object_header to
568  * lu_object.
569  */
570 struct lu_site {
571         /**
572          * objects hash table
573          */
574         struct cfs_hash         *ls_obj_hash;
575         /*
576          * buckets for summary data
577          */
578         struct lu_site_bkt_data *ls_bkts;
579         int                     ls_bkt_cnt;
580         u32                     ls_bkt_seed;
581         /**
582          * index of bucket on hash table while purging
583          */
584         unsigned int            ls_purge_start;
585         /**
586          * Top-level device for this stack.
587          */
588         struct lu_device        *ls_top_dev;
589         /**
590          * Bottom-level device for this stack
591          */
592         struct lu_device        *ls_bottom_dev;
593         /**
594          * Linkage into global list of sites.
595          */
596         struct list_head        ls_linkage;
597         /**
598          * List for lu device for this site, protected
599          * by ls_ld_lock.
600          **/
601         struct list_head        ls_ld_linkage;
602         spinlock_t              ls_ld_lock;
603         /**
604          * Lock to serialize site purge.
605          */
606         struct mutex            ls_purge_mutex;
607         /**
608          * lu_site stats
609          */
610         struct lprocfs_stats    *ls_stats;
611         /**
612          * XXX: a hack! fld has to find md_site via site, remove when possible
613          */
614         struct seq_server_site  *ld_seq_site;
615         /**
616          * Pointer to the lu_target for this site.
617          */
618         struct lu_target        *ls_tgt;
619
620         /**
621          * Number of objects in lsb_lru_lists - used for shrinking
622          */
623         struct percpu_counter   ls_lru_len_counter;
624 };
625
626 wait_queue_head_t *
627 lu_site_wq_from_fid(struct lu_site *site, struct lu_fid *fid);
628
629 static inline struct seq_server_site *lu_site2seq(const struct lu_site *s)
630 {
631         return s->ld_seq_site;
632 }
633
634 /** \name ctors
635  * Constructors/destructors.
636  * @{
637  */
638
639 int  lu_site_init         (struct lu_site *s, struct lu_device *d);
640 void lu_site_fini         (struct lu_site *s);
641 int  lu_site_init_finish  (struct lu_site *s);
642 void lu_stack_fini        (const struct lu_env *env, struct lu_device *top);
643 void lu_device_get        (struct lu_device *d);
644 void lu_device_put        (struct lu_device *d);
645 int  lu_device_init       (struct lu_device *d, struct lu_device_type *t);
646 void lu_device_fini       (struct lu_device *d);
647 int  lu_object_header_init(struct lu_object_header *h);
648 void lu_object_header_fini(struct lu_object_header *h);
649 int  lu_object_init       (struct lu_object *o,
650                            struct lu_object_header *h, struct lu_device *d);
651 void lu_object_fini       (struct lu_object *o);
652 void lu_object_add_top    (struct lu_object_header *h, struct lu_object *o);
653 void lu_object_add        (struct lu_object *before, struct lu_object *o);
654
655 void lu_dev_add_linkage(struct lu_site *s, struct lu_device *d);
656 void lu_dev_del_linkage(struct lu_site *s, struct lu_device *d);
657
658 /**
659  * Helpers to initialize and finalize device types.
660  */
661
662 int  lu_device_type_init(struct lu_device_type *ldt);
663 void lu_device_type_fini(struct lu_device_type *ldt);
664
665 /** @} ctors */
666
667 /** \name caching
668  * Caching and reference counting.
669  * @{
670  */
671
672 /**
673  * Acquire additional reference to the given object. This function is used to
674  * attain additional reference. To acquire initial reference use
675  * lu_object_find().
676  */
677 static inline void lu_object_get(struct lu_object *o)
678 {
679         LASSERT(atomic_read(&o->lo_header->loh_ref) > 0);
680         atomic_inc(&o->lo_header->loh_ref);
681 }
682
683 /**
684  * Return true if object will not be cached after last reference to it is
685  * released.
686  */
687 static inline int lu_object_is_dying(const struct lu_object_header *h)
688 {
689         return test_bit(LU_OBJECT_HEARD_BANSHEE, &h->loh_flags);
690 }
691
692 /**
693  * Return true if object is initialized.
694  */
695 static inline int lu_object_is_inited(const struct lu_object_header *h)
696 {
697         return test_bit(LU_OBJECT_INITED, &h->loh_flags);
698 }
699
700 void lu_object_put(const struct lu_env *env, struct lu_object *o);
701 void lu_object_put_nocache(const struct lu_env *env, struct lu_object *o);
702 void lu_object_unhash(const struct lu_env *env, struct lu_object *o);
703 int lu_site_purge_objects(const struct lu_env *env, struct lu_site *s, int nr,
704                           int canblock);
705
706 static inline int lu_site_purge(const struct lu_env *env, struct lu_site *s,
707                                 int nr)
708 {
709         return lu_site_purge_objects(env, s, nr, 1);
710 }
711
712 void lu_site_print(const struct lu_env *env, struct lu_site *s, void *cookie,
713                    lu_printer_t printer);
714 struct lu_object *lu_object_find(const struct lu_env *env,
715                                  struct lu_device *dev, const struct lu_fid *f,
716                                  const struct lu_object_conf *conf);
717 struct lu_object *lu_object_find_at(const struct lu_env *env,
718                                     struct lu_device *dev,
719                                     const struct lu_fid *f,
720                                     const struct lu_object_conf *conf);
721 struct lu_object *lu_object_find_slice(const struct lu_env *env,
722                                        struct lu_device *dev,
723                                        const struct lu_fid *f,
724                                        const struct lu_object_conf *conf);
725 /** @} caching */
726
727 /** \name helpers
728  * Helpers.
729  * @{
730  */
731
732 /**
733  * First (topmost) sub-object of given compound object
734  */
735 static inline struct lu_object *lu_object_top(struct lu_object_header *h)
736 {
737         LASSERT(!list_empty(&h->loh_layers));
738         return container_of0(h->loh_layers.next, struct lu_object, lo_linkage);
739 }
740
741 /**
742  * Next sub-object in the layering
743  */
744 static inline struct lu_object *lu_object_next(const struct lu_object *o)
745 {
746         return container_of0(o->lo_linkage.next, struct lu_object, lo_linkage);
747 }
748
749 /**
750  * Pointer to the fid of this object.
751  */
752 static inline const struct lu_fid *lu_object_fid(const struct lu_object *o)
753 {
754         return &o->lo_header->loh_fid;
755 }
756
757 /**
758  * return device operations vector for this object
759  */
760 static const inline struct lu_device_operations *
761 lu_object_ops(const struct lu_object *o)
762 {
763         return o->lo_dev->ld_ops;
764 }
765
766 /**
767  * Given a compound object, find its slice, corresponding to the device type
768  * \a dtype.
769  */
770 struct lu_object *lu_object_locate(struct lu_object_header *h,
771                                    const struct lu_device_type *dtype);
772
773 /**
774  * Printer function emitting messages through libcfs_debug_msg().
775  */
776 int lu_cdebug_printer(const struct lu_env *env,
777                       void *cookie, const char *format, ...);
778
779 /**
780  * Print object description followed by a user-supplied message.
781  */
782 #define LU_OBJECT_DEBUG(mask, env, object, format, ...)                   \
783 do {                                                                      \
784         if (cfs_cdebug_show(mask, DEBUG_SUBSYSTEM)) {                     \
785                 LIBCFS_DEBUG_MSG_DATA_DECL(msgdata, mask, NULL);          \
786                 lu_object_print(env, &msgdata, lu_cdebug_printer, object);\
787                 CDEBUG(mask, format "\n", ## __VA_ARGS__);                \
788         }                                                                 \
789 } while (0)
790
791 /**
792  * Print short object description followed by a user-supplied message.
793  */
794 #define LU_OBJECT_HEADER(mask, env, object, format, ...)                \
795 do {                                                                    \
796         if (cfs_cdebug_show(mask, DEBUG_SUBSYSTEM)) {                   \
797                 LIBCFS_DEBUG_MSG_DATA_DECL(msgdata, mask, NULL);        \
798                 lu_object_header_print(env, &msgdata, lu_cdebug_printer,\
799                                        (object)->lo_header);            \
800                 lu_cdebug_printer(env, &msgdata, "\n");                 \
801                 CDEBUG(mask, format , ## __VA_ARGS__);                  \
802         }                                                               \
803 } while (0)
804
805 void lu_object_print       (const struct lu_env *env, void *cookie,
806                             lu_printer_t printer, const struct lu_object *o);
807 void lu_object_header_print(const struct lu_env *env, void *cookie,
808                             lu_printer_t printer,
809                             const struct lu_object_header *hdr);
810
811 /**
812  * Check object consistency.
813  */
814 int lu_object_invariant(const struct lu_object *o);
815
816
817 /**
818  * Check whether object exists, no matter on local or remote storage.
819  * Note: LOHA_EXISTS will be set once some one created the object,
820  * and it does not needs to be committed to storage.
821  */
822 #define lu_object_exists(o) ((o)->lo_header->loh_attr & LOHA_EXISTS)
823
824 /**
825  * Check whether object on the remote storage.
826  */
827 #define lu_object_remote(o) unlikely((o)->lo_header->loh_attr & LOHA_REMOTE)
828
829 /**
830  * Check whether the object as agent entry on current target
831  */
832 #define lu_object_has_agent_entry(o) \
833         unlikely((o)->lo_header->loh_attr & LOHA_HAS_AGENT_ENTRY)
834
835 static inline void lu_object_set_agent_entry(struct lu_object *o)
836 {
837         o->lo_header->loh_attr |= LOHA_HAS_AGENT_ENTRY;
838 }
839
840 static inline void lu_object_clear_agent_entry(struct lu_object *o)
841 {
842         o->lo_header->loh_attr &= ~LOHA_HAS_AGENT_ENTRY;
843 }
844
845 static inline int lu_object_assert_exists(const struct lu_object *o)
846 {
847         return lu_object_exists(o);
848 }
849
850 static inline int lu_object_assert_not_exists(const struct lu_object *o)
851 {
852         return !lu_object_exists(o);
853 }
854
855 /**
856  * Attr of this object.
857  */
858 static inline __u32 lu_object_attr(const struct lu_object *o)
859 {
860         LASSERT(lu_object_exists(o) != 0);
861
862         return o->lo_header->loh_attr & S_IFMT;
863 }
864
865 static inline void lu_object_ref_add(struct lu_object *o,
866                                      const char *scope,
867                                      const void *source)
868 {
869         lu_ref_add(&o->lo_header->loh_reference, scope, source);
870 }
871
872 static inline void lu_object_ref_add_at(struct lu_object *o,
873                                         struct lu_ref_link *link,
874                                         const char *scope,
875                                         const void *source)
876 {
877         lu_ref_add_at(&o->lo_header->loh_reference, link, scope, source);
878 }
879
880 static inline void lu_object_ref_del(struct lu_object *o,
881                                      const char *scope, const void *source)
882 {
883         lu_ref_del(&o->lo_header->loh_reference, scope, source);
884 }
885
886 static inline void lu_object_ref_del_at(struct lu_object *o,
887                                         struct lu_ref_link *link,
888                                         const char *scope, const void *source)
889 {
890         lu_ref_del_at(&o->lo_header->loh_reference, link, scope, source);
891 }
892
893 /** input params, should be filled out by mdt */
894 struct lu_rdpg {
895         /** hash */
896         __u64                   rp_hash;
897         /** count in bytes */
898         unsigned int            rp_count;
899         /** number of pages */
900         unsigned int            rp_npages;
901         /** requested attr */
902         __u32                   rp_attrs;
903         /** pointers to pages */
904         struct page           **rp_pages;
905 };
906
907 enum lu_xattr_flags {
908         LU_XATTR_REPLACE = (1 << 0),
909         LU_XATTR_CREATE  = (1 << 1),
910         LU_XATTR_MERGE   = (1 << 2),
911         LU_XATTR_SPLIT   = (1 << 3),
912 };
913
914 /** @} helpers */
915
916 /** \name lu_context
917  * @{ */
918
919 /** For lu_context health-checks */
920 enum lu_context_state {
921         LCS_INITIALIZED = 1,
922         LCS_ENTERED,
923         LCS_LEAVING,
924         LCS_LEFT,
925         LCS_FINALIZED
926 };
927
928 /**
929  * lu_context. Execution context for lu_object methods. Currently associated
930  * with thread.
931  *
932  * All lu_object methods, except device and device type methods (called during
933  * system initialization and shutdown) are executed "within" some
934  * lu_context. This means, that pointer to some "current" lu_context is passed
935  * as an argument to all methods.
936  *
937  * All service ptlrpc threads create lu_context as part of their
938  * initialization. It is possible to create "stand-alone" context for other
939  * execution environments (like system calls).
940  *
941  * lu_object methods mainly use lu_context through lu_context_key interface
942  * that allows each layer to associate arbitrary pieces of data with each
943  * context (see pthread_key_create(3) for similar interface).
944  *
945  * On a client, lu_context is bound to a thread, see cl_env_get().
946  *
947  * \see lu_context_key
948  */
949 struct lu_context {
950         /**
951          * lu_context is used on the client side too. Yet we don't want to
952          * allocate values of server-side keys for the client contexts and
953          * vice versa.
954          *
955          * To achieve this, set of tags in introduced. Contexts and keys are
956          * marked with tags. Key value are created only for context whose set
957          * of tags has non-empty intersection with one for key. Tags are taken
958          * from enum lu_context_tag.
959          */
960         __u32                  lc_tags;
961         enum lu_context_state  lc_state;
962         /**
963          * Pointer to the home service thread. NULL for other execution
964          * contexts.
965          */
966         struct ptlrpc_thread  *lc_thread;
967         /**
968          * Pointer to an array with key values. Internal implementation
969          * detail.
970          */
971         void                  **lc_value;
972         /**
973          * Linkage into a list of all remembered contexts. Only
974          * `non-transient' contexts, i.e., ones created for service threads
975          * are placed here.
976          */
977         struct list_head        lc_remember;
978         /**
979          * Version counter used to skip calls to lu_context_refill() when no
980          * keys were registered.
981          */
982         unsigned                lc_version;
983         /**
984          * Debugging cookie.
985          */
986         unsigned                lc_cookie;
987 };
988
989 /**
990  * lu_context_key interface. Similar to pthread_key.
991  */
992
993 enum lu_context_tag {
994         /**
995          * Thread on md server
996          */
997         LCT_MD_THREAD = 1 << 0,
998         /**
999          * Thread on dt server
1000          */
1001         LCT_DT_THREAD = 1 << 1,
1002         /**
1003          * Thread on client
1004          */
1005         LCT_CL_THREAD = 1 << 3,
1006         /**
1007          * A per-request session on a server, and a per-system-call session on
1008          * a client.
1009          */
1010         LCT_SESSION   = 1 << 4,
1011         /**
1012          * A per-request data on OSP device
1013          */
1014         LCT_OSP_THREAD = 1 << 5,
1015         /**
1016          * MGS device thread
1017          */
1018         LCT_MG_THREAD = 1 << 6,
1019         /**
1020          * Context for local operations
1021          */
1022         LCT_LOCAL = 1 << 7,
1023         /**
1024          * session for server thread
1025          **/
1026         LCT_SERVER_SESSION = 1 << 8,
1027         /**
1028          * Set when at least one of keys, having values in this context has
1029          * non-NULL lu_context_key::lct_exit() method. This is used to
1030          * optimize lu_context_exit() call.
1031          */
1032         LCT_HAS_EXIT  = 1 << 28,
1033         /**
1034          * Don't add references for modules creating key values in that context.
1035          * This is only for contexts used internally by lu_object framework.
1036          */
1037         LCT_NOREF     = 1 << 29,
1038         /**
1039          * Key is being prepared for retiring, don't create new values for it.
1040          */
1041         LCT_QUIESCENT = 1 << 30,
1042         /**
1043          * Context should be remembered.
1044          */
1045         LCT_REMEMBER  = 1 << 31,
1046         /**
1047          * Contexts usable in cache shrinker thread.
1048          */
1049         LCT_SHRINKER  = LCT_MD_THREAD|LCT_DT_THREAD|LCT_CL_THREAD|LCT_NOREF
1050 };
1051
1052 /**
1053  * Key. Represents per-context value slot.
1054  *
1055  * Keys are usually registered when module owning the key is initialized, and
1056  * de-registered when module is unloaded. Once key is registered, all new
1057  * contexts with matching tags, will get key value. "Old" contexts, already
1058  * initialized at the time of key registration, can be forced to get key value
1059  * by calling lu_context_refill().
1060  *
1061  * Every key value is counted in lu_context_key::lct_used and acquires a
1062  * reference on an owning module. This means, that all key values have to be
1063  * destroyed before module can be unloaded. This is usually achieved by
1064  * stopping threads started by the module, that created contexts in their
1065  * entry functions. Situation is complicated by the threads shared by multiple
1066  * modules, like ptlrpcd daemon on a client. To work around this problem,
1067  * contexts, created in such threads, are `remembered' (see
1068  * LCT_REMEMBER)---i.e., added into a global list. When module is preparing
1069  * for unloading it does the following:
1070  *
1071  *     - marks its keys as `quiescent' (lu_context_tag::LCT_QUIESCENT)
1072  *       preventing new key values from being allocated in the new contexts,
1073  *       and
1074  *
1075  *     - scans a list of remembered contexts, destroying values of module
1076  *       keys, thus releasing references to the module.
1077  *
1078  * This is done by lu_context_key_quiesce(). If module is re-activated
1079  * before key has been de-registered, lu_context_key_revive() call clears
1080  * `quiescent' marker.
1081  *
1082  * lu_context code doesn't provide any internal synchronization for these
1083  * activities---it's assumed that startup (including threads start-up) and
1084  * shutdown are serialized by some external means.
1085  *
1086  * \see lu_context
1087  */
1088 struct lu_context_key {
1089         /**
1090          * Set of tags for which values of this key are to be instantiated.
1091          */
1092         __u32 lct_tags;
1093         /**
1094          * Value constructor. This is called when new value is created for a
1095          * context. Returns pointer to new value of error pointer.
1096          */
1097         void  *(*lct_init)(const struct lu_context *ctx,
1098                            struct lu_context_key *key);
1099         /**
1100          * Value destructor. Called when context with previously allocated
1101          * value of this slot is destroyed. \a data is a value that was returned
1102          * by a matching call to lu_context_key::lct_init().
1103          */
1104         void   (*lct_fini)(const struct lu_context *ctx,
1105                            struct lu_context_key *key, void *data);
1106         /**
1107          * Optional method called on lu_context_exit() for all allocated
1108          * keys. Can be used by debugging code checking that locks are
1109          * released, etc.
1110          */
1111         void   (*lct_exit)(const struct lu_context *ctx,
1112                            struct lu_context_key *key, void *data);
1113         /**
1114          * Internal implementation detail: index within lu_context::lc_value[]
1115          * reserved for this key.
1116          */
1117         int             lct_index;
1118         /**
1119          * Internal implementation detail: number of values created for this
1120          * key.
1121          */
1122         atomic_t        lct_used;
1123         /**
1124          * Internal implementation detail: module for this key.
1125          */
1126         struct module   *lct_owner;
1127         /**
1128          * References to this key. For debugging.
1129          */
1130         struct lu_ref   lct_reference;
1131 };
1132
1133 #define LU_KEY_INIT(mod, type)                                    \
1134         static void *mod##_key_init(const struct lu_context *ctx, \
1135                                     struct lu_context_key *key)   \
1136         {                                                         \
1137                 type *value;                                      \
1138                                                                   \
1139                 BUILD_BUG_ON(PAGE_SIZE < sizeof(*value));         \
1140                                                                   \
1141                 OBD_ALLOC_PTR(value);                             \
1142                 if (value == NULL)                                \
1143                         value = ERR_PTR(-ENOMEM);                 \
1144                                                                   \
1145                 return value;                                     \
1146         }                                                         \
1147         struct __##mod##__dummy_init { ; } /* semicolon catcher */
1148
1149 #define LU_KEY_FINI(mod, type)                                              \
1150         static void mod##_key_fini(const struct lu_context *ctx,            \
1151                                     struct lu_context_key *key, void* data) \
1152         {                                                                   \
1153                 type *info = data;                                          \
1154                                                                             \
1155                 OBD_FREE_PTR(info);                                         \
1156         }                                                                   \
1157         struct __##mod##__dummy_fini {;} /* semicolon catcher */
1158
1159 #define LU_KEY_INIT_FINI(mod, type)   \
1160         LU_KEY_INIT(mod,type);        \
1161         LU_KEY_FINI(mod,type)
1162
1163 #define LU_CONTEXT_KEY_DEFINE(mod, tags)                \
1164         struct lu_context_key mod##_thread_key = {      \
1165                 .lct_tags = tags,                       \
1166                 .lct_init = mod##_key_init,             \
1167                 .lct_fini = mod##_key_fini              \
1168         }
1169
1170 #define LU_CONTEXT_KEY_INIT(key)                        \
1171 do {                                                    \
1172         (key)->lct_owner = THIS_MODULE;                 \
1173 } while (0)
1174
1175 int   lu_context_key_register(struct lu_context_key *key);
1176 void  lu_context_key_degister(struct lu_context_key *key);
1177 void *lu_context_key_get     (const struct lu_context *ctx,
1178                                const struct lu_context_key *key);
1179 void  lu_context_key_quiesce (struct lu_context_key *key);
1180 void  lu_context_key_revive  (struct lu_context_key *key);
1181
1182
1183 /*
1184  * LU_KEY_INIT_GENERIC() has to be a macro to correctly determine an
1185  * owning module.
1186  */
1187
1188 #define LU_KEY_INIT_GENERIC(mod)                                        \
1189         static void mod##_key_init_generic(struct lu_context_key *k, ...) \
1190         {                                                               \
1191                 struct lu_context_key *key = k;                         \
1192                 va_list args;                                           \
1193                                                                         \
1194                 va_start(args, k);                                      \
1195                 do {                                                    \
1196                         LU_CONTEXT_KEY_INIT(key);                       \
1197                         key = va_arg(args, struct lu_context_key *);    \
1198                 } while (key != NULL);                                  \
1199                 va_end(args);                                           \
1200         }
1201
1202 #define LU_TYPE_INIT(mod, ...)                                          \
1203         LU_KEY_INIT_GENERIC(mod)                                        \
1204         static int mod##_type_init(struct lu_device_type *t)            \
1205         {                                                               \
1206                 mod##_key_init_generic(__VA_ARGS__, NULL);              \
1207                 return lu_context_key_register_many(__VA_ARGS__, NULL); \
1208         }                                                               \
1209         struct __##mod##_dummy_type_init {;}
1210
1211 #define LU_TYPE_FINI(mod, ...)                                          \
1212         static void mod##_type_fini(struct lu_device_type *t)           \
1213         {                                                               \
1214                 lu_context_key_degister_many(__VA_ARGS__, NULL);        \
1215         }                                                               \
1216         struct __##mod##_dummy_type_fini {;}
1217
1218 #define LU_TYPE_START(mod, ...)                                 \
1219         static void mod##_type_start(struct lu_device_type *t)  \
1220         {                                                       \
1221                 lu_context_key_revive_many(__VA_ARGS__, NULL);  \
1222         }                                                       \
1223         struct __##mod##_dummy_type_start {;}
1224
1225 #define LU_TYPE_STOP(mod, ...)                                  \
1226         static void mod##_type_stop(struct lu_device_type *t)   \
1227         {                                                       \
1228                 lu_context_key_quiesce_many(__VA_ARGS__, NULL); \
1229         }                                                       \
1230         struct __##mod##_dummy_type_stop {;}
1231
1232
1233
1234 #define LU_TYPE_INIT_FINI(mod, ...)             \
1235         LU_TYPE_INIT(mod, __VA_ARGS__);         \
1236         LU_TYPE_FINI(mod, __VA_ARGS__);         \
1237         LU_TYPE_START(mod, __VA_ARGS__);        \
1238         LU_TYPE_STOP(mod, __VA_ARGS__)
1239
1240 int   lu_context_init  (struct lu_context *ctx, __u32 tags);
1241 void  lu_context_fini  (struct lu_context *ctx);
1242 void  lu_context_enter (struct lu_context *ctx);
1243 void  lu_context_exit  (struct lu_context *ctx);
1244 int   lu_context_refill(struct lu_context *ctx);
1245
1246 /*
1247  * Helper functions to operate on multiple keys. These are used by the default
1248  * device type operations, defined by LU_TYPE_INIT_FINI().
1249  */
1250
1251 int  lu_context_key_register_many(struct lu_context_key *k, ...);
1252 void lu_context_key_degister_many(struct lu_context_key *k, ...);
1253 void lu_context_key_revive_many  (struct lu_context_key *k, ...);
1254 void lu_context_key_quiesce_many (struct lu_context_key *k, ...);
1255
1256 /*
1257  * update/clear ctx/ses tags.
1258  */
1259 void lu_context_tags_update(__u32 tags);
1260 void lu_context_tags_clear(__u32 tags);
1261 void lu_session_tags_update(__u32 tags);
1262 void lu_session_tags_clear(__u32 tags);
1263
1264 /**
1265  * Environment.
1266  */
1267 struct lu_env {
1268         /**
1269          * "Local" context, used to store data instead of stack.
1270          */
1271         struct lu_context  le_ctx;
1272         /**
1273          * "Session" context for per-request data.
1274          */
1275         struct lu_context *le_ses;
1276 };
1277
1278 int  lu_env_init  (struct lu_env *env, __u32 tags);
1279 void lu_env_fini  (struct lu_env *env);
1280 int  lu_env_refill(struct lu_env *env);
1281 int  lu_env_refill_by_tags(struct lu_env *env, __u32 ctags, __u32 stags);
1282
1283 static inline void* lu_env_info(const struct lu_env *env,
1284                                 const struct lu_context_key *key)
1285 {
1286         void *info;
1287         info = lu_context_key_get(&env->le_ctx, key);
1288         if (!info) {
1289                 if (!lu_env_refill((struct lu_env *)env))
1290                         info = lu_context_key_get(&env->le_ctx, key);
1291         }
1292         LASSERT(info);
1293         return info;
1294 }
1295
1296 struct lu_env *lu_env_find(void);
1297 int lu_env_add(struct lu_env *env);
1298 int lu_env_add_task(struct lu_env *env, struct task_struct *task);
1299 void lu_env_remove(struct lu_env *env);
1300
1301 /** @} lu_context */
1302
1303 /**
1304  * Output site statistical counters into a buffer. Suitable for
1305  * ll_rd_*()-style functions.
1306  */
1307 int lu_site_stats_seq_print(const struct lu_site *s, struct seq_file *m);
1308
1309 /**
1310  * Common name structure to be passed around for various name related methods.
1311  */
1312 struct lu_name {
1313         const char    *ln_name;
1314         int            ln_namelen;
1315 };
1316
1317 static inline bool name_is_dot_or_dotdot(const char *name, int namelen)
1318 {
1319         return name[0] == '.' &&
1320                (namelen == 1 || (namelen == 2 && name[1] == '.'));
1321 }
1322
1323 static inline bool lu_name_is_dot_or_dotdot(const struct lu_name *lname)
1324 {
1325         return name_is_dot_or_dotdot(lname->ln_name, lname->ln_namelen);
1326 }
1327
1328 static inline bool lu_name_is_temp_file(const char *name, int namelen,
1329                                         bool dot_prefix, int suffixlen)
1330 {
1331         int lower = 0;
1332         int upper = 0;
1333         int digit = 0;
1334         int len = suffixlen;
1335
1336         if (dot_prefix && name[0] != '.')
1337                 return false;
1338
1339         if (namelen < dot_prefix + suffixlen + 2 ||
1340             name[namelen - suffixlen - 1] != '.')
1341                 return false;
1342
1343         while (len) {
1344                 lower += islower(name[namelen - len]);
1345                 upper += isupper(name[namelen - len]);
1346                 digit += isdigit(name[namelen - len]);
1347                 len--;
1348         }
1349         /* mktemp() filename suffixes will have a mix of upper- and lower-case
1350          * letters and/or numbers, not all numbers, or all upper or lower-case.
1351          * About 0.07% of randomly-generated names will slip through,
1352          * but this avoids 99.93% of cross-MDT renames for those files.
1353          */
1354         if (digit >= suffixlen - 2 || upper == suffixlen || lower == suffixlen)
1355                 return false;
1356
1357         return true;
1358 }
1359
1360 static inline bool lu_name_is_backup_file(const char *name, int namelen,
1361                                           int *suffixlen)
1362 {
1363         if (namelen > 1 &&
1364             name[namelen - 2] != '.' && name[namelen - 1] == '~') {
1365                 if (suffixlen)
1366                         *suffixlen = 1;
1367                 return true;
1368         }
1369
1370         if (namelen > 4 && name[namelen - 4] == '.' &&
1371             (!strncasecmp(name + namelen - 3, "bak", 3) ||
1372              !strncasecmp(name + namelen - 3, "sav", 3))) {
1373                 if (suffixlen)
1374                         *suffixlen = 4;
1375                 return true;
1376         }
1377
1378         if (namelen > 5 && name[namelen - 5] == '.' &&
1379             !strncasecmp(name + namelen - 4, "orig", 4)) {
1380                 if (suffixlen)
1381                         *suffixlen = 5;
1382                 return true;
1383         }
1384
1385         return false;
1386 }
1387
1388 static inline bool lu_name_is_valid_len(const char *name, size_t name_len)
1389 {
1390         return name != NULL &&
1391                name_len > 0 &&
1392                name_len < INT_MAX &&
1393                strlen(name) == name_len &&
1394                memchr(name, '/', name_len) == NULL;
1395 }
1396
1397 /**
1398  * Validate names (path components)
1399  *
1400  * To be valid \a name must be non-empty, '\0' terminated of length \a
1401  * name_len, and not contain '/'. The maximum length of a name (before
1402  * say -ENAMETOOLONG will be returned) is really controlled by llite
1403  * and the server. We only check for something insane coming from bad
1404  * integer handling here.
1405  */
1406 static inline bool lu_name_is_valid_2(const char *name, size_t name_len)
1407 {
1408         return lu_name_is_valid_len(name, name_len) && name[name_len] == '\0';
1409 }
1410
1411 static inline bool lu_name_is_valid(const struct lu_name *ln)
1412 {
1413         return lu_name_is_valid_2(ln->ln_name, ln->ln_namelen);
1414 }
1415
1416 #define DNAME "%.*s"
1417 #define PNAME(ln)                                       \
1418         (lu_name_is_valid(ln) ? (ln)->ln_namelen : 0),  \
1419         (lu_name_is_valid(ln) ? (ln)->ln_name : "")
1420
1421 /**
1422  * Common buffer structure to be passed around for various xattr_{s,g}et()
1423  * methods.
1424  */
1425 struct lu_buf {
1426         void   *lb_buf;
1427         size_t  lb_len;
1428 };
1429
1430 #define DLUBUF "(%p %zu)"
1431 #define PLUBUF(buf) (buf)->lb_buf, (buf)->lb_len
1432
1433 /* read buffer params, should be filled out by out */
1434 struct lu_rdbuf {
1435         /** number of buffers */
1436         unsigned int    rb_nbufs;
1437         /** pointers to buffers */
1438         struct lu_buf   rb_bufs[];
1439 };
1440
1441 /**
1442  * One-time initializers, called at obdclass module initialization, not
1443  * exported.
1444  */
1445
1446 /**
1447  * Initialization of global lu_* data.
1448  */
1449 int lu_global_init(void);
1450
1451 /**
1452  * Dual to lu_global_init().
1453  */
1454 void lu_global_fini(void);
1455
1456 struct lu_kmem_descr {
1457         struct kmem_cache **ckd_cache;
1458         const char       *ckd_name;
1459         const size_t      ckd_size;
1460 };
1461
1462 int  lu_kmem_init(struct lu_kmem_descr *caches);
1463 void lu_kmem_fini(struct lu_kmem_descr *caches);
1464
1465 void lu_object_assign_fid(const struct lu_env *env, struct lu_object *o,
1466                           const struct lu_fid *fid);
1467 struct lu_object *lu_object_anon(const struct lu_env *env,
1468                                  struct lu_device *dev,
1469                                  const struct lu_object_conf *conf);
1470
1471 /** null buffer */
1472 extern struct lu_buf LU_BUF_NULL;
1473
1474 void lu_buf_free(struct lu_buf *buf);
1475 void lu_buf_alloc(struct lu_buf *buf, size_t size);
1476 void lu_buf_realloc(struct lu_buf *buf, size_t size);
1477
1478 int lu_buf_check_and_grow(struct lu_buf *buf, size_t len);
1479 struct lu_buf *lu_buf_check_and_alloc(struct lu_buf *buf, size_t len);
1480
1481 extern __u32 lu_context_tags_default;
1482 extern __u32 lu_session_tags_default;
1483
1484 static inline bool lu_device_is_cl(const struct lu_device *d)
1485 {
1486         return d->ld_type->ldt_tags & LU_DEVICE_CL;
1487 }
1488
1489 static inline bool lu_object_is_cl(const struct lu_object *o)
1490 {
1491         return lu_device_is_cl(o->lo_dev);
1492 }
1493
1494 /* round-robin QoS data for LOD/LMV */
1495 struct lu_qos_rr {
1496         spinlock_t               lqr_alloc;     /* protect allocation index */
1497         __u32                    lqr_start_idx; /* start index of new inode */
1498         __u32                    lqr_offset_idx;/* aliasing for start_idx */
1499         int                      lqr_start_count;/* reseed counter */
1500         struct lu_tgt_pool       lqr_pool;      /* round-robin optimized list */
1501         unsigned long            lqr_dirty:1;   /* recalc round-robin list */
1502 };
1503
1504 /* QoS data per MDS/OSS */
1505 struct lu_svr_qos {
1506         struct obd_uuid          lsq_uuid;      /* ptlrpc's c_remote_uuid */
1507         struct list_head         lsq_svr_list;  /* link to lq_svr_list */
1508         __u64                    lsq_bavail;    /* total bytes avail on svr */
1509         __u64                    lsq_iavail;    /* tital inode avail on svr */
1510         __u64                    lsq_penalty;   /* current penalty */
1511         __u64                    lsq_penalty_per_obj; /* penalty decrease
1512                                                        * every obj*/
1513         time64_t                 lsq_used;      /* last used time, seconds */
1514         __u32                    lsq_tgt_count; /* number of tgts on this svr */
1515         __u32                    lsq_id;        /* unique svr id */
1516 };
1517
1518 /* QoS data per MDT/OST */
1519 struct lu_tgt_qos {
1520         struct lu_svr_qos       *ltq_svr;       /* svr info */
1521         __u64                    ltq_penalty;   /* current penalty */
1522         __u64                    ltq_penalty_per_obj; /* penalty decrease
1523                                                        * every obj*/
1524         __u64                    ltq_weight;    /* net weighting */
1525         time64_t                 ltq_used;      /* last used time, seconds */
1526         bool                     ltq_usable:1;  /* usable for striping */
1527 };
1528
1529 /* target descriptor */
1530 struct lu_tgt_desc {
1531         union {
1532                 struct dt_device        *ltd_tgt;
1533                 struct obd_device       *ltd_obd;
1534         };
1535         struct obd_export *ltd_exp;
1536         struct obd_uuid    ltd_uuid;
1537         __u32              ltd_index;
1538         __u32              ltd_gen;
1539         struct list_head   ltd_kill;
1540         struct task_struct *ltd_recovery_task;
1541         struct mutex       ltd_fid_mutex;
1542         struct lu_tgt_qos  ltd_qos; /* qos info per target */
1543         struct obd_statfs  ltd_statfs;
1544         time64_t           ltd_statfs_age;
1545         unsigned long      ltd_active:1,/* is this target up for requests */
1546                            ltd_activate:1,/* should target be activated */
1547                            ltd_reap:1,  /* should this target be deleted */
1548                            ltd_got_update_log:1, /* Already got update log */
1549                            ltd_connecting:1; /* target is connecting */
1550 };
1551
1552 /* number of pointers at 1st level */
1553 #define TGT_PTRS                (PAGE_SIZE / sizeof(void *))
1554 /* number of pointers at 2nd level */
1555 #define TGT_PTRS_PER_BLOCK      (PAGE_SIZE / sizeof(void *))
1556
1557 struct lu_tgt_desc_idx {
1558         struct lu_tgt_desc *ldi_tgt[TGT_PTRS_PER_BLOCK];
1559 };
1560
1561 /* QoS data for LOD/LMV */
1562 struct lu_qos {
1563         struct list_head         lq_svr_list;   /* lu_svr_qos list */
1564         struct rw_semaphore      lq_rw_sem;
1565         __u32                    lq_active_svr_count;
1566         unsigned int             lq_prio_free;   /* priority for free space */
1567         unsigned int             lq_threshold_rr;/* priority for rr */
1568         struct lu_qos_rr         lq_rr;          /* round robin qos data */
1569         unsigned long            lq_dirty:1,     /* recalc qos data */
1570                                  lq_same_space:1,/* the servers all have approx.
1571                                                   * the same space avail */
1572                                  lq_reset:1;     /* zero current penalties */
1573 };
1574
1575 struct lu_tgt_descs {
1576         union {
1577                 struct lov_desc       ltd_lov_desc;
1578                 struct lmv_desc       ltd_lmv_desc;
1579         };
1580         /* list of known TGTs */
1581         struct lu_tgt_desc_idx  *ltd_tgt_idx[TGT_PTRS];
1582         /* Size of the lu_tgts array, granted to be a power of 2 */
1583         __u32                   ltd_tgts_size;
1584         /* bitmap of TGTs available */
1585         struct cfs_bitmap       *ltd_tgt_bitmap;
1586         /* TGTs scheduled to be deleted */
1587         __u32                   ltd_death_row;
1588         /* Table refcount used for delayed deletion */
1589         int                     ltd_refcount;
1590         /* mutex to serialize concurrent updates to the tgt table */
1591         struct mutex            ltd_mutex;
1592         /* read/write semaphore used for array relocation */
1593         struct rw_semaphore     ltd_rw_sem;
1594         /* QoS */
1595         struct lu_qos           ltd_qos;
1596         /* all tgts in a packed array */
1597         struct lu_tgt_pool      ltd_tgt_pool;
1598         /* true if tgt is MDT */
1599         bool                    ltd_is_mdt;
1600 };
1601
1602 #define LTD_TGT(ltd, index)                                             \
1603          (ltd)->ltd_tgt_idx[(index) /                                   \
1604          TGT_PTRS_PER_BLOCK]->ldi_tgt[(index) % TGT_PTRS_PER_BLOCK]
1605
1606 u64 lu_prandom_u64_max(u64 ep_ro);
1607 void lu_qos_rr_init(struct lu_qos_rr *lqr);
1608 int lu_qos_add_tgt(struct lu_qos *qos, struct lu_tgt_desc *ltd);
1609 void lu_tgt_qos_weight_calc(struct lu_tgt_desc *tgt);
1610
1611 int lu_tgt_descs_init(struct lu_tgt_descs *ltd, bool is_mdt);
1612 void lu_tgt_descs_fini(struct lu_tgt_descs *ltd);
1613 int ltd_add_tgt(struct lu_tgt_descs *ltd, struct lu_tgt_desc *tgt);
1614 void ltd_del_tgt(struct lu_tgt_descs *ltd, struct lu_tgt_desc *tgt);
1615 bool ltd_qos_is_usable(struct lu_tgt_descs *ltd);
1616 int ltd_qos_penalties_calc(struct lu_tgt_descs *ltd);
1617 int ltd_qos_update(struct lu_tgt_descs *ltd, struct lu_tgt_desc *tgt,
1618                    __u64 *total_wt);
1619
1620 static inline struct lu_tgt_desc *ltd_first_tgt(struct lu_tgt_descs *ltd)
1621 {
1622         int index;
1623
1624         index = find_first_bit(ltd->ltd_tgt_bitmap->data,
1625                                ltd->ltd_tgt_bitmap->size);
1626         return (index < ltd->ltd_tgt_bitmap->size) ? LTD_TGT(ltd, index) : NULL;
1627 }
1628
1629 static inline struct lu_tgt_desc *ltd_next_tgt(struct lu_tgt_descs *ltd,
1630                                                struct lu_tgt_desc *tgt)
1631 {
1632         int index;
1633
1634         if (!tgt)
1635                 return NULL;
1636
1637         index = tgt->ltd_index;
1638         LASSERT(index < ltd->ltd_tgt_bitmap->size);
1639         index = find_next_bit(ltd->ltd_tgt_bitmap->data,
1640                               ltd->ltd_tgt_bitmap->size, index + 1);
1641         return (index < ltd->ltd_tgt_bitmap->size) ? LTD_TGT(ltd, index) : NULL;
1642 }
1643
1644 #define ltd_foreach_tgt(ltd, tgt) \
1645         for (tgt = ltd_first_tgt(ltd); tgt; tgt = ltd_next_tgt(ltd, tgt))
1646
1647 #define ltd_foreach_tgt_safe(ltd, tgt, tmp)                               \
1648         for (tgt = ltd_first_tgt(ltd), tmp = ltd_next_tgt(ltd, tgt); tgt; \
1649              tgt = tmp, tmp = ltd_next_tgt(ltd, tgt))
1650
1651 /** @} lu */
1652 #endif /* __LUSTRE_LU_OBJECT_H */