Whamcloud - gitweb
203b5a486533025f9dd7ae6de706ba0d237170da
[fs/lustre-release.git] / lustre / lod / lod_object.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License version 2 for more details.  A copy is
14  * included in the COPYING file that accompanied this code.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright  2009 Sun Microsystems, Inc. All rights reserved
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2012, 2017, Intel Corporation.
27  */
28 /*
29  * lustre/lod/lod_object.c
30  *
31  * This file contains implementations of methods for the OSD API
32  * for the Logical Object Device (LOD) layer, which provides a virtual
33  * local OSD object interface to the MDD layer, and abstracts the
34  * addressing of local (OSD) and remote (OSP) objects. The API is
35  * described in the file lustre/include/dt_object.h and in
36  * Documentation/osd-api.txt.
37  *
38  * Author: Alex Zhuravlev <alexey.zhuravlev@intel.com>
39  */
40
41 #define DEBUG_SUBSYSTEM S_MDS
42
43 #include <linux/random.h>
44
45 #include <obd.h>
46 #include <obd_class.h>
47 #include <obd_support.h>
48
49 #include <lustre_fid.h>
50 #include <lustre_linkea.h>
51 #include <lustre_lmv.h>
52 #include <uapi/linux/lustre/lustre_param.h>
53 #include <lustre_swab.h>
54 #include <uapi/linux/lustre/lustre_ver.h>
55 #include <lprocfs_status.h>
56 #include <md_object.h>
57
58 #include "lod_internal.h"
59
60 static const char dot[] = ".";
61 static const char dotdot[] = "..";
62
63 /**
64  * Implementation of dt_index_operations::dio_lookup
65  *
66  * Used with regular (non-striped) objects.
67  *
68  * \see dt_index_operations::dio_lookup() in the API description for details.
69  */
70 static int lod_lookup(const struct lu_env *env, struct dt_object *dt,
71                       struct dt_rec *rec, const struct dt_key *key)
72 {
73         struct dt_object *next = dt_object_child(dt);
74         return next->do_index_ops->dio_lookup(env, next, rec, key);
75 }
76
77 /**
78  * Implementation of dt_index_operations::dio_declare_insert.
79  *
80  * Used with regular (non-striped) objects.
81  *
82  * \see dt_index_operations::dio_declare_insert() in the API description
83  * for details.
84  */
85 static int lod_declare_insert(const struct lu_env *env, struct dt_object *dt,
86                               const struct dt_rec *rec,
87                               const struct dt_key *key, struct thandle *th)
88 {
89         return lod_sub_declare_insert(env, dt_object_child(dt), rec, key, th);
90 }
91
92 /**
93  * Implementation of dt_index_operations::dio_insert.
94  *
95  * Used with regular (non-striped) objects
96  *
97  * \see dt_index_operations::dio_insert() in the API description for details.
98  */
99 static int lod_insert(const struct lu_env *env, struct dt_object *dt,
100                       const struct dt_rec *rec, const struct dt_key *key,
101                       struct thandle *th)
102 {
103         return lod_sub_insert(env, dt_object_child(dt), rec, key, th);
104 }
105
106 /**
107  * Implementation of dt_index_operations::dio_declare_delete.
108  *
109  * Used with regular (non-striped) objects.
110  *
111  * \see dt_index_operations::dio_declare_delete() in the API description
112  * for details.
113  */
114 static int lod_declare_delete(const struct lu_env *env, struct dt_object *dt,
115                               const struct dt_key *key, struct thandle *th)
116 {
117         return lod_sub_declare_delete(env, dt_object_child(dt), key, th);
118 }
119
120 /**
121  * Implementation of dt_index_operations::dio_delete.
122  *
123  * Used with regular (non-striped) objects.
124  *
125  * \see dt_index_operations::dio_delete() in the API description for details.
126  */
127 static int lod_delete(const struct lu_env *env, struct dt_object *dt,
128                       const struct dt_key *key, struct thandle *th)
129 {
130         return lod_sub_delete(env, dt_object_child(dt), key, th);
131 }
132
133 /**
134  * Implementation of dt_it_ops::init.
135  *
136  * Used with regular (non-striped) objects.
137  *
138  * \see dt_it_ops::init() in the API description for details.
139  */
140 static struct dt_it *lod_it_init(const struct lu_env *env,
141                                  struct dt_object *dt, __u32 attr)
142 {
143         struct dt_object        *next = dt_object_child(dt);
144         struct lod_it           *it = &lod_env_info(env)->lti_it;
145         struct dt_it            *it_next;
146
147         it_next = next->do_index_ops->dio_it.init(env, next, attr);
148         if (IS_ERR(it_next))
149                 return it_next;
150
151         /* currently we do not use more than one iterator per thread
152          * so we store it in thread info. if at some point we need
153          * more active iterators in a single thread, we can allocate
154          * additional ones */
155         LASSERT(it->lit_obj == NULL);
156
157         it->lit_it = it_next;
158         it->lit_obj = next;
159
160         return (struct dt_it *)it;
161 }
162
163 #define LOD_CHECK_IT(env, it)                                   \
164 do {                                                            \
165         LASSERT((it)->lit_obj != NULL);                         \
166         LASSERT((it)->lit_it != NULL);                          \
167 } while (0)
168
169 /**
170  * Implementation of dt_index_operations::dio_it.fini.
171  *
172  * Used with regular (non-striped) objects.
173  *
174  * \see dt_index_operations::dio_it.fini() in the API description for details.
175  */
176 static void lod_it_fini(const struct lu_env *env, struct dt_it *di)
177 {
178         struct lod_it *it = (struct lod_it *)di;
179
180         LOD_CHECK_IT(env, it);
181         it->lit_obj->do_index_ops->dio_it.fini(env, it->lit_it);
182
183         /* the iterator not in use any more */
184         it->lit_obj = NULL;
185         it->lit_it = NULL;
186 }
187
188 /**
189  * Implementation of dt_it_ops::get.
190  *
191  * Used with regular (non-striped) objects.
192  *
193  * \see dt_it_ops::get() in the API description for details.
194  */
195 static int lod_it_get(const struct lu_env *env, struct dt_it *di,
196                       const struct dt_key *key)
197 {
198         const struct lod_it *it = (const struct lod_it *)di;
199
200         LOD_CHECK_IT(env, it);
201         return it->lit_obj->do_index_ops->dio_it.get(env, it->lit_it, key);
202 }
203
204 /**
205  * Implementation of dt_it_ops::put.
206  *
207  * Used with regular (non-striped) objects.
208  *
209  * \see dt_it_ops::put() in the API description for details.
210  */
211 static void lod_it_put(const struct lu_env *env, struct dt_it *di)
212 {
213         struct lod_it *it = (struct lod_it *)di;
214
215         LOD_CHECK_IT(env, it);
216         return it->lit_obj->do_index_ops->dio_it.put(env, it->lit_it);
217 }
218
219 /**
220  * Implementation of dt_it_ops::next.
221  *
222  * Used with regular (non-striped) objects
223  *
224  * \see dt_it_ops::next() in the API description for details.
225  */
226 static int lod_it_next(const struct lu_env *env, struct dt_it *di)
227 {
228         struct lod_it *it = (struct lod_it *)di;
229
230         LOD_CHECK_IT(env, it);
231         return it->lit_obj->do_index_ops->dio_it.next(env, it->lit_it);
232 }
233
234 /**
235  * Implementation of dt_it_ops::key.
236  *
237  * Used with regular (non-striped) objects.
238  *
239  * \see dt_it_ops::key() in the API description for details.
240  */
241 static struct dt_key *lod_it_key(const struct lu_env *env,
242                                  const struct dt_it *di)
243 {
244         const struct lod_it *it = (const struct lod_it *)di;
245
246         LOD_CHECK_IT(env, it);
247         return it->lit_obj->do_index_ops->dio_it.key(env, it->lit_it);
248 }
249
250 /**
251  * Implementation of dt_it_ops::key_size.
252  *
253  * Used with regular (non-striped) objects.
254  *
255  * \see dt_it_ops::key_size() in the API description for details.
256  */
257 static int lod_it_key_size(const struct lu_env *env, const struct dt_it *di)
258 {
259         struct lod_it *it = (struct lod_it *)di;
260
261         LOD_CHECK_IT(env, it);
262         return it->lit_obj->do_index_ops->dio_it.key_size(env, it->lit_it);
263 }
264
265 /**
266  * Implementation of dt_it_ops::rec.
267  *
268  * Used with regular (non-striped) objects.
269  *
270  * \see dt_it_ops::rec() in the API description for details.
271  */
272 static int lod_it_rec(const struct lu_env *env, const struct dt_it *di,
273                       struct dt_rec *rec, __u32 attr)
274 {
275         const struct lod_it *it = (const struct lod_it *)di;
276
277         LOD_CHECK_IT(env, it);
278         return it->lit_obj->do_index_ops->dio_it.rec(env, it->lit_it, rec,
279                                                      attr);
280 }
281
282 /**
283  * Implementation of dt_it_ops::rec_size.
284  *
285  * Used with regular (non-striped) objects.
286  *
287  * \see dt_it_ops::rec_size() in the API description for details.
288  */
289 static int lod_it_rec_size(const struct lu_env *env, const struct dt_it *di,
290                            __u32 attr)
291 {
292         const struct lod_it *it = (const struct lod_it *)di;
293
294         LOD_CHECK_IT(env, it);
295         return it->lit_obj->do_index_ops->dio_it.rec_size(env, it->lit_it,
296                                                           attr);
297 }
298
299 /**
300  * Implementation of dt_it_ops::store.
301  *
302  * Used with regular (non-striped) objects.
303  *
304  * \see dt_it_ops::store() in the API description for details.
305  */
306 static __u64 lod_it_store(const struct lu_env *env, const struct dt_it *di)
307 {
308         const struct lod_it *it = (const struct lod_it *)di;
309
310         LOD_CHECK_IT(env, it);
311         return it->lit_obj->do_index_ops->dio_it.store(env, it->lit_it);
312 }
313
314 /**
315  * Implementation of dt_it_ops::load.
316  *
317  * Used with regular (non-striped) objects.
318  *
319  * \see dt_it_ops::load() in the API description for details.
320  */
321 static int lod_it_load(const struct lu_env *env, const struct dt_it *di,
322                        __u64 hash)
323 {
324         const struct lod_it *it = (const struct lod_it *)di;
325
326         LOD_CHECK_IT(env, it);
327         return it->lit_obj->do_index_ops->dio_it.load(env, it->lit_it, hash);
328 }
329
330 /**
331  * Implementation of dt_it_ops::key_rec.
332  *
333  * Used with regular (non-striped) objects.
334  *
335  * \see dt_it_ops::rec() in the API description for details.
336  */
337 static int lod_it_key_rec(const struct lu_env *env, const struct dt_it *di,
338                           void *key_rec)
339 {
340         const struct lod_it *it = (const struct lod_it *)di;
341
342         LOD_CHECK_IT(env, it);
343         return it->lit_obj->do_index_ops->dio_it.key_rec(env, it->lit_it,
344                                                          key_rec);
345 }
346
347 static const struct dt_index_operations lod_index_ops = {
348         .dio_lookup             = lod_lookup,
349         .dio_declare_insert     = lod_declare_insert,
350         .dio_insert             = lod_insert,
351         .dio_declare_delete     = lod_declare_delete,
352         .dio_delete             = lod_delete,
353         .dio_it = {
354                 .init           = lod_it_init,
355                 .fini           = lod_it_fini,
356                 .get            = lod_it_get,
357                 .put            = lod_it_put,
358                 .next           = lod_it_next,
359                 .key            = lod_it_key,
360                 .key_size       = lod_it_key_size,
361                 .rec            = lod_it_rec,
362                 .rec_size       = lod_it_rec_size,
363                 .store          = lod_it_store,
364                 .load           = lod_it_load,
365                 .key_rec        = lod_it_key_rec,
366         }
367 };
368
369 /**
370  * Implementation of dt_index_operations::dio_lookup
371  *
372  * Used with striped directories.
373  *
374  * \see dt_index_operations::dio_lookup() in the API description for details.
375  */
376 static int lod_striped_lookup(const struct lu_env *env, struct dt_object *dt,
377                       struct dt_rec *rec, const struct dt_key *key)
378 {
379         struct lod_object *lo = lod_dt_obj(dt);
380         struct dt_object *next;
381         const char *name = (const char *)key;
382
383         LASSERT(lo->ldo_dir_stripe_count > 0);
384
385         if (strcmp(name, dot) == 0) {
386                 struct lu_fid *fid = (struct lu_fid *)rec;
387
388                 *fid = *lod_object_fid(lo);
389                 return 1;
390         }
391
392         if (strcmp(name, dotdot) == 0) {
393                 next = dt_object_child(dt);
394         } else {
395                 int index;
396
397                 index = __lmv_name_to_stripe_index(lo->ldo_dir_hash_type,
398                                                    lo->ldo_dir_stripe_count,
399                                                    lo->ldo_dir_migrate_hash,
400                                                    lo->ldo_dir_migrate_offset,
401                                                    name, strlen(name), true);
402                 if (index < 0)
403                         return index;
404
405                 next = lo->ldo_stripe[index];
406                 if (!next || !dt_object_exists(next))
407                         return -ENODEV;
408         }
409
410         return next->do_index_ops->dio_lookup(env, next, rec, key);
411 }
412
413 /**
414  * Implementation of dt_it_ops::init.
415  *
416  * Used with striped objects. Internally just initializes the iterator
417  * on the first stripe.
418  *
419  * \see dt_it_ops::init() in the API description for details.
420  */
421 static struct dt_it *lod_striped_it_init(const struct lu_env *env,
422                                          struct dt_object *dt, __u32 attr)
423 {
424         struct lod_object *lo = lod_dt_obj(dt);
425         struct dt_object *next;
426         struct lod_it *it = &lod_env_info(env)->lti_it;
427         struct dt_it *it_next;
428         __u16 index = 0;
429
430         LASSERT(lo->ldo_dir_stripe_count > 0);
431
432         do {
433                 next = lo->ldo_stripe[index];
434                 if (next && dt_object_exists(next))
435                         break;
436         } while (++index < lo->ldo_dir_stripe_count);
437
438         /* no valid stripe */
439         if (!next || !dt_object_exists(next))
440                 return ERR_PTR(-ENODEV);
441
442         LASSERT(next->do_index_ops != NULL);
443
444         it_next = next->do_index_ops->dio_it.init(env, next, attr);
445         if (IS_ERR(it_next))
446                 return it_next;
447
448         /* currently we do not use more than one iterator per thread
449          * so we store it in thread info. if at some point we need
450          * more active iterators in a single thread, we can allocate
451          * additional ones */
452         LASSERT(it->lit_obj == NULL);
453
454         it->lit_stripe_index = index;
455         it->lit_attr = attr;
456         it->lit_it = it_next;
457         it->lit_obj = dt;
458
459         return (struct dt_it *)it;
460 }
461
462 #define LOD_CHECK_STRIPED_IT(env, it, lo)                               \
463 do {                                                                    \
464         LASSERT((it)->lit_obj != NULL);                                 \
465         LASSERT((it)->lit_it != NULL);                                  \
466         LASSERT((lo)->ldo_dir_stripe_count > 0);                        \
467         LASSERT((it)->lit_stripe_index < (lo)->ldo_dir_stripe_count);   \
468 } while (0)
469
470 /**
471  * Implementation of dt_it_ops::fini.
472  *
473  * Used with striped objects.
474  *
475  * \see dt_it_ops::fini() in the API description for details.
476  */
477 static void lod_striped_it_fini(const struct lu_env *env, struct dt_it *di)
478 {
479         struct lod_it           *it = (struct lod_it *)di;
480         struct lod_object       *lo = lod_dt_obj(it->lit_obj);
481         struct dt_object        *next;
482
483         /* If lit_it == NULL, then it means the sub_it has been finished,
484          * which only happens in failure cases, see lod_striped_it_next() */
485         if (it->lit_it != NULL) {
486                 LOD_CHECK_STRIPED_IT(env, it, lo);
487
488                 next = lo->ldo_stripe[it->lit_stripe_index];
489                 if (next) {
490                         LASSERT(next->do_index_ops != NULL);
491                         next->do_index_ops->dio_it.fini(env, it->lit_it);
492                 }
493         }
494
495         /* the iterator not in use any more */
496         it->lit_obj = NULL;
497         it->lit_it = NULL;
498         it->lit_stripe_index = 0;
499 }
500
501 /**
502  * Implementation of dt_it_ops::get.
503  *
504  * Right now it's not used widely, only to reset the iterator to the
505  * initial position. It should be possible to implement a full version
506  * which chooses a correct stripe to be able to position with any key.
507  *
508  * \see dt_it_ops::get() in the API description for details.
509  */
510 static int lod_striped_it_get(const struct lu_env *env, struct dt_it *di,
511                               const struct dt_key *key)
512 {
513         const struct lod_it *it = (const struct lod_it *)di;
514         struct lod_object *lo = lod_dt_obj(it->lit_obj);
515         struct dt_object *next;
516
517         LOD_CHECK_STRIPED_IT(env, it, lo);
518
519         next = lo->ldo_stripe[it->lit_stripe_index];
520         LASSERT(next != NULL);
521         LASSERT(dt_object_exists(next));
522         LASSERT(next->do_index_ops != NULL);
523
524         return next->do_index_ops->dio_it.get(env, it->lit_it, key);
525 }
526
527 /**
528  * Implementation of dt_it_ops::put.
529  *
530  * Used with striped objects.
531  *
532  * \see dt_it_ops::put() in the API description for details.
533  */
534 static void lod_striped_it_put(const struct lu_env *env, struct dt_it *di)
535 {
536         struct lod_it *it = (struct lod_it *)di;
537         struct lod_object *lo = lod_dt_obj(it->lit_obj);
538         struct dt_object *next;
539
540         /*
541          * If lit_it == NULL, then it means the sub_it has been finished,
542          * which only happens in failure cases, see lod_striped_it_next()
543          */
544         if (!it->lit_it)
545                 return;
546
547         LOD_CHECK_STRIPED_IT(env, it, lo);
548
549         next = lo->ldo_stripe[it->lit_stripe_index];
550         LASSERT(next != NULL);
551         LASSERT(next->do_index_ops != NULL);
552
553         return next->do_index_ops->dio_it.put(env, it->lit_it);
554 }
555
556 /**
557  * Implementation of dt_it_ops::next.
558  *
559  * Used with striped objects. When the end of the current stripe is
560  * reached, the method takes the next stripe's iterator.
561  *
562  * \see dt_it_ops::next() in the API description for details.
563  */
564 static int lod_striped_it_next(const struct lu_env *env, struct dt_it *di)
565 {
566         struct lod_it *it = (struct lod_it *)di;
567         struct lod_object *lo = lod_dt_obj(it->lit_obj);
568         struct dt_object *next;
569         struct dt_it *it_next;
570         __u32 index;
571         int rc;
572
573         ENTRY;
574
575         LOD_CHECK_STRIPED_IT(env, it, lo);
576
577         next = lo->ldo_stripe[it->lit_stripe_index];
578         LASSERT(next != NULL);
579         LASSERT(dt_object_exists(next));
580         LASSERT(next->do_index_ops != NULL);
581 again:
582         rc = next->do_index_ops->dio_it.next(env, it->lit_it);
583         if (rc < 0)
584                 RETURN(rc);
585
586         if (rc == 0 && it->lit_stripe_index == 0)
587                 RETURN(rc);
588
589         if (rc == 0 && it->lit_stripe_index > 0) {
590                 struct lu_dirent *ent;
591
592                 ent = (struct lu_dirent *)lod_env_info(env)->lti_key;
593
594                 rc = next->do_index_ops->dio_it.rec(env, it->lit_it,
595                                                     (struct dt_rec *)ent,
596                                                     it->lit_attr);
597                 if (rc != 0)
598                         RETURN(rc);
599
600                 /* skip . and .. for slave stripe */
601                 if ((strncmp(ent->lde_name, ".",
602                              le16_to_cpu(ent->lde_namelen)) == 0 &&
603                      le16_to_cpu(ent->lde_namelen) == 1) ||
604                     (strncmp(ent->lde_name, "..",
605                              le16_to_cpu(ent->lde_namelen)) == 0 &&
606                      le16_to_cpu(ent->lde_namelen) == 2))
607                         goto again;
608
609                 RETURN(rc);
610         }
611
612         next->do_index_ops->dio_it.put(env, it->lit_it);
613         next->do_index_ops->dio_it.fini(env, it->lit_it);
614         it->lit_it = NULL;
615
616         /* go to next stripe */
617         index = it->lit_stripe_index;
618         while (++index < lo->ldo_dir_stripe_count) {
619                 next = lo->ldo_stripe[index];
620                 if (!next)
621                         continue;
622
623                 if (!dt_object_exists(next))
624                         continue;
625
626                 rc = next->do_ops->do_index_try(env, next,
627                                                 &dt_directory_features);
628                 if (rc != 0)
629                         RETURN(rc);
630
631                 LASSERT(next->do_index_ops != NULL);
632
633                 it_next = next->do_index_ops->dio_it.init(env, next,
634                                                           it->lit_attr);
635                 if (IS_ERR(it_next))
636                         RETURN(PTR_ERR(it_next));
637
638                 rc = next->do_index_ops->dio_it.get(env, it_next,
639                                                     (const struct dt_key *)"");
640                 if (rc <= 0)
641                         RETURN(rc == 0 ? -EIO : rc);
642
643                 it->lit_it = it_next;
644                 it->lit_stripe_index = index;
645                 goto again;
646
647         }
648
649         RETURN(1);
650 }
651
652 /**
653  * Implementation of dt_it_ops::key.
654  *
655  * Used with striped objects.
656  *
657  * \see dt_it_ops::key() in the API description for details.
658  */
659 static struct dt_key *lod_striped_it_key(const struct lu_env *env,
660                                          const struct dt_it *di)
661 {
662         const struct lod_it     *it = (const struct lod_it *)di;
663         struct lod_object       *lo = lod_dt_obj(it->lit_obj);
664         struct dt_object        *next;
665
666         LOD_CHECK_STRIPED_IT(env, it, lo);
667
668         next = lo->ldo_stripe[it->lit_stripe_index];
669         LASSERT(next != NULL);
670         LASSERT(next->do_index_ops != NULL);
671
672         return next->do_index_ops->dio_it.key(env, it->lit_it);
673 }
674
675 /**
676  * Implementation of dt_it_ops::key_size.
677  *
678  * Used with striped objects.
679  *
680  * \see dt_it_ops::size() in the API description for details.
681  */
682 static int lod_striped_it_key_size(const struct lu_env *env,
683                                    const struct dt_it *di)
684 {
685         struct lod_it           *it = (struct lod_it *)di;
686         struct lod_object       *lo = lod_dt_obj(it->lit_obj);
687         struct dt_object        *next;
688
689         LOD_CHECK_STRIPED_IT(env, it, lo);
690
691         next = lo->ldo_stripe[it->lit_stripe_index];
692         LASSERT(next != NULL);
693         LASSERT(next->do_index_ops != NULL);
694
695         return next->do_index_ops->dio_it.key_size(env, it->lit_it);
696 }
697
698 /**
699  * Implementation of dt_it_ops::rec.
700  *
701  * Used with striped objects.
702  *
703  * \see dt_it_ops::rec() in the API description for details.
704  */
705 static int lod_striped_it_rec(const struct lu_env *env, const struct dt_it *di,
706                               struct dt_rec *rec, __u32 attr)
707 {
708         const struct lod_it     *it = (const struct lod_it *)di;
709         struct lod_object       *lo = lod_dt_obj(it->lit_obj);
710         struct dt_object        *next;
711
712         LOD_CHECK_STRIPED_IT(env, it, lo);
713
714         next = lo->ldo_stripe[it->lit_stripe_index];
715         LASSERT(next != NULL);
716         LASSERT(next->do_index_ops != NULL);
717
718         return next->do_index_ops->dio_it.rec(env, it->lit_it, rec, attr);
719 }
720
721 /**
722  * Implementation of dt_it_ops::rec_size.
723  *
724  * Used with striped objects.
725  *
726  * \see dt_it_ops::rec_size() in the API description for details.
727  */
728 static int lod_striped_it_rec_size(const struct lu_env *env,
729                                    const struct dt_it *di, __u32 attr)
730 {
731         struct lod_it           *it = (struct lod_it *)di;
732         struct lod_object       *lo = lod_dt_obj(it->lit_obj);
733         struct dt_object        *next;
734
735         LOD_CHECK_STRIPED_IT(env, it, lo);
736
737         next = lo->ldo_stripe[it->lit_stripe_index];
738         LASSERT(next != NULL);
739         LASSERT(next->do_index_ops != NULL);
740
741         return next->do_index_ops->dio_it.rec_size(env, it->lit_it, attr);
742 }
743
744 /**
745  * Implementation of dt_it_ops::store.
746  *
747  * Used with striped objects.
748  *
749  * \see dt_it_ops::store() in the API description for details.
750  */
751 static __u64 lod_striped_it_store(const struct lu_env *env,
752                                   const struct dt_it *di)
753 {
754         const struct lod_it     *it = (const struct lod_it *)di;
755         struct lod_object       *lo = lod_dt_obj(it->lit_obj);
756         struct dt_object        *next;
757
758         LOD_CHECK_STRIPED_IT(env, it, lo);
759
760         next = lo->ldo_stripe[it->lit_stripe_index];
761         LASSERT(next != NULL);
762         LASSERT(next->do_index_ops != NULL);
763
764         return next->do_index_ops->dio_it.store(env, it->lit_it);
765 }
766
767 /**
768  * Implementation of dt_it_ops::load.
769  *
770  * Used with striped objects.
771  *
772  * \see dt_it_ops::load() in the API description for details.
773  */
774 static int lod_striped_it_load(const struct lu_env *env,
775                                const struct dt_it *di, __u64 hash)
776 {
777         const struct lod_it     *it = (const struct lod_it *)di;
778         struct lod_object       *lo = lod_dt_obj(it->lit_obj);
779         struct dt_object        *next;
780
781         LOD_CHECK_STRIPED_IT(env, it, lo);
782
783         next = lo->ldo_stripe[it->lit_stripe_index];
784         LASSERT(next != NULL);
785         LASSERT(next->do_index_ops != NULL);
786
787         return next->do_index_ops->dio_it.load(env, it->lit_it, hash);
788 }
789
790 static const struct dt_index_operations lod_striped_index_ops = {
791         .dio_lookup             = lod_striped_lookup,
792         .dio_declare_insert     = lod_declare_insert,
793         .dio_insert             = lod_insert,
794         .dio_declare_delete     = lod_declare_delete,
795         .dio_delete             = lod_delete,
796         .dio_it = {
797                 .init           = lod_striped_it_init,
798                 .fini           = lod_striped_it_fini,
799                 .get            = lod_striped_it_get,
800                 .put            = lod_striped_it_put,
801                 .next           = lod_striped_it_next,
802                 .key            = lod_striped_it_key,
803                 .key_size       = lod_striped_it_key_size,
804                 .rec            = lod_striped_it_rec,
805                 .rec_size       = lod_striped_it_rec_size,
806                 .store          = lod_striped_it_store,
807                 .load           = lod_striped_it_load,
808         }
809 };
810
811 /**
812  * Append the FID for each shard of the striped directory after the
813  * given LMV EA header.
814  *
815  * To simplify striped directory and the consistency verification,
816  * we only store the LMV EA header on disk, for both master object
817  * and slave objects. When someone wants to know the whole LMV EA,
818  * such as client readdir(), we can build the entrie LMV EA on the
819  * MDT side (in RAM) via iterating the sub-directory entries that
820  * are contained in the master object of the stripe directory.
821  *
822  * For the master object of the striped directroy, the valid name
823  * for each shard is composed of the ${shard_FID}:${shard_idx}.
824  *
825  * There may be holes in the LMV EA if some shards' name entries
826  * are corrupted or lost.
827  *
828  * \param[in] env       pointer to the thread context
829  * \param[in] lo        pointer to the master object of the striped directory
830  * \param[in] buf       pointer to the lu_buf which will hold the LMV EA
831  * \param[in] resize    whether re-allocate the buffer if it is not big enough
832  *
833  * \retval              positive size of the LMV EA
834  * \retval              0 for nothing to be loaded
835  * \retval              negative error number on failure
836  */
837 int lod_load_lmv_shards(const struct lu_env *env, struct lod_object *lo,
838                         struct lu_buf *buf, bool resize)
839 {
840         struct lu_dirent        *ent    =
841                         (struct lu_dirent *)lod_env_info(env)->lti_key;
842         struct lod_device       *lod    = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
843         struct dt_object        *obj    = dt_object_child(&lo->ldo_obj);
844         struct lmv_mds_md_v1    *lmv1   = buf->lb_buf;
845         struct dt_it            *it;
846         const struct dt_it_ops  *iops;
847         __u32                    stripes;
848         __u32                    magic  = le32_to_cpu(lmv1->lmv_magic);
849         size_t                   lmv1_size;
850         int                      rc;
851         ENTRY;
852
853         if (magic != LMV_MAGIC_V1)
854                 RETURN(0);
855
856         stripes = le32_to_cpu(lmv1->lmv_stripe_count);
857         if (stripes < 1)
858                 RETURN(0);
859
860         rc = lmv_mds_md_size(stripes, magic);
861         if (rc < 0)
862                 RETURN(rc);
863         lmv1_size = rc;
864         if (buf->lb_len < lmv1_size) {
865                 struct lu_buf tbuf;
866
867                 if (!resize)
868                         RETURN(-ERANGE);
869
870                 tbuf = *buf;
871                 buf->lb_buf = NULL;
872                 buf->lb_len = 0;
873                 lu_buf_alloc(buf, lmv1_size);
874                 lmv1 = buf->lb_buf;
875                 if (lmv1 == NULL)
876                         RETURN(-ENOMEM);
877
878                 memcpy(buf->lb_buf, tbuf.lb_buf, tbuf.lb_len);
879         }
880
881         if (unlikely(!dt_try_as_dir(env, obj, true)))
882                 RETURN(-ENOTDIR);
883
884         memset(&lmv1->lmv_stripe_fids[0], 0, stripes * sizeof(struct lu_fid));
885         iops = &obj->do_index_ops->dio_it;
886         it = iops->init(env, obj, LUDA_64BITHASH);
887         if (IS_ERR(it))
888                 RETURN(PTR_ERR(it));
889
890         rc = iops->load(env, it, 0);
891         if (rc == 0)
892                 rc = iops->next(env, it);
893         else if (rc > 0)
894                 rc = 0;
895
896         while (rc == 0) {
897                 char             name[FID_LEN + 2] = "";
898                 struct lu_fid    fid;
899                 __u32            index;
900                 int              len;
901
902                 rc = iops->rec(env, it, (struct dt_rec *)ent, LUDA_64BITHASH);
903                 if (rc != 0)
904                         break;
905
906                 rc = -EIO;
907
908                 fid_le_to_cpu(&fid, &ent->lde_fid);
909                 ent->lde_namelen = le16_to_cpu(ent->lde_namelen);
910                 if (ent->lde_name[0] == '.') {
911                         if (ent->lde_namelen == 1)
912                                 goto next;
913
914                         if (ent->lde_namelen == 2 && ent->lde_name[1] == '.')
915                                 goto next;
916                 }
917
918                 len = scnprintf(name, sizeof(name),
919                                 DFID":", PFID(&ent->lde_fid));
920                 /* The ent->lde_name is composed of ${FID}:${index} */
921                 if (ent->lde_namelen < len + 1 ||
922                     memcmp(ent->lde_name, name, len) != 0) {
923                         CDEBUG_LIMIT(lod->lod_lmv_failout ? D_ERROR : D_INFO,
924                                      "%s: invalid shard name %.*s with the FID "DFID" for the striped directory "DFID", %s\n",
925                                      lod2obd(lod)->obd_name, ent->lde_namelen,
926                                      ent->lde_name, PFID(&fid),
927                                      PFID(lu_object_fid(&obj->do_lu)),
928                                      lod->lod_lmv_failout ? "failout" : "skip");
929
930                         if (lod->lod_lmv_failout)
931                                 break;
932
933                         goto next;
934                 }
935
936                 index = 0;
937                 do {
938                         if (ent->lde_name[len] < '0' ||
939                             ent->lde_name[len] > '9') {
940                                 CDEBUG_LIMIT(lod->lod_lmv_failout ?
941                                              D_ERROR : D_INFO,
942                                              "%s: invalid shard name %.*s with the FID "DFID" for the striped directory "DFID", %s\n",
943                                              lod2obd(lod)->obd_name,
944                                              ent->lde_namelen,
945                                              ent->lde_name, PFID(&fid),
946                                              PFID(lu_object_fid(&obj->do_lu)),
947                                              lod->lod_lmv_failout ?
948                                              "failout" : "skip");
949
950                                 if (lod->lod_lmv_failout)
951                                         break;
952
953                                 goto next;
954                         }
955
956                         index = index * 10 + ent->lde_name[len++] - '0';
957                 } while (len < ent->lde_namelen);
958
959                 if (len == ent->lde_namelen) {
960                         /* Out of LMV EA range. */
961                         if (index >= stripes) {
962                                 CERROR("%s: the shard %.*s for the striped "
963                                        "directory "DFID" is out of the known "
964                                        "LMV EA range [0 - %u], failout\n",
965                                        lod2obd(lod)->obd_name, ent->lde_namelen,
966                                        ent->lde_name,
967                                        PFID(lu_object_fid(&obj->do_lu)),
968                                        stripes - 1);
969
970                                 break;
971                         }
972
973                         /* The slot has been occupied. */
974                         if (!fid_is_zero(&lmv1->lmv_stripe_fids[index]) &&
975                             !CFS_FAIL_CHECK(OBD_FAIL_LFSCK_BAD_SLAVE_NAME)) {
976                                 struct lu_fid fid0;
977
978                                 fid_le_to_cpu(&fid0,
979                                         &lmv1->lmv_stripe_fids[index]);
980                                 CERROR("%s: both the shard "DFID" and "DFID
981                                        " for the striped directory "DFID
982                                        " claim the same LMV EA slot at the "
983                                        "index %d, failout\n",
984                                        lod2obd(lod)->obd_name,
985                                        PFID(&fid0), PFID(&fid),
986                                        PFID(lu_object_fid(&obj->do_lu)), index);
987
988                                 break;
989                         }
990
991                         /* stored as LE mode */
992                         lmv1->lmv_stripe_fids[index] = ent->lde_fid;
993
994 next:
995                         rc = iops->next(env, it);
996                 }
997         }
998
999         iops->put(env, it);
1000         iops->fini(env, it);
1001
1002         RETURN(rc > 0 ? lmv_mds_md_size(stripes, magic) : rc);
1003 }
1004
1005 /**
1006  * Implementation of dt_object_operations::do_index_try.
1007  *
1008  * \see dt_object_operations::do_index_try() in the API description for details.
1009  */
1010 static int lod_index_try(const struct lu_env *env, struct dt_object *dt,
1011                          const struct dt_index_features *feat)
1012 {
1013         struct lod_object       *lo = lod_dt_obj(dt);
1014         struct dt_object        *next = dt_object_child(dt);
1015         int                     rc;
1016         ENTRY;
1017
1018         LASSERT(next->do_ops);
1019         LASSERT(next->do_ops->do_index_try);
1020
1021         rc = lod_striping_load(env, lo);
1022         if (rc != 0)
1023                 RETURN(rc);
1024
1025         rc = next->do_ops->do_index_try(env, next, feat);
1026         if (rc != 0)
1027                 RETURN(rc);
1028
1029         if (lo->ldo_dir_stripe_count > 0) {
1030                 int i;
1031
1032                 for (i = 0; i < lo->ldo_dir_stripe_count; i++) {
1033                         if (!lo->ldo_stripe[i])
1034                                 continue;
1035                         if (!dt_object_exists(lo->ldo_stripe[i]))
1036                                 continue;
1037                         rc = lo->ldo_stripe[i]->do_ops->do_index_try(env,
1038                                                 lo->ldo_stripe[i], feat);
1039                         if (rc != 0)
1040                                 RETURN(rc);
1041                 }
1042                 dt->do_index_ops = &lod_striped_index_ops;
1043         } else {
1044                 dt->do_index_ops = &lod_index_ops;
1045         }
1046
1047         RETURN(rc);
1048 }
1049
1050 /**
1051  * Implementation of dt_object_operations::do_read_lock.
1052  *
1053  * \see dt_object_operations::do_read_lock() in the API description for details.
1054  */
1055 static void lod_read_lock(const struct lu_env *env, struct dt_object *dt,
1056                           unsigned role)
1057 {
1058         dt_read_lock(env, dt_object_child(dt), role);
1059 }
1060
1061 /**
1062  * Implementation of dt_object_operations::do_write_lock.
1063  *
1064  * \see dt_object_operations::do_write_lock() in the API description for
1065  * details.
1066  */
1067 static void lod_write_lock(const struct lu_env *env, struct dt_object *dt,
1068                            unsigned role)
1069 {
1070         dt_write_lock(env, dt_object_child(dt), role);
1071 }
1072
1073 /**
1074  * Implementation of dt_object_operations::do_read_unlock.
1075  *
1076  * \see dt_object_operations::do_read_unlock() in the API description for
1077  * details.
1078  */
1079 static void lod_read_unlock(const struct lu_env *env, struct dt_object *dt)
1080 {
1081         dt_read_unlock(env, dt_object_child(dt));
1082 }
1083
1084 /**
1085  * Implementation of dt_object_operations::do_write_unlock.
1086  *
1087  * \see dt_object_operations::do_write_unlock() in the API description for
1088  * details.
1089  */
1090 static void lod_write_unlock(const struct lu_env *env, struct dt_object *dt)
1091 {
1092         dt_write_unlock(env, dt_object_child(dt));
1093 }
1094
1095 /**
1096  * Implementation of dt_object_operations::do_write_locked.
1097  *
1098  * \see dt_object_operations::do_write_locked() in the API description for
1099  * details.
1100  */
1101 static int lod_write_locked(const struct lu_env *env, struct dt_object *dt)
1102 {
1103         return dt_write_locked(env, dt_object_child(dt));
1104 }
1105
1106 /**
1107  * Implementation of dt_object_operations::do_attr_get.
1108  *
1109  * \see dt_object_operations::do_attr_get() in the API description for details.
1110  */
1111 static int lod_attr_get(const struct lu_env *env,
1112                         struct dt_object *dt,
1113                         struct lu_attr *attr)
1114 {
1115         /* Note: for striped directory, client will merge attributes
1116          * from all of the sub-stripes see lmv_merge_attr(), and there
1117          * no MDD logic depend on directory nlink/size/time, so we can
1118          * always use master inode nlink and size for now. */
1119         return dt_attr_get(env, dt_object_child(dt), attr);
1120 }
1121
1122 void lod_adjust_stripe_size(struct lod_layout_component *comp,
1123                             __u32 def_stripe_size)
1124 {
1125         __u64 comp_end = comp->llc_extent.e_end;
1126
1127         /* Choose stripe size if not set. Note that default stripe size can't
1128          * be used as is, because it must be multiplier of given component end.
1129          *  - first check if default stripe size can be used
1130          *  - if not than select the lowest set bit from component end and use
1131          *    that value as stripe size
1132          */
1133         if (!comp->llc_stripe_size) {
1134                 if (comp_end == LUSTRE_EOF || !(comp_end % def_stripe_size))
1135                         comp->llc_stripe_size = def_stripe_size;
1136                 else
1137                         comp->llc_stripe_size = comp_end & ~(comp_end - 1);
1138         } else {
1139                 if (comp_end != LUSTRE_EOF &&
1140                     comp_end & (LOV_MIN_STRIPE_SIZE - 1)) {
1141                         CWARN("Component end %llu is not a multiple of min size %u\n",
1142                               comp_end, LOV_MIN_STRIPE_SIZE);
1143                         comp_end = round_up(comp_end, LOV_MIN_STRIPE_SIZE);
1144                 }
1145                 /* check stripe size is multiplier of comp_end */
1146                 if (comp_end != LUSTRE_EOF &&
1147                     comp_end != comp->llc_extent.e_start &&
1148                     comp_end % comp->llc_stripe_size) {
1149                         /* fix that even for defined stripe size but warn
1150                          * about the problem, that must not happen
1151                          */
1152                         CWARN("Component end %llu is not aligned by the stripe size %u\n",
1153                               comp_end, comp->llc_stripe_size);
1154                         comp->llc_stripe_size = comp_end & ~(comp_end - 1);
1155                 }
1156         }
1157 }
1158
1159 static inline void lod_adjust_stripe_info(struct lod_layout_component *comp,
1160                                           struct lov_desc *desc,
1161                                           int append_stripes)
1162 {
1163         if (!(comp->llc_pattern & LOV_PATTERN_MDT)) {
1164                 if (append_stripes) {
1165                         comp->llc_stripe_count = append_stripes;
1166                 } else if (!comp->llc_stripe_count) {
1167                         comp->llc_stripe_count =
1168                                 desc->ld_default_stripe_count;
1169                 }
1170         }
1171
1172         lod_adjust_stripe_size(comp, desc->ld_default_stripe_size);
1173 }
1174
1175 int lod_obj_for_each_stripe(const struct lu_env *env, struct lod_object *lo,
1176                             struct thandle *th,
1177                             struct lod_obj_stripe_cb_data *data)
1178 {
1179         struct lod_layout_component *lod_comp;
1180         int i, j, rc = 0;
1181         ENTRY;
1182
1183         mutex_lock(&lo->ldo_layout_mutex);
1184         for (i = 0; i < lo->ldo_comp_cnt; i++) {
1185                 lod_comp = &lo->ldo_comp_entries[i];
1186
1187                 if (lod_comp->llc_magic == LOV_MAGIC_FOREIGN)
1188                         continue;
1189
1190                 if (lod_comp->llc_stripe == NULL)
1191                         continue;
1192
1193                 /* has stripe but not inited yet, this component has been
1194                  * declared to be created, but hasn't created yet.
1195                  */
1196                 if (!lod_comp_inited(lod_comp))
1197                         continue;
1198
1199                 if (data->locd_comp_skip_cb &&
1200                     data->locd_comp_skip_cb(env, lo, i, data))
1201                         continue;
1202
1203                 if (data->locd_comp_cb) {
1204                         rc = data->locd_comp_cb(env, lo, i, data);
1205                         if (rc)
1206                                 GOTO(unlock, rc);
1207                 }
1208
1209                 /* could used just to do sth about component, not each
1210                  * stripes
1211                  */
1212                 if (!data->locd_stripe_cb)
1213                         continue;
1214
1215                 LASSERT(lod_comp->llc_stripe_count > 0);
1216                 for (j = 0; j < lod_comp->llc_stripe_count; j++) {
1217                         struct dt_object *dt = lod_comp->llc_stripe[j];
1218
1219                         if (dt == NULL)
1220                                 continue;
1221                         rc = data->locd_stripe_cb(env, lo, dt, th, i, j, data);
1222                         if (rc != 0)
1223                                 GOTO(unlock, rc);
1224                 }
1225         }
1226 unlock:
1227         mutex_unlock(&lo->ldo_layout_mutex);
1228         RETURN(rc);
1229 }
1230
1231 static inline int
1232 lod_obj_stripe_attr_set_cb(const struct lu_env *env, struct lod_object *lo,
1233                            struct dt_object *dt, struct thandle *th,
1234                            int comp_idx, int stripe_idx,
1235                            struct lod_obj_stripe_cb_data *data)
1236 {
1237         if (data->locd_declare)
1238                 return lod_sub_declare_attr_set(env, dt, data->locd_attr, th);
1239
1240         if (data->locd_attr->la_valid & LA_LAYOUT_VERSION) {
1241                 CDEBUG(D_LAYOUT, DFID": set layout version: %u, comp_idx: %d\n",
1242                        PFID(lu_object_fid(&dt->do_lu)),
1243                        data->locd_attr->la_layout_version, comp_idx);
1244         }
1245
1246         return lod_sub_attr_set(env, dt, data->locd_attr, th);
1247 }
1248
1249 /**
1250  * Implementation of dt_object_operations::do_declare_attr_set.
1251  *
1252  * If the object is striped, then apply the changes to all the stripes.
1253  *
1254  * \see dt_object_operations::do_declare_attr_set() in the API description
1255  * for details.
1256  */
1257 static int lod_declare_attr_set(const struct lu_env *env,
1258                                 struct dt_object *dt,
1259                                 const struct lu_attr *attr,
1260                                 struct thandle *th)
1261 {
1262         struct dt_object  *next = dt_object_child(dt);
1263         struct lod_object *lo = lod_dt_obj(dt);
1264         int                rc, i;
1265         ENTRY;
1266
1267         /*
1268          * declare setattr on the local object
1269          */
1270         rc = lod_sub_declare_attr_set(env, next, attr, th);
1271         if (rc)
1272                 RETURN(rc);
1273
1274         /* osp_declare_attr_set() ignores all attributes other than
1275          * UID, GID, PROJID, and size, and osp_attr_set() ignores all
1276          * but UID, GID and PROJID. Declaration of size attr setting
1277          * happens through lod_declare_init_size(), and not through
1278          * this function. Therefore we need not load striping unless
1279          * ownership is changing.  This should save memory and (we hope)
1280          * speed up rename().
1281          */
1282         if (!S_ISDIR(dt->do_lu.lo_header->loh_attr)) {
1283                 if (!(attr->la_valid & LA_REMOTE_ATTR_SET))
1284                         RETURN(rc);
1285
1286                 if (CFS_FAIL_CHECK(OBD_FAIL_LFSCK_BAD_OWNER))
1287                         RETURN(0);
1288         } else {
1289                 if (!(attr->la_valid & (LA_UID | LA_GID | LA_PROJID | LA_MODE |
1290                                         LA_ATIME | LA_MTIME | LA_CTIME |
1291                                         LA_FLAGS)))
1292                         RETURN(rc);
1293         }
1294         /*
1295          * load striping information, notice we don't do this when object
1296          * is being initialized as we don't need this information till
1297          * few specific cases like destroy, chown
1298          */
1299         rc = lod_striping_load(env, lo);
1300         if (rc)
1301                 RETURN(rc);
1302
1303         if (!lod_obj_is_striped(dt))
1304                 RETURN(0);
1305
1306         /*
1307          * if object is striped declare changes on the stripes
1308          */
1309         if (S_ISDIR(dt->do_lu.lo_header->loh_attr)) {
1310                 LASSERT(lo->ldo_stripe);
1311                 for (i = 0; i < lo->ldo_dir_stripe_count; i++) {
1312                         if (lo->ldo_stripe[i] == NULL)
1313                                 continue;
1314                         if (!dt_object_exists(lo->ldo_stripe[i]))
1315                                 continue;
1316                         rc = lod_sub_declare_attr_set(env, lo->ldo_stripe[i],
1317                                                       attr, th);
1318                         if (rc != 0)
1319                                 RETURN(rc);
1320                 }
1321         } else {
1322                 struct lod_obj_stripe_cb_data data = { { 0 } };
1323
1324                 data.locd_attr = attr;
1325                 data.locd_declare = true;
1326                 data.locd_stripe_cb = lod_obj_stripe_attr_set_cb;
1327                 rc = lod_obj_for_each_stripe(env, lo, th, &data);
1328         }
1329
1330         if (rc)
1331                 RETURN(rc);
1332
1333         if (!dt_object_exists(next) || dt_object_remote(next) ||
1334             !S_ISREG(attr->la_mode))
1335                 RETURN(0);
1336
1337         if (CFS_FAIL_CHECK(OBD_FAIL_LFSCK_LOST_STRIPE)) {
1338                 rc = lod_sub_declare_xattr_del(env, next, XATTR_NAME_LOV, th);
1339                 RETURN(rc);
1340         }
1341
1342         if (CFS_FAIL_CHECK(OBD_FAIL_LFSCK_CHANGE_STRIPE) ||
1343             CFS_FAIL_CHECK(OBD_FAIL_LFSCK_BAD_PFL_RANGE)) {
1344                 struct lod_thread_info *info = lod_env_info(env);
1345                 struct lu_buf *buf = &info->lti_buf;
1346
1347                 buf->lb_buf = info->lti_ea_store;
1348                 buf->lb_len = info->lti_ea_store_size;
1349                 rc = lod_sub_declare_xattr_set(env, next, buf, XATTR_NAME_LOV,
1350                                                LU_XATTR_REPLACE, th);
1351         }
1352
1353         RETURN(rc);
1354 }
1355
1356 /**
1357  * Implementation of dt_object_operations::do_attr_set.
1358  *
1359  * If the object is striped, then apply the changes to all or subset of
1360  * the stripes depending on the object type and specific attributes.
1361  *
1362  * \see dt_object_operations::do_attr_set() in the API description for details.
1363  */
1364 static int lod_attr_set(const struct lu_env *env,
1365                         struct dt_object *dt,
1366                         const struct lu_attr *attr,
1367                         struct thandle *th)
1368 {
1369         struct dt_object        *next = dt_object_child(dt);
1370         struct lod_object       *lo = lod_dt_obj(dt);
1371         int                     rc, i;
1372         ENTRY;
1373
1374         /*
1375          * apply changes to the local object
1376          */
1377         rc = lod_sub_attr_set(env, next, attr, th);
1378         if (rc)
1379                 RETURN(rc);
1380
1381         if (!S_ISDIR(dt->do_lu.lo_header->loh_attr)) {
1382                 if (!(attr->la_valid & LA_REMOTE_ATTR_SET))
1383                         RETURN(rc);
1384
1385                 if (CFS_FAIL_CHECK(OBD_FAIL_LFSCK_BAD_OWNER))
1386                         RETURN(0);
1387         } else {
1388                 if (!(attr->la_valid & (LA_UID | LA_GID | LA_MODE | LA_PROJID |
1389                                         LA_ATIME | LA_MTIME | LA_CTIME |
1390                                         LA_FLAGS)))
1391                         RETURN(rc);
1392         }
1393
1394         /* FIXME: a tricky case in the code path of mdd_layout_change():
1395          * the in-memory striping information has been freed in lod_xattr_set()
1396          * due to layout change. It has to load stripe here again. It only
1397          * changes flags of layout so declare_attr_set() is still accurate */
1398         rc = lod_striping_load(env, lo);
1399         if (rc)
1400                 RETURN(rc);
1401
1402         if (!lod_obj_is_striped(dt))
1403                 RETURN(0);
1404
1405         /*
1406          * if object is striped, apply changes to all the stripes
1407          */
1408         if (S_ISDIR(dt->do_lu.lo_header->loh_attr)) {
1409                 LASSERT(lo->ldo_stripe);
1410                 for (i = 0; i < lo->ldo_dir_stripe_count; i++) {
1411                         if (unlikely(lo->ldo_stripe[i] == NULL))
1412                                 continue;
1413
1414                         if ((dt_object_exists(lo->ldo_stripe[i]) == 0))
1415                                 continue;
1416
1417                         rc = lod_sub_attr_set(env, lo->ldo_stripe[i], attr, th);
1418                         if (rc != 0)
1419                                 break;
1420                 }
1421         } else {
1422                 struct lod_obj_stripe_cb_data data = { { 0 } };
1423
1424                 data.locd_attr = attr;
1425                 data.locd_declare = false;
1426                 data.locd_stripe_cb = lod_obj_stripe_attr_set_cb;
1427                 rc = lod_obj_for_each_stripe(env, lo, th, &data);
1428         }
1429
1430         if (rc)
1431                 RETURN(rc);
1432
1433         if (!dt_object_exists(next) || dt_object_remote(next) ||
1434             !S_ISREG(attr->la_mode))
1435                 RETURN(0);
1436
1437         if (CFS_FAIL_CHECK(OBD_FAIL_LFSCK_LOST_STRIPE)) {
1438                 rc = lod_sub_xattr_del(env, next, XATTR_NAME_LOV, th);
1439                 RETURN(rc);
1440         }
1441
1442         if (CFS_FAIL_CHECK(OBD_FAIL_LFSCK_CHANGE_STRIPE)) {
1443                 struct lod_thread_info *info = lod_env_info(env);
1444                 struct lu_buf *buf = &info->lti_buf;
1445                 struct ost_id *oi = &info->lti_ostid;
1446                 struct lu_fid *fid = &info->lti_fid;
1447                 struct lov_mds_md_v1 *lmm;
1448                 struct lov_ost_data_v1 *objs;
1449                 __u32 magic;
1450
1451                 rc = lod_get_lov_ea(env, lo);
1452                 if (rc <= 0)
1453                         RETURN(rc);
1454
1455                 buf->lb_buf = info->lti_ea_store;
1456                 buf->lb_len = info->lti_ea_store_size;
1457                 lmm = info->lti_ea_store;
1458                 magic = le32_to_cpu(lmm->lmm_magic);
1459                 if (magic == LOV_MAGIC_COMP_V1 || magic == LOV_MAGIC_SEL) {
1460                         struct lov_comp_md_v1 *lcm = buf->lb_buf;
1461                         struct lov_comp_md_entry_v1 *lcme =
1462                                                 &lcm->lcm_entries[0];
1463
1464                         lmm = buf->lb_buf + le32_to_cpu(lcme->lcme_offset);
1465                         magic = le32_to_cpu(lmm->lmm_magic);
1466                 }
1467
1468                 if (magic == LOV_MAGIC_V1)
1469                         objs = &(lmm->lmm_objects[0]);
1470                 else
1471                         objs = &((struct lov_mds_md_v3 *)lmm)->lmm_objects[0];
1472                 ostid_le_to_cpu(&objs->l_ost_oi, oi);
1473                 ostid_to_fid(fid, oi, le32_to_cpu(objs->l_ost_idx));
1474                 fid->f_oid--;
1475                 fid_to_ostid(fid, oi);
1476                 ostid_cpu_to_le(oi, &objs->l_ost_oi);
1477
1478                 rc = lod_sub_xattr_set(env, next, buf, XATTR_NAME_LOV,
1479                                        LU_XATTR_REPLACE, th);
1480         } else if (CFS_FAIL_CHECK(OBD_FAIL_LFSCK_BAD_PFL_RANGE)) {
1481                 struct lod_thread_info *info = lod_env_info(env);
1482                 struct lu_buf *buf = &info->lti_buf;
1483                 struct lov_comp_md_v1 *lcm;
1484                 struct lov_comp_md_entry_v1 *lcme;
1485
1486                 rc = lod_get_lov_ea(env, lo);
1487                 if (rc <= 0)
1488                         RETURN(rc);
1489
1490                 buf->lb_buf = info->lti_ea_store;
1491                 buf->lb_len = info->lti_ea_store_size;
1492                 lcm = buf->lb_buf;
1493                 if (le32_to_cpu(lcm->lcm_magic) != LOV_MAGIC_COMP_V1 &&
1494                     le32_to_cpu(lcm->lcm_magic) != LOV_MAGIC_SEL)
1495                         RETURN(-EINVAL);
1496
1497                 le32_add_cpu(&lcm->lcm_layout_gen, 1);
1498                 lcme = &lcm->lcm_entries[0];
1499                 le64_add_cpu(&lcme->lcme_extent.e_start, 1);
1500                 le64_add_cpu(&lcme->lcme_extent.e_end, -1);
1501
1502                 rc = lod_sub_xattr_set(env, next, buf, XATTR_NAME_LOV,
1503                                        LU_XATTR_REPLACE, th);
1504         }
1505
1506         RETURN(rc);
1507 }
1508
1509 /**
1510  * Implementation of dt_object_operations::do_xattr_get.
1511  *
1512  * If LOV EA is requested from the root object and it's not
1513  * found, then return default striping for the filesystem.
1514  *
1515  * \see dt_object_operations::do_xattr_get() in the API description for details.
1516  */
1517 static int lod_xattr_get(const struct lu_env *env, struct dt_object *dt,
1518                          struct lu_buf *buf, const char *name)
1519 {
1520         struct lod_thread_info *info = lod_env_info(env);
1521         struct lod_device *dev = lu2lod_dev(dt->do_lu.lo_dev);
1522         int is_root;
1523         int rc;
1524         ENTRY;
1525
1526         rc = dt_xattr_get(env, dt_object_child(dt), buf, name);
1527         if (strcmp(name, XATTR_NAME_LMV) == 0) {
1528                 struct lmv_mds_md_v1    *lmv1;
1529                 struct lmv_foreign_md   *lfm;
1530                 int                      rc1 = 0;
1531
1532                 if (rc > (typeof(rc))sizeof(*lmv1))
1533                         RETURN(rc);
1534
1535                 /* short (<= sizeof(struct lmv_mds_md_v1)) foreign LMV case */
1536                 /* XXX empty foreign LMV is not allowed */
1537                 if (rc <= offsetof(typeof(*lfm), lfm_value))
1538                         RETURN(rc = rc > 0 ? -EINVAL : rc);
1539
1540                 if (buf->lb_buf == NULL || buf->lb_len == 0) {
1541                         BUILD_BUG_ON(sizeof(*lmv1) > sizeof(info->lti_key));
1542
1543                         /* lti_buf is large enough for *lmv1 or a short
1544                          * (<= sizeof(struct lmv_mds_md_v1)) foreign LMV
1545                          */
1546                         info->lti_buf.lb_buf = info->lti_key;
1547                         info->lti_buf.lb_len = sizeof(*lmv1);
1548                         rc = dt_xattr_get(env, dt_object_child(dt),
1549                                           &info->lti_buf, name);
1550                         if (unlikely(rc <= offsetof(typeof(*lfm),
1551                                                     lfm_value)))
1552                                 RETURN(rc = rc > 0 ? -EINVAL : rc);
1553
1554                         lfm = info->lti_buf.lb_buf;
1555                         if (le32_to_cpu(lfm->lfm_magic) == LMV_MAGIC_FOREIGN)
1556                                 RETURN(rc);
1557
1558                         if (unlikely(rc != sizeof(*lmv1)))
1559                                 RETURN(rc = rc > 0 ? -EINVAL : rc);
1560
1561                         lmv1 = info->lti_buf.lb_buf;
1562                         /* The on-disk LMV EA only contains header, but the
1563                          * returned LMV EA size should contain the space for
1564                          * the FIDs of all shards of the striped directory. */
1565                         if (le32_to_cpu(lmv1->lmv_magic) == LMV_MAGIC_V1)
1566                                 rc = lmv_mds_md_size(
1567                                         le32_to_cpu(lmv1->lmv_stripe_count),
1568                                         le32_to_cpu(lmv1->lmv_magic));
1569                 } else {
1570                         lmv1 = buf->lb_buf;
1571                         if (le32_to_cpu(lmv1->lmv_magic) != LMV_MAGIC_V1)
1572                                 RETURN(rc);
1573
1574                         if (rc != sizeof(*lmv1))
1575                                 RETURN(rc = rc > 0 ? -EINVAL : rc);
1576
1577                         rc1 = lod_load_lmv_shards(env, lod_dt_obj(dt),
1578                                                   buf, false);
1579                 }
1580
1581                 RETURN(rc = rc1 != 0 ? rc1 : rc);
1582         }
1583
1584         if ((rc > 0) && buf->lb_buf && strcmp(name, XATTR_NAME_LOV) == 0) {
1585                 struct lov_comp_md_v1 *lcm = buf->lb_buf;
1586
1587                 if (lcm->lcm_magic == cpu_to_le32(LOV_MAGIC_SEL))
1588                         lcm->lcm_magic = cpu_to_le32(LOV_MAGIC_COMP_V1);
1589         }
1590
1591         if (rc != -ENODATA || !S_ISDIR(dt->do_lu.lo_header->loh_attr & S_IFMT))
1592                 RETURN(rc);
1593
1594         /*
1595          * XXX: Only used by lfsck
1596          *
1597          * lod returns default striping on the real root of the device
1598          * this is like the root stores default striping for the whole
1599          * filesystem. historically we've been using a different approach
1600          * and store it in the config.
1601          */
1602         dt_root_get(env, dev->lod_child, &info->lti_fid);
1603         is_root = lu_fid_eq(&info->lti_fid, lu_object_fid(&dt->do_lu));
1604
1605         if (is_root && strcmp(XATTR_NAME_LOV, name) == 0) {
1606                 struct lov_user_md *lum = buf->lb_buf;
1607                 struct lov_desc *desc = &dev->lod_ost_descs.ltd_lov_desc;
1608
1609                 if (buf->lb_buf == NULL) {
1610                         rc = sizeof(*lum);
1611                 } else if (buf->lb_len >= sizeof(*lum)) {
1612                         lum->lmm_magic = cpu_to_le32(LOV_USER_MAGIC_V1);
1613                         lmm_oi_set_seq(&lum->lmm_oi, FID_SEQ_LOV_DEFAULT);
1614                         lmm_oi_set_id(&lum->lmm_oi, 0);
1615                         lmm_oi_cpu_to_le(&lum->lmm_oi, &lum->lmm_oi);
1616                         lum->lmm_pattern = cpu_to_le32(desc->ld_pattern);
1617                         lum->lmm_stripe_size = cpu_to_le32(
1618                                                 desc->ld_default_stripe_size);
1619                         lum->lmm_stripe_count = cpu_to_le16(
1620                                                 desc->ld_default_stripe_count);
1621                         lum->lmm_stripe_offset = cpu_to_le16(
1622                                                 desc->ld_default_stripe_offset);
1623                         rc = sizeof(*lum);
1624                 } else {
1625                         rc = -ERANGE;
1626                 }
1627         }
1628
1629         RETURN(rc);
1630 }
1631
1632 /**
1633  * Verify LVM EA.
1634  *
1635  * Checks that the magic of the stripe is sane.
1636  *
1637  * \param[in] lod       lod device
1638  * \param[in] lum       a buffer storing LMV EA to verify
1639  *
1640  * \retval              0 if the EA is sane
1641  * \retval              negative otherwise
1642  */
1643 static int lod_verify_md_striping(struct lod_device *lod,
1644                                   const struct lmv_user_md_v1 *lum)
1645 {
1646         if (unlikely(le32_to_cpu(lum->lum_magic) != LMV_USER_MAGIC)) {
1647                 CERROR("%s: invalid lmv_user_md: magic = %x, "
1648                        "stripe_offset = %d, stripe_count = %u: rc = %d\n",
1649                        lod2obd(lod)->obd_name, le32_to_cpu(lum->lum_magic),
1650                        (int)le32_to_cpu(lum->lum_stripe_offset),
1651                        le32_to_cpu(lum->lum_stripe_count), -EINVAL);
1652                 return -EINVAL;
1653         }
1654
1655         return 0;
1656 }
1657
1658 /**
1659  * Initialize LMV EA for a slave.
1660  *
1661  * Initialize slave's LMV EA from the master's LMV EA.
1662  *
1663  * \param[in] master_lmv        a buffer containing master's EA
1664  * \param[out] slave_lmv        a buffer where slave's EA will be stored
1665  *
1666  */
1667 static void lod_prep_slave_lmv_md(struct lmv_mds_md_v1 *slave_lmv,
1668                                   const struct lmv_mds_md_v1 *master_lmv)
1669 {
1670         *slave_lmv = *master_lmv;
1671         slave_lmv->lmv_magic = cpu_to_le32(LMV_MAGIC_STRIPE);
1672 }
1673
1674 /**
1675  * Generate LMV EA.
1676  *
1677  * Generate LMV EA from the object passed as \a dt. The object must have
1678  * the stripes created and initialized.
1679  *
1680  * \param[in] env       execution environment
1681  * \param[in] dt        object
1682  * \param[out] lmv_buf  buffer storing generated LMV EA
1683  *
1684  * \retval              0 on success
1685  * \retval              negative if failed
1686  */
1687 static int lod_prep_lmv_md(const struct lu_env *env, struct dt_object *dt,
1688                            struct lu_buf *lmv_buf)
1689 {
1690         struct lod_thread_info  *info = lod_env_info(env);
1691         struct lod_device       *lod = lu2lod_dev(dt->do_lu.lo_dev);
1692         struct lod_object       *lo = lod_dt_obj(dt);
1693         struct lmv_mds_md_v1    *lmm1;
1694         int                     stripe_count;
1695         int                     type = LU_SEQ_RANGE_ANY;
1696         int                     rc;
1697         __u32                   mdtidx;
1698         ENTRY;
1699
1700         LASSERT(lo->ldo_dir_striped != 0);
1701         LASSERT(lo->ldo_dir_stripe_count > 0);
1702         stripe_count = lo->ldo_dir_stripe_count;
1703         /* Only store the LMV EA heahder on the disk. */
1704         if (info->lti_ea_store_size < sizeof(*lmm1)) {
1705                 rc = lod_ea_store_resize(info, sizeof(*lmm1));
1706                 if (rc != 0)
1707                         RETURN(rc);
1708         } else {
1709                 memset(info->lti_ea_store, 0, sizeof(*lmm1));
1710         }
1711
1712         lmm1 = (struct lmv_mds_md_v1 *)info->lti_ea_store;
1713         memset(lmm1, 0, sizeof(*lmm1));
1714         lmm1->lmv_magic = cpu_to_le32(LMV_MAGIC);
1715         lmm1->lmv_stripe_count = cpu_to_le32(stripe_count);
1716         lmm1->lmv_hash_type = cpu_to_le32(lo->ldo_dir_hash_type);
1717         lmm1->lmv_layout_version = cpu_to_le32(lo->ldo_dir_layout_version);
1718         if (lod_is_layout_changing(lo)) {
1719                 lmm1->lmv_migrate_hash = cpu_to_le32(lo->ldo_dir_migrate_hash);
1720                 lmm1->lmv_migrate_offset =
1721                         cpu_to_le32(lo->ldo_dir_migrate_offset);
1722         }
1723         rc = lod_fld_lookup(env, lod, lu_object_fid(&dt->do_lu),
1724                             &mdtidx, &type);
1725         if (rc != 0)
1726                 RETURN(rc);
1727
1728         lmm1->lmv_master_mdt_index = cpu_to_le32(mdtidx);
1729         lmv_buf->lb_buf = info->lti_ea_store;
1730         lmv_buf->lb_len = sizeof(*lmm1);
1731
1732         RETURN(rc);
1733 }
1734
1735 /**
1736  * Create in-core represenation for a striped directory.
1737  *
1738  * Parse the buffer containing LMV EA and instantiate LU objects
1739  * representing the stripe objects. The pointers to the objects are
1740  * stored in ldo_stripe field of \a lo. This function is used when
1741  * we need to access an already created object (i.e. load from a disk).
1742  *
1743  * \param[in] env       execution environment
1744  * \param[in] lo        lod object
1745  * \param[in] buf       buffer containing LMV EA
1746  *
1747  * \retval              0 on success
1748  * \retval              negative if failed
1749  */
1750 int lod_parse_dir_striping(const struct lu_env *env, struct lod_object *lo,
1751                            const struct lu_buf *buf)
1752 {
1753         struct lod_thread_info  *info = lod_env_info(env);
1754         struct lod_device       *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
1755         struct lod_tgt_descs    *ltd = &lod->lod_mdt_descs;
1756         struct dt_object        **stripe;
1757         union lmv_mds_md        *lmm = buf->lb_buf;
1758         struct lmv_mds_md_v1    *lmv1 = &lmm->lmv_md_v1;
1759         struct lu_fid           *fid = &info->lti_fid;
1760         unsigned int            i;
1761         int                     rc = 0;
1762         ENTRY;
1763
1764         LASSERT(mutex_is_locked(&lo->ldo_layout_mutex));
1765
1766         /* XXX may be useless as not called for foreign LMV ?? */
1767         if (le32_to_cpu(lmv1->lmv_magic) == LMV_MAGIC_FOREIGN)
1768                 RETURN(0);
1769
1770         if (le32_to_cpu(lmv1->lmv_magic) == LMV_MAGIC_STRIPE) {
1771                 lo->ldo_dir_slave_stripe = 1;
1772                 RETURN(0);
1773         }
1774
1775         if (!lmv_is_sane(lmv1))
1776                 RETURN(-EINVAL);
1777
1778         LASSERT(lo->ldo_stripe == NULL);
1779         OBD_ALLOC_PTR_ARRAY(stripe, le32_to_cpu(lmv1->lmv_stripe_count));
1780         if (stripe == NULL)
1781                 RETURN(-ENOMEM);
1782
1783         for (i = 0; i < le32_to_cpu(lmv1->lmv_stripe_count); i++) {
1784                 struct dt_device        *tgt_dt;
1785                 struct dt_object        *dto;
1786                 int                     type = LU_SEQ_RANGE_ANY;
1787                 __u32                   idx;
1788
1789                 fid_le_to_cpu(fid, &lmv1->lmv_stripe_fids[i]);
1790                 if (!fid_is_sane(fid)) {
1791                         stripe[i] = NULL;
1792                         continue;
1793                 }
1794
1795                 rc = lod_fld_lookup(env, lod, fid, &idx, &type);
1796                 if (rc != 0)
1797                         GOTO(out, rc);
1798
1799                 if (idx == lod2lu_dev(lod)->ld_site->ld_seq_site->ss_node_id) {
1800                         tgt_dt = lod->lod_child;
1801                 } else {
1802                         struct lod_tgt_desc     *tgt;
1803
1804                         tgt = LTD_TGT(ltd, idx);
1805                         if (tgt == NULL)
1806                                 GOTO(out, rc = -ESTALE);
1807                         tgt_dt = tgt->ltd_tgt;
1808                 }
1809
1810                 dto = dt_locate_at(env, tgt_dt, fid,
1811                                   lo->ldo_obj.do_lu.lo_dev->ld_site->ls_top_dev,
1812                                   NULL);
1813                 if (IS_ERR(dto))
1814                         GOTO(out, rc = PTR_ERR(dto));
1815
1816                 stripe[i] = dto;
1817         }
1818 out:
1819         lo->ldo_stripe = stripe;
1820         lo->ldo_is_foreign = 0;
1821         lo->ldo_dir_stripe_count = le32_to_cpu(lmv1->lmv_stripe_count);
1822         lo->ldo_dir_stripes_allocated = le32_to_cpu(lmv1->lmv_stripe_count);
1823         lo->ldo_dir_layout_version = le32_to_cpu(lmv1->lmv_layout_version);
1824         lo->ldo_dir_migrate_offset = le32_to_cpu(lmv1->lmv_migrate_offset);
1825         lo->ldo_dir_migrate_hash = le32_to_cpu(lmv1->lmv_migrate_hash);
1826         lo->ldo_dir_hash_type = le32_to_cpu(lmv1->lmv_hash_type);
1827         if (rc != 0)
1828                 lod_striping_free_nolock(env, lo);
1829
1830         RETURN(rc);
1831 }
1832
1833 /**
1834  * Declare create a striped directory.
1835  *
1836  * Declare creating a striped directory with a given stripe pattern on the
1837  * specified MDTs. A striped directory is represented as a regular directory
1838  * - an index listing all the stripes. The stripes point back to the master
1839  * object with ".." and LinkEA. The master object gets LMV EA which
1840  * identifies it as a striped directory. The function allocates FIDs
1841  * for all stripes.
1842  *
1843  * \param[in] env       execution environment
1844  * \param[in] dt        object
1845  * \param[in] attr      attributes to initialize the objects with
1846  * \param[in] dof       type of objects to be created
1847  * \param[in] th        transaction handle
1848  *
1849  * \retval              0 on success
1850  * \retval              negative if failed
1851  */
1852 static int lod_dir_declare_create_stripes(const struct lu_env *env,
1853                                           struct dt_object *dt,
1854                                           struct lu_attr *attr,
1855                                           struct dt_object_format *dof,
1856                                           struct thandle *th)
1857 {
1858         struct lod_thread_info  *info = lod_env_info(env);
1859         struct lu_buf           lmv_buf;
1860         struct lu_buf           slave_lmv_buf;
1861         struct lmv_mds_md_v1    *lmm;
1862         struct lmv_mds_md_v1    *slave_lmm = NULL;
1863         struct dt_insert_rec    *rec = &info->lti_dt_rec;
1864         struct lod_object       *lo = lod_dt_obj(dt);
1865         int                     rc;
1866         __u32                   i;
1867         ENTRY;
1868
1869         rc = lod_prep_lmv_md(env, dt, &lmv_buf);
1870         if (rc != 0)
1871                 GOTO(out, rc);
1872         lmm = lmv_buf.lb_buf;
1873
1874         OBD_ALLOC_PTR(slave_lmm);
1875         if (slave_lmm == NULL)
1876                 GOTO(out, rc = -ENOMEM);
1877
1878         lod_prep_slave_lmv_md(slave_lmm, lmm);
1879         slave_lmv_buf.lb_buf = slave_lmm;
1880         slave_lmv_buf.lb_len = sizeof(*slave_lmm);
1881
1882         if (!dt_try_as_dir(env, dt_object_child(dt), false))
1883                 GOTO(out, rc = -EINVAL);
1884
1885         rec->rec_type = S_IFDIR;
1886         for (i = 0; i < lo->ldo_dir_stripe_count; i++) {
1887                 struct dt_object        *dto = lo->ldo_stripe[i];
1888                 char                    *stripe_name = info->lti_key;
1889                 struct lu_name          *sname;
1890                 struct linkea_data       ldata          = { NULL };
1891                 struct lu_buf           linkea_buf;
1892
1893                 /* OBD_FAIL_MDS_STRIPE_FID may leave stripe uninitialized */
1894                 if (!dto)
1895                         continue;
1896
1897                 /* directory split skip create for existing stripes */
1898                 if (!(lod_is_splitting(lo) && i < lo->ldo_dir_split_offset)) {
1899                         rc = lod_sub_declare_create(env, dto, attr, NULL, dof,
1900                                                     th);
1901                         if (rc != 0)
1902                                 GOTO(out, rc);
1903
1904                         if (!dt_try_as_dir(env, dto, false))
1905                                 GOTO(out, rc = -EINVAL);
1906
1907                         rc = lod_sub_declare_ref_add(env, dto, th);
1908                         if (rc != 0)
1909                                 GOTO(out, rc);
1910
1911                         rec->rec_fid = lu_object_fid(&dto->do_lu);
1912                         rc = lod_sub_declare_insert(env, dto,
1913                                                     (const struct dt_rec *)rec,
1914                                                     (const struct dt_key *)dot,
1915                                                     th);
1916                         if (rc != 0)
1917                                 GOTO(out, rc);
1918
1919                         /* master stripe FID will be put to .. */
1920                         rec->rec_fid = lu_object_fid(&dt->do_lu);
1921                         rc = lod_sub_declare_insert(env, dto,
1922                                                   (const struct dt_rec *)rec,
1923                                                   (const struct dt_key *)dotdot,
1924                                                   th);
1925                         if (rc != 0)
1926                                 GOTO(out, rc);
1927
1928                         if (CFS_FAIL_CHECK(OBD_FAIL_LFSCK_BAD_SLAVE_NAME) &&
1929                             cfs_fail_val == i)
1930                                 snprintf(stripe_name, sizeof(info->lti_key),
1931                                          DFID":%u",
1932                                          PFID(lu_object_fid(&dto->do_lu)),
1933                                          i + 1);
1934                         else
1935                                 snprintf(stripe_name, sizeof(info->lti_key),
1936                                          DFID":%u",
1937                                          PFID(lu_object_fid(&dto->do_lu)), i);
1938
1939                         sname = lod_name_get(env, stripe_name,
1940                                              strlen(stripe_name));
1941                         rc = linkea_links_new(&ldata, &info->lti_linkea_buf,
1942                                               sname, lu_object_fid(&dt->do_lu));
1943                         if (rc != 0)
1944                                 GOTO(out, rc);
1945
1946                         linkea_buf.lb_buf = ldata.ld_buf->lb_buf;
1947                         linkea_buf.lb_len = ldata.ld_leh->leh_len;
1948                         rc = lod_sub_declare_xattr_set(env, dto, &linkea_buf,
1949                                                        XATTR_NAME_LINK, 0, th);
1950                         if (rc != 0)
1951                                 GOTO(out, rc);
1952
1953                         rec->rec_fid = lu_object_fid(&dto->do_lu);
1954                         rc = lod_sub_declare_insert(env, dt_object_child(dt),
1955                                         (const struct dt_rec *)rec,
1956                                         (const struct dt_key *)stripe_name, th);
1957                         if (rc != 0)
1958                                 GOTO(out, rc);
1959
1960                         rc = lod_sub_declare_ref_add(env, dt_object_child(dt),
1961                                                      th);
1962                         if (rc != 0)
1963                                 GOTO(out, rc);
1964                 }
1965
1966                 if (!CFS_FAIL_CHECK(OBD_FAIL_LFSCK_LOST_SLAVE_LMV) ||
1967                     cfs_fail_val != i) {
1968                         if (CFS_FAIL_CHECK(OBD_FAIL_LFSCK_BAD_SLAVE_LMV) &&
1969                             cfs_fail_val == i)
1970                                 slave_lmm->lmv_master_mdt_index =
1971                                                         cpu_to_le32(i + 1);
1972                         else
1973                                 slave_lmm->lmv_master_mdt_index =
1974                                                         cpu_to_le32(i);
1975                         rc = lod_sub_declare_xattr_set(env, dto, &slave_lmv_buf,
1976                                                        XATTR_NAME_LMV, 0, th);
1977                         if (rc != 0)
1978                                 GOTO(out, rc);
1979                 }
1980         }
1981
1982         rc = lod_sub_declare_xattr_set(env, dt_object_child(dt),
1983                                        &lmv_buf, XATTR_NAME_LMV, 0, th);
1984         if (rc != 0)
1985                 GOTO(out, rc);
1986 out:
1987         if (slave_lmm != NULL)
1988                 OBD_FREE_PTR(slave_lmm);
1989
1990         RETURN(rc);
1991 }
1992
1993 /**
1994  * Allocate a striping on a predefined set of MDTs.
1995  *
1996  * Allocates new striping using the MDT index range provided by the data from
1997  * the lum_obejcts contained in the lmv_user_md passed to this method if
1998  * \a is_specific is true; or allocates new layout starting from MDT index in
1999  * lo->ldo_dir_stripe_offset. The exact order of MDTs is not important and
2000  * varies depending on MDT status. The number of stripes needed and stripe
2001  * offset are taken from the object. If that number cannot be met, then the
2002  * function returns an error and then it's the caller's responsibility to
2003  * release the stripes allocated. All the internal structures are protected,
2004  * but no concurrent allocation is allowed on the same objects.
2005  *
2006  * \param[in] env               execution environment for this thread
2007  * \param[in] lo                LOD object
2008  * \param[out] stripes          striping created
2009  * \param[out] mdt_indices      MDT indices of striping created
2010  * \param[in] is_specific       true if the MDTs are provided by lum; false if
2011  *                              only the starting MDT index is provided
2012  *
2013  * \retval positive     stripes allocated, including the first stripe allocated
2014  *                      outside
2015  * \retval negative     errno on failure
2016  */
2017 static int lod_mdt_alloc_specific(const struct lu_env *env,
2018                                   struct lod_object *lo,
2019                                   struct dt_object **stripes,
2020                                   __u32 *mdt_indices, bool is_specific)
2021 {
2022         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
2023         struct lu_tgt_descs *ltd = &lod->lod_mdt_descs;
2024         struct lu_tgt_desc *tgt = NULL;
2025         struct lu_object_conf conf = { .loc_flags = LOC_F_NEW };
2026         struct dt_device *tgt_dt = NULL;
2027         struct lu_fid fid = { 0 };
2028         struct dt_object *dto;
2029         u32 master_index;
2030         u32 stripe_count = lo->ldo_dir_stripe_count;
2031         int stripe_idx = 1;
2032         int j;
2033         int idx;
2034         int rc;
2035
2036         master_index = lu_site2seq(lod2lu_dev(lod)->ld_site)->ss_node_id;
2037         if (!is_specific && stripe_count > 1)
2038                 /* Set the start index for the 2nd stripe allocation */
2039                 mdt_indices[1] = (mdt_indices[0] + 1) %
2040                                         (lod->lod_remote_mdt_count + 1);
2041
2042         for (; stripe_idx < stripe_count; stripe_idx++) {
2043                 /* Try to find next avaible target */
2044                 idx = mdt_indices[stripe_idx];
2045                 for (j = 0; j < lod->lod_remote_mdt_count;
2046                      j++, idx = (idx + 1) % (lod->lod_remote_mdt_count + 1)) {
2047                         bool already_allocated = false;
2048                         __u32 k;
2049
2050                         CDEBUG(D_INFO, "try idx %d, mdt cnt %u, allocated %u\n",
2051                                idx, lod->lod_remote_mdt_count + 1, stripe_idx);
2052
2053                         if (likely(!is_specific &&
2054                                    !CFS_FAIL_CHECK(OBD_FAIL_LARGE_STRIPE))) {
2055                                 /* check whether the idx already exists
2056                                  * in current allocated array */
2057                                 for (k = 0; k < stripe_idx; k++) {
2058                                         if (mdt_indices[k] == idx) {
2059                                                 already_allocated = true;
2060                                                 break;
2061                                         }
2062                                 }
2063
2064                                 if (already_allocated)
2065                                         continue;
2066                         }
2067
2068                         /* Sigh, this index is not in the bitmap, let's check
2069                          * next available target */
2070                         if (!test_bit(idx, ltd->ltd_tgt_bitmap) &&
2071                             idx != master_index)
2072                                 continue;
2073
2074                         if (idx == master_index) {
2075                                 /* Allocate the FID locally */
2076                                 tgt_dt = lod->lod_child;
2077                                 rc = dt_fid_alloc(env, tgt_dt, &fid, NULL,
2078                                                   NULL);
2079                                 if (rc < 0)
2080                                         continue;
2081                                 break;
2082                         }
2083
2084                         /* check the status of the OSP */
2085                         tgt = LTD_TGT(ltd, idx);
2086                         if (!tgt)
2087                                 continue;
2088
2089                         tgt_dt = tgt->ltd_tgt;
2090                         if (!tgt->ltd_active)
2091                                 /* this OSP doesn't feel well */
2092                                 continue;
2093
2094                         if (tgt->ltd_statfs.os_state & OS_STATFS_NOCREATE)
2095                                 continue;
2096
2097                         rc = dt_fid_alloc(env, tgt_dt, &fid, NULL, NULL);
2098                         if (rc < 0)
2099                                 continue;
2100
2101                         break;
2102                 }
2103
2104                 /* Can not allocate more stripes */
2105                 if (j == lod->lod_remote_mdt_count) {
2106                         CDEBUG(D_INFO, "%s: require stripes %u only get %d\n",
2107                                lod2obd(lod)->obd_name, stripe_count,
2108                                stripe_idx);
2109                         break;
2110                 }
2111
2112                 CDEBUG(D_INFO, "Get idx %d, for stripe %d "DFID"\n",
2113                        idx, stripe_idx, PFID(&fid));
2114                 mdt_indices[stripe_idx] = idx;
2115                 /* Set the start index for next stripe allocation */
2116                 if (!is_specific && stripe_idx < stripe_count - 1) {
2117                         /*
2118                          * for large dir test, put all other slaves on one
2119                          * remote MDT, otherwise we may save too many local
2120                          * slave locks which will exceed RS_MAX_LOCKS.
2121                          */
2122                         if (unlikely(CFS_FAIL_CHECK(OBD_FAIL_LARGE_STRIPE)))
2123                                 idx = master_index;
2124                         mdt_indices[stripe_idx + 1] = (idx + 1) %
2125                                            (lod->lod_remote_mdt_count + 1);
2126                 }
2127                 /* tgt_dt and fid must be ready after search avaible OSP
2128                  * in the above loop */
2129                 LASSERT(tgt_dt != NULL);
2130                 LASSERT(fid_is_sane(&fid));
2131
2132                 /* fail a remote stripe FID allocation */
2133                 if (stripe_idx && CFS_FAIL_CHECK(OBD_FAIL_MDS_STRIPE_FID))
2134                         continue;
2135
2136                 dto = dt_locate_at(env, tgt_dt, &fid,
2137                                   lo->ldo_obj.do_lu.lo_dev->ld_site->ls_top_dev,
2138                                   &conf);
2139                 if (IS_ERR(dto)) {
2140                         rc = PTR_ERR(dto);
2141                         goto error;
2142                 }
2143
2144                 stripes[stripe_idx] = dto;
2145         }
2146
2147         return stripe_idx;
2148
2149 error:
2150         for (j = 1; j < stripe_idx; j++) {
2151                 LASSERT(stripes[j] != NULL);
2152                 dt_object_put(env, stripes[j]);
2153                 stripes[j] = NULL;
2154         }
2155         return rc;
2156 }
2157
2158 static int lod_prep_md_striped_create(const struct lu_env *env,
2159                                       struct dt_object *dt,
2160                                       struct lu_attr *attr,
2161                                       const struct lmv_user_md_v1 *lum,
2162                                       struct dt_object_format *dof,
2163                                       struct thandle *th)
2164 {
2165         struct lod_device *lod = lu2lod_dev(dt->do_lu.lo_dev);
2166         struct lod_object *lo = lod_dt_obj(dt);
2167         struct dt_object **stripes;
2168         struct lu_object_conf conf = { .loc_flags = LOC_F_NEW };
2169         struct lu_fid fid = { 0 };
2170         __u32 stripe_count;
2171         int i;
2172         int rc = 0;
2173
2174         ENTRY;
2175
2176         /* The lum has been verifed in lod_verify_md_striping */
2177         LASSERT(le32_to_cpu(lum->lum_magic) == LMV_USER_MAGIC ||
2178                 le32_to_cpu(lum->lum_magic) == LMV_USER_MAGIC_SPECIFIC);
2179
2180         stripe_count = lo->ldo_dir_stripe_count;
2181
2182         OBD_ALLOC_PTR_ARRAY(stripes, stripe_count);
2183         if (!stripes)
2184                 RETURN(-ENOMEM);
2185
2186         /* Allocate the first stripe locally */
2187         rc = dt_fid_alloc(env, lod->lod_child, &fid, NULL, NULL);
2188         if (rc < 0)
2189                 GOTO(out, rc);
2190
2191         stripes[0] = dt_locate_at(env, lod->lod_child, &fid,
2192                                   dt->do_lu.lo_dev->ld_site->ls_top_dev, &conf);
2193         if (IS_ERR(stripes[0]))
2194                 GOTO(out, rc = PTR_ERR(stripes[0]));
2195
2196         if (lo->ldo_dir_stripe_offset == LMV_OFFSET_DEFAULT) {
2197                 lod_qos_statfs_update(env, lod, &lod->lod_mdt_descs);
2198                 rc = lod_mdt_alloc_qos(env, lo, stripes, 1, stripe_count);
2199                 if (rc == -EAGAIN)
2200                         rc = lod_mdt_alloc_rr(env, lo, stripes, 1,
2201                                               stripe_count);
2202         } else {
2203                 int *idx_array;
2204                 bool is_specific = false;
2205
2206                 OBD_ALLOC_PTR_ARRAY(idx_array, stripe_count);
2207                 if (!idx_array)
2208                         GOTO(out, rc = -ENOMEM);
2209
2210                 if (le32_to_cpu(lum->lum_magic) == LMV_USER_MAGIC_SPECIFIC) {
2211                         is_specific = true;
2212                         for (i = 0; i < stripe_count; i++)
2213                                 idx_array[i] =
2214                                        le32_to_cpu(lum->lum_objects[i].lum_mds);
2215                 }
2216
2217                 /* stripe 0 is local */
2218                 idx_array[0] =
2219                         lu_site2seq(lod2lu_dev(lod)->ld_site)->ss_node_id;
2220                 rc = lod_mdt_alloc_specific(env, lo, stripes, idx_array,
2221                                             is_specific);
2222                 OBD_FREE_PTR_ARRAY(idx_array, stripe_count);
2223         }
2224
2225         if (rc < 0)
2226                 GOTO(out, rc);
2227
2228         LASSERT(rc > 0);
2229
2230         lo->ldo_dir_striped = 1;
2231         lo->ldo_stripe = stripes;
2232         lo->ldo_dir_stripe_count = rc;
2233         lo->ldo_dir_stripes_allocated = stripe_count;
2234         smp_mb();
2235         lo->ldo_dir_stripe_loaded = 1;
2236
2237         rc = lod_dir_declare_create_stripes(env, dt, attr, dof, th);
2238         if (rc < 0)
2239                 lod_striping_free(env, lo);
2240
2241         RETURN(rc);
2242
2243 out:
2244         LASSERT(rc < 0);
2245         if (!IS_ERR_OR_NULL(stripes[0]))
2246                 dt_object_put(env, stripes[0]);
2247         for (i = 1; i < stripe_count; i++)
2248                 LASSERT(!stripes[i]);
2249         OBD_FREE_PTR_ARRAY(stripes, stripe_count);
2250
2251         return rc;
2252 }
2253
2254 /**
2255  *
2256  * Alloc cached foreign LOV
2257  *
2258  * \param[in] lo        object
2259  * \param[in] size      size of foreign LOV
2260  *
2261  * \retval              0 on success
2262  * \retval              negative if failed
2263  */
2264 int lod_alloc_foreign_lov(struct lod_object *lo, size_t size)
2265 {
2266         OBD_ALLOC_LARGE(lo->ldo_foreign_lov, size);
2267         if (lo->ldo_foreign_lov == NULL)
2268                 return -ENOMEM;
2269         lo->ldo_foreign_lov_size = size;
2270         lo->ldo_is_foreign = 1;
2271         return 0;
2272 }
2273
2274 /**
2275  *
2276  * Free cached foreign LOV
2277  *
2278  * \param[in] lo        object
2279  */
2280 void lod_free_foreign_lov(struct lod_object *lo)
2281 {
2282         if (lo->ldo_foreign_lov != NULL)
2283                 OBD_FREE_LARGE(lo->ldo_foreign_lov, lo->ldo_foreign_lov_size);
2284         lo->ldo_foreign_lov = NULL;
2285         lo->ldo_foreign_lov_size = 0;
2286         lo->ldo_is_foreign = 0;
2287 }
2288
2289 /**
2290  *
2291  * Alloc cached foreign LMV
2292  *
2293  * \param[in] lo        object
2294  * \param[in] size      size of foreign LMV
2295  *
2296  * \retval              0 on success
2297  * \retval              negative if failed
2298  */
2299 int lod_alloc_foreign_lmv(struct lod_object *lo, size_t size)
2300 {
2301         OBD_ALLOC_LARGE(lo->ldo_foreign_lmv, size);
2302         if (lo->ldo_foreign_lmv == NULL)
2303                 return -ENOMEM;
2304         lo->ldo_foreign_lmv_size = size;
2305         lo->ldo_is_foreign = 1;
2306
2307         return 0;
2308 }
2309
2310 static int lod_prep_md_replayed_create(const struct lu_env *env,
2311                                        struct dt_object *dt,
2312                                        struct lu_attr *attr,
2313                                        const struct lu_buf *lmv_buf,
2314                                        struct dt_object_format *dof,
2315                                        struct thandle *th)
2316 {
2317         struct lod_object *lo = lod_dt_obj(dt);
2318         int rc;
2319
2320         ENTRY;
2321
2322         mutex_lock(&lo->ldo_layout_mutex);
2323         rc = lod_parse_dir_striping(env, lo, lmv_buf);
2324         if (rc == 0) {
2325                 lo->ldo_dir_stripe_loaded = 1;
2326                 lo->ldo_dir_striped = 1;
2327                 rc = lod_dir_declare_create_stripes(env, dt, attr, dof, th);
2328         }
2329         mutex_unlock(&lo->ldo_layout_mutex);
2330
2331         RETURN(rc);
2332 }
2333
2334 /**
2335  *
2336  * Free cached foreign LMV
2337  *
2338  * \param[in] lo        object
2339  */
2340 void lod_free_foreign_lmv(struct lod_object *lo)
2341 {
2342         if (lo->ldo_foreign_lmv != NULL)
2343                 OBD_FREE_LARGE(lo->ldo_foreign_lmv, lo->ldo_foreign_lmv_size);
2344         lo->ldo_foreign_lmv = NULL;
2345         lo->ldo_foreign_lmv_size = 0;
2346         lo->ldo_is_foreign = 0;
2347 }
2348
2349 /**
2350  * Declare create striped md object.
2351  *
2352  * The function declares intention to create a striped directory. This is a
2353  * wrapper for lod_prep_md_striped_create(). The only additional functionality
2354  * is to verify pattern \a lum_buf is good. Check that function for the details.
2355  *
2356  * \param[in] env       execution environment
2357  * \param[in] dt        object
2358  * \param[in] attr      attributes to initialize the objects with
2359  * \param[in] lum_buf   a pattern specifying the number of stripes and
2360  *                      MDT to start from
2361  * \param[in] dof       type of objects to be created
2362  * \param[in] th        transaction handle
2363  *
2364  * \retval              0 on success
2365  * \retval              negative if failed
2366  *
2367  */
2368 static int lod_declare_xattr_set_lmv(const struct lu_env *env,
2369                                      struct dt_object *dt,
2370                                      struct lu_attr *attr,
2371                                      const struct lu_buf *lum_buf,
2372                                      struct dt_object_format *dof,
2373                                      struct thandle *th)
2374 {
2375         struct lod_object *lo = lod_dt_obj(dt);
2376         struct lmv_user_md_v1 *lum = lum_buf->lb_buf;
2377         int rc;
2378
2379         ENTRY;
2380         LASSERT(lum != NULL);
2381
2382         CDEBUG(D_INFO,
2383                "lum magic=%x hash=%x count=%u offset=%d inherit=%u rr=%u\n",
2384                le32_to_cpu(lum->lum_magic), le32_to_cpu(lum->lum_hash_type),
2385                le32_to_cpu(lum->lum_stripe_count),
2386                (int)le32_to_cpu(lum->lum_stripe_offset),
2387                lum->lum_max_inherit, lum->lum_max_inherit_rr);
2388
2389         if (lo->ldo_dir_stripe_count == 0) {
2390                 if (lo->ldo_is_foreign) {
2391                         rc = lod_alloc_foreign_lmv(lo, lum_buf->lb_len);
2392                         if (rc != 0)
2393                                 RETURN(rc);
2394                         memcpy(lo->ldo_foreign_lmv, lum, lum_buf->lb_len);
2395                         lo->ldo_dir_stripe_loaded = 1;
2396                 }
2397                 RETURN(0);
2398         }
2399
2400         /* client replay striped directory creation with LMV, this happens when
2401          * all involved MDTs were rebooted, or MDT recovery was aborted.
2402          */
2403         if (le32_to_cpu(lum->lum_magic) == LMV_MAGIC_V1)
2404                 rc = lod_prep_md_replayed_create(env, dt, attr, lum_buf, dof,
2405                                                  th);
2406         else
2407                 rc = lod_prep_md_striped_create(env, dt, attr, lum, dof, th);
2408         if (rc != 0)
2409                 /* failed to create striping, let's reset
2410                  * config so that others don't get confused */
2411                 lod_striping_free(env, lo);
2412
2413         RETURN(rc);
2414 }
2415
2416 /**
2417  * Set or replace striped directory layout, and LFSCK may set layout on a plain
2418  * directory, so don't check stripe count.
2419  *
2420  * \param[in] env       execution environment
2421  * \param[in] dt        target object
2422  * \param[in] lmv_buf   LMV buf which contains source stripe FIDs
2423  * \param[in] fl        set or replace
2424  * \param[in] th        transaction handle
2425  *
2426  * \retval              0 on success
2427  * \retval              negative if failed
2428  */
2429 static int lod_dir_layout_set(const struct lu_env *env,
2430                               struct dt_object *dt,
2431                               const struct lu_buf *lmv_buf,
2432                               int fl,
2433                               struct thandle *th)
2434 {
2435         struct dt_object *next = dt_object_child(dt);
2436         struct lod_object *lo = lod_dt_obj(dt);
2437         struct lod_device *lod = lu2lod_dev(lod2lu_obj(lo)->lo_dev);
2438         struct lmv_mds_md_v1 *lmv = lmv_buf->lb_buf;
2439         struct lmv_mds_md_v1 *slave_lmv;
2440         struct lu_buf slave_buf;
2441         int i;
2442         int rc;
2443
2444         ENTRY;
2445
2446         if (!lmv_is_sane2(lmv))
2447                 RETURN(-EINVAL);
2448
2449         /* adjust hash for dir merge, which may not be set in user command */
2450         if (lmv_is_merging(lmv) &&
2451             !(lmv->lmv_migrate_hash & LMV_HASH_TYPE_MASK))
2452                 lmv->lmv_merge_hash |=
2453                         lod->lod_mdt_descs.ltd_lmv_desc.ld_pattern &
2454                         LMV_HASH_TYPE_MASK;
2455
2456         LMV_DEBUG(D_INFO, lmv, "set");
2457
2458         rc = lod_sub_xattr_set(env, next, lmv_buf, XATTR_NAME_LMV, fl, th);
2459         if (rc)
2460                 RETURN(rc);
2461
2462         /* directory restripe may update stripe LMV directly */
2463         if (!lo->ldo_dir_stripe_count)
2464                 RETURN(0);
2465
2466         lo->ldo_dir_hash_type = le32_to_cpu(lmv->lmv_hash_type);
2467         lo->ldo_dir_migrate_offset = le32_to_cpu(lmv->lmv_migrate_offset);
2468         lo->ldo_dir_migrate_hash = le32_to_cpu(lmv->lmv_migrate_hash);
2469         lo->ldo_dir_layout_version = le32_to_cpu(lmv->lmv_layout_version);
2470
2471         OBD_ALLOC_PTR(slave_lmv);
2472         if (!slave_lmv)
2473                 RETURN(-ENOMEM);
2474
2475         lod_prep_slave_lmv_md(slave_lmv, lmv);
2476         slave_buf.lb_buf = slave_lmv;
2477         slave_buf.lb_len = sizeof(*slave_lmv);
2478
2479         for (i = 0; i < lo->ldo_dir_stripe_count; i++) {
2480                 if (!lo->ldo_stripe[i])
2481                         continue;
2482
2483                 if (!dt_object_exists(lo->ldo_stripe[i]))
2484                         continue;
2485
2486                 rc = lod_sub_xattr_set(env, lo->ldo_stripe[i], &slave_buf,
2487                                        XATTR_NAME_LMV, fl, th);
2488                 if (rc)
2489                         break;
2490         }
2491
2492         OBD_FREE_PTR(slave_lmv);
2493
2494         RETURN(rc);
2495 }
2496
2497 /**
2498  * Implementation of dt_object_operations::do_declare_xattr_set.
2499  *
2500  * Used with regular (non-striped) objects. Basically it
2501  * initializes the striping information and applies the
2502  * change to all the stripes.
2503  *
2504  * \see dt_object_operations::do_declare_xattr_set() in the API description
2505  * for details.
2506  */
2507 static int lod_dir_declare_xattr_set(const struct lu_env *env,
2508                                      struct dt_object *dt,
2509                                      const struct lu_buf *buf,
2510                                      const char *name, int fl,
2511                                      struct thandle *th)
2512 {
2513         struct dt_object        *next = dt_object_child(dt);
2514         struct lod_device       *d = lu2lod_dev(dt->do_lu.lo_dev);
2515         struct lod_object       *lo = lod_dt_obj(dt);
2516         int                     i;
2517         int                     rc;
2518         ENTRY;
2519
2520         if (strcmp(name, XATTR_NAME_DEFAULT_LMV) == 0) {
2521                 struct lmv_user_md_v1 *lum;
2522
2523                 LASSERT(buf != NULL && buf->lb_buf != NULL);
2524                 lum = buf->lb_buf;
2525                 rc = lod_verify_md_striping(d, lum);
2526                 if (rc != 0)
2527                         RETURN(rc);
2528         } else if (strcmp(name, XATTR_NAME_LOV) == 0) {
2529                 rc = lod_verify_striping(env, d, lo, buf, false);
2530                 if (rc != 0)
2531                         RETURN(rc);
2532         }
2533
2534         rc = lod_sub_declare_xattr_set(env, next, buf, name, fl, th);
2535         if (rc != 0)
2536                 RETURN(rc);
2537
2538         /* Note: Do not set LinkEA on sub-stripes, otherwise
2539          * it will confuse the fid2path process(see mdt_path_current()).
2540          * The linkEA between master and sub-stripes is set in
2541          * lod_xattr_set_lmv(). */
2542         if (strcmp(name, XATTR_NAME_LINK) == 0)
2543                 RETURN(0);
2544
2545         /* set xattr to each stripes, if needed */
2546         rc = lod_striping_load(env, lo);
2547         if (rc != 0)
2548                 RETURN(rc);
2549
2550         if (lo->ldo_dir_stripe_count == 0)
2551                 RETURN(0);
2552
2553         for (i = 0; i < lo->ldo_dir_stripe_count; i++) {
2554                 if (!lo->ldo_stripe[i])
2555                         continue;
2556
2557                 if (!dt_object_exists(lo->ldo_stripe[i]))
2558                         continue;
2559
2560                 rc = lod_sub_declare_xattr_set(env, lo->ldo_stripe[i],
2561                                                buf, name, fl, th);
2562                 if (rc != 0)
2563                         break;
2564         }
2565
2566         RETURN(rc);
2567 }
2568
2569 static int
2570 lod_obj_stripe_replace_parent_fid_cb(const struct lu_env *env,
2571                                      struct lod_object *lo,
2572                                      struct dt_object *dt, struct thandle *th,
2573                                      int comp_idx, int stripe_idx,
2574                                      struct lod_obj_stripe_cb_data *data)
2575 {
2576         struct lod_thread_info *info = lod_env_info(env);
2577         struct lod_layout_component *comp = &lo->ldo_comp_entries[comp_idx];
2578         struct filter_fid *ff = &info->lti_ff;
2579         struct lu_buf *buf = &info->lti_buf;
2580         int rc;
2581
2582         buf->lb_buf = ff;
2583         buf->lb_len = sizeof(*ff);
2584         rc = dt_xattr_get(env, dt, buf, XATTR_NAME_FID);
2585         if (rc < 0) {
2586                 if (rc == -ENODATA)
2587                         return 0;
2588                 return rc;
2589         }
2590
2591         /*
2592          * locd_buf is set if it's called by dir migration, which doesn't check
2593          * pfid and comp id.
2594          */
2595         if (data->locd_buf) {
2596                 memset(ff, 0, sizeof(*ff));
2597                 ff->ff_parent = *(struct lu_fid *)data->locd_buf->lb_buf;
2598         } else {
2599                 filter_fid_le_to_cpu(ff, ff, sizeof(*ff));
2600
2601                 if (lu_fid_eq(lod_object_fid(lo), &ff->ff_parent) &&
2602                     ff->ff_layout.ol_comp_id == comp->llc_id)
2603                         return 0;
2604
2605                 memset(ff, 0, sizeof(*ff));
2606                 ff->ff_parent = *lu_object_fid(&lo->ldo_obj.do_lu);
2607         }
2608
2609         /* rewrite filter_fid */
2610         ff->ff_parent.f_ver = stripe_idx;
2611         ff->ff_layout.ol_stripe_size = comp->llc_stripe_size;
2612         ff->ff_layout.ol_stripe_count = comp->llc_stripe_count;
2613         ff->ff_layout.ol_comp_id = comp->llc_id;
2614         ff->ff_layout.ol_comp_start = comp->llc_extent.e_start;
2615         ff->ff_layout.ol_comp_end = comp->llc_extent.e_end;
2616         filter_fid_cpu_to_le(ff, ff, sizeof(*ff));
2617
2618         if (data->locd_declare)
2619                 rc = lod_sub_declare_xattr_set(env, dt, buf, XATTR_NAME_FID,
2620                                                LU_XATTR_REPLACE, th);
2621         else
2622                 rc = lod_sub_xattr_set(env, dt, buf, XATTR_NAME_FID,
2623                                        LU_XATTR_REPLACE, th);
2624
2625         return rc;
2626 }
2627
2628 /**
2629  * Reset parent FID on OST object
2630  *
2631  * Replace parent FID with @dt object FID, which is only called during migration
2632  * to reset the parent FID after the MDT object is migrated to the new MDT, i.e.
2633  * the FID is changed.
2634  *
2635  * \param[in] env execution environment
2636  * \param[in] dt dt_object whose stripes's parent FID will be reset
2637  * \parem[in] th thandle
2638  * \param[in] declare if it is declare
2639  *
2640  * \retval      0 if reset succeeds
2641  * \retval      negative errno if reset fails
2642  */
2643 static int lod_replace_parent_fid(const struct lu_env *env,
2644                                   struct dt_object *dt,
2645                                   const struct lu_buf *buf,
2646                                   struct thandle *th, bool declare)
2647 {
2648         struct lod_object *lo = lod_dt_obj(dt);
2649         struct lod_thread_info  *info = lod_env_info(env);
2650         struct filter_fid *ff;
2651         struct lod_obj_stripe_cb_data data = { { 0 } };
2652         int rc;
2653         ENTRY;
2654
2655         LASSERT(S_ISREG(dt->do_lu.lo_header->loh_attr));
2656
2657         /* set xattr to each stripes, if needed */
2658         rc = lod_striping_load(env, lo);
2659         if (rc != 0)
2660                 RETURN(rc);
2661
2662         if (!lod_obj_is_striped(dt))
2663                 RETURN(0);
2664
2665         if (info->lti_ea_store_size < sizeof(*ff)) {
2666                 rc = lod_ea_store_resize(info, sizeof(*ff));
2667                 if (rc != 0)
2668                         RETURN(rc);
2669         }
2670
2671         data.locd_declare = declare;
2672         data.locd_stripe_cb = lod_obj_stripe_replace_parent_fid_cb;
2673         data.locd_buf = buf;
2674         rc = lod_obj_for_each_stripe(env, lo, th, &data);
2675
2676         RETURN(rc);
2677 }
2678
2679 __u16 lod_comp_entry_stripe_count(struct lod_object *lo, int comp_idx,
2680                                   bool is_dir)
2681 {
2682         struct lod_device *lod = lu2lod_dev(lod2lu_obj(lo)->lo_dev);
2683         struct lod_layout_component *entry;
2684         enum lod_uses_hint flags = LOD_USES_ASSIGNED_STRIPE;
2685
2686         if (is_dir)
2687                 return  0;
2688
2689         entry = &lo->ldo_comp_entries[comp_idx];
2690         if (lod_comp_inited(entry))
2691                 return entry->llc_stripe_count;
2692         if (entry->llc_stripe_count == LOV_ALL_STRIPES)
2693                 return lod_get_stripe_count_plain(lod, lo,
2694                                                   entry->llc_stripe_count,
2695                                                   entry->llc_pattern &
2696                                                       LOV_PATTERN_OVERSTRIPING,
2697                                                   &flags);
2698
2699         return lod_get_stripe_count(lod, lo, comp_idx, entry->llc_stripe_count,
2700                                  entry->llc_pattern & LOV_PATTERN_OVERSTRIPING,
2701                                  &flags);
2702 }
2703
2704 static int lod_comp_md_size(struct lod_object *lo, bool is_dir)
2705 {
2706         int magic, size = 0, i;
2707         struct lod_layout_component *comp_entries;
2708         __u16 comp_cnt;
2709         bool is_composite, is_foreign = false;
2710
2711         if (is_dir) {
2712                 comp_cnt = lo->ldo_def_striping->lds_def_comp_cnt;
2713                 comp_entries = lo->ldo_def_striping->lds_def_comp_entries;
2714                 is_composite =
2715                         lo->ldo_def_striping->lds_def_striping_is_composite;
2716         } else {
2717                 comp_cnt = lo->ldo_comp_cnt;
2718                 comp_entries = lo->ldo_comp_entries;
2719                 is_composite = lo->ldo_is_composite;
2720                 is_foreign = lo->ldo_is_foreign;
2721         }
2722
2723         if (is_foreign)
2724                 return lo->ldo_foreign_lov_size;
2725
2726         LASSERT(comp_cnt != 0 && comp_entries != NULL);
2727         if (is_composite) {
2728                 size = sizeof(struct lov_comp_md_v1) +
2729                        sizeof(struct lov_comp_md_entry_v1) * comp_cnt;
2730                 LASSERT(size % sizeof(__u64) == 0);
2731         }
2732
2733         for (i = 0; i < comp_cnt; i++) {
2734                 __u16 stripe_count;
2735
2736                 if (comp_entries[i].llc_magic == LOV_MAGIC_FOREIGN) {
2737                         size += lov_foreign_md_size(comp_entries[i].llc_length);
2738                 } else {
2739                         magic = comp_entries[i].llc_pool ? LOV_MAGIC_V3 :
2740                                                            LOV_MAGIC_V1;
2741                         stripe_count = lod_comp_entry_stripe_count(lo, i,
2742                                                                    is_dir);
2743                         if (!is_dir && is_composite)
2744                                 lod_comp_shrink_stripe_count(&comp_entries[i],
2745                                                              &stripe_count);
2746
2747                         size += lov_user_md_size(stripe_count, magic);
2748                 }
2749                 LASSERT(size % sizeof(__u64) == 0);
2750         }
2751         return size;
2752 }
2753
2754 /**
2755  * Declare component add. The xattr name is XATTR_LUSTRE_LOV.add, and
2756  * the xattr value is binary lov_comp_md_v1 which contains component(s)
2757  * to be added.
2758   *
2759  * \param[in] env       execution environment
2760  * \param[in] dt        dt_object to add components on
2761  * \param[in] buf       buffer contains components to be added
2762  * \parem[in] th        thandle
2763  *
2764  * \retval      0 on success
2765  * \retval      negative errno on failure
2766  */
2767 static int lod_declare_layout_add(const struct lu_env *env,
2768                                   struct dt_object *dt,
2769                                   const struct lu_buf *buf,
2770                                   struct thandle *th)
2771 {
2772         struct lod_thread_info  *info = lod_env_info(env);
2773         struct lod_layout_component *comp_array, *lod_comp, *old_array;
2774         struct lod_device *d = lu2lod_dev(dt->do_lu.lo_dev);
2775         struct dt_object *next = dt_object_child(dt);
2776         struct lov_desc *desc = &d->lod_ost_descs.ltd_lov_desc;
2777         struct lod_object *lo = lod_dt_obj(dt);
2778         struct lov_comp_md_v1 *comp_v1 = buf->lb_buf;
2779         __u32 magic;
2780         int i, rc, array_cnt, old_array_cnt;
2781         ENTRY;
2782
2783         LASSERT(lo->ldo_is_composite);
2784
2785         if (lo->ldo_flr_state != LCM_FL_NONE)
2786                 RETURN(-EBUSY);
2787
2788         rc = lod_verify_striping(env, d, lo, buf, false);
2789         if (rc != 0)
2790                 RETURN(rc);
2791
2792         magic = comp_v1->lcm_magic;
2793         if (magic == __swab32(LOV_USER_MAGIC_COMP_V1)) {
2794                 lustre_swab_lov_comp_md_v1(comp_v1);
2795                 magic = comp_v1->lcm_magic;
2796         }
2797
2798         if (magic != LOV_USER_MAGIC_COMP_V1)
2799                 RETURN(-EINVAL);
2800
2801         mutex_lock(&lo->ldo_layout_mutex);
2802
2803         array_cnt = lo->ldo_comp_cnt + comp_v1->lcm_entry_count;
2804         OBD_ALLOC_PTR_ARRAY(comp_array, array_cnt);
2805         if (comp_array == NULL) {
2806                 mutex_unlock(&lo->ldo_layout_mutex);
2807                 RETURN(-ENOMEM);
2808         }
2809
2810
2811         memcpy(comp_array, lo->ldo_comp_entries,
2812                sizeof(*comp_array) * lo->ldo_comp_cnt);
2813
2814         for (i = 0; i < comp_v1->lcm_entry_count; i++) {
2815                 struct lov_user_md_v1 *v1;
2816                 struct lu_extent *ext;
2817
2818                 v1 = (struct lov_user_md *)((char *)comp_v1 +
2819                                 comp_v1->lcm_entries[i].lcme_offset);
2820                 ext = &comp_v1->lcm_entries[i].lcme_extent;
2821
2822                 lod_comp = &comp_array[lo->ldo_comp_cnt + i];
2823                 lod_comp->llc_extent.e_start = ext->e_start;
2824                 lod_comp->llc_extent.e_end = ext->e_end;
2825                 lod_comp->llc_stripe_offset = v1->lmm_stripe_offset;
2826                 lod_comp->llc_flags = comp_v1->lcm_entries[i].lcme_flags;
2827
2828                 lod_comp->llc_stripe_size = v1->lmm_stripe_size;
2829                 lod_comp->llc_stripe_count = v1->lmm_stripe_count;
2830                 /**
2831                  * limit stripe count so that it's less than/equal to
2832                  * extent_size / stripe_size.
2833                  *
2834                  * Note: extension size reused llc_stripe_size field and
2835                  * uninstantiated component could be defined with
2836                  * extent_start == extent_end as extension component will
2837                  * expand it later.
2838                  */
2839                 if (!(lod_comp->llc_flags & LCME_FL_EXTENSION) &&
2840                     (lod_comp_inited(lod_comp) ||
2841                      lod_comp->llc_extent.e_start <
2842                      lod_comp->llc_extent.e_end) &&
2843                     lod_comp->llc_stripe_count != LOV_ALL_STRIPES &&
2844                     ext->e_end != OBD_OBJECT_EOF &&
2845                     (__u64)(lod_comp->llc_stripe_count *
2846                             lod_comp->llc_stripe_size) >
2847                     (ext->e_end - ext->e_start))
2848                         lod_comp->llc_stripe_count =
2849                                 DIV_ROUND_UP(ext->e_end - ext->e_start,
2850                                              lod_comp->llc_stripe_size);
2851                 lod_adjust_stripe_info(lod_comp, desc, 0);
2852
2853                 if (v1->lmm_magic == LOV_USER_MAGIC_V3) {
2854                         struct lov_user_md_v3 *v3 = (typeof(*v3) *) v1;
2855
2856                         if (v3->lmm_pool_name[0] != '\0' &&
2857                             !lov_pool_is_ignored(v3->lmm_pool_name)) {
2858                                 rc = lod_set_pool(&lod_comp->llc_pool,
2859                                                   v3->lmm_pool_name);
2860                                 if (rc)
2861                                         GOTO(error, rc);
2862                         }
2863                 }
2864         }
2865
2866         old_array = lo->ldo_comp_entries;
2867         old_array_cnt = lo->ldo_comp_cnt;
2868
2869         lo->ldo_comp_entries = comp_array;
2870         lo->ldo_comp_cnt = array_cnt;
2871
2872         /* No need to increase layout generation here, it will be increased
2873          * later when generating component ID for the new components */
2874
2875         info->lti_buf.lb_len = lod_comp_md_size(lo, false);
2876         rc = lod_sub_declare_xattr_set(env, next, &info->lti_buf,
2877                                               XATTR_NAME_LOV, 0, th);
2878         if (rc) {
2879                 lo->ldo_comp_entries = old_array;
2880                 lo->ldo_comp_cnt = old_array_cnt;
2881                 GOTO(error, rc);
2882         }
2883
2884         OBD_FREE_PTR_ARRAY(old_array, old_array_cnt);
2885
2886         LASSERT(lo->ldo_mirror_count == 1);
2887         lo->ldo_mirrors[0].lme_end = array_cnt - 1;
2888
2889         mutex_unlock(&lo->ldo_layout_mutex);
2890
2891         RETURN(0);
2892
2893 error:
2894         for (i = lo->ldo_comp_cnt; i < array_cnt; i++) {
2895                 lod_comp = &comp_array[i];
2896                 if (lod_comp->llc_pool != NULL) {
2897                         OBD_FREE(lod_comp->llc_pool,
2898                                  strlen(lod_comp->llc_pool) + 1);
2899                         lod_comp->llc_pool = NULL;
2900                 }
2901         }
2902         OBD_FREE_PTR_ARRAY(comp_array, array_cnt);
2903         mutex_unlock(&lo->ldo_layout_mutex);
2904
2905         RETURN(rc);
2906 }
2907
2908 /**
2909  * lod_last_non_stale_mirror() - Check if a mirror is the last non-stale mirror.
2910  * @mirror_id: Mirror id to be checked.
2911  * @lo:        LOD object.
2912  *
2913  * This function checks if a mirror with specified @mirror_id is the last
2914  * non-stale mirror of a LOD object @lo.
2915  *
2916  * Return: true or false.
2917  */
2918 static inline
2919 bool lod_last_non_stale_mirror(__u16 mirror_id, struct lod_object *lo)
2920 {
2921         struct lod_layout_component *lod_comp;
2922         bool has_stale_flag;
2923         int i;
2924
2925         for (i = 0; i < lo->ldo_mirror_count; i++) {
2926                 if (lo->ldo_mirrors[i].lme_id == mirror_id ||
2927                     lo->ldo_mirrors[i].lme_stale)
2928                         continue;
2929
2930                 has_stale_flag = false;
2931                 lod_foreach_mirror_comp(lod_comp, lo, i) {
2932                         if (lod_comp->llc_flags & LCME_FL_STALE) {
2933                                 has_stale_flag = true;
2934                                 break;
2935                         }
2936                 }
2937                 if (!has_stale_flag)
2938                         return false;
2939         }
2940
2941         return true;
2942 }
2943
2944 /**
2945  * Declare component set. The xattr is name XATTR_LUSTRE_LOV.set.$field,
2946  * the '$field' can only be 'flags' now. The xattr value is binary
2947  * lov_comp_md_v1 which contains the component ID(s) and the value of
2948  * the field to be modified.
2949  * Please update allowed_lustre_lov macro if $field groks more values
2950  * in the future.
2951  *
2952  * \param[in] env       execution environment
2953  * \param[in] dt        dt_object to be modified
2954  * \param[in] op        operation string, like "set.flags"
2955  * \param[in] buf       buffer contains components to be set
2956  * \parem[in] th        thandle
2957  *
2958  * \retval      0 on success
2959  * \retval      negative errno on failure
2960  */
2961 static int lod_declare_layout_set(const struct lu_env *env,
2962                                   struct dt_object *dt,
2963                                   char *op, const struct lu_buf *buf,
2964                                   struct thandle *th)
2965 {
2966         struct lod_layout_component     *lod_comp;
2967         struct lod_thread_info  *info = lod_env_info(env);
2968         struct lod_device       *d = lu2lod_dev(dt->do_lu.lo_dev);
2969         struct lod_object       *lo = lod_dt_obj(dt);
2970         struct lov_comp_md_v1   *comp_v1 = buf->lb_buf;
2971         __u32   magic;
2972         int     i, j, rc;
2973         bool    changed = false;
2974         ENTRY;
2975
2976         /* Please update allowed_lustre_lov macro if op
2977          * groks more values in the future
2978          */
2979         if (strcmp(op, "set.flags") != 0) {
2980                 CDEBUG(D_LAYOUT, "%s: operation (%s) not supported.\n",
2981                        lod2obd(d)->obd_name, op);
2982                 RETURN(-ENOTSUPP);
2983         }
2984
2985         magic = comp_v1->lcm_magic;
2986         if (magic == __swab32(LOV_USER_MAGIC_COMP_V1)) {
2987                 lustre_swab_lov_comp_md_v1(comp_v1);
2988                 magic = comp_v1->lcm_magic;
2989         }
2990
2991         if (magic != LOV_USER_MAGIC_COMP_V1)
2992                 RETURN(-EINVAL);
2993
2994         if (comp_v1->lcm_entry_count == 0) {
2995                 CDEBUG(D_LAYOUT, "%s: entry count is zero.\n",
2996                        lod2obd(d)->obd_name);
2997                 RETURN(-EINVAL);
2998         }
2999
3000         mutex_lock(&lo->ldo_layout_mutex);
3001         for (i = 0; i < comp_v1->lcm_entry_count; i++) {
3002                 __u32 id = comp_v1->lcm_entries[i].lcme_id;
3003                 __u32 flags = comp_v1->lcm_entries[i].lcme_flags;
3004                 __u32 mirror_flag = flags & LCME_MIRROR_FLAGS;
3005                 __u16 mirror_id = mirror_id_of(id);
3006                 bool neg = flags & LCME_FL_NEG;
3007
3008                 if (flags & LCME_FL_INIT) {
3009                         if (changed)
3010                                 lod_striping_free_nolock(env, lo);
3011                         mutex_unlock(&lo->ldo_layout_mutex);
3012                         RETURN(-EINVAL);
3013                 }
3014
3015                 flags &= ~(LCME_MIRROR_FLAGS | LCME_FL_NEG);
3016                 for (j = 0; j < lo->ldo_comp_cnt; j++) {
3017                         lod_comp = &lo->ldo_comp_entries[j];
3018
3019                         /* lfs only put one flag in each entry */
3020                         if ((flags && id != lod_comp->llc_id) ||
3021                             (mirror_flag && mirror_id !=
3022                                             mirror_id_of(lod_comp->llc_id)))
3023                                 continue;
3024
3025                         if (neg) {
3026                                 if (flags)
3027                                         lod_comp->llc_flags &= ~flags;
3028                                 if (mirror_flag)
3029                                         lod_comp->llc_flags &= ~mirror_flag;
3030                         } else {
3031                                 if (flags) {
3032                                         if ((flags & LCME_FL_STALE) &&
3033                                             lod_last_non_stale_mirror(mirror_id,
3034                                                                       lo)) {
3035                                                 mutex_unlock(
3036                                                         &lo->ldo_layout_mutex);
3037                                                 RETURN(-EUCLEAN);
3038                                         }
3039                                         lod_comp->llc_flags |= flags;
3040                                 }
3041                                 if (mirror_flag) {
3042                                         lod_comp->llc_flags |= mirror_flag;
3043                                         if (mirror_flag & LCME_FL_NOSYNC)
3044                                                 lod_comp->llc_timestamp =
3045                                                        ktime_get_real_seconds();
3046                                 }
3047                         }
3048                         changed = true;
3049                 }
3050         }
3051         mutex_unlock(&lo->ldo_layout_mutex);
3052
3053         if (!changed) {
3054                 CDEBUG(D_LAYOUT, "%s: requested component(s) not found.\n",
3055                        lod2obd(d)->obd_name);
3056                 RETURN(-EINVAL);
3057         }
3058
3059         lod_obj_inc_layout_gen(lo);
3060
3061         info->lti_buf.lb_len = lod_comp_md_size(lo, false);
3062         rc = lod_sub_declare_xattr_set(env, dt_object_child(dt), &info->lti_buf,
3063                                        XATTR_NAME_LOV, LU_XATTR_REPLACE, th);
3064         RETURN(rc);
3065 }
3066
3067 /**
3068  * Declare component deletion. The xattr name is XATTR_LUSTRE_LOV.del,
3069  * and the xattr value is a unique component ID or a special lcme_id.
3070  *
3071  * \param[in] env       execution environment
3072  * \param[in] dt        dt_object to be operated on
3073  * \param[in] buf       buffer contains component ID or lcme_id
3074  * \parem[in] th        thandle
3075  *
3076  * \retval      0 on success
3077  * \retval      negative errno on failure
3078  */
3079 static int lod_declare_layout_del(const struct lu_env *env,
3080                                   struct dt_object *dt,
3081                                   const struct lu_buf *buf,
3082                                   struct thandle *th)
3083 {
3084         struct lod_thread_info  *info = lod_env_info(env);
3085         struct dt_object *next = dt_object_child(dt);
3086         struct lod_device *d = lu2lod_dev(dt->do_lu.lo_dev);
3087         struct lod_object *lo = lod_dt_obj(dt);
3088         struct lu_attr *attr = &lod_env_info(env)->lti_attr;
3089         struct lov_comp_md_v1 *comp_v1 = buf->lb_buf;
3090         __u32 magic, id, flags, neg_flags = 0;
3091         int rc, i, j, left;
3092         ENTRY;
3093
3094         LASSERT(lo->ldo_is_composite);
3095
3096         if (lo->ldo_flr_state != LCM_FL_NONE)
3097                 RETURN(-EBUSY);
3098
3099         magic = comp_v1->lcm_magic;
3100         if (magic == __swab32(LOV_USER_MAGIC_COMP_V1)) {
3101                 lustre_swab_lov_comp_md_v1(comp_v1);
3102                 magic = comp_v1->lcm_magic;
3103         }
3104
3105         if (magic != LOV_USER_MAGIC_COMP_V1)
3106                 RETURN(-EINVAL);
3107
3108         id = comp_v1->lcm_entries[0].lcme_id;
3109         flags = comp_v1->lcm_entries[0].lcme_flags;
3110
3111         if (id > LCME_ID_MAX || (flags & ~LCME_KNOWN_FLAGS)) {
3112                 CDEBUG(D_LAYOUT, "%s: invalid component id %#x, flags %#x\n",
3113                        lod2obd(d)->obd_name, id, flags);
3114                 RETURN(-EINVAL);
3115         }
3116
3117         if (id != LCME_ID_INVAL && flags != 0) {
3118                 CDEBUG(D_LAYOUT, "%s: specified both id and flags.\n",
3119                        lod2obd(d)->obd_name);
3120                 RETURN(-EINVAL);
3121         }
3122
3123         if (id == LCME_ID_INVAL && !flags) {
3124                 CDEBUG(D_LAYOUT, "%s: no id or flags specified.\n",
3125                        lod2obd(d)->obd_name);
3126                 RETURN(-EINVAL);
3127         }
3128
3129         if (flags & LCME_FL_NEG) {
3130                 neg_flags = flags & ~LCME_FL_NEG;
3131                 flags = 0;
3132         }
3133
3134         mutex_lock(&lo->ldo_layout_mutex);
3135
3136         left = lo->ldo_comp_cnt;
3137         if (left <= 0) {
3138                 mutex_unlock(&lo->ldo_layout_mutex);
3139                 RETURN(-EINVAL);
3140         }
3141
3142         for (i = (lo->ldo_comp_cnt - 1); i >= 0; i--) {
3143                 struct lod_layout_component *lod_comp;
3144
3145                 lod_comp = &lo->ldo_comp_entries[i];
3146
3147                 if (id != LCME_ID_INVAL && id != lod_comp->llc_id)
3148                         continue;
3149                 else if (flags && !(flags & lod_comp->llc_flags))
3150                         continue;
3151                 else if (neg_flags && (neg_flags & lod_comp->llc_flags))
3152                         continue;
3153
3154                 if (left != (i + 1)) {
3155                         CDEBUG(D_LAYOUT, "%s: this deletion will create "
3156                                "a hole.\n", lod2obd(d)->obd_name);
3157                         mutex_unlock(&lo->ldo_layout_mutex);
3158                         RETURN(-EINVAL);
3159                 }
3160                 left--;
3161
3162                 /* Mark the component as deleted */
3163                 lod_comp->llc_id = LCME_ID_INVAL;
3164
3165                 /* Not instantiated component */
3166                 if (lod_comp->llc_stripe == NULL)
3167                         continue;
3168
3169                 LASSERT(lod_comp->llc_stripe_count > 0);
3170                 for (j = 0; j < lod_comp->llc_stripe_count; j++) {
3171                         struct dt_object *obj = lod_comp->llc_stripe[j];
3172
3173                         if (obj == NULL)
3174                                 continue;
3175                         rc = lod_sub_declare_destroy(env, obj, th);
3176                         if (rc) {
3177                                 mutex_unlock(&lo->ldo_layout_mutex);
3178                                 RETURN(rc);
3179                         }
3180                 }
3181         }
3182
3183         LASSERTF(left >= 0, "left = %d\n", left);
3184         if (left == lo->ldo_comp_cnt) {
3185                 CDEBUG(D_LAYOUT, "%s: requested component id:%#x not found\n",
3186                        lod2obd(d)->obd_name, id);
3187                 mutex_unlock(&lo->ldo_layout_mutex);
3188                 RETURN(-EINVAL);
3189         }
3190
3191         mutex_unlock(&lo->ldo_layout_mutex);
3192
3193         memset(attr, 0, sizeof(*attr));
3194         attr->la_valid = LA_SIZE;
3195         rc = lod_sub_declare_attr_set(env, next, attr, th);
3196         if (rc)
3197                 RETURN(rc);
3198
3199         if (left > 0) {
3200                 info->lti_buf.lb_len = lod_comp_md_size(lo, false);
3201                 rc = lod_sub_declare_xattr_set(env, next, &info->lti_buf,
3202                                                XATTR_NAME_LOV, 0, th);
3203         } else {
3204                 rc = lod_sub_declare_xattr_del(env, next, XATTR_NAME_LOV, th);
3205         }
3206
3207         RETURN(rc);
3208 }
3209
3210 /**
3211  * Declare layout add/set/del operations issued by special xattr names:
3212  *
3213  * XATTR_LUSTRE_LOV.add         add component(s) to existing file
3214  * XATTR_LUSTRE_LOV.del         delete component(s) from existing file
3215  * XATTR_LUSTRE_LOV.set.$field  set specified field of certain component(s)
3216  *
3217  * \param[in] env       execution environment
3218  * \param[in] dt        object
3219  * \param[in] name      name of xattr
3220  * \param[in] buf       lu_buf contains xattr value
3221  * \param[in] th        transaction handle
3222  *
3223  * \retval              0 on success
3224  * \retval              negative if failed
3225  */
3226 static int lod_declare_modify_layout(const struct lu_env *env,
3227                                      struct dt_object *dt,
3228                                      const char *name,
3229                                      const struct lu_buf *buf,
3230                                      struct thandle *th)
3231 {
3232         struct lod_device *d = lu2lod_dev(dt->do_lu.lo_dev);
3233         struct lod_object *lo = lod_dt_obj(dt);
3234         char *op;
3235         int rc, len = strlen(XATTR_LUSTRE_LOV);
3236         ENTRY;
3237
3238         LASSERT(dt_object_exists(dt));
3239
3240         if (strlen(name) <= len || name[len] != '.') {
3241                 CDEBUG(D_LAYOUT, "%s: invalid xattr name: %s\n",
3242                        lod2obd(d)->obd_name, name);
3243                 RETURN(-EINVAL);
3244         }
3245         len++;
3246
3247         rc = lod_striping_load(env, lo);
3248         if (rc)
3249                 GOTO(unlock, rc);
3250
3251         /* the layout to be modified must be a composite layout */
3252         if (!lo->ldo_is_composite) {
3253                 CDEBUG(D_LAYOUT, "%s: object "DFID" isn't a composite file.\n",
3254                        lod2obd(d)->obd_name, PFID(lu_object_fid(&dt->do_lu)));
3255                 GOTO(unlock, rc = -EINVAL);
3256         }
3257
3258         op = (char *)name + len;
3259         if (strcmp(op, "add") == 0) {
3260                 rc = lod_declare_layout_add(env, dt, buf, th);
3261         } else if (strcmp(op, "del") == 0) {
3262                 rc = lod_declare_layout_del(env, dt, buf, th);
3263         } else if (strncmp(op, "set", strlen("set")) == 0) {
3264                 rc = lod_declare_layout_set(env, dt, op, buf, th);
3265         } else  {
3266                 CDEBUG(D_LAYOUT, "%s: unsupported xattr name:%s\n",
3267                        lod2obd(d)->obd_name, name);
3268                 GOTO(unlock, rc = -ENOTSUPP);
3269         }
3270 unlock:
3271         if (rc)
3272                 lod_striping_free(env, lo);
3273
3274         RETURN(rc);
3275 }
3276
3277 /**
3278  * Convert a plain file lov_mds_md to a composite layout.
3279  *
3280  * \param[in,out] info  the thread info::lti_ea_store buffer contains little
3281  *                      endian plain file layout
3282  *
3283  * \retval              0 on success, <0 on failure
3284  */
3285 static int lod_layout_convert(struct lod_thread_info *info)
3286 {
3287         struct lov_mds_md *lmm = info->lti_ea_store;
3288         struct lov_mds_md *lmm_save;
3289         struct lov_comp_md_v1 *lcm;
3290         struct lov_comp_md_entry_v1 *lcme;
3291         size_t size;
3292         __u32 blob_size;
3293         int rc = 0;
3294         ENTRY;
3295
3296         /* realloc buffer to a composite layout which contains one component */
3297         blob_size = lov_mds_md_size(le16_to_cpu(lmm->lmm_stripe_count),
3298                                     le32_to_cpu(lmm->lmm_magic));
3299         size = sizeof(*lcm) + sizeof(*lcme) + blob_size;
3300
3301         OBD_ALLOC_LARGE(lmm_save, blob_size);
3302         if (!lmm_save)
3303                 GOTO(out, rc = -ENOMEM);
3304
3305         memcpy(lmm_save, lmm, blob_size);
3306
3307         if (info->lti_ea_store_size < size) {
3308                 rc = lod_ea_store_resize(info, size);
3309                 if (rc)
3310                         GOTO(out, rc);
3311         }
3312
3313         lcm = info->lti_ea_store;
3314         memset(lcm, 0, sizeof(*lcm) + sizeof(*lcme));
3315         lcm->lcm_magic = cpu_to_le32(LOV_MAGIC_COMP_V1);
3316         lcm->lcm_size = cpu_to_le32(size);
3317         lcm->lcm_layout_gen = cpu_to_le32(le16_to_cpu(
3318                                                 lmm_save->lmm_layout_gen));
3319         lcm->lcm_flags = cpu_to_le16(LCM_FL_NONE);
3320         lcm->lcm_entry_count = cpu_to_le16(1);
3321
3322         lcme = &lcm->lcm_entries[0];
3323         lcme->lcme_flags = cpu_to_le32(LCME_FL_INIT);
3324         lcme->lcme_extent.e_start = 0;
3325         lcme->lcme_extent.e_end = cpu_to_le64(OBD_OBJECT_EOF);
3326         lcme->lcme_offset = cpu_to_le32(sizeof(*lcm) + sizeof(*lcme));
3327         lcme->lcme_size = cpu_to_le32(blob_size);
3328
3329         memcpy((char *)lcm + lcme->lcme_offset, (char *)lmm_save, blob_size);
3330
3331         EXIT;
3332 out:
3333         if (lmm_save)
3334                 OBD_FREE_LARGE(lmm_save, blob_size);
3335         return rc;
3336 }
3337
3338 /**
3339  * Merge layouts to form a mirrored file.
3340  */
3341 static int lod_declare_layout_merge(const struct lu_env *env,
3342                                     struct dt_object *dt,
3343                                     const struct lu_buf *mbuf,
3344                                     struct thandle *th)
3345 {
3346         struct lod_thread_info *info = lod_env_info(env);
3347         struct lu_attr *layout_attr = &info->lti_layout_attr;
3348         struct lu_buf *buf = &info->lti_buf;
3349         struct lod_object *lo = lod_dt_obj(dt);
3350         struct lov_comp_md_v1 *lcm;
3351         struct lov_comp_md_v1 *cur_lcm;
3352         struct lov_comp_md_v1 *merge_lcm;
3353         struct lov_comp_md_entry_v1 *lcme;
3354         struct lov_mds_md_v1 *lmm;
3355         size_t size = 0;
3356         size_t offset;
3357         __u16 cur_entry_count;
3358         __u16 merge_entry_count;
3359         __u32 id = 0;
3360         __u16 mirror_id = 0;
3361         __u32 mirror_count;
3362         int rc, i;
3363         bool merge_has_dom;
3364
3365         ENTRY;
3366
3367         merge_lcm = mbuf->lb_buf;
3368         if (mbuf->lb_len < sizeof(*merge_lcm))
3369                 RETURN(-EINVAL);
3370
3371         /* must be an existing layout from disk */
3372         if (le32_to_cpu(merge_lcm->lcm_magic) != LOV_MAGIC_COMP_V1)
3373                 RETURN(-EINVAL);
3374
3375         merge_entry_count = le16_to_cpu(merge_lcm->lcm_entry_count);
3376
3377         /* do not allow to merge two mirrored files */
3378         if (le16_to_cpu(merge_lcm->lcm_mirror_count))
3379                 RETURN(-EBUSY);
3380
3381         /* verify the target buffer */
3382         rc = lod_get_lov_ea(env, lo);
3383         if (rc <= 0)
3384                 RETURN(rc ? : -ENODATA);
3385
3386         cur_lcm = info->lti_ea_store;
3387         switch (le32_to_cpu(cur_lcm->lcm_magic)) {
3388         case LOV_MAGIC_V1:
3389         case LOV_MAGIC_V3:
3390                 rc = lod_layout_convert(info);
3391                 break;
3392         case LOV_MAGIC_COMP_V1:
3393         case LOV_MAGIC_SEL:
3394                 rc = 0;
3395                 break;
3396         default:
3397                 rc = -EINVAL;
3398         }
3399         if (rc)
3400                 RETURN(rc);
3401
3402         /* info->lti_ea_store could be reallocated in lod_layout_convert() */
3403         cur_lcm = info->lti_ea_store;
3404         cur_entry_count = le16_to_cpu(cur_lcm->lcm_entry_count);
3405
3406         /* 'lcm_mirror_count + 1' is the current # of mirrors the file has */
3407         mirror_count = le16_to_cpu(cur_lcm->lcm_mirror_count) + 1;
3408         if (mirror_count + 1 > LUSTRE_MIRROR_COUNT_MAX)
3409                 RETURN(-ERANGE);
3410
3411         /* size of new layout */
3412         size = le32_to_cpu(cur_lcm->lcm_size) +
3413                le32_to_cpu(merge_lcm->lcm_size) - sizeof(*cur_lcm);
3414
3415         memset(buf, 0, sizeof(*buf));
3416         lu_buf_alloc(buf, size);
3417         if (buf->lb_buf == NULL)
3418                 RETURN(-ENOMEM);
3419
3420         lcm = buf->lb_buf;
3421         memcpy(lcm, cur_lcm, sizeof(*lcm) + cur_entry_count * sizeof(*lcme));
3422
3423         offset = sizeof(*lcm) +
3424                  sizeof(*lcme) * (cur_entry_count + merge_entry_count);
3425         for (i = 0; i < cur_entry_count; i++) {
3426                 struct lov_comp_md_entry_v1 *cur_lcme;
3427
3428                 lcme = &lcm->lcm_entries[i];
3429                 cur_lcme = &cur_lcm->lcm_entries[i];
3430
3431                 lcme->lcme_offset = cpu_to_le32(offset);
3432                 memcpy((char *)lcm + offset,
3433                        (char *)cur_lcm + le32_to_cpu(cur_lcme->lcme_offset),
3434                        le32_to_cpu(lcme->lcme_size));
3435
3436                 offset += le32_to_cpu(lcme->lcme_size);
3437
3438                 if (mirror_count == 1 &&
3439                     mirror_id_of(le32_to_cpu(lcme->lcme_id)) == 0) {
3440                         /* Add mirror from a non-flr file, create new mirror ID.
3441                          * Otherwise, keep existing mirror's component ID, used
3442                          * for mirror extension.
3443                          */
3444                         id = pflr_id(1, i + 1);
3445                         lcme->lcme_id = cpu_to_le32(id);
3446                 }
3447
3448                 id = max(le32_to_cpu(lcme->lcme_id), id);
3449         }
3450
3451         mirror_id = mirror_id_of(id) + 1;
3452
3453         /* check if first entry in new layout is DOM */
3454         lmm = (struct lov_mds_md_v1 *)((char *)merge_lcm +
3455                                         merge_lcm->lcm_entries[0].lcme_offset);
3456         merge_has_dom = lov_pattern(le32_to_cpu(lmm->lmm_pattern)) &
3457                         LOV_PATTERN_MDT;
3458
3459         for (i = 0; i < merge_entry_count; i++) {
3460                 struct lov_comp_md_entry_v1 *merge_lcme;
3461
3462                 merge_lcme = &merge_lcm->lcm_entries[i];
3463                 lcme = &lcm->lcm_entries[cur_entry_count + i];
3464
3465                 *lcme = *merge_lcme;
3466                 lcme->lcme_offset = cpu_to_le32(offset);
3467                 if (merge_has_dom && i == 0)
3468                         lcme->lcme_flags |= cpu_to_le32(LCME_FL_STALE);
3469
3470                 id = pflr_id(mirror_id, i + 1);
3471                 lcme->lcme_id = cpu_to_le32(id);
3472
3473                 memcpy((char *)lcm + offset,
3474                        (char *)merge_lcm + le32_to_cpu(merge_lcme->lcme_offset),
3475                        le32_to_cpu(lcme->lcme_size));
3476
3477                 offset += le32_to_cpu(lcme->lcme_size);
3478         }
3479
3480         /* fixup layout information */
3481         lcm->lcm_size = cpu_to_le32(size);
3482         lcm->lcm_entry_count = cpu_to_le16(cur_entry_count + merge_entry_count);
3483         lcm->lcm_mirror_count = cpu_to_le16(mirror_count);
3484         if ((le16_to_cpu(lcm->lcm_flags) & LCM_FL_FLR_MASK) == LCM_FL_NONE)
3485                 lcm->lcm_flags = cpu_to_le32(LCM_FL_RDONLY);
3486
3487         rc = lod_striping_reload(env, lo, buf, 0);
3488         if (rc)
3489                 GOTO(out, rc);
3490
3491         lod_obj_inc_layout_gen(lo);
3492         lcm->lcm_layout_gen = cpu_to_le32(lo->ldo_layout_gen);
3493
3494         /* transfer layout version to OST objects. */
3495         if (lo->ldo_mirror_count > 1) {
3496                 struct lod_obj_stripe_cb_data data = { {0} };
3497
3498                 layout_attr->la_valid = LA_LAYOUT_VERSION;
3499                 layout_attr->la_layout_version = 0;
3500                 data.locd_attr = layout_attr;
3501                 data.locd_declare = true;
3502                 data.locd_stripe_cb = lod_obj_stripe_attr_set_cb;
3503                 rc = lod_obj_for_each_stripe(env, lo, th, &data);
3504                 if (rc)
3505                         GOTO(out, rc);
3506         }
3507
3508         rc = lod_sub_declare_xattr_set(env, dt_object_child(dt), buf,
3509                                        XATTR_NAME_LOV, LU_XATTR_REPLACE, th);
3510
3511 out:
3512         lu_buf_free(buf);
3513         RETURN(rc);
3514 }
3515
3516 /**
3517  * Split layouts, just set the LOVEA with the layout from mbuf.
3518  */
3519 static int lod_declare_layout_split(const struct lu_env *env,
3520                 struct dt_object *dt, const struct lu_buf *mbuf,
3521                 struct thandle *th)
3522 {
3523         struct lod_thread_info *info = lod_env_info(env);
3524         struct lu_attr *layout_attr = &info->lti_layout_attr;
3525         struct lod_object *lo = lod_dt_obj(dt);
3526         struct lov_comp_md_v1 *lcm = mbuf->lb_buf;
3527         int rc;
3528         ENTRY;
3529
3530         rc = lod_striping_reload(env, lo, mbuf, LVF_ALL_STALE);
3531         if (rc)
3532                 RETURN(rc);
3533
3534         lod_obj_inc_layout_gen(lo);
3535         /* fix on-disk layout gen */
3536         lcm->lcm_layout_gen = cpu_to_le32(lo->ldo_layout_gen);
3537
3538         /* transfer layout version to OST objects. */
3539         if (lo->ldo_mirror_count > 1) {
3540                 struct lod_obj_stripe_cb_data data = { {0} };
3541
3542                 layout_attr->la_valid = LA_LAYOUT_VERSION;
3543                 layout_attr->la_layout_version = 0;
3544                 data.locd_attr = layout_attr;
3545                 data.locd_declare = true;
3546                 data.locd_stripe_cb = lod_obj_stripe_attr_set_cb;
3547                 rc = lod_obj_for_each_stripe(env, lo, th, &data);
3548                 if (rc)
3549                         RETURN(rc);
3550         }
3551
3552         rc = lod_sub_declare_xattr_set(env, dt_object_child(dt), mbuf,
3553                                        XATTR_NAME_LOV, LU_XATTR_REPLACE, th);
3554         RETURN(rc);
3555 }
3556
3557 static int lod_layout_declare_or_purge_mirror(const struct lu_env *env,
3558                         struct dt_object *dt, const struct lu_buf *buf,
3559                         struct thandle *th, bool declare)
3560 {
3561         struct lod_thread_info *info = lod_env_info(env);
3562         struct lod_device *d = lu2lod_dev(dt->do_lu.lo_dev);
3563         struct lod_object *lo = lod_dt_obj(dt);
3564         struct lov_comp_md_v1 *comp_v1 = buf->lb_buf;
3565         struct lov_comp_md_entry_v1 *entry;
3566         struct lov_mds_md_v1 *lmm;
3567         struct dt_object **sub_objs = NULL;
3568         int rc = 0, i, k, array_count = 0;
3569
3570         ENTRY;
3571
3572         /**
3573          * other ops (like lod_declare_destroy) could destroying sub objects
3574          * as well.
3575          */
3576         mutex_lock(&lo->ldo_layout_mutex);
3577
3578         if (!declare) {
3579                 /* prepare sub-objects array */
3580                 for (i = 0; i < comp_v1->lcm_entry_count; i++) {
3581                         entry = &comp_v1->lcm_entries[i];
3582
3583                         if (!(entry->lcme_flags & LCME_FL_INIT))
3584                                 continue;
3585
3586                         lmm = (struct lov_mds_md_v1 *)
3587                                         ((char *)comp_v1 + entry->lcme_offset);
3588                         array_count += lmm->lmm_stripe_count;
3589                 }
3590                 OBD_ALLOC_PTR_ARRAY(sub_objs, array_count);
3591                 if (sub_objs == NULL) {
3592                         mutex_unlock(&lo->ldo_layout_mutex);
3593                         RETURN(-ENOMEM);
3594                 }
3595         }
3596
3597         k = 0;  /* sub_objs index */
3598         for (i = 0; i < comp_v1->lcm_entry_count; i++) {
3599                 struct lov_ost_data_v1 *objs;
3600                 struct lu_object *o, *n;
3601                 struct dt_object *dto;
3602                 struct lu_device *nd;
3603                 struct lov_mds_md_v3 *v3;
3604                 __u32 idx;
3605                 int j;
3606
3607                 entry = &comp_v1->lcm_entries[i];
3608
3609                 if (!(entry->lcme_flags & LCME_FL_INIT))
3610                         continue;
3611
3612                 lmm = (struct lov_mds_md_v1 *)
3613                                 ((char *)comp_v1 + entry->lcme_offset);
3614                 v3 = (struct lov_mds_md_v3 *)lmm;
3615                 if (lmm->lmm_magic == LOV_MAGIC_V3)
3616                         objs = &v3->lmm_objects[0];
3617                 else
3618                         objs = &lmm->lmm_objects[0];
3619
3620                 for (j = 0; j < lmm->lmm_stripe_count; j++) {
3621                         idx = objs[j].l_ost_idx;
3622                         rc = ostid_to_fid(&info->lti_fid, &objs[j].l_ost_oi,
3623                                           idx);
3624                         if (rc)
3625                                 GOTO(out, rc);
3626
3627                         if (!fid_is_sane(&info->lti_fid)) {
3628                                 CERROR("%s: sub-object insane fid "DFID"\n",
3629                                        lod2obd(d)->obd_name,
3630                                        PFID(&info->lti_fid));
3631                                 GOTO(out, rc = -EINVAL);
3632                         }
3633
3634                         lod_getref(&d->lod_ost_descs);
3635
3636                         rc = validate_lod_and_idx(d, idx);
3637                         if (unlikely(rc)) {
3638                                 lod_putref(d, &d->lod_ost_descs);
3639                                 GOTO(out, rc);
3640                         }
3641
3642                         nd = &OST_TGT(d, idx)->ltd_tgt->dd_lu_dev;
3643                         lod_putref(d, &d->lod_ost_descs);
3644
3645                         o = lu_object_find_at(env, nd, &info->lti_fid, NULL);
3646                         if (IS_ERR(o))
3647                                 GOTO(out, rc = PTR_ERR(o));
3648
3649                         n = lu_object_locate(o->lo_header, nd->ld_type);
3650                         if (unlikely(!n)) {
3651                                 lu_object_put(env, n);
3652                                 GOTO(out, rc = -ENOENT);
3653                         }
3654
3655                         dto = container_of(n, struct dt_object, do_lu);
3656
3657                         if (declare) {
3658                                 rc = lod_sub_declare_destroy(env, dto, th);
3659                                 dt_object_put(env, dto);
3660                                 if (rc)
3661                                         GOTO(out, rc);
3662                         } else {
3663                                 /**
3664                                  * collect to-be-destroyed sub objects, the
3665                                  * reference would be released after actual
3666                                  * deletion.
3667                                  */
3668                                 sub_objs[k] = dto;
3669                                 k++;
3670                         }
3671                 } /* for each stripe */
3672         } /* for each component in the mirror */
3673 out:
3674         if (!declare) {
3675                 i = 0;
3676                 if (!rc) {
3677                         /* destroy the sub objects */
3678                         for (; i < k; i++) {
3679                                 rc = lod_sub_destroy(env, sub_objs[i], th);
3680                                 if (rc)
3681                                         break;
3682                                 dt_object_put(env, sub_objs[i]);
3683                         }
3684                 }
3685                 /**
3686                  * if a sub object destroy failed, we'd release sub objects
3687                  * reference get from above sub_objs collection.
3688                  */
3689                 for (; i < k; i++)
3690                         dt_object_put(env, sub_objs[i]);
3691
3692                 OBD_FREE_PTR_ARRAY(sub_objs, array_count);
3693         }
3694         mutex_unlock(&lo->ldo_layout_mutex);
3695
3696         RETURN(rc);
3697 }
3698
3699 /**
3700  * Purge layouts, delete sub objects in the mirror stored in the vic_buf,
3701  * and set the LOVEA with the layout from mbuf.
3702  */
3703 static int lod_declare_layout_purge(const struct lu_env *env,
3704                 struct dt_object *dt, const struct lu_buf *buf,
3705                 struct thandle *th)
3706 {
3707         struct lod_device *d = lu2lod_dev(dt->do_lu.lo_dev);
3708         struct lov_comp_md_v1 *comp_v1 = buf->lb_buf;
3709         int rc;
3710
3711         ENTRY;
3712
3713         if (le32_to_cpu(comp_v1->lcm_magic) != LOV_MAGIC_COMP_V1) {
3714                 CERROR("%s: invalid layout magic %#x != %#x\n",
3715                        lod2obd(d)->obd_name, le32_to_cpu(comp_v1->lcm_magic),
3716                        LOV_MAGIC_COMP_V1);
3717                 RETURN(-EINVAL);
3718         }
3719
3720         if (cpu_to_le32(LOV_MAGIC_COMP_V1) != LOV_MAGIC_COMP_V1)
3721                 lustre_swab_lov_comp_md_v1(comp_v1);
3722
3723         /* from now on, @buf contains cpu endian data */
3724
3725         if (comp_v1->lcm_mirror_count != 0) {
3726                 CERROR("%s: can only purge one mirror from "DFID"\n",
3727                        lod2obd(d)->obd_name, PFID(lu_object_fid(&dt->do_lu)));
3728                 RETURN(-EINVAL);
3729         }
3730
3731         /* delcare sub objects deletion in the mirror stored in @buf */
3732         rc = lod_layout_declare_or_purge_mirror(env, dt, buf, th, true);
3733         RETURN(rc);
3734 }
3735
3736 /* delete sub objects from the mirror stored in @buf */
3737 static int lod_layout_purge(const struct lu_env *env, struct dt_object *dt,
3738                             const struct lu_buf *buf, struct thandle *th)
3739 {
3740         int rc;
3741
3742         ENTRY;
3743         rc = lod_layout_declare_or_purge_mirror(env, dt, buf, th, false);
3744         RETURN(rc);
3745 }
3746
3747 /**
3748  * Implementation of dt_object_operations::do_declare_xattr_set.
3749  *
3750  * \see dt_object_operations::do_declare_xattr_set() in the API description
3751  * for details.
3752  *
3753  * the extension to the API:
3754  *   - declaring LOVEA requests striping creation
3755  *   - LU_XATTR_REPLACE means layout swap
3756  */
3757 static int lod_declare_xattr_set(const struct lu_env *env,
3758                                  struct dt_object *dt,
3759                                  const struct lu_buf *buf,
3760                                  const char *name, int fl,
3761                                  struct thandle *th)
3762 {
3763         struct dt_object *next = dt_object_child(dt);
3764         struct lu_attr   *attr = &lod_env_info(env)->lti_attr;
3765         __u32             mode;
3766         int               rc;
3767         ENTRY;
3768
3769         mode = dt->do_lu.lo_header->loh_attr & S_IFMT;
3770         if ((S_ISREG(mode) || mode == 0) &&
3771             !(fl & (LU_XATTR_REPLACE | LU_XATTR_MERGE | LU_XATTR_SPLIT |
3772                     LU_XATTR_PURGE)) &&
3773             (strcmp(name, XATTR_NAME_LOV) == 0 ||
3774              strcmp(name, XATTR_LUSTRE_LOV) == 0)) {
3775                 /*
3776                  * this is a request to create object's striping.
3777                  *
3778                  * allow to declare predefined striping on a new (!mode) object
3779                  * which is supposed to be replay of regular file creation
3780                  * (when LOV setting is declared)
3781                  *
3782                  * LU_XATTR_REPLACE is set to indicate a layout swap
3783                  */
3784                 if (dt_object_exists(dt)) {
3785                         rc = dt_attr_get(env, next, attr);
3786                         if (rc)
3787                                 RETURN(rc);
3788                 } else {
3789                         memset(attr, 0, sizeof(*attr));
3790                         attr->la_valid = LA_TYPE | LA_MODE;
3791                         attr->la_mode = S_IFREG;
3792                 }
3793                 rc = lod_declare_striped_create(env, dt, attr, buf, th);
3794         } else if (fl & LU_XATTR_MERGE) {
3795                 LASSERT(strcmp(name, XATTR_NAME_LOV) == 0 ||
3796                         strcmp(name, XATTR_LUSTRE_LOV) == 0);
3797                 rc = lod_declare_layout_merge(env, dt, buf, th);
3798         } else if (fl & LU_XATTR_SPLIT) {
3799                 LASSERT(strcmp(name, XATTR_NAME_LOV) == 0 ||
3800                         strcmp(name, XATTR_LUSTRE_LOV) == 0);
3801                 rc = lod_declare_layout_split(env, dt, buf, th);
3802         } else if (fl & LU_XATTR_PURGE) {
3803                 LASSERT(strcmp(name, XATTR_NAME_LOV) == 0 ||
3804                         strcmp(name, XATTR_LUSTRE_LOV) == 0);
3805                 rc = lod_declare_layout_purge(env, dt, buf, th);
3806         } else if (S_ISREG(mode) &&
3807                    strlen(name) >= sizeof(XATTR_LUSTRE_LOV) + 3 &&
3808                    allowed_lustre_lov(name)) {
3809                 /*
3810                  * this is a request to modify object's striping.
3811                  * add/set/del component(s).
3812                  */
3813                 if (!dt_object_exists(dt))
3814                         RETURN(-ENOENT);
3815
3816                 rc = lod_declare_modify_layout(env, dt, name, buf, th);
3817         } else if (S_ISDIR(mode)) {
3818                 rc = lod_dir_declare_xattr_set(env, dt, buf, name, fl, th);
3819         } else if (strcmp(name, XATTR_NAME_FID) == 0) {
3820                 rc = lod_replace_parent_fid(env, dt, buf, th, true);
3821         } else {
3822                 rc = lod_sub_declare_xattr_set(env, next, buf, name, fl, th);
3823         }
3824
3825         RETURN(rc);
3826 }
3827
3828 /**
3829  * Apply xattr changes to the object.
3830  *
3831  * Applies xattr changes to the object and the stripes if the latter exist.
3832  *
3833  * \param[in] env       execution environment
3834  * \param[in] dt        object
3835  * \param[in] buf       buffer pointing to the new value of xattr
3836  * \param[in] name      name of xattr
3837  * \param[in] fl        flags
3838  * \param[in] th        transaction handle
3839  *
3840  * \retval              0 on success
3841  * \retval              negative if failed
3842  */
3843 static int lod_xattr_set_internal(const struct lu_env *env,
3844                                   struct dt_object *dt,
3845                                   const struct lu_buf *buf,
3846                                   const char *name, int fl,
3847                                   struct thandle *th)
3848 {
3849         struct dt_object        *next = dt_object_child(dt);
3850         struct lod_object       *lo = lod_dt_obj(dt);
3851         int                     rc;
3852         int                     i;
3853         ENTRY;
3854
3855         rc = lod_sub_xattr_set(env, next, buf, name, fl, th);
3856         if (rc != 0 || !S_ISDIR(dt->do_lu.lo_header->loh_attr))
3857                 RETURN(rc);
3858
3859         /* Note: Do not set LinkEA on sub-stripes, otherwise
3860          * it will confuse the fid2path process(see mdt_path_current()).
3861          * The linkEA between master and sub-stripes is set in
3862          * lod_xattr_set_lmv(). */
3863         if (lo->ldo_dir_stripe_count == 0 || strcmp(name, XATTR_NAME_LINK) == 0)
3864                 RETURN(0);
3865
3866         for (i = 0; i < lo->ldo_dir_stripe_count; i++) {
3867                 if (!lo->ldo_stripe[i])
3868                         continue;
3869
3870                 if (!dt_object_exists(lo->ldo_stripe[i]))
3871                         continue;
3872
3873                 rc = lod_sub_xattr_set(env, lo->ldo_stripe[i], buf, name,
3874                                        fl, th);
3875                 if (rc != 0)
3876                         break;
3877         }
3878
3879         RETURN(rc);
3880 }
3881
3882 /**
3883  * Delete an extended attribute.
3884  *
3885  * Deletes specified xattr from the object and the stripes if the latter exist.
3886  *
3887  * \param[in] env       execution environment
3888  * \param[in] dt        object
3889  * \param[in] name      name of xattr
3890  * \param[in] th        transaction handle
3891  *
3892  * \retval              0 on success
3893  * \retval              negative if failed
3894  */
3895 static int lod_xattr_del_internal(const struct lu_env *env,
3896                                   struct dt_object *dt,
3897                                   const char *name, struct thandle *th)
3898 {
3899         struct dt_object *next = dt_object_child(dt);
3900         struct lod_object *lo = lod_dt_obj(dt);
3901         int i;
3902         int rc;
3903
3904         ENTRY;
3905
3906         rc = lod_sub_xattr_del(env, next, name, th);
3907         if (rc != 0 || !S_ISDIR(dt->do_lu.lo_header->loh_attr))
3908                 RETURN(rc);
3909
3910         if (lo->ldo_dir_stripe_count == 0)
3911                 RETURN(rc);
3912
3913         for (i = 0; i < lo->ldo_dir_stripe_count; i++) {
3914                 if (!lo->ldo_stripe[i])
3915                         continue;
3916
3917                 if (!dt_object_exists(lo->ldo_stripe[i]))
3918                         continue;
3919
3920                 rc = lod_sub_xattr_del(env, lo->ldo_stripe[i], name, th);
3921                 if (rc != 0)
3922                         break;
3923         }
3924
3925         RETURN(rc);
3926 }
3927
3928 /**
3929  * Set default striping on a directory.
3930  *
3931  * Sets specified striping on a directory object unless it matches the default
3932  * striping (LOVEA_DELETE_VALUES() macro). In the latter case remove existing
3933  * EA. This striping will be used when regular file is being created in this
3934  * directory.
3935  *
3936  * \param[in] env       execution environment
3937  * \param[in] dt        the striped object
3938  * \param[in] buf       buffer with the striping
3939  * \param[in] name      name of EA
3940  * \param[in] fl        xattr flag (see OSD API description)
3941  * \param[in] th        transaction handle
3942  *
3943  * \retval              0 on success
3944  * \retval              negative if failed
3945  */
3946 static int lod_xattr_set_lov_on_dir(const struct lu_env *env,
3947                                     struct dt_object *dt,
3948                                     const struct lu_buf *buf,
3949                                     const char *name, int fl,
3950                                     struct thandle *th)
3951 {
3952         struct lov_user_md_v1   *lum;
3953         struct lov_user_md_v3   *v3 = NULL;
3954         const char              *pool_name = NULL;
3955         int                      rc;
3956         bool                     is_del;
3957         ENTRY;
3958
3959         LASSERT(buf != NULL && buf->lb_buf != NULL);
3960         lum = buf->lb_buf;
3961
3962         switch (lum->lmm_magic) {
3963         case LOV_USER_MAGIC_SPECIFIC:
3964         case LOV_USER_MAGIC_V3:
3965                 v3 = buf->lb_buf;
3966                 if (lov_pool_is_reserved(v3->lmm_pool_name))
3967                         memset(v3->lmm_pool_name, 0, sizeof(v3->lmm_pool_name));
3968                 else if (v3->lmm_pool_name[0] != '\0')
3969                         pool_name = v3->lmm_pool_name;
3970                 fallthrough;
3971         case LOV_USER_MAGIC_V1:
3972                 /* if { size, offset, count } = { 0, -1, 0 } and no pool
3973                  * (i.e. all default values specified) then delete default
3974                  * striping from dir. */
3975                 CDEBUG(D_LAYOUT,
3976                        "set default striping: sz %u # %u offset %d %s %s\n",
3977                        (unsigned)lum->lmm_stripe_size,
3978                        (unsigned)lum->lmm_stripe_count,
3979                        (int)lum->lmm_stripe_offset,
3980                        v3 ? "from" : "", v3 ? v3->lmm_pool_name : "");
3981
3982                 is_del = LOVEA_DELETE_VALUES(lum->lmm_stripe_size,
3983                                              lum->lmm_stripe_count,
3984                                              lum->lmm_stripe_offset,
3985                                              pool_name);
3986                 break;
3987         case LOV_USER_MAGIC_COMP_V1:
3988         {
3989                 struct lov_comp_md_v1 *lcm = (struct lov_comp_md_v1 *)lum;
3990                 struct lov_comp_md_entry_v1 *lcme;
3991                 int i, comp_cnt;
3992
3993                 comp_cnt = le16_to_cpu(lcm->lcm_entry_count);
3994                 for (i = 0; i < comp_cnt; i++) {
3995                         lcme = &lcm->lcm_entries[i];
3996                         if (lcme->lcme_flags & cpu_to_le32(LCME_FL_EXTENSION)) {
3997                                 lcm->lcm_magic = cpu_to_le32(LOV_MAGIC_SEL);
3998                                 break;
3999                         }
4000                 }
4001
4002                 is_del = false;
4003                 break;
4004         }
4005         default:
4006                 CERROR("Invalid magic %x\n", lum->lmm_magic);
4007                 RETURN(-EINVAL);
4008         }
4009
4010         if (is_del) {
4011                 rc = lod_xattr_del_internal(env, dt, name, th);
4012                 if (rc == -ENODATA)
4013                         rc = 0;
4014         } else {
4015                 rc = lod_xattr_set_internal(env, dt, buf, name, fl, th);
4016         }
4017
4018         RETURN(rc);
4019 }
4020
4021 static int lod_get_default_lov_striping(const struct lu_env *env,
4022                                        struct lod_object *lo,
4023                                        struct lod_default_striping *lds,
4024                                        struct dt_allocation_hint *ah);
4025
4026 /**
4027  * Helper function to convert compound layout to compound layout with
4028  * pool
4029  *
4030  * Copy lcm_entries array of \a src to \a tgt. Replace lov_user_md_v1
4031  * components of \a src with lov_user_md_v3 using \a pool.
4032  *
4033  * \param[in] src       source layout
4034  * \param[in] pool      pool to use in \a tgt
4035  * \param[out] tgt      target layout
4036  */
4037 static void embed_pool_to_comp_v1(const struct lov_comp_md_v1 *src,
4038                                   const char *pool,
4039                                   struct lov_comp_md_v1 *tgt)
4040 {
4041         size_t shift;
4042         struct lov_user_md_v1 *lum;
4043         struct lov_user_md_v3 *lum3;
4044         struct lov_comp_md_entry_v1 *entry;
4045         int i;
4046         __u32 offset;
4047
4048         entry = tgt->lcm_entries;
4049         shift = 0;
4050         for (i = 0; i < le16_to_cpu(src->lcm_entry_count); i++, entry++) {
4051                 *entry = src->lcm_entries[i];
4052                 offset = le32_to_cpu(src->lcm_entries[i].lcme_offset);
4053                 entry->lcme_offset = cpu_to_le32(offset + shift);
4054
4055                 lum = (struct lov_user_md_v1 *)((char *)src + offset);
4056                 lum3 = (struct lov_user_md_v3 *)((char *)tgt + offset + shift);
4057                 *(struct lov_user_md_v1 *)lum3 = *lum;
4058                 if (lum->lmm_pattern & cpu_to_le32(LOV_PATTERN_MDT)) {
4059                         lum3->lmm_magic = cpu_to_le32(LOV_USER_MAGIC_V1);
4060                 } else {
4061                         lum3->lmm_magic = cpu_to_le32(LOV_USER_MAGIC_V3);
4062                         entry->lcme_size = cpu_to_le32(sizeof(*lum3));
4063                         strlcpy(lum3->lmm_pool_name, pool,
4064                                 sizeof(lum3->lmm_pool_name));
4065                         shift += sizeof(*lum3) - sizeof(*lum);
4066                 }
4067         }
4068 }
4069
4070 /**
4071  * Set default striping on a directory.
4072  *
4073  * Sets specified striping on a directory object unless it matches the default
4074  * striping (LOVEA_DELETE_VALUES() macro). In the latter case remove existing
4075  * EA. This striping will be used when regular file is being created in this
4076  * directory.
4077  * If current default striping includes a pool but specifed striping
4078  * does not - retain the pool if it exists.
4079  *
4080  * \param[in] env       execution environment
4081  * \param[in] dt        the striped object
4082  * \param[in] buf       buffer with the striping
4083  * \param[in] name      name of EA
4084  * \param[in] fl        xattr flag (see OSD API description)
4085  * \param[in] th        transaction handle
4086  *
4087  * \retval              0 on success
4088  * \retval              negative if failed
4089  */
4090 static int lod_xattr_set_default_lov_on_dir(const struct lu_env *env,
4091                                             struct dt_object *dt,
4092                                             const struct lu_buf *buf,
4093                                             const char *name, int fl,
4094                                             struct thandle *th)
4095 {
4096         struct lod_default_striping     *lds = lod_lds_buf_get(env);
4097         struct lov_user_md_v1           *v1 = buf->lb_buf;
4098         char                             pool[LOV_MAXPOOLNAME + 1];
4099         bool                             is_del;
4100         int                              rc;
4101
4102         ENTRY;
4103
4104         /* get existing striping config */
4105         rc = lod_get_default_lov_striping(env, lod_dt_obj(dt), lds, NULL);
4106         if (rc)
4107                 RETURN(rc);
4108
4109         memset(pool, 0, sizeof(pool));
4110         if (lds->lds_def_striping_set == 1)
4111                 lod_layout_get_pool(lds->lds_def_comp_entries,
4112                                     lds->lds_def_comp_cnt, pool,
4113                                     sizeof(pool));
4114
4115         is_del = LOVEA_DELETE_VALUES(v1->lmm_stripe_size,
4116                                      v1->lmm_stripe_count,
4117                                      v1->lmm_stripe_offset,
4118                                      NULL);
4119
4120         /* Retain the pool name if it is not given */
4121         if (v1->lmm_magic == LOV_USER_MAGIC_V1 && pool[0] != '\0' &&
4122             !is_del) {
4123                 struct lod_thread_info *info = lod_env_info(env);
4124                 struct lov_user_md_v3 *v3  = info->lti_ea_store;
4125
4126                 memset(v3, 0, sizeof(*v3));
4127                 v3->lmm_magic = cpu_to_le32(LOV_USER_MAGIC_V3);
4128                 v3->lmm_pattern = cpu_to_le32(v1->lmm_pattern);
4129                 v3->lmm_stripe_count = cpu_to_le32(v1->lmm_stripe_count);
4130                 v3->lmm_stripe_offset = cpu_to_le32(v1->lmm_stripe_offset);
4131                 v3->lmm_stripe_size = cpu_to_le32(v1->lmm_stripe_size);
4132
4133                 strlcpy(v3->lmm_pool_name, pool, sizeof(v3->lmm_pool_name));
4134
4135                 info->lti_buf.lb_buf = v3;
4136                 info->lti_buf.lb_len = sizeof(*v3);
4137                 rc = lod_xattr_set_lov_on_dir(env, dt, &info->lti_buf,
4138                                               name, fl, th);
4139         } else if (v1->lmm_magic == LOV_USER_MAGIC_COMP_V1 &&
4140                    pool[0] != '\0' && !is_del) {
4141                 /*
4142                  * try to retain the pool from default layout if the
4143                  * specified component layout does not provide pool
4144                  * info explicitly
4145                  */
4146                 struct lod_thread_info *info = lod_env_info(env);
4147                 struct lov_comp_md_v1 *comp_v1 = buf->lb_buf;
4148                 struct lov_comp_md_v1 *comp_v1p;
4149                 struct lov_user_md_v1 *lum;
4150                 int entry_count;
4151                 int i;
4152                 __u32 offset;
4153                 struct lov_comp_md_entry_v1 *entry;
4154                 int size;
4155
4156                 entry_count = le16_to_cpu(comp_v1->lcm_entry_count);
4157                 size = sizeof(*comp_v1) +
4158                         entry_count * sizeof(comp_v1->lcm_entries[0]);
4159                 entry = comp_v1->lcm_entries;
4160                 for (i = 0; i < entry_count; i++, entry++) {
4161                         offset = le32_to_cpu(entry->lcme_offset);
4162                         lum = (struct lov_user_md_v1 *)((char *)comp_v1 +
4163                                                         offset);
4164                         if (le32_to_cpu(lum->lmm_magic) != LOV_USER_MAGIC_V1)
4165                                 /* the i-th component includes pool info */
4166                                 break;
4167                         if (lum->lmm_pattern & cpu_to_le32(LOV_PATTERN_MDT))
4168                                 size += sizeof(struct lov_user_md_v1);
4169                         else
4170                                 size += sizeof(struct lov_user_md_v3);
4171                 }
4172
4173                 if (i == entry_count) {
4174                         /*
4175                          * re-compose the layout to include the pool for
4176                          * each component
4177                          */
4178                         if (info->lti_ea_store_size < size)
4179                                 rc = lod_ea_store_resize(info, size);
4180
4181                         if (rc == 0) {
4182                                 comp_v1p = info->lti_ea_store;
4183                                 *comp_v1p = *comp_v1;
4184                                 comp_v1p->lcm_size = cpu_to_le32(size);
4185                                 embed_pool_to_comp_v1(comp_v1, pool, comp_v1p);
4186
4187                                 info->lti_buf.lb_buf = comp_v1p;
4188                                 info->lti_buf.lb_len = size;
4189                                 rc = lod_xattr_set_lov_on_dir(env, dt,
4190                                                               &info->lti_buf,
4191                                                               name, fl, th);
4192                         }
4193                 } else {
4194                         rc = lod_xattr_set_lov_on_dir(env, dt, buf, name, fl,
4195                                                       th);
4196                 }
4197         } else {
4198                 rc = lod_xattr_set_lov_on_dir(env, dt, buf, name, fl, th);
4199         }
4200
4201         if (lds->lds_def_striping_set == 1 && lds->lds_def_comp_entries != NULL)
4202                 lod_free_def_comp_entries(lds);
4203
4204         RETURN(rc);
4205 }
4206
4207 /**
4208  * Set default striping on a directory object.
4209  *
4210  * Sets specified striping on a directory object unless it matches the default
4211  * striping (LOVEA_DELETE_VALUES() macro). In the latter case remove existing
4212  * EA. This striping will be used when a new directory is being created in the
4213  * directory.
4214  *
4215  * \param[in] env       execution environment
4216  * \param[in] dt        the striped object
4217  * \param[in] buf       buffer with the striping
4218  * \param[in] name      name of EA
4219  * \param[in] fl        xattr flag (see OSD API description)
4220  * \param[in] th        transaction handle
4221  *
4222  * \retval              0 on success
4223  * \retval              negative if failed
4224  */
4225 static int lod_xattr_set_default_lmv_on_dir(const struct lu_env *env,
4226                                             struct dt_object *dt,
4227                                             const struct lu_buf *buf,
4228                                             const char *name, int fl,
4229                                             struct thandle *th)
4230 {
4231         struct lmv_user_md_v1 *lum;
4232         int rc;
4233
4234         ENTRY;
4235
4236         LASSERT(buf != NULL && buf->lb_buf != NULL);
4237         lum = buf->lb_buf;
4238
4239         CDEBUG(D_INFO,
4240                "set default stripe_count # %u stripe_offset %d hash %u\n",
4241               le32_to_cpu(lum->lum_stripe_count),
4242               (int)le32_to_cpu(lum->lum_stripe_offset),
4243               le32_to_cpu(lum->lum_hash_type));
4244
4245         if (LMVEA_DELETE_VALUES((le32_to_cpu(lum->lum_stripe_count)),
4246                                  le32_to_cpu(lum->lum_stripe_offset)) &&
4247             le32_to_cpu(lum->lum_magic) == LMV_USER_MAGIC) {
4248                 rc = lod_xattr_del_internal(env, dt, name, th);
4249                 if (rc == -ENODATA)
4250                         rc = 0;
4251         } else {
4252                 rc = lod_xattr_set_internal(env, dt, buf, name, fl, th);
4253                 if (rc != 0)
4254                         RETURN(rc);
4255         }
4256
4257         RETURN(rc);
4258 }
4259
4260 /**
4261  * Turn directory into a striped directory.
4262  *
4263  * During replay the client sends the striping created before MDT
4264  * failure, then the layer above LOD sends this defined striping
4265  * using ->do_xattr_set(), so LOD uses this method to replay creation
4266  * of the stripes. Notice the original information for the striping
4267  * (#stripes, FIDs, etc) was transferred in declare path.
4268  *
4269  * \param[in] env       execution environment
4270  * \param[in] dt        the striped object
4271  * \param[in] buf       buf lmv_user_md for create, or lmv_mds_md for replay
4272  * \param[in] name      not used currently
4273  * \param[in] fl        xattr flag (see OSD API description)
4274  * \param[in] th        transaction handle
4275  *
4276  * \retval              0 on success
4277  * \retval              negative if failed
4278  */
4279 static int lod_xattr_set_lmv(const struct lu_env *env, struct dt_object *dt,
4280                              const struct lu_buf *buf, const char *name,
4281                              int fl, struct thandle *th)
4282 {
4283         struct lod_object *lo = lod_dt_obj(dt);
4284         struct lod_thread_info *info = lod_env_info(env);
4285         struct lu_attr *attr = &info->lti_attr;
4286         struct dt_object_format *dof = &info->lti_format;
4287         struct lu_buf lmv_buf;
4288         struct lu_buf slave_lmv_buf;
4289         struct lmv_user_md *lum = buf->lb_buf;
4290         struct lmv_mds_md_v1 *lmm;
4291         struct lmv_mds_md_v1 *slave_lmm = NULL;
4292         struct dt_insert_rec *rec = &info->lti_dt_rec;
4293         int i;
4294         int rc;
4295
4296         ENTRY;
4297         /* lum is used to know whether it's replay */
4298         LASSERT(lum);
4299         if (!S_ISDIR(dt->do_lu.lo_header->loh_attr))
4300                 RETURN(-ENOTDIR);
4301
4302         /* The stripes are supposed to be allocated in declare phase,
4303          * if there are no stripes being allocated, it will skip */
4304         if (lo->ldo_dir_stripe_count == 0) {
4305                 if (lo->ldo_is_foreign) {
4306                         rc = lod_sub_xattr_set(env, dt_object_child(dt), buf,
4307                                                XATTR_NAME_LMV, fl, th);
4308                         if (rc != 0)
4309                                 RETURN(rc);
4310                 }
4311                 RETURN(0);
4312         }
4313
4314         rc = dt_attr_get(env, dt_object_child(dt), attr);
4315         if (rc != 0)
4316                 RETURN(rc);
4317
4318         attr->la_valid &= LA_ATIME | LA_MTIME | LA_CTIME | LA_FLAGS |
4319                           LA_MODE | LA_UID | LA_GID | LA_TYPE | LA_PROJID;
4320         dof->dof_type = DFT_DIR;
4321
4322         rc = lod_prep_lmv_md(env, dt, &lmv_buf);
4323         if (rc != 0)
4324                 RETURN(rc);
4325         lmm = lmv_buf.lb_buf;
4326
4327         OBD_ALLOC_PTR(slave_lmm);
4328         if (slave_lmm == NULL)
4329                 RETURN(-ENOMEM);
4330
4331         lod_prep_slave_lmv_md(slave_lmm, lmm);
4332         slave_lmv_buf.lb_buf = slave_lmm;
4333         slave_lmv_buf.lb_len = sizeof(*slave_lmm);
4334
4335         rec->rec_type = S_IFDIR;
4336         for (i = 0; i < lo->ldo_dir_stripe_count; i++) {
4337                 struct dt_object *dto = lo->ldo_stripe[i];
4338                 char *stripe_name = info->lti_key;
4339                 struct lu_name *sname;
4340                 struct linkea_data ldata = { NULL };
4341                 struct lu_buf linkea_buf;
4342                 bool stripe_created = false;
4343
4344                 /* OBD_FAIL_MDS_STRIPE_FID may leave stripe uninitialized */
4345                 if (!dto)
4346                         continue;
4347
4348                 /* fail a remote stripe creation */
4349                 if (i && CFS_FAIL_CHECK(OBD_FAIL_MDS_STRIPE_CREATE))
4350                         continue;
4351
4352                 /* if it's replay by client request, and stripe exists on remote
4353                  * MDT, it means mkdir was partially executed: stripe was
4354                  * created on remote MDT successfully, but target not in last
4355                  * run.
4356                  */
4357                 if (unlikely((le32_to_cpu(lum->lum_magic) == LMV_MAGIC_V1) &&
4358                              dt_object_exists(dto) && dt_object_remote(dto)))
4359                         stripe_created = true;
4360
4361                 /* don't create stripe if:
4362                  * 1. it's source stripe of migrating directory
4363                  * 2. it's existed stripe of splitting directory
4364                  */
4365                 if ((lod_is_migrating(lo) && i >= lo->ldo_dir_migrate_offset) ||
4366                     (lod_is_splitting(lo) && i < lo->ldo_dir_split_offset)) {
4367                         if (!dt_object_exists(dto))
4368                                 GOTO(out, rc = -EINVAL);
4369                 } else if (!stripe_created) {
4370                         dt_write_lock(env, dto, DT_TGT_CHILD);
4371                         rc = lod_sub_create(env, dto, attr, NULL, dof, th);
4372                         if (rc != 0) {
4373                                 dt_write_unlock(env, dto);
4374                                 GOTO(out, rc);
4375                         }
4376
4377                         rc = lod_sub_ref_add(env, dto, th);
4378                         dt_write_unlock(env, dto);
4379                         if (rc != 0)
4380                                 GOTO(out, rc);
4381
4382                         rec->rec_fid = lu_object_fid(&dto->do_lu);
4383                         rc = lod_sub_insert(env, dto,
4384                                             (const struct dt_rec *)rec,
4385                                             (const struct dt_key *)dot, th);
4386                         if (rc != 0)
4387                                 GOTO(out, rc);
4388                 }
4389
4390                 if (!CFS_FAIL_CHECK(OBD_FAIL_LFSCK_LOST_SLAVE_LMV) ||
4391                     cfs_fail_val != i) {
4392                         if (CFS_FAIL_CHECK(OBD_FAIL_LFSCK_BAD_SLAVE_LMV) &&
4393                             cfs_fail_val == i)
4394                                 slave_lmm->lmv_master_mdt_index =
4395                                                         cpu_to_le32(i + 1);
4396                         else
4397                                 slave_lmm->lmv_master_mdt_index =
4398                                                         cpu_to_le32(i);
4399
4400                         rc = lod_sub_xattr_set(env, dto, &slave_lmv_buf,
4401                                                XATTR_NAME_LMV, 0, th);
4402                         if (rc != 0)
4403                                 GOTO(out, rc);
4404                 }
4405
4406                 /* don't insert stripe if it's existed stripe of splitting
4407                  * directory (this directory is striped).
4408                  * NB, plain directory will insert itself as the first
4409                  * stripe in target.
4410                  */
4411                 if (lod_is_splitting(lo) && lo->ldo_dir_split_offset > 1 &&
4412                     lo->ldo_dir_split_offset > i)
4413                         continue;
4414
4415                 if (CFS_FAIL_CHECK(OBD_FAIL_LFSCK_BAD_SLAVE_NAME) &&
4416                     cfs_fail_val == i)
4417                         snprintf(stripe_name, sizeof(info->lti_key), DFID":%d",
4418                                  PFID(lu_object_fid(&dto->do_lu)), i + 1);
4419                 else
4420                         snprintf(stripe_name, sizeof(info->lti_key), DFID":%d",
4421                                  PFID(lu_object_fid(&dto->do_lu)), i);
4422
4423                 if (!stripe_created) {
4424                         rec->rec_fid = lu_object_fid(&dt->do_lu);
4425                         rc = lod_sub_insert(env, dto, (struct dt_rec *)rec,
4426                                             (const struct dt_key *)dotdot, th);
4427                         if (rc != 0)
4428                                 GOTO(out, rc);
4429
4430                         sname = lod_name_get(env, stripe_name,
4431                                              strlen(stripe_name));
4432                         rc = linkea_links_new(&ldata, &info->lti_linkea_buf,
4433                                               sname, lu_object_fid(&dt->do_lu));
4434                         if (rc != 0)
4435                                 GOTO(out, rc);
4436
4437                         linkea_buf.lb_buf = ldata.ld_buf->lb_buf;
4438                         linkea_buf.lb_len = ldata.ld_leh->leh_len;
4439                         rc = lod_sub_xattr_set(env, dto, &linkea_buf,
4440                                                XATTR_NAME_LINK, 0, th);
4441                         if (rc != 0)
4442                                 GOTO(out, rc);
4443                 }
4444
4445                 rec->rec_fid = lu_object_fid(&dto->do_lu);
4446                 rc = lod_sub_insert(env, dt_object_child(dt),
4447                                     (const struct dt_rec *)rec,
4448                                     (const struct dt_key *)stripe_name, th);
4449                 if (rc != 0)
4450                         GOTO(out, rc);
4451
4452                 rc = lod_sub_ref_add(env, dt_object_child(dt), th);
4453                 if (rc != 0)
4454                         GOTO(out, rc);
4455         }
4456
4457         if (!CFS_FAIL_CHECK(OBD_FAIL_LFSCK_LOST_MASTER_LMV))
4458                 rc = lod_sub_xattr_set(env, dt_object_child(dt),
4459                                        &lmv_buf, XATTR_NAME_LMV, fl, th);
4460 out:
4461         if (slave_lmm != NULL)
4462                 OBD_FREE_PTR(slave_lmm);
4463
4464         RETURN(rc);
4465 }
4466
4467 /**
4468  * Helper function to declare/execute creation of a striped directory
4469  *
4470  * Called in declare/create object path, prepare striping for a directory
4471  * and prepare defaults data striping for the objects to be created in
4472  * that directory. Notice the function calls "declaration" or "execution"
4473  * methods depending on \a declare param. This is a consequence of the
4474  * current approach while we don't have natural distributed transactions:
4475  * we basically execute non-local updates in the declare phase. So, the
4476  * arguments for the both phases are the same and this is the reason for
4477  * this function to exist.
4478  *
4479  * \param[in] env       execution environment
4480  * \param[in] dt        object
4481  * \param[in] attr      attributes the stripes will be created with
4482  * \param[in] lmu       lmv_user_md if MDT indices are specified
4483  * \param[in] dof       format of stripes (see OSD API description)
4484  * \param[in] th        transaction handle
4485  * \param[in] declare   where to call "declare" or "execute" methods
4486  *
4487  * \retval              0 on success
4488  * \retval              negative if failed
4489  */
4490 static int lod_dir_striping_create_internal(const struct lu_env *env,
4491                                             struct dt_object *dt,
4492                                             struct lu_attr *attr,
4493                                             const struct lu_buf *lmu,
4494                                             struct dt_object_format *dof,
4495                                             struct thandle *th,
4496                                             bool declare)
4497 {
4498         struct lod_thread_info *info = lod_env_info(env);
4499         struct lod_object *lo = lod_dt_obj(dt);
4500         const struct lod_default_striping *lds = lo->ldo_def_striping;
4501         int rc;
4502         ENTRY;
4503
4504         LASSERT(ergo(lds != NULL,
4505                      lds->lds_def_striping_set ||
4506                      lds->lds_dir_def_striping_set));
4507         LASSERT(lmu);
4508
4509         if (!LMVEA_DELETE_VALUES(lo->ldo_dir_stripe_count,
4510                                  lo->ldo_dir_stripe_offset)) {
4511                 if (!lmu->lb_buf) {
4512                         /* mkdir by default LMV */
4513                         struct lmv_user_md_v1 *v1 = info->lti_ea_store;
4514                         int stripe_count = lo->ldo_dir_stripe_count;
4515
4516                         if (info->lti_ea_store_size < sizeof(*v1)) {
4517                                 rc = lod_ea_store_resize(info, sizeof(*v1));
4518                                 if (rc != 0)
4519                                         RETURN(rc);
4520                                 v1 = info->lti_ea_store;
4521                         }
4522
4523                         memset(v1, 0, sizeof(*v1));
4524                         v1->lum_magic = cpu_to_le32(LMV_USER_MAGIC);
4525                         v1->lum_stripe_count = cpu_to_le32(stripe_count);
4526                         v1->lum_stripe_offset =
4527                                         cpu_to_le32(lo->ldo_dir_stripe_offset);
4528
4529                         info->lti_buf.lb_buf = v1;
4530                         info->lti_buf.lb_len = sizeof(*v1);
4531                         lmu = &info->lti_buf;
4532                 }
4533
4534                 if (declare)
4535                         rc = lod_declare_xattr_set_lmv(env, dt, attr, lmu, dof,
4536                                                        th);
4537                 else
4538                         rc = lod_xattr_set_lmv(env, dt, lmu, XATTR_NAME_LMV, 0,
4539                                                th);
4540                 if (rc != 0)
4541                         RETURN(rc);
4542         } else if (lmu->lb_buf) {
4543                 /* foreign LMV EA case */
4544                 if (declare) {
4545                         struct lmv_foreign_md *lfm = lmu->lb_buf;
4546
4547                         if (lfm->lfm_magic == LMV_MAGIC_FOREIGN)
4548                                 rc = lod_declare_xattr_set_lmv(env, dt, attr,
4549                                                                lmu, dof, th);
4550                 } else if (lo->ldo_is_foreign) {
4551                         LASSERT(lo->ldo_foreign_lmv != NULL &&
4552                                 lo->ldo_foreign_lmv_size > 0);
4553                         info->lti_buf.lb_buf = lo->ldo_foreign_lmv;
4554                         info->lti_buf.lb_len = lo->ldo_foreign_lmv_size;
4555                         lmu = &info->lti_buf;
4556                         rc = lod_xattr_set_lmv(env, dt, lmu, XATTR_NAME_LMV, 0,
4557                                                th);
4558                 }
4559         }
4560
4561         /* Transfer default LMV striping from the parent */
4562         if (lds != NULL && lds->lds_dir_def_striping_set &&
4563             lds->lds_dir_def_max_inherit != LMV_INHERIT_END &&
4564             lds->lds_dir_def_max_inherit != LMV_INHERIT_NONE &&
4565             !(LMVEA_DELETE_VALUES(lds->lds_dir_def_stripe_count,
4566                                  lds->lds_dir_def_stripe_offset) &&
4567               le32_to_cpu(lds->lds_dir_def_hash_type) !=
4568               LMV_HASH_TYPE_UNKNOWN)) {
4569                 struct lmv_user_md_v1 *v1 = info->lti_ea_store;
4570
4571                 if (info->lti_ea_store_size < sizeof(*v1)) {
4572                         rc = lod_ea_store_resize(info, sizeof(*v1));
4573                         if (rc != 0)
4574                                 RETURN(rc);
4575                         v1 = info->lti_ea_store;
4576                 }
4577
4578                 memset(v1, 0, sizeof(*v1));
4579                 v1->lum_magic = cpu_to_le32(LMV_USER_MAGIC);
4580                 v1->lum_stripe_count =
4581                         cpu_to_le32(lds->lds_dir_def_stripe_count);
4582                 v1->lum_stripe_offset =
4583                         cpu_to_le32(lds->lds_dir_def_stripe_offset);
4584                 v1->lum_hash_type =
4585                         cpu_to_le32(lds->lds_dir_def_hash_type);
4586                 v1->lum_max_inherit =
4587                         lmv_inherit_next(lds->lds_dir_def_max_inherit);
4588                 v1->lum_max_inherit_rr =
4589                         lmv_inherit_rr_next(lds->lds_dir_def_max_inherit_rr);
4590
4591                 info->lti_buf.lb_buf = v1;
4592                 info->lti_buf.lb_len = sizeof(*v1);
4593                 if (declare)
4594                         rc = lod_dir_declare_xattr_set(env, dt, &info->lti_buf,
4595                                                        XATTR_NAME_DEFAULT_LMV,
4596                                                        0, th);
4597                 else
4598                         rc = lod_xattr_set_default_lmv_on_dir(env, dt,
4599                                                   &info->lti_buf,
4600                                                   XATTR_NAME_DEFAULT_LMV, 0,
4601                                                   th);
4602                 if (rc != 0)
4603                         RETURN(rc);
4604         }
4605
4606         /* Transfer default LOV striping from the parent */
4607         if (lds != NULL && lds->lds_def_striping_set &&
4608             lds->lds_def_comp_cnt != 0) {
4609                 struct lov_mds_md *lmm;
4610                 int lmm_size = lod_comp_md_size(lo, true);
4611
4612                 if (info->lti_ea_store_size < lmm_size) {
4613                         rc = lod_ea_store_resize(info, lmm_size);
4614                         if (rc != 0)
4615                                 RETURN(rc);
4616                 }
4617                 lmm = info->lti_ea_store;
4618
4619                 rc = lod_generate_lovea(env, lo, lmm, &lmm_size, true);
4620                 if (rc != 0)
4621                         RETURN(rc);
4622
4623                 info->lti_buf.lb_buf = lmm;
4624                 info->lti_buf.lb_len = lmm_size;
4625
4626                 if (declare)
4627                         rc = lod_dir_declare_xattr_set(env, dt, &info->lti_buf,
4628                                                        XATTR_NAME_LOV, 0, th);
4629                 else
4630                         rc = lod_xattr_set_lov_on_dir(env, dt, &info->lti_buf,
4631                                                       XATTR_NAME_LOV, 0, th);
4632                 if (rc != 0)
4633                         RETURN(rc);
4634         }
4635
4636         /* ldo_def_striping is not allocated, clear after use, in case directory
4637          * layout is changed later.
4638          */
4639         if (!declare)
4640                 lo->ldo_def_striping = NULL;
4641
4642         RETURN(0);
4643 }
4644
4645 static int lod_declare_dir_striping_create(const struct lu_env *env,
4646                                            struct dt_object *dt,
4647                                            struct lu_attr *attr,
4648                                            struct lu_buf *lmu,
4649                                            struct dt_object_format *dof,
4650                                            struct thandle *th)
4651 {
4652         return lod_dir_striping_create_internal(env, dt, attr, lmu, dof, th,
4653                                                 true);
4654 }
4655
4656 static int lod_dir_striping_create(const struct lu_env *env,
4657                                    struct dt_object *dt,
4658                                    struct lu_attr *attr,
4659                                    const struct lu_buf *lmu,
4660                                    struct dt_object_format *dof,
4661                                    struct thandle *th)
4662 {
4663         return lod_dir_striping_create_internal(env, dt, attr, lmu, dof, th,
4664                                                 false);
4665 }
4666
4667 /**
4668  * Make LOV EA for striped object.
4669  *
4670  * Generate striping information and store it in the LOV EA of the given
4671  * object. The caller must ensure nobody else is calling the function
4672  * against the object concurrently. The transaction must be started.
4673  * FLDB service must be running as well; it's used to map FID to the target,
4674  * which is stored in LOV EA.
4675  *
4676  * \param[in] env               execution environment for this thread
4677  * \param[in] lo                LOD object
4678  * \param[in] th                transaction handle
4679  *
4680  * \retval                      0 if LOV EA is stored successfully
4681  * \retval                      negative error number on failure
4682  */
4683 static int lod_generate_and_set_lovea(const struct lu_env *env,
4684                                       struct lod_object *lo,
4685                                       struct thandle *th)
4686 {
4687         struct lod_thread_info  *info = lod_env_info(env);
4688         struct dt_object        *next = dt_object_child(&lo->ldo_obj);
4689         struct lov_mds_md_v1    *lmm;
4690         int                      rc, lmm_size;
4691         ENTRY;
4692
4693         LASSERT(lo);
4694
4695         if (lo->ldo_comp_cnt == 0 && !lo->ldo_is_foreign) {
4696                 lod_striping_free_nolock(env, lo);
4697                 rc = lod_sub_xattr_del(env, next, XATTR_NAME_LOV, th);
4698                 RETURN(rc);
4699         }
4700
4701         lmm_size = lod_comp_md_size(lo, false);
4702         if (info->lti_ea_store_size < lmm_size) {
4703                 rc = lod_ea_store_resize(info, lmm_size);
4704                 if (rc)
4705                         RETURN(rc);
4706         }
4707         lmm = info->lti_ea_store;
4708
4709         rc = lod_generate_lovea(env, lo, lmm, &lmm_size, false);
4710         if (rc)
4711                 RETURN(rc);
4712
4713         info->lti_buf.lb_buf = lmm;
4714         info->lti_buf.lb_len = lmm_size;
4715         rc = lod_sub_xattr_set(env, next, &info->lti_buf,
4716                                XATTR_NAME_LOV, 0, th);
4717         RETURN(rc);
4718 }
4719
4720 static __u32 lod_gen_component_id(struct lod_object *lo,
4721                                   int mirror_id, int comp_idx);
4722
4723 /**
4724  * Repeat an existing component
4725  *
4726  * Creates a new layout by replicating an existing component.  Uses striping
4727  * policy from previous component as a template for the striping for the new
4728  * new component.
4729  *
4730  * New component starts with zero length, will be extended (or removed) before
4731  * returning layout to client.
4732  *
4733  * NB: Reallocates layout components array (lo->ldo_comp_entries), invalidating
4734  * any pre-existing pointers to components.  Handle with care.
4735  *
4736  * \param[in] env       execution environment for this thread
4737  * \param[in,out] lo    object to update the layout of
4738  * \param[in] index     index of component to copy
4739  *
4740  * \retval      0 on success
4741  * \retval      negative errno on error
4742  */
4743 static int lod_layout_repeat_comp(const struct lu_env *env,
4744                                   struct lod_object *lo, int index)
4745 {
4746         struct lod_layout_component *lod_comp;
4747         struct lod_layout_component *new_comp = NULL;
4748         struct lod_layout_component *comp_array;
4749         int rc = 0, i, new_cnt = lo->ldo_comp_cnt + 1;
4750         __u16 mirror_id;
4751         int offset = 0;
4752         ENTRY;
4753
4754         lod_comp = &lo->ldo_comp_entries[index];
4755         LASSERT(lod_comp_inited(lod_comp) && lod_comp->llc_id != LCME_ID_INVAL);
4756
4757         CDEBUG(D_LAYOUT, "repeating component %d\n", index);
4758
4759         OBD_ALLOC_PTR_ARRAY(comp_array, new_cnt);
4760         if (comp_array == NULL)
4761                 GOTO(out, rc = -ENOMEM);
4762
4763         for (i = 0; i < lo->ldo_comp_cnt; i++) {
4764                 memcpy(&comp_array[i + offset], &lo->ldo_comp_entries[i],
4765                        sizeof(*comp_array));
4766
4767                 /* Duplicate this component in to the next slot */
4768                 if (i == index) {
4769                         new_comp = &comp_array[i + 1];
4770                         memcpy(&comp_array[i + 1], &lo->ldo_comp_entries[i],
4771                                sizeof(*comp_array));
4772                         /* We must now skip this new component when copying */
4773                         offset = 1;
4774                 }
4775         }
4776
4777         /* Set up copied component */
4778         new_comp->llc_flags &= ~LCME_FL_INIT;
4779         new_comp->llc_stripe = NULL;
4780         new_comp->llc_stripes_allocated = 0;
4781         new_comp->llc_ost_indices = NULL;
4782         new_comp->llc_stripe_offset = LOV_OFFSET_DEFAULT;
4783         /* for uninstantiated components, layout gen stores default stripe
4784          * offset */
4785         new_comp->llc_layout_gen = lod_comp->llc_stripe_offset;
4786         /* This makes the repeated component zero-length, placed at the end of
4787          * the preceding component */
4788         new_comp->llc_extent.e_start = new_comp->llc_extent.e_end;
4789         new_comp->llc_timestamp = lod_comp->llc_timestamp;
4790         new_comp->llc_pool = NULL;
4791
4792         rc = lod_set_pool(&new_comp->llc_pool, lod_comp->llc_pool);
4793         if (rc)
4794                 GOTO(out, rc);
4795
4796         if (new_comp->llc_ostlist.op_array) {
4797                 __u32 *op_array = NULL;
4798
4799                 OBD_ALLOC(op_array, new_comp->llc_ostlist.op_size);
4800                 if (!op_array)
4801                         GOTO(out, rc = -ENOMEM);
4802                 memcpy(op_array, &new_comp->llc_ostlist.op_array,
4803                        new_comp->llc_ostlist.op_size);
4804                 new_comp->llc_ostlist.op_array = op_array;
4805         }
4806
4807         OBD_FREE_PTR_ARRAY(lo->ldo_comp_entries, lo->ldo_comp_cnt);
4808         lo->ldo_comp_entries = comp_array;
4809         lo->ldo_comp_cnt = new_cnt;
4810
4811         /* Generate an id for the new component */
4812         mirror_id = mirror_id_of(new_comp->llc_id);
4813         new_comp->llc_id = LCME_ID_INVAL;
4814         new_comp->llc_id = lod_gen_component_id(lo, mirror_id, index + 1);
4815         if (new_comp->llc_id == LCME_ID_INVAL)
4816                 GOTO(out, rc = -ERANGE);
4817
4818         EXIT;
4819 out:
4820         if (rc)
4821                 OBD_FREE_PTR_ARRAY(comp_array, new_cnt);
4822
4823         return rc;
4824 }
4825
4826 static int lod_layout_data_init(struct lod_thread_info *info, __u32 comp_cnt)
4827 {
4828         ENTRY;
4829
4830         /* clear memory region that will be used for layout change */
4831         memset(&info->lti_layout_attr, 0, sizeof(struct lu_attr));
4832         info->lti_count = 0;
4833
4834         if (info->lti_comp_size >= comp_cnt)
4835                 RETURN(0);
4836
4837         if (info->lti_comp_size > 0) {
4838                 OBD_FREE_PTR_ARRAY(info->lti_comp_idx, info->lti_comp_size);
4839                 info->lti_comp_size = 0;
4840         }
4841
4842         OBD_ALLOC_PTR_ARRAY(info->lti_comp_idx, comp_cnt);
4843         if (!info->lti_comp_idx)
4844                 RETURN(-ENOMEM);
4845
4846         info->lti_comp_size = comp_cnt;
4847         RETURN(0);
4848 }
4849
4850 /**
4851  * Prepare new layout minus deleted components
4852  *
4853  * Removes components marked for deletion (LCME_ID_INVAL) by copying to a new
4854  * layout and skipping those components.  Removes stripe objects if any exist.
4855  *
4856  * NB:
4857  * Reallocates layout components array (lo->ldo_comp_entries), invalidating
4858  * any pre-existing pointers to components.
4859  *
4860  * Caller is responsible for updating mirror end (ldo_mirror[].lme_end).
4861  *
4862  * \param[in] env       execution environment for this thread
4863  * \param[in,out] lo    object to update the layout of
4864  * \param[in] th        transaction handle for this operation
4865  *
4866  * \retval      # of components deleted
4867  * \retval      negative errno on error
4868  */
4869 static int lod_layout_del_prep_layout(const struct lu_env *env,
4870                                       struct lod_object *lo,
4871                                       struct thandle *th)
4872 {
4873         struct lod_layout_component     *lod_comp;
4874         struct lod_thread_info  *info = lod_env_info(env);
4875         int rc = 0, i, j, deleted = 0;
4876
4877         ENTRY;
4878
4879         LASSERT(lo->ldo_is_composite);
4880         LASSERT(lo->ldo_comp_cnt > 0 && lo->ldo_comp_entries != NULL);
4881
4882         rc = lod_layout_data_init(info, lo->ldo_comp_cnt);
4883         if (rc)
4884                 RETURN(rc);
4885
4886         for (i = 0; i < lo->ldo_comp_cnt; i++) {
4887                 lod_comp = &lo->ldo_comp_entries[i];
4888
4889                 if (lod_comp->llc_id != LCME_ID_INVAL) {
4890                         /* Build array of things to keep */
4891                         info->lti_comp_idx[info->lti_count++] = i;
4892                         continue;
4893                 }
4894
4895                 if (lod_comp->llc_magic == LOV_MAGIC_FOREIGN)
4896                         continue;
4897
4898                 lod_obj_set_pool(lo, i, NULL);
4899                 if (lod_comp->llc_ostlist.op_array) {
4900                         OBD_FREE(lod_comp->llc_ostlist.op_array,
4901                                  lod_comp->llc_ostlist.op_size);
4902                         lod_comp->llc_ostlist.op_array = NULL;
4903                         lod_comp->llc_ostlist.op_size = 0;
4904                 }
4905
4906                 deleted++;
4907                 CDEBUG(D_LAYOUT, "deleting comp %d, left %d\n", i,
4908                        lo->ldo_comp_cnt - deleted);
4909
4910                 /* No striping info for this component */
4911                 if (lod_comp->llc_stripe == NULL)
4912                         continue;
4913
4914                 LASSERT(lod_comp->llc_stripe_count > 0);
4915                 for (j = 0; j < lod_comp->llc_stripe_count; j++) {
4916                         struct dt_object *obj = lod_comp->llc_stripe[j];
4917
4918                         if (obj == NULL)
4919                                 continue;
4920
4921                         /* components which are not init have no sub objects
4922                          * to destroy */
4923                         if (lod_comp_inited(lod_comp)) {
4924                                 rc = lod_sub_destroy(env, obj, th);
4925                                 if (rc)
4926                                         GOTO(out, rc);
4927                         }
4928
4929                         lu_object_put(env, &obj->do_lu);
4930                         lod_comp->llc_stripe[j] = NULL;
4931                 }
4932                 OBD_FREE_PTR_ARRAY(lod_comp->llc_stripe,
4933                                    lod_comp->llc_stripes_allocated);
4934                 lod_comp->llc_stripe = NULL;
4935                 OBD_FREE_PTR_ARRAY(lod_comp->llc_ost_indices,
4936                                    lod_comp->llc_stripes_allocated);
4937                 lod_comp->llc_ost_indices = NULL;
4938                 lod_comp->llc_stripes_allocated = 0;
4939         }
4940
4941         /* info->lti_count has the amount of left components */
4942         LASSERTF(info->lti_count >= 0 && info->lti_count < lo->ldo_comp_cnt,
4943                  "left = %d, lo->ldo_comp_cnt %d\n", (int)info->lti_count,
4944                  (int)lo->ldo_comp_cnt);
4945
4946         if (info->lti_count > 0) {
4947                 struct lod_layout_component *comp_array;
4948
4949                 OBD_ALLOC_PTR_ARRAY(comp_array, info->lti_count);
4950                 if (comp_array == NULL)
4951                         GOTO(out, rc = -ENOMEM);
4952
4953                 for (i = 0; i < info->lti_count; i++) {
4954                         memcpy(&comp_array[i],
4955                                &lo->ldo_comp_entries[info->lti_comp_idx[i]],
4956                                sizeof(*comp_array));
4957                 }
4958
4959                 OBD_FREE_PTR_ARRAY(lo->ldo_comp_entries, lo->ldo_comp_cnt);
4960                 lo->ldo_comp_entries = comp_array;
4961                 lo->ldo_comp_cnt = info->lti_count;
4962         } else {
4963                 lod_free_comp_entries(lo);
4964         }
4965
4966         EXIT;
4967 out:
4968         return rc ? rc : deleted;
4969 }
4970
4971 /**
4972  * Delete layout component(s)
4973  *
4974  * This function sets up the layout data in the env and does the setattrs
4975  * required to write out the new layout.  The layout itself is modified in
4976  * lod_layout_del_prep_layout.
4977  *
4978  * \param[in] env       execution environment for this thread
4979  * \param[in] dt        object
4980  * \param[in] th        transaction handle
4981  *
4982  * \retval      0 on success
4983  * \retval      negative error number on failure
4984  */
4985 static int lod_layout_del(const struct lu_env *env, struct dt_object *dt,
4986                           struct thandle *th)
4987 {
4988         struct lod_object *lo = lod_dt_obj(dt);
4989         struct dt_object *next = dt_object_child(dt);
4990         struct lu_attr *attr = &lod_env_info(env)->lti_attr;
4991         int rc;
4992
4993         LASSERT(lo->ldo_mirror_count == 1);
4994
4995         mutex_lock(&lo->ldo_layout_mutex);
4996
4997         rc = lod_layout_del_prep_layout(env, lo, th);
4998         if (rc < 0)
4999                 GOTO(out, rc);
5000
5001         /* Only do this if we didn't delete all components */
5002         if (lo->ldo_comp_cnt > 0) {
5003                 lo->ldo_mirrors[0].lme_end = lo->ldo_comp_cnt - 1;
5004                 lod_obj_inc_layout_gen(lo);
5005         }
5006
5007         LASSERT(dt_object_exists(dt));
5008         rc = dt_attr_get(env, next, attr);
5009         if (rc)
5010                 GOTO(out, rc);
5011
5012         if (attr->la_size > 0) {
5013                 attr->la_size = 0;
5014                 attr->la_valid = LA_SIZE;
5015                 rc = lod_sub_attr_set(env, next, attr, th);
5016                 if (rc)
5017                         GOTO(out, rc);
5018         }
5019
5020         rc = lod_generate_and_set_lovea(env, lo, th);
5021         EXIT;
5022 out:
5023         if (rc)
5024                 lod_striping_free_nolock(env, lo);
5025
5026         mutex_unlock(&lo->ldo_layout_mutex);
5027
5028         return rc;
5029 }
5030
5031
5032 /**
5033  * Implementation of dt_object_operations::do_xattr_set.
5034  *
5035  * Sets specified extended attribute on the object. Three types of EAs are
5036  * special:
5037  *   LOV EA - stores striping for a regular file or default striping (when set
5038  *            on a directory)
5039  *   LMV EA - stores a marker for the striped directories
5040  *   DMV EA - stores default directory striping
5041  *
5042  * When striping is applied to a non-striped existing object (this is called
5043  * late striping), then LOD notices the caller wants to turn the object into a
5044  * striped one. The stripe objects are created and appropriate EA is set:
5045  * LOV EA storing all the stripes directly or LMV EA storing just a small header
5046  * with striping configuration.
5047  *
5048  * \see dt_object_operations::do_xattr_set() in the API description for details.
5049  */
5050 static int lod_xattr_set(const struct lu_env *env,
5051                          struct dt_object *dt, const struct lu_buf *buf,
5052                          const char *name, int fl, struct thandle *th)
5053 {
5054         struct dt_object *next = dt_object_child(dt);
5055         struct lu_attr *layout_attr = &lod_env_info(env)->lti_layout_attr;
5056         struct lod_object *lo = lod_dt_obj(dt);
5057         struct lod_obj_stripe_cb_data data = { {0} };
5058         int rc = 0;
5059
5060         ENTRY;
5061
5062         if (S_ISDIR(dt->do_lu.lo_header->loh_attr) &&
5063             !strcmp(name, XATTR_NAME_LMV)) {
5064                 switch (fl) {
5065                 case LU_XATTR_CREATE:
5066                         rc = lod_dir_striping_create(env, dt, NULL, buf, NULL,
5067                                                      th);
5068                         break;
5069                 case 0:
5070                 case LU_XATTR_REPLACE:
5071                         rc = lod_dir_layout_set(env, dt, buf, fl, th);
5072                         break;
5073                 default:
5074                         LBUG();
5075                 }
5076
5077                 RETURN(rc);
5078         } else if (S_ISDIR(dt->do_lu.lo_header->loh_attr) &&
5079                    strcmp(name, XATTR_NAME_LOV) == 0) {
5080                 rc = lod_xattr_set_default_lov_on_dir(env, dt, buf, name, fl,
5081                                                       th);
5082                 RETURN(rc);
5083         } else if (S_ISDIR(dt->do_lu.lo_header->loh_attr) &&
5084                    strcmp(name, XATTR_NAME_DEFAULT_LMV) == 0) {
5085                 /* default LMVEA */
5086                 rc = lod_xattr_set_default_lmv_on_dir(env, dt, buf, name, fl,
5087                                                       th);
5088                 RETURN(rc);
5089         } else if (S_ISREG(dt->do_lu.lo_header->loh_attr) &&
5090                    (strcmp(name, XATTR_NAME_LOV) == 0 ||
5091                     strcmp(name, XATTR_LUSTRE_LOV) == 0 ||
5092                     allowed_lustre_lov(name))) {
5093                 /* in case of lov EA swap, just set it
5094                  * if not, it is a replay so check striping match what we
5095                  * already have during req replay, declare_xattr_set()
5096                  * defines striping, then create() does the work */
5097                 if (fl & LU_XATTR_REPLACE) {
5098                         /* free stripes, then update disk */
5099                         lod_striping_free(env, lod_dt_obj(dt));
5100
5101                         rc = lod_sub_xattr_set(env, next, buf, name, fl, th);
5102                 } else if (fl & LU_XATTR_SPLIT) {
5103                         rc = lod_sub_xattr_set(env, next, buf, name, fl, th);
5104                         if (rc)
5105                                 RETURN(rc);
5106
5107                         rc = lod_striping_reload(env, lo, buf, LVF_ALL_STALE);
5108                         if (rc)
5109                                 RETURN(rc);
5110
5111                         if (lo->ldo_mirror_count > 1 &&
5112                             layout_attr->la_valid & LA_LAYOUT_VERSION) {
5113                                 /* mirror split */
5114                                 layout_attr->la_layout_version =
5115                                                 lo->ldo_layout_gen;
5116                                 data.locd_attr = layout_attr;
5117                                 data.locd_declare = false;
5118                                 data.locd_stripe_cb =
5119                                                 lod_obj_stripe_attr_set_cb;
5120                                 rc = lod_obj_for_each_stripe(env, lo, th,
5121                                                              &data);
5122                                 if (rc)
5123                                         RETURN(rc);
5124                         }
5125                 } else if (fl & LU_XATTR_PURGE) {
5126                         rc = lod_layout_purge(env, dt, buf, th);
5127                 } else if (dt_object_remote(dt)) {
5128                         /* This only happens during migration, see
5129                          * mdd_migrate_create(), in which Master MDT will
5130                          * create a remote target object, and only set
5131                          * (migrating) stripe EA on the remote object,
5132                          * and does not need creating each stripes. */
5133                         rc = lod_sub_xattr_set(env, next, buf, name,
5134                                                       fl, th);
5135                 } else if (strcmp(name, XATTR_LUSTRE_LOV".del") == 0) {
5136                         /* delete component(s) */
5137                         LASSERT(lod_dt_obj(dt)->ldo_comp_cached);
5138                         rc = lod_layout_del(env, dt, th);
5139                 } else {
5140                         /*
5141                          * When 'name' is XATTR_LUSTRE_LOV or XATTR_NAME_LOV,
5142                          * it's going to create create file with specified
5143                          * component(s), the striping must have not being
5144                          * cached in this case;
5145                          *
5146                          * Otherwise, it's going to add/change component(s) to
5147                          * an existing file, the striping must have been cached
5148                          * in this case.
5149                          */
5150                         LASSERT(equi(!strcmp(name, XATTR_LUSTRE_LOV) ||
5151                                      !strcmp(name, XATTR_NAME_LOV),
5152                                 !lod_dt_obj(dt)->ldo_comp_cached));
5153
5154                         rc = lod_striped_create(env, dt, NULL, NULL, th);
5155                         if (rc)
5156                                 RETURN(rc);
5157
5158                         if (fl & LU_XATTR_MERGE && lo->ldo_mirror_count > 1 &&
5159                             layout_attr->la_valid & LA_LAYOUT_VERSION) {
5160                                 /* mirror merge exec phase */
5161                                 layout_attr->la_layout_version =
5162                                                 lo->ldo_layout_gen;
5163                                 data.locd_attr = layout_attr;
5164                                 data.locd_declare = false;
5165                                 data.locd_stripe_cb =
5166                                                 lod_obj_stripe_attr_set_cb;
5167                                 rc = lod_obj_for_each_stripe(env, lo, th,
5168                                                              &data);
5169                                 if (rc)
5170                                         RETURN(rc);
5171                         }
5172                 }
5173                 RETURN(rc);
5174         } else if (strcmp(name, XATTR_NAME_FID) == 0) {
5175                 rc = lod_replace_parent_fid(env, dt, buf, th, false);
5176
5177                 RETURN(rc);
5178         }
5179
5180         /* then all other xattr */
5181         rc = lod_xattr_set_internal(env, dt, buf, name, fl, th);
5182
5183         RETURN(rc);
5184 }
5185
5186 /**
5187  * Implementation of dt_object_operations::do_declare_xattr_del.
5188  *
5189  * \see dt_object_operations::do_declare_xattr_del() in the API description
5190  * for details.
5191  */
5192 static int lod_declare_xattr_del(const struct lu_env *env,
5193                                  struct dt_object *dt, const char *name,
5194                                  struct thandle *th)
5195 {
5196         struct lod_object *lo = lod_dt_obj(dt);
5197         struct dt_object *next = dt_object_child(dt);
5198         int i;
5199         int rc;
5200         ENTRY;
5201
5202         rc = lod_sub_declare_xattr_del(env, next, name, th);
5203         if (rc != 0)
5204                 RETURN(rc);
5205
5206         if (!S_ISDIR(dt->do_lu.lo_header->loh_attr))
5207                 RETURN(0);
5208
5209         /* NB: don't delete stripe LMV, because when we do this, normally we
5210          * will remove stripes, besides, if directory LMV is corrupt, this will
5211          * prevent deleting its LMV and fixing it (via LFSCK).
5212          */
5213         if (!strcmp(name, XATTR_NAME_LMV))
5214                 RETURN(0);
5215
5216         rc = lod_striping_load(env, lo);
5217         if (rc != 0)
5218                 RETURN(rc);
5219
5220         if (lo->ldo_dir_stripe_count == 0)
5221                 RETURN(0);
5222
5223         for (i = 0; i < lo->ldo_dir_stripe_count; i++) {
5224                 struct dt_object *dto = lo->ldo_stripe[i];
5225
5226                 if (!dto)
5227                         continue;
5228
5229                 if (!dt_object_exists(dto))
5230                         continue;
5231
5232                 rc = lod_sub_declare_xattr_del(env, dto, name, th);
5233                 if (rc != 0)
5234                         break;
5235         }
5236
5237         RETURN(rc);
5238 }
5239
5240 /**
5241  * Implementation of dt_object_operations::do_xattr_del.
5242  *
5243  * If EA storing a regular striping is being deleted, then release
5244  * all the references to the stripe objects in core.
5245  *
5246  * \see dt_object_operations::do_xattr_del() in the API description for details.
5247  */
5248 static int lod_xattr_del(const struct lu_env *env, struct dt_object *dt,
5249                          const char *name, struct thandle *th)
5250 {
5251         int rc;
5252
5253         ENTRY;
5254
5255         if (!strcmp(name, XATTR_NAME_LOV) || !strcmp(name, XATTR_NAME_LMV))
5256                 lod_striping_free(env, lod_dt_obj(dt));
5257
5258         rc = lod_xattr_del_internal(env, dt, name, th);
5259
5260         RETURN(rc);
5261 }
5262
5263 /**
5264  * Implementation of dt_object_operations::do_xattr_list.
5265  *
5266  * \see dt_object_operations::do_xattr_list() in the API description
5267  * for details.
5268  */
5269 static int lod_xattr_list(const struct lu_env *env,
5270                           struct dt_object *dt, const struct lu_buf *buf)
5271 {
5272         return dt_xattr_list(env, dt_object_child(dt), buf);
5273 }
5274
5275 static inline int lod_object_will_be_striped(int is_reg, const struct lu_fid *fid)
5276 {
5277         return (is_reg && fid_seq(fid) != FID_SEQ_LOCAL_FILE);
5278 }
5279
5280 /**
5281  * Copy OST list from layout provided by user.
5282  *
5283  * \param[in] lod_comp          layout_component to be filled
5284  * \param[in] v3                LOV EA V3 user data
5285  *
5286  * \retval              0 on success
5287  * \retval              negative if failed
5288  */
5289 int lod_comp_copy_ost_lists(struct lod_layout_component *lod_comp,
5290                             struct lov_user_md_v3 *v3)
5291 {
5292         int j;
5293
5294         ENTRY;
5295
5296         if (v3->lmm_stripe_offset == LOV_OFFSET_DEFAULT)
5297                 v3->lmm_stripe_offset = v3->lmm_objects[0].l_ost_idx;
5298
5299         if (lod_comp->llc_ostlist.op_array) {
5300                 if (lod_comp->llc_ostlist.op_size >=
5301                     v3->lmm_stripe_count * sizeof(__u32))  {
5302                         lod_comp->llc_ostlist.op_count =
5303                                         v3->lmm_stripe_count;
5304                         goto skip;
5305                 }
5306                 OBD_FREE(lod_comp->llc_ostlist.op_array,
5307                          lod_comp->llc_ostlist.op_size);
5308         }
5309
5310         /* copy ost list from lmm */
5311         lod_comp->llc_ostlist.op_count = v3->lmm_stripe_count;
5312         lod_comp->llc_ostlist.op_size = v3->lmm_stripe_count * sizeof(__u32);
5313         OBD_ALLOC(lod_comp->llc_ostlist.op_array,
5314                   lod_comp->llc_ostlist.op_size);
5315         if (!lod_comp->llc_ostlist.op_array)
5316                 RETURN(-ENOMEM);
5317 skip:
5318         for (j = 0; j < v3->lmm_stripe_count; j++) {
5319                 lod_comp->llc_ostlist.op_array[j] =
5320                         v3->lmm_objects[j].l_ost_idx;
5321         }
5322
5323         RETURN(0);
5324 }
5325
5326
5327 /**
5328  * Get default striping.
5329  *
5330  * \param[in] env               execution environment
5331  * \param[in] lo                object
5332  * \param[out] lds              default striping
5333  *
5334  * \retval              0 on success
5335  * \retval              negative if failed
5336  */
5337 static int lod_get_default_lov_striping(const struct lu_env *env,
5338                                         struct lod_object *lo,
5339                                         struct lod_default_striping *lds,
5340                                         struct dt_allocation_hint *dah)
5341 {
5342         struct lod_thread_info *info = lod_env_info(env);
5343         struct lov_user_md_v1 *v1 = NULL;
5344         struct lov_user_md_v3 *v3 = NULL;
5345         struct lov_comp_md_v1 *lcm = NULL;
5346         __u32 magic;
5347         int append_stripe_count = dah != NULL ? dah->dah_append_stripe_count : 0;
5348         const char *append_pool = (dah != NULL &&
5349                                    dah->dah_append_pool != NULL &&
5350                                    dah->dah_append_pool[0] != '\0') ?
5351                                   dah->dah_append_pool : NULL;
5352         __u16 entry_count = 1;
5353         __u16 mirror_count = 0;
5354         bool want_composite = false;
5355         int rc, i, j;
5356
5357         ENTRY;
5358
5359         lds->lds_def_striping_set = 0;
5360
5361         rc = lod_get_lov_ea(env, lo);
5362         if (rc < 0)
5363                 RETURN(rc);
5364
5365         if (rc < (typeof(rc))sizeof(struct lov_user_md))
5366                 RETURN(0);
5367
5368         magic = *(__u32 *)info->lti_ea_store;
5369         if (magic == __swab32(LOV_USER_MAGIC_V1)) {
5370                 lustre_swab_lov_user_md_v1(info->lti_ea_store);
5371         } else if (magic == __swab32(LOV_USER_MAGIC_V3)) {
5372                 lustre_swab_lov_user_md_v3(info->lti_ea_store);
5373         } else if (magic == __swab32(LOV_USER_MAGIC_SPECIFIC)) {
5374                 v3 = (struct lov_user_md_v3 *)info->lti_ea_store;
5375                 lustre_swab_lov_user_md_v3(v3);
5376                 lustre_swab_lov_user_md_objects(v3->lmm_objects,
5377                                                 v3->lmm_stripe_count);
5378         } else if (magic == __swab32(LOV_USER_MAGIC_COMP_V1) ||
5379                    magic == __swab32(LOV_USER_MAGIC_SEL)) {
5380                 lustre_swab_lov_comp_md_v1(info->lti_ea_store);
5381         }
5382
5383         switch (magic) {
5384         case LOV_MAGIC_V1:
5385         case LOV_MAGIC_V3:
5386         case LOV_USER_MAGIC_SPECIFIC:
5387                 v1 = info->lti_ea_store;
5388                 break;
5389         case LOV_MAGIC_COMP_V1:
5390         case LOV_MAGIC_SEL:
5391                 lcm = info->lti_ea_store;
5392                 entry_count = lcm->lcm_entry_count;
5393                 if (entry_count == 0)
5394                         RETURN(-EINVAL);
5395
5396                 mirror_count = lcm->lcm_mirror_count + 1;
5397                 want_composite = true;
5398                 break;
5399         default:
5400                 RETURN(-ENOTSUPP);
5401         }
5402
5403         if (append_stripe_count != 0 || append_pool != NULL) {
5404                 entry_count = 1;
5405                 mirror_count = 0;
5406                 want_composite = false;
5407         }
5408
5409         /* realloc default comp entries if necessary */
5410         rc = lod_def_striping_comp_resize(lds, entry_count);
5411         if (rc < 0)
5412                 RETURN(rc);
5413
5414         lds->lds_def_comp_cnt = entry_count;
5415         lds->lds_def_striping_is_composite = want_composite;
5416         lds->lds_def_mirror_cnt = mirror_count;
5417
5418         for (i = 0; i < entry_count; i++) {
5419                 struct lod_layout_component *llc = &lds->lds_def_comp_entries[i];
5420                 const char *pool;
5421
5422                 /*
5423                  * reset llc values, llc_stripes is always NULL in the
5424                  * default striping template, llc_pool will be reset
5425                  * later below using lod_set_pool().
5426                  *
5427                  * XXX At this point llc_pool may point to valid (!)
5428                  * kmalloced strings from previous RPCs.
5429                  */
5430                 memset(llc, 0, offsetof(typeof(*llc), llc_pool));
5431
5432                 if (lcm != NULL) {
5433                         v1 = (struct lov_user_md *)((char *)lcm +
5434                                                     lcm->lcm_entries[i].lcme_offset);
5435
5436                         if (want_composite) {
5437                                 llc->llc_extent = lcm->lcm_entries[i].lcme_extent;
5438                                 /* We only inherit certain flags from the layout */
5439                                 llc->llc_flags = lcm->lcm_entries[i].lcme_flags &
5440                                         LCME_TEMPLATE_FLAGS;
5441                         }
5442                 }
5443
5444                 CDEBUG(D_LAYOUT, DFID" magic = %#08x, pattern = %#x, stripe_count = %hu, stripe_size = %u, stripe_offset = %hu, append_pool = '%s', append_stripe_count = %d\n",
5445                        PFID(lu_object_fid(&lo->ldo_obj.do_lu)),
5446                        v1->lmm_magic,
5447                        v1->lmm_pattern,
5448                        v1->lmm_stripe_count,
5449                        v1->lmm_stripe_size,
5450                        v1->lmm_stripe_offset,
5451                        append_pool ?: "",
5452                        append_stripe_count);
5453
5454                 if (!lov_pattern_supported(v1->lmm_pattern) &&
5455                     !(v1->lmm_pattern & LOV_PATTERN_F_RELEASED)) {
5456                         lod_free_def_comp_entries(lds);
5457                         RETURN(-EINVAL);
5458                 }
5459
5460                 llc->llc_stripe_count = v1->lmm_stripe_count;
5461                 llc->llc_stripe_size = v1->lmm_stripe_size;
5462                 llc->llc_stripe_offset = v1->lmm_stripe_offset;
5463                 llc->llc_pattern = v1->lmm_pattern;
5464
5465                 if (append_stripe_count != 0 || append_pool != NULL)
5466                         llc->llc_pattern = LOV_PATTERN_RAID0;
5467
5468                 if (append_stripe_count != 0)
5469                         llc->llc_stripe_count = append_stripe_count;
5470
5471                 pool = NULL;
5472                 if (append_pool != NULL) {
5473                         pool = append_pool;
5474                 } else if (v1->lmm_magic == LOV_USER_MAGIC_V3) {
5475                         /* XXX: sanity check here */
5476                         v3 = (struct lov_user_md_v3 *)v1;
5477                         if (v3->lmm_pool_name[0] != '\0')
5478                                 pool = v3->lmm_pool_name;
5479                 }
5480
5481                 lod_set_pool(&llc->llc_pool, pool);
5482
5483                 if (v1->lmm_magic == LOV_USER_MAGIC_SPECIFIC &&
5484                     append_stripe_count == 0 &&
5485                     append_pool == NULL) {
5486                         v3 = (struct lov_user_md_v3 *)v1;
5487                         rc = lod_comp_copy_ost_lists(llc, v3);
5488                         if (rc)
5489                                 RETURN(rc);
5490                 } else if (llc->llc_ostlist.op_array &&
5491                            llc->llc_ostlist.op_count) {
5492                         for (j = 0; j < llc->llc_ostlist.op_count; j++)
5493                                 llc->llc_ostlist.op_array[j] = -1;
5494                         llc->llc_ostlist.op_count = 0;
5495                 }
5496         }
5497
5498         lds->lds_def_striping_set = 1;
5499         RETURN(rc);
5500 }
5501
5502 static inline void lod_lum2lds(struct lod_default_striping *lds,
5503                                const struct lmv_user_md *lum)
5504 {
5505         lds->lds_dir_def_stripe_count = le32_to_cpu(lum->lum_stripe_count);
5506         lds->lds_dir_def_stripe_offset = le32_to_cpu(lum->lum_stripe_offset);
5507         lds->lds_dir_def_hash_type = le32_to_cpu(lum->lum_hash_type);
5508         lds->lds_dir_def_max_inherit = lum->lum_max_inherit;
5509         lds->lds_dir_def_max_inherit_rr = lum->lum_max_inherit_rr;
5510         lds->lds_dir_def_striping_set = 1;
5511 }
5512
5513 /**
5514  * Get default directory striping.
5515  *
5516  * \param[in] env               execution environment
5517  * \param[in] lo                object
5518  * \param[out] lds              default striping
5519  *
5520  * \retval              0 on success
5521  * \retval              negative if failed
5522  */
5523 static int lod_get_default_lmv_striping(const struct lu_env *env,
5524                                         struct lod_object *lo,
5525                                         struct lod_default_striping *lds)
5526 {
5527         struct lmv_user_md *lmu;
5528         int rc;
5529
5530         lds->lds_dir_def_striping_set = 0;
5531
5532         rc = lod_get_default_lmv_ea(env, lo);
5533         if (rc < 0)
5534                 return rc;
5535
5536         if (rc >= (int)sizeof(*lmu)) {
5537                 struct lod_thread_info *info = lod_env_info(env);
5538
5539                 lmu = info->lti_ea_store;
5540                 lod_lum2lds(lds, lmu);
5541         }
5542
5543         return 0;
5544 }
5545
5546 /**
5547  * Get default striping in the object.
5548  *
5549  * Get object default striping and default directory striping.
5550  *
5551  * \param[in] env               execution environment
5552  * \param[in] lo                object
5553  * \param[out] lds              default striping
5554  *
5555  * \retval              0 on success
5556  * \retval              negative if failed
5557  */
5558 static int lod_get_default_striping(const struct lu_env *env,
5559                                     struct lod_object *lo,
5560                                     struct dt_allocation_hint *ah,
5561                                     struct lod_default_striping *lds)
5562 {
5563         int rc, rc1;
5564
5565         rc = lod_get_default_lov_striping(env, lo, lds, NULL);
5566         if (lds->lds_def_striping_set) {
5567                 struct lod_thread_info *info = lod_env_info(env);
5568                 struct lod_device *d = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
5569
5570                 rc = lod_verify_striping(env, d, lo, &info->lti_buf, false);
5571                 if (rc)
5572                         lds->lds_def_striping_set = 0;
5573         }
5574
5575         if (ah->dah_eadata_is_dmv) {
5576                 lod_lum2lds(lds, ah->dah_eadata);
5577         } else if (ah->dah_dmv_imp_inherit) {
5578                 lds->lds_dir_def_striping_set = 0;
5579         } else {
5580                 rc1 = lod_get_default_lmv_striping(env, lo, lds);
5581                 if (rc == 0 && rc1 < 0)
5582                         rc = rc1;
5583         }
5584
5585         return rc;
5586 }
5587
5588 /**
5589  * Apply default striping on object.
5590  *
5591  * If object striping pattern is not set, set to the one in default striping.
5592  * The default striping is from parent or fs.
5593  *
5594  * \param[in] lo                new object
5595  * \param[in] lds               default striping
5596  * \param[in] mode              new object's mode
5597  */
5598 static void lod_striping_from_default(struct lod_object *lo,
5599                                       const struct lod_default_striping *lds,
5600                                       umode_t mode)
5601 {
5602         struct lod_device *d = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
5603         int i, rc;
5604
5605         if (lds->lds_def_striping_set && S_ISREG(mode)) {
5606                 struct lov_desc *desc = &d->lod_ost_descs.ltd_lov_desc;
5607
5608                 rc = lod_alloc_comp_entries(lo, lds->lds_def_mirror_cnt,
5609                                             lds->lds_def_comp_cnt);
5610                 if (rc != 0)
5611                         return;
5612
5613                 lo->ldo_is_composite = lds->lds_def_striping_is_composite;
5614                 if (lds->lds_def_mirror_cnt > 1)
5615                         lo->ldo_flr_state = LCM_FL_RDONLY;
5616
5617                 for (i = 0; i < lo->ldo_comp_cnt; i++) {
5618                         struct lod_layout_component *obj_comp =
5619                                                 &lo->ldo_comp_entries[i];
5620                         struct lod_layout_component *def_comp =
5621                                                 &lds->lds_def_comp_entries[i];
5622
5623                         CDEBUG(D_LAYOUT,
5624                                "inherit "DFID" file layout from default: flags=%#x size=%u nr=%u offset=%u pattern=%#x pool=%s\n",
5625                                PFID(lu_object_fid(&lo->ldo_obj.do_lu)),
5626                                def_comp->llc_flags,
5627                                def_comp->llc_stripe_size,
5628                                def_comp->llc_stripe_count,
5629                                def_comp->llc_stripe_offset,
5630                                def_comp->llc_pattern,
5631                                def_comp->llc_pool ?: "");
5632
5633                         *obj_comp = *def_comp;
5634                         if (def_comp->llc_pool != NULL) {
5635                                 /* pointer was copied from def_comp */
5636                                 obj_comp->llc_pool = NULL;
5637                                 lod_obj_set_pool(lo, i, def_comp->llc_pool);
5638                         }
5639
5640                         /* copy ost list */
5641                         if (def_comp->llc_ostlist.op_array &&
5642                             def_comp->llc_ostlist.op_count) {
5643                                 OBD_ALLOC(obj_comp->llc_ostlist.op_array,
5644                                           obj_comp->llc_ostlist.op_size);
5645                                 if (!obj_comp->llc_ostlist.op_array)
5646                                         return;
5647                                 memcpy(obj_comp->llc_ostlist.op_array,
5648                                        def_comp->llc_ostlist.op_array,
5649                                        obj_comp->llc_ostlist.op_size);
5650                         } else if (def_comp->llc_ostlist.op_array) {
5651                                 obj_comp->llc_ostlist.op_array = NULL;
5652                         }
5653
5654                         /*
5655                          * Don't initialize these fields for plain layout
5656                          * (v1/v3) here, they are inherited in the order of
5657                          * 'parent' -> 'fs default (root)' -> 'global default
5658                          * values for stripe_count & stripe_size'.
5659                          *
5660                          * see lod_ah_init().
5661                          */
5662                         if (!lo->ldo_is_composite)
5663                                 continue;
5664
5665                         lod_adjust_stripe_info(obj_comp, desc, 0);
5666                 }
5667         } else if (lds->lds_dir_def_striping_set && S_ISDIR(mode)) {
5668                 if (lo->ldo_dir_stripe_count == 0)
5669                         lo->ldo_dir_stripe_count =
5670                                 lds->lds_dir_def_stripe_count;
5671                 if (lo->ldo_dir_stripe_offset == -1)
5672                         lo->ldo_dir_stripe_offset =
5673                                 lds->lds_dir_def_stripe_offset;
5674                 if (lo->ldo_dir_hash_type == LMV_HASH_TYPE_UNKNOWN)
5675                         lo->ldo_dir_hash_type = lds->lds_dir_def_hash_type;
5676
5677                 CDEBUG(D_LAYOUT,
5678                        "inherit "DFID" dir layout from default: count=%hu offset=%u hash_type=%x\n",
5679                        PFID(lu_object_fid(&lo->ldo_obj.do_lu)),
5680                        lo->ldo_dir_stripe_count, lo->ldo_dir_stripe_offset,
5681                        lo->ldo_dir_hash_type);
5682         }
5683 }
5684
5685 static inline bool lod_need_inherit_more(struct lod_object *lo, bool from_root,
5686                                          const char *append_pool)
5687 {
5688         struct lod_layout_component *lod_comp;
5689
5690         if (lo->ldo_comp_cnt == 0)
5691                 return true;
5692
5693         if (lo->ldo_is_composite)
5694                 return false;
5695
5696         lod_comp = &lo->ldo_comp_entries[0];
5697
5698         if (lod_comp->llc_stripe_count <= 0 ||
5699             lod_comp->llc_stripe_size <= 0)
5700                 return true;
5701
5702         if (from_root && (lod_comp->llc_pool == NULL ||
5703                           lod_comp->llc_stripe_offset == LOV_OFFSET_DEFAULT))
5704                 return true;
5705
5706         if (append_pool && append_pool[0])
5707                 return true;
5708
5709         return false;
5710 }
5711
5712 /**
5713  * Implementation of dt_object_operations::do_ah_init.
5714  *
5715  * This method is used to make a decision on the striping configuration for the
5716  * object being created. It can be taken from the \a parent object if it exists,
5717  * or filesystem's default. The resulting configuration (number of stripes,
5718  * stripe size/offset, pool name, hash_type, etc.) is stored in the object
5719  * itself and will be used by the methods like ->doo_declare_create().
5720  *
5721  * \see dt_object_operations::do_ah_init() in the API description for details.
5722  */
5723 static void lod_ah_init(const struct lu_env *env,
5724                         struct dt_allocation_hint *ah,
5725                         struct dt_object *parent,
5726                         struct dt_object *child,
5727                         umode_t child_mode)
5728 {
5729         struct lod_device *d = lu2lod_dev(child->do_lu.lo_dev);
5730         struct lod_thread_info *info = lod_env_info(env);
5731         struct lod_default_striping *lds = lod_lds_buf_get(env);
5732         struct dt_object *nextp = NULL;
5733         struct dt_object *nextc;
5734         struct lod_object *lp = NULL;
5735         struct lod_object *lc;
5736         struct lov_desc *desc;
5737         struct lod_layout_component *lod_comp;
5738         int rc;
5739         ENTRY;
5740
5741         LASSERT(child);
5742
5743         if (ah->dah_append_stripe_count == -1)
5744                 ah->dah_append_stripe_count =
5745                         d->lod_ost_descs.ltd_lov_desc.ld_tgt_count;
5746
5747         if (likely(parent)) {
5748                 nextp = dt_object_child(parent);
5749                 lp = lod_dt_obj(parent);
5750         }
5751
5752         nextc = dt_object_child(child);
5753         lc = lod_dt_obj(child);
5754
5755         LASSERT(!lod_obj_is_striped(child));
5756         /* default layout template may have been set on the regular file
5757          * when this is called from mdd_create_data() */
5758         if (S_ISREG(child_mode))
5759                 lod_free_comp_entries(lc);
5760
5761         if (!dt_object_exists(nextc))
5762                 nextc->do_ops->do_ah_init(env, ah, nextp, nextc, child_mode);
5763
5764         if (S_ISDIR(child_mode)) {
5765                 const struct lmv_user_md_v1 *lum1 = ah->dah_eadata;
5766
5767                 /* other default values are 0 */
5768                 lc->ldo_dir_stripe_offset = LMV_OFFSET_DEFAULT;
5769
5770                 /* no default striping configuration is needed for
5771                  * foreign dirs
5772                  */
5773                 if (ah->dah_eadata != NULL && ah->dah_eadata_len != 0 &&
5774                     le32_to_cpu(lum1->lum_magic) == LMV_MAGIC_FOREIGN) {
5775                         lc->ldo_is_foreign = true;
5776                         /* keep stripe_count 0 and stripe_offset -1 */
5777                         CDEBUG(D_INFO, "no default striping for foreign dir\n");
5778                         RETURN_EXIT;
5779                 }
5780
5781                 if (likely(lp != NULL))
5782                         lod_get_default_striping(env, lp, ah, lds);
5783
5784                 /* It should always honour the specified stripes */
5785                 if (ah->dah_eadata && ah->dah_eadata_len &&
5786                     !ah->dah_eadata_is_dmv &&
5787                     (le32_to_cpu(lum1->lum_magic) == LMV_USER_MAGIC ||
5788                      le32_to_cpu(lum1->lum_magic) == LMV_USER_MAGIC_SPECIFIC ||
5789                      le32_to_cpu(lum1->lum_magic) == LMV_MAGIC_V1)) {
5790                         lc->ldo_dir_stripe_count =
5791                                 le32_to_cpu(lum1->lum_stripe_count);
5792                         lc->ldo_dir_stripe_offset =
5793                                 le32_to_cpu(lum1->lum_stripe_offset);
5794                         lc->ldo_dir_hash_type =
5795                                 le32_to_cpu(lum1->lum_hash_type);
5796                         CDEBUG(D_INFO,
5797                                "set dirstripe: count %hu, offset %d, hash %x\n",
5798                                 lc->ldo_dir_stripe_count,
5799                                 (int)lc->ldo_dir_stripe_offset,
5800                                 lc->ldo_dir_hash_type);
5801
5802                         if (d->lod_mdt_descs.ltd_lmv_desc.ld_active_tgt_count &&
5803                             lc->ldo_dir_stripe_count < 2 &&
5804                             lum1->lum_max_inherit != LMV_INHERIT_NONE) {
5805                                 /* when filesystem-wide default LMV is set, dirs
5806                                  * will be created on MDT by space usage, but if
5807                                  * dir is created with "lfs mkdir -c 1 ...", its
5808                                  * subdirs should be kept on the same MDT. To
5809                                  * guarantee this, set default LMV for such dir.
5810                                  */
5811                                 lds->lds_dir_def_stripe_count =
5812                                         le32_to_cpu(lum1->lum_stripe_count);
5813                                 /* if "-1" stripe offset is set, save current
5814                                  * MDT index in default LMV.
5815                                  */
5816                                 if (le32_to_cpu(lum1->lum_stripe_offset) ==
5817                                     LMV_OFFSET_DEFAULT)
5818                                         lds->lds_dir_def_stripe_offset =
5819                                                 lod2lu_dev(d)->ld_site->ld_seq_site->ss_node_id;
5820                                 else
5821                                         lds->lds_dir_def_stripe_offset =
5822                                                 le32_to_cpu(lum1->lum_stripe_offset);
5823                                 lds->lds_dir_def_hash_type =
5824                                         le32_to_cpu(lum1->lum_hash_type);
5825                                 lds->lds_dir_def_max_inherit =
5826                                         lum1->lum_max_inherit;
5827                                 /* it will be decreased by 1 later in setting */
5828                                 if (lum1->lum_max_inherit >= LMV_INHERIT_END &&
5829                                     lum1->lum_max_inherit < LMV_INHERIT_MAX)
5830                                         lds->lds_dir_def_max_inherit++;
5831                                 lds->lds_dir_def_max_inherit_rr =
5832                                         lum1->lum_max_inherit_rr;
5833                                 lds->lds_dir_def_striping_set = 1;
5834                                 /* don't inherit LOV from ROOT */
5835                                 if (lds->lds_def_striping_set &&
5836                                     fid_is_root(lod_object_fid(lp)))
5837                                         lds->lds_def_striping_set = 0;
5838                                 lc->ldo_def_striping = lds;
5839                         } else if (lds->lds_def_striping_set &&
5840                                    !fid_is_root(lod_object_fid(lp))) {
5841                                 /* don't inherit default LMV for "lfs mkdir" */
5842                                 lds->lds_dir_def_striping_set = 0;
5843                                 lc->ldo_def_striping = lds;
5844                         }
5845                 } else {
5846                         /* inherit default striping except ROOT */
5847                         if ((lds->lds_def_striping_set ||
5848                              lds->lds_dir_def_striping_set) &&
5849                             !fid_is_root(lod_object_fid(lp)))
5850                                 lc->ldo_def_striping = lds;
5851
5852                         /* transfer defaults LMV to new directory */
5853                         lod_striping_from_default(lc, lds, child_mode);
5854
5855                         /* set count 0 to create normal directory */
5856                         if (lc->ldo_dir_stripe_count == 1)
5857                                 lc->ldo_dir_stripe_count = 0;
5858
5859                         /* do not save default LMV on server */
5860                         if (ah->dah_dmv_imp_inherit) {
5861                                 lds->lds_dir_def_striping_set = 0;
5862                                 if (!lds->lds_def_striping_set)
5863                                         lc->ldo_def_striping = NULL;
5864                         }
5865                 }
5866
5867                 /* shrink the stripe count to max_mdt_stripecount if it is -1
5868                  * and max_mdt_stripecount is not 0
5869                  */
5870                 if (lc->ldo_dir_stripe_count == (__u16)(-1) &&
5871                     d->lod_max_mdt_stripecount)
5872                         lc->ldo_dir_stripe_count = d->lod_max_mdt_stripecount;
5873
5874                 /* shrink the stripe_count to the avaible MDT count */
5875                 if (lc->ldo_dir_stripe_count > d->lod_remote_mdt_count + 1 &&
5876                     !CFS_FAIL_CHECK(OBD_FAIL_LARGE_STRIPE)) {
5877                         lc->ldo_dir_stripe_count = d->lod_remote_mdt_count + 1;
5878                         if (lc->ldo_dir_stripe_count == 1)
5879                                 lc->ldo_dir_stripe_count = 0;
5880                 }
5881
5882                 if (!lmv_is_known_hash_type(lc->ldo_dir_hash_type))
5883                         lc->ldo_dir_hash_type =
5884                                 (lc->ldo_dir_hash_type & LMV_HASH_FLAG_KNOWN) |
5885                                 d->lod_mdt_descs.ltd_lmv_desc.ld_pattern;
5886
5887                 /* make sure all fscrypt metadata stays on same mdt */
5888                 if (child->do_lu.lo_header->loh_attr & LOHA_FSCRYPT_MD) {
5889                         lc->ldo_dir_stripe_count = 0;
5890                         lds->lds_dir_def_stripe_offset =
5891                                 lod2lu_dev(d)->ld_site->ld_seq_site->ss_node_id;
5892                         lds->lds_dir_def_striping_set = 1;
5893                         lc->ldo_def_striping = lds;
5894                 }
5895
5896                 CDEBUG(D_INFO, "final dir stripe_count=%hu offset=%d hash=%u\n",
5897                        lc->ldo_dir_stripe_count,
5898                        (int)lc->ldo_dir_stripe_offset, lc->ldo_dir_hash_type);
5899
5900                 RETURN_EXIT;
5901         }
5902
5903         /* child object regular file*/
5904
5905         if (!lod_object_will_be_striped(S_ISREG(child_mode),
5906                                         lu_object_fid(&child->do_lu)))
5907                 RETURN_EXIT;
5908
5909         /* If object is going to be striped over OSTs, transfer default
5910          * striping information to the child, so that we can use it
5911          * during declaration and creation.
5912          *
5913          * Try from the parent first.
5914          */
5915         if (likely(lp != NULL)) {
5916                 rc = lod_get_default_lov_striping(env, lp, lds, ah);
5917                 if (rc == 0 && lds->lds_def_striping_set) {
5918                         rc = lod_verify_striping(env, d, lp, &info->lti_buf,
5919                                                  false);
5920                         if (rc == 0)
5921                                 lod_striping_from_default(lc, lds, child_mode);
5922                 }
5923         }
5924
5925         /* Initialize lod_device::lod_md_root object reference */
5926         if (d->lod_md_root == NULL) {
5927                 struct dt_object *root;
5928                 struct lod_object *lroot;
5929
5930                 lu_root_fid(&info->lti_fid);
5931                 root = dt_locate(env, &d->lod_dt_dev, &info->lti_fid);
5932                 if (!IS_ERR(root)) {
5933                         lroot = lod_dt_obj(root);
5934
5935                         spin_lock(&d->lod_lock);
5936                         if (d->lod_md_root != NULL)
5937                                 dt_object_put(env, &d->lod_md_root->ldo_obj);
5938                         d->lod_md_root = lroot;
5939                         spin_unlock(&d->lod_lock);
5940                 }
5941         }
5942
5943         /* try inherit layout from the root object (fs default) when:
5944          *  - parent does not have default layout; or
5945          *  - parent has plain(v1/v3) default layout, and some attributes
5946          *    are not specified in the default layout;
5947          */
5948         if (d->lod_md_root != NULL &&
5949             lod_need_inherit_more(lc, true, ah->dah_append_pool)) {
5950                 rc = lod_get_default_lov_striping(env, d->lod_md_root, lds,
5951                                                   ah);
5952                 if (rc || !lds->lds_def_striping_set)
5953                         goto out;
5954
5955                 rc = lod_verify_striping(env, d, d->lod_md_root, &info->lti_buf,
5956                                          false);
5957                 if (rc)
5958                         goto out;
5959
5960                 if (lc->ldo_comp_cnt == 0) {
5961                         lod_striping_from_default(lc, lds, child_mode);
5962                 } else if (!lds->lds_def_striping_is_composite) {
5963                         struct lod_layout_component *def_comp;
5964
5965                         LASSERT(!lc->ldo_is_composite);
5966                         lod_comp = &lc->ldo_comp_entries[0];
5967                         def_comp = &lds->lds_def_comp_entries[0];
5968
5969                         if (lod_comp->llc_stripe_count <= 0)
5970                                 lod_comp->llc_stripe_count =
5971                                         def_comp->llc_stripe_count;
5972                         if (lod_comp->llc_stripe_size <= 0)
5973                                 lod_comp->llc_stripe_size =
5974                                         def_comp->llc_stripe_size;
5975                         if (lod_comp->llc_stripe_offset == LOV_OFFSET_DEFAULT &&
5976                             (!lod_comp->llc_pool || !lod_comp->llc_pool[0]))
5977                                 lod_comp->llc_stripe_offset =
5978                                         def_comp->llc_stripe_offset;
5979                         if (lod_comp->llc_pool == NULL)
5980                                 lod_obj_set_pool(lc, 0, def_comp->llc_pool);
5981                 }
5982         }
5983 out:
5984         /*
5985          * fs default striping may not be explicitly set, or historically set
5986          * in config log, use them.
5987          */
5988         if (lod_need_inherit_more(lc, false, ah->dah_append_pool)) {
5989                 if (lc->ldo_comp_cnt == 0) {
5990                         rc = lod_alloc_comp_entries(lc, 0, 1);
5991                         if (rc)
5992                                 /* fail to allocate memory, will create a
5993                                  * non-striped file. */
5994                                 RETURN_EXIT;
5995                         lc->ldo_is_composite = 0;
5996                         lod_comp = &lc->ldo_comp_entries[0];
5997                         lod_comp->llc_stripe_offset = LOV_OFFSET_DEFAULT;
5998                 }
5999                 LASSERT(!lc->ldo_is_composite);
6000                 lod_comp = &lc->ldo_comp_entries[0];
6001                 desc = &d->lod_ost_descs.ltd_lov_desc;
6002                 lod_adjust_stripe_info(lod_comp, desc,
6003                                        ah->dah_append_stripe_count);
6004                 if (ah->dah_append_pool && ah->dah_append_pool[0])
6005                         lod_obj_set_pool(lc, 0, ah->dah_append_pool);
6006         }
6007
6008         EXIT;
6009 }
6010
6011 /**
6012  * Size initialization on late striping.
6013  *
6014  * Propagate the size of a truncated object to a deferred striping.
6015  * This function handles a special case when truncate was done on a
6016  * non-striped object and now while the striping is being created
6017  * we can't lose that size, so we have to propagate it to the stripes
6018  * being created.
6019  *
6020  * \param[in] env       execution environment
6021  * \param[in] dt        object
6022  * \param[in] th        transaction handle
6023  *
6024  * \retval              0 on success
6025  * \retval              negative if failed
6026  */
6027 static int lod_declare_init_size(const struct lu_env *env,
6028                                  struct dt_object *dt, struct thandle *th)
6029 {
6030         struct dt_object        *next = dt_object_child(dt);
6031         struct lod_object       *lo = lod_dt_obj(dt);
6032         struct dt_object        **objects = NULL;
6033         struct lu_attr  *attr = &lod_env_info(env)->lti_attr;
6034         uint64_t        size, offs;
6035         int     i, rc, stripe, stripe_count = 0, stripe_size = 0;
6036         struct lu_extent size_ext;
6037         ENTRY;
6038
6039         if (!lod_obj_is_striped(dt))
6040                 RETURN(0);
6041
6042         rc = dt_attr_get(env, next, attr);
6043         LASSERT(attr->la_valid & LA_SIZE);
6044         if (rc)
6045                 RETURN(rc);
6046
6047         size = attr->la_size;
6048         if (size == 0)
6049                 RETURN(0);
6050
6051         size_ext = (typeof(size_ext)){ .e_start = size - 1, .e_end = size };
6052         for (i = 0; i < lo->ldo_comp_cnt; i++) {
6053                 struct lod_layout_component *lod_comp;
6054                 struct lu_extent *extent;
6055
6056                 lod_comp = &lo->ldo_comp_entries[i];
6057
6058                 if (lod_comp->llc_stripe == NULL)
6059                         continue;
6060
6061                 extent = &lod_comp->llc_extent;
6062                 CDEBUG(D_INFO, "%lld "DEXT"\n", size, PEXT(extent));
6063                 if (!lo->ldo_is_composite ||
6064                     lu_extent_is_overlapped(extent, &size_ext)) {
6065                         objects = lod_comp->llc_stripe;
6066                         stripe_count = lod_comp->llc_stripe_count;
6067                         stripe_size = lod_comp->llc_stripe_size;
6068
6069                         /* next mirror */
6070                         if (stripe_count == 0)
6071                                 continue;
6072
6073                         LASSERT(objects != NULL && stripe_size != 0);
6074                         do_div(size, stripe_size);
6075                         stripe = do_div(size, stripe_count);
6076                         LASSERT(objects[stripe] != NULL);
6077
6078                         size = size * stripe_size;
6079                         offs = attr->la_size;
6080                         size += do_div(offs, stripe_size);
6081
6082                         attr->la_valid = LA_SIZE;
6083                         attr->la_size = size;
6084
6085                         rc = lod_sub_declare_attr_set(env, objects[stripe],
6086                                                       attr, th);
6087                 }
6088         }
6089
6090         RETURN(rc);
6091 }
6092
6093 /**
6094  * Declare creation of striped object.
6095  *
6096  * The function declares creation stripes for a regular object. The function
6097  * also declares whether the stripes will be created with non-zero size if
6098  * previously size was set non-zero on the master object. If object \a dt is
6099  * not local, then only fully defined striping can be applied in \a lovea.
6100  * Otherwise \a lovea can be in the form of pattern, see lod_qos_parse_config()
6101  * for the details.
6102  *
6103  * \param[in] env       execution environment
6104  * \param[in] dt        object
6105  * \param[in] attr      attributes the stripes will be created with
6106  * \param[in] lovea     a buffer containing striping description
6107  * \param[in] th        transaction handle
6108  *
6109  * \retval              0 on success
6110  * \retval              negative if failed
6111  */
6112 int lod_declare_striped_create(const struct lu_env *env, struct dt_object *dt,
6113                                struct lu_attr *attr,
6114                                const struct lu_buf *lovea, struct thandle *th)
6115 {
6116         struct lod_thread_info  *info = lod_env_info(env);
6117         struct dt_object        *next = dt_object_child(dt);
6118         struct lod_object       *lo = lod_dt_obj(dt);
6119         int                      rc;
6120         ENTRY;
6121
6122         if (CFS_FAIL_CHECK(OBD_FAIL_MDS_ALLOC_OBDO))
6123                 GOTO(out, rc = -ENOMEM);
6124
6125         if (!dt_object_remote(next)) {
6126                 /* choose OST and generate appropriate objects */
6127                 rc = lod_prepare_create(env, lo, attr, lovea, th);
6128                 if (rc)
6129                         GOTO(out, rc);
6130
6131                 /*
6132                  * declare storage for striping data
6133                  */
6134                 info->lti_buf.lb_len = lod_comp_md_size(lo, false);
6135         } else {
6136                 /* LOD can not choose OST objects for remote objects, i.e.
6137                  * stripes must be ready before that. Right now, it can only
6138                  * happen during migrate, i.e. migrate process needs to create
6139                  * remote regular file (mdd_migrate_create), then the migrate
6140                  * process will provide stripeEA. */
6141                 LASSERT(lovea != NULL);
6142                 info->lti_buf = *lovea;
6143         }
6144
6145         rc = lod_sub_declare_xattr_set(env, next, &info->lti_buf,
6146                                        XATTR_NAME_LOV, 0, th);
6147         if (rc)
6148                 GOTO(out, rc);
6149
6150         /*
6151          * if striping is created with local object's size > 0,
6152          * we have to propagate this size to specific object
6153          * the case is possible only when local object was created previously
6154          */
6155         if (dt_object_exists(next))
6156                 rc = lod_declare_init_size(env, dt, th);
6157
6158 out:
6159         /* failed to create striping or to set initial size, let's reset
6160          * config so that others don't get confused */
6161         if (rc)
6162                 lod_striping_free(env, lo);
6163
6164         RETURN(rc);
6165 }
6166
6167 /*
6168  * Whether subdirectories under \a dt should be created on MDTs by space QoS
6169  *
6170  * If LMV_HASH_FLAG_SPACE is set on directory default layout, its subdirectories
6171  * should be created on MDT by space QoS.
6172  *
6173  * \param[in] env       execution environment
6174  * \param[in] dev       lu device
6175  * \param[in] dt        object
6176  *
6177  * \retval              1 if directory should create subdir by space usage
6178  * \retval              0 if not
6179  * \retval              -ev if failed
6180  */
6181 static inline int dt_object_qos_mkdir(const struct lu_env *env,
6182                                       struct lu_device *dev,
6183                                       struct dt_object *dt)
6184 {
6185         struct lod_thread_info *info = lod_env_info(env);
6186         struct lu_object *obj;
6187         struct lod_object *lo;
6188         struct lmv_user_md *lmu;
6189         int rc;
6190
6191         obj = lu_object_find_slice(env, dev, lu_object_fid(&dt->do_lu), NULL);
6192         if (IS_ERR(obj))
6193                 return PTR_ERR(obj);
6194
6195         lo = lu2lod_obj(obj);
6196
6197         rc = lod_get_default_lmv_ea(env, lo);
6198         dt_object_put(env, dt);
6199         if (rc <= 0)
6200                 return rc;
6201
6202         if (rc < (int)sizeof(*lmu))
6203                 return -EINVAL;
6204
6205         lmu = info->lti_ea_store;
6206         return le32_to_cpu(lmu->lum_stripe_offset) == LMV_OFFSET_DEFAULT;
6207 }
6208
6209 /**
6210  * Implementation of dt_object_operations::do_declare_create.
6211  *
6212  * The method declares creation of a new object. If the object will be striped,
6213  * then helper functions are called to find FIDs for the stripes, declare
6214  * creation of the stripes and declare initialization of the striping
6215  * information to be stored in the master object.
6216  *
6217  * \see dt_object_operations::do_declare_create() in the API description
6218  * for details.
6219  */
6220 static int lod_declare_create(const struct lu_env *env, struct dt_object *dt,
6221                               struct lu_attr *attr,
6222                               struct dt_allocation_hint *hint,
6223                               struct dt_object_format *dof, struct thandle *th)
6224 {
6225         struct dt_object   *next = dt_object_child(dt);
6226         struct lod_object  *lo = lod_dt_obj(dt);
6227         int                 rc;
6228         ENTRY;
6229
6230         LASSERT(dof);
6231         LASSERT(attr);
6232         LASSERT(th);
6233
6234         /*
6235          * first of all, we declare creation of local object
6236          */
6237         rc = lod_sub_declare_create(env, next, attr, hint, dof, th);
6238         if (rc != 0)
6239                 GOTO(out, rc);
6240
6241         /*
6242          * it's lod_ah_init() that has decided the object will be striped
6243          */
6244         if (dof->dof_type == DFT_REGULAR) {
6245                 /* callers don't want stripes */
6246                 /* XXX: all tricky interactions with ->ah_make_hint() decided
6247                  * to use striping, then ->declare_create() behaving differently
6248                  * should be cleaned */
6249                 if (dof->u.dof_reg.striped != 0)
6250                         rc = lod_declare_striped_create(env, dt, attr,
6251                                                         NULL, th);
6252         } else if (dof->dof_type == DFT_DIR) {
6253                 struct seq_server_site *ss;
6254                 struct lu_buf buf = { NULL };
6255
6256                 ss = lu_site2seq(dt->do_lu.lo_dev->ld_site);
6257
6258                 /* If the parent has default stripeEA, and client
6259                  * did not find it before sending create request,
6260                  * then MDT will return -EREMOTE, and client will
6261                  * retrieve the default stripeEA and re-create the
6262                  * sub directory.
6263                  *
6264                  * Note: if dah_eadata != NULL, it means creating the
6265                  * striped directory with specified stripeEA, then it
6266                  * should ignore the default stripeEA */
6267                 if (hint != NULL && hint->dah_eadata == NULL) {
6268                         if (CFS_FAIL_CHECK(OBD_FAIL_MDS_STALE_DIR_LAYOUT))
6269                                 GOTO(out, rc = -EREMOTE);
6270
6271                         if (lo->ldo_dir_stripe_offset != LMV_OFFSET_DEFAULT &&
6272                             lo->ldo_dir_stripe_offset != ss->ss_node_id) {
6273                                 struct lod_device *lod;
6274                                 struct lu_tgt_desc *mdt = NULL;
6275                                 bool found_mdt = false;
6276
6277                                 lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
6278                                 lod_foreach_mdt(lod, mdt) {
6279                                         if (mdt->ltd_index ==
6280                                                 lo->ldo_dir_stripe_offset) {
6281                                                 found_mdt = true;
6282                                                 break;
6283                                         }
6284                                 }
6285
6286                                 /* If the MDT indicated by stripe_offset can be
6287                                  * found, then tell client to resend the create
6288                                  * request to the correct MDT, otherwise return
6289                                  * error to client */
6290                                 if (found_mdt)
6291                                         GOTO(out, rc = -EREMOTE);
6292                                 else
6293                                         GOTO(out, rc = -EINVAL);
6294                         }
6295                 } else if (hint && hint->dah_eadata) {
6296                         buf.lb_buf = (void *)hint->dah_eadata;
6297                         buf.lb_len = hint->dah_eadata_len;
6298                 }
6299
6300                 rc = lod_declare_dir_striping_create(env, dt, attr, &buf, dof,
6301                                                      th);
6302         }
6303 out:
6304         /* failed to create striping or to set initial size, let's reset
6305          * config so that others don't get confused */
6306         if (rc)
6307                 lod_striping_free(env, lo);
6308         RETURN(rc);
6309 }
6310
6311 /**
6312  * Generate component ID for new created component.
6313  *
6314  * \param[in] lo                LOD object
6315  * \param[in] comp_idx          index of ldo_comp_entries
6316  *
6317  * \retval                      component ID on success
6318  * \retval                      LCME_ID_INVAL on failure
6319  */
6320 static __u32 lod_gen_component_id(struct lod_object *lo,
6321                                   int mirror_id, int comp_idx)
6322 {
6323         struct lod_layout_component *lod_comp;
6324         __u32   id, start, end;
6325         int     i;
6326
6327         LASSERT(lo->ldo_comp_entries[comp_idx].llc_id == LCME_ID_INVAL);
6328
6329         lod_obj_inc_layout_gen(lo);
6330         id = lo->ldo_layout_gen;
6331         if (likely(id <= SEQ_ID_MAX))
6332                 RETURN(pflr_id(mirror_id, id & SEQ_ID_MASK));
6333
6334         /* Layout generation wraps, need to check collisions. */
6335         start = id & SEQ_ID_MASK;
6336         end = SEQ_ID_MAX;
6337 again:
6338         for (id = start; id <= end; id++) {
6339                 for (i = 0; i < lo->ldo_comp_cnt; i++) {
6340                         lod_comp = &lo->ldo_comp_entries[i];
6341                         if (pflr_id(mirror_id, id) == lod_comp->llc_id)
6342                                 break;
6343                 }
6344                 /* Found the ununsed ID */
6345                 if (i == lo->ldo_comp_cnt)
6346                         RETURN(pflr_id(mirror_id, id));
6347         }
6348
6349         if (end == SEQ_ID_MAX) {
6350                 end = min_t(__u32, start, SEQ_ID_MAX) - 1;
6351                 start = 1;
6352                 goto again;
6353         }
6354
6355         RETURN(LCME_ID_INVAL);
6356 }
6357
6358 /**
6359  * Creation of a striped regular object.
6360  *
6361  * The function is called to create the stripe objects for a regular
6362  * striped file. This can happen at the initial object creation or
6363  * when the caller asks LOD to do so using ->do_xattr_set() method
6364  * (so called late striping). Notice all the information are already
6365  * prepared in the form of the list of objects (ldo_stripe field).
6366  * This is done during declare phase.
6367  *
6368  * \param[in] env       execution environment
6369  * \param[in] dt        object
6370  * \param[in] attr      attributes the stripes will be created with
6371  * \param[in] dof       format of stripes (see OSD API description)
6372  * \param[in] th        transaction handle
6373  *
6374  * \retval              0 on success
6375  * \retval              negative if failed
6376  */
6377 int lod_striped_create(const struct lu_env *env, struct dt_object *dt,
6378                        struct lu_attr *attr, struct dt_object_format *dof,
6379                        struct thandle *th)
6380 {
6381         struct lod_layout_component     *lod_comp;
6382         struct lod_object       *lo = lod_dt_obj(dt);
6383         __u16   mirror_id;
6384         int     rc = 0, i, j;
6385         ENTRY;
6386
6387         mutex_lock(&lo->ldo_layout_mutex);
6388
6389         LASSERT((lo->ldo_comp_cnt != 0 && lo->ldo_comp_entries != NULL) ||
6390                 lo->ldo_is_foreign);
6391
6392         mirror_id = 0; /* non-flr file's mirror_id is 0 */
6393         if (lo->ldo_mirror_count > 1) {
6394                 for (i = 0; i < lo->ldo_comp_cnt; i++) {
6395                         lod_comp = &lo->ldo_comp_entries[i];
6396                         if (lod_comp->llc_id != LCME_ID_INVAL &&
6397                             mirror_id_of(lod_comp->llc_id) > mirror_id)
6398                                 mirror_id = mirror_id_of(lod_comp->llc_id);
6399                 }
6400         }
6401
6402         /* create all underlying objects */
6403         for (i = 0; i < lo->ldo_comp_cnt; i++) {
6404                 lod_comp = &lo->ldo_comp_entries[i];
6405
6406                 if (lod_comp->llc_id == LCME_ID_INVAL) {
6407                         /* only the component of FLR layout with more than 1
6408                          * mirror has mirror ID in its component ID.
6409                          */
6410                         if (lod_comp->llc_extent.e_start == 0 &&
6411                             lo->ldo_mirror_count > 1)
6412                                 ++mirror_id;
6413
6414                         lod_comp->llc_id = lod_gen_component_id(lo,
6415                                                                 mirror_id, i);
6416                         if (lod_comp->llc_id == LCME_ID_INVAL)
6417                                 GOTO(out, rc = -ERANGE);
6418                 }
6419
6420                 if (lod_comp_inited(lod_comp))
6421                         continue;
6422
6423                 if (lod_comp->llc_magic == LOV_MAGIC_FOREIGN) {
6424                         lod_comp_set_init(lod_comp);
6425                         continue;
6426                 }
6427
6428                 if (lod_comp->llc_pattern & LOV_PATTERN_F_RELEASED)
6429                         lod_comp_set_init(lod_comp);
6430
6431                 if (lov_pattern(lod_comp->llc_pattern) & LOV_PATTERN_MDT)
6432                         lod_comp_set_init(lod_comp);
6433
6434                 if (lod_comp->llc_stripe == NULL)
6435                         continue;
6436
6437                 LASSERT(lod_comp->llc_stripe_count);
6438                 for (j = 0; j < lod_comp->llc_stripe_count; j++) {
6439                         struct dt_object *object = lod_comp->llc_stripe[j];
6440                         LASSERT(object != NULL);
6441                         rc = lod_sub_create(env, object, attr, NULL, dof, th);
6442                         if (rc)
6443                                 GOTO(out, rc);
6444                 }
6445                 lod_comp_set_init(lod_comp);
6446         }
6447
6448         rc = lod_fill_mirrors(lo);
6449         if (rc)
6450                 GOTO(out, rc);
6451
6452         lo->ldo_comp_cached = 1;
6453
6454         rc = lod_generate_and_set_lovea(env, lo, th);
6455         if (rc)
6456                 GOTO(out, rc);
6457
6458         mutex_unlock(&lo->ldo_layout_mutex);
6459
6460         RETURN(0);
6461
6462 out:
6463         lod_striping_free_nolock(env, lo);
6464         mutex_unlock(&lo->ldo_layout_mutex);
6465
6466         RETURN(rc);
6467 }
6468
6469 static inline bool lod_obj_is_dom(struct dt_object *dt)
6470 {
6471         struct lod_object *lo = lod_dt_obj(dt);
6472
6473         if (!dt_object_exists(dt_object_child(dt)))
6474                 return false;
6475
6476         if (S_ISDIR(dt->do_lu.lo_header->loh_attr))
6477                 return false;
6478
6479         if (!lo->ldo_comp_cnt)
6480                 return false;
6481
6482         return (lov_pattern(lo->ldo_comp_entries[0].llc_pattern) &
6483                 LOV_PATTERN_MDT);
6484 }
6485
6486 /**
6487  * Implementation of dt_object_operations::do_create.
6488  *
6489  * If any of preceeding methods (like ->do_declare_create(),
6490  * ->do_ah_init(), etc) chose to create a striped object,
6491  * then this method will create the master and the stripes.
6492  *
6493  * \see dt_object_operations::do_create() in the API description for details.
6494  */
6495 static int lod_create(const struct lu_env *env, struct dt_object *dt,
6496                       struct lu_attr *attr, struct dt_allocation_hint *hint,
6497                       struct dt_object_format *dof, struct thandle *th)
6498 {
6499         int                 rc;
6500         ENTRY;
6501
6502         /* create local object */
6503         rc = lod_sub_create(env, dt_object_child(dt), attr, hint, dof, th);
6504         if (rc != 0)
6505                 RETURN(rc);
6506
6507         if (S_ISREG(dt->do_lu.lo_header->loh_attr) &&
6508             (lod_obj_is_striped(dt) || lod_obj_is_dom(dt)) &&
6509             dof->u.dof_reg.striped != 0) {
6510                 LASSERT(lod_dt_obj(dt)->ldo_comp_cached == 0);
6511                 rc = lod_striped_create(env, dt, attr, dof, th);
6512         }
6513
6514         RETURN(rc);
6515 }
6516
6517 static inline int
6518 lod_obj_stripe_destroy_cb(const struct lu_env *env, struct lod_object *lo,
6519                           struct dt_object *dt, struct thandle *th,
6520                           int comp_idx, int stripe_idx,
6521                           struct lod_obj_stripe_cb_data *data)
6522 {
6523         if (data->locd_declare)
6524                 return lod_sub_declare_destroy(env, dt, th);
6525
6526         if (!CFS_FAIL_CHECK(OBD_FAIL_LFSCK_LOST_SPEOBJ) ||
6527             stripe_idx == cfs_fail_val)
6528                 return lod_sub_destroy(env, dt, th);
6529
6530         return 0;
6531 }
6532
6533 /**
6534  * Implementation of dt_object_operations::do_declare_destroy.
6535  *
6536  * If the object is a striped directory, then the function declares reference
6537  * removal from the master object (this is an index) to the stripes and declares
6538  * destroy of all the stripes. In all the cases, it declares an intention to
6539  * destroy the object itself.
6540  *
6541  * \see dt_object_operations::do_declare_destroy() in the API description
6542  * for details.
6543  */
6544 static int lod_declare_destroy(const struct lu_env *env, struct dt_object *dt,
6545                                struct thandle *th)
6546 {
6547         struct dt_object *next = dt_object_child(dt);
6548         struct lod_object *lo = lod_dt_obj(dt);
6549         struct lod_thread_info *info = lod_env_info(env);
6550         struct dt_object *stripe;
6551         char *stripe_name = info->lti_key;
6552         int rc, i;
6553
6554         ENTRY;
6555
6556         /*
6557          * load striping information, notice we don't do this when object
6558          * is being initialized as we don't need this information till
6559          * few specific cases like destroy, chown
6560          */
6561         rc = lod_striping_load(env, lo);
6562         if (rc)
6563                 RETURN(rc);
6564
6565         /* declare destroy for all underlying objects */
6566         if (S_ISDIR(dt->do_lu.lo_header->loh_attr)) {
6567                 rc = next->do_ops->do_index_try(env, next,
6568                                                 &dt_directory_features);
6569                 if (rc != 0)
6570                         RETURN(rc);
6571
6572                 for (i = 0; i < lo->ldo_dir_stripe_count; i++) {
6573                         stripe = lo->ldo_stripe[i];
6574                         if (!stripe)
6575                                 continue;
6576
6577                         rc = lod_sub_declare_ref_del(env, next, th);
6578                         if (rc != 0)
6579                                 RETURN(rc);
6580
6581                         snprintf(stripe_name, sizeof(info->lti_key),
6582                                  DFID":%d",
6583                                  PFID(lu_object_fid(&stripe->do_lu)), i);
6584                         rc = lod_sub_declare_delete(env, next,
6585                                         (const struct dt_key *)stripe_name, th);
6586                         if (rc != 0)
6587                                 RETURN(rc);
6588                 }
6589         }
6590
6591         /*
6592          * we declare destroy for the local object
6593          */
6594         rc = lod_sub_declare_destroy(env, next, th);
6595         if (rc)
6596                 RETURN(rc);
6597
6598         if (CFS_FAIL_CHECK(OBD_FAIL_LFSCK_LOST_MDTOBJ) ||
6599             CFS_FAIL_CHECK(OBD_FAIL_LFSCK_LOST_MDTOBJ2))
6600                 RETURN(0);
6601
6602         if (!lod_obj_is_striped(dt))
6603                 RETURN(0);
6604
6605         /* declare destroy all striped objects */
6606         if (S_ISDIR(dt->do_lu.lo_header->loh_attr)) {
6607                 for (i = 0; i < lo->ldo_dir_stripe_count; i++) {
6608                         stripe = lo->ldo_stripe[i];
6609                         if (!stripe)
6610                                 continue;
6611
6612                         if (!dt_object_exists(stripe))
6613                                 continue;
6614
6615                         rc = lod_sub_declare_ref_del(env, stripe, th);
6616                         if (rc != 0)
6617                                 break;
6618
6619                         rc = lod_sub_declare_destroy(env, stripe, th);
6620                         if (rc != 0)
6621                                 break;
6622                 }
6623         } else {
6624                 struct lod_obj_stripe_cb_data data = { { 0 } };
6625
6626                 data.locd_declare = true;
6627                 data.locd_stripe_cb = lod_obj_stripe_destroy_cb;
6628                 rc = lod_obj_for_each_stripe(env, lo, th, &data);
6629         }
6630
6631         RETURN(rc);
6632 }
6633
6634 /**
6635  * Implementation of dt_object_operations::do_destroy.
6636  *
6637  * If the object is a striped directory, then the function removes references
6638  * from the master object (this is an index) to the stripes and destroys all
6639  * the stripes. In all the cases, the function destroys the object itself.
6640  *
6641  * \see dt_object_operations::do_destroy() in the API description for details.
6642  */
6643 static int lod_destroy(const struct lu_env *env, struct dt_object *dt,
6644                        struct thandle *th)
6645 {
6646         struct dt_object  *next = dt_object_child(dt);
6647         struct lod_object *lo = lod_dt_obj(dt);
6648         struct lod_thread_info *info = lod_env_info(env);
6649         char *stripe_name = info->lti_key;
6650         struct dt_object *stripe;
6651         unsigned int i;
6652         int rc;
6653
6654         ENTRY;
6655
6656         /* destroy sub-stripe of master object */
6657         if (S_ISDIR(dt->do_lu.lo_header->loh_attr)) {
6658                 rc = next->do_ops->do_index_try(env, next,
6659                                                 &dt_directory_features);
6660                 if (rc != 0)
6661                         RETURN(rc);
6662
6663                 for (i = 0; i < lo->ldo_dir_stripe_count; i++) {
6664                         stripe = lo->ldo_stripe[i];
6665                         if (!stripe)
6666                                 continue;
6667
6668                         rc = lod_sub_ref_del(env, next, th);
6669                         if (rc != 0)
6670                                 RETURN(rc);
6671
6672                         snprintf(stripe_name, sizeof(info->lti_key), DFID":%d",
6673                                 PFID(lu_object_fid(&stripe->do_lu)), i);
6674
6675                         CDEBUG(D_INFO, DFID" delete stripe %s "DFID"\n",
6676                                PFID(lu_object_fid(&dt->do_lu)), stripe_name,
6677                                PFID(lu_object_fid(&stripe->do_lu)));
6678
6679                         rc = lod_sub_delete(env, next,
6680                                        (const struct dt_key *)stripe_name, th);
6681                         if (rc != 0)
6682                                 RETURN(rc);
6683                 }
6684         }
6685
6686         rc = lod_sub_destroy(env, next, th);
6687         if (rc != 0)
6688                 RETURN(rc);
6689
6690         if (CFS_FAIL_CHECK(OBD_FAIL_LFSCK_LOST_MDTOBJ) ||
6691             CFS_FAIL_CHECK(OBD_FAIL_LFSCK_LOST_MDTOBJ2))
6692                 RETURN(0);
6693
6694         if (!lod_obj_is_striped(dt))
6695                 RETURN(0);
6696
6697         /* destroy all striped objects */
6698         if (S_ISDIR(dt->do_lu.lo_header->loh_attr)) {
6699                 for (i = 0; i < lo->ldo_dir_stripe_count; i++) {
6700                         stripe = lo->ldo_stripe[i];
6701                         if (!stripe)
6702                                 continue;
6703
6704                         if (!dt_object_exists(stripe))
6705                                 continue;
6706
6707                         if (!CFS_FAIL_CHECK(OBD_FAIL_LFSCK_LOST_SPEOBJ) ||
6708                             i == cfs_fail_val) {
6709                                 dt_write_lock(env, stripe, DT_TGT_CHILD);
6710                                 rc = lod_sub_ref_del(env, stripe, th);
6711                                 dt_write_unlock(env, stripe);
6712                                 if (rc != 0)
6713                                         break;
6714
6715                                 rc = lod_sub_destroy(env, stripe, th);
6716                                 if (rc != 0)
6717                                         break;
6718                         }
6719                 }
6720         } else {
6721                 struct lod_obj_stripe_cb_data data = { { 0 } };
6722
6723                 data.locd_declare = false;
6724                 data.locd_stripe_cb = lod_obj_stripe_destroy_cb;
6725                 rc = lod_obj_for_each_stripe(env, lo, th, &data);
6726         }
6727
6728         RETURN(rc);
6729 }
6730
6731 /**
6732  * Implementation of dt_object_operations::do_declare_ref_add.
6733  *
6734  * \see dt_object_operations::do_declare_ref_add() in the API description
6735  * for details.
6736  */
6737 static int lod_declare_ref_add(const struct lu_env *env,
6738                                struct dt_object *dt, struct thandle *th)
6739 {
6740         return lod_sub_declare_ref_add(env, dt_object_child(dt), th);
6741 }
6742
6743 /**
6744  * Implementation of dt_object_operations::do_ref_add.
6745  *
6746  * \see dt_object_operations::do_ref_add() in the API description for details.
6747  */
6748 static int lod_ref_add(const struct lu_env *env,
6749                        struct dt_object *dt, struct thandle *th)
6750 {
6751         return lod_sub_ref_add(env, dt_object_child(dt), th);
6752 }
6753
6754 /**
6755  * Implementation of dt_object_operations::do_declare_ref_del.
6756  *
6757  * \see dt_object_operations::do_declare_ref_del() in the API description
6758  * for details.
6759  */
6760 static int lod_declare_ref_del(const struct lu_env *env,
6761                                struct dt_object *dt, struct thandle *th)
6762 {
6763         return lod_sub_declare_ref_del(env, dt_object_child(dt), th);
6764 }
6765
6766 /**
6767  * Implementation of dt_object_operations::do_ref_del
6768  *
6769  * \see dt_object_operations::do_ref_del() in the API description for details.
6770  */
6771 static int lod_ref_del(const struct lu_env *env,
6772                        struct dt_object *dt, struct thandle *th)
6773 {
6774         return lod_sub_ref_del(env, dt_object_child(dt), th);
6775 }
6776
6777 /**
6778  * Implementation of dt_object_operations::do_object_sync.
6779  *
6780  * \see dt_object_operations::do_object_sync() in the API description
6781  * for details.
6782  */
6783 static int lod_object_sync(const struct lu_env *env, struct dt_object *dt,
6784                            __u64 start, __u64 end)
6785 {
6786         return dt_object_sync(env, dt_object_child(dt), start, end);
6787 }
6788
6789 /**
6790  * Implementation of dt_object_operations::do_object_unlock.
6791  *
6792  * Used to release LDLM lock(s).
6793  *
6794  * \see dt_object_operations::do_object_unlock() in the API description
6795  * for details.
6796  */
6797 static int lod_object_unlock(const struct lu_env *env, struct dt_object *dt,
6798                              struct ldlm_enqueue_info *einfo,
6799                              union ldlm_policy_data *policy)
6800 {
6801         struct lod_object *lo = lod_dt_obj(dt);
6802         struct lustre_handle_array *slave_locks = einfo->ei_cbdata;
6803         int slave_locks_size;
6804         int i;
6805         ENTRY;
6806
6807         if (slave_locks == NULL)
6808                 RETURN(0);
6809
6810         LASSERT(S_ISDIR(dt->do_lu.lo_header->loh_attr));
6811         /* Note: for remote lock for single stripe dir, MDT will cancel
6812          * the lock by lockh directly */
6813         LASSERT(!dt_object_remote(dt_object_child(dt)));
6814
6815         /* locks were unlocked in MDT layer */
6816         for (i = 0; i < slave_locks->ha_count; i++)
6817                 LASSERT(!lustre_handle_is_used(&slave_locks->ha_handles[i]));
6818
6819         /*
6820          * NB, ha_count may not equal to ldo_dir_stripe_count, because dir
6821          * layout may change, e.g., shrink dir layout after migration.
6822          */
6823         for (i = 0; i < lo->ldo_dir_stripe_count; i++) {
6824                 if (lo->ldo_stripe[i])
6825                         dt_invalidate(env, lo->ldo_stripe[i]);
6826         }
6827
6828         slave_locks_size = offsetof(typeof(*slave_locks),
6829                                     ha_handles[slave_locks->ha_count]);
6830         OBD_FREE(slave_locks, slave_locks_size);
6831         einfo->ei_cbdata = NULL;
6832
6833         RETURN(0);
6834 }
6835
6836 /**
6837  * Implementation of dt_object_operations::do_object_lock.
6838  *
6839  * Used to get LDLM lock on the non-striped and striped objects.
6840  *
6841  * \see dt_object_operations::do_object_lock() in the API description
6842  * for details.
6843  */
6844 static int lod_object_lock(const struct lu_env *env,
6845                            struct dt_object *dt,
6846                            struct lustre_handle *lh,
6847                            struct ldlm_enqueue_info *einfo,
6848                            union ldlm_policy_data *policy)
6849 {
6850         struct lod_object *lo = lod_dt_obj(dt);
6851         int slave_locks_size;
6852         struct lustre_handle_array *slave_locks = NULL;
6853         int i;
6854         int rc;
6855         ENTRY;
6856
6857         /* remote object lock */
6858         if (!einfo->ei_enq_slave) {
6859                 LASSERT(dt_object_remote(dt));
6860                 return dt_object_lock(env, dt_object_child(dt), lh, einfo,
6861                                       policy);
6862         }
6863
6864         if (!S_ISDIR(dt->do_lu.lo_header->loh_attr))
6865                 RETURN(-ENOTDIR);
6866
6867         rc = lod_striping_load(env, lo);
6868         if (rc != 0)
6869                 RETURN(rc);
6870
6871         /* No stripes */
6872         if (lo->ldo_dir_stripe_count <= 1)
6873                 RETURN(0);
6874
6875         slave_locks_size = offsetof(typeof(*slave_locks),
6876                                     ha_handles[lo->ldo_dir_stripe_count]);
6877         /* Freed in lod_object_unlock */
6878         OBD_ALLOC(slave_locks, slave_locks_size);
6879         if (!slave_locks)
6880                 RETURN(-ENOMEM);
6881         slave_locks->ha_count = lo->ldo_dir_stripe_count;
6882
6883         /* striped directory lock */
6884         for (i = 0; i < lo->ldo_dir_stripe_count; i++) {
6885                 struct lustre_handle lockh;
6886                 struct ldlm_res_id *res_id;
6887                 struct dt_object *stripe;
6888
6889                 stripe = lo->ldo_stripe[i];
6890                 if (!stripe)
6891                         continue;
6892
6893                 res_id = &lod_env_info(env)->lti_res_id;
6894                 fid_build_reg_res_name(lu_object_fid(&stripe->do_lu), res_id);
6895                 einfo->ei_res_id = res_id;
6896
6897                 if (dt_object_remote(stripe)) {
6898                         set_bit(i, (void *)slave_locks->ha_map);
6899                         rc = dt_object_lock(env, stripe, &lockh, einfo, policy);
6900                 } else {
6901                         struct ldlm_namespace *ns = einfo->ei_namespace;
6902                         ldlm_blocking_callback blocking = einfo->ei_cb_local_bl;
6903                         ldlm_completion_callback completion = einfo->ei_cb_cp;
6904                         __u64 dlmflags = LDLM_FL_ATOMIC_CB;
6905
6906                         LASSERT(ns != NULL);
6907                         rc = ldlm_cli_enqueue_local(env, ns, res_id, LDLM_IBITS,
6908                                                     policy, einfo->ei_mode,
6909                                                     &dlmflags, blocking,
6910                                                     completion, NULL,
6911                                                     NULL, 0, LVB_T_NONE,
6912                                                     NULL, &lockh);
6913                 }
6914                 if (rc) {
6915                         while (i--)
6916                                 ldlm_lock_decref_and_cancel(
6917                                                 &slave_locks->ha_handles[i],
6918                                                 einfo->ei_mode);
6919                         OBD_FREE(slave_locks, slave_locks_size);
6920                         RETURN(rc);
6921                 }
6922                 slave_locks->ha_handles[i] = lockh;
6923         }
6924         einfo->ei_cbdata = slave_locks;
6925
6926         RETURN(0);
6927 }
6928
6929 /**
6930  * Implementation of dt_object_operations::do_invalidate.
6931  *
6932  * \see dt_object_operations::do_invalidate() in the API description for details
6933  */
6934 static int lod_invalidate(const struct lu_env *env, struct dt_object *dt)
6935 {
6936         return dt_invalidate(env, dt_object_child(dt));
6937 }
6938
6939 static int lod_declare_instantiate_components(const struct lu_env *env,
6940                                               struct lod_object *lo,
6941                                               struct thandle *th,
6942                                               __u64 reserve)
6943 {
6944         struct lod_thread_info *info = lod_env_info(env);
6945         int i;
6946         int rc = 0;
6947         ENTRY;
6948
6949         LASSERT(info->lti_count < lo->ldo_comp_cnt);
6950
6951         for (i = 0; i < info->lti_count; i++) {
6952                 rc = lod_qos_prep_create(env, lo, NULL, th,
6953                                          info->lti_comp_idx[i], reserve);
6954                 if (rc)
6955                         break;
6956         }
6957
6958         if (!rc) {
6959                 info->lti_buf.lb_len = lod_comp_md_size(lo, false);
6960                 rc = lod_sub_declare_xattr_set(env, lod_object_child(lo),
6961                                 &info->lti_buf, XATTR_NAME_LOV, 0, th);
6962         }
6963
6964         RETURN(rc);
6965 }
6966
6967 /**
6968  * Check OSTs for an existing component for further extension
6969  *
6970  * Checks if OSTs are still healthy and not out of space.  Gets free space
6971  * on OSTs (relative to allocation watermark rmb_low) and compares to
6972  * the proposed new_end for this component.
6973  *
6974  * Decides whether or not to extend a component on its current OSTs.
6975  *
6976  * \param[in] env               execution environment for this thread
6977  * \param[in] lo                object we're checking
6978  * \param[in] index             index of this component
6979  * \param[in] extension_size    extension size for this component
6980  * \param[in] extent            layout extent for requested operation
6981  * \param[in] comp_extent       extension component extent
6982  * \param[in] write             if this is write operation
6983  *
6984  * \retval      true - OK to extend on current OSTs
6985  * \retval      false - do not extend on current OSTs
6986  */
6987 static bool lod_sel_osts_allowed(const struct lu_env *env,
6988                                  struct lod_object *lo,
6989                                  int index, __u64 reserve,
6990                                  struct lu_extent *extent,
6991                                  struct lu_extent *comp_extent, int write)
6992 {
6993         struct lod_layout_component *lod_comp = &lo->ldo_comp_entries[index];
6994         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
6995         struct lod_thread_info *tinfo = lod_env_info(env);
6996         struct obd_statfs *sfs = &tinfo->lti_osfs;
6997         __u64 available = 0;
6998         bool ret = true;
6999         int i, rc;
7000
7001         ENTRY;
7002
7003         LASSERT(lod_comp->llc_stripe_count != 0);
7004
7005         lod_getref(&lod->lod_ost_descs);
7006         for (i = 0; i < lod_comp->llc_stripe_count; i++) {
7007                 int index = lod_comp->llc_ost_indices[i];
7008                 struct lod_tgt_desc *ost = OST_TGT(lod, index);
7009                 struct obd_statfs_info info = { 0 };
7010                 int j, repeated = 0;
7011
7012                 LASSERT(ost);
7013
7014                 /* Get the number of times this OST repeats in this component.
7015                  * Note: inter-component repeats are not counted as this is
7016                  * considered as a rare case: we try to not repeat OST in other
7017                  * components if possible. */
7018                 for (j = 0; j < lod_comp->llc_stripe_count; j++) {
7019                         if (index != lod_comp->llc_ost_indices[j])
7020                                 continue;
7021
7022                         /* already handled */
7023                         if (j < i)
7024                                 break;
7025
7026                         repeated++;
7027                 }
7028                 if (j < lod_comp->llc_stripe_count)
7029                         continue;
7030
7031                 if (!test_bit(index, lod->lod_ost_bitmap)) {
7032                         CDEBUG(D_LAYOUT, "ost %d no longer present\n", index);
7033                         ret = false;
7034                         break;
7035                 }
7036
7037                 rc = dt_statfs_info(env, ost->ltd_tgt, sfs, &info);
7038                 if (rc) {
7039                         CDEBUG(D_LAYOUT, "statfs failed for ost %d, error %d\n",
7040                                index, rc);
7041                         ret = false;
7042                         break;
7043                 }
7044
7045                 if (sfs->os_state & OS_STATFS_ENOSPC ||
7046                     sfs->os_state & OS_STATFS_READONLY ||
7047                     sfs->os_state & OS_STATFS_NOCREATE ||
7048                     sfs->os_state & OS_STATFS_DEGRADED) {
7049                         CDEBUG(D_LAYOUT,
7050                                "OST%04x unusable for SEL extension, state %x\n",
7051                                index, sfs->os_state);
7052                         ret = false;
7053                         break;
7054                 }
7055
7056                 /* In bytes */
7057                 available = sfs->os_bavail * sfs->os_bsize;
7058                 /* 'available' is relative to the allocation threshold */
7059                 available -= (__u64) info.os_reserved_mb_low << 20;
7060
7061                 CDEBUG(D_LAYOUT, "ost %d lowwm: %d highwm: %d, "
7062                        "%llu %% blocks available, %llu %% blocks free\n",
7063                        index, info.os_reserved_mb_low, info.os_reserved_mb_high,
7064                        (100ull * sfs->os_bavail) / sfs->os_blocks,
7065                        (100ull * sfs->os_bfree) / sfs->os_blocks);
7066
7067                 if (reserve * repeated > available) {
7068                         ret = false;
7069                         CDEBUG(D_LAYOUT, "low space on ost %d, available %llu "
7070                                "< extension size %llu repeated %d\n", index,
7071                                available, reserve, repeated);
7072                         break;
7073                 }
7074         }
7075         lod_putref(lod, &lod->lod_ost_descs);
7076
7077         RETURN(ret);
7078 }
7079
7080 /**
7081  * Adjust extents after component removal
7082  *
7083  * When we remove an extension component, we move the start of the next
7084  * component to match the start of the extension component, so no space is left
7085  * without layout.
7086  *
7087  * \param[in] env       execution environment for this thread
7088  * \param[in] lo        object
7089  * \param[in] max_comp  layout component
7090  * \param[in] index     index of this component
7091  *
7092  * \retval              0 on success
7093  * \retval              negative errno on error
7094  */
7095 static void lod_sel_adjust_extents(const struct lu_env *env,
7096                                    struct lod_object *lo,
7097                                    int max_comp, int index)
7098 {
7099         struct lod_layout_component *lod_comp = NULL;
7100         struct lod_layout_component *next = NULL;
7101         struct lod_layout_component *prev = NULL;
7102         __u64 new_start = 0;
7103         __u64 start;
7104         int i;
7105
7106         /* Extension space component */
7107         lod_comp = &lo->ldo_comp_entries[index];
7108         next = &lo->ldo_comp_entries[index + 1];
7109         prev = &lo->ldo_comp_entries[index - 1];
7110
7111         LASSERT(lod_comp != NULL && prev != NULL && next != NULL);
7112         LASSERT(lod_comp->llc_flags & LCME_FL_EXTENSION);
7113
7114         /* Previous is being removed */
7115         if (prev && prev->llc_id == LCME_ID_INVAL)
7116                 new_start = prev->llc_extent.e_start;
7117         else
7118                 new_start = lod_comp->llc_extent.e_start;
7119
7120         for (i = index + 1; i < max_comp; i++) {
7121                 lod_comp = &lo->ldo_comp_entries[i];
7122
7123                 start = lod_comp->llc_extent.e_start;
7124                 lod_comp->llc_extent.e_start = new_start;
7125
7126                 /* We only move zero length extendable components */
7127                 if (!(start == lod_comp->llc_extent.e_end))
7128                         break;
7129
7130                 LASSERT(!(lod_comp->llc_flags & LCME_FL_INIT));
7131
7132                 lod_comp->llc_extent.e_end = new_start;
7133         }
7134 }
7135
7136 /* Calculate the proposed 'new end' for a component we're extending */
7137 static __u64 lod_extension_new_end(__u64 extension_size, __u64 extent_end,
7138                                    __u32 stripe_size, __u64 component_end,
7139                                    __u64 extension_end)
7140 {
7141         __u64 new_end;
7142
7143         LASSERT(extension_size != 0 && stripe_size != 0);
7144
7145         /* Round up to extension size */
7146         if (extent_end == OBD_OBJECT_EOF) {
7147                 new_end = OBD_OBJECT_EOF;
7148         } else {
7149                 /* Add at least extension_size to the previous component_end,
7150                  * covering the req layout extent */
7151                 new_end = max(extent_end - component_end, extension_size);
7152                 new_end = roundup(new_end, extension_size);
7153                 new_end += component_end;
7154
7155                 /* Component end must be min stripe size aligned */
7156                 if (new_end % stripe_size) {
7157                         CDEBUG(D_LAYOUT, "new component end is not aligned "
7158                                "by the stripe size %u: [%llu, %llu) ext size "
7159                                "%llu new end %llu, aligning\n",
7160                                stripe_size, component_end, extent_end,
7161                                extension_size, new_end);
7162                         new_end = roundup(new_end, stripe_size);
7163                 }
7164
7165                 /* Overflow */
7166                 if (new_end < extent_end)
7167                         new_end = OBD_OBJECT_EOF;
7168         }
7169
7170         /* Don't extend past the end of the extension component */
7171         if (new_end > extension_end)
7172                 new_end = extension_end;
7173
7174         return new_end;
7175 }
7176
7177 /**
7178  * Calculate the exact reservation (per-OST extension_size) on the OSTs being
7179  * instantiated. It needs to be calculated in advance and taken into account at
7180  * the instantiation time, because otherwise lod_statfs_and_check() may consider
7181  * an OST as OK, but SEL needs its extension_size to fit the free space and the
7182  * OST may turn out to be low-on-space, thus inappropriate OST may be used and
7183  * ENOSPC occurs.
7184  *
7185  * \param[in] lod_comp          lod component we are checking
7186  *
7187  * \retval      size to reserved on each OST of lod_comp's stripe.
7188  */
7189 static __u64 lod_sel_stripe_reserved(struct lod_layout_component *lod_comp)
7190 {
7191         /* extension_size is file level, so we must divide by stripe count to
7192          * compare it to available space on a single OST */
7193         return  lod_comp->llc_stripe_size * SEL_UNIT_SIZE /
7194                 lod_comp->llc_stripe_count;
7195 }
7196
7197 /* As lod_sel_handler() could be re-entered for the same component several
7198  * times, this is the data for the next call. Fields could be changed to
7199  * component indexes when needed, (e.g. if there is no need to instantiate
7200  * all the previous components up to the current position) to tell the caller
7201  * where to start over from. */
7202 struct sel_data {
7203         int sd_force;
7204         int sd_repeat;
7205 };
7206
7207 /**
7208  * Process extent updates for a particular layout component
7209  *
7210  * Handle layout updates for a particular extension space component touched by
7211  * a layout update operation.  Core function of self-extending PFL feature.
7212  *
7213  * In general, this function processes exactly *one* stage of an extension
7214  * operation, modifying the layout accordingly, then returns to the caller.
7215  * The caller is responsible for restarting processing with the new layout,
7216  * which may repeatedly return to this function until the extension updates
7217  * are complete.
7218  *
7219  * This function does one of a few things to the layout:
7220  * 1. Extends the component before the current extension space component to
7221  * allow it to accomodate the requested operation (if space/policy permit that
7222  * component to continue on its current OSTs)
7223  *
7224  * 2. If extension of the existing component fails, we do one of two things:
7225  *    a. If there is a component after the extension space, we remove the
7226  *       extension space component, move the start of the next component down
7227  *       accordingly, then notify the caller to restart processing w/the new
7228  *       layout.
7229  *    b. If there is no following component, we try repeating the current
7230  *       component, creating a new component using the current one as a
7231  *       template (keeping its stripe properties but not specific striping),
7232  *       and try assigning striping for this component.  If there is sufficient
7233  *       free space on the OSTs chosen for this component, it is instantiated
7234  *       and i/o continues there.
7235  *
7236  *       If there is not sufficient space on the new OSTs, we remove this new
7237  *       component & extend the current component.
7238  *
7239  * Note further that uninited components followed by extension space can be zero
7240  * length meaning that we will try to extend them before initializing them, and
7241  * if that fails, they will be removed without initialization.
7242  *
7243  * 3. If we extend to/beyond the end of an extension space component, that
7244  * component is exhausted (all of its range has been given to real components),
7245  * so we remove it and restart processing.
7246  *
7247  * \param[in] env               execution environment for this thread
7248  * \param[in,out] lo            object to update the layout of
7249  * \param[in] extent            layout extent for requested operation, update
7250  *                              layout to fit this operation
7251  * \param[in] th                transaction handle for this operation
7252  * \param[in,out] max_comp      the highest comp for the portion of the layout
7253  *                              we are operating on (For FLR, the chosen
7254  *                              replica).  Updated because we may remove
7255  *                              components.
7256  * \param[in] index             index of the extension space component we're
7257  *                              working on
7258  * \param[in] write             if this is write op
7259  * \param[in,out] force         if the extension is to be forced; set here
7260                                 to force it on the 2nd call for the same
7261                                 extension component
7262  *
7263  * \retval      0 on success
7264  * \retval      negative errno on error
7265  */
7266 static int lod_sel_handler(const struct lu_env *env,
7267                           struct lod_object *lo,
7268                           struct lu_extent *extent,
7269                           struct thandle *th, int *max_comp,
7270                           int index, int write,
7271                           struct sel_data *sd)
7272 {
7273         struct lod_device *d = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
7274         struct lod_thread_info *info = lod_env_info(env);
7275         struct lod_layout_component *lod_comp;
7276         struct lod_layout_component *prev;
7277         struct lod_layout_component *next = NULL;
7278         __u64 extension_size, reserve;
7279         __u64 new_end = 0;
7280         bool repeated;
7281         int change = 0;
7282         int rc = 0;
7283         ENTRY;
7284
7285         /* First component cannot be extension space */
7286         if (index == 0) {
7287                 CERROR("%s: "DFID" first component cannot be extension space\n",
7288                        lod2obd(d)->obd_name, PFID(lod_object_fid(lo)));
7289                 RETURN(-EINVAL);
7290         }
7291
7292         lod_comp = &lo->ldo_comp_entries[index];
7293         prev = &lo->ldo_comp_entries[index - 1];
7294         if ((index + 1) < *max_comp)
7295                 next = &lo->ldo_comp_entries[index + 1];
7296
7297         /* extension size uses the stripe size field as KiB */
7298         extension_size = lod_comp->llc_stripe_size * SEL_UNIT_SIZE;
7299
7300         CDEBUG(D_LAYOUT, "prev start %llu, extension start %llu, extension end"
7301                " %llu, extension size %llu\n", prev->llc_extent.e_start,
7302                lod_comp->llc_extent.e_start, lod_comp->llc_extent.e_end,
7303                extension_size);
7304
7305         /* Two extension space components cannot be adjacent & extension space
7306          * components cannot be init */
7307         if ((prev->llc_flags & LCME_FL_EXTENSION) ||
7308             !(ergo(next, !(next->llc_flags & LCME_FL_EXTENSION))) ||
7309              lod_comp_inited(lod_comp)) {
7310                 CERROR("%s: "DFID" invalid extension space components\n",
7311                        lod2obd(d)->obd_name, PFID(lod_object_fid(lo)));
7312                 RETURN(-EINVAL);
7313         }
7314
7315         reserve = lod_sel_stripe_reserved(lod_comp);
7316
7317         if (!prev->llc_stripe) {
7318                 CDEBUG(D_LAYOUT, "Previous component not inited\n");
7319                 info->lti_count = 1;
7320                 info->lti_comp_idx[0] = index - 1;
7321                 rc = lod_declare_instantiate_components(env, lo, th, reserve);
7322                 /* ENOSPC tells us we can't use this component.  If there is
7323                  * a next or we are repeating, we either spill over (next) or
7324                  * extend the original comp (repeat).  Otherwise, return the
7325                  * error to the user. */
7326                 if (rc == -ENOSPC && (next || sd->sd_repeat))
7327                         rc = 1;
7328                 if (rc < 0)
7329                         RETURN(rc);
7330         }
7331
7332         if (sd->sd_force == 0 && rc == 0)
7333                 rc = !lod_sel_osts_allowed(env, lo, index - 1, reserve, extent,
7334                                            &lod_comp->llc_extent, write);
7335
7336         repeated = !!(sd->sd_repeat);
7337         sd->sd_repeat = 0;
7338         sd->sd_force = 0;
7339
7340         /* Extend previous component */
7341         if (rc == 0) {
7342                 new_end = lod_extension_new_end(extension_size, extent->e_end,
7343                                                 prev->llc_stripe_size,
7344                                                 prev->llc_extent.e_end,
7345                                                 lod_comp->llc_extent.e_end);
7346
7347                 CDEBUG(D_LAYOUT, "new end %llu\n", new_end);
7348                 lod_comp->llc_extent.e_start = new_end;
7349                 prev->llc_extent.e_end = new_end;
7350
7351                 if (prev->llc_extent.e_end == lod_comp->llc_extent.e_end) {
7352                         CDEBUG(D_LAYOUT, "Extension component exhausted\n");
7353                         lod_comp->llc_id = LCME_ID_INVAL;
7354                         change--;
7355                 }
7356         } else {
7357                 /* rc == 1, failed to extend current component */
7358                 LASSERT(rc == 1);
7359                 if (next) {
7360                         /* Normal 'spillover' case - Remove the extension
7361                          * space component & bring down the start of the next
7362                          * component. */
7363                         lod_comp->llc_id = LCME_ID_INVAL;
7364                         change--;
7365                         if (!(prev->llc_flags & LCME_FL_INIT)) {
7366                                 prev->llc_id = LCME_ID_INVAL;
7367                                 change--;
7368                         }
7369                         lod_sel_adjust_extents(env, lo, *max_comp, index);
7370                 } else if (lod_comp_inited(prev)) {
7371                         /* If there is no next, and the previous component is
7372                          * INIT'ed, try repeating the previous component. */
7373                         LASSERT(repeated == 0);
7374                         rc = lod_layout_repeat_comp(env, lo, index - 1);
7375                         if (rc < 0)
7376                                 RETURN(rc);
7377                         change++;
7378                         /* The previous component is a repeated component.
7379                          * Record this so we don't keep trying to repeat it. */
7380                         sd->sd_repeat = 1;
7381                 } else {
7382                         /* If the previous component is not INIT'ed, this may
7383                          * be a component we have just instantiated but failed
7384                          * to extend. Or even a repeated component we failed
7385                          * to prepare a striping for. Do not repeat but instead
7386                          * remove the repeated component & force the extention
7387                          * of the original one */
7388                         sd->sd_force = 1;
7389                         if (repeated) {
7390                                 prev->llc_id = LCME_ID_INVAL;
7391                                 change--;
7392                         }
7393                 }
7394         }
7395
7396         if (change < 0) {
7397                 rc = lod_layout_del_prep_layout(env, lo, NULL);
7398                 if (rc < 0)
7399                         RETURN(rc);
7400                 LASSERTF(-rc == change,
7401                          "number deleted %d != requested %d\n", -rc,
7402                          change);
7403         }
7404         *max_comp = *max_comp + change;
7405
7406         /* lod_del_prep_layout reallocates ldo_comp_entries, so we must
7407          * refresh these pointers before using them */
7408         lod_comp = &lo->ldo_comp_entries[index];
7409         prev = &lo->ldo_comp_entries[index - 1];
7410         CDEBUG(D_LAYOUT, "After extent updates: prev start %llu, current start "
7411                "%llu, current end %llu max_comp %d ldo_comp_cnt %d\n",
7412                prev->llc_extent.e_start, lod_comp->llc_extent.e_start,
7413                lod_comp->llc_extent.e_end, *max_comp, lo->ldo_comp_cnt);
7414
7415         /* Layout changed successfully */
7416         RETURN(0);
7417 }
7418
7419 /**
7420  * Declare layout extent updates
7421  *
7422  * Handles extensions.  Identifies extension components touched by current
7423  * operation and passes them to processing function.
7424  *
7425  * Restarts with updated layouts from the processing function until the current
7426  * operation no longer touches an extension space component.
7427  *
7428  * \param[in] env       execution environment for this thread
7429  * \param[in,out] lo    object to update the layout of
7430  * \param[in] extent    layout extent for requested operation, update layout to
7431  *                      fit this operation
7432  * \param[in] th        transaction handle for this operation
7433  * \param[in] pick      identifies chosen mirror for FLR layouts
7434  * \param[in] write     if this is write op
7435  *
7436  * \retval      1 on layout changed, 0 on no change
7437  * \retval      negative errno on error
7438  */
7439 static int lod_declare_update_extents(const struct lu_env *env,
7440                 struct lod_object *lo, struct lu_extent *extent,
7441                 struct thandle *th, int pick, int write)
7442 {
7443         struct lod_thread_info *info = lod_env_info(env);
7444         struct lod_layout_component *lod_comp;
7445         bool layout_changed = false;
7446         struct sel_data sd = { 0 };
7447         int start_index;
7448         int i = 0;
7449         int max_comp = 0;
7450         int rc = 0, rc2;
7451         int change = 0;
7452         ENTRY;
7453
7454         /* This makes us work on the components of the chosen mirror */
7455         start_index = lo->ldo_mirrors[pick].lme_start;
7456         max_comp = lo->ldo_mirrors[pick].lme_end + 1;
7457         if (lo->ldo_flr_state == LCM_FL_NONE)
7458                 LASSERT(start_index == 0 && max_comp == lo->ldo_comp_cnt);
7459
7460         CDEBUG(D_LAYOUT, "extent->e_start %llu, extent->e_end %llu\n",
7461                extent->e_start, extent->e_end);
7462         for (i = start_index; i < max_comp; i++) {
7463                 lod_comp = &lo->ldo_comp_entries[i];
7464
7465                 /* We've passed all components of interest */
7466                 if (lod_comp->llc_extent.e_start >= extent->e_end)
7467                         break;
7468
7469                 if (lod_comp->llc_flags & LCME_FL_EXTENSION) {
7470                         layout_changed = true;
7471                         rc = lod_sel_handler(env, lo, extent, th, &max_comp,
7472                                              i, write, &sd);
7473                         if (rc < 0)
7474                                 GOTO(out, rc);
7475
7476                         /* Nothing has changed behind the prev one */
7477                         i -= 2;
7478                         continue;
7479                 }
7480         }
7481
7482         /* We may have added or removed components.  If so, we must update the
7483          * start & ends of all the mirrors after the current one, and the end
7484          * of the current mirror. */
7485         change = max_comp - 1 - lo->ldo_mirrors[pick].lme_end;
7486         if (change) {
7487                 lo->ldo_mirrors[pick].lme_end += change;
7488                 for (i = pick + 1; i < lo->ldo_mirror_count; i++) {
7489                         lo->ldo_mirrors[i].lme_start += change;
7490                         lo->ldo_mirrors[i].lme_end += change;
7491                 }
7492         }
7493
7494         EXIT;
7495 out:
7496         /* The amount of components has changed, adjust the lti_comp_idx */
7497         rc2 = lod_layout_data_init(info, lo->ldo_comp_cnt);
7498
7499         return rc < 0 ? rc : rc2 < 0 ? rc2 : layout_changed;
7500 }
7501
7502 /* If striping is already instantiated or INIT'ed DOM? */
7503 static bool lod_is_instantiation_needed(struct lod_layout_component *comp)
7504 {
7505         if (comp->llc_magic == LOV_MAGIC_FOREIGN)
7506                 return false;
7507
7508         return !(((lov_pattern(comp->llc_pattern) & LOV_PATTERN_MDT) &&
7509                   lod_comp_inited(comp)) || comp->llc_stripe);
7510 }
7511
7512 /**
7513  * Declare layout update for a non-FLR layout.
7514  *
7515  * \param[in] env       execution environment for this thread
7516  * \param[in,out] lo    object to update the layout of
7517  * \param[in] layout    layout intent for requested operation, "update" is
7518  *                      a process of reacting to this
7519  * \param[in] buf       buffer containing lov ea (see comment on usage inline)
7520  * \param[in] th        transaction handle for this operation
7521  *
7522  * \retval      0 on success
7523  * \retval      negative errno on error
7524  */
7525 static int lod_declare_update_plain(const struct lu_env *env,
7526                 struct lod_object *lo, struct layout_intent *layout,
7527                 const struct lu_buf *buf, struct thandle *th)
7528 {
7529         struct lod_thread_info *info = lod_env_info(env);
7530         struct lod_device *d = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
7531         struct lod_layout_component *lod_comp;
7532         struct lov_comp_md_v1 *comp_v1 = NULL;
7533         bool layout_changed = false;
7534         bool replay = false;
7535         int i, rc;
7536         ENTRY;
7537
7538         LASSERT(lo->ldo_flr_state == LCM_FL_NONE);
7539
7540         /*
7541          * In case the client is passing lovea, which only happens during
7542          * the replay of layout intent write RPC for now, we may need to
7543          * parse the lovea and apply new layout configuration.
7544          */
7545         if (buf && buf->lb_len)  {
7546                 struct lov_user_md_v1 *v1 = buf->lb_buf;
7547
7548                 if (v1->lmm_magic != (LOV_MAGIC_DEFINED | LOV_MAGIC_COMP_V1) &&
7549                     v1->lmm_magic != __swab32(LOV_MAGIC_DEFINED |
7550                                               LOV_MAGIC_COMP_V1)) {
7551                         CERROR("%s: the replay buffer of layout extend "
7552                                "(magic %#x) does not contain expected "
7553                                "composite layout.\n",
7554                                lod2obd(d)->obd_name, v1->lmm_magic);
7555                         GOTO(out, rc = -EINVAL);
7556                 }
7557
7558                 rc = lod_use_defined_striping(env, lo, buf);
7559                 if (rc)
7560                         GOTO(out, rc);
7561                 lo->ldo_comp_cached = 1;
7562
7563                 rc = lod_get_lov_ea(env, lo);
7564                 if (rc <= 0)
7565                         GOTO(out, rc);
7566                 /* old on-disk EA is stored in info->lti_buf */
7567                 comp_v1 = (struct lov_comp_md_v1 *)info->lti_buf.lb_buf;
7568                 replay = true;
7569                 layout_changed = true;
7570
7571                 rc = lod_layout_data_init(info, lo->ldo_comp_cnt);
7572                 if (rc)
7573                         GOTO(out, rc);
7574         } else {
7575                 /* non replay path */
7576                 rc = lod_striping_load(env, lo);
7577                 if (rc)
7578                         GOTO(out, rc);
7579         }
7580
7581         /* Make sure defined layout covers the requested write range. */
7582         lod_comp = &lo->ldo_comp_entries[lo->ldo_comp_cnt - 1];
7583         if (lo->ldo_comp_cnt > 1 &&
7584             lod_comp->llc_extent.e_end != OBD_OBJECT_EOF &&
7585             lod_comp->llc_extent.e_end < layout->li_extent.e_end) {
7586                 CDEBUG_LIMIT(replay ? D_ERROR : D_LAYOUT,
7587                              "%s: the defined layout [0, %#llx) does not "
7588                              "covers the write range "DEXT"\n",
7589                              lod2obd(d)->obd_name, lod_comp->llc_extent.e_end,
7590                              PEXT(&layout->li_extent));
7591                 GOTO(out, rc = -EINVAL);
7592         }
7593
7594         CDEBUG(D_LAYOUT, "%s: "DFID": update components "DEXT"\n",
7595                lod2obd(d)->obd_name, PFID(lod_object_fid(lo)),
7596                PEXT(&layout->li_extent));
7597
7598         if (!replay) {
7599                 rc = lod_declare_update_extents(env, lo, &layout->li_extent,
7600                                 th, 0, layout->li_opc == LAYOUT_INTENT_WRITE);
7601                 if (rc < 0)
7602                         GOTO(out, rc);
7603                 else if (rc)
7604                         layout_changed = true;
7605         }
7606
7607         /*
7608          * Iterate ld->ldo_comp_entries, find the component whose extent under
7609          * the write range and not instantianted.
7610          */
7611         for (i = 0; i < lo->ldo_comp_cnt; i++) {
7612                 lod_comp = &lo->ldo_comp_entries[i];
7613
7614                 if (lod_comp->llc_extent.e_start >= layout->li_extent.e_end)
7615                         break;
7616
7617                 if (!replay) {
7618                         /* If striping is instantiated or INIT'ed DOM skip */
7619                         if (!lod_is_instantiation_needed(lod_comp))
7620                                 continue;
7621                 } else {
7622                         /**
7623                          * In replay path, lod_comp is the EA passed by
7624                          * client replay buffer,  comp_v1 is the pre-recovery
7625                          * on-disk EA, we'd sift out those components which
7626                          * were init-ed in the on-disk EA.
7627                          */
7628                         if (le32_to_cpu(comp_v1->lcm_entries[i].lcme_flags) &
7629                             LCME_FL_INIT)
7630                                 continue;
7631                 }
7632                 /*
7633                  * this component hasn't instantiated in normal path, or during
7634                  * replay it needs replay the instantiation.
7635                  */
7636
7637                 /* A released component is being extended */
7638                 if (lod_comp->llc_pattern & LOV_PATTERN_F_RELEASED)
7639                         GOTO(out, rc = -EINVAL);
7640
7641                 LASSERT(info->lti_comp_idx != NULL);
7642                 info->lti_comp_idx[info->lti_count++] = i;
7643                 layout_changed = true;
7644         }
7645
7646         if (!layout_changed)
7647                 RETURN(-EALREADY);
7648
7649         lod_obj_inc_layout_gen(lo);
7650         rc = lod_declare_instantiate_components(env, lo, th, 0);
7651         EXIT;
7652 out:
7653         if (rc)
7654                 lod_striping_free(env, lo);
7655         return rc;
7656 }
7657
7658 static inline int lod_comp_index(struct lod_object *lo,
7659                                  struct lod_layout_component *lod_comp)
7660 {
7661         LASSERT(lod_comp >= lo->ldo_comp_entries &&
7662                 lod_comp <= &lo->ldo_comp_entries[lo->ldo_comp_cnt - 1]);
7663
7664         return lod_comp - lo->ldo_comp_entries;
7665 }
7666
7667 /**
7668  * Stale other mirrors by writing extent.
7669  */
7670 static int lod_stale_components(const struct lu_env *env, struct lod_object *lo,
7671                                 int primary, struct lu_extent *extent,
7672                                 struct thandle *th)
7673 {
7674         struct lod_layout_component *pri_comp, *lod_comp;
7675         struct lu_extent pri_extent;
7676         int rc = 0;
7677         int i;
7678         ENTRY;
7679
7680         /* The writing extent decides which components in the primary
7681          * are affected... */
7682         CDEBUG(D_LAYOUT, "primary mirror %d, "DEXT"\n", primary, PEXT(extent));
7683
7684 restart:
7685         lod_foreach_mirror_comp(pri_comp, lo, primary) {
7686                 if (!lu_extent_is_overlapped(extent, &pri_comp->llc_extent))
7687                         continue;
7688
7689                 CDEBUG(D_LAYOUT, "primary comp %u "DEXT"\n",
7690                        lod_comp_index(lo, pri_comp),
7691                        PEXT(&pri_comp->llc_extent));
7692
7693                 pri_extent.e_start = pri_comp->llc_extent.e_start;
7694                 pri_extent.e_end = pri_comp->llc_extent.e_end;
7695
7696                 for (i = 0; i < lo->ldo_mirror_count; i++) {
7697                         if (i == primary)
7698                                 continue;
7699                         rc = lod_declare_update_extents(env, lo, &pri_extent,
7700                                                         th, i, 0);
7701                         /* if update_extents changed the layout, it may have
7702                          * reallocated the component array, so start over to
7703                          * avoid using stale pointers */
7704                         if (rc == 1)
7705                                 goto restart;
7706                         if (rc < 0)
7707                                 RETURN(rc);
7708
7709                         /* ... and then stale other components that are
7710                          * overlapping with primary components */
7711                         lod_foreach_mirror_comp(lod_comp, lo, i) {
7712                                 if (!lu_extent_is_overlapped(
7713                                                         &pri_extent,
7714                                                         &lod_comp->llc_extent))
7715                                         continue;
7716
7717                                 CDEBUG(D_LAYOUT, "stale: %u / %u\n",
7718                                       i, lod_comp_index(lo, lod_comp));
7719
7720                                 lod_comp->llc_flags |= LCME_FL_STALE;
7721                                 lo->ldo_mirrors[i].lme_stale = 1;
7722                                 if (lod_is_hsm(lod_comp))
7723                                         lod_comp->llc_foreign_flags |= HS_DIRTY;
7724                         }
7725                 }
7726         }
7727
7728         RETURN(rc);
7729 }
7730
7731 /**
7732  * check an OST's availability
7733  * \param[in] env       execution environment
7734  * \param[in] lo        lod object
7735  * \param[in] dt        dt object
7736  * \param[in] index     mirror index
7737  *
7738  * \retval      negative if failed
7739  * \retval      1 if \a dt is available
7740  * \retval      0 if \a dt is not available
7741  */
7742 static inline int lod_check_ost_avail(const struct lu_env *env,
7743                                       struct lod_object *lo,
7744                                       struct dt_object *dt, int index)
7745 {
7746         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
7747         struct lod_tgt_desc *ost;
7748         __u32 idx;
7749         int type = LU_SEQ_RANGE_OST;
7750         int rc;
7751
7752         rc = lod_fld_lookup(env, lod, lu_object_fid(&dt->do_lu), &idx, &type);
7753         if (rc < 0) {
7754                 CERROR("%s: can't locate "DFID":rc = %d\n",
7755                        lod2obd(lod)->obd_name, PFID(lu_object_fid(&dt->do_lu)),
7756                        rc);
7757                 return rc;
7758         }
7759
7760         ost = OST_TGT(lod, idx);
7761         if (ost->ltd_active == 0) {
7762                 CDEBUG(D_LAYOUT, DFID ": mirror %d OST%d unavail\n",
7763                        PFID(lod_object_fid(lo)), index, idx);
7764                 return 0;
7765         }
7766
7767         return 1;
7768 }
7769
7770 /**
7771  * Pick primary mirror for write
7772  * \param[in] env       execution environment
7773  * \param[in] lo        object
7774  * \param[in] extent    write range
7775  */
7776 static int lod_primary_pick(const struct lu_env *env, struct lod_object *lo,
7777                             struct lu_extent *extent)
7778 {
7779         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
7780         unsigned int seq = 0;
7781         struct lod_layout_component *lod_comp;
7782         int i, j, rc;
7783         int picked = -1, second_pick = -1, third_pick = -1;
7784         ENTRY;
7785
7786         if (CFS_FAIL_CHECK(OBD_FAIL_FLR_RANDOM_PICK_MIRROR)) {
7787                 get_random_bytes(&seq, sizeof(seq));
7788                 seq %= lo->ldo_mirror_count;
7789         }
7790
7791         /**
7792          * Pick a mirror as the primary, and check the availability of OSTs.
7793          *
7794          * This algo can be revised later after knowing the topology of
7795          * cluster.
7796          */
7797         lod_qos_statfs_update(env, lod, &lod->lod_ost_descs);
7798
7799         rc = lod_fill_mirrors(lo);
7800         if (rc)
7801                 RETURN(rc);
7802
7803         for (i = 0; i < lo->ldo_mirror_count; i++) {
7804                 bool ost_avail = true;
7805                 int index = (i + seq) % lo->ldo_mirror_count;
7806
7807                 if (lo->ldo_mirrors[index].lme_stale) {
7808                         CDEBUG(D_LAYOUT, DFID": mirror %d stale\n",
7809                                PFID(lod_object_fid(lo)), index);
7810                         continue;
7811                 }
7812
7813                 /* 2nd pick is for the primary mirror containing unavail OST */
7814                 if (lo->ldo_mirrors[index].lme_prefer && second_pick < 0)
7815                         second_pick = index;
7816
7817                 /* 3rd pick is for non-primary mirror containing unavail OST */
7818                 if (second_pick < 0 && third_pick < 0)
7819                         third_pick = index;
7820
7821                 /**
7822                  * we found a non-primary 1st pick, we'd like to find a
7823                  * potential pirmary mirror.
7824                  */
7825                 if (picked >= 0 && !lo->ldo_mirrors[index].lme_prefer)
7826                         continue;
7827
7828                 /* check the availability of OSTs */
7829                 lod_foreach_mirror_comp(lod_comp, lo, index) {
7830                         if (!lod_comp_inited(lod_comp) || !lod_comp->llc_stripe)
7831                                 continue;
7832
7833                         for (j = 0; j < lod_comp->llc_stripe_count; j++) {
7834                                 struct dt_object *dt = lod_comp->llc_stripe[j];
7835
7836                                 rc = lod_check_ost_avail(env, lo, dt, index);
7837                                 if (rc < 0)
7838                                         RETURN(rc);
7839
7840                                 ost_avail = !!rc;
7841                                 if (!ost_avail)
7842                                         break;
7843                         } /* for all dt object in one component */
7844                         if (!ost_avail)
7845                                 break;
7846                 } /* for all components in a mirror */
7847
7848                 /**
7849                  * the OSTs where allocated objects locates in the components
7850                  * of the mirror are available.
7851                  */
7852                 if (!ost_avail)
7853                         continue;
7854
7855                 /* this mirror has all OSTs available */
7856                 picked = index;
7857
7858                 /**
7859                  * primary with all OSTs are available, this is the perfect
7860                  * 1st pick.
7861                  */
7862                 if (lo->ldo_mirrors[index].lme_prefer)
7863                         break;
7864         } /* for all mirrors */
7865
7866         /* failed to pick a sound mirror, lower our expectation */
7867         if (picked < 0)
7868                 picked = second_pick;
7869         if (picked < 0)
7870                 picked = third_pick;
7871         if (picked < 0)
7872                 RETURN(-ENODATA);
7873
7874         RETURN(picked);
7875 }
7876
7877 static int lod_prepare_resync_mirror(const struct lu_env *env,
7878                                      struct lod_object *lo,
7879                                      __u16 mirror_id)
7880 {
7881         struct lod_thread_info *info = lod_env_info(env);
7882         struct lod_layout_component *lod_comp;
7883         bool neg = !!(MIRROR_ID_NEG & mirror_id);
7884         int i;
7885
7886         mirror_id &= ~MIRROR_ID_NEG;
7887
7888         for (i = 0; i < lo->ldo_mirror_count; i++) {
7889                 if ((!neg && lo->ldo_mirrors[i].lme_id != mirror_id) ||
7890                     (neg && lo->ldo_mirrors[i].lme_id == mirror_id))
7891                         continue;
7892
7893                 lod_foreach_mirror_comp(lod_comp, lo, i) {
7894                         if (lod_comp_inited(lod_comp))
7895                                 continue;
7896
7897                         info->lti_comp_idx[info->lti_count++] =
7898                                 lod_comp_index(lo, lod_comp);
7899                 }
7900         }
7901
7902         return 0;
7903 }
7904
7905 /**
7906  * figure out the components should be instantiated for resync.
7907  */
7908 static int lod_prepare_resync(const struct lu_env *env, struct lod_object *lo,
7909                               struct lu_extent *extent)
7910 {
7911         struct lod_thread_info *info = lod_env_info(env);
7912         struct lod_layout_component *lod_comp;
7913         unsigned int need_sync = 0;
7914         int i;
7915
7916         CDEBUG(D_LAYOUT,
7917                DFID": instantiate all stale components in "DEXT"\n",
7918                PFID(lod_object_fid(lo)), PEXT(extent));
7919
7920         /**
7921          * instantiate all components within this extent, even non-stale
7922          * components.
7923          */
7924         for (i = 0; i < lo->ldo_mirror_count; i++) {
7925                 if (!lo->ldo_mirrors[i].lme_stale)
7926                         continue;
7927
7928                 lod_foreach_mirror_comp(lod_comp, lo, i) {
7929                         if (!lu_extent_is_overlapped(extent,
7930                                                 &lod_comp->llc_extent))
7931                                 break;
7932
7933                         need_sync++;
7934
7935                         if (lod_comp_inited(lod_comp))
7936                                 continue;
7937
7938                         CDEBUG(D_LAYOUT, "resync instantiate %d / %d\n",
7939                                i, lod_comp_index(lo, lod_comp));
7940                         info->lti_comp_idx[info->lti_count++] =
7941                                         lod_comp_index(lo, lod_comp);
7942                 }
7943         }
7944
7945         return need_sync ? 0 : -EALREADY;
7946 }
7947
7948 static struct lod_layout_component *
7949 lod_locate_comp_hsm(struct lod_object *lo, int *hsm_mirror_id)
7950 {
7951         struct lod_layout_component *lod_comp = NULL;
7952         int i;
7953
7954         if (!lo->ldo_is_composite)
7955                 return NULL;
7956
7957         for (i = 0; i < lo->ldo_mirror_count; i++) {
7958                 /*
7959                  * FIXME: In the current design, there is only one HSM
7960                  * mirror component in range [0, EOF] for a FLR file. This
7961                  * should be fixed to support multiple HSM mirror components
7962                  * with different HSM backend types and partial file ranges
7963                  * in the future.
7964                  */
7965                 if (lo->ldo_mirrors[i].lme_hsm) {
7966                         __u16 start_idx;
7967                         __u16 end_idx;
7968
7969                         if (hsm_mirror_id)
7970                                 *hsm_mirror_id = i;
7971                         start_idx = lo->ldo_mirrors[i].lme_start;
7972                         end_idx = lo->ldo_mirrors[i].lme_end;
7973                         LASSERT(start_idx == end_idx);
7974                         lod_comp = &lo->ldo_comp_entries[start_idx];
7975                         LASSERT(lo->ldo_is_composite && lod_is_hsm(lod_comp) &&
7976                                 lod_comp->llc_extent.e_start == 0 &&
7977                                 lod_comp->llc_extent.e_end == LUSTRE_EOF);
7978                         break;
7979                 }
7980         }
7981
7982         return lod_comp;
7983 }
7984
7985 static int lod_declare_pccro_set(const struct lu_env *env,
7986                                  struct dt_object *dt, struct thandle *th)
7987 {
7988         struct lod_thread_info *info = lod_env_info(env);
7989         struct lu_buf *buf = &info->lti_buf;
7990         struct lod_object *lo = lod_dt_obj(dt);
7991         struct lod_layout_component *lod_comp;
7992         struct lod_layout_component *comp_array;
7993         struct lod_mirror_entry *mirror_array;
7994         __u16 mirror_id;
7995         int hsm_mirror_id;
7996         int mirror_cnt;
7997         int new_cnt;
7998         int rc;
7999         int i;
8000
8001         ENTRY;
8002
8003         rc = lod_striping_load(env, lo);
8004         if (rc)
8005                 RETURN(rc);
8006
8007         if (lo->ldo_flr_state & LCM_FL_PCC_RDONLY)
8008                 RETURN(-EALREADY);
8009
8010         rc = lod_layout_data_init(info, lo->ldo_comp_cnt);
8011         if (rc)
8012                 RETURN(rc);
8013
8014         lod_comp = lod_locate_comp_hsm(lo, &hsm_mirror_id);
8015         if (lod_comp) {
8016                 if (lod_comp->llc_foreign_flags & HS_PCCRO) {
8017                         CDEBUG(D_LAYOUT, "bad HSM flags: %#x\n",
8018                                lod_comp->llc_foreign_flags);
8019                         RETURN(-EINVAL);
8020                 }
8021
8022                 lod_obj_inc_layout_gen(lo);
8023                 lod_comp->llc_foreign_flags |= HS_PCCRO;
8024                 lod_comp->llc_foreign_flags &= ~HS_DIRTY;
8025                 lod_comp->llc_flags &= ~LCME_FL_STALE;
8026                 lo->ldo_mirrors[hsm_mirror_id].lme_stale = 0;
8027                 lo->ldo_flr_state |= LCM_FL_PCC_RDONLY;
8028                 buf->lb_len = lod_comp_md_size(lo, false);
8029                 rc = lod_sub_declare_xattr_set(env, lod_object_child(lo),
8030                                                buf, XATTR_NAME_LOV, 0, th);
8031                 RETURN(rc);
8032         }
8033
8034         /*
8035          * Create an new composite layout with only one HSM component.
8036          * Field @lhm_archive_uuid is used to be the identifier within HSM
8037          * backend for the archive copy. In the PCC case with a POSIX archive,
8038          * This can just be the original inode FID. This is important because
8039          * the inode FID may change due to layout swaps or migration to a new
8040          * MDT, and we do not want that to cause problems with finding the copy
8041          * in HSM/PCC.
8042          */
8043         mirror_cnt = lo->ldo_mirror_count + 1;
8044         if (!lo->ldo_is_composite) {
8045                 LASSERT(lo->ldo_mirror_count == 0);
8046                 mirror_cnt++;
8047         }
8048
8049         OBD_ALLOC_PTR_ARRAY(mirror_array, mirror_cnt);
8050         if (mirror_array == NULL)
8051                 RETURN(-ENOMEM);
8052
8053         new_cnt = lo->ldo_comp_cnt + 1;
8054         OBD_ALLOC_PTR_ARRAY(comp_array, new_cnt);
8055         if (comp_array == NULL) {
8056                 OBD_FREE_PTR_ARRAY(mirror_array, mirror_cnt);
8057                 RETURN(-ENOMEM);
8058         }
8059
8060         mirror_id = 0;
8061         for (i = 0; i < lo->ldo_comp_cnt; i++) {
8062                 lod_comp = &lo->ldo_comp_entries[i];
8063
8064                 /*
8065                  * Add mirror from a non-flr file, create new mirror ID.
8066                  * Otherwise, keep existing mirror's component ID, used
8067                  * for mirror extension.
8068                  */
8069                 if (lo->ldo_mirror_count == 0 &&
8070                     mirror_id_of(lod_comp->llc_id) == 0)
8071                         lod_comp->llc_id = pflr_id(1, i + 1);
8072
8073                 if (lod_comp->llc_id != LCME_ID_INVAL &&
8074                     mirror_id_of(lod_comp->llc_id) > mirror_id)
8075                         mirror_id = mirror_id_of(lod_comp->llc_id);
8076
8077                 if (!lo->ldo_is_composite) {
8078                         lod_comp->llc_extent.e_start = 0;
8079                         lod_comp->llc_extent.e_end = LUSTRE_EOF;
8080                         lod_comp_set_init(lod_comp);
8081                 }
8082         }
8083
8084         memcpy(comp_array, lo->ldo_comp_entries,
8085                sizeof(*comp_array) * lo->ldo_comp_cnt);
8086
8087         lod_comp = &comp_array[new_cnt - 1];
8088         lod_comp->llc_magic = LOV_MAGIC_FOREIGN;
8089         lod_comp->llc_extent.e_start = 0;
8090         lod_comp->llc_extent.e_end = LUSTRE_EOF;
8091         lod_comp->llc_length = sizeof(struct lov_hsm_base);
8092         lod_comp->llc_type = LU_FOREIGN_TYPE_PCCRO;
8093         lod_comp->llc_foreign_flags = HS_EXISTS | HS_ARCHIVED | HS_PCCRO;
8094         memset(&lod_comp->llc_hsm, 0, sizeof(lod_comp->llc_hsm));
8095
8096         if (lo->ldo_mirrors)
8097                 OBD_FREE_PTR_ARRAY(lo->ldo_mirrors, lo->ldo_mirror_count);
8098         OBD_FREE_PTR_ARRAY(lo->ldo_comp_entries, lo->ldo_comp_cnt);
8099
8100         /*
8101          * The @ldo_mirror will be refilled by lod_fill_mirrors() when
8102          * call lod_striped_create() for layout change.
8103          */
8104         lo->ldo_mirrors = mirror_array;
8105         lo->ldo_mirror_count = mirror_cnt;
8106         lo->ldo_comp_entries = comp_array;
8107         lo->ldo_comp_cnt = new_cnt;
8108         lo->ldo_is_composite = 1;
8109
8110         ++mirror_id;
8111         lod_comp->llc_id = LCME_ID_INVAL;
8112         lod_comp->llc_id = lod_gen_component_id(lo, mirror_id, new_cnt - 1);
8113
8114         if (lo->ldo_flr_state == LCM_FL_NONE)
8115                 lo->ldo_flr_state = LCM_FL_RDONLY;
8116         lo->ldo_flr_state |= LCM_FL_PCC_RDONLY;
8117         buf->lb_len = lod_comp_md_size(lo, false);
8118         rc = lod_sub_declare_xattr_set(env, lod_object_child(lo),
8119                                        buf, XATTR_NAME_LOV, 0, th);
8120         if (rc)
8121                 lod_striping_free(env, lo);
8122
8123         RETURN(rc);
8124 }
8125
8126 /*
8127  * TODO: When clear LCM_FL_PCC_RDONLY flag from the layouts, it means the file
8128  * is going to be modified. Currently it needs two RPCs: first one is to clear
8129  * LCM_FL_PCC_RDONLY flag; the second one is to pick primary mirror and mark
8130  * the file as LCM_FL_WRITE_PENDING.
8131  * These two RPCs can be combined in one RPC call.
8132  */
8133 static int lod_declare_pccro_clear(const struct lu_env *env,
8134                                    struct dt_object *dt, struct thandle *th)
8135 {
8136         struct lod_thread_info *info = lod_env_info(env);
8137         struct lod_object *lo = lod_dt_obj(dt);
8138         struct lod_layout_component *lod_comp;
8139         int rc;
8140
8141         ENTRY;
8142
8143         rc = lod_striping_load(env, lo);
8144         if (rc)
8145                 RETURN(rc);
8146
8147         if (!(lo->ldo_flr_state & LCM_FL_PCC_RDONLY))
8148                 RETURN(-EALREADY);
8149
8150         rc = lod_layout_data_init(info, lo->ldo_comp_cnt);
8151         if (rc)
8152                 RETURN(rc);
8153
8154         lod_comp = lod_locate_comp_hsm(lo, NULL);
8155         if (lod_comp == NULL) {
8156                 CDEBUG(D_LAYOUT, "Not found any HSM component\n");
8157                 GOTO(out, rc = -EINVAL);
8158         }
8159
8160         lod_comp->llc_foreign_flags &= ~HS_PCCRO;
8161         lo->ldo_flr_state &= ~LCM_FL_PCC_RDONLY;
8162         lod_obj_inc_layout_gen(lo);
8163         info->lti_buf.lb_len = lod_comp_md_size(lo, false);
8164         rc = lod_sub_declare_xattr_set(env, lod_object_child(lo),
8165                                        &info->lti_buf, XATTR_NAME_LOV, 0, th);
8166 out:
8167         if (rc)
8168                 lod_striping_free(env, lo);
8169
8170         RETURN(rc);
8171 }
8172
8173 static int lod_declare_update_pccro(const struct lu_env *env,
8174                                     struct dt_object *dt,
8175                                     struct md_layout_change *mlc,
8176                                     struct thandle *th)
8177 {
8178         struct layout_intent *intent = mlc->mlc_intent;
8179         int rc;
8180
8181         switch (intent->li_opc) {
8182         case LAYOUT_INTENT_PCCRO_SET:
8183                 rc = lod_declare_pccro_set(env, dt, th);
8184                 break;
8185         case LAYOUT_INTENT_PCCRO_CLEAR:
8186                 rc = lod_declare_pccro_clear(env, dt, th);
8187                 break;
8188         default:
8189                 rc = -EOPNOTSUPP;
8190                 break;
8191         }
8192
8193         return rc;
8194 }
8195
8196 static int lod_declare_update_rdonly(const struct lu_env *env,
8197                 struct lod_object *lo, struct md_layout_change *mlc,
8198                 struct thandle *th)
8199 {
8200         struct lod_thread_info *info = lod_env_info(env);
8201         struct lu_attr *layout_attr = &info->lti_layout_attr;
8202         struct lod_layout_component *lod_comp;
8203         struct lu_extent extent = { 0 };
8204         int rc;
8205         ENTRY;
8206
8207         LASSERT(lo->ldo_flr_state == LCM_FL_RDONLY);
8208         LASSERT(mlc->mlc_opc == MD_LAYOUT_WRITE ||
8209                 mlc->mlc_opc == MD_LAYOUT_RESYNC);
8210         LASSERT(lo->ldo_mirror_count > 0);
8211
8212         if (mlc->mlc_opc == MD_LAYOUT_WRITE) {
8213                 struct layout_intent *layout = mlc->mlc_intent;
8214                 int write = layout->li_opc == LAYOUT_INTENT_WRITE;
8215                 int picked;
8216
8217                 extent = layout->li_extent;
8218                 CDEBUG(D_LAYOUT, DFID": trying to write :"DEXT"\n",
8219                        PFID(lod_object_fid(lo)), PEXT(&extent));
8220
8221                 picked = lod_primary_pick(env, lo, &extent);
8222                 if (picked < 0)
8223                         RETURN(picked);
8224
8225                 CDEBUG(D_LAYOUT, DFID": picked mirror id %u as primary\n",
8226                        PFID(lod_object_fid(lo)),
8227                        lo->ldo_mirrors[picked].lme_id);
8228
8229                 /* Update extents of primary before staling */
8230                 rc = lod_declare_update_extents(env, lo, &extent, th, picked,
8231                                                 write);
8232                 if (rc < 0)
8233                         GOTO(out, rc);
8234
8235                 if (layout->li_opc == LAYOUT_INTENT_TRUNC) {
8236                         /**
8237                          * trunc transfers [0, size) in the intent extent, we'd
8238                          * stale components overlapping [size, eof).
8239                          */
8240                         extent.e_start = extent.e_end;
8241                         extent.e_end = OBD_OBJECT_EOF;
8242                 }
8243
8244                 /* stale overlapping components from other mirrors */
8245                 rc = lod_stale_components(env, lo, picked, &extent, th);
8246                 if (rc < 0)
8247                         GOTO(out, rc);
8248
8249                 /* restore truncate intent extent */
8250                 if (layout->li_opc == LAYOUT_INTENT_TRUNC)
8251                         extent.e_end = extent.e_start;
8252
8253                 /* instantiate components for the picked mirror, start from 0 */
8254                 extent.e_start = 0;
8255
8256                 lod_foreach_mirror_comp(lod_comp, lo, picked) {
8257                         if (!lu_extent_is_overlapped(&extent,
8258                                                      &lod_comp->llc_extent))
8259                                 break;
8260
8261                         if (!lod_is_instantiation_needed(lod_comp))
8262                                 continue;
8263
8264                         info->lti_comp_idx[info->lti_count++] =
8265                                                 lod_comp_index(lo, lod_comp);
8266                 }
8267
8268                 lo->ldo_flr_state = LCM_FL_WRITE_PENDING;
8269         } else { /* MD_LAYOUT_RESYNC */
8270                 int i;
8271
8272                 /**
8273                  * could contain multiple non-stale mirrors, so we need to
8274                  * prep uninited all components assuming any non-stale mirror
8275                  * could be picked as the primary mirror.
8276                  */
8277                 if (mlc->mlc_mirror_id == 0) {
8278                         /* normal resync */
8279                         for (i = 0; i < lo->ldo_mirror_count; i++) {
8280                                 if (lo->ldo_mirrors[i].lme_stale)
8281                                         continue;
8282
8283                                 lod_foreach_mirror_comp(lod_comp, lo, i) {
8284                                         if (!lod_comp_inited(lod_comp))
8285                                                 break;
8286
8287                                         if (extent.e_end <
8288                                                 lod_comp->llc_extent.e_end)
8289                                                 extent.e_end =
8290                                                      lod_comp->llc_extent.e_end;
8291                                 }
8292                         }
8293                         rc = lod_prepare_resync(env, lo, &extent);
8294                         if (rc)
8295                                 GOTO(out, rc);
8296                 } else {
8297                         /* mirror write, try to init its all components */
8298                         rc = lod_prepare_resync_mirror(env, lo,
8299                                                        mlc->mlc_mirror_id);
8300                         if (rc)
8301                                 GOTO(out, rc);
8302                 }
8303
8304                 /* change the file state to SYNC_PENDING */
8305                 lo->ldo_flr_state = LCM_FL_SYNC_PENDING;
8306         }
8307
8308         /* Reset the layout version once it's becoming too large.
8309          * This way it can make sure that the layout version is
8310          * monotonously increased in this writing era. */
8311         lod_obj_inc_layout_gen(lo);
8312
8313         rc = lod_declare_instantiate_components(env, lo, th, 0);
8314         if (rc)
8315                 GOTO(out, rc);
8316
8317         layout_attr->la_valid = LA_LAYOUT_VERSION;
8318         layout_attr->la_layout_version = 0;
8319         if (mlc->mlc_opc == MD_LAYOUT_RESYNC)
8320                 layout_attr->la_layout_version = LU_LAYOUT_RESYNC;
8321         rc = lod_declare_attr_set(env, &lo->ldo_obj, layout_attr, th);
8322         if (rc)
8323                 GOTO(out, rc);
8324
8325 out:
8326         if (rc)
8327                 lod_striping_free(env, lo);
8328         RETURN(rc);
8329 }
8330
8331 static int lod_declare_update_write_pending(const struct lu_env *env,
8332                 struct lod_object *lo, struct md_layout_change *mlc,
8333                 struct thandle *th)
8334 {
8335         struct lod_thread_info *info = lod_env_info(env);
8336         struct lu_attr *layout_attr = &info->lti_layout_attr;
8337         struct lod_layout_component *lod_comp;
8338         struct lu_extent extent = { 0 };
8339         int primary = -1;
8340         int i;
8341         int rc;
8342         ENTRY;
8343
8344         LASSERT(lo->ldo_flr_state == LCM_FL_WRITE_PENDING);
8345         LASSERT(mlc->mlc_opc == MD_LAYOUT_WRITE ||
8346                 mlc->mlc_opc == MD_LAYOUT_RESYNC);
8347
8348         /* look for the first preferred mirror */
8349         for (i = 0; i < lo->ldo_mirror_count; i++) {
8350                 if (lo->ldo_mirrors[i].lme_stale)
8351                         continue;
8352                 if (lo->ldo_mirrors[i].lme_prefer == 0)
8353                         continue;
8354                 if (lo->ldo_mirrors[i].lme_hsm)
8355                         continue;
8356
8357                 primary = i;
8358                 break;
8359         }
8360         if (primary < 0) {
8361                 /* no primary, use any in-sync */
8362                 for (i = 0; i < lo->ldo_mirror_count; i++) {
8363                         if (lo->ldo_mirrors[i].lme_stale)
8364                                 continue;
8365                         primary = i;
8366                         break;
8367                 }
8368                 if (primary < 0) {
8369                         CERROR(DFID ": doesn't have a primary mirror\n",
8370                                PFID(lod_object_fid(lo)));
8371                         GOTO(out, rc = -ENODATA);
8372                 }
8373         }
8374
8375         CDEBUG(D_LAYOUT, DFID": found primary %u\n",
8376                PFID(lod_object_fid(lo)), lo->ldo_mirrors[primary].lme_id);
8377
8378         LASSERT(!lo->ldo_mirrors[primary].lme_stale);
8379
8380         /* for LAYOUT_WRITE opc, it has to do the following operations:
8381          * 1. stale overlapping componets from stale mirrors;
8382          * 2. instantiate components of the primary mirror;
8383          * 3. transfter layout version to all objects of the primary;
8384          *
8385          * for LAYOUT_RESYNC opc, it will do:
8386          * 1. instantiate components of all stale mirrors;
8387          * 2. transfer layout version to all objects to close write era. */
8388
8389         if (mlc->mlc_opc == MD_LAYOUT_WRITE) {
8390                 struct layout_intent *layout = mlc->mlc_intent;
8391                 int write = layout->li_opc == LAYOUT_INTENT_WRITE;
8392
8393                 LASSERT(mlc->mlc_intent != NULL);
8394
8395                 extent = mlc->mlc_intent->li_extent;
8396
8397                 CDEBUG(D_LAYOUT, DFID": intent to write: "DEXT"\n",
8398                        PFID(lod_object_fid(lo)), PEXT(&extent));
8399
8400                 /* 1. Update extents of primary before staling */
8401                 rc = lod_declare_update_extents(env, lo, &extent, th, primary,
8402                                                 write);
8403                 if (rc < 0)
8404                         GOTO(out, rc);
8405
8406                 if (mlc->mlc_intent->li_opc == LAYOUT_INTENT_TRUNC) {
8407                         /**
8408                          * trunc transfers [0, size) in the intent extent, we'd
8409                          * stale components overlapping [size, eof).
8410                          */
8411                         extent.e_start = extent.e_end;
8412                         extent.e_end = OBD_OBJECT_EOF;
8413                 }
8414
8415                 /* 2. stale overlapping components */
8416                 rc = lod_stale_components(env, lo, primary, &extent, th);
8417                 if (rc < 0)
8418                         GOTO(out, rc);
8419
8420                 /* 3. find the components which need instantiating.
8421                  * instantiate [0, mlc->mlc_intent->e_end) */
8422
8423                 /* restore truncate intent extent */
8424                 if (mlc->mlc_intent->li_opc == LAYOUT_INTENT_TRUNC)
8425                         extent.e_end = extent.e_start;
8426                 extent.e_start = 0;
8427
8428                 lod_foreach_mirror_comp(lod_comp, lo, primary) {
8429                         if (!lu_extent_is_overlapped(&extent,
8430                                                      &lod_comp->llc_extent))
8431                                 break;
8432
8433                         if (!lod_is_instantiation_needed(lod_comp))
8434                                 continue;
8435
8436                         CDEBUG(D_LAYOUT, "write instantiate %d / %d\n",
8437                                primary, lod_comp_index(lo, lod_comp));
8438                         info->lti_comp_idx[info->lti_count++] =
8439                                                 lod_comp_index(lo, lod_comp);
8440                 }
8441         } else { /* MD_LAYOUT_RESYNC */
8442                 if (mlc->mlc_mirror_id == 0) {
8443                         /* normal resync */
8444                         lod_foreach_mirror_comp(lod_comp, lo, primary) {
8445                                 if (!lod_comp_inited(lod_comp))
8446                                         break;
8447
8448                                 extent.e_end = lod_comp->llc_extent.e_end;
8449                         }
8450
8451                         rc = lod_prepare_resync(env, lo, &extent);
8452                         if (rc)
8453                                 GOTO(out, rc);
8454                 } else {
8455                         /* mirror write, try to init its all components */
8456                         rc = lod_prepare_resync_mirror(env, lo,
8457                                                        mlc->mlc_mirror_id);
8458                         if (rc)
8459                                 GOTO(out, rc);
8460                 }
8461
8462                 /* change the file state to SYNC_PENDING */
8463                 lo->ldo_flr_state = LCM_FL_SYNC_PENDING;
8464         }
8465
8466         rc = lod_declare_instantiate_components(env, lo, th, 0);
8467         if (rc)
8468                 GOTO(out, rc);
8469
8470         lod_obj_inc_layout_gen(lo);
8471
8472         /* 3. transfer layout version to OST objects.
8473          * transfer new layout version to OST objects so that stale writes
8474          * can be denied. It also ends an era of writing by setting
8475          * LU_LAYOUT_RESYNC. Normal client can never use this bit to
8476          * send write RPC; only resync RPCs could do it. */
8477         layout_attr->la_valid = LA_LAYOUT_VERSION;
8478         layout_attr->la_layout_version = 0;
8479         if (mlc->mlc_opc == MD_LAYOUT_RESYNC)
8480                 layout_attr->la_layout_version = LU_LAYOUT_RESYNC;
8481         rc = lod_declare_attr_set(env, &lo->ldo_obj, layout_attr, th);
8482         if (rc)
8483                 GOTO(out, rc);
8484 out:
8485         if (rc)
8486                 lod_striping_free(env, lo);
8487         RETURN(rc);
8488 }
8489
8490 static int lod_declare_update_sync_pending(const struct lu_env *env,
8491                 struct lod_object *lo, struct md_layout_change *mlc,
8492                 struct thandle *th)
8493 {
8494         struct lod_thread_info  *info = lod_env_info(env);
8495         struct lu_attr *layout_attr = &info->lti_layout_attr;
8496         unsigned sync_components = 0;
8497         unsigned resync_components = 0;
8498         int i;
8499         int rc;
8500         ENTRY;
8501
8502         LASSERT(lo->ldo_flr_state == LCM_FL_SYNC_PENDING);
8503         LASSERT(mlc->mlc_opc == MD_LAYOUT_RESYNC_DONE ||
8504                 mlc->mlc_opc == MD_LAYOUT_WRITE);
8505
8506         CDEBUG(D_LAYOUT, DFID ": received op %d in sync pending\n",
8507                PFID(lod_object_fid(lo)), mlc->mlc_opc);
8508
8509         if (mlc->mlc_opc == MD_LAYOUT_WRITE) {
8510                 CDEBUG(D_LAYOUT, DFID": cocurrent write to sync pending\n",
8511                        PFID(lod_object_fid(lo)));
8512
8513                 lo->ldo_flr_state = LCM_FL_WRITE_PENDING;
8514                 return lod_declare_update_write_pending(env, lo, mlc, th);
8515         }
8516
8517         /* MD_LAYOUT_RESYNC_DONE */
8518
8519         for (i = 0; i < lo->ldo_comp_cnt; i++) {
8520                 struct lod_layout_component *lod_comp;
8521                 int j;
8522
8523                 lod_comp = &lo->ldo_comp_entries[i];
8524
8525                 if (!(lod_comp->llc_flags & LCME_FL_STALE)) {
8526                         sync_components++;
8527                         continue;
8528                 }
8529
8530                 for (j = 0; j < mlc->mlc_resync_count; j++) {
8531                         if (lod_comp->llc_id != mlc->mlc_resync_ids[j])
8532                                 continue;
8533
8534                         mlc->mlc_resync_ids[j] = LCME_ID_INVAL;
8535                         lod_comp->llc_flags &= ~LCME_FL_STALE;
8536                         resync_components++;
8537                         break;
8538                 }
8539         }
8540
8541         /* valid check */
8542         for (i = 0; i < mlc->mlc_resync_count; i++) {
8543                 if (mlc->mlc_resync_ids[i] == LCME_ID_INVAL)
8544                         continue;
8545
8546                 CDEBUG(D_LAYOUT, DFID": lcme id %u (%d / %zd) not exist "
8547                        "or already synced\n", PFID(lod_object_fid(lo)),
8548                        mlc->mlc_resync_ids[i], i, mlc->mlc_resync_count);
8549                 GOTO(out, rc = -EINVAL);
8550         }
8551
8552         if (!sync_components || (mlc->mlc_resync_count && !resync_components)) {
8553                 CDEBUG(D_LAYOUT, DFID": no mirror in sync\n",
8554                        PFID(lod_object_fid(lo)));
8555
8556                 /* tend to return an error code here to prevent
8557                  * the MDT from setting SoM attribute */
8558                 GOTO(out, rc = -EINVAL);
8559         }
8560
8561         CDEBUG(D_LAYOUT, DFID": synced %u resynced %u/%zu components\n",
8562                PFID(lod_object_fid(lo)),
8563                sync_components, resync_components, mlc->mlc_resync_count);
8564
8565         lo->ldo_flr_state = LCM_FL_RDONLY;
8566         lod_obj_inc_layout_gen(lo);
8567
8568         layout_attr->la_valid = LA_LAYOUT_VERSION;
8569         layout_attr->la_layout_version = 0;
8570         rc = lod_declare_attr_set(env, &lo->ldo_obj, layout_attr, th);
8571         if (rc)
8572                 GOTO(out, rc);
8573
8574         info->lti_buf.lb_len = lod_comp_md_size(lo, false);
8575         rc = lod_sub_declare_xattr_set(env, lod_object_child(lo),
8576                                        &info->lti_buf, XATTR_NAME_LOV, 0, th);
8577         EXIT;
8578
8579 out:
8580         if (rc)
8581                 lod_striping_free(env, lo);
8582         RETURN(rc);
8583 }
8584
8585 typedef int (*mlc_handler)(const struct lu_env *env, struct dt_object *dt,
8586                            const struct md_layout_change *mlc,
8587                            struct thandle *th);
8588
8589 /**
8590  * Attach stripes after target's for migrating directory. NB, we
8591  * only need to declare this, the actual work is done inside
8592  * lod_xattr_set_lmv().
8593  *
8594  * \param[in] env       execution environment
8595  * \param[in] dt        target object
8596  * \param[in] mlc       layout change data
8597  * \param[in] th        transaction handle
8598  *
8599  * \retval              0 on success
8600  * \retval              negative if failed
8601  */
8602 static int lod_dir_declare_layout_attach(const struct lu_env *env,
8603                                          struct dt_object *dt,
8604                                          const struct md_layout_change *mlc,
8605                                          struct thandle *th)
8606 {
8607         struct lod_thread_info *info = lod_env_info(env);
8608         struct lod_device *lod = lu2lod_dev(dt->do_lu.lo_dev);
8609         struct lod_tgt_descs *ltd = &lod->lod_mdt_descs;
8610         struct lod_object *lo = lod_dt_obj(dt);
8611         struct dt_object *next = dt_object_child(dt);
8612         struct dt_object_format *dof = &info->lti_format;
8613         struct lmv_mds_md_v1 *lmv = mlc->mlc_buf.lb_buf;
8614         struct dt_object **stripes;
8615         __u32 stripe_count = le32_to_cpu(lmv->lmv_stripe_count);
8616         struct lu_fid *fid = &info->lti_fid;
8617         struct lod_tgt_desc *tgt;
8618         struct dt_object *dto;
8619         struct dt_device *tgt_dt;
8620         int type = LU_SEQ_RANGE_ANY;
8621         struct dt_insert_rec *rec = &info->lti_dt_rec;
8622         char *stripe_name = info->lti_key;
8623         struct lu_name *sname;
8624         struct linkea_data ldata = { NULL };
8625         struct lu_buf linkea_buf;
8626         __u32 idx;
8627         int i;
8628         int rc;
8629
8630         ENTRY;
8631
8632         if (!lmv_is_sane(lmv))
8633                 RETURN(-EINVAL);
8634
8635         if (!dt_try_as_dir(env, dt, false))
8636                 RETURN(-ENOTDIR);
8637
8638         dof->dof_type = DFT_DIR;
8639
8640         OBD_ALLOC_PTR_ARRAY(stripes, (lo->ldo_dir_stripe_count + stripe_count));
8641         if (!stripes)
8642                 RETURN(-ENOMEM);
8643
8644         for (i = 0; i < lo->ldo_dir_stripe_count; i++)
8645                 stripes[i] = lo->ldo_stripe[i];
8646
8647         rec->rec_type = S_IFDIR;
8648
8649         for (i = 0; i < stripe_count; i++) {
8650                 fid_le_to_cpu(fid,
8651                         &lmv->lmv_stripe_fids[i]);
8652                 if (!fid_is_sane(fid))
8653                         continue;
8654
8655                 rc = lod_fld_lookup(env, lod, fid, &idx, &type);
8656                 if (rc)
8657                         GOTO(out, rc);
8658
8659                 if (idx == lod2lu_dev(lod)->ld_site->ld_seq_site->ss_node_id) {
8660                         tgt_dt = lod->lod_child;
8661                 } else {
8662                         tgt = LTD_TGT(ltd, idx);
8663                         if (tgt == NULL)
8664                                 GOTO(out, rc = -ESTALE);
8665                         tgt_dt = tgt->ltd_tgt;
8666                 }
8667
8668                 dto = dt_locate_at(env, tgt_dt, fid,
8669                                   lo->ldo_obj.do_lu.lo_dev->ld_site->ls_top_dev,
8670                                   NULL);
8671                 if (IS_ERR(dto))
8672                         GOTO(out, rc = PTR_ERR(dto));
8673
8674                 stripes[i + lo->ldo_dir_stripe_count] = dto;
8675
8676                 if (!dt_try_as_dir(env, dto, true))
8677                         GOTO(out, rc = -ENOTDIR);
8678
8679                 rc = lod_sub_declare_ref_add(env, dto, th);
8680                 if (rc)
8681                         GOTO(out, rc);
8682
8683                 rec->rec_fid = lu_object_fid(&dto->do_lu);
8684                 rc = lod_sub_declare_insert(env, dto,
8685                                             (const struct dt_rec *)rec,
8686                                             (const struct dt_key *)dot, th);
8687                 if (rc)
8688                         GOTO(out, rc);
8689
8690                 rc = lod_sub_declare_insert(env, dto,
8691                                             (const struct dt_rec *)rec,
8692                                             (const struct dt_key *)dotdot, th);
8693                 if (rc)
8694                         GOTO(out, rc);
8695
8696                 rc = lod_sub_declare_xattr_set(env, dto, &mlc->mlc_buf,
8697                                                 XATTR_NAME_LMV, 0, th);
8698                 if (rc)
8699                         GOTO(out, rc);
8700
8701                 snprintf(stripe_name, sizeof(info->lti_key), DFID":%u",
8702                          PFID(lu_object_fid(&dto->do_lu)),
8703                          i + lo->ldo_dir_stripe_count);
8704
8705                 sname = lod_name_get(env, stripe_name, strlen(stripe_name));
8706                 rc = linkea_links_new(&ldata, &info->lti_linkea_buf,
8707                                       sname, lu_object_fid(&dt->do_lu));
8708                 if (rc)
8709                         GOTO(out, rc);
8710
8711                 linkea_buf.lb_buf = ldata.ld_buf->lb_buf;
8712                 linkea_buf.lb_len = ldata.ld_leh->leh_len;
8713                 rc = lod_sub_declare_xattr_set(env, dto, &linkea_buf,
8714                                                XATTR_NAME_LINK, 0, th);
8715                 if (rc)
8716                         GOTO(out, rc);
8717
8718                 rc = lod_sub_declare_insert(env, next,
8719                                             (const struct dt_rec *)rec,
8720                                             (const struct dt_key *)stripe_name,
8721                                             th);
8722                 if (rc)
8723                         GOTO(out, rc);
8724
8725                 rc = lod_sub_declare_ref_add(env, next, th);
8726                 if (rc)
8727                         GOTO(out, rc);
8728         }
8729
8730         if (lo->ldo_stripe)
8731                 OBD_FREE_PTR_ARRAY(lo->ldo_stripe,
8732                                    lo->ldo_dir_stripes_allocated);
8733         lo->ldo_stripe = stripes;
8734         lo->ldo_is_foreign = 0;
8735         lo->ldo_dir_migrate_offset = lo->ldo_dir_stripe_count;
8736         lo->ldo_dir_migrate_hash = le32_to_cpu(lmv->lmv_hash_type);
8737         lo->ldo_dir_stripe_count += stripe_count;
8738         lo->ldo_dir_layout_version++;
8739         lo->ldo_dir_stripes_allocated += stripe_count;
8740
8741         /* plain directory split creates target as a plain directory, while
8742          * after source attached as the first stripe, it becomes a striped
8743          * directory, set correct do_index_ops, otherwise it can't be unlinked.
8744          */
8745         dt->do_index_ops = &lod_striped_index_ops;
8746
8747         RETURN(0);
8748 out:
8749         i = lo->ldo_dir_stripe_count;
8750         while (i < lo->ldo_dir_stripe_count + stripe_count && stripes[i])
8751                 dt_object_put(env, stripes[i++]);
8752
8753         OBD_FREE_PTR_ARRAY(stripes, stripe_count + lo->ldo_dir_stripe_count);
8754         return rc;
8755 }
8756
8757 static int lod_dir_declare_layout_detach(const struct lu_env *env,
8758                                          struct dt_object *dt,
8759                                          const struct md_layout_change *unused,
8760                                          struct thandle *th)
8761 {
8762         struct lod_thread_info *info = lod_env_info(env);
8763         struct lod_object *lo = lod_dt_obj(dt);
8764         struct dt_object *next = dt_object_child(dt);
8765         char *stripe_name = info->lti_key;
8766         struct dt_object *dto;
8767         int i;
8768         int rc = 0;
8769
8770         if (!dt_try_as_dir(env, dt, true))
8771                 return -ENOTDIR;
8772
8773         if (!lo->ldo_dir_stripe_count)
8774                 return lod_sub_declare_delete(env, next,
8775                                         (const struct dt_key *)dotdot, th);
8776
8777         for (i = 0; i < lo->ldo_dir_stripe_count; i++) {
8778                 dto = lo->ldo_stripe[i];
8779                 if (!dto)
8780                         continue;
8781
8782                 if (!dt_try_as_dir(env, dto, true))
8783                         return -ENOTDIR;
8784
8785                 rc = lod_sub_declare_delete(env, dto,
8786                                         (const struct dt_key *)dotdot, th);
8787                 if (rc)
8788                         return rc;
8789
8790                 snprintf(stripe_name, sizeof(info->lti_key), DFID":%d",
8791                          PFID(lu_object_fid(&dto->do_lu)), i);
8792
8793                 rc = lod_sub_declare_delete(env, next,
8794                                         (const struct dt_key *)stripe_name, th);
8795                 if (rc)
8796                         return rc;
8797
8798                 rc = lod_sub_declare_ref_del(env, next, th);
8799                 if (rc)
8800                         return rc;
8801         }
8802
8803         return 0;
8804 }
8805
8806 static int dt_dir_is_empty(const struct lu_env *env,
8807                            struct dt_object *obj)
8808 {
8809         struct dt_it *it;
8810         const struct dt_it_ops *iops;
8811         int rc;
8812
8813         ENTRY;
8814
8815         if (!dt_try_as_dir(env, obj, true))
8816                 RETURN(-ENOTDIR);
8817
8818         iops = &obj->do_index_ops->dio_it;
8819         it = iops->init(env, obj, LUDA_64BITHASH);
8820         if (IS_ERR(it))
8821                 RETURN(PTR_ERR(it));
8822
8823         rc = iops->get(env, it, (const struct dt_key *)"");
8824         if (rc > 0) {
8825                 int i;
8826
8827                 for (rc = 0, i = 0; rc == 0 && i < 3; ++i)
8828                         rc = iops->next(env, it);
8829                 if (!rc)
8830                         rc = -ENOTEMPTY;
8831                 else if (rc == 1)
8832                         rc = 0;
8833         } else if (!rc) {
8834                 /* Huh? Index contains no zero key? */
8835                 rc = -EIO;
8836         }
8837
8838         iops->put(env, it);
8839         iops->fini(env, it);
8840
8841         RETURN(rc);
8842 }
8843
8844 static int lod_dir_declare_layout_shrink(const struct lu_env *env,
8845                                          struct dt_object *dt,
8846                                          const struct md_layout_change *mlc,
8847                                          struct thandle *th)
8848 {
8849         struct lod_thread_info *info = lod_env_info(env);
8850         struct lod_object *lo = lod_dt_obj(dt);
8851         struct dt_object *next = dt_object_child(dt);
8852         struct lmv_user_md *lmu = mlc->mlc_buf.lb_buf;
8853         char *stripe_name = info->lti_key;
8854         struct lu_buf *lmv_buf = &info->lti_buf;
8855         __u32 final_stripe_count;
8856         struct dt_object *dto;
8857         int i;
8858         int rc;
8859
8860         LASSERT(lmu);
8861
8862         if (!dt_try_as_dir(env, dt, true))
8863                 return -ENOTDIR;
8864
8865         /* shouldn't be called on plain directory */
8866         LASSERT(lo->ldo_dir_stripe_count);
8867
8868         lmv_buf->lb_buf = &info->lti_lmv.lmv_md_v1;
8869         lmv_buf->lb_len = sizeof(info->lti_lmv.lmv_md_v1);
8870
8871         final_stripe_count = le32_to_cpu(lmu->lum_stripe_count);
8872         LASSERT(final_stripe_count &&
8873                 final_stripe_count < lo->ldo_dir_stripe_count);
8874
8875         for (i = 0; i < lo->ldo_dir_stripe_count; i++) {
8876                 dto = lo->ldo_stripe[i];
8877                 if (!dto)
8878                         continue;
8879
8880                 if (i < final_stripe_count) {
8881                         rc = lod_sub_declare_xattr_set(env, dto, lmv_buf,
8882                                                        XATTR_NAME_LMV,
8883                                                        LU_XATTR_REPLACE, th);
8884                         if (rc)
8885                                 return rc;
8886
8887                         continue;
8888                 }
8889
8890                 rc = dt_dir_is_empty(env, dto);
8891                 if (rc < 0)
8892                         return rc;
8893
8894                 rc = lod_sub_declare_ref_del(env, dto, th);
8895                 if (rc)
8896                         return rc;
8897
8898                 rc = lod_sub_declare_destroy(env, dto, th);
8899                 if (rc)
8900                         return rc;
8901
8902                 snprintf(stripe_name, sizeof(info->lti_key), DFID":%d",
8903                          PFID(lu_object_fid(&dto->do_lu)), i);
8904
8905                 rc = lod_sub_declare_delete(env, next,
8906                                         (const struct dt_key *)stripe_name, th);
8907                 if (rc)
8908                         return rc;
8909
8910                 rc = lod_sub_declare_ref_del(env, next, th);
8911                 if (rc)
8912                         return rc;
8913         }
8914
8915         rc = lod_sub_declare_xattr_set(env, next, lmv_buf, XATTR_NAME_LMV,
8916                                        LU_XATTR_REPLACE, th);
8917         return rc;
8918 }
8919
8920 /**
8921  * Allocate stripes for split directory.
8922  *
8923  * \param[in] env       execution environment
8924  * \param[in] dt        target object
8925  * \param[in] mlc       layout change data
8926  * \param[in] th        transaction handle
8927  *
8928  * \retval              0 on success
8929  * \retval              negative if failed
8930  */
8931 static int lod_dir_declare_layout_split(const struct lu_env *env,
8932                                         struct dt_object *dt,
8933                                         const struct md_layout_change *mlc,
8934                                         struct thandle *th)
8935 {
8936         struct lod_thread_info *info = lod_env_info(env);
8937         struct lod_device *lod = lu2lod_dev(dt->do_lu.lo_dev);
8938         struct lod_object *lo = lod_dt_obj(dt);
8939         struct dt_object_format *dof = &info->lti_format;
8940         struct lmv_user_md_v1 *lum = mlc->mlc_spec->u.sp_ea.eadata;
8941         struct dt_object **stripes;
8942         u32 stripe_count;
8943         u32 saved_count;
8944         int i;
8945         int rc;
8946
8947         ENTRY;
8948
8949         LASSERT(le32_to_cpu(lum->lum_magic) == LMV_USER_MAGIC);
8950         LASSERT(le32_to_cpu(lum->lum_stripe_offset) == LMV_OFFSET_DEFAULT);
8951
8952         saved_count = lo->ldo_dir_stripes_allocated;
8953         stripe_count = le32_to_cpu(lum->lum_stripe_count);
8954         if (stripe_count <= saved_count)
8955                 RETURN(-EINVAL);
8956
8957         dof->dof_type = DFT_DIR;
8958
8959         OBD_ALLOC(stripes, sizeof(*stripes) * stripe_count);
8960         if (!stripes)
8961                 RETURN(-ENOMEM);
8962
8963         for (i = 0; i < lo->ldo_dir_stripes_allocated; i++)
8964                 stripes[i] = lo->ldo_stripe[i];
8965
8966         lod_qos_statfs_update(env, lod, &lod->lod_mdt_descs);
8967         rc = lod_mdt_alloc_qos(env, lo, stripes, saved_count, stripe_count);
8968         if (rc == -EAGAIN)
8969                 rc = lod_mdt_alloc_rr(env, lo, stripes, saved_count,
8970                                       stripe_count);
8971         if (rc < 0) {
8972                 OBD_FREE(stripes, sizeof(*stripes) * stripe_count);
8973                 RETURN(rc);
8974         }
8975
8976         LASSERT(rc > saved_count);
8977         OBD_FREE(lo->ldo_stripe,
8978                  sizeof(*stripes) * lo->ldo_dir_stripes_allocated);
8979         lo->ldo_stripe = stripes;
8980         lo->ldo_is_foreign = 0;
8981         lo->ldo_dir_striped = 1;
8982         lo->ldo_dir_stripe_count = rc;
8983         lo->ldo_dir_stripes_allocated = stripe_count;
8984         lo->ldo_dir_split_hash = lo->ldo_dir_hash_type;
8985         lo->ldo_dir_hash_type = le32_to_cpu(lum->lum_hash_type);
8986         if (!lmv_is_known_hash_type(lo->ldo_dir_hash_type))
8987                 lo->ldo_dir_hash_type =
8988                         lod->lod_mdt_descs.ltd_lmv_desc.ld_pattern;
8989         lo->ldo_dir_hash_type |= LMV_HASH_FLAG_SPLIT | LMV_HASH_FLAG_MIGRATION;
8990         lo->ldo_dir_split_offset = saved_count;
8991         lo->ldo_dir_layout_version++;
8992         lo->ldo_dir_stripe_loaded = 1;
8993
8994         rc = lod_dir_declare_create_stripes(env, dt, mlc->mlc_attr, dof, th);
8995         if (rc)
8996                 lod_striping_free(env, lo);
8997
8998         RETURN(rc);
8999 }
9000
9001 /*
9002  * detach all stripes from dir master object, NB, stripes are not destroyed, but
9003  * deleted from it's parent namespace, this function is called in two places:
9004  * 1. mdd_migrate_mdt() detach stripes from source, and attach them to
9005  *    target.
9006  * 2. mdd_dir_layout_update() detach stripe before turning 1-stripe directory to
9007  *    a plain directory.
9008  *
9009  * \param[in] env       execution environment
9010  * \param[in] dt        target object
9011  * \param[in] mlc       layout change data
9012  * \param[in] th        transaction handle
9013  *
9014  * \retval              0 on success
9015  * \retval              negative if failed
9016  */
9017 static int lod_dir_layout_detach(const struct lu_env *env,
9018                                  struct dt_object *dt,
9019                                  const struct md_layout_change *mlc,
9020                                  struct thandle *th)
9021 {
9022         struct lod_thread_info *info = lod_env_info(env);
9023         struct lod_object *lo = lod_dt_obj(dt);
9024         struct dt_object *next = dt_object_child(dt);
9025         char *stripe_name = info->lti_key;
9026         struct dt_object *dto;
9027         int i;
9028         int rc = 0;
9029
9030         ENTRY;
9031
9032         if (!lo->ldo_dir_stripe_count) {
9033                 /* plain directory delete .. */
9034                 rc = lod_sub_delete(env, next,
9035                                     (const struct dt_key *)dotdot, th);
9036                 RETURN(rc);
9037         }
9038
9039         for (i = 0; i < lo->ldo_dir_stripe_count; i++) {
9040                 dto = lo->ldo_stripe[i];
9041                 if (!dto)
9042                         continue;
9043
9044                 rc = lod_sub_delete(env, dto,
9045                                     (const struct dt_key *)dotdot, th);
9046                 if (rc)
9047                         break;
9048
9049                 snprintf(stripe_name, sizeof(info->lti_key), DFID":%d",
9050                          PFID(lu_object_fid(&dto->do_lu)), i);
9051
9052                 rc = lod_sub_delete(env, next,
9053                                     (const struct dt_key *)stripe_name, th);
9054                 if (rc)
9055                         break;
9056
9057                 rc = lod_sub_ref_del(env, next, th);
9058                 if (rc)
9059                         break;
9060         }
9061
9062         for (i = 0; i < lo->ldo_dir_stripe_count; i++) {
9063                 dto = lo->ldo_stripe[i];
9064                 if (dto)
9065                         dt_object_put(env, dto);
9066         }
9067         OBD_FREE_PTR_ARRAY(lo->ldo_stripe, lo->ldo_dir_stripes_allocated);
9068         lo->ldo_stripe = NULL;
9069         lo->ldo_dir_stripes_allocated = 0;
9070         lo->ldo_dir_stripe_count = 0;
9071         dt->do_index_ops = &lod_index_ops;
9072
9073         RETURN(rc);
9074 }
9075
9076 static int lod_dir_layout_shrink(const struct lu_env *env,
9077                                  struct dt_object *dt,
9078                                  const struct md_layout_change *mlc,
9079                                  struct thandle *th)
9080 {
9081         struct lod_thread_info *info = lod_env_info(env);
9082         struct lod_object *lo = lod_dt_obj(dt);
9083         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
9084         struct dt_object *next = dt_object_child(dt);
9085         struct lmv_user_md *lmu = mlc->mlc_buf.lb_buf;
9086         __u32 final_stripe_count;
9087         char *stripe_name = info->lti_key;
9088         struct dt_object *dto;
9089         struct lu_buf *lmv_buf = &info->lti_buf;
9090         struct lmv_mds_md_v1 *lmv = &info->lti_lmv.lmv_md_v1;
9091         u32 mdtidx;
9092         int type = LU_SEQ_RANGE_ANY;
9093         int i;
9094         int rc;
9095
9096         ENTRY;
9097
9098         final_stripe_count = le32_to_cpu(lmu->lum_stripe_count);
9099
9100         lmv_buf->lb_buf = lmv;
9101         lmv_buf->lb_len = sizeof(*lmv);
9102         lmv->lmv_magic = cpu_to_le32(LMV_MAGIC_STRIPE);
9103         lmv->lmv_stripe_count = cpu_to_le32(final_stripe_count);
9104         lmv->lmv_hash_type = cpu_to_le32(lo->ldo_dir_hash_type) &
9105                              cpu_to_le32(LMV_HASH_TYPE_MASK |
9106                                          LMV_HASH_FLAG_FIXED);
9107         lmv->lmv_layout_version =
9108                         cpu_to_le32(lo->ldo_dir_layout_version + 1);
9109         lmv->lmv_migrate_offset = 0;
9110         lmv->lmv_migrate_hash = 0;
9111
9112         for (i = 0; i < lo->ldo_dir_stripe_count; i++) {
9113                 dto = lo->ldo_stripe[i];
9114                 if (!dto)
9115                         continue;
9116
9117                 if (i < final_stripe_count) {
9118                         rc = lod_fld_lookup(env, lod,
9119                                             lu_object_fid(&dto->do_lu),
9120                                             &mdtidx, &type);
9121                         if (rc)
9122                                 RETURN(rc);
9123
9124                         lmv->lmv_master_mdt_index = cpu_to_le32(mdtidx);
9125                         rc = lod_sub_xattr_set(env, dto, lmv_buf,
9126                                                XATTR_NAME_LMV,
9127                                                LU_XATTR_REPLACE, th);
9128                         if (rc)
9129                                 RETURN(rc);
9130
9131                         continue;
9132                 }
9133
9134                 dt_write_lock(env, dto, DT_TGT_CHILD);
9135                 rc = lod_sub_ref_del(env, dto, th);
9136                 dt_write_unlock(env, dto);
9137                 if (rc)
9138                         RETURN(rc);
9139
9140                 rc = lod_sub_destroy(env, dto, th);
9141                 if (rc)
9142                         RETURN(rc);
9143
9144                 snprintf(stripe_name, sizeof(info->lti_key), DFID":%d",
9145                          PFID(lu_object_fid(&dto->do_lu)), i);
9146
9147                 rc = lod_sub_delete(env, next,
9148                                     (const struct dt_key *)stripe_name, th);
9149                 if (rc)
9150                         RETURN(rc);
9151
9152                 rc = lod_sub_ref_del(env, next, th);
9153                 if (rc)
9154                         RETURN(rc);
9155         }
9156
9157         rc = lod_fld_lookup(env, lod, lu_object_fid(&dt->do_lu), &mdtidx,
9158                             &type);
9159         if (rc)
9160                 RETURN(rc);
9161
9162         lmv->lmv_magic = cpu_to_le32(LMV_MAGIC_V1);
9163         lmv->lmv_master_mdt_index = cpu_to_le32(mdtidx);
9164         rc = lod_sub_xattr_set(env, next, lmv_buf, XATTR_NAME_LMV,
9165                                LU_XATTR_REPLACE, th);
9166         if (rc)
9167                 RETURN(rc);
9168
9169         for (i = final_stripe_count; i < lo->ldo_dir_stripe_count; i++) {
9170                 dto = lo->ldo_stripe[i];
9171                 if (dto)
9172                         dt_object_put(env, dto);
9173         }
9174         lo->ldo_dir_stripe_count = final_stripe_count;
9175
9176         RETURN(rc);
9177 }
9178
9179 static mlc_handler dir_mlc_declare_ops[MD_LAYOUT_MAX] = {
9180         [MD_LAYOUT_ATTACH] = lod_dir_declare_layout_attach,
9181         [MD_LAYOUT_DETACH] = lod_dir_declare_layout_detach,
9182         [MD_LAYOUT_SHRINK] = lod_dir_declare_layout_shrink,
9183         [MD_LAYOUT_SPLIT]  = lod_dir_declare_layout_split,
9184 };
9185
9186 static mlc_handler dir_mlc_ops[MD_LAYOUT_MAX] = {
9187         [MD_LAYOUT_DETACH] = lod_dir_layout_detach,
9188         [MD_LAYOUT_SHRINK] = lod_dir_layout_shrink,
9189 };
9190
9191 static int lod_declare_layout_change(const struct lu_env *env,
9192                 struct dt_object *dt, struct md_layout_change *mlc,
9193                 struct thandle *th)
9194 {
9195         struct lod_thread_info  *info = lod_env_info(env);
9196         struct lod_object *lo = lod_dt_obj(dt);
9197         int rc;
9198
9199         ENTRY;
9200
9201         if (S_ISDIR(dt->do_lu.lo_header->loh_attr)) {
9202                 LASSERT(dir_mlc_declare_ops[mlc->mlc_opc]);
9203                 rc = dir_mlc_declare_ops[mlc->mlc_opc](env, dt, mlc, th);
9204                 RETURN(rc);
9205         }
9206
9207         if (!S_ISREG(dt->do_lu.lo_header->loh_attr) || !dt_object_exists(dt) ||
9208             dt_object_remote(dt_object_child(dt)))
9209                 RETURN(-EINVAL);
9210
9211         if (mlc->mlc_opc == MD_LAYOUT_WRITE) {
9212                 struct layout_intent *intent = mlc->mlc_intent;
9213
9214                 if (intent->li_opc == LAYOUT_INTENT_PCCRO_SET ||
9215                     intent->li_opc == LAYOUT_INTENT_PCCRO_CLEAR) {
9216                         if (!S_ISREG(dt->do_lu.lo_header->loh_attr))
9217                                 RETURN(-EINVAL);
9218
9219                         rc = lod_declare_update_pccro(env, dt, mlc, th);
9220                         RETURN(rc);
9221                 }
9222         }
9223
9224         rc = lod_striping_load(env, lo);
9225         if (rc)
9226                 GOTO(out, rc);
9227
9228         LASSERT(lo->ldo_comp_cnt > 0);
9229
9230         rc = lod_layout_data_init(info, lo->ldo_comp_cnt);
9231         if (rc)
9232                 GOTO(out, rc);
9233
9234         switch (lo->ldo_flr_state) {
9235         case LCM_FL_NONE:
9236                 rc = lod_declare_update_plain(env, lo, mlc->mlc_intent,
9237                                               &mlc->mlc_buf, th);
9238                 break;
9239         case LCM_FL_RDONLY:
9240                 rc = lod_declare_update_rdonly(env, lo, mlc, th);
9241                 break;
9242         case LCM_FL_WRITE_PENDING:
9243                 rc = lod_declare_update_write_pending(env, lo, mlc, th);
9244                 break;
9245         case LCM_FL_SYNC_PENDING:
9246                 rc = lod_declare_update_sync_pending(env, lo, mlc, th);
9247                 break;
9248         default:
9249                 rc = -ENOTSUPP;
9250                 break;
9251         }
9252 out:
9253         RETURN(rc);
9254 }
9255
9256 /**
9257  * Instantiate layout component objects which covers the intent write offset.
9258  */
9259 static int lod_layout_change(const struct lu_env *env, struct dt_object *dt,
9260                              struct md_layout_change *mlc, struct thandle *th)
9261 {
9262         struct lu_attr *attr = &lod_env_info(env)->lti_attr;
9263         struct lu_attr *layout_attr = &lod_env_info(env)->lti_layout_attr;
9264         struct lod_object *lo = lod_dt_obj(dt);
9265         int rc;
9266
9267         ENTRY;
9268
9269         if (S_ISDIR(dt->do_lu.lo_header->loh_attr)) {
9270                 LASSERT(dir_mlc_ops[mlc->mlc_opc]);
9271                 rc = dir_mlc_ops[mlc->mlc_opc](env, dt, mlc, th);
9272                 RETURN(rc);
9273         }
9274
9275         rc = lod_striped_create(env, dt, attr, NULL, th);
9276         if (!rc && layout_attr->la_valid & LA_LAYOUT_VERSION) {
9277                 layout_attr->la_layout_version |= lo->ldo_layout_gen;
9278                 rc = lod_attr_set(env, dt, layout_attr, th);
9279         }
9280
9281         RETURN(rc);
9282 }
9283
9284 const struct dt_object_operations lod_obj_ops = {
9285         .do_read_lock           = lod_read_lock,
9286         .do_write_lock          = lod_write_lock,
9287         .do_read_unlock         = lod_read_unlock,
9288         .do_write_unlock        = lod_write_unlock,
9289         .do_write_locked        = lod_write_locked,
9290         .do_attr_get            = lod_attr_get,
9291         .do_declare_attr_set    = lod_declare_attr_set,
9292         .do_attr_set            = lod_attr_set,
9293         .do_xattr_get           = lod_xattr_get,
9294         .do_declare_xattr_set   = lod_declare_xattr_set,
9295         .do_xattr_set           = lod_xattr_set,
9296         .do_declare_xattr_del   = lod_declare_xattr_del,
9297         .do_xattr_del           = lod_xattr_del,
9298         .do_xattr_list          = lod_xattr_list,
9299         .do_ah_init             = lod_ah_init,
9300         .do_declare_create      = lod_declare_create,
9301         .do_create              = lod_create,
9302         .do_declare_destroy     = lod_declare_destroy,
9303         .do_destroy             = lod_destroy,
9304         .do_index_try           = lod_index_try,
9305         .do_declare_ref_add     = lod_declare_ref_add,
9306         .do_ref_add             = lod_ref_add,
9307         .do_declare_ref_del     = lod_declare_ref_del,
9308         .do_ref_del             = lod_ref_del,
9309         .do_object_sync         = lod_object_sync,
9310         .do_object_lock         = lod_object_lock,
9311         .do_object_unlock       = lod_object_unlock,
9312         .do_invalidate          = lod_invalidate,
9313         .do_declare_layout_change = lod_declare_layout_change,
9314         .do_layout_change       = lod_layout_change,
9315 };
9316
9317 /**
9318  * Implementation of dt_body_operations::dbo_read.
9319  *
9320  * \see dt_body_operations::dbo_read() in the API description for details.
9321  */
9322 static ssize_t lod_read(const struct lu_env *env, struct dt_object *dt,
9323                         struct lu_buf *buf, loff_t *pos)
9324 {
9325         struct dt_object *next = dt_object_child(dt);
9326
9327         LASSERT(S_ISREG(dt->do_lu.lo_header->loh_attr) ||
9328                 S_ISLNK(dt->do_lu.lo_header->loh_attr));
9329         return next->do_body_ops->dbo_read(env, next, buf, pos);
9330 }
9331
9332 /**
9333  * Implementation of dt_body_operations::dbo_declare_write.
9334  *
9335  * \see dt_body_operations::dbo_declare_write() in the API description
9336  * for details.
9337  */
9338 static ssize_t lod_declare_write(const struct lu_env *env,
9339                                  struct dt_object *dt,
9340                                  const struct lu_buf *buf, loff_t pos,
9341                                  struct thandle *th)
9342 {
9343         return lod_sub_declare_write(env, dt_object_child(dt), buf, pos, th);
9344 }
9345
9346 /**
9347  * Implementation of dt_body_operations::dbo_write.
9348  *
9349  * \see dt_body_operations::dbo_write() in the API description for details.
9350  */
9351 static ssize_t lod_write(const struct lu_env *env, struct dt_object *dt,
9352                          const struct lu_buf *buf, loff_t *pos,
9353                          struct thandle *th)
9354 {
9355         LASSERT(S_ISREG(dt->do_lu.lo_header->loh_attr) ||
9356                 S_ISLNK(dt->do_lu.lo_header->loh_attr));
9357         return lod_sub_write(env, dt_object_child(dt), buf, pos, th);
9358 }
9359
9360 static int lod_declare_punch(const struct lu_env *env, struct dt_object *dt,
9361                              __u64 start, __u64 end, struct thandle *th)
9362 {
9363         if (dt_object_remote(dt))
9364                 return -ENOTSUPP;
9365
9366         return lod_sub_declare_punch(env, dt_object_child(dt), start, end, th);
9367 }
9368
9369 static int lod_punch(const struct lu_env *env, struct dt_object *dt,
9370                      __u64 start, __u64 end, struct thandle *th)
9371 {
9372         if (dt_object_remote(dt))
9373                 return -ENOTSUPP;
9374
9375         LASSERT(S_ISREG(dt->do_lu.lo_header->loh_attr));
9376         return lod_sub_punch(env, dt_object_child(dt), start, end, th);
9377 }
9378
9379 /*
9380  * different type of files use the same body_ops because object may be created
9381  * in OUT, where there is no chance to set correct body_ops for each type, so
9382  * body_ops themselves will check file type inside, see lod_read/write/punch for
9383  * details.
9384  */
9385 static const struct dt_body_operations lod_body_ops = {
9386         .dbo_read               = lod_read,
9387         .dbo_declare_write      = lod_declare_write,
9388         .dbo_write              = lod_write,
9389         .dbo_declare_punch      = lod_declare_punch,
9390         .dbo_punch              = lod_punch,
9391 };
9392
9393 /**
9394  * Implementation of lu_object_operations::loo_object_init.
9395  *
9396  * The function determines the type and the index of the target device using
9397  * sequence of the object's FID. Then passes control down to the
9398  * corresponding device:
9399  *  OSD for the local objects, OSP for remote
9400  *
9401  * \see lu_object_operations::loo_object_init() in the API description
9402  * for details.
9403  */
9404 static int lod_object_init(const struct lu_env *env, struct lu_object *lo,
9405                            const struct lu_object_conf *conf)
9406 {
9407         struct lod_device       *lod    = lu2lod_dev(lo->lo_dev);
9408         struct lu_device        *cdev   = NULL;
9409         struct lu_object        *cobj;
9410         struct lod_tgt_descs    *ltd    = NULL;
9411         struct lod_tgt_desc     *tgt;
9412         u32                      idx    = 0;
9413         int                      type   = LU_SEQ_RANGE_ANY;
9414         int                      rc;
9415         ENTRY;
9416
9417         rc = lod_fld_lookup(env, lod, lu_object_fid(lo), &idx, &type);
9418         if (rc != 0)
9419                 RETURN(rc);
9420
9421         if (type == LU_SEQ_RANGE_MDT &&
9422             idx == lu_site2seq(lo->lo_dev->ld_site)->ss_node_id) {
9423                 cdev = &lod->lod_child->dd_lu_dev;
9424         } else if (type == LU_SEQ_RANGE_MDT) {
9425                 ltd = &lod->lod_mdt_descs;
9426                 lod_getref(ltd);
9427         } else if (type == LU_SEQ_RANGE_OST) {
9428                 ltd = &lod->lod_ost_descs;
9429                 lod_getref(ltd);
9430         } else {
9431                 LBUG();
9432         }
9433
9434         if (ltd != NULL) {
9435                 if (ltd->ltd_tgts_size > idx &&
9436                     test_bit(idx, ltd->ltd_tgt_bitmap)) {
9437                         tgt = LTD_TGT(ltd, idx);
9438
9439                         LASSERT(tgt != NULL);
9440                         LASSERT(tgt->ltd_tgt != NULL);
9441
9442                         cdev = &(tgt->ltd_tgt->dd_lu_dev);
9443                 }
9444                 lod_putref(lod, ltd);
9445         }
9446
9447         if (unlikely(cdev == NULL))
9448                 RETURN(-ENOENT);
9449
9450         cobj = cdev->ld_ops->ldo_object_alloc(env, lo->lo_header, cdev);
9451         if (unlikely(cobj == NULL))
9452                 RETURN(-ENOMEM);
9453
9454         lu2lod_obj(lo)->ldo_obj.do_body_ops = &lod_body_ops;
9455
9456         lu_object_add(lo, cobj);
9457
9458         RETURN(0);
9459 }
9460
9461 /**
9462  *
9463  * Release resources associated with striping.
9464  *
9465  * If the object is striped (regular or directory), then release
9466  * the stripe objects references and free the ldo_stripe array.
9467  *
9468  * \param[in] env       execution environment
9469  * \param[in] lo        object
9470  */
9471 void lod_striping_free_nolock(const struct lu_env *env, struct lod_object *lo)
9472 {
9473         struct lod_layout_component *lod_comp;
9474         __u32 obj_attr = lo->ldo_obj.do_lu.lo_header->loh_attr;
9475         int i, j;
9476
9477         if (unlikely(lo->ldo_is_foreign)) {
9478                 if (S_ISREG(obj_attr)) {
9479                         lod_free_foreign_lov(lo);
9480                         lo->ldo_comp_cached = 0;
9481                 } else if (S_ISDIR(obj_attr)) {
9482                         lod_free_foreign_lmv(lo);
9483                         lo->ldo_dir_stripe_loaded = 0;
9484                 }
9485         } else if (lo->ldo_stripe != NULL) {
9486                 LASSERT(lo->ldo_comp_entries == NULL);
9487                 LASSERT(lo->ldo_dir_stripes_allocated > 0);
9488
9489                 for (i = 0; i < lo->ldo_dir_stripe_count; i++) {
9490                         if (lo->ldo_stripe[i])
9491                                 dt_object_put(env, lo->ldo_stripe[i]);
9492                 }
9493
9494                 j = sizeof(struct dt_object *) * lo->ldo_dir_stripes_allocated;
9495                 OBD_FREE(lo->ldo_stripe, j);
9496                 lo->ldo_stripe = NULL;
9497                 lo->ldo_dir_stripes_allocated = 0;
9498                 lo->ldo_dir_stripe_loaded = 0;
9499                 lo->ldo_dir_stripe_count = 0;
9500                 lo->ldo_obj.do_index_ops = NULL;
9501         } else if (lo->ldo_comp_entries != NULL) {
9502                 for (i = 0; i < lo->ldo_comp_cnt; i++) {
9503                         /* free lod_layout_component::llc_stripe array */
9504                         lod_comp = &lo->ldo_comp_entries[i];
9505
9506                         /* HSM layout component */
9507                         if (lod_comp->llc_magic == LOV_MAGIC_FOREIGN)
9508                                 continue;
9509                         if (lod_comp->llc_stripe == NULL)
9510                                 continue;
9511                         LASSERT(lod_comp->llc_stripes_allocated != 0);
9512                         for (j = 0; j < lod_comp->llc_stripes_allocated; j++) {
9513                                 if (lod_comp->llc_stripe[j] != NULL)
9514                                         lu_object_put(env,
9515                                                &lod_comp->llc_stripe[j]->do_lu);
9516                         }
9517                         OBD_FREE_PTR_ARRAY(lod_comp->llc_stripe,
9518                                            lod_comp->llc_stripes_allocated);
9519                         lod_comp->llc_stripe = NULL;
9520                         OBD_FREE_PTR_ARRAY(lod_comp->llc_ost_indices,
9521                                            lod_comp->llc_stripes_allocated);
9522                         lod_comp->llc_ost_indices = NULL;
9523                         lod_comp->llc_stripes_allocated = 0;
9524                 }
9525                 lod_free_comp_entries(lo);
9526                 lo->ldo_comp_cached = 0;
9527         }
9528 }
9529
9530 void lod_striping_free(const struct lu_env *env, struct lod_object *lo)
9531 {
9532         mutex_lock(&lo->ldo_layout_mutex);
9533         lod_striping_free_nolock(env, lo);
9534         mutex_unlock(&lo->ldo_layout_mutex);
9535 }
9536
9537 /**
9538  * Implementation of lu_object_operations::loo_object_free.
9539  *
9540  * \see lu_object_operations::loo_object_free() in the API description
9541  * for details.
9542  */
9543 static void lod_object_free(const struct lu_env *env, struct lu_object *o)
9544 {
9545         struct lod_object *lo = lu2lod_obj(o);
9546
9547         /* release all underlying object pinned */
9548         lod_striping_free(env, lo);
9549         lu_object_fini(o);
9550         /* lo doesn't contain a lu_object_header, so we don't need call_rcu */
9551         OBD_SLAB_FREE_PTR(lo, lod_object_kmem);
9552 }
9553
9554 /**
9555  * Implementation of lu_object_operations::loo_object_release.
9556  *
9557  * \see lu_object_operations::loo_object_release() in the API description
9558  * for details.
9559  */
9560 static void lod_object_release(const struct lu_env *env, struct lu_object *o)
9561 {
9562         /* XXX: shouldn't we release everything here in case if object
9563          * creation failed before? */
9564 }
9565
9566 /**
9567  * Implementation of lu_object_operations::loo_object_print.
9568  *
9569  * \see lu_object_operations::loo_object_print() in the API description
9570  * for details.
9571  */
9572 static int lod_object_print(const struct lu_env *env, void *cookie,
9573                             lu_printer_t p, const struct lu_object *l)
9574 {
9575         struct lod_object *o = lu2lod_obj((struct lu_object *) l);
9576
9577         return (*p)(env, cookie, LUSTRE_LOD_NAME"-object@%p", o);
9578 }
9579
9580 const struct lu_object_operations lod_lu_obj_ops = {
9581         .loo_object_init        = lod_object_init,
9582         .loo_object_free        = lod_object_free,
9583         .loo_object_release     = lod_object_release,
9584         .loo_object_print       = lod_object_print,
9585 };