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