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