Whamcloud - gitweb
LU-6142 lustre: mark strings in char arrays as const
[fs/lustre-release.git] / lustre / utils / liblustreapi_layout.c
1 /*
2  * LGPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * All rights reserved. This program and the accompanying materials
7  * are made available under the terms of the GNU Lesser General Public License
8  * (LGPL) version 2.1 or (at your discretion) any later version.
9  * (LGPL) version 2.1 accompanies this distribution, and is available at
10  * http://www.gnu.org/licenses/lgpl-2.1.html
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * Lesser General Public License for more details.
16  *
17  * LGPL HEADER END
18  */
19 /*
20  * lustre/utils/liblustreapi_layout.c
21  *
22  * lustreapi library for layout calls for interacting with the layout of
23  * Lustre files while hiding details of the internal data structures
24  * from the user.
25  *
26  * Copyright (c) 2016, 2017, Intel Corporation.
27  *
28  * Author: Ned Bass <bass6@llnl.gov>
29  */
30
31 #include <stdio.h>
32 #include <fcntl.h>
33 #include <stdlib.h>
34 #include <unistd.h>
35 #include <errno.h>
36 #include <limits.h>
37 #include <assert.h>
38 #include <sys/xattr.h>
39 #include <sys/param.h>
40
41 #include <libcfs/util/list.h>
42 #include <lustre/lustreapi.h>
43 #include "lustreapi_internal.h"
44
45 /**
46  * Layout component, which contains all attributes of a plain
47  * V1/V3 layout.
48  */
49 struct llapi_layout_comp {
50         uint64_t        llc_pattern;
51         uint64_t        llc_stripe_size;
52         uint64_t        llc_stripe_count;
53         uint64_t        llc_stripe_offset;
54         /* Add 1 so user always gets back a null terminated string. */
55         char            llc_pool_name[LOV_MAXPOOLNAME + 1];
56         /** Number of objects in llc_objects array if was initialized. */
57         uint32_t        llc_objects_count;
58         struct          lov_user_ost_data_v1 *llc_objects;
59         /* fields used only for composite layouts */
60         struct lu_extent        llc_extent;     /* [start, end) of component */
61         uint32_t                llc_id;         /* unique ID of component */
62         uint32_t                llc_flags;      /* LCME_FL_* flags */
63         uint64_t                llc_timestamp;  /* snapshot timestamp */
64         struct list_head        llc_list;       /* linked to the llapi_layout
65                                                    components list */
66         bool            llc_ondisk;
67 };
68
69 /**
70  * An Opaque data type abstracting the layout of a Lustre file.
71  */
72 struct llapi_layout {
73         uint32_t        llot_magic; /* LLAPI_LAYOUT_MAGIC */
74         uint32_t        llot_gen;
75         uint32_t        llot_flags;
76         bool            llot_is_composite;
77         uint16_t        llot_mirror_count;
78         /* Cursor pointing to one of the components in llot_comp_list */
79         struct llapi_layout_comp *llot_cur_comp;
80         struct list_head          llot_comp_list;
81 };
82
83 /**
84  * Compute the number of elements in the lmm_objects array of \a lum
85  * with size \a lum_size.
86  *
87  * \param[in] lum       the struct lov_user_md to check
88  * \param[in] lum_size  the number of bytes in \a lum
89  *
90  * \retval              number of elements in array lum->lmm_objects
91  */
92 static int llapi_layout_objects_in_lum(struct lov_user_md *lum, size_t lum_size)
93 {
94         uint32_t magic;
95         size_t base_size;
96
97         if (lum_size < lov_user_md_size(0, LOV_MAGIC_V1))
98                 return 0;
99
100         if (lum->lmm_magic == __swab32(LOV_MAGIC_V1) ||
101             lum->lmm_magic == __swab32(LOV_MAGIC_V3))
102                 magic = __swab32(lum->lmm_magic);
103         else
104                 magic = lum->lmm_magic;
105
106         base_size = lov_user_md_size(0, magic);
107
108         if (lum_size <= base_size)
109                 return 0;
110         else
111                 return (lum_size - base_size) / sizeof(lum->lmm_objects[0]);
112 }
113
114 /**
115  * Byte-swap the fields of struct lov_user_md.
116  *
117  * XXX Rather than duplicating swabbing code here, we should eventually
118  * refactor the needed functions in lustre/ptlrpc/pack_generic.c
119  * into a library that can be shared between kernel and user code.
120  */
121 static void
122 llapi_layout_swab_lov_user_md(struct lov_user_md *lum, int lum_size)
123 {
124         int i, j, ent_count, obj_count;
125         struct lov_comp_md_v1 *comp_v1 = NULL;
126         struct lov_comp_md_entry_v1 *ent;
127         struct lov_user_ost_data *lod;
128
129         if (lum->lmm_magic != __swab32(LOV_MAGIC_V1) &&
130             lum->lmm_magic != __swab32(LOV_MAGIC_V3) &&
131             lum->lmm_magic != __swab32(LOV_MAGIC_COMP_V1))
132                 return;
133
134         if (lum->lmm_magic == __swab32(LOV_MAGIC_COMP_V1))
135                 comp_v1 = (struct lov_comp_md_v1 *)lum;
136
137         if (comp_v1 != NULL) {
138                 comp_v1->lcm_magic = __swab32(comp_v1->lcm_magic);
139                 comp_v1->lcm_size = __swab32(comp_v1->lcm_size);
140                 comp_v1->lcm_layout_gen = __swab32(comp_v1->lcm_layout_gen);
141                 comp_v1->lcm_flags = __swab16(comp_v1->lcm_flags);
142                 comp_v1->lcm_entry_count = __swab16(comp_v1->lcm_entry_count);
143                 ent_count = comp_v1->lcm_entry_count;
144         } else {
145                 ent_count = 1;
146         }
147
148         for (i = 0; i < ent_count; i++) {
149                 if (comp_v1 != NULL) {
150                         ent = &comp_v1->lcm_entries[i];
151                         ent->lcme_id = __swab32(ent->lcme_id);
152                         ent->lcme_flags = __swab32(ent->lcme_flags);
153                         ent->lcme_timestamp = __swab64(ent->lcme_timestamp);
154                         ent->lcme_extent.e_start = __swab64(ent->lcme_extent.e_start);
155                         ent->lcme_extent.e_end = __swab64(ent->lcme_extent.e_end);
156                         ent->lcme_offset = __swab32(ent->lcme_offset);
157                         ent->lcme_size = __swab32(ent->lcme_size);
158
159                         lum = (struct lov_user_md *)((char *)comp_v1 +
160                                         ent->lcme_offset);
161                         lum_size = ent->lcme_size;
162                 }
163                 obj_count = llapi_layout_objects_in_lum(lum, lum_size);
164
165                 lum->lmm_magic = __swab32(lum->lmm_magic);
166                 lum->lmm_pattern = __swab32(lum->lmm_pattern);
167                 lum->lmm_stripe_size = __swab32(lum->lmm_stripe_size);
168                 lum->lmm_stripe_count = __swab16(lum->lmm_stripe_count);
169                 lum->lmm_stripe_offset = __swab16(lum->lmm_stripe_offset);
170
171                 if (lum->lmm_magic != LOV_MAGIC_V1) {
172                         struct lov_user_md_v3 *v3;
173                         v3 = (struct lov_user_md_v3 *)lum;
174                         lod = v3->lmm_objects;
175                 } else {
176                         lod = lum->lmm_objects;
177                 }
178
179                 for (j = 0; j < obj_count; j++)
180                         lod[j].l_ost_idx = __swab32(lod[j].l_ost_idx);
181         }
182 }
183
184 /**
185  * (Re-)allocate llc_objects[] to \a num_stripes stripes.
186  *
187  * Copy over existing llc_objects[], if any, to the new llc_objects[].
188  *
189  * \param[in] layout            existing layout to be modified
190  * \param[in] num_stripes       number of stripes in new layout
191  *
192  * \retval      0 if the objects are re-allocated successfully
193  * \retval      -1 on error with errno set
194  */
195 static int __llapi_comp_objects_realloc(struct llapi_layout_comp *comp,
196                                         unsigned int new_stripes)
197 {
198         struct lov_user_ost_data_v1 *new_objects;
199         unsigned int i;
200
201         if (new_stripes > LOV_MAX_STRIPE_COUNT) {
202                 errno = EINVAL;
203                 return -1;
204         }
205
206         if (new_stripes == comp->llc_objects_count)
207                 return 0;
208
209         if (new_stripes != 0 && new_stripes <= comp->llc_objects_count)
210                 return 0;
211
212         new_objects = realloc(comp->llc_objects,
213                               sizeof(*new_objects) * new_stripes);
214         if (new_objects == NULL && new_stripes != 0) {
215                 errno = ENOMEM;
216                 return -1;
217         }
218
219         for (i = comp->llc_objects_count; i < new_stripes; i++)
220                 new_objects[i].l_ost_idx = LLAPI_LAYOUT_IDX_MAX;
221
222         comp->llc_objects = new_objects;
223         comp->llc_objects_count = new_stripes;
224
225         return 0;
226 }
227
228 /**
229  * Allocate storage for a llapi_layout_comp with \a num_stripes stripes.
230  *
231  * \param[in] num_stripes       number of stripes in new layout
232  *
233  * \retval      valid pointer if allocation succeeds
234  * \retval      NULL if allocation fails
235  */
236 static struct llapi_layout_comp *__llapi_comp_alloc(unsigned int num_stripes)
237 {
238         struct llapi_layout_comp *comp;
239
240         if (num_stripes > LOV_MAX_STRIPE_COUNT) {
241                 errno = EINVAL;
242                 return NULL;
243         }
244
245         comp = calloc(1, sizeof(*comp));
246         if (comp == NULL) {
247                 errno = ENOMEM;
248                 return NULL;
249         }
250
251         comp->llc_objects = NULL;
252         comp->llc_objects_count = 0;
253
254         if (__llapi_comp_objects_realloc(comp, num_stripes) < 0) {
255                 free(comp);
256                 return NULL;
257         }
258
259         /* Set defaults. */
260         comp->llc_pattern = LLAPI_LAYOUT_DEFAULT;
261         comp->llc_stripe_size = LLAPI_LAYOUT_DEFAULT;
262         comp->llc_stripe_count = LLAPI_LAYOUT_DEFAULT;
263         comp->llc_stripe_offset = LLAPI_LAYOUT_DEFAULT;
264         comp->llc_pool_name[0] = '\0';
265         comp->llc_extent.e_start = 0;
266         comp->llc_extent.e_end = LUSTRE_EOF;
267         comp->llc_flags = 0;
268         comp->llc_id = 0;
269         INIT_LIST_HEAD(&comp->llc_list);
270
271         return comp;
272 }
273
274 /**
275  * Free memory allocated for \a comp
276  *
277  * \param[in] comp      previously allocated by __llapi_comp_alloc()
278  */
279 static void __llapi_comp_free(struct llapi_layout_comp *comp)
280 {
281         if (comp->llc_objects != NULL)
282                 free(comp->llc_objects);
283         free(comp);
284 }
285
286 /**
287  * Free memory allocated for \a layout.
288  *
289  * \param[in] layout    previously allocated by llapi_layout_alloc()
290  */
291 void llapi_layout_free(struct llapi_layout *layout)
292 {
293         struct llapi_layout_comp *comp, *n;
294
295         if (layout == NULL)
296                 return;
297
298         list_for_each_entry_safe(comp, n, &layout->llot_comp_list, llc_list) {
299                 list_del_init(&comp->llc_list);
300                 __llapi_comp_free(comp);
301         }
302         free(layout);
303 }
304
305 /**
306  * Allocate and initialize a llapi_layout structure.
307  *
308  * \retval      valid llapi_layout pointer on success
309  * \retval      NULL if memory allocation fails
310  */
311 static struct llapi_layout *__llapi_layout_alloc(void)
312 {
313         struct llapi_layout *layout;
314
315         layout = calloc(1, sizeof(*layout));
316         if (layout == NULL) {
317                 errno = ENOMEM;
318                 return NULL;
319         }
320
321         /* Set defaults. */
322         layout->llot_magic = LLAPI_LAYOUT_MAGIC;
323         layout->llot_gen = 0;
324         layout->llot_flags = 0;
325         layout->llot_is_composite = false;
326         layout->llot_mirror_count = 1;
327         layout->llot_cur_comp = NULL;
328         INIT_LIST_HEAD(&layout->llot_comp_list);
329
330         return layout;
331 }
332
333 /**
334  * Allocate and initialize a new plain layout.
335  *
336  * \retval      valid llapi_layout pointer on success
337  * \retval      NULL if memory allocation fails
338  */
339 struct llapi_layout *llapi_layout_alloc(void)
340 {
341         struct llapi_layout_comp *comp;
342         struct llapi_layout *layout;
343
344         layout = __llapi_layout_alloc();
345         if (layout == NULL)
346                 return NULL;
347
348         comp = __llapi_comp_alloc(0);
349         if (comp == NULL) {
350                 free(layout);
351                 return NULL;
352         }
353
354         list_add_tail(&comp->llc_list, &layout->llot_comp_list);
355         layout->llot_cur_comp = comp;
356
357         return layout;
358 }
359
360 /**
361  * Check if the given \a lum_size is large enough to hold the required
362  * fields in \a lum.
363  *
364  * \param[in] lum       the struct lov_user_md to check
365  * \param[in] lum_size  the number of bytes in \a lum
366  *
367  * \retval true         the \a lum_size is too small
368  * \retval false        the \a lum_size is large enough
369  */
370 static bool llapi_layout_lum_truncated(struct lov_user_md *lum, size_t lum_size)
371 {
372         uint32_t magic;
373
374         if (lum_size < sizeof(lum->lmm_magic))
375                 return true;
376
377         if (lum->lmm_magic == LOV_MAGIC_V1 ||
378             lum->lmm_magic == __swab32(LOV_MAGIC_V1))
379                 magic = LOV_MAGIC_V1;
380         else if (lum->lmm_magic == LOV_MAGIC_V3 ||
381                  lum->lmm_magic == __swab32(LOV_MAGIC_V3))
382                 magic = LOV_MAGIC_V3;
383         else if (lum->lmm_magic == LOV_MAGIC_COMP_V1 ||
384                  lum->lmm_magic == __swab32(LOV_MAGIC_COMP_V1))
385                 magic = LOV_MAGIC_COMP_V1;
386         else
387                 return true;
388
389         if (magic == LOV_MAGIC_V1 || magic == LOV_MAGIC_V3)
390                 return lum_size < lov_user_md_size(0, magic);
391         else
392                 return lum_size < sizeof(struct lov_comp_md_v1);
393 }
394
395 /* Verify if the objects count in lum is consistent with the
396  * stripe count in lum. It applies to regular file only. */
397 static bool llapi_layout_lum_valid(struct lov_user_md *lum, int lum_size)
398 {
399         struct lov_comp_md_v1 *comp_v1 = NULL;
400         int i, ent_count, obj_count;
401
402         if (lum->lmm_magic == LOV_MAGIC_COMP_V1) {
403                 comp_v1 = (struct lov_comp_md_v1 *)lum;
404                 ent_count = comp_v1->lcm_entry_count;
405         } else if (lum->lmm_magic == LOV_MAGIC_V1 ||
406                    lum->lmm_magic == LOV_MAGIC_V3) {
407                 ent_count = 1;
408         } else {
409                 return false;
410         }
411
412         for (i = 0; i < ent_count; i++) {
413                 if (comp_v1) {
414                         lum = (struct lov_user_md *)((char *)comp_v1 +
415                                 comp_v1->lcm_entries[i].lcme_offset);
416                         lum_size = comp_v1->lcm_entries[i].lcme_size;
417                 }
418                 obj_count = llapi_layout_objects_in_lum(lum, lum_size);
419
420                 if (comp_v1) {
421                         if (!(comp_v1->lcm_entries[i].lcme_flags &
422                                  LCME_FL_INIT) && obj_count != 0)
423                                 return false;
424                 } else if (obj_count != lum->lmm_stripe_count) {
425                         return false;
426                 }
427         }
428         return true;
429 }
430
431 /**
432  * Convert the data from a lov_user_md to a newly allocated llapi_layout.
433  * The caller is responsible for freeing the returned pointer.
434  *
435  * \param[in] lov_xattr         LOV user metadata xattr to copy data from
436  * \param[in] lov_xattr_size    size the lov_xattr_size passed in
437  * \param[in] flags             bitwise-or'd flags to control the behavior
438  *
439  * \retval              valid llapi_layout pointer on success
440  * \retval              NULL if memory allocation fails
441  */
442 struct llapi_layout *llapi_layout_get_by_xattr(void *lov_xattr,
443                                                ssize_t lov_xattr_size,
444                                                uint32_t flags)
445 {
446         struct lov_user_md *lum = lov_xattr;
447         struct lov_comp_md_v1 *comp_v1 = NULL;
448         struct lov_comp_md_entry_v1 *ent;
449         struct lov_user_md *v1;
450         struct llapi_layout *layout = NULL;
451         struct llapi_layout_comp *comp;
452         int i, ent_count = 0, obj_count;
453
454         if (lov_xattr == NULL || lov_xattr_size <= 0) {
455                 errno = EINVAL;
456                 return NULL;
457         }
458
459         /* Return an error if we got back a partial layout. */
460         if (llapi_layout_lum_truncated(lov_xattr, lov_xattr_size)) {
461                 errno = ERANGE;
462                 return NULL;
463         }
464
465 #if __BYTE_ORDER == __BIG_ENDIAN
466         if (flags & LLAPI_LXF_COPY) {
467                 lum = malloc(lov_xattr_size);
468                 if (lum == NULL) {
469                         errno = ENOMEM;
470                         return NULL;
471                 }
472                 memcpy(lum, lov_xattr, lov_xattr_size);
473         }
474 #endif
475
476         llapi_layout_swab_lov_user_md(lum, lov_xattr_size);
477
478         if ((flags & LLAPI_LXF_CHECK) &&
479             !llapi_layout_lum_valid(lum, lov_xattr_size)) {
480                 errno = EBADSLT;
481                 goto out;
482         }
483
484         layout = __llapi_layout_alloc();
485         if (layout == NULL) {
486                 errno = ENOMEM;
487                 goto out;
488         }
489
490         if (lum->lmm_magic == LOV_MAGIC_COMP_V1) {
491                 comp_v1 = (struct lov_comp_md_v1 *)lum;
492                 ent_count = comp_v1->lcm_entry_count;
493                 layout->llot_gen = comp_v1->lcm_layout_gen;
494                 layout->llot_is_composite = true;
495                 layout->llot_mirror_count = comp_v1->lcm_mirror_count + 1;
496                 layout->llot_gen = comp_v1->lcm_layout_gen;
497                 layout->llot_flags = comp_v1->lcm_flags;
498         } else if (lum->lmm_magic == LOV_MAGIC_V1 ||
499                    lum->lmm_magic == LOV_MAGIC_V3) {
500                 ent_count = 1;
501                 layout->llot_is_composite = false;
502
503                 if (lov_xattr_size <= 0) {
504                         errno = EINVAL;
505                         goto out_layout;
506                 }
507         } else {
508                 errno = EOPNOTSUPP;
509                 goto out_layout;
510         }
511
512         if (ent_count == 0) {
513                 errno = EINVAL;
514                 goto out_layout;
515         }
516
517         v1 = (struct lov_user_md *)lum;
518         for (i = 0; i < ent_count; i++) {
519                 if (comp_v1 != NULL) {
520                         ent = &comp_v1->lcm_entries[i];
521                         v1 = (struct lov_user_md *)((char *)comp_v1 +
522                                 ent->lcme_offset);
523                         lov_xattr_size = ent->lcme_size;
524                 } else {
525                         ent = NULL;
526                 }
527
528                 obj_count = llapi_layout_objects_in_lum(v1, lov_xattr_size);
529                 comp = __llapi_comp_alloc(obj_count);
530                 if (comp == NULL)
531                         goto out_layout;
532
533                 if (ent != NULL) {
534                         comp->llc_extent.e_start = ent->lcme_extent.e_start;
535                         comp->llc_extent.e_end = ent->lcme_extent.e_end;
536                         comp->llc_id = ent->lcme_id;
537                         comp->llc_flags = ent->lcme_flags;
538                         if (comp->llc_flags & LCME_FL_NOSYNC)
539                                 comp->llc_timestamp = ent->lcme_timestamp;
540                 } else {
541                         comp->llc_extent.e_start = 0;
542                         comp->llc_extent.e_end = LUSTRE_EOF;
543                         comp->llc_id = 0;
544                         comp->llc_flags = 0;
545                 }
546
547                 if (v1->lmm_pattern == LOV_PATTERN_RAID0)
548                         comp->llc_pattern = LLAPI_LAYOUT_RAID0;
549                 else if (v1->lmm_pattern == (LOV_PATTERN_RAID0 |
550                                          LOV_PATTERN_OVERSTRIPING))
551                         comp->llc_pattern = LLAPI_LAYOUT_OVERSTRIPING;
552                 else if (v1->lmm_pattern == LOV_PATTERN_MDT)
553                         comp->llc_pattern = LLAPI_LAYOUT_MDT;
554                 else
555                         /* Lustre only supports RAID0, overstripping
556                          * and DoM for now.
557                          */
558                         comp->llc_pattern = v1->lmm_pattern;
559
560                 if (v1->lmm_stripe_size == 0)
561                         comp->llc_stripe_size = LLAPI_LAYOUT_DEFAULT;
562                 else
563                         comp->llc_stripe_size = v1->lmm_stripe_size;
564
565                 if (v1->lmm_stripe_count == (typeof(v1->lmm_stripe_count))-1)
566                         comp->llc_stripe_count = LLAPI_LAYOUT_WIDE;
567                 else if (v1->lmm_stripe_count == 0)
568                         comp->llc_stripe_count = LLAPI_LAYOUT_DEFAULT;
569                 else
570                         comp->llc_stripe_count = v1->lmm_stripe_count;
571
572                 if (v1->lmm_stripe_offset ==
573                     (typeof(v1->lmm_stripe_offset))-1)
574                         comp->llc_stripe_offset = LLAPI_LAYOUT_DEFAULT;
575                 else
576                         comp->llc_stripe_offset = v1->lmm_stripe_offset;
577
578                 if (v1->lmm_magic != LOV_USER_MAGIC_V1) {
579                         const struct lov_user_md_v3 *lumv3;
580                         lumv3 = (struct lov_user_md_v3 *)v1;
581                         snprintf(comp->llc_pool_name,
582                                  sizeof(comp->llc_pool_name),
583                                  "%s", lumv3->lmm_pool_name);
584                         memcpy(comp->llc_objects, lumv3->lmm_objects,
585                                obj_count * sizeof(lumv3->lmm_objects[0]));
586                 } else {
587                         const struct lov_user_md_v1 *lumv1;
588                         lumv1 = (struct lov_user_md_v1 *)v1;
589                         memcpy(comp->llc_objects, lumv1->lmm_objects,
590                                obj_count * sizeof(lumv1->lmm_objects[0]));
591                 }
592
593                 if (obj_count != 0)
594                         comp->llc_stripe_offset =
595                                 comp->llc_objects[0].l_ost_idx;
596
597                 comp->llc_ondisk = true;
598                 list_add_tail(&comp->llc_list, &layout->llot_comp_list);
599                 layout->llot_cur_comp = comp;
600         }
601
602 out:
603         if (lum != lov_xattr)
604                 free(lum);
605         return layout;
606 out_layout:
607         llapi_layout_free(layout);
608         layout = NULL;
609         goto out;
610 }
611
612 __u32 llapi_pattern_to_lov(uint64_t pattern)
613 {
614         __u32 lov_pattern;
615
616         switch (pattern) {
617         case LLAPI_LAYOUT_DEFAULT:
618                 lov_pattern = LOV_PATTERN_RAID0;
619                 break;
620         case LLAPI_LAYOUT_RAID0:
621                 lov_pattern = LOV_PATTERN_RAID0;
622                 break;
623         case LLAPI_LAYOUT_MDT:
624                 lov_pattern = LOV_PATTERN_MDT;
625                 break;
626         case LLAPI_LAYOUT_OVERSTRIPING:
627                 lov_pattern = LOV_PATTERN_OVERSTRIPING | LOV_PATTERN_RAID0;
628                 break;
629         default:
630                 lov_pattern = EINVAL;
631         }
632
633         return lov_pattern;
634 }
635
636 /**
637  * Convert the data from a llapi_layout to a newly allocated lov_user_md.
638  * The caller is responsible for freeing the returned pointer.
639  *
640  * \param[in] layout    the layout to copy from
641  *
642  * \retval      valid lov_user_md pointer on success
643  * \retval      NULL if memory allocation fails or the layout is invalid
644  */
645 static struct lov_user_md *
646 llapi_layout_to_lum(const struct llapi_layout *layout)
647 {
648         struct llapi_layout_comp *comp;
649         struct lov_comp_md_v1 *comp_v1 = NULL;
650         struct lov_comp_md_entry_v1 *ent;
651         struct lov_user_md *lum = NULL;
652         size_t lum_size = 0;
653         int ent_idx = 0;
654         uint32_t offset = 0;
655
656         if (layout == NULL ||
657             list_empty((struct list_head *)&layout->llot_comp_list)) {
658                 errno = EINVAL;
659                 return NULL;
660         }
661
662         /* Allocate header of lov_comp_md_v1 if necessary */
663         if (layout->llot_is_composite) {
664                 int comp_cnt = 0;
665
666                 list_for_each_entry(comp, &layout->llot_comp_list, llc_list)
667                         comp_cnt++;
668
669                 lum_size = sizeof(*comp_v1) + comp_cnt * sizeof(*ent);
670                 lum = calloc(lum_size, 1);
671                 if (lum == NULL) {
672                         errno = ENOMEM;
673                         return NULL;
674                 }
675                 comp_v1 = (struct lov_comp_md_v1 *)lum;
676                 comp_v1->lcm_magic = LOV_USER_MAGIC_COMP_V1;
677                 comp_v1->lcm_size = lum_size;
678                 comp_v1->lcm_layout_gen = 0;
679                 comp_v1->lcm_flags = layout->llot_flags;
680                 comp_v1->lcm_entry_count = comp_cnt;
681                 comp_v1->lcm_mirror_count = layout->llot_mirror_count - 1;
682                 offset += lum_size;
683         }
684
685         list_for_each_entry(comp, &layout->llot_comp_list, llc_list) {
686                 struct lov_user_md *blob;
687                 size_t blob_size;
688                 uint32_t magic;
689                 int i, obj_count = 0;
690                 struct lov_user_ost_data *lmm_objects;
691                 uint64_t pattern = comp->llc_pattern;
692
693                 if ((pattern & LLAPI_LAYOUT_SPECIFIC) != 0) {
694                         if (comp->llc_objects_count <
695                             comp->llc_stripe_count) {
696                                 errno = EINVAL;
697                                 goto error;
698                         }
699                         magic = LOV_USER_MAGIC_SPECIFIC;
700                         obj_count = comp->llc_stripe_count;
701                         pattern &= ~LLAPI_LAYOUT_SPECIFIC;
702                 } else if (strlen(comp->llc_pool_name) != 0) {
703                         magic = LOV_USER_MAGIC_V3;
704                 } else {
705                         magic = LOV_USER_MAGIC_V1;
706                 }
707                 /* All stripes must be specified when the pattern contains
708                  * LLAPI_LAYOUT_SPECIFIC */
709                 for (i = 0; i < obj_count; i++) {
710                         if (comp->llc_objects[i].l_ost_idx ==
711                             LLAPI_LAYOUT_IDX_MAX) {
712                                 errno = EINVAL;
713                                 goto error;
714                         }
715                 }
716
717                 blob_size = lov_user_md_size(obj_count, magic);
718                 blob = realloc(lum, lum_size + blob_size);
719                 if (blob == NULL) {
720                         errno = ENOMEM;
721                         goto error;
722                 } else {
723                         lum = blob;
724                         comp_v1 = (struct lov_comp_md_v1 *)lum;
725                         blob = (struct lov_user_md *)((char *)lum + lum_size);
726                         lum_size += blob_size;
727                 }
728
729                 blob->lmm_magic = magic;
730                 blob->lmm_pattern = llapi_pattern_to_lov(pattern);
731                 if (blob->lmm_pattern == EINVAL) {
732                         errno = EINVAL;
733                         goto error;
734                 }
735
736                 if (comp->llc_stripe_size == LLAPI_LAYOUT_DEFAULT)
737                         blob->lmm_stripe_size = 0;
738                 else
739                         blob->lmm_stripe_size = comp->llc_stripe_size;
740
741                 if (comp->llc_stripe_count == LLAPI_LAYOUT_DEFAULT)
742                         blob->lmm_stripe_count = 0;
743                 else if (comp->llc_stripe_count == LLAPI_LAYOUT_WIDE)
744                         blob->lmm_stripe_count = LOV_ALL_STRIPES;
745                 else
746                         blob->lmm_stripe_count = comp->llc_stripe_count;
747
748                 if (comp->llc_stripe_offset == LLAPI_LAYOUT_DEFAULT)
749                         blob->lmm_stripe_offset = -1;
750                 else
751                         blob->lmm_stripe_offset = comp->llc_stripe_offset;
752
753                 if (magic == LOV_USER_MAGIC_V3 ||
754                     magic == LOV_USER_MAGIC_SPECIFIC) {
755                         struct lov_user_md_v3 *lumv3 =
756                                 (struct lov_user_md_v3 *)blob;
757
758                         if (comp->llc_pool_name[0] != '\0') {
759                                 strncpy(lumv3->lmm_pool_name,
760                                         comp->llc_pool_name,
761                                         sizeof(lumv3->lmm_pool_name));
762                         } else {
763                                 memset(lumv3->lmm_pool_name, 0,
764                                        sizeof(lumv3->lmm_pool_name));
765                         }
766                         lmm_objects = lumv3->lmm_objects;
767                 } else {
768                         lmm_objects = blob->lmm_objects;
769                 }
770
771                 for (i = 0; i < obj_count; i++)
772                         lmm_objects[i].l_ost_idx =
773                                 comp->llc_objects[i].l_ost_idx;
774
775                 if (layout->llot_is_composite) {
776                         ent = &comp_v1->lcm_entries[ent_idx];
777                         ent->lcme_id = comp->llc_id;
778                         ent->lcme_flags = comp->llc_flags;
779                         if (ent->lcme_flags & LCME_FL_NOSYNC)
780                                 ent->lcme_timestamp = comp->llc_timestamp;
781                         ent->lcme_extent.e_start = comp->llc_extent.e_start;
782                         ent->lcme_extent.e_end = comp->llc_extent.e_end;
783                         ent->lcme_size = blob_size;
784                         ent->lcme_offset = offset;
785                         offset += blob_size;
786                         comp_v1->lcm_size += blob_size;
787                         ent_idx++;
788                 } else {
789                         break;
790                 }
791         }
792
793         return lum;
794 error:
795         free(lum);
796         return NULL;
797 }
798
799 /**
800  * Get the parent directory of a path.
801  *
802  * \param[in] path      path to get parent of
803  * \param[out] buf      buffer in which to store parent path
804  * \param[in] size      size in bytes of buffer \a buf
805  */
806 static void get_parent_dir(const char *path, char *buf, size_t size)
807 {
808         char *p;
809
810         strncpy(buf, path, size - 1);
811         p = strrchr(buf, '/');
812
813         if (p != NULL) {
814                 *p = '\0';
815         } else if (size >= 2) {
816                 strncpy(buf, ".", 2);
817                 buf[size - 1] = '\0';
818         }
819 }
820
821 /**
822  * Substitute unspecified attribute values in \a layout with values
823  * from fs global settings. (lov.stripesize, lov.stripecount,
824  * lov.stripeoffset)
825  *
826  * \param[in] layout    layout to inherit values from
827  * \param[in] path      file path of the filesystem
828  */
829 static void inherit_sys_attributes(struct llapi_layout *layout,
830                                    const char *path)
831 {
832         struct llapi_layout_comp *comp;
833         unsigned int ssize, scount, soffset;
834         int rc;
835
836         rc = sattr_cache_get_defaults(NULL, path, &scount, &ssize, &soffset);
837         if (rc)
838                 return;
839
840         list_for_each_entry(comp, &layout->llot_comp_list, llc_list) {
841                 if (comp->llc_pattern == LLAPI_LAYOUT_DEFAULT)
842                         comp->llc_pattern = LLAPI_LAYOUT_RAID0;
843                 if (comp->llc_stripe_size == LLAPI_LAYOUT_DEFAULT)
844                         comp->llc_stripe_size = ssize;
845                 if (comp->llc_stripe_count == LLAPI_LAYOUT_DEFAULT)
846                         comp->llc_stripe_count = scount;
847                 if (comp->llc_stripe_offset == LLAPI_LAYOUT_DEFAULT)
848                         comp->llc_stripe_offset = soffset;
849         }
850 }
851
852 /**
853  * Get the current component of \a layout.
854  *
855  * \param[in] layout    layout to get current component
856  *
857  * \retval      valid llapi_layout_comp pointer on success
858  * \retval      NULL on error
859  */
860 static struct llapi_layout_comp *
861 __llapi_layout_cur_comp(const struct llapi_layout *layout)
862 {
863         struct llapi_layout_comp *comp;
864
865         if (layout == NULL || layout->llot_magic != LLAPI_LAYOUT_MAGIC) {
866                 errno = EINVAL;
867                 return NULL;
868         }
869         if (layout->llot_cur_comp == NULL) {
870                 errno = EINVAL;
871                 return NULL;
872         }
873         /* Verify data consistency */
874         list_for_each_entry(comp, &layout->llot_comp_list, llc_list)
875                 if (comp == layout->llot_cur_comp)
876                         return comp;
877         errno = EFAULT;
878         return NULL;
879 }
880
881 /**
882  * Test if any attributes of \a layout are specified.
883  *
884  * \param[in] layout    the layout to check
885  *
886  * \retval true         any attributes are specified
887  * \retval false        all attributes are unspecified
888  */
889 static bool is_any_specified(const struct llapi_layout *layout)
890 {
891         struct llapi_layout_comp *comp;
892
893         comp = __llapi_layout_cur_comp(layout);
894         if (comp == NULL)
895                 return false;
896
897         if (layout->llot_is_composite || layout->llot_mirror_count != 1)
898                 return true;
899
900         return comp->llc_pattern != LLAPI_LAYOUT_DEFAULT ||
901                comp->llc_stripe_size != LLAPI_LAYOUT_DEFAULT ||
902                comp->llc_stripe_count != LLAPI_LAYOUT_DEFAULT ||
903                comp->llc_stripe_offset != LLAPI_LAYOUT_DEFAULT ||
904                strlen(comp->llc_pool_name);
905 }
906
907 /**
908  * Get the striping layout for the file referenced by file descriptor \a fd.
909  *
910  * If the filesystem does not support the "lustre." xattr namespace, the
911  * file must be on a non-Lustre filesystem, so set errno to ENOTTY per
912  * convention.  If the file has no "lustre.lov" data, the file will
913  * inherit default values, so return a default layout.
914  *
915  * If the kernel gives us back less than the expected amount of data,
916  * we fail with errno set to EINTR.
917  *
918  * \param[in] fd        open file descriptor
919  * \param[in] flags     open file descriptor
920  *
921  * \retval      valid llapi_layout pointer on success
922  * \retval      NULL if an error occurs
923  */
924 struct llapi_layout *llapi_layout_get_by_fd(int fd, uint32_t flags)
925 {
926         size_t lum_len;
927         struct lov_user_md *lum;
928         struct llapi_layout *layout = NULL;
929         ssize_t bytes_read;
930         struct stat st;
931
932         lum_len = XATTR_SIZE_MAX;
933         lum = malloc(lum_len);
934         if (lum == NULL)
935                 return NULL;
936
937         bytes_read = fgetxattr(fd, XATTR_LUSTRE_LOV, lum, lum_len);
938         if (bytes_read < 0) {
939                 if (errno == EOPNOTSUPP)
940                         errno = ENOTTY;
941                 else if (errno == ENODATA)
942                         layout = llapi_layout_alloc();
943                 goto out;
944         }
945
946         /* Directories may have a positive non-zero lum->lmm_stripe_count
947          * yet have an empty lum->lmm_objects array. For non-directories the
948          * amount of data returned from the kernel must be consistent
949          * with the stripe count. */
950         if (fstat(fd, &st) < 0)
951                 goto out;
952
953         layout = llapi_layout_get_by_xattr(lum, bytes_read,
954                 S_ISDIR(st.st_mode) ? 0 : LLAPI_LXF_CHECK);
955 out:
956         free(lum);
957         return layout;
958 }
959
960 /**
961  * Get the expected striping layout for a file at \a path.
962  *
963  * Substitute expected inherited attribute values for unspecified
964  * attributes.  Unspecified attributes may belong to directories and
965  * never-written-to files, and indicate that default values will be
966  * assigned when files are created or first written to.  A default value
967  * is inherited from the parent directory if the attribute is specified
968  * there, otherwise it is inherited from the filesystem root.
969  * Unspecified attributes normally have the value LLAPI_LAYOUT_DEFAULT.
970  *
971  * The complete \a path need not refer to an existing file or directory,
972  * but some leading portion of it must reside within a lustre filesystem.
973  * A use case for this interface would be to obtain the literal striping
974  * values that would be assigned to a new file in a given directory.
975  *
976  * \param[in] path      path for which to get the expected layout
977  *
978  * \retval      valid llapi_layout pointer on success
979  * \retval      NULL if an error occurs
980  */
981 static struct llapi_layout *llapi_layout_expected(const char *path)
982 {
983         struct llapi_layout     *path_layout = NULL;
984         char                    donor_path[PATH_MAX];
985         struct stat st;
986         int fd;
987         int rc;
988
989         fd = open(path, O_RDONLY);
990         if (fd < 0 && errno != ENOENT)
991                 return NULL;
992
993         if (fd >= 0) {
994                 int tmp;
995
996                 path_layout = llapi_layout_get_by_fd(fd, 0);
997                 tmp = errno;
998                 close(fd);
999                 errno = tmp;
1000         }
1001
1002         if (path_layout == NULL) {
1003                 if (errno != ENODATA && errno != ENOENT)
1004                         return NULL;
1005
1006                 path_layout = llapi_layout_alloc();
1007                 if (path_layout == NULL)
1008                         return NULL;
1009         }
1010
1011         if (is_any_specified(path_layout)) {
1012                 inherit_sys_attributes(path_layout, path);
1013                 return path_layout;
1014         }
1015
1016         llapi_layout_free(path_layout);
1017
1018         rc = stat(path, &st);
1019         if (rc < 0 && errno != ENOENT)
1020                 return NULL;
1021
1022         /* If path is a not a directory or doesn't exist, inherit layout
1023          * from parent directory. */
1024         if ((rc == 0 && !S_ISDIR(st.st_mode)) ||
1025             (rc < 0 && errno == ENOENT)) {
1026                 get_parent_dir(path, donor_path, sizeof(donor_path));
1027                 path_layout = llapi_layout_get_by_path(donor_path, 0);
1028                 if (path_layout != NULL) {
1029                         if (is_any_specified(path_layout)) {
1030                                 inherit_sys_attributes(path_layout, donor_path);
1031                                 return path_layout;
1032                         }
1033                         llapi_layout_free(path_layout);
1034                 }
1035         }
1036
1037         /* Inherit layout from the filesystem root. */
1038         rc = llapi_search_mounts(path, 0, donor_path, NULL);
1039         if (rc < 0)
1040                 return NULL;
1041         path_layout = llapi_layout_get_by_path(donor_path, 0);
1042         if (path_layout == NULL)
1043                 return NULL;
1044
1045         inherit_sys_attributes(path_layout, donor_path);
1046         return path_layout;
1047 }
1048
1049 /**
1050  * Get the striping layout for the file at \a path.
1051  *
1052  * If \a flags contains LAYOUT_GET_EXPECTED, substitute
1053  * expected inherited attribute values for unspecified attributes. See
1054  * llapi_layout_expected().
1055  *
1056  * \param[in] path      path for which to get the layout
1057  * \param[in] flags     flags to control how layout is retrieved
1058  *
1059  * \retval      valid llapi_layout pointer on success
1060  * \retval      NULL if an error occurs
1061  */
1062 struct llapi_layout *llapi_layout_get_by_path(const char *path, uint32_t flags)
1063 {
1064         struct llapi_layout *layout = NULL;
1065         int fd;
1066         int tmp;
1067
1068         if (flags & LAYOUT_GET_EXPECTED)
1069                 return llapi_layout_expected(path);
1070
1071         fd = open(path, O_RDONLY);
1072         if (fd < 0)
1073                 return layout;
1074
1075         layout = llapi_layout_get_by_fd(fd, flags);
1076         tmp = errno;
1077         close(fd);
1078         errno = tmp;
1079
1080         return layout;
1081 }
1082
1083 /**
1084  * Get the layout for the file with FID \a fidstr in filesystem \a lustre_dir.
1085  *
1086  * \param[in] lustre_dir        path within Lustre filesystem containing \a fid
1087  * \param[in] fid               Lustre identifier of file to get layout for
1088  *
1089  * \retval      valid llapi_layout pointer on success
1090  * \retval      NULL if an error occurs
1091  */
1092 struct llapi_layout *llapi_layout_get_by_fid(const char *lustre_dir,
1093                                              const struct lu_fid *fid,
1094                                              uint32_t flags)
1095 {
1096         int fd;
1097         int tmp;
1098         int saved_msg_level = llapi_msg_get_level();
1099         struct llapi_layout *layout = NULL;
1100
1101         /* Prevent llapi internal routines from writing to console
1102          * while executing this function, then restore previous message
1103          * level. */
1104         llapi_msg_set_level(LLAPI_MSG_OFF);
1105         fd = llapi_open_by_fid(lustre_dir, fid, O_RDONLY);
1106         llapi_msg_set_level(saved_msg_level);
1107
1108         if (fd < 0)
1109                 return NULL;
1110
1111         layout = llapi_layout_get_by_fd(fd, flags);
1112         tmp = errno;
1113         close(fd);
1114         errno = tmp;
1115
1116         return layout;
1117 }
1118
1119 /**
1120  * Get the stripe count of \a layout.
1121  *
1122  * \param[in] layout    layout to get stripe count from
1123  * \param[out] count    integer to store stripe count in
1124  *
1125  * \retval      0 on success
1126  * \retval      -1 if arguments are invalid
1127  */
1128 int llapi_layout_stripe_count_get(const struct llapi_layout *layout,
1129                                   uint64_t *count)
1130 {
1131         struct llapi_layout_comp *comp;
1132
1133         comp = __llapi_layout_cur_comp(layout);
1134         if (comp == NULL)
1135                 return -1;
1136
1137         if (count == NULL) {
1138                 errno = EINVAL;
1139                 return -1;
1140         }
1141
1142         *count = comp->llc_stripe_count;
1143
1144         return 0;
1145 }
1146
1147 /*
1148  * The llapi_layout API functions have these extra validity checks since
1149  * they use intuitively named macros to denote special behavior, whereas
1150  * the old API uses 0 and -1.
1151  */
1152
1153 static bool llapi_layout_stripe_count_is_valid(int64_t stripe_count)
1154 {
1155         return stripe_count == LLAPI_LAYOUT_DEFAULT ||
1156                 stripe_count == LLAPI_LAYOUT_WIDE ||
1157                 (stripe_count != 0 && stripe_count != -1 &&
1158                  llapi_stripe_count_is_valid(stripe_count));
1159 }
1160
1161 static bool llapi_layout_extension_size_is_valid(uint64_t ext_size)
1162 {
1163         return (ext_size != 0 &&
1164                 llapi_stripe_size_is_aligned(ext_size) &&
1165                 !llapi_stripe_size_is_too_big(ext_size));
1166 }
1167
1168 static bool llapi_layout_stripe_size_is_valid(uint64_t stripe_size)
1169 {
1170         return stripe_size == LLAPI_LAYOUT_DEFAULT ||
1171                 (stripe_size != 0 &&
1172                  llapi_stripe_size_is_aligned(stripe_size) &&
1173                  !llapi_stripe_size_is_too_big(stripe_size));
1174 }
1175
1176 static bool llapi_layout_stripe_index_is_valid(int64_t stripe_index)
1177 {
1178         return stripe_index == LLAPI_LAYOUT_DEFAULT ||
1179                 (stripe_index >= 0 &&
1180                 llapi_stripe_index_is_valid(stripe_index));
1181 }
1182
1183 /**
1184  * Set the stripe count of \a layout.
1185  *
1186  * \param[in] layout    layout to set stripe count in
1187  * \param[in] count     value to be set
1188  *
1189  * \retval      0 on success
1190  * \retval      -1 if arguments are invalid
1191  */
1192 int llapi_layout_stripe_count_set(struct llapi_layout *layout,
1193                                   uint64_t count)
1194 {
1195         struct llapi_layout_comp *comp;
1196
1197         comp = __llapi_layout_cur_comp(layout);
1198         if (comp == NULL)
1199                 return -1;
1200
1201         if (!llapi_layout_stripe_count_is_valid(count)) {
1202                 errno = EINVAL;
1203                 return -1;
1204         }
1205
1206         comp->llc_stripe_count = count;
1207
1208         return 0;
1209 }
1210
1211 /**
1212  * Get the stripe/extension size of \a layout.
1213  *
1214  * \param[in] layout    layout to get stripe size from
1215  * \param[out] size     integer to store stripe size in
1216  * \param[in] extension flag if extenion size is requested
1217  *
1218  * \retval      0 on success
1219  * \retval      -1 if arguments are invalid
1220  */
1221 static int layout_stripe_size_get(const struct llapi_layout *layout,
1222                                   uint64_t *size, bool extension)
1223 {
1224         struct llapi_layout_comp *comp;
1225         int comp_ext;
1226
1227         comp = __llapi_layout_cur_comp(layout);
1228         if (comp == NULL)
1229                 return -1;
1230
1231         if (size == NULL) {
1232                 errno = EINVAL;
1233                 return -1;
1234         }
1235
1236         comp_ext = comp->llc_flags & LCME_FL_EXTENSION;
1237         if ((comp_ext && !extension) || (!comp_ext && extension)) {
1238                 errno = EINVAL;
1239                 return -1;
1240         }
1241
1242         *size = comp->llc_stripe_size;
1243         if (comp->llc_flags & LCME_FL_EXTENSION)
1244                 *size *= SEL_UNIT_SIZE;
1245
1246         return 0;
1247 }
1248
1249 int llapi_layout_stripe_size_get(const struct llapi_layout *layout,
1250                                  uint64_t *size)
1251 {
1252         return layout_stripe_size_get(layout, size, false);
1253 }
1254
1255 int llapi_layout_extension_size_get(const struct llapi_layout *layout,
1256                                     uint64_t *size)
1257 {
1258         return layout_stripe_size_get(layout, size, true);
1259 }
1260
1261 /**
1262  * Set the stripe/extension size of \a layout.
1263  *
1264  * \param[in] layout    layout to set stripe size in
1265  * \param[in] size      value to be set
1266  * \param[in] extension flag if extenion size is passed
1267  *
1268  * \retval      0 on success
1269  * \retval      -1 if arguments are invalid
1270  */
1271 static int layout_stripe_size_set(struct llapi_layout *layout,
1272                                   uint64_t size, bool extension)
1273 {
1274         struct llapi_layout_comp *comp;
1275         int comp_ext;
1276
1277         comp = __llapi_layout_cur_comp(layout);
1278         if (comp == NULL)
1279                 return -1;
1280
1281         comp_ext = comp->llc_flags & LCME_FL_EXTENSION;
1282         if ((comp_ext && !extension) || (!comp_ext && extension)) {
1283                 errno = EINVAL;
1284                 return -1;
1285         }
1286
1287         if (comp_ext)
1288                 size /= SEL_UNIT_SIZE;
1289
1290         if ((comp_ext && !llapi_layout_extension_size_is_valid(size)) ||
1291             (!comp_ext && !llapi_layout_stripe_size_is_valid(size))) {
1292                 errno = EINVAL;
1293                 return -1;
1294         }
1295
1296         comp->llc_stripe_size = size;
1297         return 0;
1298 }
1299
1300 int llapi_layout_stripe_size_set(struct llapi_layout *layout,
1301                                  uint64_t size)
1302 {
1303         return layout_stripe_size_set(layout, size, false);
1304 }
1305
1306 int llapi_layout_extension_size_set(struct llapi_layout *layout,
1307                                     uint64_t size)
1308 {
1309         return layout_stripe_size_set(layout, size, true);
1310 }
1311
1312 /**
1313  * Get the RAID pattern of \a layout.
1314  *
1315  * \param[in] layout    layout to get pattern from
1316  * \param[out] pattern  integer to store pattern in
1317  *
1318  * \retval      0 on success
1319  * \retval      -1 if arguments are invalid
1320  */
1321 int llapi_layout_pattern_get(const struct llapi_layout *layout,
1322                              uint64_t *pattern)
1323 {
1324         struct llapi_layout_comp *comp;
1325
1326         comp = __llapi_layout_cur_comp(layout);
1327         if (comp == NULL)
1328                 return -1;
1329
1330         if (pattern == NULL) {
1331                 errno = EINVAL;
1332                 return -1;
1333         }
1334
1335         *pattern = comp->llc_pattern;
1336
1337         return 0;
1338 }
1339
1340 /**
1341  * Set the pattern of \a layout.
1342  *
1343  * \param[in] layout    layout to set pattern in
1344  * \param[in] pattern   value to be set
1345  *
1346  * \retval      0 on success
1347  * \retval      -1 if arguments are invalid or RAID pattern
1348  *              is unsupported
1349  */
1350 int llapi_layout_pattern_set(struct llapi_layout *layout, uint64_t pattern)
1351 {
1352         struct llapi_layout_comp *comp;
1353
1354         comp = __llapi_layout_cur_comp(layout);
1355         if (comp == NULL)
1356                 return -1;
1357
1358         if (pattern != LLAPI_LAYOUT_DEFAULT &&
1359             pattern != LLAPI_LAYOUT_RAID0 && pattern != LLAPI_LAYOUT_MDT
1360             && pattern != LLAPI_LAYOUT_OVERSTRIPING) {
1361                 errno = EOPNOTSUPP;
1362                 return -1;
1363         }
1364
1365         comp->llc_pattern = pattern |
1366                             (comp->llc_pattern & LLAPI_LAYOUT_SPECIFIC);
1367
1368         return 0;
1369 }
1370
1371 static inline int stripe_number_roundup(int stripe_number)
1372 {
1373         unsigned int round_up = (stripe_number + 8) & ~7;
1374         return round_up > LOV_MAX_STRIPE_COUNT ?
1375                 LOV_MAX_STRIPE_COUNT : round_up;
1376 }
1377
1378 /**
1379  * Set the OST index of stripe number \a stripe_number to \a ost_index.
1380  *
1381  * If only the starting stripe's OST index is specified, then this can use
1382  * the normal LOV_MAGIC_{V1,V3} layout type.  If multiple OST indices are
1383  * given, then allocate an array to hold the list of indices and ensure that
1384  * the LOV_USER_MAGIC_SPECIFIC layout is used when creating the file.
1385  *
1386  * \param[in] layout            layout to set OST index in
1387  * \param[in] stripe_number     stripe number to set index for
1388  * \param[in] ost_index         the index to set
1389  *
1390  * \retval      0 on success
1391  * \retval      -1 if arguments are invalid or an unsupported stripe number
1392  *              was specified, error returned in errno
1393  */
1394 int llapi_layout_ost_index_set(struct llapi_layout *layout, int stripe_number,
1395                                uint64_t ost_index)
1396 {
1397         struct llapi_layout_comp *comp;
1398
1399         comp = __llapi_layout_cur_comp(layout);
1400         if (comp == NULL)
1401                 return -1;
1402
1403         if (!llapi_layout_stripe_index_is_valid(ost_index)) {
1404                 errno = EINVAL;
1405                 return -1;
1406         }
1407
1408         if (stripe_number == 0 && ost_index == LLAPI_LAYOUT_DEFAULT) {
1409                 comp->llc_stripe_offset = ost_index;
1410                 comp->llc_pattern &= ~LLAPI_LAYOUT_SPECIFIC;
1411                 __llapi_comp_objects_realloc(comp, 0);
1412         } else if (stripe_number >= 0 &&
1413                    stripe_number < LOV_MAX_STRIPE_COUNT) {
1414                 if (ost_index >= LLAPI_LAYOUT_IDX_MAX) {
1415                         errno = EINVAL;
1416                         return -1;
1417                 }
1418
1419                 /* Preallocate a few more stripes to avoid realloc() overhead.*/
1420                 if (__llapi_comp_objects_realloc(comp,
1421                                 stripe_number_roundup(stripe_number)) < 0)
1422                         return -1;
1423
1424                 comp->llc_objects[stripe_number].l_ost_idx = ost_index;
1425
1426                 if (stripe_number == 0)
1427                         comp->llc_stripe_offset = ost_index;
1428                 else
1429                         comp->llc_pattern |= LLAPI_LAYOUT_SPECIFIC;
1430
1431                 if (comp->llc_stripe_count == LLAPI_LAYOUT_DEFAULT ||
1432                     comp->llc_stripe_count <= stripe_number)
1433                         comp->llc_stripe_count = stripe_number + 1;
1434         } else {
1435                 errno = EINVAL;
1436                 return -1;
1437         }
1438
1439         return 0;
1440 }
1441
1442 /**
1443  * Get the OST index associated with stripe \a stripe_number.
1444  *
1445  * Stripes are indexed starting from zero.
1446  *
1447  * \param[in] layout            layout to get index from
1448  * \param[in] stripe_number     stripe number to get index for
1449  * \param[out] index            integer to store index in
1450  *
1451  * \retval      0 on success
1452  * \retval      -1 if arguments are invalid
1453  */
1454 int llapi_layout_ost_index_get(const struct llapi_layout *layout,
1455                                uint64_t stripe_number, uint64_t *index)
1456 {
1457         struct llapi_layout_comp *comp;
1458
1459         comp = __llapi_layout_cur_comp(layout);
1460         if (comp == NULL)
1461                 return -1;
1462
1463         if (index == NULL) {
1464                 errno = EINVAL;
1465                 return -1;
1466         }
1467
1468         if (stripe_number >= comp->llc_stripe_count ||
1469             stripe_number >= comp->llc_objects_count) {
1470                 errno = EINVAL;
1471                 return -1;
1472         }
1473
1474         if (comp->llc_stripe_offset == LLAPI_LAYOUT_DEFAULT)
1475                 *index = LLAPI_LAYOUT_DEFAULT;
1476         else
1477                 *index = comp->llc_objects[stripe_number].l_ost_idx;
1478
1479         return 0;
1480 }
1481
1482 /**
1483  *
1484  * Get the pool name of layout \a layout.
1485  *
1486  * \param[in] layout    layout to get pool name from
1487  * \param[out] dest     buffer to store pool name in
1488  * \param[in] n         size in bytes of buffer \a dest
1489  *
1490  * \retval      0 on success
1491  * \retval      -1 if arguments are invalid
1492  */
1493 int llapi_layout_pool_name_get(const struct llapi_layout *layout, char *dest,
1494                                size_t n)
1495 {
1496         struct llapi_layout_comp *comp;
1497
1498         comp = __llapi_layout_cur_comp(layout);
1499         if (comp == NULL)
1500                 return -1;
1501
1502         if (dest == NULL) {
1503                 errno = EINVAL;
1504                 return -1;
1505         }
1506
1507         strncpy(dest, comp->llc_pool_name, n);
1508
1509         return 0;
1510 }
1511
1512 /**
1513  * Set the name of the pool of layout \a layout.
1514  *
1515  * \param[in] layout    layout to set pool name in
1516  * \param[in] pool_name pool name to set
1517  *
1518  * \retval      0 on success
1519  * \retval      -1 if arguments are invalid or pool name is too long
1520  */
1521 int llapi_layout_pool_name_set(struct llapi_layout *layout,
1522                                const char *pool_name)
1523 {
1524         struct llapi_layout_comp *comp;
1525         char *ptr;
1526
1527         comp = __llapi_layout_cur_comp(layout);
1528         if (comp == NULL)
1529                 return -1;
1530
1531         if (pool_name == NULL) {
1532                 errno = EINVAL;
1533                 return -1;
1534         }
1535
1536         /* Strip off any 'fsname.' portion. */
1537         ptr = strchr(pool_name, '.');
1538         if (ptr != NULL)
1539                 pool_name = ptr + 1;
1540
1541         if (strlen(pool_name) > LOV_MAXPOOLNAME) {
1542                 errno = EINVAL;
1543                 return -1;
1544         }
1545
1546         strncpy(comp->llc_pool_name, pool_name, sizeof(comp->llc_pool_name));
1547
1548         return 0;
1549 }
1550
1551 /**
1552  * Open and possibly create a file with a given \a layout.
1553  *
1554  * If \a layout is NULL this function acts as a simple wrapper for
1555  * open().  By convention, ENOTTY is returned in errno if \a path
1556  * refers to a non-Lustre file.
1557  *
1558  * \param[in] path              name of the file to open
1559  * \param[in] open_flags        open() flags
1560  * \param[in] mode              permissions to create file, filtered by umask
1561  * \param[in] layout            layout to create new file with
1562  *
1563  * \retval              non-negative file descriptor on successful open
1564  * \retval              -1 if an error occurred
1565  */
1566 int llapi_layout_file_open(const char *path, int open_flags, mode_t mode,
1567                            const struct llapi_layout *layout)
1568 {
1569         int fd;
1570         int rc;
1571         int tmp;
1572         struct lov_user_md *lum;
1573         size_t lum_size;
1574
1575         if (path == NULL ||
1576             (layout != NULL && layout->llot_magic != LLAPI_LAYOUT_MAGIC)) {
1577                 errno = EINVAL;
1578                 return -1;
1579         }
1580
1581         if (layout) {
1582                 rc = llapi_layout_sanity((struct llapi_layout *)layout, false,
1583                                          !!(layout->llot_mirror_count > 1));
1584                 if (rc) {
1585                         llapi_layout_sanity_perror(rc);
1586                         return -1;
1587                 }
1588         }
1589
1590         /* Object creation must be postponed until after layout attributes
1591          * have been applied. */
1592         if (layout != NULL && (open_flags & O_CREAT))
1593                 open_flags |= O_LOV_DELAY_CREATE;
1594
1595         fd = open(path, open_flags, mode);
1596
1597         if (layout == NULL || fd < 0)
1598                 return fd;
1599
1600         lum = llapi_layout_to_lum(layout);
1601
1602         if (lum == NULL) {
1603                 tmp = errno;
1604                 close(fd);
1605                 errno = tmp;
1606                 return -1;
1607         }
1608
1609         if (lum->lmm_magic == LOV_USER_MAGIC_COMP_V1)
1610                 lum_size = ((struct lov_comp_md_v1 *)lum)->lcm_size;
1611         else if (lum->lmm_magic == LOV_USER_MAGIC_SPECIFIC)
1612                 lum_size = lov_user_md_size(lum->lmm_stripe_count,
1613                                             lum->lmm_magic);
1614         else
1615                 lum_size = lov_user_md_size(0, lum->lmm_magic);
1616
1617         rc = fsetxattr(fd, XATTR_LUSTRE_LOV, lum, lum_size, 0);
1618         if (rc < 0) {
1619                 tmp = errno;
1620                 close(fd);
1621                 errno = tmp;
1622                 fd = -1;
1623         }
1624
1625         free(lum);
1626         errno = errno == EOPNOTSUPP ? ENOTTY : errno;
1627
1628         return fd;
1629 }
1630
1631 /**
1632  * Create a file with a given \a layout.
1633  *
1634  * Force O_CREAT and O_EXCL flags on so caller is assured that file was
1635  * created with the given \a layout on successful function return.
1636  *
1637  * \param[in] path              name of the file to open
1638  * \param[in] open_flags        open() flags
1639  * \param[in] mode              permissions to create new file with
1640  * \param[in] layout            layout to create new file with
1641  *
1642  * \retval              non-negative file descriptor on successful open
1643  * \retval              -1 if an error occurred
1644  */
1645 int llapi_layout_file_create(const char *path, int open_flags, int mode,
1646                              const struct llapi_layout *layout)
1647 {
1648         return llapi_layout_file_open(path, open_flags|O_CREAT|O_EXCL, mode,
1649                                       layout);
1650 }
1651
1652 int llapi_layout_flags_get(struct llapi_layout *layout, uint32_t *flags)
1653 {
1654         if (layout->llot_magic != LLAPI_LAYOUT_MAGIC) {
1655                 errno = EINVAL;
1656                 return -1;
1657         }
1658
1659         *flags = layout->llot_flags;
1660         return 0;
1661 }
1662
1663 /**
1664  * Set flags to the header of a component layout.
1665  */
1666 int llapi_layout_flags_set(struct llapi_layout *layout, uint32_t flags)
1667 {
1668         if (layout->llot_magic != LLAPI_LAYOUT_MAGIC) {
1669                 errno = EINVAL;
1670                 return -1;
1671         }
1672
1673         layout->llot_flags = flags;
1674         return 0;
1675 }
1676
1677 const char *llapi_layout_flags_string(uint32_t flags)
1678 {
1679         switch (flags & LCM_FL_FLR_MASK) {
1680         case LCM_FL_RDONLY:
1681                 return "ro";
1682         case LCM_FL_WRITE_PENDING:
1683                 return "wp";
1684         case LCM_FL_SYNC_PENDING:
1685                 return "sp";
1686         }
1687
1688         return "0";
1689 }
1690
1691 const __u16 llapi_layout_string_flags(char *string)
1692 {
1693         if (strncmp(string, "ro", strlen(string)) == 0)
1694                 return LCM_FL_RDONLY;
1695         if (strncmp(string, "wp", strlen(string)) == 0)
1696                 return LCM_FL_WRITE_PENDING;
1697         if (strncmp(string, "sp", strlen(string)) == 0)
1698                 return LCM_FL_SYNC_PENDING;
1699
1700         return 0;
1701 }
1702
1703 /**
1704  * llapi_layout_mirror_count_is_valid() - Check the validity of mirror count.
1705  * @count: Mirror count value to be checked.
1706  *
1707  * This function checks the validity of mirror count.
1708  *
1709  * Return: true on success or false on failure.
1710  */
1711 static bool llapi_layout_mirror_count_is_valid(uint16_t count)
1712 {
1713         return count >= 0 && count <= LUSTRE_MIRROR_COUNT_MAX;
1714 }
1715
1716 /**
1717  * llapi_layout_mirror_count_get() - Get mirror count from the header of
1718  *                                   a layout.
1719  * @layout: Layout to get mirror count from.
1720  * @count:  Returned mirror count value.
1721  *
1722  * This function gets mirror count from the header of a layout.
1723  *
1724  * Return: 0 on success or -1 on failure.
1725  */
1726 int llapi_layout_mirror_count_get(struct llapi_layout *layout,
1727                                   uint16_t *count)
1728 {
1729         if (layout->llot_magic != LLAPI_LAYOUT_MAGIC) {
1730                 errno = EINVAL;
1731                 return -1;
1732         }
1733
1734         *count = layout->llot_mirror_count;
1735         return 0;
1736 }
1737
1738 /**
1739  * llapi_layout_mirror_count_set() - Set mirror count to the header of a layout.
1740  * @layout: Layout to set mirror count in.
1741  * @count:  Mirror count value to be set.
1742  *
1743  * This function sets mirror count to the header of a layout.
1744  *
1745  * Return: 0 on success or -1 on failure.
1746  */
1747 int llapi_layout_mirror_count_set(struct llapi_layout *layout,
1748                                   uint16_t count)
1749 {
1750         if (layout->llot_magic != LLAPI_LAYOUT_MAGIC) {
1751                 errno = EINVAL;
1752                 return -1;
1753         }
1754
1755         if (!llapi_layout_mirror_count_is_valid(count)) {
1756                 errno = EINVAL;
1757                 return -1;
1758         }
1759
1760         layout->llot_mirror_count = count;
1761         return 0;
1762 }
1763
1764 /**
1765  * Fetch the start and end offset of the current layout component.
1766  *
1767  * \param[in] layout    the layout component
1768  * \param[out] start    extent start, inclusive
1769  * \param[out] end      extent end, exclusive
1770  *
1771  * \retval      0 on success
1772  * \retval      <0 if error occurs
1773  */
1774 int llapi_layout_comp_extent_get(const struct llapi_layout *layout,
1775                                  uint64_t *start, uint64_t *end)
1776 {
1777         struct llapi_layout_comp *comp;
1778
1779         comp = __llapi_layout_cur_comp(layout);
1780         if (comp == NULL)
1781                 return -1;
1782
1783         if (start == NULL || end == NULL) {
1784                 errno = EINVAL;
1785                 return -1;
1786         }
1787
1788         *start = comp->llc_extent.e_start;
1789         *end = comp->llc_extent.e_end;
1790
1791         return 0;
1792 }
1793
1794 /**
1795  * Set the layout extent of a layout.
1796  *
1797  * \param[in] layout    the layout to be set
1798  * \param[in] start     extent start, inclusive
1799  * \param[in] end       extent end, exclusive
1800  *
1801  * \retval      0 on success
1802  * \retval      <0 if error occurs
1803  */
1804 int llapi_layout_comp_extent_set(struct llapi_layout *layout,
1805                                  uint64_t start, uint64_t end)
1806 {
1807         struct llapi_layout_comp *comp;
1808
1809         comp = __llapi_layout_cur_comp(layout);
1810         if (comp == NULL)
1811                 return -1;
1812
1813         if (start > end) {
1814                 errno = EINVAL;
1815                 return -1;
1816         }
1817
1818         comp->llc_extent.e_start = start;
1819         comp->llc_extent.e_end = end;
1820         layout->llot_is_composite = true;
1821
1822         return 0;
1823 }
1824
1825 /**
1826  * Gets the attribute flags of the current component.
1827  *
1828  * \param[in] layout    the layout component
1829  * \param[out] flags    stored the returned component flags
1830  *
1831  * \retval      0 on success
1832  * \retval      <0 if error occurs
1833  */
1834 int llapi_layout_comp_flags_get(const struct llapi_layout *layout,
1835                                 uint32_t *flags)
1836 {
1837         struct llapi_layout_comp *comp;
1838
1839         comp = __llapi_layout_cur_comp(layout);
1840         if (comp == NULL)
1841                 return -1;
1842
1843         if (flags == NULL) {
1844                 errno = EINVAL;
1845                 return -1;
1846         }
1847
1848         *flags = comp->llc_flags;
1849
1850         return 0;
1851 }
1852
1853 /**
1854  * Sets the specified flags of the current component leaving other flags as-is.
1855  *
1856  * \param[in] layout    the layout component
1857  * \param[in] flags     component flags to be set
1858  *
1859  * \retval      0 on success
1860  * \retval      <0 if error occurs
1861  */
1862 int llapi_layout_comp_flags_set(struct llapi_layout *layout, uint32_t flags)
1863 {
1864         struct llapi_layout_comp *comp;
1865
1866         comp = __llapi_layout_cur_comp(layout);
1867         if (comp == NULL)
1868                 return -1;
1869
1870         comp->llc_flags |= flags;
1871
1872         return 0;
1873 }
1874
1875 /**
1876  * Clears the flags specified in the flags leaving other flags as-is.
1877  *
1878  * \param[in] layout    the layout component
1879  * \param[in] flags     component flags to be cleared
1880  *
1881  * \retval      0 on success
1882  * \retval      <0 if error occurs
1883  */
1884 int llapi_layout_comp_flags_clear(struct llapi_layout *layout,
1885                                   uint32_t flags)
1886 {
1887         struct llapi_layout_comp *comp;
1888
1889         comp = __llapi_layout_cur_comp(layout);
1890         if (comp == NULL)
1891                 return -1;
1892
1893         comp->llc_flags &= ~flags;
1894
1895         return 0;
1896 }
1897
1898 /**
1899  * Fetches the file-unique component ID of the current layout component.
1900  *
1901  * \param[in] layout    the layout component
1902  * \param[out] id       stored the returned component ID
1903  *
1904  * \retval      0 on success
1905  * \retval      <0 if error occurs
1906  */
1907 int llapi_layout_comp_id_get(const struct llapi_layout *layout, uint32_t *id)
1908 {
1909         struct llapi_layout_comp *comp;
1910
1911         comp = __llapi_layout_cur_comp(layout);
1912         if (comp == NULL)
1913                 return -1;
1914
1915         if (id == NULL) {
1916                 errno = EINVAL;
1917                 return -1;
1918         }
1919         *id = comp->llc_id;
1920
1921         return 0;
1922 }
1923
1924 /**
1925  * Return the mirror id of the current layout component.
1926  *
1927  * \param[in] layout    the layout component
1928  * \param[out] id       stored the returned mirror ID
1929  *
1930  * \retval      0 on success
1931  * \retval      <0 if error occurs
1932  */
1933 int llapi_layout_mirror_id_get(const struct llapi_layout *layout, uint32_t *id)
1934 {
1935         struct llapi_layout_comp *comp;
1936
1937         comp = __llapi_layout_cur_comp(layout);
1938         if (comp == NULL)
1939                 return -1;
1940
1941         if (id == NULL) {
1942                 errno = EINVAL;
1943                 return -1;
1944         }
1945
1946         *id = mirror_id_of(comp->llc_id);
1947
1948         return 0;
1949 }
1950
1951 /**
1952  * Adds a component to \a layout, the new component will be added to
1953  * the tail of components list and it'll inherit attributes of existing
1954  * ones. The \a layout will change it's current component pointer to
1955  * the newly added component, and it'll be turned into a composite
1956  * layout if it was not before the adding.
1957  *
1958  * \param[in] layout    existing composite or plain layout
1959  *
1960  * \retval      0 on success
1961  * \retval      <0 if error occurs
1962  */
1963 int llapi_layout_comp_add(struct llapi_layout *layout)
1964 {
1965         struct llapi_layout_comp *last, *comp, *new;
1966         bool composite = layout->llot_is_composite;
1967
1968         comp = __llapi_layout_cur_comp(layout);
1969         if (comp == NULL)
1970                 return -1;
1971
1972         new = __llapi_comp_alloc(0);
1973         if (new == NULL)
1974                 return -1;
1975
1976         last = list_entry(layout->llot_comp_list.prev, typeof(*last),
1977                           llc_list);
1978
1979         list_add_tail(&new->llc_list, &layout->llot_comp_list);
1980
1981         /* We must mark the layout composite for the sanity check, but it may
1982          * not stay that way if the check fails */
1983         layout->llot_is_composite = true;
1984         layout->llot_cur_comp = new;
1985
1986         /* We need to set a temporary non-zero value for "end" when we call
1987          * comp_extent_set, so we use LUSTRE_EOF-1, which is > all allowed
1988          * for the end of the previous component.  (If we're adding this
1989          * component, the end of the previous component cannot be EOF.) */
1990         if (llapi_layout_comp_extent_set(layout, last->llc_extent.e_end,
1991                                         LUSTRE_EOF - 1)) {
1992                 llapi_layout_comp_del(layout);
1993                 layout->llot_is_composite = composite;
1994                 return -1;
1995         }
1996
1997         return 0;
1998 }
1999 /**
2000  * Adds a first component of a mirror to \a layout.
2001  * The \a layout will change it's current component pointer to
2002  * the newly added component, and it'll be turned into a composite
2003  * layout if it was not before the adding.
2004  *
2005  * \param[in] layout            existing composite or plain layout
2006  *
2007  * \retval      0 on success
2008  * \retval      <0 if error occurs
2009  */
2010 int llapi_layout_add_first_comp(struct llapi_layout *layout)
2011 {
2012         struct llapi_layout_comp *comp, *new;
2013
2014         comp = __llapi_layout_cur_comp(layout);
2015         if (comp == NULL)
2016                 return -1;
2017
2018         new = __llapi_comp_alloc(0);
2019         if (new == NULL)
2020                 return -1;
2021
2022         new->llc_extent.e_start = 0;
2023
2024         list_add_tail(&new->llc_list, &layout->llot_comp_list);
2025         layout->llot_cur_comp = new;
2026         layout->llot_is_composite = true;
2027
2028         return 0;
2029 }
2030
2031 /**
2032  * Deletes current component from the composite layout. The component
2033  * to be deleted must be the tail of components list, and it can't be
2034  * the only component in the layout.
2035  *
2036  * \param[in] layout    composite layout
2037  *
2038  * \retval      0 on success
2039  * \retval      <0 if error occurs
2040  */
2041 int llapi_layout_comp_del(struct llapi_layout *layout)
2042 {
2043         struct llapi_layout_comp *comp;
2044
2045         comp = __llapi_layout_cur_comp(layout);
2046         if (comp == NULL)
2047                 return -1;
2048
2049         if (!layout->llot_is_composite) {
2050                 errno = EINVAL;
2051                 return -1;
2052         }
2053
2054         /* It must be the tail of the list (for PFL, can be relaxed
2055          * once we get mirrored components) */
2056         if (comp->llc_list.next != &layout->llot_comp_list) {
2057                 errno = EINVAL;
2058                 return -1;
2059         }
2060         layout->llot_cur_comp =
2061                 list_entry(comp->llc_list.prev, typeof(*comp), llc_list);
2062         if (comp->llc_list.prev == &layout->llot_comp_list)
2063                 layout->llot_cur_comp = NULL;
2064
2065         list_del_init(&comp->llc_list);
2066         __llapi_comp_free(comp);
2067
2068         return 0;
2069 }
2070
2071 /**
2072  * Move the current component pointer to the component with
2073  * specified component ID.
2074  *
2075  * \param[in] layout    composite layout
2076  * \param[in] id        component ID
2077  *
2078  * \retval      =0 : moved successfully
2079  * \retval      <0 if error occurs
2080  */
2081 int llapi_layout_comp_use_id(struct llapi_layout *layout, uint32_t comp_id)
2082 {
2083         struct llapi_layout_comp *comp;
2084
2085         comp = __llapi_layout_cur_comp(layout);
2086         if (comp == NULL)
2087                 return -1; /* use previously set errno */
2088
2089         if (!layout->llot_is_composite) {
2090                 errno = EINVAL;
2091                 return -1;
2092         }
2093
2094         if (comp_id == LCME_ID_INVAL) {
2095                 errno = EINVAL;
2096                 return -1;
2097         }
2098
2099         list_for_each_entry(comp, &layout->llot_comp_list, llc_list) {
2100                 if (comp->llc_id == comp_id) {
2101                         layout->llot_cur_comp = comp;
2102                         return 0;
2103                 }
2104         }
2105         errno = ENOENT;
2106         return -1;
2107 }
2108
2109 /**
2110  * Move the current component pointer to a specified position.
2111  *
2112  * \param[in] layout    composite layout
2113  * \param[in] pos       the position to be moved, it can be:
2114  *                      LLAPI_LAYOUT_COMP_USE_FIRST: use first component
2115  *                      LLAPI_LAYOUT_COMP_USE_LAST: use last component
2116  *                      LLAPI_LAYOUT_COMP_USE_NEXT: use component after current
2117  *                      LLAPI_LAYOUT_COMP_USE_PREV: use component before current
2118  *
2119  * \retval      =0 : moved successfully
2120  * \retval      =1 : at last component with NEXT, at first component with PREV
2121  * \retval      <0 if error occurs
2122  */
2123 int llapi_layout_comp_use(struct llapi_layout *layout,
2124                           enum llapi_layout_comp_use pos)
2125 {
2126         struct llapi_layout_comp *comp, *head, *tail;
2127
2128         comp = __llapi_layout_cur_comp(layout);
2129         if (comp == NULL)
2130                 return -1;
2131
2132         if (!layout->llot_is_composite) {
2133                 if (pos == LLAPI_LAYOUT_COMP_USE_FIRST ||
2134                     pos == LLAPI_LAYOUT_COMP_USE_LAST)
2135                         return 0;
2136                 errno = ENOENT;
2137                 return 1;
2138         }
2139
2140         head = list_entry(layout->llot_comp_list.next, typeof(*head), llc_list);
2141         tail = list_entry(layout->llot_comp_list.prev, typeof(*tail), llc_list);
2142         switch (pos) {
2143         case LLAPI_LAYOUT_COMP_USE_FIRST:
2144                 layout->llot_cur_comp = head;
2145                 break;
2146         case LLAPI_LAYOUT_COMP_USE_NEXT:
2147                 if (comp == tail) {
2148                         errno = ENOENT;
2149                         return 1;
2150                 }
2151                 layout->llot_cur_comp = list_entry(comp->llc_list.next,
2152                                                    typeof(*comp), llc_list);
2153                 break;
2154         case LLAPI_LAYOUT_COMP_USE_LAST:
2155                 layout->llot_cur_comp = tail;
2156                 break;
2157         case LLAPI_LAYOUT_COMP_USE_PREV:
2158                 if (comp == head) {
2159                         errno = ENOENT;
2160                         return 1;
2161                 }
2162                 layout->llot_cur_comp = list_entry(comp->llc_list.prev,
2163                                                    typeof(*comp), llc_list);
2164                 break;
2165         default:
2166                 errno = EINVAL;
2167                 return -1;
2168         }
2169
2170         return 0;
2171 }
2172
2173 /**
2174  * Add layout component(s) to an existing file.
2175  *
2176  * \param[in] path      The path name of the file
2177  * \param[in] layout    The layout component(s) to be added
2178  */
2179 int llapi_layout_file_comp_add(const char *path,
2180                                const struct llapi_layout *layout)
2181 {
2182         int rc, fd = -1, lum_size, tmp_errno = 0;
2183         struct llapi_layout *existing_layout = NULL;
2184         struct lov_user_md *lum = NULL;
2185
2186         if (path == NULL || layout == NULL ||
2187             layout->llot_magic != LLAPI_LAYOUT_MAGIC) {
2188                 errno = EINVAL;
2189                 return -1;
2190         }
2191
2192         fd = open(path, O_RDWR);
2193         if (fd < 0) {
2194                 tmp_errno = errno;
2195                 rc = -1;
2196                 goto out;
2197         }
2198
2199         existing_layout = llapi_layout_get_by_fd(fd, 0);
2200         if (existing_layout == NULL) {
2201                 tmp_errno = errno;
2202                 rc = -1;
2203                 goto out;
2204         }
2205
2206         rc = llapi_layout_merge(&existing_layout, layout);
2207         if (rc) {
2208                 tmp_errno = errno;
2209                 rc = -1;
2210                 goto out;
2211         }
2212
2213         rc = llapi_layout_sanity(existing_layout, false, false);
2214         if (rc) {
2215                 tmp_errno = errno;
2216                 llapi_layout_sanity_perror(rc);
2217                 rc = -1;
2218                 goto out;
2219         }
2220
2221         lum = llapi_layout_to_lum(layout);
2222         if (lum == NULL) {
2223                 tmp_errno = errno;
2224                 rc = -1;
2225                 goto out;
2226         }
2227
2228         if (lum->lmm_magic != LOV_USER_MAGIC_COMP_V1) {
2229                 tmp_errno = EINVAL;
2230                 rc = -1;
2231                 goto out;
2232         }
2233         lum_size = ((struct lov_comp_md_v1 *)lum)->lcm_size;
2234
2235         rc = fsetxattr(fd, XATTR_LUSTRE_LOV".add", lum, lum_size, 0);
2236         if (rc < 0) {
2237                 tmp_errno = errno;
2238                 rc = -1;
2239                 goto out;
2240         }
2241 out:
2242         if (fd >= 0)
2243                 close(fd);
2244         free(lum);
2245         llapi_layout_free(existing_layout);
2246         errno = tmp_errno;
2247         return rc;
2248 }
2249
2250 /**
2251  * Delete component(s) by the specified component id or component flags
2252  * from an existing file.
2253  *
2254  * \param[in] path      path name of the file
2255  * \param[in] id        unique component ID
2256  * \param[in] flags     flags: LCME_FL_* or;
2257  *                      negative flags: (LCME_FL_NEG|LCME_FL_*)
2258  */
2259 int llapi_layout_file_comp_del(const char *path, uint32_t id, uint32_t flags)
2260 {
2261         int rc = 0, fd = -1, lum_size, tmp_errno = 0;
2262         struct llapi_layout *layout;
2263         struct llapi_layout_comp *comp, *next;
2264         struct llapi_layout *existing_layout = NULL;
2265         struct lov_user_md *lum = NULL;
2266
2267         if (path == NULL || id > LCME_ID_MAX || (flags & ~LCME_KNOWN_FLAGS)) {
2268                 errno = EINVAL;
2269                 return -1;
2270         }
2271
2272         /* Can only specify ID or flags, not both, not none. */
2273         if ((id != LCME_ID_INVAL && flags != 0) ||
2274             (id == LCME_ID_INVAL && flags == 0)) {
2275                 errno = EINVAL;
2276                 return -1;
2277         }
2278
2279         layout = llapi_layout_alloc();
2280         if (layout == NULL)
2281                 return -1;
2282
2283         llapi_layout_comp_extent_set(layout, 0, LUSTRE_EOF);
2284         comp = __llapi_layout_cur_comp(layout);
2285         if (comp == NULL) {
2286                 tmp_errno = errno;
2287                 rc = -1;
2288                 goto out;
2289         }
2290
2291         comp->llc_id = id;
2292         comp->llc_flags = flags;
2293
2294         lum = llapi_layout_to_lum(layout);
2295         if (lum == NULL) {
2296                 tmp_errno = errno;
2297                 rc = -1;
2298                 goto out;
2299         }
2300         lum_size = ((struct lov_comp_md_v1 *)lum)->lcm_size;
2301
2302         fd = open(path, O_RDWR);
2303         if (fd < 0) {
2304                 tmp_errno = errno;
2305                 rc = -1;
2306                 goto out;
2307         }
2308
2309         existing_layout = llapi_layout_get_by_fd(fd, 0);
2310         if (existing_layout == NULL) {
2311                 tmp_errno = errno;
2312                 rc = -1;
2313                 goto out;
2314         }
2315
2316         comp = NULL;
2317         next = NULL;
2318         while (rc == 0 && existing_layout->llot_cur_comp != NULL) {
2319                 rc = llapi_layout_comp_use(existing_layout, comp ?
2320                                            LLAPI_LAYOUT_COMP_USE_PREV :
2321                                            LLAPI_LAYOUT_COMP_USE_LAST);
2322                 if (rc != 0)
2323                         break;
2324
2325                 next = comp;
2326                 comp = __llapi_layout_cur_comp(existing_layout);
2327                 if (comp == NULL) {
2328                         rc = -1;
2329                         break;
2330                 }
2331
2332                 if (id != LCME_ID_INVAL && id != comp->llc_id)
2333                         continue;
2334                 else if ((flags & LCME_FL_NEG) && (flags & comp->llc_flags))
2335                         continue;
2336                 else if (flags && !(flags & comp->llc_flags))
2337                         continue;
2338
2339                 rc = llapi_layout_comp_del(existing_layout);
2340                 /* the layout position is moved to previous one, adjust */
2341                 comp = next;
2342         }
2343         if (rc < 0) {
2344                 tmp_errno = errno;
2345                 goto out;
2346         }
2347
2348         rc = llapi_layout_sanity(existing_layout, false, false);
2349         if (rc) {
2350                 tmp_errno = errno;
2351                 llapi_layout_sanity_perror(rc);
2352                 rc = -1;
2353                 goto out;
2354         }
2355
2356         rc = fsetxattr(fd, XATTR_LUSTRE_LOV".del", lum, lum_size, 0);
2357         if (rc < 0) {
2358                 tmp_errno = errno;
2359                 rc = -1;
2360                 goto out;
2361         }
2362
2363 out:
2364         if (fd >= 0)
2365                 close(fd);
2366         free(lum);
2367         llapi_layout_free(layout);
2368         llapi_layout_free(existing_layout);
2369         errno = tmp_errno;
2370
2371         return rc;
2372 }
2373
2374 /* Internal utility function to apply flags for sanity checking */
2375 static void llapi_layout_comp_apply_flags(struct llapi_layout_comp *comp,
2376                                           uint32_t flags)
2377 {
2378         if (flags & LCME_FL_NEG)
2379                 comp->llc_flags &= ~flags;
2380         else
2381                 comp->llc_flags |= flags;
2382 }
2383
2384 struct llapi_layout_apply_flags_args {
2385         uint32_t *lfa_ids;
2386         uint32_t *lfa_flags;
2387         int lfa_count;
2388         int lfa_rc;
2389 };
2390
2391
2392 static int llapi_layout_apply_flags_cb(struct llapi_layout *layout,
2393                                        void *arg)
2394 {
2395         struct llapi_layout_apply_flags_args *args = arg;
2396         struct llapi_layout_comp *comp;
2397         int i = 0;
2398
2399         comp = __llapi_layout_cur_comp(layout);
2400         if (comp == NULL) {
2401                 args->lfa_rc = -1;
2402                 return LLAPI_LAYOUT_ITER_STOP;
2403         }
2404
2405         for (i = 0; i < args->lfa_count; i++) {
2406                 if (comp->llc_id == args->lfa_ids[i])
2407                         llapi_layout_comp_apply_flags(comp, args->lfa_flags[i]);
2408         }
2409
2410         return LLAPI_LAYOUT_ITER_CONT;
2411 }
2412
2413 /* Apply flags to the layout for sanity checking */
2414 static int llapi_layout_apply_flags(struct llapi_layout *layout, uint32_t *ids,
2415                                     uint32_t *flags, int count)
2416 {
2417         struct llapi_layout_apply_flags_args args;
2418         int rc = 0;
2419
2420         if (!ids || !flags || count == 0) {
2421                 errno = EINVAL;
2422                 return -1;
2423         }
2424
2425         args.lfa_ids = ids;
2426         args.lfa_flags = flags;
2427         args.lfa_count = count;
2428         args.lfa_rc = 0;
2429
2430         rc = llapi_layout_comp_iterate(layout,
2431                                        llapi_layout_apply_flags_cb,
2432                                        &args);
2433         if (errno == ENOENT)
2434                 errno = 0;
2435
2436         if (rc != LLAPI_LAYOUT_ITER_CONT)
2437                 rc = args.lfa_rc;
2438
2439         return rc;
2440 }
2441 /**
2442  * Change flags by component ID of components of an existing file.
2443  * The component to be modified is specified by the comp->lcme_id value,
2444  * which must be a unique component ID.
2445  *
2446  * \param[in] path      path name of the file
2447  * \param[in] ids       An array of component IDs
2448  * \param[in] flags     flags: LCME_FL_* or;
2449  *                      negative flags: (LCME_FL_NEG|LCME_FL_*)
2450  * \param[in] count     Number of elements in ids and flags array
2451  */
2452 int llapi_layout_file_comp_set(const char *path, uint32_t *ids, uint32_t *flags,
2453                                size_t count)
2454 {
2455         int rc = -1, fd = -1, i, tmp_errno = 0;
2456         size_t lum_size;
2457         struct llapi_layout *existing_layout = NULL;
2458         struct llapi_layout *layout = NULL;
2459         struct llapi_layout_comp *comp;
2460         struct lov_user_md *lum = NULL;
2461
2462         if (path == NULL) {
2463                 errno = EINVAL;
2464                 return -1;
2465         }
2466
2467         if (!count)
2468                 return 0;
2469
2470         for (i = 0; i < count; i++) {
2471                 if (!ids[i] || !flags[i]) {
2472                         errno = EINVAL;
2473                         return -1;
2474                 }
2475
2476                 if (ids[i] > LCME_ID_MAX || (flags[i] & ~LCME_KNOWN_FLAGS)) {
2477                         errno = EINVAL;
2478                         return -1;
2479                 }
2480
2481                 /* do not allow to set or clear INIT flag */
2482                 if (flags[i] & LCME_FL_INIT) {
2483                         errno = EINVAL;
2484                         return -1;
2485                 }
2486         }
2487
2488         fd = open(path, O_RDWR);
2489         if (fd < 0) {
2490                 tmp_errno = errno;
2491                 rc = -1;
2492                 goto out;
2493         }
2494
2495         existing_layout = llapi_layout_get_by_fd(fd, 0);
2496         if (existing_layout == NULL) {
2497                 tmp_errno = errno;
2498                 rc = -1;
2499                 goto out;
2500         }
2501
2502         if (llapi_layout_apply_flags(existing_layout, ids, flags, count)) {
2503                 tmp_errno = errno;
2504                 rc = -1;
2505                 goto out;
2506         }
2507
2508         rc = llapi_layout_sanity(existing_layout, false, false);
2509         if (rc) {
2510                 tmp_errno = errno;
2511                 llapi_layout_sanity_perror(rc);
2512                 rc = -1;
2513                 goto out;
2514         }
2515
2516         layout = __llapi_layout_alloc();
2517         if (layout == NULL) {
2518                 tmp_errno = errno;
2519                 rc = -1;
2520                 goto out;
2521         }
2522
2523         layout->llot_is_composite = true;
2524         for (i = 0; i < count; i++) {
2525                 comp = __llapi_comp_alloc(0);
2526                 if (comp == NULL) {
2527                         tmp_errno = errno;
2528                         rc = -1;
2529                         goto out;
2530                 }
2531
2532                 comp->llc_id = ids[i];
2533                 comp->llc_flags = flags[i];
2534
2535                 list_add_tail(&comp->llc_list, &layout->llot_comp_list);
2536                 layout->llot_cur_comp = comp;
2537         }
2538
2539         lum = llapi_layout_to_lum(layout);
2540         if (lum == NULL) {
2541                 tmp_errno = errno;
2542                 rc = -1;
2543                 goto out;
2544         }
2545
2546         lum_size = ((struct lov_comp_md_v1 *)lum)->lcm_size;
2547
2548         /* flush cached pages from clients */
2549         rc = llapi_file_flush(fd);
2550         if (rc) {
2551                 tmp_errno = -rc;
2552                 rc = -1;
2553                 goto out;
2554         }
2555
2556         rc = fsetxattr(fd, XATTR_LUSTRE_LOV".set.flags", lum, lum_size, 0);
2557         if (rc < 0) {
2558                 tmp_errno = errno;
2559                 goto out;
2560         }
2561
2562         rc = 0;
2563
2564 out:
2565         if (fd >= 0)
2566                 close(fd);
2567
2568         free(lum);
2569         llapi_layout_free(existing_layout);
2570         llapi_layout_free(layout);
2571         errno = tmp_errno;
2572         return rc;
2573 }
2574
2575 /**
2576  * Check if the file layout is composite.
2577  *
2578  * \param[in] layout    the file layout to check
2579  *
2580  * \retval true         composite
2581  * \retval false        not composite
2582  */
2583 bool llapi_layout_is_composite(struct llapi_layout *layout)
2584 {
2585         return layout->llot_is_composite;
2586 }
2587
2588 /**
2589  * Iterate every components in the @layout and call callback function @cb.
2590  *
2591  * \param[in] layout    component layout list.
2592  * \param[in] cb        callback for each component
2593  * \param[in] cbdata    callback data
2594  *
2595  * \retval < 0                          error happens during the iteration
2596  * \retval LLAPI_LAYOUT_ITER_CONT       finished the iteration w/o error
2597  * \retval LLAPI_LAYOUT_ITER_STOP       got something, stop the iteration
2598  */
2599 int llapi_layout_comp_iterate(struct llapi_layout *layout,
2600                               llapi_layout_iter_cb cb, void *cbdata)
2601 {
2602         int rc;
2603
2604         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
2605         if (rc < 0)
2606                 return rc;
2607
2608         /**
2609          * make sure on success llapi_layout_comp_use() API returns 0 with
2610          * USE_FIRST.
2611          */
2612         assert(rc == 0);
2613
2614         while (1) {
2615                 rc = cb(layout, cbdata);
2616                 if (rc != LLAPI_LAYOUT_ITER_CONT)
2617                         break;
2618
2619                 rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_NEXT);
2620                 if (rc < 0)
2621                         return rc;
2622                 else if (rc == 1)       /* reached the last comp */
2623                         return LLAPI_LAYOUT_ITER_CONT;
2624         }
2625
2626         return rc;
2627 }
2628
2629 /**
2630  * llapi_layout_merge() - Merge a composite layout into another one.
2631  * @dst_layout: Destination composite layout.
2632  * @src_layout: Source composite layout.
2633  *
2634  * This function copies all of the components from @src_layout and
2635  * appends them to @dst_layout.
2636  *
2637  * Return: 0 on success or -1 on failure.
2638  */
2639 int llapi_layout_merge(struct llapi_layout **dst_layout,
2640                        const struct llapi_layout *src_layout)
2641 {
2642         struct llapi_layout *new_layout = *dst_layout;
2643         struct llapi_layout_comp *new = NULL;
2644         struct llapi_layout_comp *comp = NULL;
2645         int i = 0;
2646
2647         if (src_layout == NULL ||
2648             list_empty((struct list_head *)&src_layout->llot_comp_list))
2649                 return 0;
2650
2651         if (new_layout == NULL) {
2652                 new_layout = __llapi_layout_alloc();
2653                 if (new_layout == NULL) {
2654                         errno = ENOMEM;
2655                         return -1;
2656                 }
2657         }
2658
2659         list_for_each_entry(comp, &src_layout->llot_comp_list, llc_list) {
2660                 new = __llapi_comp_alloc(0);
2661                 if (new == NULL) {
2662                         errno = ENOMEM;
2663                         goto error;
2664                 }
2665
2666                 new->llc_pattern = comp->llc_pattern;
2667                 new->llc_stripe_size = comp->llc_stripe_size;
2668                 new->llc_stripe_count = comp->llc_stripe_count;
2669                 new->llc_stripe_offset = comp->llc_stripe_offset;
2670
2671                 if (comp->llc_pool_name[0] != '\0')
2672                         strncpy(new->llc_pool_name, comp->llc_pool_name,
2673                                 sizeof(new->llc_pool_name));
2674
2675                 for (i = 0; i < comp->llc_objects_count; i++) {
2676                         if (__llapi_comp_objects_realloc(new,
2677                             stripe_number_roundup(i)) < 0) {
2678                                 errno = EINVAL;
2679                                 __llapi_comp_free(new);
2680                                 goto error;
2681                         }
2682                         new->llc_objects[i].l_ost_idx = \
2683                                 comp->llc_objects[i].l_ost_idx;
2684                 }
2685
2686                 new->llc_objects_count = comp->llc_objects_count;
2687                 new->llc_extent.e_start = comp->llc_extent.e_start;
2688                 new->llc_extent.e_end = comp->llc_extent.e_end;
2689                 new->llc_id = comp->llc_id;
2690                 new->llc_flags = comp->llc_flags;
2691
2692                 list_add_tail(&new->llc_list, &new_layout->llot_comp_list);
2693                 new_layout->llot_cur_comp = new;
2694         }
2695         new_layout->llot_is_composite = true;
2696
2697         *dst_layout = new_layout;
2698         return 0;
2699 error:
2700         llapi_layout_free(new_layout);
2701         return -1;
2702 }
2703
2704 /**
2705  * Get the last initialized component
2706  *
2707  * \param[in] layout    component layout list.
2708  *
2709  * \retval 0            found
2710  * \retval -EINVAL      not found
2711  * \retval -EISDIR      directory layout
2712  */
2713 int llapi_layout_get_last_init_comp(struct llapi_layout *layout)
2714 {
2715         struct llapi_layout_comp *comp = NULL, *head = NULL;
2716
2717         if (!layout->llot_is_composite)
2718                 return 0;
2719
2720         head = list_entry(layout->llot_comp_list.next, typeof(*comp), llc_list);
2721         if (head == NULL)
2722                 return -EINVAL;
2723         if (head->llc_id == 0 && !(head->llc_flags & LCME_FL_INIT))
2724                 /* a directory */
2725                 return -EISDIR;
2726
2727         /* traverse the components from the tail to find the last init one */
2728         comp = list_entry(layout->llot_comp_list.prev, typeof(*comp), llc_list);
2729         while (comp != head) {
2730                 if (comp->llc_flags & LCME_FL_INIT)
2731                         break;
2732                 comp = list_entry(comp->llc_list.prev, typeof(*comp), llc_list);
2733         }
2734
2735         layout->llot_cur_comp = comp;
2736
2737         return comp->llc_flags & LCME_FL_INIT ? 0 : -EINVAL;
2738 }
2739
2740 /**
2741  * Interit stripe info from the file's component to the mirror
2742  *
2743  * \param[in] layout    file component layout list.
2744  * \param[in] layout    mirro component layout list.
2745  *
2746  * \retval 0            on success
2747  * \retval -EINVAL      on error
2748  */
2749 int llapi_layout_mirror_inherit(struct llapi_layout *f_layout,
2750                                 struct llapi_layout *m_layout)
2751 {
2752         struct llapi_layout_comp *m_comp = NULL;
2753         struct llapi_layout_comp *f_comp = NULL;
2754         int rc = 0;
2755
2756         f_comp = __llapi_layout_cur_comp(f_layout);
2757         if (f_comp == NULL)
2758                 return -EINVAL;
2759         m_comp = __llapi_layout_cur_comp(m_layout);
2760         if (m_comp == NULL)
2761                 return -EINVAL;
2762
2763         m_comp->llc_stripe_size = f_comp->llc_stripe_size;
2764         m_comp->llc_stripe_count = f_comp->llc_stripe_count;
2765
2766         return rc;
2767 }
2768
2769 /**
2770  * Find all stale components.
2771  *
2772  * \param[in] layout            component layout list.
2773  * \param[out] comp             array of stale component info.
2774  * \param[in] comp_size         array size of @comp.
2775  * \param[in] mirror_ids        array of mirror id that only components
2776  *                              belonging to these mirror will be collected.
2777  * \param[in] ids_nr            number of mirror ids array.
2778  *
2779  * \retval              number of component info collected on sucess or
2780  *                      an error code on failure.
2781  */
2782 int llapi_mirror_find_stale(struct llapi_layout *layout,
2783                 struct llapi_resync_comp *comp, size_t comp_size,
2784                 __u16 *mirror_ids, int ids_nr)
2785 {
2786         int idx = 0;
2787         int rc;
2788
2789         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
2790         if (rc < 0)
2791                 goto error;
2792
2793         while (rc == 0) {
2794                 uint32_t id;
2795                 uint32_t mirror_id;
2796                 uint32_t flags;
2797                 uint64_t start, end;
2798
2799                 rc = llapi_layout_comp_flags_get(layout, &flags);
2800                 if (rc < 0)
2801                         goto error;
2802
2803                 if (!(flags & LCME_FL_STALE))
2804                         goto next;
2805
2806                 rc = llapi_layout_mirror_id_get(layout, &mirror_id);
2807                 if (rc < 0)
2808                         goto error;
2809
2810                 /* the caller only wants stale components from specific
2811                  * mirrors */
2812                 if (ids_nr > 0) {
2813                         int j;
2814
2815                         for (j = 0; j < ids_nr; j++) {
2816                                 if (mirror_ids[j] == mirror_id)
2817                                         break;
2818                         }
2819
2820                         /* not in the specified mirror */
2821                         if (j == ids_nr)
2822                                 goto next;
2823                 } else if (flags & LCME_FL_NOSYNC) {
2824                         /* if not specified mirrors, do not resync "nosync"
2825                          * mirrors */
2826                         goto next;
2827                 }
2828
2829                 rc = llapi_layout_comp_id_get(layout, &id);
2830                 if (rc < 0)
2831                         goto error;
2832
2833                 rc = llapi_layout_comp_extent_get(layout, &start, &end);
2834                 if (rc < 0)
2835                         goto error;
2836
2837                 /* pack this component into @comp array */
2838                 comp[idx].lrc_id = id;
2839                 comp[idx].lrc_mirror_id = mirror_id;
2840                 comp[idx].lrc_start = start;
2841                 comp[idx].lrc_end = end;
2842                 idx++;
2843
2844                 if (idx >= comp_size) {
2845                         rc = -EINVAL;
2846                         goto error;
2847                 }
2848
2849         next:
2850                 rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_NEXT);
2851                 if (rc < 0) {
2852                         rc = -EINVAL;
2853                         goto error;
2854                 }
2855         }
2856 error:
2857         return rc < 0 ? rc : idx;
2858 }
2859
2860 /* locate @layout to a valid component covering file [file_start, file_end) */
2861 uint32_t llapi_mirror_find(struct llapi_layout *layout,
2862                            uint64_t file_start, uint64_t file_end,
2863                            uint64_t *endp)
2864 {
2865         uint32_t mirror_id = 0;
2866         int rc;
2867
2868         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
2869         if (rc < 0)
2870                 return rc;
2871
2872         *endp = 0;
2873         while (rc == 0) {
2874                 uint64_t start, end;
2875                 uint32_t flags, id, rid;
2876
2877                 rc = llapi_layout_comp_flags_get(layout, &flags);
2878                 if (rc < 0)
2879                         return rc;
2880
2881                 if (flags & LCME_FL_STALE)
2882                         goto next;
2883
2884                 rc = llapi_layout_mirror_id_get(layout, &rid);
2885                 if (rc < 0)
2886                         return rc;
2887
2888                 rc = llapi_layout_comp_id_get(layout, &id);
2889                 if (rc < 0)
2890                         return rc;
2891
2892                 rc = llapi_layout_comp_extent_get(layout, &start, &end);
2893                 if (rc < 0)
2894                         return rc;
2895
2896                 if (file_start >= start && file_start < end) {
2897                         if (!mirror_id)
2898                                 mirror_id = rid;
2899                         else if (mirror_id != rid || *endp != start)
2900                                 break;
2901
2902                         file_start = *endp = end;
2903                         if (end >= file_end)
2904                                 break;
2905                 }
2906
2907         next:
2908                 rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_NEXT);
2909                 if (rc < 0)
2910                         return rc;
2911         }
2912
2913         return mirror_id;
2914 }
2915
2916 int llapi_mirror_resync_many(int fd, struct llapi_layout *layout,
2917                              struct llapi_resync_comp *comp_array,
2918                              int comp_size,  uint64_t start, uint64_t end)
2919 {
2920         uint64_t count;
2921         size_t page_size = sysconf(_SC_PAGESIZE);
2922         const size_t buflen = 4 << 20; /* 4M */
2923         void *buf;
2924         uint64_t pos = start;
2925         int i;
2926         int rc;
2927         int rc2 = 0;
2928
2929         rc = posix_memalign(&buf, page_size, buflen);
2930         if (rc)
2931                 return -rc;
2932
2933         if (end == OBD_OBJECT_EOF)
2934                 count = OBD_OBJECT_EOF;
2935         else
2936                 count = end - start;
2937
2938         while (count > 0) {
2939                 uint32_t src;
2940                 uint64_t mirror_end = 0;
2941                 uint64_t bytes_left;
2942                 ssize_t bytes_read;
2943                 size_t to_read;
2944                 size_t to_write;
2945
2946                 src = llapi_mirror_find(layout, pos, end, &mirror_end);
2947                 if (src == 0)
2948                         return -ENOENT;
2949
2950                 if (mirror_end == OBD_OBJECT_EOF) {
2951                         bytes_left = count;
2952                 } else {
2953                         bytes_left = MIN(count, mirror_end - pos);
2954                         bytes_left = ((bytes_left - 1) | (page_size - 1)) + 1;
2955                 }
2956                 to_read = MIN(buflen, bytes_left);
2957
2958                 bytes_read = llapi_mirror_read(fd, src, buf, to_read, pos);
2959                 if (bytes_read == 0) {
2960                         /* end of file */
2961                         break;
2962                 }
2963                 if (bytes_read < 0) {
2964                         rc = bytes_read;
2965                         break;
2966                 }
2967
2968                 /* round up to page align to make direct IO happy. */
2969                 to_write = ((bytes_read - 1) | (page_size - 1)) + 1;
2970
2971                 for (i = 0; i < comp_size; i++) {
2972                         ssize_t written;
2973                         off_t pos2 = pos;
2974                         size_t to_write2 = to_write;
2975
2976                         /* skip non-overlapped component */
2977                         if (pos >= comp_array[i].lrc_end ||
2978                             pos + to_write <= comp_array[i].lrc_start)
2979                                 continue;
2980
2981                         if (pos < comp_array[i].lrc_start)
2982                                 pos2 = comp_array[i].lrc_start;
2983
2984                         to_write2 -= pos2 - pos;
2985
2986                         if ((pos + to_write) > comp_array[i].lrc_end)
2987                                 to_write2 -= pos + to_write -
2988                                              comp_array[i].lrc_end;
2989
2990                         written = llapi_mirror_write(fd,
2991                                         comp_array[i].lrc_mirror_id,
2992                                         buf + pos2 - pos,
2993                                         to_write2, pos2);
2994                         if (written < 0) {
2995                                 /**
2996                                  * this component is not written successfully,
2997                                  * mark it using its lrc_synced, it is supposed
2998                                  * to be false before getting here.
2999                                  *
3000                                  * And before this function returns, all
3001                                  * elements of comp_array will reverse their
3002                                  * lrc_synced flag to reflect their true
3003                                  * meanings.
3004                                  */
3005                                 comp_array[i].lrc_synced = true;
3006                                 llapi_error(LLAPI_MSG_ERROR, written,
3007                                             "component %u not synced",
3008                                             comp_array[i].lrc_id);
3009                                 if (rc2 == 0)
3010                                         rc2 = (int)written;
3011                                 continue;
3012                         }
3013                         assert(written == to_write2);
3014                 }
3015
3016                 pos += bytes_read;
3017                 count -= bytes_read;
3018         }
3019
3020         free(buf);
3021
3022         if (rc < 0) {
3023                 /* fatal error happens */
3024                 for (i = 0; i < comp_size; i++)
3025                         comp_array[i].lrc_synced = false;
3026                 return rc;
3027         }
3028
3029         /**
3030          * no fatal error happens, each lrc_synced tells whether the component
3031          * has been resync successfully (note: we'd reverse the value to
3032          * reflect its true meaning.
3033          */
3034         for (i = 0; i < comp_size; i++) {
3035                 comp_array[i].lrc_synced = !comp_array[i].lrc_synced;
3036                 if (comp_array[i].lrc_synced && pos & (page_size - 1)) {
3037                         rc = llapi_mirror_truncate(fd,
3038                                         comp_array[i].lrc_mirror_id, pos);
3039                         if (rc < 0)
3040                                 comp_array[i].lrc_synced = false;
3041                 }
3042         }
3043
3044         /**
3045          * returns the first error code for partially successful resync if
3046          * possible.
3047          */
3048         return rc2;
3049 }
3050
3051 enum llapi_layout_comp_sanity_error {
3052         LSE_OK,
3053         LSE_INCOMPLETE_MIRROR,
3054         LSE_ADJACENT_EXTENSION,
3055         LSE_INIT_EXTENSION,
3056         LSE_FLAGS,
3057         LSE_DOM_EXTENSION,
3058         LSE_DOM_EXTENSION_FOLLOWING,
3059         LSE_DOM_FIRST,
3060         LSE_SET_COMP_START,
3061         LSE_NOT_ZERO_LENGTH_EXTENDABLE,
3062         LSE_END_NOT_GREATER,
3063         LSE_ZERO_LENGTH_NORMAL,
3064         LSE_NOT_ADJACENT_PREV,
3065         LSE_START_GT_END,
3066         LSE_ALIGN_END,
3067         LSE_ALIGN_EXT,
3068         LSE_LAST,
3069 };
3070
3071 const char *const llapi_layout_strerror[] =
3072 {
3073         [LSE_OK] = "",
3074         [LSE_INCOMPLETE_MIRROR] =
3075                 "Incomplete mirror - must go to EOF",
3076         [LSE_ADJACENT_EXTENSION] =
3077                 "No adjacent extension space components",
3078         [LSE_INIT_EXTENSION] =
3079                 "Cannot apply extension flag to init components",
3080         [LSE_FLAGS] =
3081                 "Wrong flags",
3082         [LSE_DOM_EXTENSION] =
3083                 "DoM components can't be extension space",
3084         [LSE_DOM_EXTENSION_FOLLOWING] =
3085                 "DoM components cannot be followed by extension space",
3086         [LSE_DOM_FIRST] =
3087                 "DoM component should be the first one in a file/mirror",
3088         [LSE_SET_COMP_START] =
3089                 "Must set previous component extent before adding next",
3090         [LSE_NOT_ZERO_LENGTH_EXTENDABLE] =
3091                 "Extendable component must start out zero-length",
3092         [LSE_END_NOT_GREATER] =
3093                 "Component end is before end of previous component",
3094         [LSE_ZERO_LENGTH_NORMAL] =
3095                 "Zero length components must be followed by extension",
3096         [LSE_NOT_ADJACENT_PREV] =
3097                 "Components not adjacent (end != next->start",
3098         [LSE_START_GT_END] =
3099                 "Component start is > end",
3100         [LSE_ALIGN_END] =
3101                 "The component end must be aligned by the stripe size",
3102         [LSE_ALIGN_EXT] =
3103                 "The extension size must be aligned by the stripe size",
3104 };
3105
3106 struct llapi_layout_sanity_args {
3107         bool lsa_incomplete;
3108         bool lsa_flr;
3109         bool lsa_ondisk;
3110         int lsa_rc;
3111 };
3112
3113 /* The component flags can be set by users at creation/modification time. */
3114 #define LCME_USER_COMP_FLAGS    (LCME_FL_PREF_RW | LCME_FL_NOSYNC | \
3115                                  LCME_FL_EXTENSION)
3116
3117 static int llapi_layout_sanity_cb(struct llapi_layout *layout,
3118                                   void *arg)
3119 {
3120         struct llapi_layout_comp *comp, *next, *prev;
3121         struct llapi_layout_sanity_args *args = arg;
3122         bool first_comp = false;
3123
3124         comp = __llapi_layout_cur_comp(layout);
3125         if (comp == NULL) {
3126                 args->lsa_rc = -1;
3127                 goto out_err;
3128         }
3129
3130         if (comp->llc_list.prev != &layout->llot_comp_list)
3131                 prev = list_entry(comp->llc_list.prev, typeof(*prev),
3132                                   llc_list);
3133         else
3134                 prev = NULL;
3135
3136         if (comp->llc_list.next != &layout->llot_comp_list)
3137                 next = list_entry(comp->llc_list.next, typeof(*next),
3138                                   llc_list);
3139         else
3140                 next = NULL;
3141
3142         /* Start of zero implies a new mirror */
3143         if (comp->llc_extent.e_start == 0) {
3144                 first_comp = true;
3145                 /* Most checks apply only within one mirror, this is an
3146                  * exception. */
3147                 if (prev && prev->llc_extent.e_end != LUSTRE_EOF) {
3148                         args->lsa_rc = LSE_INCOMPLETE_MIRROR;
3149                         goto out_err;
3150                 }
3151
3152                 prev = NULL;
3153         }
3154
3155         if (next && next->llc_extent.e_start == 0)
3156                 next = NULL;
3157
3158         /* Flag sanity checks */
3159         /* No adjacent extension components */
3160         if ((comp->llc_flags & LCME_FL_EXTENSION) && next &&
3161             (next->llc_flags & LCME_FL_EXTENSION)) {
3162                 args->lsa_rc = LSE_ADJACENT_EXTENSION;
3163                 goto out_err;
3164         }
3165
3166         /* Extension flag cannot be applied to init components and the first
3167          * component of each mirror is automatically init */
3168         if ((comp->llc_flags & LCME_FL_EXTENSION) &&
3169             (comp->llc_flags & LCME_FL_INIT || first_comp)) {
3170                 args->lsa_rc = LSE_INIT_EXTENSION;
3171                 goto out_err;
3172         }
3173
3174         if (comp->llc_ondisk) {
3175                 if (comp->llc_flags & LCME_FL_NEG)
3176                         args->lsa_rc = LSE_FLAGS;
3177         } else if (!args->lsa_incomplete) {
3178                 if (args->lsa_flr) {
3179                         if (comp->llc_flags & ~LCME_USER_COMP_FLAGS)
3180                                 args->lsa_rc = LSE_FLAGS;
3181                 } else {
3182                         if (comp->llc_flags &
3183                             ~(LCME_FL_EXTENSION | LCME_FL_PREF_RW))
3184                                 args->lsa_rc = LSE_FLAGS;
3185                 }
3186         }
3187         if (args->lsa_rc)
3188                 goto out_err;
3189
3190         /* DoM sanity checks */
3191         if (comp->llc_pattern == LLAPI_LAYOUT_MDT ||
3192             comp->llc_pattern == LOV_PATTERN_MDT) {
3193                 /* DoM components can't be extension components */
3194                 if (comp->llc_flags & LCME_FL_EXTENSION) {
3195                         args->lsa_rc = LSE_DOM_EXTENSION;
3196                         goto out_err;
3197                 }
3198                 /* DoM components cannot be followed by an extension comp */
3199                 if (next && (next->llc_flags & LCME_FL_EXTENSION)) {
3200                         args->lsa_rc = LSE_DOM_EXTENSION_FOLLOWING;
3201                         goto out_err;
3202                 }
3203
3204                 /* DoM should be the first component in a mirror */
3205                 if (!first_comp) {
3206                         args->lsa_rc = LSE_DOM_FIRST;
3207                         errno = EINVAL;
3208                         goto out_err;
3209                 }
3210         }
3211
3212         /* Extent sanity checks */
3213         /* Must set previous component extent before adding another */
3214         if (prev && prev->llc_extent.e_start == 0 &&
3215             prev->llc_extent.e_end == 0) {
3216                 args->lsa_rc = LSE_SET_COMP_START;
3217                 goto out_err;
3218         }
3219
3220         if (!args->lsa_incomplete) {
3221                 /* Components followed by extension space (extendable
3222                  * components) must be zero length before initialization.
3223                  * (Except for first comp, which will be initialized on
3224                  * creation). */
3225                 if (next && (next->llc_flags & LCME_FL_EXTENSION) &&
3226                     !first_comp && !(comp->llc_flags & LCME_FL_INIT) &&
3227                     comp->llc_extent.e_start != comp->llc_extent.e_end) {
3228                         args->lsa_rc = LSE_NOT_ZERO_LENGTH_EXTENDABLE;
3229                         goto out_err;
3230                 }
3231
3232                 /* End must come after end of previous comp */
3233                 if (prev && comp->llc_extent.e_end < prev->llc_extent.e_end) {
3234                         args->lsa_rc = LSE_END_NOT_GREATER;
3235                         goto out_err;
3236                 }
3237
3238                 /* Components not followed by ext space must have length > 0. */
3239                 if (comp->llc_extent.e_start == comp->llc_extent.e_end &&
3240                     (next == NULL || !(next->llc_flags & LCME_FL_EXTENSION))) {
3241                         args->lsa_rc = LSE_ZERO_LENGTH_NORMAL;
3242                         goto out_err;
3243                 }
3244
3245                 /* The component end must be aligned by the stripe size */
3246                 if ((comp->llc_flags & LCME_FL_EXTENSION) &&
3247                     (prev->llc_stripe_size != LLAPI_LAYOUT_DEFAULT)) {
3248                         if (comp->llc_extent.e_end != LUSTRE_EOF &&
3249                             comp->llc_extent.e_end % prev->llc_stripe_size) {
3250                                 args->lsa_rc = LSE_ALIGN_END;
3251                                 goto out_err;
3252                         }
3253                         if ((comp->llc_stripe_size * SEL_UNIT_SIZE) %
3254                             prev->llc_stripe_size) {
3255                                 args->lsa_rc = LSE_ALIGN_EXT;
3256                                 goto out_err;
3257                         }
3258                 } else if (!(comp->llc_flags & LCME_FL_EXTENSION) &&
3259                            (comp->llc_stripe_size != LLAPI_LAYOUT_DEFAULT)) {
3260                         if (comp->llc_extent.e_end != LUSTRE_EOF &&
3261                             comp->llc_extent.e_end % comp->llc_stripe_size) {
3262                                 args->lsa_rc = LSE_ALIGN_END;
3263                                 goto out_err;
3264                         }
3265                 }
3266         }
3267
3268         /* Components must have start == prev->end */
3269         if (prev && comp->llc_extent.e_start != 0 &&
3270             comp->llc_extent.e_start != prev->llc_extent.e_end) {
3271                 args->lsa_rc = LSE_NOT_ADJACENT_PREV;
3272                 goto out_err;
3273         }
3274
3275         /* Components must have start <= end */
3276         if (comp->llc_extent.e_start > comp->llc_extent.e_end) {
3277                 args->lsa_rc = LSE_START_GT_END;
3278                 goto out_err;
3279         }
3280
3281         return LLAPI_LAYOUT_ITER_CONT;
3282
3283 out_err:
3284         errno = errno ? errno : EINVAL;
3285         return LLAPI_LAYOUT_ITER_STOP;
3286 }
3287
3288 /* Print explanation of layout error */
3289 void llapi_layout_sanity_perror(int error)
3290 {
3291         if (error >= LSE_LAST || error < 0) {
3292                 fprintf(stdout, "Invalid layout, unrecognized error: %d\n",
3293                         error);
3294         } else {
3295                 fprintf(stdout, "Invalid layout: %s\n",
3296                         llapi_layout_strerror[error]);
3297         }
3298 }
3299
3300 /* Walk a layout and enforce sanity checks that apply to > 1 component
3301  *
3302  * The core idea here is that of sanity checking individual tokens vs semantic
3303  * checking.
3304  * We cannot check everything at the individual component level ('token'),
3305  * instead we must check whether or not the full layout has a valid meaning.
3306  *
3307  * An example of a component level check is "is stripe size valid?".  That is
3308  * handled when setting stripe size.
3309  *
3310  * An example of a layout level check is "are the extents of these components
3311  * valid when adjacent to one another", or "can we set these flags on adjacent
3312  * components"?
3313  *
3314  * \param[in] layout            component layout list.
3315  * \param[in] incomplete        if layout is complete or not - some checks can
3316  *                              only be done on complete layouts.
3317  * \param[in] flr               set when this is called from FLR mirror create
3318  *
3319  * \retval                      0, success, positive: various errors, see
3320  *                              llapi_layout_sanity_perror, -1, failure
3321  */
3322 int llapi_layout_sanity(struct llapi_layout *layout, bool incomplete, bool flr)
3323 {
3324         struct llapi_layout_sanity_args args;
3325         struct llapi_layout_comp *curr;
3326         int rc = 0;
3327
3328         if (!layout)
3329                 return 0;
3330
3331         curr = layout->llot_cur_comp;
3332         if (!curr)
3333                 return 0;
3334
3335         /* Set up args */
3336         args.lsa_rc = 0;
3337         args.lsa_flr = flr;
3338         args.lsa_incomplete = incomplete;
3339
3340         /* When we modify an existing layout, this tells us if it's FLR */
3341         if (mirror_id_of(curr->llc_id) > 0)
3342                 args.lsa_flr = true;
3343
3344         errno = 0;
3345         rc = llapi_layout_comp_iterate(layout,
3346                                        llapi_layout_sanity_cb,
3347                                        &args);
3348         if (errno == ENOENT)
3349                 errno = 0;
3350
3351         if (rc != LLAPI_LAYOUT_ITER_CONT)
3352                 rc = args.lsa_rc;
3353
3354         layout->llot_cur_comp = curr;
3355
3356         return rc;
3357 }
3358
3359 int llapi_layout_dom_size(struct llapi_layout *layout, uint64_t *size)
3360 {
3361         uint64_t pattern, start;
3362         int rc;
3363
3364         if (!layout || !llapi_layout_is_composite(layout)) {
3365                 *size = 0;
3366                 return 0;
3367         }
3368
3369         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
3370         if (rc)
3371                 return -errno;
3372
3373         rc = llapi_layout_pattern_get(layout, &pattern);
3374         if (rc)
3375                 return -errno;
3376
3377         if (pattern != LOV_PATTERN_MDT && pattern != LLAPI_LAYOUT_MDT) {
3378                 *size = 0;
3379                 return 0;
3380         }
3381
3382         rc = llapi_layout_comp_extent_get(layout, &start, size);
3383         if (rc)
3384                 return -errno;
3385         if (start)
3386                 return -ERANGE;
3387         return 0;
3388 }
3389
3390 int lov_comp_md_size(struct lov_comp_md_v1 *lcm)
3391 {
3392         if (lcm->lcm_magic == LOV_MAGIC_V1 || lcm->lcm_magic == LOV_MAGIC_V3) {
3393                 struct lov_user_md *lum = (void *)lcm;
3394
3395                 return lov_user_md_size(lum->lmm_stripe_count, lum->lmm_magic);
3396         }
3397
3398         if (lcm->lcm_magic == LOV_MAGIC_FOREIGN) {
3399                 struct lov_foreign_md *lfm = (void *)lcm;
3400
3401                 return lfm->lfm_length;
3402         }
3403
3404         if (lcm->lcm_magic != LOV_MAGIC_COMP_V1)
3405                 return -EOPNOTSUPP;
3406
3407         return lcm->lcm_size;
3408 }
3409
3410 int llapi_get_lum_file_fd(int dir_fd, const char *fname, __u64 *valid,
3411                           lstatx_t *statx, struct lov_user_md *lum,
3412                           size_t lumsize)
3413 {
3414         struct lov_user_mds_data *lmd;
3415         char buf[65536 + offsetof(typeof(*lmd), lmd_lmm)];
3416         int parent_fd = -1;
3417         int rc;
3418
3419         if (lum && lumsize < sizeof(*lum))
3420                 return -EINVAL;
3421
3422         /* If a file name is provided, it is relative to the parent directory */
3423         if (fname) {
3424                 parent_fd = dir_fd;
3425                 dir_fd = -1;
3426         }
3427
3428         lmd = (struct lov_user_mds_data *)buf;
3429         rc = get_lmd_info_fd(fname, parent_fd, dir_fd, buf, sizeof(buf),
3430                              GET_LMD_INFO);
3431         if (rc)
3432                 return rc;
3433
3434         if (valid)
3435                 *valid = lmd->lmd_flags;
3436
3437         if (statx)
3438                 memcpy(statx, &lmd->lmd_stx, sizeof(*statx));
3439
3440         if (lum) {
3441                 if (lmd->lmd_lmmsize > lumsize)
3442                         return -EOVERFLOW;
3443                 memcpy(lum, &lmd->lmd_lmm, lmd->lmd_lmmsize);
3444         }
3445
3446         return 0;
3447 }
3448
3449 int llapi_get_lum_dir_fd(int dir_fd, __u64 *valid, lstatx_t *statx,
3450                          struct lov_user_md *lum, size_t lumsize)
3451 {
3452         return llapi_get_lum_file_fd(dir_fd, NULL, valid, statx, lum, lumsize);
3453 }
3454
3455 int llapi_get_lum_file(const char *path, __u64 *valid, lstatx_t *statx,
3456                        struct lov_user_md *lum, size_t lumsize)
3457 {
3458         char parent[PATH_MAX];
3459         const char *fname;
3460         char *tmp;
3461         int offset;
3462         int dir_fd;
3463         int rc;
3464
3465         tmp = strrchr(path, '/');
3466         if (!tmp) {
3467                 strncpy(parent, ".", sizeof(parent) - 1);
3468                 offset = -1;
3469         } else {
3470                 strncpy(parent, path, tmp - path);
3471                 offset = tmp - path - 1;
3472                 parent[tmp - path] = 0;
3473         }
3474
3475         fname = path;
3476         if (offset >= 0)
3477                 fname += offset + 2;
3478
3479         dir_fd = open(parent, O_RDONLY);
3480         if (dir_fd < 0) {
3481                 rc = -errno;
3482                 llapi_error(LLAPI_MSG_ERROR, rc, "cannot open '%s'", path);
3483                 return rc;
3484         }
3485
3486         rc = llapi_get_lum_file_fd(dir_fd, fname, valid, statx, lum, lumsize);
3487         close(dir_fd);
3488         return rc;
3489 }
3490
3491 int llapi_get_lum_dir(const char *path, __u64 *valid, lstatx_t *statx,
3492                       struct lov_user_md *lum, size_t lumsize)
3493 {
3494         int dir_fd;
3495         int rc;
3496
3497         dir_fd = open(path, O_RDONLY);
3498         if (dir_fd < 0) {
3499                 rc = -errno;
3500                 llapi_error(LLAPI_MSG_ERROR, rc, "cannot open '%s'", path);
3501                 return rc;
3502         }
3503
3504         rc = llapi_get_lum_dir_fd(dir_fd, valid, statx, lum, lumsize);
3505         close(dir_fd);
3506         return rc;
3507 }