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