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