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