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