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