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