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