Whamcloud - gitweb
e47b303798b7652eb9c1786670195e08f74bf4e0
[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) {
1578                 rc = llapi_layout_sanity((struct llapi_layout *)layout, false,
1579                                          !!(layout->llot_mirror_count > 1));
1580                 if (rc) {
1581                         llapi_layout_sanity_perror(rc);
1582                         return -1;
1583                 }
1584         }
1585
1586         /* Object creation must be postponed until after layout attributes
1587          * have been applied. */
1588         if (layout != NULL && (open_flags & O_CREAT))
1589                 open_flags |= O_LOV_DELAY_CREATE;
1590
1591         fd = open(path, open_flags, mode);
1592
1593         if (layout == NULL || fd < 0)
1594                 return fd;
1595
1596         lum = llapi_layout_to_lum(layout);
1597
1598         if (lum == NULL) {
1599                 tmp = errno;
1600                 close(fd);
1601                 errno = tmp;
1602                 return -1;
1603         }
1604
1605         if (lum->lmm_magic == LOV_USER_MAGIC_COMP_V1)
1606                 lum_size = ((struct lov_comp_md_v1 *)lum)->lcm_size;
1607         else if (lum->lmm_magic == LOV_USER_MAGIC_SPECIFIC)
1608                 lum_size = lov_user_md_size(lum->lmm_stripe_count,
1609                                             lum->lmm_magic);
1610         else
1611                 lum_size = lov_user_md_size(0, lum->lmm_magic);
1612
1613         rc = fsetxattr(fd, XATTR_LUSTRE_LOV, lum, lum_size, 0);
1614         if (rc < 0) {
1615                 tmp = errno;
1616                 close(fd);
1617                 errno = tmp;
1618                 fd = -1;
1619         }
1620
1621         free(lum);
1622         errno = errno == EOPNOTSUPP ? ENOTTY : errno;
1623
1624         return fd;
1625 }
1626
1627 /**
1628  * Create a file with a given \a layout.
1629  *
1630  * Force O_CREAT and O_EXCL flags on so caller is assured that file was
1631  * created with the given \a layout on successful function return.
1632  *
1633  * \param[in] path              name of the file to open
1634  * \param[in] open_flags        open() flags
1635  * \param[in] mode              permissions to create new file with
1636  * \param[in] layout            layout to create new file with
1637  *
1638  * \retval              non-negative file descriptor on successful open
1639  * \retval              -1 if an error occurred
1640  */
1641 int llapi_layout_file_create(const char *path, int open_flags, int mode,
1642                              const struct llapi_layout *layout)
1643 {
1644         return llapi_layout_file_open(path, open_flags|O_CREAT|O_EXCL, mode,
1645                                       layout);
1646 }
1647
1648 int llapi_layout_flags_get(struct llapi_layout *layout, uint32_t *flags)
1649 {
1650         if (layout->llot_magic != LLAPI_LAYOUT_MAGIC) {
1651                 errno = EINVAL;
1652                 return -1;
1653         }
1654
1655         *flags = layout->llot_flags;
1656         return 0;
1657 }
1658
1659 /**
1660  * Set flags to the header of a component layout.
1661  */
1662 int llapi_layout_flags_set(struct llapi_layout *layout, uint32_t flags)
1663 {
1664         if (layout->llot_magic != LLAPI_LAYOUT_MAGIC) {
1665                 errno = EINVAL;
1666                 return -1;
1667         }
1668
1669         layout->llot_flags = flags;
1670         return 0;
1671 }
1672
1673 const char *llapi_layout_flags_string(uint32_t flags)
1674 {
1675         switch (flags & LCM_FL_FLR_MASK) {
1676         case LCM_FL_RDONLY:
1677                 return "ro";
1678         case LCM_FL_WRITE_PENDING:
1679                 return "wp";
1680         case LCM_FL_SYNC_PENDING:
1681                 return "sp";
1682         }
1683
1684         return "0";
1685 }
1686
1687 const __u16 llapi_layout_string_flags(char *string)
1688 {
1689         if (strncmp(string, "ro", strlen(string)) == 0)
1690                 return LCM_FL_RDONLY;
1691         if (strncmp(string, "wp", strlen(string)) == 0)
1692                 return LCM_FL_WRITE_PENDING;
1693         if (strncmp(string, "sp", strlen(string)) == 0)
1694                 return LCM_FL_SYNC_PENDING;
1695
1696         return 0;
1697 }
1698
1699 /**
1700  * llapi_layout_mirror_count_is_valid() - Check the validity of mirror count.
1701  * @count: Mirror count value to be checked.
1702  *
1703  * This function checks the validity of mirror count.
1704  *
1705  * Return: true on success or false on failure.
1706  */
1707 static bool llapi_layout_mirror_count_is_valid(uint16_t count)
1708 {
1709         return count >= 0 && count <= LUSTRE_MIRROR_COUNT_MAX;
1710 }
1711
1712 /**
1713  * llapi_layout_mirror_count_get() - Get mirror count from the header of
1714  *                                   a layout.
1715  * @layout: Layout to get mirror count from.
1716  * @count:  Returned mirror count value.
1717  *
1718  * This function gets mirror count from the header of a layout.
1719  *
1720  * Return: 0 on success or -1 on failure.
1721  */
1722 int llapi_layout_mirror_count_get(struct llapi_layout *layout,
1723                                   uint16_t *count)
1724 {
1725         if (layout->llot_magic != LLAPI_LAYOUT_MAGIC) {
1726                 errno = EINVAL;
1727                 return -1;
1728         }
1729
1730         *count = layout->llot_mirror_count;
1731         return 0;
1732 }
1733
1734 /**
1735  * llapi_layout_mirror_count_set() - Set mirror count to the header of a layout.
1736  * @layout: Layout to set mirror count in.
1737  * @count:  Mirror count value to be set.
1738  *
1739  * This function sets mirror count to the header of a layout.
1740  *
1741  * Return: 0 on success or -1 on failure.
1742  */
1743 int llapi_layout_mirror_count_set(struct llapi_layout *layout,
1744                                   uint16_t count)
1745 {
1746         if (layout->llot_magic != LLAPI_LAYOUT_MAGIC) {
1747                 errno = EINVAL;
1748                 return -1;
1749         }
1750
1751         if (!llapi_layout_mirror_count_is_valid(count)) {
1752                 errno = EINVAL;
1753                 return -1;
1754         }
1755
1756         layout->llot_mirror_count = count;
1757         return 0;
1758 }
1759
1760 /**
1761  * Fetch the start and end offset of the current layout component.
1762  *
1763  * \param[in] layout    the layout component
1764  * \param[out] start    extent start, inclusive
1765  * \param[out] end      extent end, exclusive
1766  *
1767  * \retval      0 on success
1768  * \retval      <0 if error occurs
1769  */
1770 int llapi_layout_comp_extent_get(const struct llapi_layout *layout,
1771                                  uint64_t *start, uint64_t *end)
1772 {
1773         struct llapi_layout_comp *comp;
1774
1775         comp = __llapi_layout_cur_comp(layout);
1776         if (comp == NULL)
1777                 return -1;
1778
1779         if (start == NULL || end == NULL) {
1780                 errno = EINVAL;
1781                 return -1;
1782         }
1783
1784         *start = comp->llc_extent.e_start;
1785         *end = comp->llc_extent.e_end;
1786
1787         return 0;
1788 }
1789
1790 /**
1791  * Set the layout extent of a layout.
1792  *
1793  * \param[in] layout    the layout to be set
1794  * \param[in] start     extent start, inclusive
1795  * \param[in] end       extent end, exclusive
1796  *
1797  * \retval      0 on success
1798  * \retval      <0 if error occurs
1799  */
1800 int llapi_layout_comp_extent_set(struct llapi_layout *layout,
1801                                  uint64_t start, uint64_t end)
1802 {
1803         struct llapi_layout_comp *comp;
1804
1805         comp = __llapi_layout_cur_comp(layout);
1806         if (comp == NULL)
1807                 return -1;
1808
1809         if (start > end) {
1810                 errno = EINVAL;
1811                 return -1;
1812         }
1813
1814         comp->llc_extent.e_start = start;
1815         comp->llc_extent.e_end = end;
1816         layout->llot_is_composite = true;
1817
1818         return 0;
1819 }
1820
1821 /**
1822  * Gets the attribute flags of the current component.
1823  *
1824  * \param[in] layout    the layout component
1825  * \param[out] flags    stored the returned component flags
1826  *
1827  * \retval      0 on success
1828  * \retval      <0 if error occurs
1829  */
1830 int llapi_layout_comp_flags_get(const struct llapi_layout *layout,
1831                                 uint32_t *flags)
1832 {
1833         struct llapi_layout_comp *comp;
1834
1835         comp = __llapi_layout_cur_comp(layout);
1836         if (comp == NULL)
1837                 return -1;
1838
1839         if (flags == NULL) {
1840                 errno = EINVAL;
1841                 return -1;
1842         }
1843
1844         *flags = comp->llc_flags;
1845
1846         return 0;
1847 }
1848
1849 /**
1850  * Sets the specified flags of the current component leaving other flags as-is.
1851  *
1852  * \param[in] layout    the layout component
1853  * \param[in] flags     component flags to be set
1854  *
1855  * \retval      0 on success
1856  * \retval      <0 if error occurs
1857  */
1858 int llapi_layout_comp_flags_set(struct llapi_layout *layout, uint32_t flags)
1859 {
1860         struct llapi_layout_comp *comp;
1861
1862         comp = __llapi_layout_cur_comp(layout);
1863         if (comp == NULL)
1864                 return -1;
1865
1866         comp->llc_flags |= flags;
1867
1868         return 0;
1869 }
1870
1871 /**
1872  * Clears the flags specified in the flags leaving other flags as-is.
1873  *
1874  * \param[in] layout    the layout component
1875  * \param[in] flags     component flags to be cleared
1876  *
1877  * \retval      0 on success
1878  * \retval      <0 if error occurs
1879  */
1880 int llapi_layout_comp_flags_clear(struct llapi_layout *layout,
1881                                   uint32_t flags)
1882 {
1883         struct llapi_layout_comp *comp;
1884
1885         comp = __llapi_layout_cur_comp(layout);
1886         if (comp == NULL)
1887                 return -1;
1888
1889         comp->llc_flags &= ~flags;
1890
1891         return 0;
1892 }
1893
1894 /**
1895  * Fetches the file-unique component ID of the current layout component.
1896  *
1897  * \param[in] layout    the layout component
1898  * \param[out] id       stored the returned component ID
1899  *
1900  * \retval      0 on success
1901  * \retval      <0 if error occurs
1902  */
1903 int llapi_layout_comp_id_get(const struct llapi_layout *layout, uint32_t *id)
1904 {
1905         struct llapi_layout_comp *comp;
1906
1907         comp = __llapi_layout_cur_comp(layout);
1908         if (comp == NULL)
1909                 return -1;
1910
1911         if (id == NULL) {
1912                 errno = EINVAL;
1913                 return -1;
1914         }
1915         *id = comp->llc_id;
1916
1917         return 0;
1918 }
1919
1920 /**
1921  * Return the mirror id of the current layout component.
1922  *
1923  * \param[in] layout    the layout component
1924  * \param[out] id       stored the returned mirror ID
1925  *
1926  * \retval      0 on success
1927  * \retval      <0 if error occurs
1928  */
1929 int llapi_layout_mirror_id_get(const struct llapi_layout *layout, uint32_t *id)
1930 {
1931         struct llapi_layout_comp *comp;
1932
1933         comp = __llapi_layout_cur_comp(layout);
1934         if (comp == NULL)
1935                 return -1;
1936
1937         if (id == NULL) {
1938                 errno = EINVAL;
1939                 return -1;
1940         }
1941
1942         *id = mirror_id_of(comp->llc_id);
1943
1944         return 0;
1945 }
1946
1947 /**
1948  * Adds a component to \a layout, the new component will be added to
1949  * the tail of components list and it'll inherit attributes of existing
1950  * ones. The \a layout will change it's current component pointer to
1951  * the newly added component, and it'll be turned into a composite
1952  * layout if it was not before the adding.
1953  *
1954  * \param[in] layout    existing composite or plain layout
1955  *
1956  * \retval      0 on success
1957  * \retval      <0 if error occurs
1958  */
1959 int llapi_layout_comp_add(struct llapi_layout *layout)
1960 {
1961         struct llapi_layout_comp *last, *comp, *new;
1962         bool composite = layout->llot_is_composite;
1963
1964         comp = __llapi_layout_cur_comp(layout);
1965         if (comp == NULL)
1966                 return -1;
1967
1968         new = __llapi_comp_alloc(0);
1969         if (new == NULL)
1970                 return -1;
1971
1972         last = list_entry(layout->llot_comp_list.prev, typeof(*last),
1973                           llc_list);
1974
1975         list_add_tail(&new->llc_list, &layout->llot_comp_list);
1976
1977         /* We must mark the layout composite for the sanity check, but it may
1978          * not stay that way if the check fails */
1979         layout->llot_is_composite = true;
1980         layout->llot_cur_comp = new;
1981
1982         /* We need to set a temporary non-zero value for "end" when we call
1983          * comp_extent_set, so we use LUSTRE_EOF-1, which is > all allowed
1984          * for the end of the previous component.  (If we're adding this
1985          * component, the end of the previous component cannot be EOF.) */
1986         if (llapi_layout_comp_extent_set(layout, last->llc_extent.e_end,
1987                                         LUSTRE_EOF - 1)) {
1988                 llapi_layout_comp_del(layout);
1989                 layout->llot_is_composite = composite;
1990                 return -1;
1991         }
1992
1993         return 0;
1994 }
1995 /**
1996  * Adds a first component of a mirror to \a layout.
1997  * The \a layout will change it's current component pointer to
1998  * the newly added component, and it'll be turned into a composite
1999  * layout if it was not before the adding.
2000  *
2001  * \param[in] layout            existing composite or plain layout
2002  *
2003  * \retval      0 on success
2004  * \retval      <0 if error occurs
2005  */
2006 int llapi_layout_add_first_comp(struct llapi_layout *layout)
2007 {
2008         struct llapi_layout_comp *comp, *new;
2009
2010         comp = __llapi_layout_cur_comp(layout);
2011         if (comp == NULL)
2012                 return -1;
2013
2014         new = __llapi_comp_alloc(0);
2015         if (new == NULL)
2016                 return -1;
2017
2018         new->llc_extent.e_start = 0;
2019
2020         list_add_tail(&new->llc_list, &layout->llot_comp_list);
2021         layout->llot_cur_comp = new;
2022         layout->llot_is_composite = true;
2023
2024         return 0;
2025 }
2026
2027 /**
2028  * Deletes current component from the composite layout. The component
2029  * to be deleted must be the tail of components list, and it can't be
2030  * the only component in the layout.
2031  *
2032  * \param[in] layout    composite layout
2033  *
2034  * \retval      0 on success
2035  * \retval      <0 if error occurs
2036  */
2037 int llapi_layout_comp_del(struct llapi_layout *layout)
2038 {
2039         struct llapi_layout_comp *comp;
2040
2041         comp = __llapi_layout_cur_comp(layout);
2042         if (comp == NULL)
2043                 return -1;
2044
2045         if (!layout->llot_is_composite) {
2046                 errno = EINVAL;
2047                 return -1;
2048         }
2049
2050         /* It must be the tail of the list (for PFL, can be relaxed
2051          * once we get mirrored components) */
2052         if (comp->llc_list.next != &layout->llot_comp_list) {
2053                 errno = EINVAL;
2054                 return -1;
2055         }
2056         layout->llot_cur_comp =
2057                 list_entry(comp->llc_list.prev, typeof(*comp), llc_list);
2058         if (comp->llc_list.prev == &layout->llot_comp_list)
2059                 layout->llot_cur_comp = NULL;
2060
2061         list_del_init(&comp->llc_list);
2062         __llapi_comp_free(comp);
2063
2064         return 0;
2065 }
2066
2067 /**
2068  * Move the current component pointer to the component with
2069  * specified component ID.
2070  *
2071  * \param[in] layout    composite layout
2072  * \param[in] id        component ID
2073  *
2074  * \retval      =0 : moved successfully
2075  * \retval      <0 if error occurs
2076  */
2077 int llapi_layout_comp_use_id(struct llapi_layout *layout, uint32_t comp_id)
2078 {
2079         struct llapi_layout_comp *comp;
2080
2081         comp = __llapi_layout_cur_comp(layout);
2082         if (comp == NULL)
2083                 return -1; /* use previously set errno */
2084
2085         if (!layout->llot_is_composite) {
2086                 errno = EINVAL;
2087                 return -1;
2088         }
2089
2090         if (comp_id == LCME_ID_INVAL) {
2091                 errno = EINVAL;
2092                 return -1;
2093         }
2094
2095         list_for_each_entry(comp, &layout->llot_comp_list, llc_list) {
2096                 if (comp->llc_id == comp_id) {
2097                         layout->llot_cur_comp = comp;
2098                         return 0;
2099                 }
2100         }
2101         errno = ENOENT;
2102         return -1;
2103 }
2104
2105 /**
2106  * Move the current component pointer to a specified position.
2107  *
2108  * \param[in] layout    composite layout
2109  * \param[in] pos       the position to be moved, it can be:
2110  *                      LLAPI_LAYOUT_COMP_USE_FIRST: use first component
2111  *                      LLAPI_LAYOUT_COMP_USE_LAST: use last component
2112  *                      LLAPI_LAYOUT_COMP_USE_NEXT: use component after current
2113  *                      LLAPI_LAYOUT_COMP_USE_PREV: use component before current
2114  *
2115  * \retval      =0 : moved successfully
2116  * \retval      =1 : at last component with NEXT, at first component with PREV
2117  * \retval      <0 if error occurs
2118  */
2119 int llapi_layout_comp_use(struct llapi_layout *layout,
2120                           enum llapi_layout_comp_use pos)
2121 {
2122         struct llapi_layout_comp *comp, *head, *tail;
2123
2124         comp = __llapi_layout_cur_comp(layout);
2125         if (comp == NULL)
2126                 return -1;
2127
2128         if (!layout->llot_is_composite) {
2129                 if (pos == LLAPI_LAYOUT_COMP_USE_FIRST ||
2130                     pos == LLAPI_LAYOUT_COMP_USE_LAST)
2131                         return 0;
2132                 errno = ENOENT;
2133                 return 1;
2134         }
2135
2136         head = list_entry(layout->llot_comp_list.next, typeof(*head), llc_list);
2137         tail = list_entry(layout->llot_comp_list.prev, typeof(*tail), llc_list);
2138         switch (pos) {
2139         case LLAPI_LAYOUT_COMP_USE_FIRST:
2140                 layout->llot_cur_comp = head;
2141                 break;
2142         case LLAPI_LAYOUT_COMP_USE_NEXT:
2143                 if (comp == tail) {
2144                         errno = ENOENT;
2145                         return 1;
2146                 }
2147                 layout->llot_cur_comp = list_entry(comp->llc_list.next,
2148                                                    typeof(*comp), llc_list);
2149                 break;
2150         case LLAPI_LAYOUT_COMP_USE_LAST:
2151                 layout->llot_cur_comp = tail;
2152                 break;
2153         case LLAPI_LAYOUT_COMP_USE_PREV:
2154                 if (comp == head) {
2155                         errno = ENOENT;
2156                         return 1;
2157                 }
2158                 layout->llot_cur_comp = list_entry(comp->llc_list.prev,
2159                                                    typeof(*comp), llc_list);
2160                 break;
2161         default:
2162                 errno = EINVAL;
2163                 return -1;
2164         }
2165
2166         return 0;
2167 }
2168
2169 /**
2170  * Add layout component(s) to an existing file.
2171  *
2172  * \param[in] path      The path name of the file
2173  * \param[in] layout    The layout component(s) to be added
2174  */
2175 int llapi_layout_file_comp_add(const char *path,
2176                                const struct llapi_layout *layout)
2177 {
2178         int rc, fd = -1, lum_size, tmp_errno = 0;
2179         struct llapi_layout *existing_layout = NULL;
2180         struct lov_user_md *lum = NULL;
2181
2182         if (path == NULL || layout == NULL ||
2183             layout->llot_magic != LLAPI_LAYOUT_MAGIC) {
2184                 errno = EINVAL;
2185                 return -1;
2186         }
2187
2188         fd = open(path, O_RDWR);
2189         if (fd < 0) {
2190                 tmp_errno = errno;
2191                 rc = -1;
2192                 goto out;
2193         }
2194
2195         existing_layout = llapi_layout_get_by_fd(fd, 0);
2196         if (existing_layout == NULL) {
2197                 tmp_errno = errno;
2198                 rc = -1;
2199                 goto out;
2200         }
2201
2202         rc = llapi_layout_merge(&existing_layout, layout);
2203         if (rc) {
2204                 tmp_errno = errno;
2205                 rc = -1;
2206                 goto out;
2207         }
2208
2209         rc = llapi_layout_sanity(existing_layout, false, false);
2210         if (rc) {
2211                 tmp_errno = errno;
2212                 llapi_layout_sanity_perror(rc);
2213                 rc = -1;
2214                 goto out;
2215         }
2216
2217         lum = llapi_layout_to_lum(layout);
2218         if (lum == NULL) {
2219                 tmp_errno = errno;
2220                 rc = -1;
2221                 goto out;
2222         }
2223
2224         if (lum->lmm_magic != LOV_USER_MAGIC_COMP_V1) {
2225                 tmp_errno = EINVAL;
2226                 rc = -1;
2227                 goto out;
2228         }
2229         lum_size = ((struct lov_comp_md_v1 *)lum)->lcm_size;
2230
2231         rc = fsetxattr(fd, XATTR_LUSTRE_LOV".add", lum, lum_size, 0);
2232         if (rc < 0) {
2233                 tmp_errno = errno;
2234                 rc = -1;
2235                 goto out;
2236         }
2237 out:
2238         if (fd >= 0)
2239                 close(fd);
2240         free(lum);
2241         llapi_layout_free(existing_layout);
2242         errno = tmp_errno;
2243         return rc;
2244 }
2245
2246 /**
2247  * Delete component(s) by the specified component id or component flags
2248  * from an existing file.
2249  *
2250  * \param[in] path      path name of the file
2251  * \param[in] id        unique component ID
2252  * \param[in] flags     flags: LCME_FL_* or;
2253  *                      negative flags: (LCME_FL_NEG|LCME_FL_*)
2254  */
2255 int llapi_layout_file_comp_del(const char *path, uint32_t id, uint32_t flags)
2256 {
2257         int rc = 0, fd = -1, lum_size, tmp_errno = 0;
2258         struct llapi_layout *layout;
2259         struct llapi_layout_comp *comp, *next;
2260         struct llapi_layout *existing_layout = NULL;
2261         struct lov_user_md *lum = NULL;
2262
2263         if (path == NULL || id > LCME_ID_MAX || (flags & ~LCME_KNOWN_FLAGS)) {
2264                 errno = EINVAL;
2265                 return -1;
2266         }
2267
2268         /* Can only specify ID or flags, not both, not none. */
2269         if ((id != LCME_ID_INVAL && flags != 0) ||
2270             (id == LCME_ID_INVAL && flags == 0)) {
2271                 errno = EINVAL;
2272                 return -1;
2273         }
2274
2275         layout = llapi_layout_alloc();
2276         if (layout == NULL)
2277                 return -1;
2278
2279         llapi_layout_comp_extent_set(layout, 0, LUSTRE_EOF);
2280         comp = __llapi_layout_cur_comp(layout);
2281         if (comp == NULL) {
2282                 tmp_errno = errno;
2283                 rc = -1;
2284                 goto out;
2285         }
2286
2287         comp->llc_id = id;
2288         comp->llc_flags = flags;
2289
2290         lum = llapi_layout_to_lum(layout);
2291         if (lum == NULL) {
2292                 tmp_errno = errno;
2293                 rc = -1;
2294                 goto out;
2295         }
2296         lum_size = ((struct lov_comp_md_v1 *)lum)->lcm_size;
2297
2298         fd = open(path, O_RDWR);
2299         if (fd < 0) {
2300                 tmp_errno = errno;
2301                 rc = -1;
2302                 goto out;
2303         }
2304
2305         existing_layout = llapi_layout_get_by_fd(fd, 0);
2306         if (existing_layout == NULL) {
2307                 tmp_errno = errno;
2308                 rc = -1;
2309                 goto out;
2310         }
2311
2312         comp = NULL;
2313         next = NULL;
2314         while (rc == 0 && existing_layout->llot_cur_comp != NULL) {
2315                 rc = llapi_layout_comp_use(existing_layout, comp ?
2316                                            LLAPI_LAYOUT_COMP_USE_PREV :
2317                                            LLAPI_LAYOUT_COMP_USE_LAST);
2318                 if (rc != 0)
2319                         break;
2320
2321                 next = comp;
2322                 comp = __llapi_layout_cur_comp(existing_layout);
2323                 if (comp == NULL) {
2324                         rc = -1;
2325                         break;
2326                 }
2327
2328                 if (id != LCME_ID_INVAL && id != comp->llc_id)
2329                         continue;
2330                 else if ((flags & LCME_FL_NEG) && (flags & comp->llc_flags))
2331                         continue;
2332                 else if (flags && !(flags & comp->llc_flags))
2333                         continue;
2334
2335                 rc = llapi_layout_comp_del(existing_layout);
2336                 /* the layout position is moved to previous one, adjust */
2337                 comp = next;
2338         }
2339         if (rc < 0) {
2340                 tmp_errno = errno;
2341                 goto out;
2342         }
2343
2344         rc = llapi_layout_sanity(existing_layout, false, false);
2345         if (rc) {
2346                 tmp_errno = errno;
2347                 llapi_layout_sanity_perror(rc);
2348                 rc = -1;
2349                 goto out;
2350         }
2351
2352         rc = fsetxattr(fd, XATTR_LUSTRE_LOV".del", lum, lum_size, 0);
2353         if (rc < 0) {
2354                 tmp_errno = errno;
2355                 rc = -1;
2356                 goto out;
2357         }
2358
2359 out:
2360         if (fd >= 0)
2361                 close(fd);
2362         free(lum);
2363         llapi_layout_free(layout);
2364         llapi_layout_free(existing_layout);
2365         errno = tmp_errno;
2366
2367         return rc;
2368 }
2369
2370 /* Internal utility function to apply flags for sanity checking */
2371 static void llapi_layout_comp_apply_flags(struct llapi_layout_comp *comp,
2372                                           uint32_t flags)
2373 {
2374         if (flags & LCME_FL_NEG)
2375                 comp->llc_flags &= ~flags;
2376         else
2377                 comp->llc_flags |= flags;
2378 }
2379
2380 struct llapi_layout_apply_flags_args {
2381         uint32_t *lfa_ids;
2382         uint32_t *lfa_flags;
2383         int lfa_count;
2384         int lfa_rc;
2385 };
2386
2387
2388 static int llapi_layout_apply_flags_cb(struct llapi_layout *layout,
2389                                        void *arg)
2390 {
2391         struct llapi_layout_apply_flags_args *args = arg;
2392         struct llapi_layout_comp *comp;
2393         int i = 0;
2394
2395         comp = __llapi_layout_cur_comp(layout);
2396         if (comp == NULL) {
2397                 args->lfa_rc = -1;
2398                 return LLAPI_LAYOUT_ITER_STOP;
2399         }
2400
2401         for (i = 0; i < args->lfa_count; i++) {
2402                 if (comp->llc_id == args->lfa_ids[i])
2403                         llapi_layout_comp_apply_flags(comp, args->lfa_flags[i]);
2404         }
2405
2406         return LLAPI_LAYOUT_ITER_CONT;
2407 }
2408
2409 /* Apply flags to the layout for sanity checking */
2410 static int llapi_layout_apply_flags(struct llapi_layout *layout, uint32_t *ids,
2411                                     uint32_t *flags, int count)
2412 {
2413         struct llapi_layout_apply_flags_args args;
2414         int rc = 0;
2415
2416         if (!ids || !flags || count == 0) {
2417                 errno = EINVAL;
2418                 return -1;
2419         }
2420
2421         args.lfa_ids = ids;
2422         args.lfa_flags = flags;
2423         args.lfa_count = count;
2424         args.lfa_rc = 0;
2425
2426         rc = llapi_layout_comp_iterate(layout,
2427                                        llapi_layout_apply_flags_cb,
2428                                        &args);
2429         if (errno == ENOENT)
2430                 errno = 0;
2431
2432         if (rc != LLAPI_LAYOUT_ITER_CONT)
2433                 rc = args.lfa_rc;
2434
2435         return rc;
2436 }
2437 /**
2438  * Change flags by component ID of components of an existing file.
2439  * The component to be modified is specified by the comp->lcme_id value,
2440  * which must be a unique component ID.
2441  *
2442  * \param[in] path      path name of the file
2443  * \param[in] ids       An array of component IDs
2444  * \param[in] flags     flags: LCME_FL_* or;
2445  *                      negative flags: (LCME_FL_NEG|LCME_FL_*)
2446  * \param[in] count     Number of elements in ids and flags array
2447  */
2448 int llapi_layout_file_comp_set(const char *path, uint32_t *ids, uint32_t *flags,
2449                                size_t count)
2450 {
2451         int rc = -1, fd = -1, i, tmp_errno = 0;
2452         size_t lum_size;
2453         struct llapi_layout *existing_layout = NULL;
2454         struct llapi_layout *layout = NULL;
2455         struct llapi_layout_comp *comp;
2456         struct lov_user_md *lum = NULL;
2457
2458         if (path == NULL) {
2459                 errno = EINVAL;
2460                 return -1;
2461         }
2462
2463         if (!count)
2464                 return 0;
2465
2466         for (i = 0; i < count; i++) {
2467                 if (!ids[i] || !flags[i]) {
2468                         errno = EINVAL;
2469                         return -1;
2470                 }
2471
2472                 if (ids[i] > LCME_ID_MAX || (flags[i] & ~LCME_KNOWN_FLAGS)) {
2473                         errno = EINVAL;
2474                         return -1;
2475                 }
2476
2477                 /* do not allow to set or clear INIT flag */
2478                 if (flags[i] & LCME_FL_INIT) {
2479                         errno = EINVAL;
2480                         return -1;
2481                 }
2482         }
2483
2484         fd = open(path, O_RDWR);
2485         if (fd < 0) {
2486                 tmp_errno = errno;
2487                 rc = -1;
2488                 goto out;
2489         }
2490
2491         existing_layout = llapi_layout_get_by_fd(fd, 0);
2492         if (existing_layout == NULL) {
2493                 tmp_errno = errno;
2494                 rc = -1;
2495                 goto out;
2496         }
2497
2498         if (llapi_layout_apply_flags(existing_layout, ids, flags, count)) {
2499                 tmp_errno = errno;
2500                 rc = -1;
2501                 goto out;
2502         }
2503
2504         rc = llapi_layout_sanity(existing_layout, false, false);
2505         if (rc) {
2506                 tmp_errno = errno;
2507                 llapi_layout_sanity_perror(rc);
2508                 rc = -1;
2509                 goto out;
2510         }
2511
2512         layout = __llapi_layout_alloc();
2513         if (layout == NULL) {
2514                 tmp_errno = errno;
2515                 rc = -1;
2516                 goto out;
2517         }
2518
2519         layout->llot_is_composite = true;
2520         for (i = 0; i < count; i++) {
2521                 comp = __llapi_comp_alloc(0);
2522                 if (comp == NULL) {
2523                         tmp_errno = errno;
2524                         rc = -1;
2525                         goto out;
2526                 }
2527
2528                 comp->llc_id = ids[i];
2529                 comp->llc_flags = flags[i];
2530
2531                 list_add_tail(&comp->llc_list, &layout->llot_comp_list);
2532                 layout->llot_cur_comp = comp;
2533         }
2534
2535         lum = llapi_layout_to_lum(layout);
2536         if (lum == NULL) {
2537                 tmp_errno = errno;
2538                 rc = -1;
2539                 goto out;
2540         }
2541
2542         lum_size = ((struct lov_comp_md_v1 *)lum)->lcm_size;
2543
2544         /* flush cached pages from clients */
2545         rc = llapi_file_flush(fd);
2546         if (rc) {
2547                 tmp_errno = -rc;
2548                 rc = -1;
2549                 goto out;
2550         }
2551
2552         rc = fsetxattr(fd, XATTR_LUSTRE_LOV".set.flags", lum, lum_size, 0);
2553         if (rc < 0) {
2554                 tmp_errno = errno;
2555                 goto out;
2556         }
2557
2558         rc = 0;
2559
2560 out:
2561         if (fd >= 0)
2562                 close(fd);
2563
2564         free(lum);
2565         llapi_layout_free(existing_layout);
2566         llapi_layout_free(layout);
2567         errno = tmp_errno;
2568         return rc;
2569 }
2570
2571 /**
2572  * Check if the file layout is composite.
2573  *
2574  * \param[in] layout    the file layout to check
2575  *
2576  * \retval true         composite
2577  * \retval false        not composite
2578  */
2579 bool llapi_layout_is_composite(struct llapi_layout *layout)
2580 {
2581         return layout->llot_is_composite;
2582 }
2583
2584 /**
2585  * Iterate every components in the @layout and call callback function @cb.
2586  *
2587  * \param[in] layout    component layout list.
2588  * \param[in] cb        callback for each component
2589  * \param[in] cbdata    callback data
2590  *
2591  * \retval < 0                          error happens during the iteration
2592  * \retval LLAPI_LAYOUT_ITER_CONT       finished the iteration w/o error
2593  * \retval LLAPI_LAYOUT_ITER_STOP       got something, stop the iteration
2594  */
2595 int llapi_layout_comp_iterate(struct llapi_layout *layout,
2596                               llapi_layout_iter_cb cb, void *cbdata)
2597 {
2598         int rc;
2599
2600         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
2601         if (rc < 0)
2602                 return rc;
2603
2604         /**
2605          * make sure on success llapi_layout_comp_use() API returns 0 with
2606          * USE_FIRST.
2607          */
2608         assert(rc == 0);
2609
2610         while (1) {
2611                 rc = cb(layout, cbdata);
2612                 if (rc != LLAPI_LAYOUT_ITER_CONT)
2613                         break;
2614
2615                 rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_NEXT);
2616                 if (rc < 0)
2617                         return rc;
2618                 else if (rc == 1)       /* reached the last comp */
2619                         return LLAPI_LAYOUT_ITER_CONT;
2620         }
2621
2622         return rc;
2623 }
2624
2625 /**
2626  * llapi_layout_merge() - Merge a composite layout into another one.
2627  * @dst_layout: Destination composite layout.
2628  * @src_layout: Source composite layout.
2629  *
2630  * This function copies all of the components from @src_layout and
2631  * appends them to @dst_layout.
2632  *
2633  * Return: 0 on success or -1 on failure.
2634  */
2635 int llapi_layout_merge(struct llapi_layout **dst_layout,
2636                        const struct llapi_layout *src_layout)
2637 {
2638         struct llapi_layout *new_layout = *dst_layout;
2639         struct llapi_layout_comp *new = NULL;
2640         struct llapi_layout_comp *comp = NULL;
2641         int i = 0;
2642
2643         if (src_layout == NULL ||
2644             list_empty((struct list_head *)&src_layout->llot_comp_list))
2645                 return 0;
2646
2647         if (new_layout == NULL) {
2648                 new_layout = __llapi_layout_alloc();
2649                 if (new_layout == NULL) {
2650                         errno = ENOMEM;
2651                         return -1;
2652                 }
2653         }
2654
2655         list_for_each_entry(comp, &src_layout->llot_comp_list, llc_list) {
2656                 new = __llapi_comp_alloc(0);
2657                 if (new == NULL) {
2658                         errno = ENOMEM;
2659                         goto error;
2660                 }
2661
2662                 new->llc_pattern = comp->llc_pattern;
2663                 new->llc_stripe_size = comp->llc_stripe_size;
2664                 new->llc_stripe_count = comp->llc_stripe_count;
2665                 new->llc_stripe_offset = comp->llc_stripe_offset;
2666
2667                 if (comp->llc_pool_name[0] != '\0')
2668                         strncpy(new->llc_pool_name, comp->llc_pool_name,
2669                                 sizeof(new->llc_pool_name));
2670
2671                 for (i = 0; i < comp->llc_objects_count; i++) {
2672                         if (__llapi_comp_objects_realloc(new,
2673                             stripe_number_roundup(i)) < 0) {
2674                                 errno = EINVAL;
2675                                 __llapi_comp_free(new);
2676                                 goto error;
2677                         }
2678                         new->llc_objects[i].l_ost_idx = \
2679                                 comp->llc_objects[i].l_ost_idx;
2680                 }
2681
2682                 new->llc_objects_count = comp->llc_objects_count;
2683                 new->llc_extent.e_start = comp->llc_extent.e_start;
2684                 new->llc_extent.e_end = comp->llc_extent.e_end;
2685                 new->llc_id = comp->llc_id;
2686                 new->llc_flags = comp->llc_flags;
2687
2688                 list_add_tail(&new->llc_list, &new_layout->llot_comp_list);
2689                 new_layout->llot_cur_comp = new;
2690         }
2691         new_layout->llot_is_composite = true;
2692
2693         *dst_layout = new_layout;
2694         return 0;
2695 error:
2696         llapi_layout_free(new_layout);
2697         return -1;
2698 }
2699
2700 /**
2701  * Find all stale components.
2702  *
2703  * \param[in] layout            component layout list.
2704  * \param[out] comp             array of stale component info.
2705  * \param[in] comp_size         array size of @comp.
2706  * \param[in] mirror_ids        array of mirror id that only components
2707  *                              belonging to these mirror will be collected.
2708  * \param[in] ids_nr            number of mirror ids array.
2709  *
2710  * \retval              number of component info collected on sucess or
2711  *                      an error code on failure.
2712  */
2713 int llapi_mirror_find_stale(struct llapi_layout *layout,
2714                 struct llapi_resync_comp *comp, size_t comp_size,
2715                 __u16 *mirror_ids, int ids_nr)
2716 {
2717         int idx = 0;
2718         int rc;
2719
2720         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
2721         if (rc < 0)
2722                 goto error;
2723
2724         while (rc == 0) {
2725                 uint32_t id;
2726                 uint32_t mirror_id;
2727                 uint32_t flags;
2728                 uint64_t start, end;
2729
2730                 rc = llapi_layout_comp_flags_get(layout, &flags);
2731                 if (rc < 0)
2732                         goto error;
2733
2734                 if (!(flags & LCME_FL_STALE))
2735                         goto next;
2736
2737                 rc = llapi_layout_mirror_id_get(layout, &mirror_id);
2738                 if (rc < 0)
2739                         goto error;
2740
2741                 /* the caller only wants stale components from specific
2742                  * mirrors */
2743                 if (ids_nr > 0) {
2744                         int j;
2745
2746                         for (j = 0; j < ids_nr; j++) {
2747                                 if (mirror_ids[j] == mirror_id)
2748                                         break;
2749                         }
2750
2751                         /* not in the specified mirror */
2752                         if (j == ids_nr)
2753                                 goto next;
2754                 } else if (flags & LCME_FL_NOSYNC) {
2755                         /* if not specified mirrors, do not resync "nosync"
2756                          * mirrors */
2757                         goto next;
2758                 }
2759
2760                 rc = llapi_layout_comp_id_get(layout, &id);
2761                 if (rc < 0)
2762                         goto error;
2763
2764                 rc = llapi_layout_comp_extent_get(layout, &start, &end);
2765                 if (rc < 0)
2766                         goto error;
2767
2768                 /* pack this component into @comp array */
2769                 comp[idx].lrc_id = id;
2770                 comp[idx].lrc_mirror_id = mirror_id;
2771                 comp[idx].lrc_start = start;
2772                 comp[idx].lrc_end = end;
2773                 idx++;
2774
2775                 if (idx >= comp_size) {
2776                         rc = -EINVAL;
2777                         goto error;
2778                 }
2779
2780         next:
2781                 rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_NEXT);
2782                 if (rc < 0) {
2783                         rc = -EINVAL;
2784                         goto error;
2785                 }
2786         }
2787 error:
2788         return rc < 0 ? rc : idx;
2789 }
2790
2791 /* locate @layout to a valid component covering file [file_start, file_end) */
2792 uint32_t llapi_mirror_find(struct llapi_layout *layout,
2793                            uint64_t file_start, uint64_t file_end,
2794                            uint64_t *endp)
2795 {
2796         uint32_t mirror_id = 0;
2797         int rc;
2798
2799         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
2800         if (rc < 0)
2801                 return rc;
2802
2803         *endp = 0;
2804         while (rc == 0) {
2805                 uint64_t start, end;
2806                 uint32_t flags, id, rid;
2807
2808                 rc = llapi_layout_comp_flags_get(layout, &flags);
2809                 if (rc < 0)
2810                         return rc;
2811
2812                 if (flags & LCME_FL_STALE)
2813                         goto next;
2814
2815                 rc = llapi_layout_mirror_id_get(layout, &rid);
2816                 if (rc < 0)
2817                         return rc;
2818
2819                 rc = llapi_layout_comp_id_get(layout, &id);
2820                 if (rc < 0)
2821                         return rc;
2822
2823                 rc = llapi_layout_comp_extent_get(layout, &start, &end);
2824                 if (rc < 0)
2825                         return rc;
2826
2827                 if (file_start >= start && file_start < end) {
2828                         if (!mirror_id)
2829                                 mirror_id = rid;
2830                         else if (mirror_id != rid || *endp != start)
2831                                 break;
2832
2833                         file_start = *endp = end;
2834                         if (end >= file_end)
2835                                 break;
2836                 }
2837
2838         next:
2839                 rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_NEXT);
2840                 if (rc < 0)
2841                         return rc;
2842         }
2843
2844         return mirror_id;
2845 }
2846
2847 int llapi_mirror_resync_many(int fd, struct llapi_layout *layout,
2848                              struct llapi_resync_comp *comp_array,
2849                              int comp_size,  uint64_t start, uint64_t end)
2850 {
2851         uint64_t count;
2852         size_t page_size = sysconf(_SC_PAGESIZE);
2853         const size_t buflen = 4 << 20; /* 4M */
2854         void *buf;
2855         uint64_t pos = start;
2856         int i;
2857         int rc;
2858         int rc2 = 0;
2859
2860         rc = posix_memalign(&buf, page_size, buflen);
2861         if (rc)
2862                 return -rc;
2863
2864         if (end == OBD_OBJECT_EOF)
2865                 count = OBD_OBJECT_EOF;
2866         else
2867                 count = end - start;
2868
2869         while (count > 0) {
2870                 uint32_t src;
2871                 uint64_t mirror_end = 0;
2872                 uint64_t bytes_left;
2873                 ssize_t bytes_read;
2874                 size_t to_read;
2875                 size_t to_write;
2876
2877                 src = llapi_mirror_find(layout, pos, end, &mirror_end);
2878                 if (src == 0)
2879                         return -ENOENT;
2880
2881                 if (mirror_end == OBD_OBJECT_EOF) {
2882                         bytes_left = count;
2883                 } else {
2884                         bytes_left = MIN(count, mirror_end - pos);
2885                         bytes_left = ((bytes_left - 1) | (page_size - 1)) + 1;
2886                 }
2887                 to_read = MIN(buflen, bytes_left);
2888
2889                 bytes_read = llapi_mirror_read(fd, src, buf, to_read, pos);
2890                 if (bytes_read == 0) {
2891                         /* end of file */
2892                         break;
2893                 }
2894                 if (bytes_read < 0) {
2895                         rc = bytes_read;
2896                         break;
2897                 }
2898
2899                 /* round up to page align to make direct IO happy. */
2900                 to_write = ((bytes_read - 1) | (page_size - 1)) + 1;
2901
2902                 for (i = 0; i < comp_size; i++) {
2903                         ssize_t written;
2904                         off_t pos2 = pos;
2905                         size_t to_write2 = to_write;
2906
2907                         /* skip non-overlapped component */
2908                         if (pos >= comp_array[i].lrc_end ||
2909                             pos + to_write <= comp_array[i].lrc_start)
2910                                 continue;
2911
2912                         if (pos < comp_array[i].lrc_start)
2913                                 pos2 = comp_array[i].lrc_start;
2914
2915                         to_write2 -= pos2 - pos;
2916
2917                         if ((pos + to_write) > comp_array[i].lrc_end)
2918                                 to_write2 -= pos + to_write -
2919                                              comp_array[i].lrc_end;
2920
2921                         written = llapi_mirror_write(fd,
2922                                         comp_array[i].lrc_mirror_id,
2923                                         buf + pos2 - pos,
2924                                         to_write2, pos2);
2925                         if (written < 0) {
2926                                 /**
2927                                  * this component is not written successfully,
2928                                  * mark it using its lrc_synced, it is supposed
2929                                  * to be false before getting here.
2930                                  *
2931                                  * And before this function returns, all
2932                                  * elements of comp_array will reverse their
2933                                  * lrc_synced flag to reflect their true
2934                                  * meanings.
2935                                  */
2936                                 comp_array[i].lrc_synced = true;
2937                                 llapi_error(LLAPI_MSG_ERROR, written,
2938                                             "component %u not synced\n",
2939                                             comp_array[i].lrc_id);
2940                                 if (rc2 == 0)
2941                                         rc2 = (int)written;
2942                                 continue;
2943                         }
2944                         assert(written == to_write2);
2945                 }
2946
2947                 pos += bytes_read;
2948                 count -= bytes_read;
2949         }
2950
2951         free(buf);
2952
2953         if (rc < 0) {
2954                 /* fatal error happens */
2955                 for (i = 0; i < comp_size; i++)
2956                         comp_array[i].lrc_synced = false;
2957                 return rc;
2958         }
2959
2960         /**
2961          * no fatal error happens, each lrc_synced tells whether the component
2962          * has been resync successfully (note: we'd reverse the value to
2963          * reflect its true meaning.
2964          */
2965         for (i = 0; i < comp_size; i++) {
2966                 comp_array[i].lrc_synced = !comp_array[i].lrc_synced;
2967                 if (comp_array[i].lrc_synced && pos & (page_size - 1)) {
2968                         rc = llapi_mirror_truncate(fd,
2969                                         comp_array[i].lrc_mirror_id, pos);
2970                         if (rc < 0)
2971                                 comp_array[i].lrc_synced = false;
2972                 }
2973         }
2974
2975         /**
2976          * returns the first error code for partially successful resync if
2977          * possible.
2978          */
2979         return rc2;
2980 }
2981
2982 enum llapi_layout_comp_sanity_error {
2983         LSE_OK,
2984         LSE_INCOMPLETE_MIRROR,
2985         LSE_ADJACENT_EXTENSION,
2986         LSE_INIT_EXTENSION,
2987         LSE_FLAGS,
2988         LSE_DOM_EXTENSION,
2989         LSE_DOM_EXTENSION_FOLLOWING,
2990         LSE_DOM_FIRST,
2991         LSE_SET_COMP_START,
2992         LSE_NOT_ZERO_LENGTH_EXTENDABLE,
2993         LSE_END_NOT_GREATER,
2994         LSE_ZERO_LENGTH_NORMAL,
2995         LSE_NOT_ADJACENT_PREV,
2996         LSE_START_GT_END,
2997         LSE_ALIGN_END,
2998         LSE_ALIGN_EXT,
2999         LSE_LAST,
3000 };
3001
3002 const char *llapi_layout_strerror[] =
3003 {
3004         [LSE_OK] = "",
3005         [LSE_INCOMPLETE_MIRROR] =
3006                 "Incomplete mirror - must go to EOF",
3007         [LSE_ADJACENT_EXTENSION] =
3008                 "No adjacent extension space components",
3009         [LSE_INIT_EXTENSION] =
3010                 "Cannot apply extension flag to init components",
3011         [LSE_FLAGS] =
3012                 "Wrong flags",
3013         [LSE_DOM_EXTENSION] =
3014                 "DoM components can't be extension space",
3015         [LSE_DOM_EXTENSION_FOLLOWING] =
3016                 "DoM components cannot be followed by extension space",
3017         [LSE_DOM_FIRST] =
3018                 "DoM component should be the first one in a file/mirror",
3019         [LSE_SET_COMP_START] =
3020                 "Must set previous component extent before adding next",
3021         [LSE_NOT_ZERO_LENGTH_EXTENDABLE] =
3022                 "Extendable component must start out zero-length",
3023         [LSE_END_NOT_GREATER] =
3024                 "Component end is before end of previous component",
3025         [LSE_ZERO_LENGTH_NORMAL] =
3026                 "Zero length components must be followed by extension",
3027         [LSE_NOT_ADJACENT_PREV] =
3028                 "Components not adjacent (end != next->start",
3029         [LSE_START_GT_END] =
3030                 "Component start is > end",
3031         [LSE_ALIGN_END] =
3032                 "The component end must be aligned by the stripe size",
3033         [LSE_ALIGN_EXT] =
3034                 "The extension size must be aligned by the stripe size",
3035 };
3036
3037 struct llapi_layout_sanity_args {
3038         bool lsa_incomplete;
3039         bool lsa_flr;
3040         bool lsa_ondisk;
3041         int lsa_rc;
3042 };
3043
3044 static int llapi_layout_sanity_cb(struct llapi_layout *layout,
3045                                   void *arg)
3046 {
3047         struct llapi_layout_comp *comp, *next, *prev;
3048         struct llapi_layout_sanity_args *args = arg;
3049         bool first_comp = false;
3050
3051         comp = __llapi_layout_cur_comp(layout);
3052         if (comp == NULL) {
3053                 args->lsa_rc = -1;
3054                 goto out_err;
3055         }
3056
3057         if (comp->llc_list.prev != &layout->llot_comp_list)
3058                 prev = list_entry(comp->llc_list.prev, typeof(*prev),
3059                                   llc_list);
3060         else
3061                 prev = NULL;
3062
3063         if (comp->llc_list.next != &layout->llot_comp_list)
3064                 next = list_entry(comp->llc_list.next, typeof(*next),
3065                                   llc_list);
3066         else
3067                 next = NULL;
3068
3069         /* Start of zero implies a new mirror */
3070         if (comp->llc_extent.e_start == 0) {
3071                 first_comp = true;
3072                 /* Most checks apply only within one mirror, this is an
3073                  * exception. */
3074                 if (prev && prev->llc_extent.e_end != LUSTRE_EOF) {
3075                         args->lsa_rc = LSE_INCOMPLETE_MIRROR;
3076                         goto out_err;
3077                 }
3078
3079                 prev = NULL;
3080         }
3081
3082         if (next && next->llc_extent.e_start == 0)
3083                 next = NULL;
3084
3085         /* Flag sanity checks */
3086         /* No adjacent extension components */
3087         if ((comp->llc_flags & LCME_FL_EXTENSION) && next &&
3088             (next->llc_flags & LCME_FL_EXTENSION)) {
3089                 args->lsa_rc = LSE_ADJACENT_EXTENSION;
3090                 goto out_err;
3091         }
3092
3093         /* Extension flag cannot be applied to init components and the first
3094          * component of each mirror is automatically init */
3095         if ((comp->llc_flags & LCME_FL_EXTENSION) &&
3096             (comp->llc_flags & LCME_FL_INIT || first_comp)) {
3097                 args->lsa_rc = LSE_INIT_EXTENSION;
3098                 goto out_err;
3099         }
3100
3101         if (comp->llc_ondisk) {
3102                 if (comp->llc_flags & LCME_FL_NEG)
3103                         args->lsa_rc = LSE_FLAGS;
3104         } else if (!args->lsa_incomplete) {
3105                 if (args->lsa_flr) {
3106                         if (comp->llc_flags & ~LCME_USER_COMP_FLAGS)
3107                                 args->lsa_rc = LSE_FLAGS;
3108                 } else {
3109                         if (comp->llc_flags & ~LCME_FL_EXTENSION)
3110                                 args->lsa_rc = LSE_FLAGS;
3111                 }
3112         }
3113         if (args->lsa_rc)
3114                 goto out_err;
3115
3116         /* DoM sanity checks */
3117         if (comp->llc_pattern == LLAPI_LAYOUT_MDT ||
3118             comp->llc_pattern == LOV_PATTERN_MDT) {
3119                 /* DoM components can't be extension components */
3120                 if (comp->llc_flags & LCME_FL_EXTENSION) {
3121                         args->lsa_rc = LSE_DOM_EXTENSION;
3122                         goto out_err;
3123                 }
3124                 /* DoM components cannot be followed by an extension comp */
3125                 if (next && (next->llc_flags & LCME_FL_EXTENSION)) {
3126                         args->lsa_rc = LSE_DOM_EXTENSION_FOLLOWING;
3127                         goto out_err;
3128                 }
3129
3130                 /* DoM should be the first component in a mirror */
3131                 if (!first_comp) {
3132                         args->lsa_rc = LSE_DOM_FIRST;
3133                         errno = EINVAL;
3134                         goto out_err;
3135                 }
3136         }
3137
3138         /* Extent sanity checks */
3139         /* Must set previous component extent before adding another */
3140         if (prev && prev->llc_extent.e_start == 0 &&
3141             prev->llc_extent.e_end == 0) {
3142                 args->lsa_rc = LSE_SET_COMP_START;
3143                 goto out_err;
3144         }
3145
3146         if (!args->lsa_incomplete) {
3147                 /* Components followed by extension space (extendable
3148                  * components) must be zero length before initialization.
3149                  * (Except for first comp, which will be initialized on
3150                  * creation). */
3151                 if (next && (next->llc_flags & LCME_FL_EXTENSION) &&
3152                     !first_comp && !(comp->llc_flags & LCME_FL_INIT) &&
3153                     comp->llc_extent.e_start != comp->llc_extent.e_end) {
3154                         args->lsa_rc = LSE_NOT_ZERO_LENGTH_EXTENDABLE;
3155                         goto out_err;
3156                 }
3157
3158                 /* End must come after end of previous comp */
3159                 if (prev && comp->llc_extent.e_end < prev->llc_extent.e_end) {
3160                         args->lsa_rc = LSE_END_NOT_GREATER;
3161                         goto out_err;
3162                 }
3163
3164                 /* Components not followed by ext space must have length > 0. */
3165                 if (comp->llc_extent.e_start == comp->llc_extent.e_end &&
3166                     (next == NULL || !(next->llc_flags & LCME_FL_EXTENSION))) {
3167                         args->lsa_rc = LSE_ZERO_LENGTH_NORMAL;
3168                         goto out_err;
3169                 }
3170
3171                 /* The component end must be aligned by the stripe size */
3172                 if ((comp->llc_flags & LCME_FL_EXTENSION) &&
3173                     (prev->llc_stripe_size != LLAPI_LAYOUT_DEFAULT)) {
3174                         if (comp->llc_extent.e_end != LUSTRE_EOF &&
3175                             comp->llc_extent.e_end % prev->llc_stripe_size) {
3176                                 args->lsa_rc = LSE_ALIGN_END;
3177                                 goto out_err;
3178                         }
3179                         if ((comp->llc_stripe_size * SEL_UNIT_SIZE) %
3180                             prev->llc_stripe_size) {
3181                                 args->lsa_rc = LSE_ALIGN_EXT;
3182                                 goto out_err;
3183                         }
3184                 } else if (!(comp->llc_flags & LCME_FL_EXTENSION) &&
3185                            (comp->llc_stripe_size != LLAPI_LAYOUT_DEFAULT)) {
3186                         if (comp->llc_extent.e_end != LUSTRE_EOF &&
3187                             comp->llc_extent.e_end % comp->llc_stripe_size) {
3188                                 args->lsa_rc = LSE_ALIGN_END;
3189                                 goto out_err;
3190                         }
3191                 }
3192         }
3193
3194         /* Components must have start == prev->end */
3195         if (prev && comp->llc_extent.e_start != 0 &&
3196             comp->llc_extent.e_start != prev->llc_extent.e_end) {
3197                 args->lsa_rc = LSE_NOT_ADJACENT_PREV;
3198                 goto out_err;
3199         }
3200
3201         /* Components must have start <= end */
3202         if (comp->llc_extent.e_start > comp->llc_extent.e_end) {
3203                 args->lsa_rc = LSE_START_GT_END;
3204                 goto out_err;
3205         }
3206
3207         return LLAPI_LAYOUT_ITER_CONT;
3208
3209 out_err:
3210         errno = errno ? errno : EINVAL;
3211         return LLAPI_LAYOUT_ITER_STOP;
3212 }
3213
3214 /* Print explanation of layout error */
3215 void llapi_layout_sanity_perror(int error)
3216 {
3217         if (error >= LSE_LAST || error < 0) {
3218                 fprintf(stdout, "Invalid layout, unrecognized error: %d\n",
3219                         error);
3220         } else {
3221                 fprintf(stdout, "Invalid layout: %s\n",
3222                         llapi_layout_strerror[error]);
3223         }
3224 }
3225
3226 /* Walk a layout and enforce sanity checks that apply to > 1 component
3227  *
3228  * The core idea here is that of sanity checking individual tokens vs semantic
3229  * checking.
3230  * We cannot check everything at the individual component level ('token'),
3231  * instead we must check whether or not the full layout has a valid meaning.
3232  *
3233  * An example of a component level check is "is stripe size valid?".  That is
3234  * handled when setting stripe size.
3235  *
3236  * An example of a layout level check is "are the extents of these components
3237  * valid when adjacent to one another", or "can we set these flags on adjacent
3238  * components"?
3239  *
3240  * \param[in] layout            component layout list.
3241  * \param[in] incomplete        if layout is complete or not - some checks can
3242  *                              only be done on complete layouts.
3243  * \param[in] flr               set when this is called from FLR mirror create
3244  *
3245  * \retval                      0, success, positive: various errors, see
3246  *                              llapi_layout_sanity_perror, -1, failure
3247  */
3248 int llapi_layout_sanity(struct llapi_layout *layout, bool incomplete, bool flr)
3249 {
3250         struct llapi_layout_sanity_args args;
3251         struct llapi_layout_comp *curr;
3252         int rc = 0;
3253
3254         if (!layout)
3255                 return 0;
3256
3257         curr = layout->llot_cur_comp;
3258         if (!curr)
3259                 return 0;
3260
3261         /* Set up args */
3262         args.lsa_rc = 0;
3263         args.lsa_flr = flr;
3264         args.lsa_incomplete = incomplete;
3265
3266         /* When we modify an existing layout, this tells us if it's FLR */
3267         if (mirror_id_of(curr->llc_id) > 0)
3268                 args.lsa_flr = true;
3269
3270         errno = 0;
3271         rc = llapi_layout_comp_iterate(layout,
3272                                        llapi_layout_sanity_cb,
3273                                        &args);
3274         if (errno == ENOENT)
3275                 errno = 0;
3276
3277         if (rc != LLAPI_LAYOUT_ITER_CONT)
3278                 rc = args.lsa_rc;
3279
3280         layout->llot_cur_comp = curr;
3281
3282         return rc;
3283 }
3284
3285 int llapi_layout_dom_size(struct llapi_layout *layout, uint64_t *size)
3286 {
3287         uint64_t pattern, start;
3288         int rc;
3289
3290         if (!layout || !llapi_layout_is_composite(layout)) {
3291                 *size = 0;
3292                 return 0;
3293         }
3294
3295         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
3296         if (rc)
3297                 return -errno;
3298
3299         rc = llapi_layout_pattern_get(layout, &pattern);
3300         if (rc)
3301                 return -errno;
3302
3303         if (pattern != LOV_PATTERN_MDT && pattern != LLAPI_LAYOUT_MDT) {
3304                 *size = 0;
3305                 return 0;
3306         }
3307
3308         rc = llapi_layout_comp_extent_get(layout, &start, size);
3309         if (rc)
3310                 return -errno;
3311         if (start)
3312                 return -ERANGE;
3313         return 0;
3314 }
3315
3316 int lov_comp_md_size(struct lov_comp_md_v1 *lcm)
3317 {
3318         if (lcm->lcm_magic == LOV_MAGIC_V1 || lcm->lcm_magic == LOV_MAGIC_V3) {
3319                 struct lov_user_md *lum = (void *)lcm;
3320
3321                 return lov_user_md_size(lum->lmm_stripe_count, lum->lmm_magic);
3322         }
3323
3324         if (lcm->lcm_magic == LOV_MAGIC_FOREIGN) {
3325                 struct lov_foreign_md *lfm = (void *)lcm;
3326
3327                 return lfm->lfm_length;
3328         }
3329
3330         if (lcm->lcm_magic != LOV_MAGIC_COMP_V1)
3331                 return -EOPNOTSUPP;
3332
3333         return lcm->lcm_size;
3334 }
3335
3336 int llapi_get_lum_file_fd(int dir_fd, const char *fname, __u64 *valid,
3337                           lstatx_t *statx, struct lov_user_md *lum,
3338                           size_t lumsize)
3339 {
3340         struct lov_user_mds_data *lmd;
3341         char buf[65536 + offsetof(typeof(*lmd), lmd_lmm)];
3342         int parent_fd = -1;
3343         int rc;
3344
3345         if (lum && lumsize < sizeof(*lum))
3346                 return -EINVAL;
3347
3348         /* If a file name is provided, it is relative to the parent directory */
3349         if (fname) {
3350                 parent_fd = dir_fd;
3351                 dir_fd = -1;
3352         }
3353
3354         lmd = (struct lov_user_mds_data *)buf;
3355         rc = get_lmd_info_fd(fname, parent_fd, dir_fd, buf, sizeof(buf),
3356                              GET_LMD_INFO);
3357         if (rc)
3358                 return rc;
3359
3360         *valid = lmd->lmd_flags;
3361         if (statx)
3362                 memcpy(statx, &lmd->lmd_stx, sizeof(*statx));
3363
3364         if (lum) {
3365                 if (lmd->lmd_lmmsize > lumsize)
3366                         return -EOVERFLOW;
3367                 memcpy(lum, &lmd->lmd_lmm, lmd->lmd_lmmsize);
3368         }
3369
3370         return 0;
3371 }
3372
3373 int llapi_get_lum_dir_fd(int dir_fd, __u64 *valid, lstatx_t *statx,
3374                          struct lov_user_md *lum, size_t lumsize)
3375 {
3376         return llapi_get_lum_file_fd(dir_fd, NULL, valid, statx, lum, lumsize);
3377 }
3378
3379 int llapi_get_lum_file(const char *path, __u64 *valid, lstatx_t *statx,
3380                        struct lov_user_md *lum, size_t lumsize)
3381 {
3382         char parent[PATH_MAX];
3383         const char *fname;
3384         char *tmp;
3385         int offset;
3386         int dir_fd;
3387         int rc;
3388
3389         tmp = strrchr(path, '/');
3390         if (!tmp) {
3391                 strncpy(parent, ".", sizeof(parent) - 1);
3392                 offset = -1;
3393         } else {
3394                 strncpy(parent, path, tmp - path);
3395                 offset = tmp - path - 1;
3396                 parent[tmp - path] = 0;
3397         }
3398
3399         fname = path;
3400         if (offset >= 0)
3401                 fname += offset + 2;
3402
3403         dir_fd = open(parent, O_RDONLY);
3404         if (dir_fd < 0) {
3405                 rc = -errno;
3406                 llapi_error(LLAPI_MSG_ERROR, rc, "cannot open '%s'", path);
3407                 return rc;
3408         }
3409
3410         rc = llapi_get_lum_file_fd(dir_fd, fname, valid, statx, lum, lumsize);
3411         close(dir_fd);
3412         return rc;
3413 }
3414
3415 int llapi_get_lum_dir(const char *path, __u64 *valid, lstatx_t *statx,
3416                       struct lov_user_md *lum, size_t lumsize)
3417 {
3418         int dir_fd;
3419         int rc;
3420
3421         dir_fd = open(path, O_RDONLY);
3422         if (dir_fd < 0) {
3423                 rc = -errno;
3424                 llapi_error(LLAPI_MSG_ERROR, rc, "cannot open '%s'", path);
3425                 return rc;
3426         }
3427
3428         rc = llapi_get_lum_dir_fd(dir_fd, valid, statx, lum, lumsize);
3429         close(dir_fd);
3430         return rc;
3431 }