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