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