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