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