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