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