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