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