Whamcloud - gitweb
LU-16974 utils: make bandwidth options consistent
[fs/lustre-release.git] / lustre / lod / lod_lov.c
1 // SPDX-License-Identifier: GPL-2.0
2
3 /*
4  * Copyright  2009 Sun Microsystems, Inc. All rights reserved
5  * Use is subject to license terms.
6  *
7  * Copyright (c) 2012, 2017, Intel Corporation.
8  */
9
10 /*
11  * A set of helpers to maintain Logical Object Volume (LOV)
12  * Extended Attribute (EA) and known OST targets
13  *
14  * Author: Alex Zhuravlev <alexey.zhuravlev@intel.com>
15  */
16
17 #define DEBUG_SUBSYSTEM S_MDS
18
19 #include <obd_class.h>
20 #include <lustre_lfsck.h>
21 #include <lustre_lmv.h>
22 #include <lustre_swab.h>
23
24 #include "lod_internal.h"
25
26 /**
27  * lod_getref() - Increase reference count on the target table
28  * @ltd: target table (lod_ost_descs or lod_mdt_descs)
29  *
30  * Increase reference count on the target table usage to prevent racing with
31  * addition/deletion. Any function that expects the table to remain
32  * stationary must take a ref.
33  */
34 void lod_getref(struct lod_tgt_descs *ltd)
35 {
36         down_read(&ltd->ltd_rw_sem);
37         mutex_lock(&ltd->ltd_mutex);
38         atomic_inc(&ltd->ltd_refcount);
39         mutex_unlock(&ltd->ltd_mutex);
40 }
41
42 /**
43  * lod_putref() - Decrease reference count on the target table.
44  * @lod: LOD device from which we release a reference
45  * @ltd: target table (lod_ost_descs or lod_mdt_descs)
46  *
47  * Companion of lod_getref() to release a reference on the target table.
48  * If this is the last reference and the OST entry was scheduled for deletion,
49  * the descriptor is removed from the table.
50  */
51 void lod_putref(struct lod_device *lod, struct lod_tgt_descs *ltd)
52 {
53         mutex_lock(&ltd->ltd_mutex);
54         if (atomic_dec_and_test(&ltd->ltd_refcount) && ltd->ltd_death_row) {
55                 struct lod_tgt_desc *tgt_desc, *tmp;
56                 LIST_HEAD(kill);
57
58                 CDEBUG(D_CONFIG, "destroying %d ltd desc\n",
59                        ltd->ltd_death_row);
60
61                 ltd_foreach_tgt_safe(ltd, tgt_desc, tmp) {
62                         LASSERT(tgt_desc);
63                         if (!tgt_desc->ltd_reap)
64                                 continue;
65
66                         list_add(&tgt_desc->ltd_kill, &kill);
67                         lu_tgt_pool_remove(&ltd->ltd_tgt_pool,
68                                            tgt_desc->ltd_index);
69                         ltd_del_tgt(ltd, tgt_desc);
70                         ltd->ltd_death_row--;
71                 }
72                 mutex_unlock(&ltd->ltd_mutex);
73                 up_read(&ltd->ltd_rw_sem);
74
75                 list_for_each_entry_safe(tgt_desc, tmp, &kill, ltd_kill) {
76                         int rc;
77
78                         list_del(&tgt_desc->ltd_kill);
79                         rc = obd_disconnect(tgt_desc->ltd_exp);
80                         if (rc)
81                                 CERROR("%s: failed to disconnect %s: rc = %d\n",
82                                        lod2obd(lod)->obd_name,
83                                        obd_uuid2str(&tgt_desc->ltd_uuid), rc);
84                         OBD_FREE_PTR(tgt_desc);
85                 }
86         } else {
87                 mutex_unlock(&ltd->ltd_mutex);
88                 up_read(&ltd->ltd_rw_sem);
89         }
90 }
91
92 /**
93  * lod_add_device() - Connect LOD to a new OSP and add it to the target table.
94  * @env: execution environment for this thread
95  * @lod: LOD device to be connected to the new OSP
96  * @osp: name of OSP device name to be added
97  * @index: index of the new target
98  * @gen: target's generation number
99  * @tgt_index: OSP's group
100  * @type: type of device (MDC or OSC)
101  * @active: state of OSP: 0 - inactive, 1 - active
102  *
103  * Connect to the OSP device passed, initialize all the internal
104  * structures related to the device and add it to the target table.
105  *
106  * Return:
107  * * %0 if added successfully
108  * * %negative error number on failure
109  */
110 int lod_add_device(const struct lu_env *env, struct lod_device *lod,
111                    char *osp, unsigned index, unsigned gen, int tgt_index,
112                    char *type, int active)
113 {
114         struct obd_connect_data *data = NULL;
115         struct obd_export       *exp = NULL;
116         struct obd_device       *obd;
117         struct lu_device        *lu_dev;
118         struct dt_device        *dt_dev;
119         int                      rc;
120         struct lod_tgt_desc     *tgt_desc;
121         struct lod_tgt_descs    *ltd;
122         struct lustre_cfg       *lcfg;
123         struct obd_uuid         obd_uuid;
124         bool                    for_ost;
125         bool connected = false;
126         ENTRY;
127
128         CDEBUG(D_CONFIG, "osp:%s idx:%d gen:%d\n", osp, index, gen);
129
130         if (gen <= 0) {
131                 CERROR("request to add OBD %s with invalid generation: %d\n",
132                        osp, gen);
133                 RETURN(-EINVAL);
134         }
135
136         obd_str2uuid(&obd_uuid, osp);
137
138         obd = class_find_client_obd(&obd_uuid, LUSTRE_OSP_NAME,
139                                 &lod->lod_dt_dev.dd_lu_dev.ld_obd->obd_uuid);
140         if (obd == NULL) {
141                 CERROR("can't find %s device\n", osp);
142                 RETURN(-EINVAL);
143         }
144
145         LASSERT(obd->obd_lu_dev != NULL);
146         LASSERT(obd->obd_lu_dev->ld_site == lod->lod_dt_dev.dd_lu_dev.ld_site);
147
148         lu_dev = obd->obd_lu_dev;
149         dt_dev = lu2dt_dev(lu_dev);
150
151         OBD_ALLOC_PTR(data);
152         if (data == NULL)
153                 GOTO(out_cleanup, rc = -ENOMEM);
154
155         data->ocd_connect_flags = OBD_CONNECT_INDEX | OBD_CONNECT_VERSION |
156                                   OBD_CONNECT_FLAGS2;
157         data->ocd_version = LUSTRE_VERSION_CODE;
158         data->ocd_index = index;
159
160         if (strcmp(LUSTRE_OSC_NAME, type) == 0) {
161                 for_ost = true;
162                 data->ocd_connect_flags |= OBD_CONNECT_AT |
163                                            OBD_CONNECT_FULL20 |
164                                            OBD_CONNECT_INDEX |
165 #ifdef HAVE_LRU_RESIZE_SUPPORT
166                                            OBD_CONNECT_LRU_RESIZE |
167 #endif
168                                            OBD_CONNECT_MDS |
169                                            OBD_CONNECT_SKIP_ORPHAN |
170                                            OBD_CONNECT_FID |
171                                            OBD_CONNECT_LVB_TYPE |
172                                            OBD_CONNECT_VERSION |
173                                            OBD_CONNECT_PINGLESS |
174                                            OBD_CONNECT_LFSCK |
175                                            OBD_CONNECT_BULK_MBITS;
176                 data->ocd_connect_flags2 = OBD_CONNECT2_REPLAY_CREATE;
177
178                 data->ocd_group = tgt_index;
179                 ltd = &lod->lod_ost_descs;
180         } else {
181                 struct obd_import *imp = obd->u.cli.cl_import;
182
183                 for_ost = false;
184                 data->ocd_ibits_known = MDS_INODELOCK_UPDATE;
185                 data->ocd_connect_flags |= OBD_CONNECT_ACL |
186                                            OBD_CONNECT_IBITS |
187                                            OBD_CONNECT_MDS_MDS |
188                                            OBD_CONNECT_MULTIMODRPCS |
189                                            OBD_CONNECT_FID |
190                                            OBD_CONNECT_AT |
191                                            OBD_CONNECT_FULL20 |
192                                            OBD_CONNECT_LFSCK |
193                                            OBD_CONNECT_BULK_MBITS;
194                 spin_lock(&imp->imp_lock);
195                 imp->imp_server_timeout = 1;
196                 spin_unlock(&imp->imp_lock);
197                 imp->imp_client->cli_request_portal = OUT_PORTAL;
198                 CDEBUG(D_OTHER, "%s: Set 'mds' portal and timeout\n",
199                       obd->obd_name);
200                 ltd = &lod->lod_mdt_descs;
201         }
202
203         rc = obd_connect(env, &exp, obd, &obd->obd_uuid, data, NULL);
204         OBD_FREE_PTR(data);
205         if (rc) {
206                 CERROR("%s: cannot connect to next dev %s (%d)\n",
207                        obd->obd_name, osp, rc);
208                 GOTO(out_cleanup, rc);
209         }
210         connected = true;
211
212         /* Allocate ost descriptor and fill it */
213         OBD_ALLOC_PTR(tgt_desc);
214         if (!tgt_desc)
215                 GOTO(out_cleanup, rc = -ENOMEM);
216
217         tgt_desc->ltd_tgt    = dt_dev;
218         tgt_desc->ltd_exp    = exp;
219         tgt_desc->ltd_uuid   = obd->u.cli.cl_target_uuid;
220         tgt_desc->ltd_gen    = gen;
221         tgt_desc->ltd_index  = index;
222         tgt_desc->ltd_active = active;
223
224         down_write(&ltd->ltd_rw_sem);
225         mutex_lock(&ltd->ltd_mutex);
226         rc = ltd_add_tgt(ltd, tgt_desc);
227         if (rc)
228                 GOTO(out_mutex, rc);
229
230         rc = lu_qos_add_tgt(&ltd->ltd_qos, tgt_desc);
231         if (rc)
232                 GOTO(out_del_tgt, rc);
233
234         rc = lu_tgt_pool_add(&ltd->ltd_tgt_pool, index,
235                           ltd->ltd_lov_desc.ld_tgt_count);
236         if (rc) {
237                 CERROR("%s: can't set up pool, failed with %d\n",
238                        obd->obd_name, rc);
239                 GOTO(out_del_tgt, rc);
240         }
241
242         mutex_unlock(&ltd->ltd_mutex);
243         up_write(&ltd->ltd_rw_sem);
244
245         if (lod->lod_recovery_completed)
246                 lu_dev->ld_ops->ldo_recovery_complete(env, lu_dev);
247
248         if (!for_ost && lod->lod_initialized) {
249                 rc = lod_sub_init_llog(env, lod, tgt_desc->ltd_tgt);
250                 if (rc != 0) {
251                         CERROR("%s: cannot start llog on %s:rc = %d\n",
252                                lod2obd(lod)->obd_name, osp, rc);
253                         GOTO(out_ltd, rc);
254                 }
255         }
256
257         rc = lfsck_add_target(env, lod->lod_child, dt_dev, exp, index, for_ost);
258         if (rc != 0) {
259                 CERROR("Fail to add LFSCK target: name = %s, type = %s, "
260                        "index = %u, rc = %d\n", osp, type, index, rc);
261                 GOTO(out_fini_llog, rc);
262         }
263         RETURN(rc);
264 out_fini_llog:
265         lod_sub_fini_llog(env, tgt_desc->ltd_tgt,
266                           &tgt_desc->ltd_recovery_task);
267 out_ltd:
268         down_write(&ltd->ltd_rw_sem);
269         mutex_lock(&ltd->ltd_mutex);
270         lu_tgt_pool_remove(&ltd->ltd_tgt_pool, index);
271 out_del_tgt:
272         ltd_del_tgt(ltd, tgt_desc);
273 out_mutex:
274         mutex_unlock(&ltd->ltd_mutex);
275         up_write(&ltd->ltd_rw_sem);
276         OBD_FREE_PTR(tgt_desc);
277 out_cleanup:
278         /* XXX OSP needs us to send down LCFG_CLEANUP because it uses
279          * objects from the MDT stack. See LU-7184. */
280         lcfg = &lod_env_info(env)->lti_lustre_cfg;
281         memset(lcfg, 0, sizeof(*lcfg));
282         lcfg->lcfg_version = LUSTRE_CFG_VERSION;
283         lcfg->lcfg_command = LCFG_CLEANUP;
284         lu_dev->ld_ops->ldo_process_config(env, lu_dev, lcfg);
285
286         if (connected)
287                 obd_disconnect(exp);
288
289         return rc;
290 }
291
292 /**
293  * __lod_del_device() - Schedule target removal from the target table.
294  * @env: execution environment for this thread
295  * @lod: LOD device the target table belongs to
296  * @ltd: target table
297  * @tgt: target
298  *
299  * Mark the device as dead. The device is not removed here because it may
300  * still be in use. The device will be removed in lod_putref() when the
301  * last reference is released.
302  */
303 static void __lod_del_device(const struct lu_env *env, struct lod_device *lod,
304                              struct lod_tgt_descs *ltd, struct lu_tgt_desc *tgt)
305 {
306         lfsck_del_target(env, lod->lod_child, tgt->ltd_tgt, tgt->ltd_index,
307                          !ltd->ltd_is_mdt);
308
309         if (!tgt->ltd_reap) {
310                 tgt->ltd_reap = 1;
311                 ltd->ltd_death_row++;
312         }
313 }
314
315 /**
316  * lod_fini_tgt() - Schedule removal of all the targets from the given target
317  * table.See more details in the description for @__lod_del_device()
318  * @env: execution environment for this thread
319  * @lod: LOD device the target table belongs to
320  * @ltd: target table
321  *
322  * Returns 0 always
323  */
324 int lod_fini_tgt(const struct lu_env *env, struct lod_device *lod,
325                  struct lod_tgt_descs *ltd)
326 {
327         struct lu_tgt_desc *tgt;
328
329         if (ltd->ltd_tgts_size <= 0)
330                 return 0;
331
332         lod_getref(ltd);
333         mutex_lock(&ltd->ltd_mutex);
334         ltd_foreach_tgt(ltd, tgt)
335                 __lod_del_device(env, lod, ltd, tgt);
336         mutex_unlock(&ltd->ltd_mutex);
337         lod_putref(lod, ltd);
338
339         lu_tgt_descs_fini(ltd);
340
341         return 0;
342 }
343
344 /**
345  * lod_del_device() - Remove device by name.
346  * @env: execution environment for this thread
347  * @lod: LOD device to be connected to the new OSP
348  * @ltd: target table
349  * @osp: name of OSP device to be removed
350  * @idx: index of the target
351  * @gen: generation number, not used currently
352  *
353  * Remove a device identified by \a osp from the target table. Given
354  * the device can be in use, the real deletion happens in lod_putref().
355  *
356  * Return:
357  * * %0 if the device was scheduled for removal
358  * * %-EINVAL if no device was found
359  */
360 int lod_del_device(const struct lu_env *env, struct lod_device *lod,
361                    struct lod_tgt_descs *ltd, char *osp, unsigned int idx,
362                    unsigned int gen)
363 {
364         struct obd_device *obd;
365         struct lu_tgt_desc *tgt;
366         struct obd_uuid uuid;
367         int rc = 0;
368
369         ENTRY;
370
371         CDEBUG(D_CONFIG, "osp:%s idx:%d gen:%d\n", osp, idx, gen);
372
373         obd_str2uuid(&uuid, osp);
374
375         obd = class_find_client_obd(&uuid, LUSTRE_OSP_NAME,
376                                    &lod->lod_dt_dev.dd_lu_dev.ld_obd->obd_uuid);
377         if (obd == NULL) {
378                 CERROR("can't find %s device\n", osp);
379                 RETURN(-EINVAL);
380         }
381
382         if (gen <= 0) {
383                 CERROR("%s: request to remove OBD %s with invalid generation %d"
384                        "\n", obd->obd_name, osp, gen);
385                 RETURN(-EINVAL);
386         }
387
388         obd_str2uuid(&uuid,  osp);
389
390         lod_getref(ltd);
391         mutex_lock(&ltd->ltd_mutex);
392         tgt = LTD_TGT(ltd, idx);
393         /* check that the index is allocated in the bitmap */
394         if (!test_bit(idx, ltd->ltd_tgt_bitmap) || !tgt) {
395                 CERROR("%s: device %d is not set up\n", obd->obd_name, idx);
396                 GOTO(out, rc = -EINVAL);
397         }
398
399         /* check that the UUID matches */
400         if (!obd_uuid_equals(&uuid, &tgt->ltd_uuid)) {
401                 CERROR("%s: LOD target UUID %s at index %d does not match %s\n",
402                        obd->obd_name, obd_uuid2str(&tgt->ltd_uuid), idx, osp);
403                 GOTO(out, rc = -EINVAL);
404         }
405
406         __lod_del_device(env, lod, ltd, tgt);
407         EXIT;
408 out:
409         mutex_unlock(&ltd->ltd_mutex);
410         lod_putref(lod, ltd);
411         return(rc);
412 }
413
414 /**
415  * lod_ea_store_resize() - Resize per-thread storage to hold specified size.
416  * @info: LOD-specific storage in the environment
417  * @size: new size to grow the buffer to
418  *
419  * A helper function to resize per-thread temporary storage. This storage
420  * is used to process LOV/LVM EAs and may be quite large. We do not want to
421  * allocate/release it every time, so instead we put it into the env and
422  * reallocate on demand. The memory is released when the correspondent thread
423  * is finished.
424  *
425  * Return:
426  * * %0 on success
427  * * %-ENOMEM if reallocation failed
428  */
429 int lod_ea_store_resize(struct lod_thread_info *info, size_t size)
430 {
431         __u32 round = size_roundup_power2(size);
432
433         lu_buf_check_and_alloc(&info->lti_ea_buf, round);
434         if (info->lti_ea_buf.lb_buf == NULL)
435                 RETURN(-ENOMEM);
436
437         RETURN(0);
438 }
439
440 static void lod_free_comp_buffer(struct lod_layout_component *entries,
441                                  __u16 count, __u32 bufsize)
442 {
443         struct lod_layout_component *entry;
444         int i;
445
446         for (i = 0; i < count; i++) {
447                 entry = &entries[i];
448                 if (entry->llc_magic == LOV_MAGIC_FOREIGN)
449                         continue;
450                 if (entry->llc_pool != NULL)
451                         lod_set_pool(&entry->llc_pool, NULL);
452                 if (entry->llc_ostlist.op_array) {
453                         OBD_FREE(entry->llc_ostlist.op_array,
454                                  entry->llc_ostlist.op_size);
455                         entry->llc_ostlist.op_array = NULL;
456                         entry->llc_ostlist.op_size = 0;
457                 }
458                 LASSERT(entry->llc_stripe == NULL);
459                 LASSERT(entry->llc_stripes_allocated == 0);
460         }
461
462         if (bufsize != 0)
463                 OBD_FREE_LARGE(entries, bufsize);
464 }
465
466 void lod_free_def_comp_entries(struct lod_default_striping *lds)
467 {
468         lod_free_comp_buffer(lds->lds_def_comp_entries,
469                              lds->lds_def_comp_size_cnt,
470                              size_roundup_power2(
471                                      sizeof(*lds->lds_def_comp_entries) *
472                                      lds->lds_def_comp_size_cnt));
473         lds->lds_def_comp_entries = NULL;
474         lds->lds_def_comp_cnt = 0;
475         lds->lds_def_striping_is_composite = 0;
476         lds->lds_def_comp_size_cnt = 0;
477 }
478
479 /**
480  * lod_def_striping_comp_resize() - Resize per-thread storage to hold default
481  * striping component entries
482  * @lds: default striping [in, out]
483  * @count: new component count to grow the buffer to
484  *
485  * A helper function to resize per-thread temporary storage. This storage
486  * is used to hold default LOV/LVM EAs and may be quite large. We do not want
487  * to allocate/release it every time, so instead we put it into the env and
488  * reallocate it on demand. The memory is released when the correspondent
489  * thread is finished.
490  *
491  * Return:
492  * * %0 on success
493  * * %-ENOMEM if reallocation failed
494  */
495 int lod_def_striping_comp_resize(struct lod_default_striping *lds, __u16 count)
496 {
497         struct lod_layout_component *entries;
498         __u32 new = size_roundup_power2(sizeof(*lds->lds_def_comp_entries) *
499                                         count);
500         __u32 old = size_roundup_power2(sizeof(*lds->lds_def_comp_entries) *
501                                         lds->lds_def_comp_size_cnt);
502
503         if (new <= old)
504                 return 0;
505
506         OBD_ALLOC_LARGE(entries, new);
507         if (entries == NULL)
508                 return -ENOMEM;
509
510         if (lds->lds_def_comp_entries != NULL) {
511                 CDEBUG(D_INFO, "default striping component size %d is not "
512                        "enough, need %d\n", old, new);
513                 lod_free_def_comp_entries(lds);
514         }
515
516         lds->lds_def_comp_entries = entries;
517         lds->lds_def_comp_size_cnt = count;
518
519         RETURN(0);
520 }
521
522 void lod_free_comp_entries(struct lod_object *lo)
523 {
524         if (lo->ldo_mirrors) {
525                 OBD_FREE_PTR_ARRAY(lo->ldo_mirrors, lo->ldo_mirror_count);
526                 lo->ldo_mirrors = NULL;
527                 lo->ldo_mirror_count = 0;
528         }
529         lod_free_comp_buffer(lo->ldo_comp_entries,
530                              lo->ldo_comp_cnt,
531                              sizeof(*lo->ldo_comp_entries) * lo->ldo_comp_cnt);
532         lo->ldo_comp_entries = NULL;
533         lo->ldo_comp_cnt = 0;
534         lo->ldo_is_composite = 0;
535 }
536
537 int lod_alloc_comp_entries(struct lod_object *lo,
538                            int mirror_count, int comp_count)
539 {
540         LASSERT(comp_count != 0);
541         LASSERT(lo->ldo_comp_cnt == 0 && lo->ldo_comp_entries == NULL);
542
543         if (mirror_count > 0) {
544                 OBD_ALLOC_PTR_ARRAY(lo->ldo_mirrors, mirror_count);
545                 if (!lo->ldo_mirrors)
546                         return -ENOMEM;
547
548                 lo->ldo_mirror_count = mirror_count;
549         }
550
551         OBD_ALLOC_LARGE(lo->ldo_comp_entries,
552                         sizeof(*lo->ldo_comp_entries) * comp_count);
553         if (lo->ldo_comp_entries == NULL) {
554                 OBD_FREE_PTR_ARRAY(lo->ldo_mirrors, mirror_count);
555                 lo->ldo_mirrors = NULL;
556                 lo->ldo_mirror_count = 0;
557                 return -ENOMEM;
558         }
559
560         lo->ldo_comp_cnt = comp_count;
561         lo->ldo_is_foreign = 0;
562         return 0;
563 }
564
565 int lod_fill_mirrors(struct lod_object *lo)
566 {
567         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
568         struct lod_layout_component *lod_comp;
569         bool found_preferred = false;
570         int mirror_idx = -1;
571         __u16 mirror_id = 0xffff;
572         int i, pref;
573         ENTRY;
574
575         LASSERT(equi(!lo->ldo_is_composite, lo->ldo_mirror_count == 0));
576
577         if (!lo->ldo_is_composite)
578                 RETURN(0);
579
580         lod_comp = &lo->ldo_comp_entries[0];
581
582         for (i = 0; i < lo->ldo_comp_cnt; i++, lod_comp++) {
583                 bool stale = lod_comp->llc_flags & LCME_FL_STALE;
584                 bool preferred = lod_comp->llc_flags & LCME_FL_PREF_WR;
585                 bool mirror_hsm = lod_is_hsm(lod_comp);
586                 bool init = (lod_comp->llc_stripe != NULL) &&
587                             !(lod_comp->llc_pattern & LOV_PATTERN_F_RELEASED) &&
588                             !(lod_comp->llc_pattern & LOV_PATTERN_MDT);
589                 int j;
590
591                 pref = 0;
592                 /* calculate component preference over all used OSTs */
593                 for (j = 0; init && j < lod_comp->llc_stripes_allocated; j++) {
594                         __u32 idx = lod_comp->llc_ost_indices[j];
595                         struct lod_tgt_desc *ltd;
596
597                         if (lod_comp->llc_stripe[j] == NULL)
598                                 continue;
599
600                         if (unlikely(idx >= lod->lod_ost_descs.ltd_tgts_size)) {
601                                 CERROR("%s: "DFID" OST idx %u > max %u\n",
602                                        lod2obd(lod)->obd_name,
603                                        PFID(lu_object_fid(&lo->ldo_obj.do_lu)),
604                                        idx, lod->lod_ost_descs.ltd_tgts_size);
605                                 continue;
606                         }
607                         ltd = OST_TGT(lod, idx);
608                         if (unlikely(!ltd)) {
609                                 CERROR("%s: "DFID" OST idx %u is NULL\n",
610                                        lod2obd(lod)->obd_name,
611                                        PFID(lu_object_fid(&lo->ldo_obj.do_lu)),
612                                        idx);
613                                 continue;
614                         }
615
616                         if (ltd->ltd_statfs.os_state & OS_STATFS_NONROT)
617                                 pref++;
618                 }
619
620                 if (mirror_id_of(lod_comp->llc_id) == mirror_id) {
621                         /* Currently HSM mirror does not support PFL. */
622                         if (lo->ldo_mirrors[mirror_idx].lme_hsm)
623                                 RETURN(-EINVAL);
624                         lo->ldo_mirrors[mirror_idx].lme_stale |= stale;
625                         lo->ldo_mirrors[mirror_idx].lme_prefer |= preferred;
626                         lo->ldo_mirrors[mirror_idx].lme_preference += pref;
627                         lo->ldo_mirrors[mirror_idx].lme_end = i;
628                         continue;
629                 }
630
631                 if (mirror_idx >= 0 && preferred &&
632                     !lo->ldo_mirrors[mirror_idx].lme_stale)
633                         found_preferred = true;
634
635                 /* new mirror */
636                 ++mirror_idx;
637                 if (mirror_idx >= lo->ldo_mirror_count)
638                         RETURN(-EINVAL);
639
640                 if (mirror_hsm && (lod_comp->llc_extent.e_start != 0 ||
641                                    lod_comp->llc_extent.e_end != LUSTRE_EOF))
642                         RETURN(-EINVAL);
643
644                 mirror_id = mirror_id_of(lod_comp->llc_id);
645
646                 lo->ldo_mirrors[mirror_idx].lme_id = mirror_id;
647                 lo->ldo_mirrors[mirror_idx].lme_stale = stale;
648                 lo->ldo_mirrors[mirror_idx].lme_prefer = preferred;
649                 lo->ldo_mirrors[mirror_idx].lme_hsm = mirror_hsm;
650                 lo->ldo_mirrors[mirror_idx].lme_preference = pref;
651                 lo->ldo_mirrors[mirror_idx].lme_start = i;
652                 lo->ldo_mirrors[mirror_idx].lme_end = i;
653         }
654         if (mirror_idx != lo->ldo_mirror_count - 1)
655                 RETURN(-EINVAL);
656
657         if (!found_preferred && mirror_idx > 0) {
658                 int best = -1;
659
660                 /*
661                  * if no explicited preferred found, then find a mirror
662                  * with higher number of non-rotational OSTs
663                  * */
664                 pref = -1;
665                 for (i = 0; i <= mirror_idx; i++) {
666                         if (lo->ldo_mirrors[i].lme_stale)
667                                 continue;
668                         if (lo->ldo_mirrors[i].lme_preference > pref) {
669                                 pref = lo->ldo_mirrors[i].lme_preference;
670                                 best = i;
671                         }
672                 }
673
674                 LASSERT(best >= 0);
675                 lo->ldo_mirrors[best].lme_prefer = 1;
676         }
677
678         RETURN(0);
679 }
680
681 /**
682  * lod_gen_component_ea() - Generate on-disk lov_mds_md structure for each
683  * layout component based on the information in lod_object->ldo_comp_entries[i].
684  * @env: execution environment for this thread
685  * @lo: LOD object
686  * @comp_idx: index of ldo_comp_entries
687  * @lmm: buffer to cotain the on-disk lov_mds_md
688  * @lmm_size: buffer size/lmm size [in|out]
689  * @is_dir: generate lov ea for dir or file? For dir case, the stripe info is
690  * from the default stripe template, which is collected in @lod_ah_init(),
691  * either from parent object or root object; for file case, it's from the @lo
692  * object
693  *
694  * Return:
695  * * %0 if on disk structure is created successfully
696  * * %negative error number on failure
697  */
698 static int lod_gen_component_ea(const struct lu_env *env,
699                                 struct lod_object *lo, int comp_idx,
700                                 struct lov_mds_md *lmm, int *lmm_size,
701                                 bool is_dir)
702 {
703         struct lod_thread_info  *info = lod_env_info(env);
704         const struct lu_fid     *fid  = lu_object_fid(&lo->ldo_obj.do_lu);
705         struct lod_device       *lod;
706         struct lov_ost_data_v1  *objs;
707         struct lod_layout_component *lod_comp;
708         __u32   magic;
709         __u16 stripe_count;
710         int     i, rc = 0;
711         ENTRY;
712
713         LASSERT(lo);
714         if (is_dir)
715                 lod_comp =
716                         &lo->ldo_def_striping->lds_def_comp_entries[comp_idx];
717         else
718                 lod_comp = &lo->ldo_comp_entries[comp_idx];
719
720         magic = lod_comp->llc_pool != NULL ? LOV_MAGIC_V3 : LOV_MAGIC_V1;
721         if (is_dir && lod_comp->llc_ostlist.op_count)
722                 magic = LOV_MAGIC_SPECIFIC;
723
724         if (lod_comp->llc_pattern == 0) /* default striping */
725                 lod_comp->llc_pattern = LOV_PATTERN_RAID0;
726
727         lmm->lmm_magic = cpu_to_le32(magic);
728         lmm->lmm_pattern = cpu_to_le32(lod_comp->llc_pattern);
729         fid_to_lmm_oi(fid, &lmm->lmm_oi);
730         if (CFS_FAIL_CHECK(OBD_FAIL_LFSCK_BAD_LMMOI))
731                 lmm->lmm_oi.oi.oi_id++;
732         lmm_oi_cpu_to_le(&lmm->lmm_oi, &lmm->lmm_oi);
733
734         lmm->lmm_stripe_size = cpu_to_le32(lod_comp->llc_stripe_size);
735         lmm->lmm_stripe_count = cpu_to_le16(lod_comp->llc_stripe_count);
736         /**
737          * for dir and uninstantiated component, lmm_layout_gen stores
738          * default stripe offset.
739          */
740         lmm->lmm_layout_gen =
741                 (is_dir || !lod_comp_inited(lod_comp)) ?
742                         cpu_to_le16(lod_comp->llc_stripe_offset) :
743                         cpu_to_le16(lod_comp->llc_layout_gen);
744
745         if (magic == LOV_MAGIC_V1) {
746                 objs = &lmm->lmm_objects[0];
747         } else {
748                 struct lov_mds_md_v3 *v3 = (struct lov_mds_md_v3 *)lmm;
749                 ssize_t cplen = strscpy(v3->lmm_pool_name,
750                                        lod_comp->llc_pool ? : "\0",
751                                        sizeof(v3->lmm_pool_name));
752
753                 if (cplen < 0)
754                         RETURN(cplen);
755                 objs = &v3->lmm_objects[0];
756         }
757         lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
758         stripe_count = lod_comp_entry_stripe_count(lo, comp_idx, is_dir);
759         if (stripe_count == 0 && !is_dir &&
760             !(lod_comp->llc_pattern & LOV_PATTERN_F_RELEASED) &&
761             !(lod_comp->llc_pattern & LOV_PATTERN_MDT)) {
762                 /* Try again if all active targets are disconnected.
763                  * It is possible when MDS does failover. */
764                 if (!lod->lod_ost_active_count &&
765                     lod->lod_ost_count)
766                         RETURN(-EAGAIN);
767                 RETURN(-E2BIG);
768         }
769
770         if (!is_dir && lo->ldo_is_composite)
771                 lod_comp_shrink_stripe_count(lod_comp, &stripe_count);
772
773         if ((is_dir && magic != LOV_MAGIC_SPECIFIC) ||
774             lod_comp->llc_pattern & LOV_PATTERN_F_RELEASED)
775                 GOTO(done, rc = 0);
776
777         /* generate ost_idx of this component stripe */
778         for (i = 0; i < stripe_count; i++) {
779                 struct dt_object *object;
780                 __u32 ost_idx = (__u32)-1UL;
781                 int type = LU_SEQ_RANGE_OST;
782
783                 if (lod_comp->llc_stripe && lod_comp->llc_stripe[i]) {
784                         object = lod_comp->llc_stripe[i];
785                         /* instantiated component */
786                         info->lti_fid = *lu_object_fid(&object->do_lu);
787
788                         if (CFS_FAIL_CHECK(OBD_FAIL_LFSCK_MULTIPLE_REF) &&
789                             comp_idx == 0) {
790                                 if (cfs_fail_val == 0)
791                                         cfs_fail_val = info->lti_fid.f_oid;
792                                 else if (i == 0)
793                                         info->lti_fid.f_oid = cfs_fail_val;
794                         }
795
796                         rc = fid_to_ostid(&info->lti_fid, &info->lti_ostid);
797                         LASSERT(rc == 0);
798
799                         ostid_cpu_to_le(&info->lti_ostid, &objs[i].l_ost_oi);
800                         objs[i].l_ost_gen = cpu_to_le32(0);
801                         if (CFS_FAIL_CHECK(OBD_FAIL_MDS_FLD_LOOKUP))
802                                 rc = -ENOENT;
803                         else
804                                 rc = lod_fld_lookup(env, lod, &info->lti_fid,
805                                                     &ost_idx, &type);
806                         if (rc < 0) {
807                                 CERROR("%s: Can not locate "DFID": rc = %d\n",
808                                        lod2obd(lod)->obd_name,
809                                        PFID(&info->lti_fid), rc);
810                                 RETURN(rc);
811                         }
812                 } else if (lod_comp->llc_ostlist.op_array &&
813                            lod_comp->llc_ostlist.op_count) {
814                         /* user specified ost list */
815                         ost_idx = lod_comp->llc_ostlist.op_array[i];
816                 }
817                 /*
818                  * with un-instantiated or with no specified ost list
819                  * component, its l_ost_idx does not matter.
820                  */
821                 objs[i].l_ost_idx = cpu_to_le32(ost_idx);
822
823                 /* simulation of broken LOVEA */
824                 if (CFS_FAIL_CHECK(OBD_FAIL_LOV_INVALID_OSTIDX) &&
825                     comp_idx == 0 && i == 0 && lo->ldo_mirror_count > 1) {
826                         objs[i].l_ost_idx = cpu_to_le32(0xffffffff);
827                 }
828
829         }
830 done:
831         if (lmm_size != NULL)
832                 *lmm_size = lov_mds_md_size(stripe_count, magic);
833         RETURN(rc);
834 }
835
836 /*
837  * Generate on-disk lov_hsm_md structure based on the information in
838  * the lod_object->ldo_comp_entries.
839  */
840 static int lod_gen_component_ea_foreign(const struct lu_env *env,
841                                         struct lod_object *lo,
842                                         struct lod_layout_component *lod_comp,
843                                         void *lmm, int *lmm_size)
844 {
845         struct lov_foreign_md *lfm = (struct lov_foreign_md *)lmm;
846
847         ENTRY;
848
849         lfm->lfm_magic = cpu_to_le32(LOV_MAGIC_FOREIGN);
850         lfm->lfm_length = cpu_to_le32(lod_comp->llc_length);
851         lfm->lfm_type = cpu_to_le32(lod_comp->llc_type);
852         lfm->lfm_flags = cpu_to_le32(lod_comp->llc_foreign_flags);
853
854         if (lov_hsm_type_supported(lod_comp->llc_type)) {
855                 if (lod_comp->llc_length != sizeof(struct lov_hsm_base))
856                         return -EINVAL;
857
858                 lov_foreign_hsm_to_le(lfm, &lod_comp->llc_hsm);
859         }
860
861         if (lmm_size)
862                 *lmm_size = lov_foreign_md_size(lod_comp->llc_length);
863
864         RETURN(0);
865 }
866
867 /**
868  * lod_generate_lovea() - Generate on-disk lov_mds_md structure based on the
869  * information in the lod_object->ldo_comp_entries.
870  * @env: execution environment for this thread
871  * @lo: LOD object
872  * @lmm: buffer to cotain the on-disk lov_mds_md
873  * @lmm_size: buffer size/lmm size [in|out]
874  * @is_dir: generate lov ea for dir or file? For dir case, the stripe info is
875  * from the default stripe template, which is collected in @lod_ah_init(),
876  * either from parent object or root object; for file case, it's from the @lo
877  * object
878  *
879  * Return:
880  * * %0 if on disk structure is created successfully
881  * * %negative error number on failure
882  */
883 int lod_generate_lovea(const struct lu_env *env, struct lod_object *lo,
884                        struct lov_mds_md *lmm, int *lmm_size, bool is_dir)
885 {
886         struct lov_comp_md_entry_v1 *lcme;
887         struct lov_comp_md_v1 *lcm;
888         struct lod_layout_component *comp_entries;
889         __u16 comp_cnt, mirror_cnt;
890         bool is_composite, is_foreign = false;
891         int i, rc = 0, offset;
892         ENTRY;
893
894         if (is_dir) {
895                 comp_cnt = lo->ldo_def_striping->lds_def_comp_cnt;
896                 mirror_cnt = lo->ldo_def_striping->lds_def_mirror_cnt;
897                 comp_entries = lo->ldo_def_striping->lds_def_comp_entries;
898                 is_composite =
899                         lo->ldo_def_striping->lds_def_striping_is_composite;
900         } else {
901                 comp_cnt = lo->ldo_comp_cnt;
902                 mirror_cnt = lo->ldo_mirror_count;
903                 comp_entries = lo->ldo_comp_entries;
904                 is_composite = lo->ldo_is_composite;
905                 is_foreign = lo->ldo_is_foreign;
906         }
907
908         LASSERT(lmm_size != NULL);
909
910         if (is_foreign) {
911                 struct lov_foreign_md *lfm;
912
913                 lfm = (struct lov_foreign_md *)lmm;
914                 memcpy(lfm, lo->ldo_foreign_lov, lo->ldo_foreign_lov_size);
915                 /* need to store little-endian */
916                 if (cpu_to_le32(LOV_MAGIC_FOREIGN) != LOV_MAGIC_FOREIGN) {
917                         __swab32s(&lfm->lfm_magic);
918                         __swab32s(&lfm->lfm_length);
919                         __swab32s(&lfm->lfm_type);
920                         __swab32s(&lfm->lfm_flags);
921                 }
922                 *lmm_size = lo->ldo_foreign_lov_size;
923                 RETURN(0);
924         }
925
926         LASSERT(comp_cnt != 0 && comp_entries != NULL);
927
928         if (!is_composite) {
929                 rc = lod_gen_component_ea(env, lo, 0, lmm, lmm_size, is_dir);
930                 RETURN(rc);
931         }
932
933         lcm = (struct lov_comp_md_v1 *)lmm;
934         memset(lcm, 0, sizeof(*lcm));
935
936         lcm->lcm_magic = cpu_to_le32(LOV_MAGIC_COMP_V1);
937         lcm->lcm_entry_count = cpu_to_le16(comp_cnt);
938         lcm->lcm_mirror_count = cpu_to_le16(mirror_cnt - 1);
939         if (mirror_cnt > 1)
940                 lcm->lcm_flags = cpu_to_le16(lo->ldo_flr_state);
941         else
942                 lcm->lcm_flags = LCM_FL_NONE;
943
944         offset = sizeof(*lcm) + sizeof(*lcme) * comp_cnt;
945         LASSERT(offset % sizeof(__u64) == 0);
946
947         for (i = 0; i < comp_cnt; i++) {
948                 struct lod_layout_component *lod_comp;
949                 struct lov_mds_md *sub_md;
950                 int size;
951
952                 lod_comp = &comp_entries[i];
953                 lcme = &lcm->lcm_entries[i];
954
955                 LASSERT(ergo(!is_dir, lod_comp->llc_id != LCME_ID_INVAL));
956                 lcme->lcme_id = cpu_to_le32(lod_comp->llc_id);
957
958                 /* component could be un-inistantiated */
959                 lcme->lcme_flags = cpu_to_le32(lod_comp->llc_flags);
960                 if (lod_comp->llc_flags & LCME_FL_NOSYNC)
961                         lcme->lcme_timestamp =
962                                 cpu_to_le64(lod_comp->llc_timestamp);
963                 if (lod_comp->llc_flags & LCME_FL_EXTENSION && !is_dir)
964                         lcm->lcm_magic = cpu_to_le32(LOV_MAGIC_SEL);
965
966                 lcme->lcme_extent.e_start =
967                         cpu_to_le64(lod_comp->llc_extent.e_start);
968                 lcme->lcme_extent.e_end =
969                         cpu_to_le64(lod_comp->llc_extent.e_end);
970                 lcme->lcme_offset = cpu_to_le32(offset);
971
972                 sub_md = (struct lov_mds_md *)((char *)lcm + offset);
973                 if (lod_comp->llc_magic == LOV_MAGIC_FOREIGN) {
974                         if (!lov_hsm_type_supported(lod_comp->llc_type)) {
975                                 CDEBUG(D_LAYOUT, "Unknown HSM type: %u\n",
976                                        lod_comp->llc_type);
977                                 GOTO(out, rc = -EINVAL);
978                         }
979                         rc = lod_gen_component_ea_foreign(env, lo, lod_comp,
980                                                           sub_md, &size);
981                 } else {
982                         rc = lod_gen_component_ea(env, lo, i, sub_md,
983                                                   &size, is_dir);
984                 }
985                 if (rc)
986                         GOTO(out, rc);
987                 lcme->lcme_size = cpu_to_le32(size);
988                 offset += size;
989                 LASSERTF((offset <= *lmm_size) && (offset % sizeof(__u64) == 0),
990                          "offset:%d lmm_size:%d\n", offset, *lmm_size);
991         }
992         lcm->lcm_size = cpu_to_le32(offset);
993         lcm->lcm_layout_gen = cpu_to_le32(is_dir ? 0 : lo->ldo_layout_gen);
994
995         lustre_print_user_md(D_LAYOUT, (struct lov_user_md *)lmm,
996                              "generate lum");
997 out:
998         if (rc == 0)
999                 *lmm_size = offset;
1000         RETURN(rc);
1001 }
1002
1003 /**
1004  * lod_get_ea() - Get LOV EA.
1005  * @env: execution environment for this thread (.lti_ea_store buffer is
1006  * filled with EA's value) [in|out]
1007  * @lo: LOD object
1008  * @name: name of the EA
1009  *
1010  * Fill lti_ea_buf buffer in the environment with a value for the given
1011  * EA. The buffer is reallocated if the value doesn't fit.
1012  *
1013  * Return:
1014  * * %0 if EA is fetched successfully
1015  * * %0 if EA is empty
1016  * * %negative error number on failure
1017  */
1018 int lod_get_ea(const struct lu_env *env, struct lod_object *lo,
1019                const char *name)
1020 {
1021         struct lod_thread_info  *info = lod_env_info(env);
1022         struct dt_object        *next = dt_object_child(&lo->ldo_obj);
1023         int rc, count = 0;
1024         ENTRY;
1025
1026         LASSERT(info);
1027
1028         if (unlikely(info->lti_ea_buf.lb_buf == NULL)) {
1029                 /* just to enter in allocation block below */
1030                 rc = -ERANGE;
1031         } else {
1032 repeat:
1033                 info->lti_buf = info->lti_ea_buf;
1034                 rc = dt_xattr_get(env, next, &info->lti_buf, name);
1035         }
1036
1037         /* if object is not striped or inaccessible */
1038         if (rc == -ENODATA || rc == -ENOENT)
1039                 RETURN(0);
1040
1041         if (rc == -ERANGE) {
1042                 /* EA doesn't fit, reallocate new buffer */
1043                 rc = dt_xattr_get(env, next, &LU_BUF_NULL, name);
1044                 if (rc == -ENODATA || rc == -ENOENT)
1045                         RETURN(0);
1046                 else if (rc < 0)
1047                         RETURN(rc);
1048
1049                 LASSERT(rc > 0);
1050                 if (rc <= info->lti_ea_store_size) {
1051                         /* sometimes LOVEA can shrink in parallel */
1052                         LASSERT(count++ < 10);
1053                         goto repeat;
1054                 }
1055                 rc = lod_ea_store_resize(info, rc);
1056                 if (rc)
1057                         RETURN(rc);
1058                 goto repeat;
1059         }
1060
1061         RETURN(rc);
1062 }
1063
1064 /**
1065  * validate_lod_and_idx() - Verify the target index is present in the current
1066  * configuration.
1067  * @md: LOD device where the target table is stored
1068  * @idx: target's index
1069  *
1070  * Return:
1071  * * %0 if the index is present
1072  * * %-EINVAL if not
1073  */
1074 int validate_lod_and_idx(struct lod_device *md, __u32 idx)
1075 {
1076         if (unlikely(idx >= md->lod_ost_descs.ltd_tgts_size ||
1077                      !test_bit(idx, md->lod_ost_bitmap))) {
1078                 CERROR("%s: bad idx: %d of %d\n", lod2obd(md)->obd_name, idx,
1079                        md->lod_ost_descs.ltd_tgts_size);
1080                 return -EINVAL;
1081         }
1082
1083         if (unlikely(OST_TGT(md, idx) == NULL)) {
1084                 CERROR("%s: bad lod_tgt_desc for idx: %d\n",
1085                        lod2obd(md)->obd_name, idx);
1086                 return -EINVAL;
1087         }
1088
1089         if (unlikely(OST_TGT(md, idx)->ltd_tgt == NULL)) {
1090                 CERROR("%s: invalid lod device, for idx: %d\n",
1091                        lod2obd(md)->obd_name , idx);
1092                 return -EINVAL;
1093         }
1094
1095         return 0;
1096 }
1097
1098 /**
1099  * lod_initialize_objects() - Instantiate objects for stripes.
1100  * @env: execution environment for this thread
1101  * @lo: LOD object
1102  * @objs: an array of IDs to creates the objects from
1103  * @comp_idx: index of ldo_comp_entries
1104  *
1105  * Allocate and initialize LU-objects representing the stripes. The number
1106  * of the stripes (llc_stripe_count) must be initialized already. The caller
1107  * must ensure nobody else is calling the function on the object at the same
1108  * time. FLDB service must be running to be able to map a FID to the targets
1109  * and find appropriate device representing that target.
1110  *
1111  * Return:
1112  * * %0 if the objects are instantiated successfully
1113  * * %negative error number on failure
1114  */
1115 int lod_initialize_objects(const struct lu_env *env, struct lod_object *lo,
1116                            struct lov_ost_data_v1 *objs, int comp_idx)
1117 {
1118         struct lod_layout_component *lod_comp;
1119         struct lod_thread_info *info = lod_env_info(env);
1120         struct lod_device *md;
1121         struct lu_object *o, *n;
1122         struct lu_device *nd;
1123         struct dt_object **stripe = NULL;
1124         __u32 *ost_indices = NULL;
1125         int stripe_len;
1126         int i, rc = 0;
1127         __u32 idx;
1128         ENTRY;
1129
1130         LASSERT(lo != NULL);
1131         md = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
1132
1133         LASSERT(lo->ldo_comp_cnt != 0 && lo->ldo_comp_entries != NULL);
1134         lod_comp = &lo->ldo_comp_entries[comp_idx];
1135
1136         LASSERT(lod_comp->llc_stripe == NULL);
1137         LASSERT(lod_comp->llc_stripe_count > 0);
1138         LASSERT(lod_comp->llc_stripe_size > 0);
1139
1140         stripe_len = lod_comp->llc_stripe_count;
1141         OBD_ALLOC_PTR_ARRAY(stripe, stripe_len);
1142         if (stripe == NULL)
1143                 RETURN(-ENOMEM);
1144         OBD_ALLOC_PTR_ARRAY(ost_indices, stripe_len);
1145         if (!ost_indices)
1146                 GOTO(out, rc = -ENOMEM);
1147
1148         for (i = 0; i < lod_comp->llc_stripe_count; i++) {
1149                 if (unlikely(lovea_slot_is_dummy(&objs[i])))
1150                         continue;
1151
1152                 ostid_le_to_cpu(&objs[i].l_ost_oi, &info->lti_ostid);
1153                 idx = le32_to_cpu(objs[i].l_ost_idx);
1154                 rc = ostid_to_fid(&info->lti_fid, &info->lti_ostid, idx);
1155                 if (rc != 0)
1156                         GOTO(out, rc);
1157                 LASSERTF(fid_is_sane(&info->lti_fid), ""DFID" insane!\n",
1158                          PFID(&info->lti_fid));
1159                 lod_getref(&md->lod_ost_descs);
1160
1161                 rc = validate_lod_and_idx(md, idx);
1162                 if (unlikely(rc != 0)) {
1163                         lod_putref(md, &md->lod_ost_descs);
1164                         GOTO(out, rc);
1165                 }
1166
1167                 nd = &OST_TGT(md, idx)->ltd_tgt->dd_lu_dev;
1168                 lod_putref(md, &md->lod_ost_descs);
1169
1170                 /* In the function below, .hs_keycmp resolves to
1171                  * u_obj_hop_keycmp() */
1172                 o = lu_object_find_at(env, nd, &info->lti_fid, NULL);
1173                 if (IS_ERR(o))
1174                         GOTO(out, rc = PTR_ERR(o));
1175
1176                 n = lu_object_locate(o->lo_header, nd->ld_type);
1177                 LASSERT(n);
1178
1179                 stripe[i] = container_of(n, struct dt_object, do_lu);
1180                 ost_indices[i] = idx;
1181         }
1182
1183 out:
1184         if (rc != 0) {
1185                 for (i = 0; i < stripe_len; i++)
1186                         if (stripe[i] != NULL)
1187                                 dt_object_put(env, stripe[i]);
1188
1189                 OBD_FREE_PTR_ARRAY(stripe, stripe_len);
1190                 lod_comp->llc_stripe_count = 0;
1191                 if (ost_indices)
1192                         OBD_FREE_PTR_ARRAY(ost_indices, stripe_len);
1193         } else {
1194                 lod_comp->llc_stripe = stripe;
1195                 lod_comp->llc_ost_indices = ost_indices;
1196                 lod_comp->llc_stripes_allocated = stripe_len;
1197         }
1198
1199         RETURN(rc);
1200 }
1201
1202 int lod_init_comp_foreign(struct lod_layout_component *lod_comp, void *lmm)
1203 {
1204         struct lov_foreign_md *lfm;
1205
1206         lfm = (struct lov_foreign_md *)lmm;
1207         lod_comp->llc_length = le32_to_cpu(lfm->lfm_length);
1208         lod_comp->llc_type = le32_to_cpu(lfm->lfm_type);
1209
1210         if (!lov_hsm_type_supported(lod_comp->llc_type)) {
1211                 CDEBUG(D_LAYOUT,
1212                        "Unsupport HSM type: %u length: %u flags: %08X\n",
1213                        lod_comp->llc_type, lod_comp->llc_length,
1214                        le32_to_cpu(lfm->lfm_flags));
1215                 return -EINVAL;
1216         }
1217
1218         /*
1219          * Currently it only stores the file FID as the field @lhm_archive_uuid
1220          * which is used to be the identifier within HSM backend for the archive
1221          * copy.
1222          * Thus the length of foreign layout value (HSM is a kind of foreign
1223          * layout type) is: sizeof(lhm_archive_id) + sizeof(lhm_archive_ver) +
1224          *                  UUID_MAX
1225          * It should fix to support other kinds of identifier for different HSM
1226          * solutions such as S3.
1227          */
1228         if (lod_comp->llc_length != sizeof(struct lov_hsm_base)) {
1229                 CDEBUG(D_LAYOUT, "Invalid HSM len: %u, should be %zu\n",
1230                        lod_comp->llc_length, sizeof(struct lov_hsm_base));
1231                 return -EINVAL;
1232         }
1233
1234         lod_comp->llc_foreign_flags = le32_to_cpu(lfm->lfm_flags);
1235         lov_foreign_hsm_to_cpu(&lod_comp->llc_hsm, lfm);
1236         return 0;
1237 }
1238
1239 /**
1240  * lod_parse_striping() - Instantiate objects for striping.
1241  * @env: execution environment for this thread
1242  * @lo: LOD object
1243  * @buf: buffer storing LOV EA to parse
1244  * @lvf: verify flags when parsing the layout
1245  *
1246  * Parse striping information in @buf and instantiate the objects
1247  * representing the stripes.
1248  *
1249  * Return:
1250  * * %0 if parsing and objects creation succeed
1251  * * %negative error number on failure
1252  */
1253 int lod_parse_striping(const struct lu_env *env, struct lod_object *lo,
1254                        const struct lu_buf *buf, enum layout_verify_flags lvf)
1255 {
1256         struct lod_device *d = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
1257         struct lov_mds_md_v1 *lmm;
1258         struct lov_comp_md_v1 *comp_v1 = NULL;
1259         struct lov_foreign_md *foreign = NULL;
1260         struct lov_ost_data_v1 *objs;
1261         __u32 magic, pattern;
1262         __u16 mirror_cnt = 0;
1263         __u16 comp_cnt;
1264         __u64 dom_size = 0;
1265         int i, rc;
1266         __u16 mirror_id = MIRROR_ID_NEG;
1267         bool stale = false;
1268         int stale_mirrors = 0;
1269         ENTRY;
1270
1271         LASSERT(buf);
1272         LASSERT(buf->lb_buf);
1273         LASSERT(buf->lb_len);
1274         LASSERT(mutex_is_locked(&lo->ldo_layout_mutex));
1275
1276         lmm = (struct lov_mds_md_v1 *)buf->lb_buf;
1277         magic = le32_to_cpu(lmm->lmm_magic);
1278
1279         if (magic != LOV_MAGIC_V1 && magic != LOV_MAGIC_V3 &&
1280             magic != LOV_MAGIC_COMP_V1 && magic != LOV_MAGIC_FOREIGN &&
1281             magic != LOV_MAGIC_SEL)
1282                 GOTO(out, rc = -EINVAL);
1283
1284         lod_striping_free_nolock(env, lo);
1285
1286         if (magic == LOV_MAGIC_COMP_V1 || magic == LOV_MAGIC_SEL) {
1287                 comp_v1 = (struct lov_comp_md_v1 *)lmm;
1288                 comp_cnt = le16_to_cpu(comp_v1->lcm_entry_count);
1289                 if (comp_cnt == 0)
1290                         GOTO(out, rc = -EINVAL);
1291
1292                 lo->ldo_layout_gen = le32_to_cpu(comp_v1->lcm_layout_gen);
1293                 lo->ldo_is_composite = 1;
1294                 mirror_cnt = le16_to_cpu(comp_v1->lcm_mirror_count) + 1;
1295                 if (mirror_cnt > 1)
1296                         lo->ldo_flr_state = le16_to_cpu(comp_v1->lcm_flags) &
1297                                                         LCM_FL_FLR_MASK;
1298                 else
1299                         lo->ldo_flr_state = LCM_FL_NONE;
1300         } else if (magic == LOV_MAGIC_FOREIGN) {
1301                 size_t length;
1302
1303                 foreign = (struct lov_foreign_md *)buf->lb_buf;
1304                 length = offsetof(typeof(*foreign), lfm_value);
1305                 if (buf->lb_len < length ||
1306                     buf->lb_len < (length + le32_to_cpu(foreign->lfm_length))) {
1307                         CDEBUG(D_LAYOUT,
1308                                "buf len %zu too small for lov_foreign_md\n",
1309                                buf->lb_len);
1310                         GOTO(out, rc = -EINVAL);
1311                 }
1312
1313                 /* just cache foreign LOV EA raw */
1314                 rc = lod_alloc_foreign_lov(lo, length);
1315                 if (rc)
1316                         GOTO(out, rc);
1317                 memcpy(lo->ldo_foreign_lov, buf->lb_buf, length);
1318                 GOTO(out, rc);
1319         } else {
1320                 comp_cnt = 1;
1321                 lo->ldo_layout_gen = le16_to_cpu(lmm->lmm_layout_gen);
1322                 lo->ldo_is_composite = 0;
1323         }
1324
1325         rc = lod_alloc_comp_entries(lo, mirror_cnt, comp_cnt);
1326         if (rc)
1327                 GOTO(out, rc);
1328
1329         for (i = 0; i < comp_cnt; i++) {
1330                 struct lod_layout_component *lod_comp;
1331                 struct lu_extent *ext;
1332                 __u32 offs;
1333
1334                 lod_comp = &lo->ldo_comp_entries[i];
1335                 if (lo->ldo_is_composite) {
1336                         offs = le32_to_cpu(comp_v1->lcm_entries[i].lcme_offset);
1337                         lmm = (struct lov_mds_md_v1 *)((char *)comp_v1 + offs);
1338
1339                         ext = &comp_v1->lcm_entries[i].lcme_extent;
1340                         lod_comp->llc_extent.e_start =
1341                                 le64_to_cpu(ext->e_start);
1342                         if (lod_comp->llc_extent.e_start &
1343                             (LOV_MIN_STRIPE_SIZE - 1)) {
1344                                 CDEBUG(D_LAYOUT,
1345                                        "extent start %llu is not a multiple of min size %u\n",
1346                                        lod_comp->llc_extent.e_start,
1347                                        LOV_MIN_STRIPE_SIZE);
1348                                 GOTO(out, rc = -EINVAL);
1349                         }
1350
1351                         lod_comp->llc_extent.e_end = le64_to_cpu(ext->e_end);
1352                         if (lod_comp->llc_extent.e_end != LUSTRE_EOF &&
1353                             lod_comp->llc_extent.e_end &
1354                             (LOV_MIN_STRIPE_SIZE - 1)) {
1355                                 CDEBUG(D_LAYOUT,
1356                                        "extent end %llu is not a multiple of min size %u\n",
1357                                        lod_comp->llc_extent.e_end,
1358                                        LOV_MIN_STRIPE_SIZE);
1359                                 GOTO(out, rc = -EINVAL);
1360                         }
1361
1362                         lod_comp->llc_flags =
1363                                 le32_to_cpu(comp_v1->lcm_entries[i].lcme_flags);
1364
1365                         if (lod_comp->llc_flags & LCME_FL_NOSYNC)
1366                                 lod_comp->llc_timestamp = le64_to_cpu(
1367                                         comp_v1->lcm_entries[i].lcme_timestamp);
1368                         lod_comp->llc_id =
1369                                 le32_to_cpu(comp_v1->lcm_entries[i].lcme_id);
1370                         if (lod_comp->llc_id == LCME_ID_INVAL)
1371                                 GOTO(out, rc = -EINVAL);
1372
1373                         if (lvf & LVF_ALL_STALE) {
1374                                 if (mirror_id_of(lod_comp->llc_id) ==
1375                                     mirror_id) {
1376                                         /* remaining comps in the mirror */
1377                                         stale |= lod_comp->llc_flags &
1378                                                  LCME_FL_STALE;
1379                                 } else {
1380                                         /*
1381                                          * new mirror, check last mirror's
1382                                          * stale-ness
1383                                          */
1384                                         if (stale)
1385                                                 stale_mirrors++;
1386
1387                                         mirror_id =
1388                                                 mirror_id_of(lod_comp->llc_id);
1389
1390                                         /* the first comp of the new mirror */
1391                                         stale = lod_comp->llc_flags &
1392                                                 LCME_FL_STALE;
1393                                 }
1394                         }
1395
1396                         if ((lod_comp->llc_flags & LCME_FL_EXTENSION) &&
1397                             comp_v1->lcm_magic != cpu_to_le32(LOV_MAGIC_SEL)) {
1398                                 CWARN("%s: EXTENSION flags=%x set on component[%u]=%x of non-SEL file "DFID" with magic=%#08x\n",
1399                                       lod2obd(d)->obd_name,
1400                                       lod_comp->llc_flags, lod_comp->llc_id, i,
1401                                       PFID(lod_object_fid(lo)),
1402                                       le32_to_cpu(comp_v1->lcm_magic));
1403                         }
1404
1405                         lod_comp->llc_magic = le32_to_cpu(lmm->lmm_magic);
1406                         if (lod_comp->llc_magic == LOV_MAGIC_FOREIGN) {
1407                                 rc = lod_init_comp_foreign(lod_comp, lmm);
1408                                 if (rc)
1409                                         GOTO(out, rc);
1410                                 continue;
1411                         }
1412                 } else {
1413                         lod_comp->llc_magic = le32_to_cpu(lmm->lmm_magic);
1414                         lod_comp_set_init(lod_comp);
1415                 }
1416
1417                 pattern = le32_to_cpu(lmm->lmm_pattern);
1418                 if (!lov_pattern_supported(lov_pattern(pattern)))
1419                         GOTO(out, rc = -EINVAL);
1420
1421                 if (pattern & LOV_PATTERN_MDT) {
1422                         if (lod_comp->llc_extent.e_start != 0) {
1423                                 CERROR("%s: DOM entry must be the first stripe "
1424                                        "in a mirror\n", lod2obd(d)->obd_name);
1425                                 GOTO(out, rc = -EINVAL);
1426                         }
1427                         if (!dom_size) {
1428                                 dom_size = lod_comp->llc_extent.e_end;
1429                         } else if (dom_size != lod_comp->llc_extent.e_end) {
1430                                 CERROR("%s: DOM entries with different sizes "
1431                                        "%#llx/%#llx\n", lod2obd(d)->obd_name,
1432                                        dom_size, lod_comp->llc_extent.e_end);
1433                                 GOTO(out, rc = -EINVAL);
1434                         }
1435                 }
1436
1437                 lod_comp->llc_pattern = pattern;
1438                 lod_comp->llc_stripe_size = le32_to_cpu(lmm->lmm_stripe_size);
1439                 lod_comp->llc_stripe_count = le16_to_cpu(lmm->lmm_stripe_count);
1440                 lod_comp->llc_layout_gen = le16_to_cpu(lmm->lmm_layout_gen);
1441
1442                 if (lmm->lmm_magic == cpu_to_le32(LOV_MAGIC_V3)) {
1443                         struct lov_mds_md_v3 *v3 = (struct lov_mds_md_v3 *)lmm;
1444
1445                         lod_set_pool(&lod_comp->llc_pool, v3->lmm_pool_name);
1446                         objs = &v3->lmm_objects[0];
1447                 } else {
1448                         lod_set_pool(&lod_comp->llc_pool, NULL);
1449                         objs = &lmm->lmm_objects[0];
1450                 }
1451
1452                 /**
1453                  * If uninstantiated template component has valid l_ost_idx,
1454                  * then user has specified ost list for this component.
1455                  */
1456                 if (!lod_comp_inited(lod_comp)) {
1457                         __u16 stripe_count;
1458
1459                         if (objs[0].l_ost_idx != (__u32)-1UL) {
1460                                 int j;
1461
1462                                 stripe_count = lod_comp_entry_stripe_count(
1463                                                         lo, i, false);
1464                                 if (stripe_count == 0 &&
1465                                     !(lod_comp->llc_pattern & LOV_PATTERN_F_RELEASED) &&
1466                                     !(lod_comp->llc_pattern & LOV_PATTERN_MDT))
1467                                         GOTO(out, rc = -E2BIG);
1468                                 /**
1469                                  * load the user specified ost list, when this
1470                                  * component is instantiated later, it will be
1471                                  * used in lod_alloc_ost_list().
1472                                  */
1473                                 lod_comp->llc_ostlist.op_count = stripe_count;
1474                                 lod_comp->llc_ostlist.op_size =
1475                                         stripe_count * sizeof(__u32);
1476                                 OBD_ALLOC(lod_comp->llc_ostlist.op_array,
1477                                           lod_comp->llc_ostlist.op_size);
1478                                 if (!lod_comp->llc_ostlist.op_array)
1479                                         GOTO(out, rc = -ENOMEM);
1480
1481                                 for (j = 0; j < stripe_count; j++)
1482                                         lod_comp->llc_ostlist.op_array[j] =
1483                                                 le32_to_cpu(objs[j].l_ost_idx);
1484
1485                                 /**
1486                                  * this component OST objects starts from the
1487                                  * first ost_idx, lod_alloc_ost_list() will
1488                                  * check this.
1489                                  */
1490                                 lod_comp->llc_stripe_offset = objs[0].l_ost_idx;
1491                         } else {
1492                                 /**
1493                                  * for uninstantiated component,
1494                                  * lmm_layout_gen stores default stripe offset.
1495                                  */
1496                                 lod_comp->llc_stripe_offset =
1497                                                         lmm->lmm_layout_gen;
1498                         }
1499                 }
1500
1501                 /* skip un-instantiated component object initialization */
1502                 if (!lod_comp_inited(lod_comp))
1503                         continue;
1504
1505                 if (!(lod_comp->llc_pattern & LOV_PATTERN_F_RELEASED) &&
1506                     !(lod_comp->llc_pattern & LOV_PATTERN_MDT)) {
1507                         rc = lod_initialize_objects(env, lo, objs, i);
1508                         if (rc)
1509                                 GOTO(out, rc);
1510                 }
1511         }
1512
1513         if (lo->ldo_is_composite && (lvf & LVF_ALL_STALE)) {
1514                 /* check the last mirror stale-ness */
1515                 if (stale)
1516                         stale_mirrors++;
1517
1518                 if (mirror_cnt == stale_mirrors) {
1519                         rc = -EPERM;
1520                         CERROR("%s: can not set all stale mirrors for "
1521                                DFID": rc = %d\n",
1522                                lod2obd(d)->obd_name, PFID(lod_object_fid(lo)),
1523                                rc);
1524                         GOTO(out, rc);
1525                 }
1526         }
1527
1528         rc = lod_fill_mirrors(lo);
1529         if (rc)
1530                 GOTO(out, rc);
1531
1532 out:
1533         if (rc)
1534                 lod_striping_free_nolock(env, lo);
1535         RETURN(rc);
1536 }
1537
1538 /**
1539  * lod_striping_loaded() - Check whether the striping (LOVEA for regular file,
1540  * LMVEA for directory) is already cached.
1541  * @lo: LOD object
1542  *
1543  * Returns True if the striping is cached, otherwise return false.
1544  */
1545 static bool lod_striping_loaded(struct lod_object *lo)
1546 {
1547         if (S_ISREG(lod2lu_obj(lo)->lo_header->loh_attr) &&
1548             lo->ldo_comp_cached)
1549                 return true;
1550
1551         if (S_ISDIR(lod2lu_obj(lo)->lo_header->loh_attr)) {
1552                 if (lo->ldo_dir_stripe_loaded)
1553                         return true;
1554
1555                 /* Never load LMV stripe for slaves of striped dir */
1556                 if (lo->ldo_dir_slave_stripe)
1557                         return true;
1558         }
1559
1560         return false;
1561 }
1562
1563 /**
1564  * lod_striping_load() - A generic function to initialize the stripe objects.
1565  * @env: execution environment for this thread
1566  * @lo: lo LOD object, where striping is stored and which gets an array of
1567  * references
1568  *
1569  * A protected version of lod_striping_load_locked() - load the striping
1570  * information from storage, parse that and instantiate LU objects to
1571  * represent the stripes.  The LOD object @lo supplies a pointer to the
1572  * next sub-object in the LU stack so we can lock it. Also use @lo to
1573  * return an array of references to the newly instantiated objects.
1574  *
1575  * Return:
1576  * * %0 if parsing and object creation succeed
1577  * * %negative error number on failure
1578  */
1579 int lod_striping_load(const struct lu_env *env, struct lod_object *lo)
1580 {
1581         struct lod_thread_info *info = lod_env_info(env);
1582         struct dt_object *next = dt_object_child(&lo->ldo_obj);
1583         struct lu_buf *buf = &info->lti_buf;
1584         int rc = 0;
1585
1586         ENTRY;
1587
1588         if (!dt_object_exists(next))
1589                 RETURN(0);
1590
1591         if (lod_striping_loaded(lo))
1592                 RETURN(0);
1593
1594         mutex_lock(&lo->ldo_layout_mutex);
1595         if (lod_striping_loaded(lo))
1596                 GOTO(unlock, rc = 0);
1597
1598         if (S_ISREG(lod2lu_obj(lo)->lo_header->loh_attr)) {
1599                 rc = lod_get_lov_ea(env, lo);
1600                 if (rc <= 0)
1601                         GOTO(unlock, rc);
1602
1603                 /*
1604                  * there is LOV EA (striping information) in this object
1605                  * let's parse it and create in-core objects for the stripes
1606                  */
1607                 *buf = info->lti_ea_buf;
1608                 rc = lod_parse_striping(env, lo, buf, 0);
1609                 if (rc == 0)
1610                         lo->ldo_comp_cached = 1;
1611         } else if (S_ISDIR(lod2lu_obj(lo)->lo_header->loh_attr)) {
1612                 rc = lod_get_lmv_ea(env, lo);
1613
1614                 if (rc > (int)sizeof(struct lmv_foreign_md)) {
1615                         struct lmv_foreign_md *lfm = info->lti_ea_buf.lb_buf;
1616
1617                         if (le32_to_cpu(lfm->lfm_magic) == LMV_MAGIC_FOREIGN) {
1618                                 lo->ldo_foreign_lmv = info->lti_ea_buf.lb_buf;
1619                                 lo->ldo_foreign_lmv_size =
1620                                         info->lti_ea_buf.lb_len;
1621                                 info->lti_ea_buf = LU_BUF_NULL;
1622
1623                                 lo->ldo_dir_stripe_loaded = 1;
1624                                 lo->ldo_is_foreign = 1;
1625                                 GOTO(unlock, rc = 0);
1626                         }
1627                 }
1628
1629                 if (rc < (int)sizeof(struct lmv_mds_md_v1)) {
1630                         /* Let's set stripe_loaded to avoid further
1631                          * stripe loading especially for non-stripe directory,
1632                          * which can hurt performance. (See LU-9840)
1633                          */
1634                         if (rc == 0)
1635                                 lo->ldo_dir_stripe_loaded = 1;
1636                         GOTO(unlock, rc = rc > 0 ? -EINVAL : rc);
1637                 }
1638                 *buf = info->lti_ea_buf;
1639                 if (rc == sizeof(struct lmv_mds_md_v1)) {
1640                         rc = lod_load_lmv_shards(env, lo, buf, true);
1641                         if (buf->lb_buf != info->lti_ea_buf.lb_buf) {
1642                                 lu_buf_free(&info->lti_ea_buf);
1643                                 info->lti_ea_buf = *buf;
1644                         }
1645
1646                         if (rc < 0)
1647                                 GOTO(unlock, rc);
1648                 }
1649
1650                 /*
1651                  * there is LMV EA (striping information) in this object
1652                  * let's parse it and create in-core objects for the stripes
1653                  */
1654                 rc = lod_parse_dir_striping(env, lo, buf);
1655                 if (rc == 0)
1656                         lo->ldo_dir_stripe_loaded = 1;
1657         }
1658         EXIT;
1659 unlock:
1660         mutex_unlock(&lo->ldo_layout_mutex);
1661
1662         return rc;
1663 }
1664
1665 int lod_striping_reload(const struct lu_env *env, struct lod_object *lo,
1666                         const struct lu_buf *buf, enum layout_verify_flags lvf)
1667 {
1668         int rc;
1669
1670         ENTRY;
1671
1672         mutex_lock(&lo->ldo_layout_mutex);
1673         rc = lod_parse_striping(env, lo, buf, lvf);
1674         mutex_unlock(&lo->ldo_layout_mutex);
1675
1676         RETURN(rc);
1677 }
1678
1679 /**
1680  * lod_verify_v1v3() - Verify lov_user_md_v1/v3 striping.
1681  * @d: LOD device
1682  * @buf: buffer with LOV EA to verify
1683  * @is_from_disk: 0 - from user, allow some fields to be 0
1684  *                1 - from disk, do not allow
1685  *
1686  * Check the validity of all fields including the magic, stripe size,
1687  * stripe count, stripe offset and that the pool is present.  Also check
1688  * that each target index points to an existing target. The additional
1689  * @is_from_disk turns additional checks. In some cases zero fields
1690  * are allowed (like pattern=0).
1691  *
1692  * Return:
1693  * * %0 if the striping is valid
1694  * * %-EINVAL if striping is invalid
1695  */
1696 static int lod_verify_v1v3(struct lod_device *d, const struct lu_buf *buf,
1697                            bool is_from_disk)
1698 {
1699         struct lov_user_md_v1   *lum;
1700         struct lov_user_md_v3   *lum3;
1701         struct lod_pool_desc    *pool = NULL;
1702         __u32                    magic;
1703         __u32                    stripe_size;
1704         __u16                    stripe_count;
1705         __u16                    stripe_offset;
1706         size_t                   lum_size;
1707         int                      rc = 0;
1708         ENTRY;
1709
1710         lum = buf->lb_buf;
1711
1712         if (buf->lb_len < sizeof(*lum)) {
1713                 CDEBUG(D_LAYOUT, "buf len %zu too small for lov_user_md\n",
1714                        buf->lb_len);
1715                 GOTO(out, rc = -EINVAL);
1716         }
1717
1718         magic = le32_to_cpu(lum->lmm_magic) & ~LOV_MAGIC_DEFINED;
1719         if (magic != LOV_USER_MAGIC_V1 &&
1720             magic != LOV_USER_MAGIC_V3 &&
1721             magic != LOV_USER_MAGIC_SPECIFIC) {
1722                 CDEBUG(D_LAYOUT, "bad userland LOV MAGIC: %#x\n",
1723                        le32_to_cpu(lum->lmm_magic));
1724                 GOTO(out, rc = -EINVAL);
1725         }
1726
1727         /* the user uses "0" for default stripe pattern normally. */
1728         if (!is_from_disk && lum->lmm_pattern == LOV_PATTERN_NONE)
1729                 lum->lmm_pattern = cpu_to_le32(LOV_PATTERN_RAID0);
1730
1731         if (!lov_pattern_supported(le32_to_cpu(lum->lmm_pattern))) {
1732                 CDEBUG(D_LAYOUT, "bad userland stripe pattern: %#x\n",
1733                        le32_to_cpu(lum->lmm_pattern));
1734                 GOTO(out, rc = -EINVAL);
1735         }
1736
1737         /* a released lum comes from creating orphan on hsm release,
1738          * doesn't make sense to verify it. */
1739         if (le32_to_cpu(lum->lmm_pattern) & LOV_PATTERN_F_RELEASED)
1740                 GOTO(out, rc = 0);
1741
1742         /* 64kB is the largest common page size we see (ia64), and matches the
1743          * check in lfs */
1744         stripe_size = le32_to_cpu(lum->lmm_stripe_size);
1745         if (stripe_size & (LOV_MIN_STRIPE_SIZE - 1)) {
1746                 CDEBUG(D_LAYOUT, "stripe size %u not a multiple of %u\n",
1747                        stripe_size, LOV_MIN_STRIPE_SIZE);
1748                 GOTO(out, rc = -EINVAL);
1749         }
1750
1751         stripe_offset = le16_to_cpu(lum->lmm_stripe_offset);
1752         if (!is_from_disk && stripe_offset != LOV_OFFSET_DEFAULT &&
1753             !(lov_pattern(le32_to_cpu(lum->lmm_pattern)) & LOV_PATTERN_MDT)) {
1754                 /* if offset is not within valid range [0, osts_size) */
1755                 if (stripe_offset >= d->lod_ost_descs.ltd_tgts_size) {
1756                         CDEBUG(D_LAYOUT, "stripe offset %u >= bitmap size %u\n",
1757                                stripe_offset, d->lod_ost_descs.ltd_tgts_size);
1758                         GOTO(out, rc = -EINVAL);
1759                 }
1760
1761                 /* if lmm_stripe_offset is *not* in bitmap */
1762                 if (!test_bit(stripe_offset, d->lod_ost_bitmap)) {
1763                         CDEBUG(D_LAYOUT, "stripe offset %u not in bitmap\n",
1764                                stripe_offset);
1765                         GOTO(out, rc = -EINVAL);
1766                 }
1767         }
1768
1769         if (magic == LOV_USER_MAGIC_V1)
1770                 lum_size = offsetof(struct lov_user_md_v1,
1771                                     lmm_objects[0]);
1772         else if (magic == LOV_USER_MAGIC_V3 || magic == LOV_USER_MAGIC_SPECIFIC)
1773                 lum_size = offsetof(struct lov_user_md_v3,
1774                                     lmm_objects[0]);
1775         else
1776                 GOTO(out, rc = -EINVAL);
1777
1778         stripe_count = le16_to_cpu(lum->lmm_stripe_count);
1779         if (buf->lb_len < lum_size) {
1780                 CDEBUG(D_LAYOUT, "invalid buf len %zu/%zu for lov_user_md with "
1781                        "magic %#x and stripe_count %u\n",
1782                        buf->lb_len, lum_size, magic, stripe_count);
1783                 GOTO(out, rc = -EINVAL);
1784         }
1785
1786         if (!(magic == LOV_USER_MAGIC_V3 || magic == LOV_USER_MAGIC_SPECIFIC))
1787                 goto out;
1788
1789         lum3 = buf->lb_buf;
1790         /* In the function below, .hs_keycmp resolves to
1791          * pool_hashkey_keycmp() */
1792         pool = lod_find_pool(d, lum3->lmm_pool_name);
1793         if (pool == NULL)
1794                 goto out;
1795
1796         if (!is_from_disk && stripe_offset != LOV_OFFSET_DEFAULT) {
1797                 rc = lod_check_index_in_pool(stripe_offset, pool);
1798                 if (rc < 0)
1799                         GOTO(out, rc = -EINVAL);
1800         }
1801
1802         if (is_from_disk && stripe_count > pool_tgt_count(pool)) {
1803                 CDEBUG(D_LAYOUT, "stripe count %u > # OSTs %u in the pool\n",
1804                        stripe_count, pool_tgt_count(pool));
1805                 GOTO(out, rc = -EINVAL);
1806         }
1807
1808 out:
1809         if (pool != NULL)
1810                 lod_pool_putref(pool);
1811
1812         RETURN(rc);
1813 }
1814
1815 static inline
1816 struct lov_comp_md_entry_v1 *comp_entry_v1(struct lov_comp_md_v1 *comp, int i)
1817 {
1818         LASSERTF((le32_to_cpu(comp->lcm_magic) & ~LOV_MAGIC_DEFINED) ==
1819                  LOV_USER_MAGIC_COMP_V1 ||
1820                  (le32_to_cpu(comp->lcm_magic) & ~LOV_MAGIC_DEFINED) ==
1821                  LOV_USER_MAGIC_SEL, "Wrong magic %x\n",
1822                  le32_to_cpu(comp->lcm_magic));
1823         LASSERTF(i >= 0 && i < le16_to_cpu(comp->lcm_entry_count),
1824                  "bad index %d, max = %d\n",
1825                  i, le16_to_cpu(comp->lcm_entry_count));
1826
1827         return &comp->lcm_entries[i];
1828 }
1829
1830 #define for_each_comp_entry_v1(comp, entry) \
1831         for (entry = comp_entry_v1(comp, 0); \
1832              entry <= comp_entry_v1(comp, \
1833                                    le16_to_cpu(comp->lcm_entry_count) - 1); \
1834              entry++)
1835
1836 static int lod_erase_dom_stripe(struct lov_comp_md_v1 *comp_v1,
1837                                 struct lov_comp_md_entry_v1 *dom_ent)
1838 {
1839         struct lov_comp_md_entry_v1 *ent;
1840         __u16 entries;
1841         __u32 dom_off, dom_size, comp_size, off;
1842         void *src, *dst;
1843         unsigned int size, shift;
1844
1845         entries = le16_to_cpu(comp_v1->lcm_entry_count) - 1;
1846         LASSERT(entries > 0);
1847         comp_v1->lcm_entry_count = cpu_to_le16(entries);
1848
1849         comp_size = le32_to_cpu(comp_v1->lcm_size);
1850         dom_off = le32_to_cpu(dom_ent->lcme_offset);
1851         dom_size = le32_to_cpu(dom_ent->lcme_size);
1852
1853         /* all entries offsets are shifted by entry size at least */
1854         shift = sizeof(*dom_ent);
1855         for_each_comp_entry_v1(comp_v1, ent) {
1856                 off = le32_to_cpu(ent->lcme_offset);
1857                 if (off == dom_off) {
1858                         /* Entry deletion creates two holes in layout data:
1859                          * - hole in entries array
1860                          * - hole in layout data at dom_off with dom_size
1861                          *
1862                          * First memmove is one entry shift from next entry
1863                          * start with size up to dom_off in blob
1864                          */
1865                         dst = (void *)ent;
1866                         src = (void *)(ent + 1);
1867                         size = (unsigned long)((void *)comp_v1 + dom_off - src);
1868                         memmove(dst, src, size);
1869                         /* take 'off' from just moved entry */
1870                         off = le32_to_cpu(ent->lcme_offset);
1871                         /* second memmove is blob tail after 'off' up to
1872                          * component end
1873                          */
1874                         dst = (void *)comp_v1 + dom_off - sizeof(*ent);
1875                         src = (void *)comp_v1 + off;
1876                         size = (unsigned long)(comp_size - off);
1877                         memmove(dst, src, size);
1878                         /* all entries offsets after DoM entry are shifted by
1879                          * dom_size additionally
1880                          */
1881                         shift += dom_size;
1882                 }
1883                 ent->lcme_offset = cpu_to_le32(off - shift);
1884         }
1885         comp_v1->lcm_size = cpu_to_le32(comp_size - shift);
1886
1887         /* notify a caller to re-check entry */
1888         return -ERESTART;
1889 }
1890
1891 void lod_dom_stripesize_recalc(struct lod_device *d)
1892 {
1893         __u64 threshold_mb = d->lod_dom_threshold_free_mb;
1894         __u32 max_size = d->lod_dom_stripesize_max_kb;
1895         __u32 def_size = d->lod_dom_stripesize_cur_kb;
1896
1897         /* use maximum allowed value if free space is above threshold */
1898         if (d->lod_lsfs_free_mb >= threshold_mb) {
1899                 def_size = max_size;
1900         } else if (!d->lod_lsfs_free_mb || max_size <= LOD_DOM_MIN_SIZE_KB) {
1901                 def_size = 0;
1902         } else {
1903                 /* recalc threshold like it would be with def_size as max */
1904                 threshold_mb = mult_frac(threshold_mb, def_size, max_size);
1905                 if (d->lod_lsfs_free_mb < threshold_mb)
1906                         def_size = rounddown(def_size / 2, LOD_DOM_MIN_SIZE_KB);
1907                 else if (d->lod_lsfs_free_mb > threshold_mb * 2)
1908                         def_size = max_t(unsigned int, def_size * 2,
1909                                          LOD_DOM_MIN_SIZE_KB);
1910         }
1911
1912         if (d->lod_dom_stripesize_cur_kb != def_size) {
1913                 CDEBUG(D_LAYOUT, "Change default DOM stripe size %d->%d\n",
1914                        d->lod_dom_stripesize_cur_kb, def_size);
1915                 d->lod_dom_stripesize_cur_kb = def_size;
1916         }
1917 }
1918
1919 static __u32 lod_dom_stripesize_limit(const struct lu_env *env,
1920                                       struct lod_device *d)
1921 {
1922         int rc;
1923
1924         /* set bfree as fraction of total space */
1925         if (CFS_FAIL_CHECK(OBD_FAIL_MDS_STATFS_SPOOF)) {
1926                 spin_lock(&d->lod_lsfs_lock);
1927                 d->lod_lsfs_free_mb = mult_frac(d->lod_lsfs_total_mb,
1928                                         min_t(int, cfs_fail_val, 100), 100);
1929                 GOTO(recalc, rc = 0);
1930         }
1931
1932         if (d->lod_lsfs_age < ktime_get_seconds() - LOD_DOM_SFS_MAX_AGE) {
1933                 struct obd_statfs sfs;
1934
1935                 spin_lock(&d->lod_lsfs_lock);
1936                 if (d->lod_lsfs_age > ktime_get_seconds() - LOD_DOM_SFS_MAX_AGE)
1937                         GOTO(unlock, rc = 0);
1938
1939                 d->lod_lsfs_age = ktime_get_seconds();
1940                 spin_unlock(&d->lod_lsfs_lock);
1941                 rc = dt_statfs(env, d->lod_child, &sfs);
1942                 if (rc) {
1943                         CDEBUG(D_LAYOUT,
1944                                "%s: failed to get OSD statfs: rc = %d\n",
1945                                lod2obd(d)->obd_name, rc);
1946                         GOTO(out, rc);
1947                 }
1948                 /* udpate local OSD cached statfs data */
1949                 spin_lock(&d->lod_lsfs_lock);
1950                 d->lod_lsfs_total_mb = (sfs.os_blocks * sfs.os_bsize) >> 20;
1951                 d->lod_lsfs_free_mb = (sfs.os_bfree * sfs.os_bsize) >> 20;
1952 recalc:
1953                 lod_dom_stripesize_recalc(d);
1954 unlock:
1955                 spin_unlock(&d->lod_lsfs_lock);
1956         }
1957 out:
1958         return d->lod_dom_stripesize_cur_kb << 10;
1959 }
1960
1961 static int lod_dom_stripesize_choose(const struct lu_env *env,
1962                                      struct lod_device *d,
1963                                      struct lov_comp_md_v1 *comp_v1,
1964                                      struct lov_comp_md_entry_v1 *dom_ent,
1965                                      __u32 stripe_size)
1966 {
1967         struct lov_comp_md_entry_v1 *ent;
1968         struct lu_extent *dom_ext, *ext;
1969         struct lov_user_md_v1 *lum;
1970         __u32 max_stripe_size;
1971         __u16 mid, dom_mid;
1972         int rc = 0;
1973         bool dom_next_entry = false;
1974
1975         dom_ext = &dom_ent->lcme_extent;
1976         dom_mid = mirror_id_of(le32_to_cpu(dom_ent->lcme_id));
1977         max_stripe_size = lod_dom_stripesize_limit(env, d);
1978
1979         /* Check stripe size againts current per-MDT limit */
1980         if (stripe_size <= max_stripe_size)
1981                 return 0;
1982
1983         lum = (void *)comp_v1 + le32_to_cpu(dom_ent->lcme_offset);
1984         CDEBUG(D_LAYOUT, "overwrite DoM component size %u with MDT limit %u\n",
1985                stripe_size, max_stripe_size);
1986         lum->lmm_stripe_size = cpu_to_le32(max_stripe_size);
1987
1988         /* In common case the DoM stripe is first entry in a mirror and
1989          * can be deleted only if it is not single entry in layout or
1990          * mirror, otherwise error should be returned.
1991          */
1992         for_each_comp_entry_v1(comp_v1, ent) {
1993                 if (ent == dom_ent)
1994                         continue;
1995
1996                 mid = mirror_id_of(le32_to_cpu(ent->lcme_id));
1997                 if (mid != dom_mid)
1998                         continue;
1999
2000                 ext = &ent->lcme_extent;
2001                 if (ext->e_start != dom_ext->e_end)
2002                         continue;
2003
2004                 /* Found next component after the DoM one with the same
2005                  * mirror_id and adjust its start with DoM component end.
2006                  *
2007                  * NOTE: we are considering here that there can be only one
2008                  * DoM component in a file, all replicas are located on OSTs
2009                  * always and don't need adjustment since use own layouts.
2010                  */
2011                 ext->e_start = cpu_to_le64(max_stripe_size);
2012                 dom_next_entry = true;
2013                 break;
2014         }
2015
2016         if (max_stripe_size == 0) {
2017                 /* DoM component size is zero due to server setting, remove
2018                  * it from the layout but only if next component exists in
2019                  * the same mirror. That must be checked prior calling the
2020                  * lod_erase_dom_stripe().
2021                  */
2022                 if (!dom_next_entry)
2023                         return -EFBIG;
2024
2025                 rc = lod_erase_dom_stripe(comp_v1, dom_ent);
2026         } else {
2027                 /* Update DoM extent end finally */
2028                 dom_ext->e_end = cpu_to_le64(max_stripe_size);
2029         }
2030
2031         return rc;
2032 }
2033
2034 /**
2035  * lod_verify_striping() - Verify LOV striping.
2036  * @env: execution environment for this thread
2037  * @d: LOD device
2038  * @lo: LOD object
2039  * @buf: buffer with LOV EA to verify
2040  * @is_from_disk: 0 - from user, allow some fields to be 0
2041  *                1 - from disk, do not allow
2042  *
2043  * Return:
2044  * * %0 if the striping is valid
2045  * * %-EINVAL if striping is invalid
2046  */
2047 int lod_verify_striping(const struct lu_env *env, struct lod_device *d,
2048                         struct lod_object *lo, const struct lu_buf *buf,
2049                         bool is_from_disk)
2050 {
2051         struct lov_user_md_v1   *lum;
2052         struct lov_comp_md_v1   *comp_v1;
2053         struct lov_comp_md_entry_v1     *ent;
2054         struct lu_extent        *ext;
2055         struct lu_buf   tmp;
2056         __u64   prev_end = 0;
2057         __u32   stripe_size = 0;
2058         __u16   prev_mid = -1, mirror_id = -1;
2059         __u32   mirror_count;
2060         __u32   magic;
2061         int     rc = 0;
2062         ENTRY;
2063
2064         if (buf->lb_len < sizeof(lum->lmm_magic)) {
2065                 CDEBUG(D_LAYOUT, "invalid buf len %zu\n", buf->lb_len);
2066                 RETURN(-EINVAL);
2067         }
2068
2069         lum = buf->lb_buf;
2070
2071         magic = le32_to_cpu(lum->lmm_magic) & ~LOV_MAGIC_DEFINED;
2072         /* treat foreign LOV EA/object case first
2073          * XXX is it expected to try setting again a foreign?
2074          * XXX should we care about different current vs new layouts ?
2075          */
2076         if (unlikely(magic == LOV_USER_MAGIC_FOREIGN)) {
2077                 struct lov_foreign_md *lfm = buf->lb_buf;
2078
2079                 if (buf->lb_len < offsetof(typeof(*lfm), lfm_value)) {
2080                         CDEBUG(D_LAYOUT,
2081                                "buf len %zu < min lov_foreign_md size (%zu)\n",
2082                                buf->lb_len, offsetof(typeof(*lfm),
2083                                lfm_value));
2084                         RETURN(-EINVAL);
2085                 }
2086
2087                 if (lov_foreign_size_le(lfm) > buf->lb_len) {
2088                         CDEBUG(D_LAYOUT,
2089                                "buf len %zu < this lov_foreign_md size (%zu)\n",
2090                                buf->lb_len, lov_foreign_size_le(lfm));
2091                         RETURN(-EINVAL);
2092                 }
2093                 /* Don't do anything with foreign layouts */
2094                 RETURN(0);
2095         }
2096
2097         /* normal LOV/layout cases */
2098
2099         if (buf->lb_len < sizeof(*lum)) {
2100                 CDEBUG(D_LAYOUT, "buf len %zu too small for lov_user_md\n",
2101                        buf->lb_len);
2102                 RETURN(-EINVAL);
2103         }
2104
2105         switch (magic) {
2106         case LOV_USER_MAGIC_FOREIGN:
2107                 RETURN(0);
2108         case LOV_USER_MAGIC_V1:
2109         case LOV_USER_MAGIC_V3:
2110         case LOV_USER_MAGIC_SPECIFIC:
2111                 if (lov_pattern(le32_to_cpu(lum->lmm_pattern)) &
2112                     LOV_PATTERN_MDT) {
2113                         /* DoM must use composite layout */
2114                         CDEBUG(D_LAYOUT, "DoM without composite layout\n");
2115                         RETURN(-EINVAL);
2116                 }
2117                 RETURN(lod_verify_v1v3(d, buf, is_from_disk));
2118         case LOV_USER_MAGIC_COMP_V1:
2119         case LOV_USER_MAGIC_SEL:
2120                 break;
2121         default:
2122                 CDEBUG(D_LAYOUT, "bad userland LOV MAGIC: %#x\n",
2123                        le32_to_cpu(lum->lmm_magic));
2124                 RETURN(-EINVAL);
2125         }
2126
2127         /* magic == LOV_USER_MAGIC_COMP_V1 */
2128         comp_v1 = buf->lb_buf;
2129         if (buf->lb_len < le32_to_cpu(comp_v1->lcm_size)) {
2130                 CDEBUG(D_LAYOUT, "buf len %zu is less than %u\n",
2131                        buf->lb_len, le32_to_cpu(comp_v1->lcm_size));
2132                 RETURN(-EINVAL);
2133         }
2134
2135 recheck:
2136         mirror_count = 0;
2137         if (le16_to_cpu(comp_v1->lcm_entry_count) == 0) {
2138                 CDEBUG(D_LAYOUT, "entry count is zero\n");
2139                 RETURN(-EINVAL);
2140         }
2141
2142         if (S_ISREG(lod2lu_obj(lo)->lo_header->loh_attr) &&
2143             lo->ldo_comp_cnt > 0) {
2144                 /* could be called from lustre.lov.add */
2145                 __u32 cnt = lo->ldo_comp_cnt;
2146
2147                 ext = &lo->ldo_comp_entries[cnt - 1].llc_extent;
2148                 prev_end = ext->e_end;
2149
2150                 ++mirror_count;
2151         }
2152
2153         for_each_comp_entry_v1(comp_v1, ent) {
2154                 ext = &ent->lcme_extent;
2155
2156                 if (le64_to_cpu(ext->e_start) > le64_to_cpu(ext->e_end) ||
2157                     le64_to_cpu(ext->e_start) & (LOV_MIN_STRIPE_SIZE - 1) ||
2158                     ((__s64)le64_to_cpu(ext->e_start) < 0 &&
2159                     le64_to_cpu(ext->e_start) != LUSTRE_EOF) ||
2160                     (le64_to_cpu(ext->e_end) != LUSTRE_EOF &&
2161                     le64_to_cpu(ext->e_end) & (LOV_MIN_STRIPE_SIZE - 1)) ||
2162                     ((__s64)le64_to_cpu(ext->e_end) < 0 &&
2163                     le64_to_cpu(ext->e_end) != LUSTRE_EOF)) {
2164                         CDEBUG(D_LAYOUT, "invalid extent "DEXT"\n",
2165                                le64_to_cpu(ext->e_start),
2166                                le64_to_cpu(ext->e_end));
2167                         RETURN(-EINVAL);
2168                 }
2169
2170                 if (is_from_disk) {
2171                         /* lcme_id contains valid value */
2172                         if (le32_to_cpu(ent->lcme_id) == 0 ||
2173                             le32_to_cpu(ent->lcme_id) > LCME_ID_MAX) {
2174                                 CDEBUG(D_LAYOUT, "invalid id %u\n",
2175                                        le32_to_cpu(ent->lcme_id));
2176                                 RETURN(-EINVAL);
2177                         }
2178
2179                         if (le16_to_cpu(comp_v1->lcm_mirror_count) > 0) {
2180                                 mirror_id = mirror_id_of(
2181                                                 le32_to_cpu(ent->lcme_id));
2182
2183                                 /* first component must start with 0 */
2184                                 if (mirror_id != prev_mid &&
2185                                     le64_to_cpu(ext->e_start) != 0) {
2186                                         CDEBUG(D_LAYOUT,
2187                                                "invalid start:%llu, expect:0\n",
2188                                                le64_to_cpu(ext->e_start));
2189                                         RETURN(-EINVAL);
2190                                 }
2191
2192                                 prev_mid = mirror_id;
2193                         }
2194                 }
2195
2196                 if (le64_to_cpu(ext->e_start) == 0) {
2197                         ++mirror_count;
2198                         prev_end = 0;
2199                 }
2200
2201                 /* the next must be adjacent with the previous one */
2202                 if (le64_to_cpu(ext->e_start) != prev_end) {
2203                         CDEBUG(D_LAYOUT,
2204                                "invalid start actual:%llu, expect:%llu\n",
2205                                le64_to_cpu(ext->e_start), prev_end);
2206                         RETURN(-EINVAL);
2207                 }
2208
2209                 tmp.lb_buf = (char *)comp_v1 + le32_to_cpu(ent->lcme_offset);
2210                 tmp.lb_len = le32_to_cpu(ent->lcme_size);
2211
2212                 lum = tmp.lb_buf;
2213                 if (le32_to_cpu(lum->lmm_magic) == LOV_MAGIC_FOREIGN) {
2214                         struct lov_foreign_md *lfm;
2215                         struct lov_hsm_md *lhm;
2216                         u32 hsmsize;
2217                         u32 ftype;
2218
2219                         /*
2220                          * Currently when the foreign layout is used as a basic
2221                          * layout component, it only supports HSM foreign types:
2222                          * LU_FOREIGN_TYPE_{POSIX, S3, PCCRW, PCCRO}.
2223                          */
2224                         lfm = (struct lov_foreign_md *)lum;
2225                         ftype = le32_to_cpu(lfm->lfm_type);
2226                         if (!lov_hsm_type_supported(ftype)) {
2227                                 CDEBUG(D_LAYOUT,
2228                                        "Foreign type %#x is not HSM\n", ftype);
2229                                 RETURN(-EINVAL);
2230                         }
2231
2232                         /* Current HSM component must cover [0, EOF]. */
2233                         if (le64_to_cpu(ext->e_start) > 0) {
2234                                 CDEBUG(D_LAYOUT, "Invalid HSM component with %llu extent start\n",
2235                                        le64_to_cpu(ext->e_start));
2236                                 RETURN(-EINVAL);
2237                         }
2238                         if (le64_to_cpu(ext->e_end) != LUSTRE_EOF) {
2239                                 CDEBUG(D_LAYOUT, "Invalid HSM component with %llu extent end\n",
2240                                        le64_to_cpu(ext->e_end));
2241                                 RETURN(-EINVAL);
2242                         }
2243
2244                         lhm = (struct lov_hsm_md *)lfm;
2245                         hsmsize = lov_foreign_size_le(lhm);
2246
2247                         if (le32_to_cpu(lhm->lhm_length) !=
2248                             sizeof(struct lov_hsm_base)) {
2249                                 CDEBUG(D_LAYOUT,
2250                                        "Invalid HSM component size %u != %u\n",
2251                                        le32_to_cpu(ent->lcme_size), hsmsize);
2252                                 RETURN(-EINVAL);
2253                         }
2254
2255                         if (le32_to_cpu(ent->lcme_size) < hsmsize) {
2256                                 CDEBUG(D_LAYOUT,
2257                                        "Invalid HSM component size %u != %u\n",
2258                                        le32_to_cpu(ent->lcme_size), hsmsize);
2259                                 RETURN(-EINVAL);
2260                         }
2261                         if (le32_to_cpu(lhm->lhm_flags) & ~HSM_FLAGS_MASK ||
2262                             !(le32_to_cpu(lhm->lhm_flags) & HSM_FLAGS_MASK)) {
2263                                 CDEBUG(D_LAYOUT,
2264                                        "Invalid HSM component flags %#x\n",
2265                                        le32_to_cpu(lhm->lhm_flags));
2266                                 RETURN(-EINVAL);
2267                         }
2268                         continue;
2269                 }
2270
2271                 /* Check DoM entry is always the first one */
2272                 if (lov_pattern(le32_to_cpu(lum->lmm_pattern)) &
2273                     LOV_PATTERN_MDT) {
2274                         /* DoM component must be the first in a mirror */
2275                         if (le64_to_cpu(ext->e_start) > 0) {
2276                                 CDEBUG(D_LAYOUT, "invalid DoM component "
2277                                        "with %llu extent start\n",
2278                                        le64_to_cpu(ext->e_start));
2279                                 RETURN(-EINVAL);
2280                         }
2281                         stripe_size = le32_to_cpu(lum->lmm_stripe_size);
2282                         /* There is just one stripe on MDT and it must
2283                          * cover whole component size. */
2284                         if (stripe_size != le64_to_cpu(ext->e_end)) {
2285                                 CDEBUG(D_LAYOUT, "invalid DoM layout "
2286                                        "stripe size %u != %llu "
2287                                        "(component size)\n",
2288                                        stripe_size, prev_end);
2289                                 RETURN(-EINVAL);
2290                         }
2291                         /* Check and adjust stripe size by per-MDT limit */
2292                         rc = lod_dom_stripesize_choose(env, d, comp_v1, ent,
2293                                                        stripe_size);
2294                         /* DoM entry was removed, re-check layout from start */
2295                         if (rc == -ERESTART)
2296                                 goto recheck;
2297                         else if (rc)
2298                                 RETURN(rc);
2299
2300                         if (le16_to_cpu(lum->lmm_stripe_count) == 1)
2301                                 lum->lmm_stripe_count = 0;
2302                         /* Any stripe count is forbidden on DoM component */
2303                         if (lum->lmm_stripe_count > 0) {
2304                                 CDEBUG(D_LAYOUT,
2305                                        "invalid DoM layout stripe count %u, must be 0\n",
2306                                        le16_to_cpu(lum->lmm_stripe_count));
2307                                 RETURN(-EINVAL);
2308                         }
2309
2310                         /* Any pool is forbidden on DoM component */
2311                         if (lum->lmm_magic == LOV_USER_MAGIC_V3) {
2312                                 struct lov_user_md_v3 *v3 = (void *)lum;
2313
2314                                 if (v3->lmm_pool_name[0] != '\0') {
2315                                         CDEBUG(D_LAYOUT,
2316                                                "DoM component cannot have pool assigned\n");
2317                                         RETURN(-EINVAL);
2318                                 }
2319                         }
2320                 }
2321
2322                 prev_end = le64_to_cpu(ext->e_end);
2323
2324                 rc = lod_verify_v1v3(d, &tmp, is_from_disk);
2325                 if (rc)
2326                         RETURN(rc);
2327
2328                 if (prev_end == LUSTRE_EOF || ext->e_start == prev_end)
2329                         continue;
2330
2331                 /* extent end must be aligned with the stripe_size */
2332                 stripe_size = le32_to_cpu(lum->lmm_stripe_size);
2333                 if (stripe_size && prev_end % stripe_size) {
2334                         CDEBUG(D_LAYOUT, "stripe size isn't aligned, "
2335                                "stripe_sz: %u, [%llu, %llu)\n",
2336                                stripe_size, ext->e_start, prev_end);
2337                         RETURN(-EINVAL);
2338                 }
2339         }
2340
2341         /* make sure that the mirror_count is telling the truth */
2342         if (mirror_count != le16_to_cpu(comp_v1->lcm_mirror_count) + 1)
2343                 RETURN(-EINVAL);
2344
2345         RETURN(0);
2346 }
2347
2348 /**
2349  * lod_fix_desc_stripe_size() - set the default stripe size, if unset.
2350  * @val: val number of bytes per OST stripe [in,out]
2351  *
2352  * The minimum stripe size is 64KB to ensure that a single stripe is an
2353  * even multiple of a client PAGE_SIZE (IA64, PPC, etc).  Otherwise, it
2354  * is difficult to split dirty pages across OSCs during writes.
2355  */
2356 void lod_fix_desc_stripe_size(__u64 *val)
2357 {
2358         if (*val < LOV_MIN_STRIPE_SIZE) {
2359                 if (*val != 0)
2360                         LCONSOLE_INFO("Increasing default stripe size to "
2361                                       "minimum value %u\n",
2362                                       LOV_DESC_STRIPE_SIZE_DEFAULT);
2363                 *val = LOV_DESC_STRIPE_SIZE_DEFAULT;
2364         } else if (*val & (LOV_MIN_STRIPE_SIZE - 1)) {
2365                 *val &= ~(LOV_MIN_STRIPE_SIZE - 1);
2366                 LCONSOLE_WARN("Changing default stripe size to %llu (a "
2367                               "multiple of %u)\n",
2368                               *val, LOV_MIN_STRIPE_SIZE);
2369         }
2370 }
2371
2372 /**
2373  * lod_fix_desc_stripe_count() - set the filesystem default number of stripes,
2374  * if unset.
2375  * @val: val number of stripes
2376  *
2377  * A value of "0" means "use the system-wide default stripe count", which
2378  * has either been inherited by now, or falls back to 1 stripe per file.
2379  * A value of "-1" (0xffffffff) means "stripe over all available OSTs",
2380  * and is a valid value, so is left unchanged here.
2381  */
2382 void lod_fix_desc_stripe_count(__u32 *val)
2383 {
2384         if (*val == 0)
2385                 *val = 1;
2386 }
2387
2388 /**
2389  * lod_fix_desc_pattern() - set the filesystem default layout pattern
2390  * @val: LOV_PATTERN_* layout [in, out]
2391  *
2392  * A value of "0" means "use the system-wide default layout type", which
2393  * has either been inherited by now, or falls back to plain RAID0 striping.
2394  */
2395 void lod_fix_desc_pattern(__u32 *val)
2396 {
2397         /* from lov_setstripe */
2398         if ((*val != 0) && !lov_pattern_supported_normal_comp(*val)) {
2399                 LCONSOLE_WARN("lod: Unknown stripe pattern: %#x\n", *val);
2400                 *val = 0;
2401         }
2402 }
2403
2404 void lod_fix_lmv_desc_pattern(__u32 *val)
2405 {
2406         if ((*val) && !lmv_is_known_hash_type(*val)) {
2407                 LCONSOLE_WARN("lod: Unknown md stripe pattern: %#x\n", *val);
2408                 *val = 0;
2409         }
2410 }
2411
2412 void lod_fix_desc_qos_maxage(__u32 *val)
2413 {
2414         /* fix qos_maxage */
2415         if (*val == 0)
2416                 *val = LOV_DESC_QOS_MAXAGE_DEFAULT;
2417 }
2418
2419 /**
2420  * lod_fix_desc() - Is used to fix insane default striping.
2421  * @desc: striping description
2422  */
2423 void lod_fix_desc(struct lov_desc *desc)
2424 {
2425         lod_fix_desc_stripe_size(&desc->ld_default_stripe_size);
2426         lod_fix_desc_stripe_count(&desc->ld_default_stripe_count);
2427         lod_fix_desc_pattern(&desc->ld_pattern);
2428         lod_fix_desc_qos_maxage(&desc->ld_qos_maxage);
2429 }
2430
2431 static void lod_fix_lmv_desc(struct lmv_desc *desc)
2432 {
2433         desc->ld_active_tgt_count = 0;
2434         lod_fix_desc_stripe_count(&desc->ld_default_stripe_count);
2435         lod_fix_lmv_desc_pattern(&desc->ld_pattern);
2436         lod_fix_desc_qos_maxage(&desc->ld_qos_maxage);
2437 }
2438
2439 /**
2440  * lod_pools_init() - Initialize the structures used to store pools and default
2441  * striping.
2442  * @lod: LOD device
2443  * @lcfg: configuration structure storing default striping.
2444  *
2445  * Return:
2446  * * %0 if initialization succeeds
2447  * * %negative error number on failure
2448  */
2449 int lod_pools_init(struct lod_device *lod, struct lustre_cfg *lcfg)
2450 {
2451         struct obd_device          *obd;
2452         struct lov_desc            *desc;
2453         int                         rc;
2454         ENTRY;
2455
2456         obd = class_name2obd(lustre_cfg_string(lcfg, 0));
2457         LASSERT(obd != NULL);
2458         obd->obd_lu_dev = &lod->lod_dt_dev.dd_lu_dev;
2459
2460         if (LUSTRE_CFG_BUFLEN(lcfg, 1) < 1) {
2461                 CERROR("LOD setup requires a descriptor\n");
2462                 RETURN(-EINVAL);
2463         }
2464
2465         desc = (struct lov_desc *)lustre_cfg_buf(lcfg, 1);
2466
2467         if (sizeof(*desc) > LUSTRE_CFG_BUFLEN(lcfg, 1)) {
2468                 CERROR("descriptor size wrong: %d > %d\n",
2469                        (int)sizeof(*desc), LUSTRE_CFG_BUFLEN(lcfg, 1));
2470                 RETURN(-EINVAL);
2471         }
2472
2473         if (desc->ld_magic != LOV_DESC_MAGIC) {
2474                 if (desc->ld_magic == __swab32(LOV_DESC_MAGIC)) {
2475                         CDEBUG(D_OTHER, "%s: Swabbing lov desc %p\n",
2476                                obd->obd_name, desc);
2477                         lustre_swab_lov_desc(desc);
2478                 } else {
2479                         CERROR("%s: Bad lov desc magic: %#x\n",
2480                                obd->obd_name, desc->ld_magic);
2481                         RETURN(-EINVAL);
2482                 }
2483         }
2484
2485         lod_fix_desc(desc);
2486
2487         desc->ld_active_tgt_count = 0;
2488         lod->lod_ost_descs.ltd_lov_desc = *desc;
2489
2490         /* NB: config doesn't contain lmv_desc, alter it via sysfs. */
2491         lod_fix_lmv_desc(&lod->lod_mdt_descs.ltd_lmv_desc);
2492
2493         lod->lod_sp_me = LUSTRE_SP_CLI;
2494
2495         /* Set up OST pool environment */
2496         lod->lod_pool_count = 0;
2497         rc = lod_pool_hash_init(&lod->lod_pools_hash_body);
2498         if (rc)
2499                 RETURN(-ENOMEM);
2500
2501         INIT_LIST_HEAD(&lod->lod_pool_list);
2502         lod->lod_pool_count = 0;
2503         rc = lu_tgt_pool_init(&lod->lod_mdt_descs.ltd_tgt_pool, 0);
2504         if (rc)
2505                 GOTO(out_hash, rc);
2506
2507         rc = lu_tgt_pool_init(&lod->lod_mdt_descs.ltd_qos.lq_rr.lqr_pool, 0);
2508         if (rc)
2509                 GOTO(out_mdt_pool, rc);
2510
2511         rc = lu_tgt_pool_init(&lod->lod_ost_descs.ltd_tgt_pool, 0);
2512         if (rc)
2513                 GOTO(out_mdt_rr_pool, rc);
2514
2515         rc = lu_tgt_pool_init(&lod->lod_ost_descs.ltd_qos.lq_rr.lqr_pool, 0);
2516         if (rc)
2517                 GOTO(out_ost_pool, rc);
2518
2519         RETURN(0);
2520
2521 out_ost_pool:
2522         lu_tgt_pool_free(&lod->lod_ost_descs.ltd_tgt_pool);
2523 out_mdt_rr_pool:
2524         lu_tgt_pool_free(&lod->lod_mdt_descs.ltd_qos.lq_rr.lqr_pool);
2525 out_mdt_pool:
2526         lu_tgt_pool_free(&lod->lod_mdt_descs.ltd_tgt_pool);
2527 out_hash:
2528         lod_pool_hash_destroy(&lod->lod_pools_hash_body);
2529
2530         return rc;
2531 }
2532
2533 /**
2534  * lod_pools_fini() - Release the structures describing the pools.
2535  * @lod: LOD device from which we release the structures
2536  *
2537  * Return 0 always
2538  */
2539 int lod_pools_fini(struct lod_device *lod)
2540 {
2541         struct obd_device   *obd = lod2obd(lod);
2542         struct lod_pool_desc *pool, *tmp;
2543         ENTRY;
2544
2545         list_for_each_entry_safe(pool, tmp, &lod->lod_pool_list, pool_list) {
2546                 /* free pool structs */
2547                 CDEBUG(D_INFO, "delete pool %p\n", pool);
2548                 /* In the function below, .hs_keycmp resolves to
2549                  * pool_hashkey_keycmp() */
2550                 lod_pool_del(obd, pool->pool_name);
2551         }
2552
2553         lod_pool_hash_destroy(&lod->lod_pools_hash_body);
2554         lu_tgt_pool_free(&lod->lod_ost_descs.ltd_qos.lq_rr.lqr_pool);
2555         lu_tgt_pool_free(&lod->lod_ost_descs.ltd_tgt_pool);
2556         lu_tgt_pool_free(&lod->lod_mdt_descs.ltd_qos.lq_rr.lqr_pool);
2557         lu_tgt_pool_free(&lod->lod_mdt_descs.ltd_tgt_pool);
2558
2559         RETURN(0);
2560 }