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