Whamcloud - gitweb
LU-11103 lod: add lock for lod_object layout
[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, int ign)
102 {
103         return lod_sub_insert(env, dt_object_child(dt), rec, key, th, ign);
104 }
105
106 /**
107  * Implementation of dt_index_operations::dio_declare_delete.
108  *
109  * Used with regular (non-striped) objects.
110  *
111  * \see dt_index_operations::dio_declare_delete() in the API description
112  * for details.
113  */
114 static int lod_declare_delete(const struct lu_env *env, struct dt_object *dt,
115                               const struct dt_key *key, struct thandle *th)
116 {
117         return lod_sub_declare_delete(env, dt_object_child(dt), key, th);
118 }
119
120 /**
121  * Implementation of dt_index_operations::dio_delete.
122  *
123  * Used with regular (non-striped) objects.
124  *
125  * \see dt_index_operations::dio_delete() in the API description for details.
126  */
127 static int lod_delete(const struct lu_env *env, struct dt_object *dt,
128                       const struct dt_key *key, struct thandle *th)
129 {
130         return lod_sub_delete(env, dt_object_child(dt), key, th);
131 }
132
133 /**
134  * Implementation of dt_it_ops::init.
135  *
136  * Used with regular (non-striped) objects.
137  *
138  * \see dt_it_ops::init() in the API description for details.
139  */
140 static struct dt_it *lod_it_init(const struct lu_env *env,
141                                  struct dt_object *dt, __u32 attr)
142 {
143         struct dt_object        *next = dt_object_child(dt);
144         struct lod_it           *it = &lod_env_info(env)->lti_it;
145         struct dt_it            *it_next;
146
147         it_next = next->do_index_ops->dio_it.init(env, next, attr);
148         if (IS_ERR(it_next))
149                 return it_next;
150
151         /* currently we do not use more than one iterator per thread
152          * so we store it in thread info. if at some point we need
153          * more active iterators in a single thread, we can allocate
154          * additional ones */
155         LASSERT(it->lit_obj == NULL);
156
157         it->lit_it = it_next;
158         it->lit_obj = next;
159
160         return (struct dt_it *)it;
161 }
162
163 #define LOD_CHECK_IT(env, it)                                   \
164 do {                                                            \
165         LASSERT((it)->lit_obj != NULL);                         \
166         LASSERT((it)->lit_it != NULL);                          \
167 } while (0)
168
169 /**
170  * Implementation of dt_index_operations::dio_it.fini.
171  *
172  * Used with regular (non-striped) objects.
173  *
174  * \see dt_index_operations::dio_it.fini() in the API description for details.
175  */
176 static void lod_it_fini(const struct lu_env *env, struct dt_it *di)
177 {
178         struct lod_it *it = (struct lod_it *)di;
179
180         LOD_CHECK_IT(env, it);
181         it->lit_obj->do_index_ops->dio_it.fini(env, it->lit_it);
182
183         /* the iterator not in use any more */
184         it->lit_obj = NULL;
185         it->lit_it = NULL;
186 }
187
188 /**
189  * Implementation of dt_it_ops::get.
190  *
191  * Used with regular (non-striped) objects.
192  *
193  * \see dt_it_ops::get() in the API description for details.
194  */
195 static int lod_it_get(const struct lu_env *env, struct dt_it *di,
196                       const struct dt_key *key)
197 {
198         const struct lod_it *it = (const struct lod_it *)di;
199
200         LOD_CHECK_IT(env, it);
201         return it->lit_obj->do_index_ops->dio_it.get(env, it->lit_it, key);
202 }
203
204 /**
205  * Implementation of dt_it_ops::put.
206  *
207  * Used with regular (non-striped) objects.
208  *
209  * \see dt_it_ops::put() in the API description for details.
210  */
211 static void lod_it_put(const struct lu_env *env, struct dt_it *di)
212 {
213         struct lod_it *it = (struct lod_it *)di;
214
215         LOD_CHECK_IT(env, it);
216         return it->lit_obj->do_index_ops->dio_it.put(env, it->lit_it);
217 }
218
219 /**
220  * Implementation of dt_it_ops::next.
221  *
222  * Used with regular (non-striped) objects
223  *
224  * \see dt_it_ops::next() in the API description for details.
225  */
226 static int lod_it_next(const struct lu_env *env, struct dt_it *di)
227 {
228         struct lod_it *it = (struct lod_it *)di;
229
230         LOD_CHECK_IT(env, it);
231         return it->lit_obj->do_index_ops->dio_it.next(env, it->lit_it);
232 }
233
234 /**
235  * Implementation of dt_it_ops::key.
236  *
237  * Used with regular (non-striped) objects.
238  *
239  * \see dt_it_ops::key() in the API description for details.
240  */
241 static struct dt_key *lod_it_key(const struct lu_env *env,
242                                  const struct dt_it *di)
243 {
244         const struct lod_it *it = (const struct lod_it *)di;
245
246         LOD_CHECK_IT(env, it);
247         return it->lit_obj->do_index_ops->dio_it.key(env, it->lit_it);
248 }
249
250 /**
251  * Implementation of dt_it_ops::key_size.
252  *
253  * Used with regular (non-striped) objects.
254  *
255  * \see dt_it_ops::key_size() in the API description for details.
256  */
257 static int lod_it_key_size(const struct lu_env *env, const struct dt_it *di)
258 {
259         struct lod_it *it = (struct lod_it *)di;
260
261         LOD_CHECK_IT(env, it);
262         return it->lit_obj->do_index_ops->dio_it.key_size(env, it->lit_it);
263 }
264
265 /**
266  * Implementation of dt_it_ops::rec.
267  *
268  * Used with regular (non-striped) objects.
269  *
270  * \see dt_it_ops::rec() in the API description for details.
271  */
272 static int lod_it_rec(const struct lu_env *env, const struct dt_it *di,
273                       struct dt_rec *rec, __u32 attr)
274 {
275         const struct lod_it *it = (const struct lod_it *)di;
276
277         LOD_CHECK_IT(env, it);
278         return it->lit_obj->do_index_ops->dio_it.rec(env, it->lit_it, rec,
279                                                      attr);
280 }
281
282 /**
283  * Implementation of dt_it_ops::rec_size.
284  *
285  * Used with regular (non-striped) objects.
286  *
287  * \see dt_it_ops::rec_size() in the API description for details.
288  */
289 static int lod_it_rec_size(const struct lu_env *env, const struct dt_it *di,
290                            __u32 attr)
291 {
292         const struct lod_it *it = (const struct lod_it *)di;
293
294         LOD_CHECK_IT(env, it);
295         return it->lit_obj->do_index_ops->dio_it.rec_size(env, it->lit_it,
296                                                           attr);
297 }
298
299 /**
300  * Implementation of dt_it_ops::store.
301  *
302  * Used with regular (non-striped) objects.
303  *
304  * \see dt_it_ops::store() in the API description for details.
305  */
306 static __u64 lod_it_store(const struct lu_env *env, const struct dt_it *di)
307 {
308         const struct lod_it *it = (const struct lod_it *)di;
309
310         LOD_CHECK_IT(env, it);
311         return it->lit_obj->do_index_ops->dio_it.store(env, it->lit_it);
312 }
313
314 /**
315  * Implementation of dt_it_ops::load.
316  *
317  * Used with regular (non-striped) objects.
318  *
319  * \see dt_it_ops::load() in the API description for details.
320  */
321 static int lod_it_load(const struct lu_env *env, const struct dt_it *di,
322                        __u64 hash)
323 {
324         const struct lod_it *it = (const struct lod_it *)di;
325
326         LOD_CHECK_IT(env, it);
327         return it->lit_obj->do_index_ops->dio_it.load(env, it->lit_it, hash);
328 }
329
330 /**
331  * Implementation of dt_it_ops::key_rec.
332  *
333  * Used with regular (non-striped) objects.
334  *
335  * \see dt_it_ops::rec() in the API description for details.
336  */
337 static int lod_it_key_rec(const struct lu_env *env, const struct dt_it *di,
338                           void *key_rec)
339 {
340         const struct lod_it *it = (const struct lod_it *)di;
341
342         LOD_CHECK_IT(env, it);
343         return it->lit_obj->do_index_ops->dio_it.key_rec(env, it->lit_it,
344                                                          key_rec);
345 }
346
347 static struct dt_index_operations lod_index_ops = {
348         .dio_lookup             = lod_lookup,
349         .dio_declare_insert     = lod_declare_insert,
350         .dio_insert             = lod_insert,
351         .dio_declare_delete     = lod_declare_delete,
352         .dio_delete             = lod_delete,
353         .dio_it = {
354                 .init           = lod_it_init,
355                 .fini           = lod_it_fini,
356                 .get            = lod_it_get,
357                 .put            = lod_it_put,
358                 .next           = lod_it_next,
359                 .key            = lod_it_key,
360                 .key_size       = lod_it_key_size,
361                 .rec            = lod_it_rec,
362                 .rec_size       = lod_it_rec_size,
363                 .store          = lod_it_store,
364                 .load           = lod_it_load,
365                 .key_rec        = lod_it_key_rec,
366         }
367 };
368
369 /**
370  * Implementation of dt_it_ops::init.
371  *
372  * Used with striped objects. Internally just initializes the iterator
373  * on the first stripe.
374  *
375  * \see dt_it_ops::init() in the API description for details.
376  */
377 static struct dt_it *lod_striped_it_init(const struct lu_env *env,
378                                          struct dt_object *dt, __u32 attr)
379 {
380         struct lod_object       *lo = lod_dt_obj(dt);
381         struct dt_object        *next;
382         struct lod_it           *it = &lod_env_info(env)->lti_it;
383         struct dt_it            *it_next;
384         ENTRY;
385
386         LASSERT(lo->ldo_dir_stripe_count > 0);
387         next = lo->ldo_stripe[0];
388         LASSERT(next != NULL);
389         LASSERT(next->do_index_ops != NULL);
390
391         it_next = next->do_index_ops->dio_it.init(env, next, attr);
392         if (IS_ERR(it_next))
393                 return it_next;
394
395         /* currently we do not use more than one iterator per thread
396          * so we store it in thread info. if at some point we need
397          * more active iterators in a single thread, we can allocate
398          * additional ones */
399         LASSERT(it->lit_obj == NULL);
400
401         it->lit_stripe_index = 0;
402         it->lit_attr = attr;
403         it->lit_it = it_next;
404         it->lit_obj = dt;
405
406         return (struct dt_it *)it;
407 }
408
409 #define LOD_CHECK_STRIPED_IT(env, it, lo)                               \
410 do {                                                                    \
411         LASSERT((it)->lit_obj != NULL);                                 \
412         LASSERT((it)->lit_it != NULL);                                  \
413         LASSERT((lo)->ldo_dir_stripe_count > 0);                        \
414         LASSERT((it)->lit_stripe_index < (lo)->ldo_dir_stripe_count);   \
415 } while (0)
416
417 /**
418  * Implementation of dt_it_ops::fini.
419  *
420  * Used with striped objects.
421  *
422  * \see dt_it_ops::fini() in the API description for details.
423  */
424 static void lod_striped_it_fini(const struct lu_env *env, struct dt_it *di)
425 {
426         struct lod_it           *it = (struct lod_it *)di;
427         struct lod_object       *lo = lod_dt_obj(it->lit_obj);
428         struct dt_object        *next;
429
430         /* If lit_it == NULL, then it means the sub_it has been finished,
431          * which only happens in failure cases, see lod_striped_it_next() */
432         if (it->lit_it != NULL) {
433                 LOD_CHECK_STRIPED_IT(env, it, lo);
434
435                 next = lo->ldo_stripe[it->lit_stripe_index];
436                 LASSERT(next != NULL);
437                 LASSERT(next->do_index_ops != NULL);
438
439                 next->do_index_ops->dio_it.fini(env, it->lit_it);
440         }
441
442         /* the iterator not in use any more */
443         it->lit_obj = NULL;
444         it->lit_it = NULL;
445         it->lit_stripe_index = 0;
446 }
447
448 /**
449  * Implementation of dt_it_ops::get.
450  *
451  * Right now it's not used widely, only to reset the iterator to the
452  * initial position. It should be possible to implement a full version
453  * which chooses a correct stripe to be able to position with any key.
454  *
455  * \see dt_it_ops::get() in the API description for details.
456  */
457 static int lod_striped_it_get(const struct lu_env *env, struct dt_it *di,
458                               const struct dt_key *key)
459 {
460         const struct lod_it     *it = (const struct lod_it *)di;
461         struct lod_object       *lo = lod_dt_obj(it->lit_obj);
462         struct dt_object        *next;
463         ENTRY;
464
465         LOD_CHECK_STRIPED_IT(env, it, lo);
466
467         next = lo->ldo_stripe[it->lit_stripe_index];
468         LASSERT(next != NULL);
469         LASSERT(next->do_index_ops != NULL);
470
471         return next->do_index_ops->dio_it.get(env, it->lit_it, key);
472 }
473
474 /**
475  * Implementation of dt_it_ops::put.
476  *
477  * Used with striped objects.
478  *
479  * \see dt_it_ops::put() in the API description for details.
480  */
481 static void lod_striped_it_put(const struct lu_env *env, struct dt_it *di)
482 {
483         struct lod_it           *it = (struct lod_it *)di;
484         struct lod_object       *lo = lod_dt_obj(it->lit_obj);
485         struct dt_object        *next;
486
487         LOD_CHECK_STRIPED_IT(env, it, lo);
488
489         next = lo->ldo_stripe[it->lit_stripe_index];
490         LASSERT(next != NULL);
491         LASSERT(next->do_index_ops != NULL);
492
493         return next->do_index_ops->dio_it.put(env, it->lit_it);
494 }
495
496 /**
497  * Implementation of dt_it_ops::next.
498  *
499  * Used with striped objects. When the end of the current stripe is
500  * reached, the method takes the next stripe's iterator.
501  *
502  * \see dt_it_ops::next() in the API description for details.
503  */
504 static int lod_striped_it_next(const struct lu_env *env, struct dt_it *di)
505 {
506         struct lod_it           *it = (struct lod_it *)di;
507         struct lod_object       *lo = lod_dt_obj(it->lit_obj);
508         struct dt_object        *next;
509         struct dt_it            *it_next;
510         int                     rc;
511         ENTRY;
512
513         LOD_CHECK_STRIPED_IT(env, it, lo);
514
515         next = lo->ldo_stripe[it->lit_stripe_index];
516         LASSERT(next != NULL);
517         LASSERT(next->do_index_ops != NULL);
518 again:
519         rc = next->do_index_ops->dio_it.next(env, it->lit_it);
520         if (rc < 0)
521                 RETURN(rc);
522
523         if (rc == 0 && it->lit_stripe_index == 0)
524                 RETURN(rc);
525
526         if (rc == 0 && it->lit_stripe_index > 0) {
527                 struct lu_dirent *ent;
528
529                 ent = (struct lu_dirent *)lod_env_info(env)->lti_key;
530
531                 rc = next->do_index_ops->dio_it.rec(env, it->lit_it,
532                                                     (struct dt_rec *)ent,
533                                                     it->lit_attr);
534                 if (rc != 0)
535                         RETURN(rc);
536
537                 /* skip . and .. for slave stripe */
538                 if ((strncmp(ent->lde_name, ".",
539                              le16_to_cpu(ent->lde_namelen)) == 0 &&
540                      le16_to_cpu(ent->lde_namelen) == 1) ||
541                     (strncmp(ent->lde_name, "..",
542                              le16_to_cpu(ent->lde_namelen)) == 0 &&
543                      le16_to_cpu(ent->lde_namelen) == 2))
544                         goto again;
545
546                 RETURN(rc);
547         }
548
549         /* go to next stripe */
550         if (it->lit_stripe_index + 1 >= lo->ldo_dir_stripe_count)
551                 RETURN(1);
552
553         it->lit_stripe_index++;
554
555         next->do_index_ops->dio_it.put(env, it->lit_it);
556         next->do_index_ops->dio_it.fini(env, it->lit_it);
557         it->lit_it = NULL;
558
559         next = lo->ldo_stripe[it->lit_stripe_index];
560         LASSERT(next != NULL);
561         rc = next->do_ops->do_index_try(env, next, &dt_directory_features);
562         if (rc != 0)
563                 RETURN(rc);
564
565         LASSERT(next->do_index_ops != NULL);
566
567         it_next = next->do_index_ops->dio_it.init(env, next, it->lit_attr);
568         if (!IS_ERR(it_next)) {
569                 it->lit_it = it_next;
570                 goto again;
571         } else {
572                 rc = PTR_ERR(it_next);
573         }
574
575         RETURN(rc);
576 }
577
578 /**
579  * Implementation of dt_it_ops::key.
580  *
581  * Used with striped objects.
582  *
583  * \see dt_it_ops::key() in the API description for details.
584  */
585 static struct dt_key *lod_striped_it_key(const struct lu_env *env,
586                                          const struct dt_it *di)
587 {
588         const struct lod_it     *it = (const struct lod_it *)di;
589         struct lod_object       *lo = lod_dt_obj(it->lit_obj);
590         struct dt_object        *next;
591
592         LOD_CHECK_STRIPED_IT(env, it, lo);
593
594         next = lo->ldo_stripe[it->lit_stripe_index];
595         LASSERT(next != NULL);
596         LASSERT(next->do_index_ops != NULL);
597
598         return next->do_index_ops->dio_it.key(env, it->lit_it);
599 }
600
601 /**
602  * Implementation of dt_it_ops::key_size.
603  *
604  * Used with striped objects.
605  *
606  * \see dt_it_ops::size() in the API description for details.
607  */
608 static int lod_striped_it_key_size(const struct lu_env *env,
609                                    const struct dt_it *di)
610 {
611         struct lod_it           *it = (struct lod_it *)di;
612         struct lod_object       *lo = lod_dt_obj(it->lit_obj);
613         struct dt_object        *next;
614
615         LOD_CHECK_STRIPED_IT(env, it, lo);
616
617         next = lo->ldo_stripe[it->lit_stripe_index];
618         LASSERT(next != NULL);
619         LASSERT(next->do_index_ops != NULL);
620
621         return next->do_index_ops->dio_it.key_size(env, it->lit_it);
622 }
623
624 /**
625  * Implementation of dt_it_ops::rec.
626  *
627  * Used with striped objects.
628  *
629  * \see dt_it_ops::rec() in the API description for details.
630  */
631 static int lod_striped_it_rec(const struct lu_env *env, const struct dt_it *di,
632                               struct dt_rec *rec, __u32 attr)
633 {
634         const struct lod_it     *it = (const struct lod_it *)di;
635         struct lod_object       *lo = lod_dt_obj(it->lit_obj);
636         struct dt_object        *next;
637
638         LOD_CHECK_STRIPED_IT(env, it, lo);
639
640         next = lo->ldo_stripe[it->lit_stripe_index];
641         LASSERT(next != NULL);
642         LASSERT(next->do_index_ops != NULL);
643
644         return next->do_index_ops->dio_it.rec(env, it->lit_it, rec, attr);
645 }
646
647 /**
648  * Implementation of dt_it_ops::rec_size.
649  *
650  * Used with striped objects.
651  *
652  * \see dt_it_ops::rec_size() in the API description for details.
653  */
654 static int lod_striped_it_rec_size(const struct lu_env *env,
655                                    const struct dt_it *di, __u32 attr)
656 {
657         struct lod_it           *it = (struct lod_it *)di;
658         struct lod_object       *lo = lod_dt_obj(it->lit_obj);
659         struct dt_object        *next;
660
661         LOD_CHECK_STRIPED_IT(env, it, lo);
662
663         next = lo->ldo_stripe[it->lit_stripe_index];
664         LASSERT(next != NULL);
665         LASSERT(next->do_index_ops != NULL);
666
667         return next->do_index_ops->dio_it.rec_size(env, it->lit_it, attr);
668 }
669
670 /**
671  * Implementation of dt_it_ops::store.
672  *
673  * Used with striped objects.
674  *
675  * \see dt_it_ops::store() in the API description for details.
676  */
677 static __u64 lod_striped_it_store(const struct lu_env *env,
678                                   const struct dt_it *di)
679 {
680         const struct lod_it     *it = (const struct lod_it *)di;
681         struct lod_object       *lo = lod_dt_obj(it->lit_obj);
682         struct dt_object        *next;
683
684         LOD_CHECK_STRIPED_IT(env, it, lo);
685
686         next = lo->ldo_stripe[it->lit_stripe_index];
687         LASSERT(next != NULL);
688         LASSERT(next->do_index_ops != NULL);
689
690         return next->do_index_ops->dio_it.store(env, it->lit_it);
691 }
692
693 /**
694  * Implementation of dt_it_ops::load.
695  *
696  * Used with striped objects.
697  *
698  * \see dt_it_ops::load() in the API description for details.
699  */
700 static int lod_striped_it_load(const struct lu_env *env,
701                                const struct dt_it *di, __u64 hash)
702 {
703         const struct lod_it     *it = (const struct lod_it *)di;
704         struct lod_object       *lo = lod_dt_obj(it->lit_obj);
705         struct dt_object        *next;
706
707         LOD_CHECK_STRIPED_IT(env, it, lo);
708
709         next = lo->ldo_stripe[it->lit_stripe_index];
710         LASSERT(next != NULL);
711         LASSERT(next->do_index_ops != NULL);
712
713         return next->do_index_ops->dio_it.load(env, it->lit_it, hash);
714 }
715
716 static struct dt_index_operations lod_striped_index_ops = {
717         .dio_lookup             = lod_lookup,
718         .dio_declare_insert     = lod_declare_insert,
719         .dio_insert             = lod_insert,
720         .dio_declare_delete     = lod_declare_delete,
721         .dio_delete             = lod_delete,
722         .dio_it = {
723                 .init           = lod_striped_it_init,
724                 .fini           = lod_striped_it_fini,
725                 .get            = lod_striped_it_get,
726                 .put            = lod_striped_it_put,
727                 .next           = lod_striped_it_next,
728                 .key            = lod_striped_it_key,
729                 .key_size       = lod_striped_it_key_size,
730                 .rec            = lod_striped_it_rec,
731                 .rec_size       = lod_striped_it_rec_size,
732                 .store          = lod_striped_it_store,
733                 .load           = lod_striped_it_load,
734         }
735 };
736
737 /**
738  * Append the FID for each shard of the striped directory after the
739  * given LMV EA header.
740  *
741  * To simplify striped directory and the consistency verification,
742  * we only store the LMV EA header on disk, for both master object
743  * and slave objects. When someone wants to know the whole LMV EA,
744  * such as client readdir(), we can build the entrie LMV EA on the
745  * MDT side (in RAM) via iterating the sub-directory entries that
746  * are contained in the master object of the stripe directory.
747  *
748  * For the master object of the striped directroy, the valid name
749  * for each shard is composed of the ${shard_FID}:${shard_idx}.
750  *
751  * There may be holes in the LMV EA if some shards' name entries
752  * are corrupted or lost.
753  *
754  * \param[in] env       pointer to the thread context
755  * \param[in] lo        pointer to the master object of the striped directory
756  * \param[in] buf       pointer to the lu_buf which will hold the LMV EA
757  * \param[in] resize    whether re-allocate the buffer if it is not big enough
758  *
759  * \retval              positive size of the LMV EA
760  * \retval              0 for nothing to be loaded
761  * \retval              negative error number on failure
762  */
763 int lod_load_lmv_shards(const struct lu_env *env, struct lod_object *lo,
764                         struct lu_buf *buf, bool resize)
765 {
766         struct lu_dirent        *ent    =
767                         (struct lu_dirent *)lod_env_info(env)->lti_key;
768         struct lod_device       *lod    = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
769         struct dt_object        *obj    = dt_object_child(&lo->ldo_obj);
770         struct lmv_mds_md_v1    *lmv1   = buf->lb_buf;
771         struct dt_it            *it;
772         const struct dt_it_ops  *iops;
773         __u32                    stripes;
774         __u32                    magic  = le32_to_cpu(lmv1->lmv_magic);
775         size_t                   lmv1_size;
776         int                      rc;
777         ENTRY;
778
779         /* If it is not a striped directory, then load nothing. */
780         if (magic != LMV_MAGIC_V1)
781                 RETURN(0);
782
783         /* If it is in migration (or failure), then load nothing. */
784         if (le32_to_cpu(lmv1->lmv_hash_type) & LMV_HASH_FLAG_MIGRATION)
785                 RETURN(0);
786
787         stripes = le32_to_cpu(lmv1->lmv_stripe_count);
788         if (stripes < 1)
789                 RETURN(0);
790
791         rc = lmv_mds_md_size(stripes, magic);
792         if (rc < 0)
793                 RETURN(rc);
794         lmv1_size = rc;
795         if (buf->lb_len < lmv1_size) {
796                 struct lu_buf tbuf;
797
798                 if (!resize)
799                         RETURN(-ERANGE);
800
801                 tbuf = *buf;
802                 buf->lb_buf = NULL;
803                 buf->lb_len = 0;
804                 lu_buf_alloc(buf, lmv1_size);
805                 lmv1 = buf->lb_buf;
806                 if (lmv1 == NULL)
807                         RETURN(-ENOMEM);
808
809                 memcpy(buf->lb_buf, tbuf.lb_buf, tbuf.lb_len);
810         }
811
812         if (unlikely(!dt_try_as_dir(env, obj)))
813                 RETURN(-ENOTDIR);
814
815         memset(&lmv1->lmv_stripe_fids[0], 0, stripes * sizeof(struct lu_fid));
816         iops = &obj->do_index_ops->dio_it;
817         it = iops->init(env, obj, LUDA_64BITHASH);
818         if (IS_ERR(it))
819                 RETURN(PTR_ERR(it));
820
821         rc = iops->load(env, it, 0);
822         if (rc == 0)
823                 rc = iops->next(env, it);
824         else if (rc > 0)
825                 rc = 0;
826
827         while (rc == 0) {
828                 char             name[FID_LEN + 2] = "";
829                 struct lu_fid    fid;
830                 __u32            index;
831                 int              len;
832
833                 rc = iops->rec(env, it, (struct dt_rec *)ent, LUDA_64BITHASH);
834                 if (rc != 0)
835                         break;
836
837                 rc = -EIO;
838
839                 fid_le_to_cpu(&fid, &ent->lde_fid);
840                 ent->lde_namelen = le16_to_cpu(ent->lde_namelen);
841                 if (ent->lde_name[0] == '.') {
842                         if (ent->lde_namelen == 1)
843                                 goto next;
844
845                         if (ent->lde_namelen == 2 && ent->lde_name[1] == '.')
846                                 goto next;
847                 }
848
849                 len = snprintf(name, sizeof(name),
850                                DFID":", PFID(&ent->lde_fid));
851                 /* The ent->lde_name is composed of ${FID}:${index} */
852                 if (ent->lde_namelen < len + 1 ||
853                     memcmp(ent->lde_name, name, len) != 0) {
854                         CDEBUG(lod->lod_lmv_failout ? D_ERROR : D_INFO,
855                                "%s: invalid shard name %.*s with the FID "DFID
856                                " for the striped directory "DFID", %s\n",
857                                lod2obd(lod)->obd_name, ent->lde_namelen,
858                                ent->lde_name, PFID(&fid),
859                                PFID(lu_object_fid(&obj->do_lu)),
860                                lod->lod_lmv_failout ? "failout" : "skip");
861
862                         if (lod->lod_lmv_failout)
863                                 break;
864
865                         goto next;
866                 }
867
868                 index = 0;
869                 do {
870                         if (ent->lde_name[len] < '0' ||
871                             ent->lde_name[len] > '9') {
872                                 CDEBUG(lod->lod_lmv_failout ? D_ERROR : D_INFO,
873                                        "%s: invalid shard name %.*s with the "
874                                        "FID "DFID" for the striped directory "
875                                        DFID", %s\n",
876                                        lod2obd(lod)->obd_name, ent->lde_namelen,
877                                        ent->lde_name, PFID(&fid),
878                                        PFID(lu_object_fid(&obj->do_lu)),
879                                        lod->lod_lmv_failout ?
880                                        "failout" : "skip");
881
882                                 if (lod->lod_lmv_failout)
883                                         break;
884
885                                 goto next;
886                         }
887
888                         index = index * 10 + ent->lde_name[len++] - '0';
889                 } while (len < ent->lde_namelen);
890
891                 if (len == ent->lde_namelen) {
892                         /* Out of LMV EA range. */
893                         if (index >= stripes) {
894                                 CERROR("%s: the shard %.*s for the striped "
895                                        "directory "DFID" is out of the known "
896                                        "LMV EA range [0 - %u], failout\n",
897                                        lod2obd(lod)->obd_name, ent->lde_namelen,
898                                        ent->lde_name,
899                                        PFID(lu_object_fid(&obj->do_lu)),
900                                        stripes - 1);
901
902                                 break;
903                         }
904
905                         /* The slot has been occupied. */
906                         if (!fid_is_zero(&lmv1->lmv_stripe_fids[index])) {
907                                 struct lu_fid fid0;
908
909                                 fid_le_to_cpu(&fid0,
910                                         &lmv1->lmv_stripe_fids[index]);
911                                 CERROR("%s: both the shard "DFID" and "DFID
912                                        " for the striped directory "DFID
913                                        " claim the same LMV EA slot at the "
914                                        "index %d, failout\n",
915                                        lod2obd(lod)->obd_name,
916                                        PFID(&fid0), PFID(&fid),
917                                        PFID(lu_object_fid(&obj->do_lu)), index);
918
919                                 break;
920                         }
921
922                         /* stored as LE mode */
923                         lmv1->lmv_stripe_fids[index] = ent->lde_fid;
924
925 next:
926                         rc = iops->next(env, it);
927                 }
928         }
929
930         iops->put(env, it);
931         iops->fini(env, it);
932
933         RETURN(rc > 0 ? lmv_mds_md_size(stripes, magic) : rc);
934 }
935
936 /**
937  * Implementation of dt_object_operations::do_index_try.
938  *
939  * \see dt_object_operations::do_index_try() in the API description for details.
940  */
941 static int lod_index_try(const struct lu_env *env, struct dt_object *dt,
942                          const struct dt_index_features *feat)
943 {
944         struct lod_object       *lo = lod_dt_obj(dt);
945         struct dt_object        *next = dt_object_child(dt);
946         int                     rc;
947         ENTRY;
948
949         LASSERT(next->do_ops);
950         LASSERT(next->do_ops->do_index_try);
951
952         rc = lod_striping_load(env, lo);
953         if (rc != 0)
954                 RETURN(rc);
955
956         rc = next->do_ops->do_index_try(env, next, feat);
957         if (rc != 0)
958                 RETURN(rc);
959
960         if (lo->ldo_dir_stripe_count > 0) {
961                 int i;
962
963                 for (i = 0; i < lo->ldo_dir_stripe_count; i++) {
964                         if (dt_object_exists(lo->ldo_stripe[i]) == 0)
965                                 continue;
966                         rc = lo->ldo_stripe[i]->do_ops->do_index_try(env,
967                                                 lo->ldo_stripe[i], feat);
968                         if (rc != 0)
969                                 RETURN(rc);
970                 }
971                 dt->do_index_ops = &lod_striped_index_ops;
972         } else {
973                 dt->do_index_ops = &lod_index_ops;
974         }
975
976         RETURN(rc);
977 }
978
979 /**
980  * Implementation of dt_object_operations::do_read_lock.
981  *
982  * \see dt_object_operations::do_read_lock() in the API description for details.
983  */
984 static void lod_read_lock(const struct lu_env *env, struct dt_object *dt,
985                           unsigned role)
986 {
987         dt_read_lock(env, dt_object_child(dt), role);
988 }
989
990 /**
991  * Implementation of dt_object_operations::do_write_lock.
992  *
993  * \see dt_object_operations::do_write_lock() in the API description for
994  * details.
995  */
996 static void lod_write_lock(const struct lu_env *env, struct dt_object *dt,
997                            unsigned role)
998 {
999         dt_write_lock(env, dt_object_child(dt), role);
1000 }
1001
1002 /**
1003  * Implementation of dt_object_operations::do_read_unlock.
1004  *
1005  * \see dt_object_operations::do_read_unlock() in the API description for
1006  * details.
1007  */
1008 static void lod_read_unlock(const struct lu_env *env, struct dt_object *dt)
1009 {
1010         dt_read_unlock(env, dt_object_child(dt));
1011 }
1012
1013 /**
1014  * Implementation of dt_object_operations::do_write_unlock.
1015  *
1016  * \see dt_object_operations::do_write_unlock() in the API description for
1017  * details.
1018  */
1019 static void lod_write_unlock(const struct lu_env *env, struct dt_object *dt)
1020 {
1021         dt_write_unlock(env, dt_object_child(dt));
1022 }
1023
1024 /**
1025  * Implementation of dt_object_operations::do_write_locked.
1026  *
1027  * \see dt_object_operations::do_write_locked() in the API description for
1028  * details.
1029  */
1030 static int lod_write_locked(const struct lu_env *env, struct dt_object *dt)
1031 {
1032         return dt_write_locked(env, dt_object_child(dt));
1033 }
1034
1035 /**
1036  * Implementation of dt_object_operations::do_attr_get.
1037  *
1038  * \see dt_object_operations::do_attr_get() in the API description for details.
1039  */
1040 static int lod_attr_get(const struct lu_env *env,
1041                         struct dt_object *dt,
1042                         struct lu_attr *attr)
1043 {
1044         /* Note: for striped directory, client will merge attributes
1045          * from all of the sub-stripes see lmv_merge_attr(), and there
1046          * no MDD logic depend on directory nlink/size/time, so we can
1047          * always use master inode nlink and size for now. */
1048         return dt_attr_get(env, dt_object_child(dt), attr);
1049 }
1050
1051 static inline void lod_adjust_stripe_info(struct lod_layout_component *comp,
1052                                           struct lov_desc *desc)
1053 {
1054         if (comp->llc_pattern != LOV_PATTERN_MDT) {
1055                 if (!comp->llc_stripe_count)
1056                         comp->llc_stripe_count =
1057                                 desc->ld_default_stripe_count;
1058         }
1059         if (comp->llc_stripe_size <= 0)
1060                 comp->llc_stripe_size = desc->ld_default_stripe_size;
1061 }
1062
1063 int lod_obj_for_each_stripe(const struct lu_env *env, struct lod_object *lo,
1064                             struct thandle *th,
1065                             struct lod_obj_stripe_cb_data *data)
1066 {
1067         struct lod_layout_component *lod_comp;
1068         int i, j, rc;
1069         ENTRY;
1070
1071         LASSERT(lo->ldo_comp_cnt != 0 && lo->ldo_comp_entries != NULL);
1072         for (i = 0; i < lo->ldo_comp_cnt; i++) {
1073                 lod_comp = &lo->ldo_comp_entries[i];
1074
1075                 if (lod_comp->llc_stripe == NULL)
1076                         continue;
1077
1078                 /* has stripe but not inited yet, this component has been
1079                  * declared to be created, but hasn't created yet.
1080                  */
1081                 if (!lod_comp_inited(lod_comp))
1082                         continue;
1083
1084                 if (data->locd_comp_skip_cb &&
1085                     data->locd_comp_skip_cb(env, lo, i, data))
1086                         continue;
1087
1088                 LASSERT(lod_comp->llc_stripe_count > 0);
1089                 for (j = 0; j < lod_comp->llc_stripe_count; j++) {
1090                         struct dt_object *dt = lod_comp->llc_stripe[j];
1091
1092                         if (dt == NULL)
1093                                 continue;
1094                         rc = data->locd_stripe_cb(env, lo, dt, th, i, j, data);
1095                         if (rc != 0)
1096                                 RETURN(rc);
1097                 }
1098         }
1099         RETURN(0);
1100 }
1101
1102 static bool lod_obj_attr_set_comp_skip_cb(const struct lu_env *env,
1103                 struct lod_object *lo, int comp_idx,
1104                 struct lod_obj_stripe_cb_data *data)
1105 {
1106         struct lod_layout_component *lod_comp = &lo->ldo_comp_entries[comp_idx];
1107         bool skipped = false;
1108
1109         if (!(data->locd_attr->la_valid & LA_LAYOUT_VERSION))
1110                 return skipped;
1111
1112         switch (lo->ldo_flr_state) {
1113         case LCM_FL_WRITE_PENDING: {
1114                 int i;
1115
1116                 /* skip stale components */
1117                 if (lod_comp->llc_flags & LCME_FL_STALE) {
1118                         skipped = true;
1119                         break;
1120                 }
1121
1122                 /* skip valid and overlapping components, therefore any
1123                  * attempts to write overlapped components will never succeed
1124                  * because client will get EINPROGRESS. */
1125                 for (i = 0; i < lo->ldo_comp_cnt; i++) {
1126                         if (i == comp_idx)
1127                                 continue;
1128
1129                         if (lo->ldo_comp_entries[i].llc_flags & LCME_FL_STALE)
1130                                 continue;
1131
1132                         if (lu_extent_is_overlapped(&lod_comp->llc_extent,
1133                                         &lo->ldo_comp_entries[i].llc_extent)) {
1134                                 skipped = true;
1135                                 break;
1136                         }
1137                 }
1138                 break;
1139         }
1140         default:
1141                 LASSERTF(0, "impossible: %d\n", lo->ldo_flr_state);
1142         case LCM_FL_SYNC_PENDING:
1143                 break;
1144         }
1145
1146         CDEBUG(D_LAYOUT, DFID": %s to set component %x to version: %u\n",
1147                PFID(lu_object_fid(&lo->ldo_obj.do_lu)),
1148                skipped ? "skipped" : "chose", lod_comp->llc_id,
1149                data->locd_attr->la_layout_version);
1150
1151         return skipped;
1152 }
1153
1154 static inline int
1155 lod_obj_stripe_attr_set_cb(const struct lu_env *env, struct lod_object *lo,
1156                            struct dt_object *dt, struct thandle *th,
1157                            int comp_idx, int stripe_idx,
1158                            struct lod_obj_stripe_cb_data *data)
1159 {
1160         if (data->locd_declare)
1161                 return lod_sub_declare_attr_set(env, dt, data->locd_attr, th);
1162
1163         if (data->locd_attr->la_valid & LA_LAYOUT_VERSION) {
1164                 CDEBUG(D_LAYOUT, DFID": set layout version: %u, comp_idx: %d\n",
1165                        PFID(lu_object_fid(&dt->do_lu)),
1166                        data->locd_attr->la_layout_version, comp_idx);
1167         }
1168
1169         return lod_sub_attr_set(env, dt, data->locd_attr, th);
1170 }
1171
1172 /**
1173  * Implementation of dt_object_operations::do_declare_attr_set.
1174  *
1175  * If the object is striped, then apply the changes to all the stripes.
1176  *
1177  * \see dt_object_operations::do_declare_attr_set() in the API description
1178  * for details.
1179  */
1180 static int lod_declare_attr_set(const struct lu_env *env,
1181                                 struct dt_object *dt,
1182                                 const struct lu_attr *attr,
1183                                 struct thandle *th)
1184 {
1185         struct dt_object  *next = dt_object_child(dt);
1186         struct lod_object *lo = lod_dt_obj(dt);
1187         int                rc, i;
1188         ENTRY;
1189
1190         /*
1191          * declare setattr on the local object
1192          */
1193         rc = lod_sub_declare_attr_set(env, next, attr, th);
1194         if (rc)
1195                 RETURN(rc);
1196
1197         /* osp_declare_attr_set() ignores all attributes other than
1198          * UID, GID, PROJID, and size, and osp_attr_set() ignores all
1199          * but UID, GID and PROJID. Declaration of size attr setting
1200          * happens through lod_declare_init_size(), and not through
1201          * this function. Therefore we need not load striping unless
1202          * ownership is changing.  This should save memory and (we hope)
1203          * speed up rename().
1204          */
1205         if (!S_ISDIR(dt->do_lu.lo_header->loh_attr)) {
1206                 if (!(attr->la_valid & LA_REMOTE_ATTR_SET))
1207                         RETURN(rc);
1208
1209                 if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_BAD_OWNER))
1210                         RETURN(0);
1211         } else {
1212                 if (!(attr->la_valid & (LA_UID | LA_GID | LA_PROJID | LA_MODE |
1213                                         LA_ATIME | LA_MTIME | LA_CTIME |
1214                                         LA_FLAGS)))
1215                         RETURN(rc);
1216         }
1217         /*
1218          * load striping information, notice we don't do this when object
1219          * is being initialized as we don't need this information till
1220          * few specific cases like destroy, chown
1221          */
1222         rc = lod_striping_load(env, lo);
1223         if (rc)
1224                 RETURN(rc);
1225
1226         if (!lod_obj_is_striped(dt))
1227                 RETURN(0);
1228
1229         /*
1230          * if object is striped declare changes on the stripes
1231          */
1232         if (S_ISDIR(dt->do_lu.lo_header->loh_attr)) {
1233                 LASSERT(lo->ldo_stripe);
1234                 for (i = 0; i < lo->ldo_dir_stripe_count; i++) {
1235                         if (lo->ldo_stripe[i] == NULL)
1236                                 continue;
1237                         rc = lod_sub_declare_attr_set(env, lo->ldo_stripe[i],
1238                                                       attr, th);
1239                         if (rc != 0)
1240                                 RETURN(rc);
1241                 }
1242         } else {
1243                 struct lod_obj_stripe_cb_data data = { { 0 } };
1244
1245                 data.locd_attr = attr;
1246                 data.locd_declare = true;
1247                 data.locd_stripe_cb = lod_obj_stripe_attr_set_cb;
1248                 rc = lod_obj_for_each_stripe(env, lo, th, &data);
1249         }
1250
1251         if (rc)
1252                 RETURN(rc);
1253
1254         if (!dt_object_exists(next) || dt_object_remote(next) ||
1255             !S_ISREG(attr->la_mode))
1256                 RETURN(0);
1257
1258         if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_LOST_STRIPE)) {
1259                 rc = lod_sub_declare_xattr_del(env, next, XATTR_NAME_LOV, th);
1260                 RETURN(rc);
1261         }
1262
1263         if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_CHANGE_STRIPE) ||
1264             OBD_FAIL_CHECK(OBD_FAIL_LFSCK_BAD_PFL_RANGE)) {
1265                 struct lod_thread_info *info = lod_env_info(env);
1266                 struct lu_buf *buf = &info->lti_buf;
1267
1268                 buf->lb_buf = info->lti_ea_store;
1269                 buf->lb_len = info->lti_ea_store_size;
1270                 rc = lod_sub_declare_xattr_set(env, next, buf, XATTR_NAME_LOV,
1271                                                LU_XATTR_REPLACE, th);
1272         }
1273
1274         RETURN(rc);
1275 }
1276
1277 /**
1278  * Implementation of dt_object_operations::do_attr_set.
1279  *
1280  * If the object is striped, then apply the changes to all or subset of
1281  * the stripes depending on the object type and specific attributes.
1282  *
1283  * \see dt_object_operations::do_attr_set() in the API description for details.
1284  */
1285 static int lod_attr_set(const struct lu_env *env,
1286                         struct dt_object *dt,
1287                         const struct lu_attr *attr,
1288                         struct thandle *th)
1289 {
1290         struct dt_object        *next = dt_object_child(dt);
1291         struct lod_object       *lo = lod_dt_obj(dt);
1292         int                     rc, i;
1293         ENTRY;
1294
1295         /*
1296          * apply changes to the local object
1297          */
1298         rc = lod_sub_attr_set(env, next, attr, th);
1299         if (rc)
1300                 RETURN(rc);
1301
1302         if (!S_ISDIR(dt->do_lu.lo_header->loh_attr)) {
1303                 if (!(attr->la_valid & LA_REMOTE_ATTR_SET))
1304                         RETURN(rc);
1305
1306                 if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_BAD_OWNER))
1307                         RETURN(0);
1308         } else {
1309                 if (!(attr->la_valid & (LA_UID | LA_GID | LA_MODE | LA_PROJID |
1310                                         LA_ATIME | LA_MTIME | LA_CTIME |
1311                                         LA_FLAGS)))
1312                         RETURN(rc);
1313         }
1314
1315         /* FIXME: a tricky case in the code path of mdd_layout_change():
1316          * the in-memory striping information has been freed in lod_xattr_set()
1317          * due to layout change. It has to load stripe here again. It only
1318          * changes flags of layout so declare_attr_set() is still accurate */
1319         rc = lod_striping_load(env, lo);
1320         if (rc)
1321                 RETURN(rc);
1322
1323         if (!lod_obj_is_striped(dt))
1324                 RETURN(0);
1325
1326         /*
1327          * if object is striped, apply changes to all the stripes
1328          */
1329         if (S_ISDIR(dt->do_lu.lo_header->loh_attr)) {
1330                 LASSERT(lo->ldo_stripe);
1331                 for (i = 0; i < lo->ldo_dir_stripe_count; i++) {
1332                         if (unlikely(lo->ldo_stripe[i] == NULL))
1333                                 continue;
1334
1335                         if ((dt_object_exists(lo->ldo_stripe[i]) == 0))
1336                                 continue;
1337
1338                         rc = lod_sub_attr_set(env, lo->ldo_stripe[i], attr, th);
1339                         if (rc != 0)
1340                                 break;
1341                 }
1342         } else {
1343                 struct lod_obj_stripe_cb_data data = { { 0 } };
1344
1345                 data.locd_attr = attr;
1346                 data.locd_declare = false;
1347                 data.locd_comp_skip_cb = lod_obj_attr_set_comp_skip_cb;
1348                 data.locd_stripe_cb = lod_obj_stripe_attr_set_cb;
1349                 rc = lod_obj_for_each_stripe(env, lo, th, &data);
1350         }
1351
1352         if (rc)
1353                 RETURN(rc);
1354
1355         if (!dt_object_exists(next) || dt_object_remote(next) ||
1356             !S_ISREG(attr->la_mode))
1357                 RETURN(0);
1358
1359         if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_LOST_STRIPE)) {
1360                 rc = lod_sub_xattr_del(env, next, XATTR_NAME_LOV, th);
1361                 RETURN(rc);
1362         }
1363
1364         if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_CHANGE_STRIPE)) {
1365                 struct lod_thread_info *info = lod_env_info(env);
1366                 struct lu_buf *buf = &info->lti_buf;
1367                 struct ost_id *oi = &info->lti_ostid;
1368                 struct lu_fid *fid = &info->lti_fid;
1369                 struct lov_mds_md_v1 *lmm;
1370                 struct lov_ost_data_v1 *objs;
1371                 __u32 magic;
1372
1373                 rc = lod_get_lov_ea(env, lo);
1374                 if (rc <= 0)
1375                         RETURN(rc);
1376
1377                 buf->lb_buf = info->lti_ea_store;
1378                 buf->lb_len = info->lti_ea_store_size;
1379                 lmm = info->lti_ea_store;
1380                 magic = le32_to_cpu(lmm->lmm_magic);
1381                 if (magic == LOV_MAGIC_COMP_V1) {
1382                         struct lov_comp_md_v1 *lcm = buf->lb_buf;
1383                         struct lov_comp_md_entry_v1 *lcme =
1384                                                 &lcm->lcm_entries[0];
1385
1386                         lmm = buf->lb_buf + le32_to_cpu(lcme->lcme_offset);
1387                         magic = le32_to_cpu(lmm->lmm_magic);
1388                 }
1389
1390                 if (magic == LOV_MAGIC_V1)
1391                         objs = &(lmm->lmm_objects[0]);
1392                 else
1393                         objs = &((struct lov_mds_md_v3 *)lmm)->lmm_objects[0];
1394                 ostid_le_to_cpu(&objs->l_ost_oi, oi);
1395                 ostid_to_fid(fid, oi, le32_to_cpu(objs->l_ost_idx));
1396                 fid->f_oid--;
1397                 fid_to_ostid(fid, oi);
1398                 ostid_cpu_to_le(oi, &objs->l_ost_oi);
1399
1400                 rc = lod_sub_xattr_set(env, next, buf, XATTR_NAME_LOV,
1401                                        LU_XATTR_REPLACE, th);
1402         } else if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_BAD_PFL_RANGE)) {
1403                 struct lod_thread_info *info = lod_env_info(env);
1404                 struct lu_buf *buf = &info->lti_buf;
1405                 struct lov_comp_md_v1 *lcm;
1406                 struct lov_comp_md_entry_v1 *lcme;
1407
1408                 rc = lod_get_lov_ea(env, lo);
1409                 if (rc <= 0)
1410                         RETURN(rc);
1411
1412                 buf->lb_buf = info->lti_ea_store;
1413                 buf->lb_len = info->lti_ea_store_size;
1414                 lcm = buf->lb_buf;
1415                 if (le32_to_cpu(lcm->lcm_magic) != LOV_MAGIC_COMP_V1)
1416                         RETURN(-EINVAL);
1417
1418                 le32_add_cpu(&lcm->lcm_layout_gen, 1);
1419                 lcme = &lcm->lcm_entries[0];
1420                 le64_add_cpu(&lcme->lcme_extent.e_start, 1);
1421                 le64_add_cpu(&lcme->lcme_extent.e_end, -1);
1422
1423                 rc = lod_sub_xattr_set(env, next, buf, XATTR_NAME_LOV,
1424                                        LU_XATTR_REPLACE, th);
1425         }
1426
1427         RETURN(rc);
1428 }
1429
1430 /**
1431  * Implementation of dt_object_operations::do_xattr_get.
1432  *
1433  * If LOV EA is requested from the root object and it's not
1434  * found, then return default striping for the filesystem.
1435  *
1436  * \see dt_object_operations::do_xattr_get() in the API description for details.
1437  */
1438 static int lod_xattr_get(const struct lu_env *env, struct dt_object *dt,
1439                          struct lu_buf *buf, const char *name)
1440 {
1441         struct lod_thread_info *info = lod_env_info(env);
1442         struct lod_device *dev = lu2lod_dev(dt->do_lu.lo_dev);
1443         int is_root;
1444         int rc;
1445         ENTRY;
1446
1447         rc = dt_xattr_get(env, dt_object_child(dt), buf, name);
1448         if (strcmp(name, XATTR_NAME_LMV) == 0) {
1449                 struct lmv_mds_md_v1    *lmv1;
1450                 int                      rc1 = 0;
1451
1452                 if (rc > (typeof(rc))sizeof(*lmv1))
1453                         RETURN(rc);
1454
1455                 if (rc < (typeof(rc))sizeof(*lmv1))
1456                         RETURN(rc = rc > 0 ? -EINVAL : rc);
1457
1458                 if (buf->lb_buf == NULL || buf->lb_len == 0) {
1459                         CLASSERT(sizeof(*lmv1) <= sizeof(info->lti_key));
1460
1461                         info->lti_buf.lb_buf = info->lti_key;
1462                         info->lti_buf.lb_len = sizeof(*lmv1);
1463                         rc = dt_xattr_get(env, dt_object_child(dt),
1464                                           &info->lti_buf, name);
1465                         if (unlikely(rc != sizeof(*lmv1)))
1466                                 RETURN(rc = rc > 0 ? -EINVAL : rc);
1467
1468                         lmv1 = info->lti_buf.lb_buf;
1469                         /* The on-disk LMV EA only contains header, but the
1470                          * returned LMV EA size should contain the space for
1471                          * the FIDs of all shards of the striped directory. */
1472                         if (le32_to_cpu(lmv1->lmv_magic) == LMV_MAGIC_V1)
1473                                 rc = lmv_mds_md_size(
1474                                         le32_to_cpu(lmv1->lmv_stripe_count),
1475                                         LMV_MAGIC_V1);
1476                 } else {
1477                         rc1 = lod_load_lmv_shards(env, lod_dt_obj(dt),
1478                                                   buf, false);
1479                 }
1480
1481                 RETURN(rc = rc1 != 0 ? rc1 : rc);
1482         }
1483
1484         if (rc != -ENODATA || !S_ISDIR(dt->do_lu.lo_header->loh_attr & S_IFMT))
1485                 RETURN(rc);
1486
1487         /*
1488          * XXX: Only used by lfsck
1489          *
1490          * lod returns default striping on the real root of the device
1491          * this is like the root stores default striping for the whole
1492          * filesystem. historically we've been using a different approach
1493          * and store it in the config.
1494          */
1495         dt_root_get(env, dev->lod_child, &info->lti_fid);
1496         is_root = lu_fid_eq(&info->lti_fid, lu_object_fid(&dt->do_lu));
1497
1498         if (is_root && strcmp(XATTR_NAME_LOV, name) == 0) {
1499                 struct lov_user_md *lum = buf->lb_buf;
1500                 struct lov_desc    *desc = &dev->lod_desc;
1501
1502                 if (buf->lb_buf == NULL) {
1503                         rc = sizeof(*lum);
1504                 } else if (buf->lb_len >= sizeof(*lum)) {
1505                         lum->lmm_magic = cpu_to_le32(LOV_USER_MAGIC_V1);
1506                         lmm_oi_set_seq(&lum->lmm_oi, FID_SEQ_LOV_DEFAULT);
1507                         lmm_oi_set_id(&lum->lmm_oi, 0);
1508                         lmm_oi_cpu_to_le(&lum->lmm_oi, &lum->lmm_oi);
1509                         lum->lmm_pattern = cpu_to_le32(desc->ld_pattern);
1510                         lum->lmm_stripe_size = cpu_to_le32(
1511                                                 desc->ld_default_stripe_size);
1512                         lum->lmm_stripe_count = cpu_to_le16(
1513                                                 desc->ld_default_stripe_count);
1514                         lum->lmm_stripe_offset = cpu_to_le16(
1515                                                 desc->ld_default_stripe_offset);
1516                         rc = sizeof(*lum);
1517                 } else {
1518                         rc = -ERANGE;
1519                 }
1520         }
1521
1522         RETURN(rc);
1523 }
1524
1525 /**
1526  * Verify LVM EA.
1527  *
1528  * Checks that the magic of the stripe is sane.
1529  *
1530  * \param[in] lod       lod device
1531  * \param[in] lum       a buffer storing LMV EA to verify
1532  *
1533  * \retval              0 if the EA is sane
1534  * \retval              negative otherwise
1535  */
1536 static int lod_verify_md_striping(struct lod_device *lod,
1537                                   const struct lmv_user_md_v1 *lum)
1538 {
1539         if (unlikely(le32_to_cpu(lum->lum_magic) != LMV_USER_MAGIC)) {
1540                 CERROR("%s: invalid lmv_user_md: magic = %x, "
1541                        "stripe_offset = %d, stripe_count = %u: rc = %d\n",
1542                        lod2obd(lod)->obd_name, le32_to_cpu(lum->lum_magic),
1543                        (int)le32_to_cpu(lum->lum_stripe_offset),
1544                        le32_to_cpu(lum->lum_stripe_count), -EINVAL);
1545                 return -EINVAL;
1546         }
1547
1548         return 0;
1549 }
1550
1551 /**
1552  * Initialize LMV EA for a slave.
1553  *
1554  * Initialize slave's LMV EA from the master's LMV EA.
1555  *
1556  * \param[in] master_lmv        a buffer containing master's EA
1557  * \param[out] slave_lmv        a buffer where slave's EA will be stored
1558  *
1559  */
1560 static void lod_prep_slave_lmv_md(struct lmv_mds_md_v1 *slave_lmv,
1561                                   const struct lmv_mds_md_v1 *master_lmv)
1562 {
1563         *slave_lmv = *master_lmv;
1564         slave_lmv->lmv_magic = cpu_to_le32(LMV_MAGIC_STRIPE);
1565 }
1566
1567 /**
1568  * Generate LMV EA.
1569  *
1570  * Generate LMV EA from the object passed as \a dt. The object must have
1571  * the stripes created and initialized.
1572  *
1573  * \param[in] env       execution environment
1574  * \param[in] dt        object
1575  * \param[out] lmv_buf  buffer storing generated LMV EA
1576  *
1577  * \retval              0 on success
1578  * \retval              negative if failed
1579  */
1580 static int lod_prep_lmv_md(const struct lu_env *env, struct dt_object *dt,
1581                            struct lu_buf *lmv_buf)
1582 {
1583         struct lod_thread_info  *info = lod_env_info(env);
1584         struct lod_device       *lod = lu2lod_dev(dt->do_lu.lo_dev);
1585         struct lod_object       *lo = lod_dt_obj(dt);
1586         struct lmv_mds_md_v1    *lmm1;
1587         int                     stripe_count;
1588         int                     type = LU_SEQ_RANGE_ANY;
1589         int                     rc;
1590         __u32                   mdtidx;
1591         ENTRY;
1592
1593         LASSERT(lo->ldo_dir_striped != 0);
1594         LASSERT(lo->ldo_dir_stripe_count > 0);
1595         stripe_count = lo->ldo_dir_stripe_count;
1596         /* Only store the LMV EA heahder on the disk. */
1597         if (info->lti_ea_store_size < sizeof(*lmm1)) {
1598                 rc = lod_ea_store_resize(info, sizeof(*lmm1));
1599                 if (rc != 0)
1600                         RETURN(rc);
1601         } else {
1602                 memset(info->lti_ea_store, 0, sizeof(*lmm1));
1603         }
1604
1605         lmm1 = (struct lmv_mds_md_v1 *)info->lti_ea_store;
1606         lmm1->lmv_magic = cpu_to_le32(LMV_MAGIC);
1607         lmm1->lmv_stripe_count = cpu_to_le32(stripe_count);
1608         lmm1->lmv_hash_type = cpu_to_le32(lo->ldo_dir_hash_type);
1609         rc = lod_fld_lookup(env, lod, lu_object_fid(&dt->do_lu),
1610                             &mdtidx, &type);
1611         if (rc != 0)
1612                 RETURN(rc);
1613
1614         lmm1->lmv_master_mdt_index = cpu_to_le32(mdtidx);
1615         lmv_buf->lb_buf = info->lti_ea_store;
1616         lmv_buf->lb_len = sizeof(*lmm1);
1617
1618         RETURN(rc);
1619 }
1620
1621 /**
1622  * Create in-core represenation for a striped directory.
1623  *
1624  * Parse the buffer containing LMV EA and instantiate LU objects
1625  * representing the stripe objects. The pointers to the objects are
1626  * stored in ldo_stripe field of \a lo. This function is used when
1627  * we need to access an already created object (i.e. load from a disk).
1628  *
1629  * \param[in] env       execution environment
1630  * \param[in] lo        lod object
1631  * \param[in] buf       buffer containing LMV EA
1632  *
1633  * \retval              0 on success
1634  * \retval              negative if failed
1635  */
1636 int lod_parse_dir_striping(const struct lu_env *env, struct lod_object *lo,
1637                            const struct lu_buf *buf)
1638 {
1639         struct lod_thread_info  *info = lod_env_info(env);
1640         struct lod_device       *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
1641         struct lod_tgt_descs    *ltd = &lod->lod_mdt_descs;
1642         struct dt_object        **stripe;
1643         union lmv_mds_md        *lmm = buf->lb_buf;
1644         struct lmv_mds_md_v1    *lmv1 = &lmm->lmv_md_v1;
1645         struct lu_fid           *fid = &info->lti_fid;
1646         unsigned int            i;
1647         int                     rc = 0;
1648         ENTRY;
1649
1650         LASSERT(mutex_is_locked(&lo->ldo_layout_mutex));
1651
1652         if (le32_to_cpu(lmv1->lmv_hash_type) & LMV_HASH_FLAG_MIGRATION)
1653                 RETURN(0);
1654
1655         if (le32_to_cpu(lmv1->lmv_magic) == LMV_MAGIC_STRIPE) {
1656                 lo->ldo_dir_slave_stripe = 1;
1657                 RETURN(0);
1658         }
1659
1660         if (le32_to_cpu(lmv1->lmv_magic) != LMV_MAGIC_V1)
1661                 RETURN(-EINVAL);
1662
1663         if (le32_to_cpu(lmv1->lmv_stripe_count) < 1)
1664                 RETURN(0);
1665
1666         LASSERT(lo->ldo_stripe == NULL);
1667         OBD_ALLOC(stripe, sizeof(stripe[0]) *
1668                   (le32_to_cpu(lmv1->lmv_stripe_count)));
1669         if (stripe == NULL)
1670                 RETURN(-ENOMEM);
1671
1672         for (i = 0; i < le32_to_cpu(lmv1->lmv_stripe_count); i++) {
1673                 struct dt_device        *tgt_dt;
1674                 struct dt_object        *dto;
1675                 int                     type = LU_SEQ_RANGE_ANY;
1676                 __u32                   idx;
1677
1678                 fid_le_to_cpu(fid, &lmv1->lmv_stripe_fids[i]);
1679                 if (!fid_is_sane(fid))
1680                         GOTO(out, rc = -ESTALE);
1681
1682                 rc = lod_fld_lookup(env, lod, fid, &idx, &type);
1683                 if (rc != 0)
1684                         GOTO(out, rc);
1685
1686                 if (idx == lod2lu_dev(lod)->ld_site->ld_seq_site->ss_node_id) {
1687                         tgt_dt = lod->lod_child;
1688                 } else {
1689                         struct lod_tgt_desc     *tgt;
1690
1691                         tgt = LTD_TGT(ltd, idx);
1692                         if (tgt == NULL)
1693                                 GOTO(out, rc = -ESTALE);
1694                         tgt_dt = tgt->ltd_tgt;
1695                 }
1696
1697                 dto = dt_locate_at(env, tgt_dt, fid,
1698                                   lo->ldo_obj.do_lu.lo_dev->ld_site->ls_top_dev,
1699                                   NULL);
1700                 if (IS_ERR(dto))
1701                         GOTO(out, rc = PTR_ERR(dto));
1702
1703                 stripe[i] = dto;
1704         }
1705 out:
1706         lo->ldo_stripe = stripe;
1707         lo->ldo_dir_stripe_count = le32_to_cpu(lmv1->lmv_stripe_count);
1708         lo->ldo_dir_stripes_allocated = le32_to_cpu(lmv1->lmv_stripe_count);
1709         if (rc != 0)
1710                 lod_striping_free_nolock(env, lo);
1711
1712         RETURN(rc);
1713 }
1714
1715 /**
1716  * Declare create a striped directory.
1717  *
1718  * Declare creating a striped directory with a given stripe pattern on the
1719  * specified MDTs. A striped directory is represented as a regular directory
1720  * - an index listing all the stripes. The stripes point back to the master
1721  * object with ".." and LinkEA. The master object gets LMV EA which
1722  * identifies it as a striped directory. The function allocates FIDs
1723  * for all stripes.
1724  *
1725  * \param[in] env       execution environment
1726  * \param[in] dt        object
1727  * \param[in] attr      attributes to initialize the objects with
1728  * \param[in] dof       type of objects to be created
1729  * \param[in] th        transaction handle
1730  *
1731  * \retval              0 on success
1732  * \retval              negative if failed
1733  */
1734 static int lod_dir_declare_create_stripes(const struct lu_env *env,
1735                                           struct dt_object *dt,
1736                                           struct lu_attr *attr,
1737                                           struct dt_object_format *dof,
1738                                           struct thandle *th)
1739 {
1740         struct lod_thread_info  *info = lod_env_info(env);
1741         struct lu_buf           lmv_buf;
1742         struct lu_buf           slave_lmv_buf;
1743         struct lmv_mds_md_v1    *lmm;
1744         struct lmv_mds_md_v1    *slave_lmm = NULL;
1745         struct dt_insert_rec    *rec = &info->lti_dt_rec;
1746         struct lod_object       *lo = lod_dt_obj(dt);
1747         int                     rc;
1748         __u32                   i;
1749         ENTRY;
1750
1751         rc = lod_prep_lmv_md(env, dt, &lmv_buf);
1752         if (rc != 0)
1753                 GOTO(out, rc);
1754         lmm = lmv_buf.lb_buf;
1755
1756         OBD_ALLOC_PTR(slave_lmm);
1757         if (slave_lmm == NULL)
1758                 GOTO(out, rc = -ENOMEM);
1759
1760         lod_prep_slave_lmv_md(slave_lmm, lmm);
1761         slave_lmv_buf.lb_buf = slave_lmm;
1762         slave_lmv_buf.lb_len = sizeof(*slave_lmm);
1763
1764         if (!dt_try_as_dir(env, dt_object_child(dt)))
1765                 GOTO(out, rc = -EINVAL);
1766
1767         rec->rec_type = S_IFDIR;
1768         for (i = 0; i < lo->ldo_dir_stripe_count; i++) {
1769                 struct dt_object        *dto = lo->ldo_stripe[i];
1770                 char                    *stripe_name = info->lti_key;
1771                 struct lu_name          *sname;
1772                 struct linkea_data       ldata          = { NULL };
1773                 struct lu_buf           linkea_buf;
1774
1775                 rc = lod_sub_declare_create(env, dto, attr, NULL, dof, th);
1776                 if (rc != 0)
1777                         GOTO(out, rc);
1778
1779                 if (!dt_try_as_dir(env, dto))
1780                         GOTO(out, rc = -EINVAL);
1781
1782                 rc = lod_sub_declare_ref_add(env, dto, th);
1783                 if (rc != 0)
1784                         GOTO(out, rc);
1785
1786                 rec->rec_fid = lu_object_fid(&dto->do_lu);
1787                 rc = lod_sub_declare_insert(env, dto,
1788                                             (const struct dt_rec *)rec,
1789                                             (const struct dt_key *)dot, th);
1790                 if (rc != 0)
1791                         GOTO(out, rc);
1792
1793                 /* master stripe FID will be put to .. */
1794                 rec->rec_fid = lu_object_fid(&dt->do_lu);
1795                 rc = lod_sub_declare_insert(env, dto,
1796                                             (const struct dt_rec *)rec,
1797                                             (const struct dt_key *)dotdot, th);
1798                 if (rc != 0)
1799                         GOTO(out, rc);
1800
1801                 if (!OBD_FAIL_CHECK(OBD_FAIL_LFSCK_LOST_SLAVE_LMV) ||
1802                     cfs_fail_val != i) {
1803                         if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_BAD_SLAVE_LMV) &&
1804                             cfs_fail_val == i)
1805                                 slave_lmm->lmv_master_mdt_index =
1806                                                         cpu_to_le32(i + 1);
1807                         else
1808                                 slave_lmm->lmv_master_mdt_index =
1809                                                         cpu_to_le32(i);
1810                         rc = lod_sub_declare_xattr_set(env, dto, &slave_lmv_buf,
1811                                                        XATTR_NAME_LMV, 0, th);
1812                         if (rc != 0)
1813                                 GOTO(out, rc);
1814                 }
1815
1816                 if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_BAD_SLAVE_NAME) &&
1817                     cfs_fail_val == i)
1818                         snprintf(stripe_name, sizeof(info->lti_key), DFID":%u",
1819                                 PFID(lu_object_fid(&dto->do_lu)), i + 1);
1820                 else
1821                         snprintf(stripe_name, sizeof(info->lti_key), DFID":%u",
1822                                 PFID(lu_object_fid(&dto->do_lu)), i);
1823
1824                 sname = lod_name_get(env, stripe_name, strlen(stripe_name));
1825                 rc = linkea_links_new(&ldata, &info->lti_linkea_buf,
1826                                       sname, lu_object_fid(&dt->do_lu));
1827                 if (rc != 0)
1828                         GOTO(out, rc);
1829
1830                 linkea_buf.lb_buf = ldata.ld_buf->lb_buf;
1831                 linkea_buf.lb_len = ldata.ld_leh->leh_len;
1832                 rc = lod_sub_declare_xattr_set(env, dto, &linkea_buf,
1833                                                XATTR_NAME_LINK, 0, th);
1834                 if (rc != 0)
1835                         GOTO(out, rc);
1836
1837                 rec->rec_fid = lu_object_fid(&dto->do_lu);
1838                 rc = lod_sub_declare_insert(env, dt_object_child(dt),
1839                                             (const struct dt_rec *)rec,
1840                                             (const struct dt_key *)stripe_name,
1841                                             th);
1842                 if (rc != 0)
1843                         GOTO(out, rc);
1844
1845                 rc = lod_sub_declare_ref_add(env, dt_object_child(dt), th);
1846                 if (rc != 0)
1847                         GOTO(out, rc);
1848         }
1849
1850         rc = lod_sub_declare_xattr_set(env, dt_object_child(dt),
1851                                        &lmv_buf, XATTR_NAME_LMV, 0, th);
1852         if (rc != 0)
1853                 GOTO(out, rc);
1854 out:
1855         if (slave_lmm != NULL)
1856                 OBD_FREE_PTR(slave_lmm);
1857
1858         RETURN(rc);
1859 }
1860
1861 static int lod_prep_md_striped_create(const struct lu_env *env,
1862                                       struct dt_object *dt,
1863                                       struct lu_attr *attr,
1864                                       const struct lmv_user_md_v1 *lum,
1865                                       struct dt_object_format *dof,
1866                                       struct thandle *th)
1867 {
1868         struct lod_device       *lod = lu2lod_dev(dt->do_lu.lo_dev);
1869         struct lod_tgt_descs    *ltd = &lod->lod_mdt_descs;
1870         struct lod_object       *lo = lod_dt_obj(dt);
1871         struct dt_object        **stripe;
1872         __u32                   stripe_count;
1873         int                     *idx_array;
1874         __u32                   master_index;
1875         int                     rc = 0;
1876         __u32                   i;
1877         __u32                   j;
1878         bool                    is_specific = false;
1879         ENTRY;
1880
1881         /* The lum has been verifed in lod_verify_md_striping */
1882         LASSERT(le32_to_cpu(lum->lum_magic) == LMV_USER_MAGIC ||
1883                 le32_to_cpu(lum->lum_magic) == LMV_USER_MAGIC_SPECIFIC);
1884         LASSERT(le32_to_cpu(lum->lum_stripe_count) > 0);
1885
1886         stripe_count = le32_to_cpu(lum->lum_stripe_count);
1887
1888         OBD_ALLOC(idx_array, sizeof(idx_array[0]) * stripe_count);
1889         if (idx_array == NULL)
1890                 RETURN(-ENOMEM);
1891
1892         OBD_ALLOC(stripe, sizeof(stripe[0]) * stripe_count);
1893         if (stripe == NULL)
1894                 GOTO(out_free, rc = -ENOMEM);
1895
1896         /* Start index must be the master MDT */
1897         master_index = lu_site2seq(lod2lu_dev(lod)->ld_site)->ss_node_id;
1898         idx_array[0] = master_index;
1899         if (le32_to_cpu(lum->lum_magic) == LMV_USER_MAGIC_SPECIFIC) {
1900                 is_specific = true;
1901                 for (i = 1; i < stripe_count; i++)
1902                         idx_array[i] = le32_to_cpu(lum->lum_objects[i].lum_mds);
1903         }
1904
1905         for (i = 0; i < stripe_count; i++) {
1906                 struct lod_tgt_desc     *tgt = NULL;
1907                 struct dt_object        *dto;
1908                 struct lu_fid           fid = { 0 };
1909                 int                     idx;
1910                 struct lu_object_conf   conf = { 0 };
1911                 struct dt_device        *tgt_dt = NULL;
1912
1913                 /* Try to find next avaible target */
1914                 idx = idx_array[i];
1915                 for (j = 0; j < lod->lod_remote_mdt_count;
1916                      j++, idx = (idx + 1) % (lod->lod_remote_mdt_count + 1)) {
1917                         bool already_allocated = false;
1918                         __u32 k;
1919
1920                         CDEBUG(D_INFO, "try idx %d, mdt cnt %u, allocated %u\n",
1921                                idx, lod->lod_remote_mdt_count + 1, i);
1922
1923                         if (likely(!is_specific &&
1924                                    !OBD_FAIL_CHECK(OBD_FAIL_LARGE_STRIPE))) {
1925                                 /* check whether the idx already exists
1926                                  * in current allocated array */
1927                                 for (k = 0; k < i; k++) {
1928                                         if (idx_array[k] == idx) {
1929                                                 already_allocated = true;
1930                                                 break;
1931                                         }
1932                                 }
1933
1934                                 if (already_allocated)
1935                                         continue;
1936                         }
1937
1938                         /* Sigh, this index is not in the bitmap, let's check
1939                          * next available target */
1940                         if (!cfs_bitmap_check(ltd->ltd_tgt_bitmap, idx) &&
1941                             idx != master_index)
1942                                 continue;
1943
1944                         if (idx == master_index) {
1945                                 /* Allocate the FID locally */
1946                                 rc = obd_fid_alloc(env, lod->lod_child_exp,
1947                                                    &fid, NULL);
1948                                 if (rc < 0)
1949                                         GOTO(out_put, rc);
1950                                 tgt_dt = lod->lod_child;
1951                                 break;
1952                         }
1953
1954                         /* check the status of the OSP */
1955                         tgt = LTD_TGT(ltd, idx);
1956                         if (tgt == NULL)
1957                                 continue;
1958
1959                         tgt_dt = tgt->ltd_tgt;
1960                         rc = dt_statfs(env, tgt_dt, NULL);
1961                         if (rc) {
1962                                 /* this OSP doesn't feel well */
1963                                 rc = 0;
1964                                 continue;
1965                         }
1966
1967                         rc = obd_fid_alloc(env, tgt->ltd_exp, &fid, NULL);
1968                         if (rc < 0) {
1969                                 rc = 0;
1970                                 continue;
1971                         }
1972
1973                         break;
1974                 }
1975
1976                 /* Can not allocate more stripes */
1977                 if (j == lod->lod_remote_mdt_count) {
1978                         CDEBUG(D_INFO, "%s: require stripes %u only get %d\n",
1979                                lod2obd(lod)->obd_name, stripe_count, i);
1980                         break;
1981                 }
1982
1983                 CDEBUG(D_INFO, "Get idx %d, for stripe %d "DFID"\n",
1984                        idx, i, PFID(&fid));
1985                 idx_array[i] = idx;
1986                 /* Set the start index for next stripe allocation */
1987                 if (!is_specific && i < stripe_count - 1) {
1988                         /*
1989                          * for large dir test, put all other slaves on one
1990                          * remote MDT, otherwise we may save too many local
1991                          * slave locks which will exceed RS_MAX_LOCKS.
1992                          */
1993                         if (unlikely(OBD_FAIL_CHECK(OBD_FAIL_LARGE_STRIPE)))
1994                                 idx = master_index;
1995                         idx_array[i + 1] = (idx + 1) %
1996                                            (lod->lod_remote_mdt_count + 1);
1997                 }
1998                 /* tgt_dt and fid must be ready after search avaible OSP
1999                  * in the above loop */
2000                 LASSERT(tgt_dt != NULL);
2001                 LASSERT(fid_is_sane(&fid));
2002                 conf.loc_flags = LOC_F_NEW;
2003                 dto = dt_locate_at(env, tgt_dt, &fid,
2004                                    dt->do_lu.lo_dev->ld_site->ls_top_dev,
2005                                    &conf);
2006                 if (IS_ERR(dto))
2007                         GOTO(out_put, rc = PTR_ERR(dto));
2008                 stripe[i] = dto;
2009         }
2010
2011         lo->ldo_dir_striped = 1;
2012         lo->ldo_stripe = stripe;
2013         lo->ldo_dir_stripe_count = i;
2014         lo->ldo_dir_stripes_allocated = stripe_count;
2015         smp_mb();
2016         lo->ldo_dir_stripe_loaded = 1;
2017
2018         if (lo->ldo_dir_stripe_count == 0)
2019                 GOTO(out_put, rc = -ENOSPC);
2020
2021         rc = lod_dir_declare_create_stripes(env, dt, attr, dof, th);
2022         if (rc != 0)
2023                 GOTO(out_put, rc);
2024
2025 out_put:
2026         if (rc < 0) {
2027                 for (i = 0; i < stripe_count; i++)
2028                         if (stripe[i] != NULL)
2029                                 dt_object_put(env, stripe[i]);
2030                 OBD_FREE(stripe, sizeof(stripe[0]) * stripe_count);
2031                 lo->ldo_dir_stripe_count = 0;
2032                 lo->ldo_dir_stripes_allocated = 0;
2033                 lo->ldo_stripe = NULL;
2034         }
2035
2036 out_free:
2037         OBD_FREE(idx_array, sizeof(idx_array[0]) * stripe_count);
2038
2039         RETURN(rc);
2040 }
2041
2042 /**
2043  * Declare create striped md object.
2044  *
2045  * The function declares intention to create a striped directory. This is a
2046  * wrapper for lod_prep_md_striped_create(). The only additional functionality
2047  * is to verify pattern \a lum_buf is good. Check that function for the details.
2048  *
2049  * \param[in] env       execution environment
2050  * \param[in] dt        object
2051  * \param[in] attr      attributes to initialize the objects with
2052  * \param[in] lum_buf   a pattern specifying the number of stripes and
2053  *                      MDT to start from
2054  * \param[in] dof       type of objects to be created
2055  * \param[in] th        transaction handle
2056  *
2057  * \retval              0 on success
2058  * \retval              negative if failed
2059  *
2060  */
2061 static int lod_declare_xattr_set_lmv(const struct lu_env *env,
2062                                      struct dt_object *dt,
2063                                      struct lu_attr *attr,
2064                                      const struct lu_buf *lum_buf,
2065                                      struct dt_object_format *dof,
2066                                      struct thandle *th)
2067 {
2068         struct lod_object       *lo = lod_dt_obj(dt);
2069         struct lmv_user_md_v1   *lum = lum_buf->lb_buf;
2070         int                     rc;
2071         ENTRY;
2072
2073         LASSERT(lum != NULL);
2074
2075         CDEBUG(D_INFO, "lum magic = %x count = %u offset = %d\n",
2076                le32_to_cpu(lum->lum_magic), le32_to_cpu(lum->lum_stripe_count),
2077                (int)le32_to_cpu(lum->lum_stripe_offset));
2078
2079         if (lo->ldo_dir_stripe_count == 0)
2080                 GOTO(out, rc = 0);
2081
2082         /* prepare dir striped objects */
2083         rc = lod_prep_md_striped_create(env, dt, attr, lum, dof, th);
2084         if (rc != 0) {
2085                 /* failed to create striping, let's reset
2086                  * config so that others don't get confused */
2087                 lod_striping_free(env, lo);
2088                 GOTO(out, rc);
2089         }
2090 out:
2091         RETURN(rc);
2092 }
2093
2094 /**
2095  * Implementation of dt_object_operations::do_declare_xattr_set.
2096  *
2097  * Used with regular (non-striped) objects. Basically it
2098  * initializes the striping information and applies the
2099  * change to all the stripes.
2100  *
2101  * \see dt_object_operations::do_declare_xattr_set() in the API description
2102  * for details.
2103  */
2104 static int lod_dir_declare_xattr_set(const struct lu_env *env,
2105                                      struct dt_object *dt,
2106                                      const struct lu_buf *buf,
2107                                      const char *name, int fl,
2108                                      struct thandle *th)
2109 {
2110         struct dt_object        *next = dt_object_child(dt);
2111         struct lod_device       *d = lu2lod_dev(dt->do_lu.lo_dev);
2112         struct lod_object       *lo = lod_dt_obj(dt);
2113         int                     i;
2114         int                     rc;
2115         ENTRY;
2116
2117         if (strcmp(name, XATTR_NAME_DEFAULT_LMV) == 0) {
2118                 struct lmv_user_md_v1 *lum;
2119
2120                 LASSERT(buf != NULL && buf->lb_buf != NULL);
2121                 lum = buf->lb_buf;
2122                 rc = lod_verify_md_striping(d, lum);
2123                 if (rc != 0)
2124                         RETURN(rc);
2125         } else if (strcmp(name, XATTR_NAME_LOV) == 0) {
2126                 rc = lod_verify_striping(d, lo, buf, false);
2127                 if (rc != 0)
2128                         RETURN(rc);
2129         }
2130
2131         rc = lod_sub_declare_xattr_set(env, next, buf, name, fl, th);
2132         if (rc != 0)
2133                 RETURN(rc);
2134
2135         /* Note: Do not set LinkEA on sub-stripes, otherwise
2136          * it will confuse the fid2path process(see mdt_path_current()).
2137          * The linkEA between master and sub-stripes is set in
2138          * lod_xattr_set_lmv(). */
2139         if (strcmp(name, XATTR_NAME_LINK) == 0)
2140                 RETURN(0);
2141
2142         /* set xattr to each stripes, if needed */
2143         rc = lod_striping_load(env, lo);
2144         if (rc != 0)
2145                 RETURN(rc);
2146
2147         if (lo->ldo_dir_stripe_count == 0)
2148                 RETURN(0);
2149
2150         for (i = 0; i < lo->ldo_dir_stripe_count; i++) {
2151                 LASSERT(lo->ldo_stripe[i]);
2152
2153                 rc = lod_sub_declare_xattr_set(env, lo->ldo_stripe[i],
2154                                                buf, name, fl, th);
2155                 if (rc != 0)
2156                         break;
2157         }
2158
2159         RETURN(rc);
2160 }
2161
2162 static int
2163 lod_obj_stripe_replace_parent_fid_cb(const struct lu_env *env,
2164                                      struct lod_object *lo,
2165                                      struct dt_object *dt, struct thandle *th,
2166                                      int comp_idx, int stripe_idx,
2167                                      struct lod_obj_stripe_cb_data *data)
2168 {
2169         struct lod_thread_info *info = lod_env_info(env);
2170         struct lod_layout_component *comp = &lo->ldo_comp_entries[comp_idx];
2171         struct filter_fid *ff = &info->lti_ff;
2172         struct lu_buf *buf = &info->lti_buf;
2173         int rc;
2174
2175         buf->lb_buf = ff;
2176         buf->lb_len = sizeof(*ff);
2177         rc = dt_xattr_get(env, dt, buf, XATTR_NAME_FID);
2178         if (rc < 0) {
2179                 if (rc == -ENODATA)
2180                         return 0;
2181                 return rc;
2182         }
2183
2184         filter_fid_le_to_cpu(ff, ff, sizeof(*ff));
2185         if (lu_fid_eq(lu_object_fid(&lo->ldo_obj.do_lu), &ff->ff_parent) &&
2186             ff->ff_layout.ol_comp_id == comp->llc_id)
2187                 return 0;
2188
2189         /* rewrite filter_fid */
2190         memset(ff, 0, sizeof(*ff));
2191         ff->ff_parent = *lu_object_fid(&lo->ldo_obj.do_lu);
2192         ff->ff_parent.f_ver = stripe_idx;
2193         ff->ff_layout.ol_stripe_size = comp->llc_stripe_size;
2194         ff->ff_layout.ol_stripe_count = comp->llc_stripe_count;
2195         ff->ff_layout.ol_comp_id = comp->llc_id;
2196         ff->ff_layout.ol_comp_start = comp->llc_extent.e_start;
2197         ff->ff_layout.ol_comp_end = comp->llc_extent.e_end;
2198         filter_fid_cpu_to_le(ff, ff, sizeof(*ff));
2199
2200         if (data->locd_declare)
2201                 rc = lod_sub_declare_xattr_set(env, dt, buf, XATTR_NAME_FID,
2202                                                LU_XATTR_REPLACE, th);
2203         else
2204                 rc = lod_sub_xattr_set(env, dt, buf, XATTR_NAME_FID,
2205                                        LU_XATTR_REPLACE, th);
2206
2207         return rc;
2208 }
2209
2210 /**
2211  * Reset parent FID on OST object
2212  *
2213  * Replace parent FID with @dt object FID, which is only called during migration
2214  * to reset the parent FID after the MDT object is migrated to the new MDT, i.e.
2215  * the FID is changed.
2216  *
2217  * \param[in] env execution environment
2218  * \param[in] dt dt_object whose stripes's parent FID will be reset
2219  * \parem[in] th thandle
2220  * \param[in] declare if it is declare
2221  *
2222  * \retval      0 if reset succeeds
2223  * \retval      negative errno if reset fails
2224  */
2225 static int lod_replace_parent_fid(const struct lu_env *env,
2226                                   struct dt_object *dt,
2227                                   struct thandle *th, bool declare)
2228 {
2229         struct lod_object *lo = lod_dt_obj(dt);
2230         struct lod_thread_info  *info = lod_env_info(env);
2231         struct lu_buf *buf = &info->lti_buf;
2232         struct filter_fid *ff;
2233         struct lod_obj_stripe_cb_data data = { { 0 } };
2234         int rc;
2235         ENTRY;
2236
2237         LASSERT(S_ISREG(dt->do_lu.lo_header->loh_attr));
2238
2239         /* set xattr to each stripes, if needed */
2240         rc = lod_striping_load(env, lo);
2241         if (rc != 0)
2242                 RETURN(rc);
2243
2244         if (!lod_obj_is_striped(dt))
2245                 RETURN(0);
2246
2247         if (info->lti_ea_store_size < sizeof(*ff)) {
2248                 rc = lod_ea_store_resize(info, sizeof(*ff));
2249                 if (rc != 0)
2250                         RETURN(rc);
2251         }
2252
2253         buf->lb_buf = info->lti_ea_store;
2254         buf->lb_len = info->lti_ea_store_size;
2255
2256         data.locd_declare = declare;
2257         data.locd_stripe_cb = lod_obj_stripe_replace_parent_fid_cb;
2258         rc = lod_obj_for_each_stripe(env, lo, th, &data);
2259
2260         RETURN(rc);
2261 }
2262
2263 inline __u16 lod_comp_entry_stripe_count(struct lod_object *lo,
2264                                          struct lod_layout_component *entry,
2265                                          bool is_dir)
2266 {
2267         struct lod_device *lod = lu2lod_dev(lod2lu_obj(lo)->lo_dev);
2268
2269         if (is_dir)
2270                 return  0;
2271         else if (lod_comp_inited(entry))
2272                 return entry->llc_stripe_count;
2273         else if ((__u16)-1 == entry->llc_stripe_count)
2274                 return lod->lod_desc.ld_tgt_count;
2275         else
2276                 return lod_get_stripe_count(lod, lo, entry->llc_stripe_count);
2277 }
2278
2279 static int lod_comp_md_size(struct lod_object *lo, bool is_dir)
2280 {
2281         int magic, size = 0, i;
2282         struct lod_layout_component *comp_entries;
2283         __u16 comp_cnt;
2284         bool is_composite;
2285
2286         if (is_dir) {
2287                 comp_cnt = lo->ldo_def_striping->lds_def_comp_cnt;
2288                 comp_entries = lo->ldo_def_striping->lds_def_comp_entries;
2289                 is_composite =
2290                         lo->ldo_def_striping->lds_def_striping_is_composite;
2291         } else {
2292                 comp_cnt = lo->ldo_comp_cnt;
2293                 comp_entries = lo->ldo_comp_entries;
2294                 is_composite = lo->ldo_is_composite;
2295         }
2296
2297
2298         LASSERT(comp_cnt != 0 && comp_entries != NULL);
2299         if (is_composite) {
2300                 size = sizeof(struct lov_comp_md_v1) +
2301                        sizeof(struct lov_comp_md_entry_v1) * comp_cnt;
2302                 LASSERT(size % sizeof(__u64) == 0);
2303         }
2304
2305         for (i = 0; i < comp_cnt; i++) {
2306                 __u16 stripe_count;
2307
2308                 magic = comp_entries[i].llc_pool ? LOV_MAGIC_V3 : LOV_MAGIC_V1;
2309                 stripe_count = lod_comp_entry_stripe_count(lo, &comp_entries[i],
2310                                                            is_dir);
2311                 if (!is_dir && is_composite)
2312                         lod_comp_shrink_stripe_count(&comp_entries[i],
2313                                                      &stripe_count);
2314
2315                 size += lov_user_md_size(stripe_count, magic);
2316                 LASSERT(size % sizeof(__u64) == 0);
2317         }
2318         return size;
2319 }
2320
2321 /**
2322  * Declare component add. The xattr name is XATTR_LUSTRE_LOV.add, and
2323  * the xattr value is binary lov_comp_md_v1 which contains component(s)
2324  * to be added.
2325   *
2326  * \param[in] env       execution environment
2327  * \param[in] dt        dt_object to add components on
2328  * \param[in] buf       buffer contains components to be added
2329  * \parem[in] th        thandle
2330  *
2331  * \retval      0 on success
2332  * \retval      negative errno on failure
2333  */
2334 static int lod_declare_layout_add(const struct lu_env *env,
2335                                   struct dt_object *dt,
2336                                   const struct lu_buf *buf,
2337                                   struct thandle *th)
2338 {
2339         struct lod_thread_info  *info = lod_env_info(env);
2340         struct lod_layout_component *comp_array, *lod_comp, *old_array;
2341         struct lod_device       *d = lu2lod_dev(dt->do_lu.lo_dev);
2342         struct dt_object *next = dt_object_child(dt);
2343         struct lov_desc         *desc = &d->lod_desc;
2344         struct lod_object       *lo = lod_dt_obj(dt);
2345         struct lov_user_md_v3   *v3;
2346         struct lov_comp_md_v1   *comp_v1 = buf->lb_buf;
2347         __u32   magic;
2348         int     i, rc, array_cnt, old_array_cnt;
2349         ENTRY;
2350
2351         LASSERT(lo->ldo_is_composite);
2352
2353         if (lo->ldo_flr_state != LCM_FL_NONE)
2354                 RETURN(-EBUSY);
2355
2356         rc = lod_verify_striping(d, lo, buf, false);
2357         if (rc != 0)
2358                 RETURN(rc);
2359
2360         magic = comp_v1->lcm_magic;
2361         if (magic == __swab32(LOV_USER_MAGIC_COMP_V1)) {
2362                 lustre_swab_lov_comp_md_v1(comp_v1);
2363                 magic = comp_v1->lcm_magic;
2364         }
2365
2366         if (magic != LOV_USER_MAGIC_COMP_V1)
2367                 RETURN(-EINVAL);
2368
2369         array_cnt = lo->ldo_comp_cnt + comp_v1->lcm_entry_count;
2370         OBD_ALLOC(comp_array, sizeof(*comp_array) * array_cnt);
2371         if (comp_array == NULL)
2372                 RETURN(-ENOMEM);
2373
2374         memcpy(comp_array, lo->ldo_comp_entries,
2375                sizeof(*comp_array) * lo->ldo_comp_cnt);
2376
2377         for (i = 0; i < comp_v1->lcm_entry_count; i++) {
2378                 struct lov_user_md_v1 *v1;
2379                 struct lu_extent *ext;
2380
2381                 v1 = (struct lov_user_md *)((char *)comp_v1 +
2382                                 comp_v1->lcm_entries[i].lcme_offset);
2383                 ext = &comp_v1->lcm_entries[i].lcme_extent;
2384
2385                 lod_comp = &comp_array[lo->ldo_comp_cnt + i];
2386                 lod_comp->llc_extent.e_start = ext->e_start;
2387                 lod_comp->llc_extent.e_end = ext->e_end;
2388                 lod_comp->llc_stripe_offset = v1->lmm_stripe_offset;
2389                 lod_comp->llc_flags = comp_v1->lcm_entries[i].lcme_flags;
2390
2391                 lod_comp->llc_stripe_count = v1->lmm_stripe_count;
2392                 lod_comp->llc_stripe_size = v1->lmm_stripe_size;
2393                 lod_adjust_stripe_info(lod_comp, desc);
2394
2395                 if (v1->lmm_magic == LOV_USER_MAGIC_V3) {
2396                         v3 = (struct lov_user_md_v3 *) v1;
2397                         if (v3->lmm_pool_name[0] != '\0') {
2398                                 rc = lod_set_pool(&lod_comp->llc_pool,
2399                                                   v3->lmm_pool_name);
2400                                 if (rc)
2401                                         GOTO(error, rc);
2402                         }
2403                 }
2404         }
2405
2406         old_array = lo->ldo_comp_entries;
2407         old_array_cnt = lo->ldo_comp_cnt;
2408
2409         lo->ldo_comp_entries = comp_array;
2410         lo->ldo_comp_cnt = array_cnt;
2411
2412         /* No need to increase layout generation here, it will be increased
2413          * later when generating component ID for the new components */
2414
2415         info->lti_buf.lb_len = lod_comp_md_size(lo, false);
2416         rc = lod_sub_declare_xattr_set(env, next, &info->lti_buf,
2417                                               XATTR_NAME_LOV, 0, th);
2418         if (rc) {
2419                 lo->ldo_comp_entries = old_array;
2420                 lo->ldo_comp_cnt = old_array_cnt;
2421                 GOTO(error, rc);
2422         }
2423
2424         OBD_FREE(old_array, sizeof(*lod_comp) * old_array_cnt);
2425
2426         LASSERT(lo->ldo_mirror_count == 1);
2427         lo->ldo_mirrors[0].lme_end = array_cnt - 1;
2428
2429         RETURN(0);
2430
2431 error:
2432         for (i = lo->ldo_comp_cnt; i < array_cnt; i++) {
2433                 lod_comp = &comp_array[i];
2434                 if (lod_comp->llc_pool != NULL) {
2435                         OBD_FREE(lod_comp->llc_pool,
2436                                  strlen(lod_comp->llc_pool) + 1);
2437                         lod_comp->llc_pool = NULL;
2438                 }
2439         }
2440         OBD_FREE(comp_array, sizeof(*comp_array) * array_cnt);
2441         RETURN(rc);
2442 }
2443
2444 /**
2445  * Declare component set. The xattr is name XATTR_LUSTRE_LOV.set.$field,
2446  * the '$field' can only be 'flags' now. The xattr value is binary
2447  * lov_comp_md_v1 which contains the component ID(s) and the value of
2448  * the field to be modified.
2449  *
2450  * \param[in] env       execution environment
2451  * \param[in] dt        dt_object to be modified
2452  * \param[in] op        operation string, like "set.flags"
2453  * \param[in] buf       buffer contains components to be set
2454  * \parem[in] th        thandle
2455  *
2456  * \retval      0 on success
2457  * \retval      negative errno on failure
2458  */
2459 static int lod_declare_layout_set(const struct lu_env *env,
2460                                   struct dt_object *dt,
2461                                   char *op, const struct lu_buf *buf,
2462                                   struct thandle *th)
2463 {
2464         struct lod_layout_component     *lod_comp;
2465         struct lod_thread_info  *info = lod_env_info(env);
2466         struct lod_device       *d = lu2lod_dev(dt->do_lu.lo_dev);
2467         struct lod_object       *lo = lod_dt_obj(dt);
2468         struct lov_comp_md_v1   *comp_v1 = buf->lb_buf;
2469         __u32   magic;
2470         int     i, j, rc;
2471         bool    changed = false;
2472         ENTRY;
2473
2474         if (strcmp(op, "set.flags") != 0) {
2475                 CDEBUG(D_LAYOUT, "%s: operation (%s) not supported.\n",
2476                        lod2obd(d)->obd_name, op);
2477                 RETURN(-ENOTSUPP);
2478         }
2479
2480         magic = comp_v1->lcm_magic;
2481         if (magic == __swab32(LOV_USER_MAGIC_COMP_V1)) {
2482                 lustre_swab_lov_comp_md_v1(comp_v1);
2483                 magic = comp_v1->lcm_magic;
2484         }
2485
2486         if (magic != LOV_USER_MAGIC_COMP_V1)
2487                 RETURN(-EINVAL);
2488
2489         if (comp_v1->lcm_entry_count == 0) {
2490                 CDEBUG(D_LAYOUT, "%s: entry count is zero.\n",
2491                        lod2obd(d)->obd_name);
2492                 RETURN(-EINVAL);
2493         }
2494
2495         for (i = 0; i < comp_v1->lcm_entry_count; i++) {
2496                 __u32 id = comp_v1->lcm_entries[i].lcme_id;
2497                 __u32 flags = comp_v1->lcm_entries[i].lcme_flags;
2498
2499                 if (flags & LCME_FL_INIT) {
2500                         if (changed)
2501                                 lod_striping_free(env, lo);
2502                         RETURN(-EINVAL);
2503                 }
2504
2505                 for (j = 0; j < lo->ldo_comp_cnt; j++) {
2506                         lod_comp = &lo->ldo_comp_entries[j];
2507                         if (id != lod_comp->llc_id)
2508                                 continue;
2509
2510                         if (flags & LCME_FL_NEG) {
2511                                 flags &= ~LCME_FL_NEG;
2512                                 lod_comp->llc_flags &= ~flags;
2513                         } else {
2514                                 lod_comp->llc_flags |= flags;
2515                         }
2516                         changed = true;
2517                 }
2518         }
2519
2520         if (!changed) {
2521                 CDEBUG(D_LAYOUT, "%s: requested component(s) not found.\n",
2522                        lod2obd(d)->obd_name);
2523                 RETURN(-EINVAL);
2524         }
2525
2526         lod_obj_inc_layout_gen(lo);
2527
2528         info->lti_buf.lb_len = lod_comp_md_size(lo, false);
2529         rc = lod_sub_declare_xattr_set(env, dt_object_child(dt), &info->lti_buf,
2530                                        XATTR_NAME_LOV, LU_XATTR_REPLACE, th);
2531         RETURN(rc);
2532 }
2533
2534 /**
2535  * Declare component deletion. The xattr name is XATTR_LUSTRE_LOV.del,
2536  * and the xattr value is a unique component ID or a special lcme_id.
2537  *
2538  * \param[in] env       execution environment
2539  * \param[in] dt        dt_object to be operated on
2540  * \param[in] buf       buffer contains component ID or lcme_id
2541  * \parem[in] th        thandle
2542  *
2543  * \retval      0 on success
2544  * \retval      negative errno on failure
2545  */
2546 static int lod_declare_layout_del(const struct lu_env *env,
2547                                   struct dt_object *dt,
2548                                   const struct lu_buf *buf,
2549                                   struct thandle *th)
2550 {
2551         struct lod_thread_info  *info = lod_env_info(env);
2552         struct dt_object *next = dt_object_child(dt);
2553         struct lod_device *d = lu2lod_dev(dt->do_lu.lo_dev);
2554         struct lod_object *lo = lod_dt_obj(dt);
2555         struct lu_attr *attr = &lod_env_info(env)->lti_attr;
2556         struct lov_comp_md_v1 *comp_v1 = buf->lb_buf;
2557         __u32 magic, id, flags, neg_flags = 0;
2558         int rc, i, j, left;
2559         ENTRY;
2560
2561         LASSERT(lo->ldo_is_composite);
2562
2563         if (lo->ldo_flr_state != LCM_FL_NONE)
2564                 RETURN(-EBUSY);
2565
2566         magic = comp_v1->lcm_magic;
2567         if (magic == __swab32(LOV_USER_MAGIC_COMP_V1)) {
2568                 lustre_swab_lov_comp_md_v1(comp_v1);
2569                 magic = comp_v1->lcm_magic;
2570         }
2571
2572         if (magic != LOV_USER_MAGIC_COMP_V1)
2573                 RETURN(-EINVAL);
2574
2575         id = comp_v1->lcm_entries[0].lcme_id;
2576         flags = comp_v1->lcm_entries[0].lcme_flags;
2577
2578         if (id > LCME_ID_MAX || (flags & ~LCME_KNOWN_FLAGS)) {
2579                 CDEBUG(D_LAYOUT, "%s: invalid component id %#x, flags %#x\n",
2580                        lod2obd(d)->obd_name, id, flags);
2581                 RETURN(-EINVAL);
2582         }
2583
2584         if (id != LCME_ID_INVAL && flags != 0) {
2585                 CDEBUG(D_LAYOUT, "%s: specified both id and flags.\n",
2586                        lod2obd(d)->obd_name);
2587                 RETURN(-EINVAL);
2588         }
2589
2590         if (id == LCME_ID_INVAL && !flags) {
2591                 CDEBUG(D_LAYOUT, "%s: no id or flags specified.\n",
2592                        lod2obd(d)->obd_name);
2593                 RETURN(-EINVAL);
2594         }
2595
2596         if (flags & LCME_FL_NEG) {
2597                 neg_flags = flags & ~LCME_FL_NEG;
2598                 flags = 0;
2599         }
2600
2601         left = lo->ldo_comp_cnt;
2602         if (left <= 0)
2603                 RETURN(-EINVAL);
2604
2605         for (i = (lo->ldo_comp_cnt - 1); i >= 0; i--) {
2606                 struct lod_layout_component *lod_comp;
2607
2608                 lod_comp = &lo->ldo_comp_entries[i];
2609
2610                 if (id != LCME_ID_INVAL && id != lod_comp->llc_id)
2611                         continue;
2612                 else if (flags && !(flags & lod_comp->llc_flags))
2613                         continue;
2614                 else if (neg_flags && (neg_flags & lod_comp->llc_flags))
2615                         continue;
2616
2617                 if (left != (i + 1)) {
2618                         CDEBUG(D_LAYOUT, "%s: this deletion will create "
2619                                "a hole.\n", lod2obd(d)->obd_name);
2620                         RETURN(-EINVAL);
2621                 }
2622                 left--;
2623
2624                 /* Mark the component as deleted */
2625                 lod_comp->llc_id = LCME_ID_INVAL;
2626
2627                 /* Not instantiated component */
2628                 if (lod_comp->llc_stripe == NULL)
2629                         continue;
2630
2631                 LASSERT(lod_comp->llc_stripe_count > 0);
2632                 for (j = 0; j < lod_comp->llc_stripe_count; j++) {
2633                         struct dt_object *obj = lod_comp->llc_stripe[j];
2634
2635                         if (obj == NULL)
2636                                 continue;
2637                         rc = lod_sub_declare_destroy(env, obj, th);
2638                         if (rc)
2639                                 RETURN(rc);
2640                 }
2641         }
2642
2643         LASSERTF(left >= 0, "left = %d\n", left);
2644         if (left == lo->ldo_comp_cnt) {
2645                 CDEBUG(D_LAYOUT, "%s: requested component id:%#x not found\n",
2646                        lod2obd(d)->obd_name, id);
2647                 RETURN(-EINVAL);
2648         }
2649
2650         memset(attr, 0, sizeof(*attr));
2651         attr->la_valid = LA_SIZE;
2652         rc = lod_sub_declare_attr_set(env, next, attr, th);
2653         if (rc)
2654                 RETURN(rc);
2655
2656         if (left > 0) {
2657                 info->lti_buf.lb_len = lod_comp_md_size(lo, false);
2658                 rc = lod_sub_declare_xattr_set(env, next, &info->lti_buf,
2659                                                XATTR_NAME_LOV, 0, th);
2660         } else {
2661                 rc = lod_sub_declare_xattr_del(env, next, XATTR_NAME_LOV, th);
2662         }
2663
2664         RETURN(rc);
2665 }
2666
2667 /**
2668  * Declare layout add/set/del operations issued by special xattr names:
2669  *
2670  * XATTR_LUSTRE_LOV.add         add component(s) to existing file
2671  * XATTR_LUSTRE_LOV.del         delete component(s) from existing file
2672  * XATTR_LUSTRE_LOV.set.$field  set specified field of certain component(s)
2673  *
2674  * \param[in] env       execution environment
2675  * \param[in] dt        object
2676  * \param[in] name      name of xattr
2677  * \param[in] buf       lu_buf contains xattr value
2678  * \param[in] th        transaction handle
2679  *
2680  * \retval              0 on success
2681  * \retval              negative if failed
2682  */
2683 static int lod_declare_modify_layout(const struct lu_env *env,
2684                                      struct dt_object *dt,
2685                                      const char *name,
2686                                      const struct lu_buf *buf,
2687                                      struct thandle *th)
2688 {
2689         struct lod_device *d = lu2lod_dev(dt->do_lu.lo_dev);
2690         struct lod_object *lo = lod_dt_obj(dt);
2691         char *op;
2692         int rc, len = strlen(XATTR_LUSTRE_LOV);
2693         ENTRY;
2694
2695         LASSERT(dt_object_exists(dt));
2696
2697         if (strlen(name) <= len || name[len] != '.') {
2698                 CDEBUG(D_LAYOUT, "%s: invalid xattr name: %s\n",
2699                        lod2obd(d)->obd_name, name);
2700                 RETURN(-EINVAL);
2701         }
2702         len++;
2703
2704         rc = lod_striping_load(env, lo);
2705         if (rc)
2706                 GOTO(unlock, rc);
2707
2708         /* the layout to be modified must be a composite layout */
2709         if (!lo->ldo_is_composite) {
2710                 CDEBUG(D_LAYOUT, "%s: object "DFID" isn't a composite file.\n",
2711                        lod2obd(d)->obd_name, PFID(lu_object_fid(&dt->do_lu)));
2712                 GOTO(unlock, rc = -EINVAL);
2713         }
2714
2715         op = (char *)name + len;
2716         if (strcmp(op, "add") == 0) {
2717                 rc = lod_declare_layout_add(env, dt, buf, th);
2718         } else if (strcmp(op, "del") == 0) {
2719                 rc = lod_declare_layout_del(env, dt, buf, th);
2720         } else if (strncmp(op, "set", strlen("set")) == 0) {
2721                 rc = lod_declare_layout_set(env, dt, op, buf, th);
2722         } else  {
2723                 CDEBUG(D_LAYOUT, "%s: unsupported xattr name:%s\n",
2724                        lod2obd(d)->obd_name, name);
2725                 GOTO(unlock, rc = -ENOTSUPP);
2726         }
2727 unlock:
2728         if (rc)
2729                 lod_striping_free(env, lo);
2730
2731         RETURN(rc);
2732 }
2733
2734 /**
2735  * Convert a plain file lov_mds_md to a composite layout.
2736  *
2737  * \param[in,out] info  the thread info::lti_ea_store buffer contains little
2738  *                      endian plain file layout
2739  *
2740  * \retval              0 on success, <0 on failure
2741  */
2742 static int lod_layout_convert(struct lod_thread_info *info)
2743 {
2744         struct lov_mds_md *lmm = info->lti_ea_store;
2745         struct lov_mds_md *lmm_save;
2746         struct lov_comp_md_v1 *lcm;
2747         struct lov_comp_md_entry_v1 *lcme;
2748         size_t size;
2749         __u32 blob_size;
2750         int rc = 0;
2751         ENTRY;
2752
2753         /* realloc buffer to a composite layout which contains one component */
2754         blob_size = lov_mds_md_size(le16_to_cpu(lmm->lmm_stripe_count),
2755                                     le32_to_cpu(lmm->lmm_magic));
2756         size = sizeof(*lcm) + sizeof(*lcme) + blob_size;
2757
2758         OBD_ALLOC_LARGE(lmm_save, blob_size);
2759         if (!lmm_save)
2760                 GOTO(out, rc = -ENOMEM);
2761
2762         memcpy(lmm_save, lmm, blob_size);
2763
2764         if (info->lti_ea_store_size < size) {
2765                 rc = lod_ea_store_resize(info, size);
2766                 if (rc)
2767                         GOTO(out, rc);
2768         }
2769
2770         lcm = info->lti_ea_store;
2771         lcm->lcm_magic = cpu_to_le32(LOV_MAGIC_COMP_V1);
2772         lcm->lcm_size = cpu_to_le32(size);
2773         lcm->lcm_layout_gen = cpu_to_le32(le16_to_cpu(
2774                                                 lmm_save->lmm_layout_gen));
2775         lcm->lcm_flags = cpu_to_le16(LCM_FL_NONE);
2776         lcm->lcm_entry_count = cpu_to_le16(1);
2777         lcm->lcm_mirror_count = 0;
2778
2779         lcme = &lcm->lcm_entries[0];
2780         lcme->lcme_flags = cpu_to_le32(LCME_FL_INIT);
2781         lcme->lcme_extent.e_start = 0;
2782         lcme->lcme_extent.e_end = cpu_to_le64(OBD_OBJECT_EOF);
2783         lcme->lcme_offset = cpu_to_le32(sizeof(*lcm) + sizeof(*lcme));
2784         lcme->lcme_size = cpu_to_le32(blob_size);
2785
2786         memcpy((char *)lcm + lcme->lcme_offset, (char *)lmm_save, blob_size);
2787
2788         EXIT;
2789 out:
2790         if (lmm_save)
2791                 OBD_FREE_LARGE(lmm_save, blob_size);
2792         return rc;
2793 }
2794
2795 /**
2796  * Merge layouts to form a mirrored file.
2797  */
2798 static int lod_declare_layout_merge(const struct lu_env *env,
2799                 struct dt_object *dt, const struct lu_buf *mbuf,
2800                 struct thandle *th)
2801 {
2802         struct lod_thread_info  *info = lod_env_info(env);
2803         struct lu_buf           *buf = &info->lti_buf;
2804         struct lod_object       *lo = lod_dt_obj(dt);
2805         struct lov_comp_md_v1   *lcm;
2806         struct lov_comp_md_v1   *cur_lcm;
2807         struct lov_comp_md_v1   *merge_lcm;
2808         struct lov_comp_md_entry_v1     *lcme;
2809         size_t size = 0;
2810         size_t offset;
2811         __u16 cur_entry_count;
2812         __u16 merge_entry_count;
2813         __u32 id = 0;
2814         __u16 mirror_id = 0;
2815         __u32 mirror_count;
2816         int     rc, i;
2817         ENTRY;
2818
2819         merge_lcm = mbuf->lb_buf;
2820         if (mbuf->lb_len < sizeof(*merge_lcm))
2821                 RETURN(-EINVAL);
2822
2823         /* must be an existing layout from disk */
2824         if (le32_to_cpu(merge_lcm->lcm_magic) != LOV_MAGIC_COMP_V1)
2825                 RETURN(-EINVAL);
2826
2827         merge_entry_count = le16_to_cpu(merge_lcm->lcm_entry_count);
2828
2829         /* do not allow to merge two mirrored files */
2830         if (le16_to_cpu(merge_lcm->lcm_mirror_count))
2831                 RETURN(-EBUSY);
2832
2833         /* verify the target buffer */
2834         rc = lod_get_lov_ea(env, lo);
2835         if (rc <= 0)
2836                 RETURN(rc ? : -ENODATA);
2837
2838         cur_lcm = info->lti_ea_store;
2839         switch (le32_to_cpu(cur_lcm->lcm_magic)) {
2840         case LOV_MAGIC_V1:
2841         case LOV_MAGIC_V3:
2842                 rc = lod_layout_convert(info);
2843                 break;
2844         case LOV_MAGIC_COMP_V1:
2845                 rc = 0;
2846                 break;
2847         default:
2848                 rc = -EINVAL;
2849         }
2850         if (rc)
2851                 RETURN(rc);
2852
2853         /* info->lti_ea_store could be reallocated in lod_layout_convert() */
2854         cur_lcm = info->lti_ea_store;
2855         cur_entry_count = le16_to_cpu(cur_lcm->lcm_entry_count);
2856
2857         /* 'lcm_mirror_count + 1' is the current # of mirrors the file has */
2858         mirror_count = le16_to_cpu(cur_lcm->lcm_mirror_count) + 1;
2859         if (mirror_count + 1 > LUSTRE_MIRROR_COUNT_MAX)
2860                 RETURN(-ERANGE);
2861
2862         /* size of new layout */
2863         size = le32_to_cpu(cur_lcm->lcm_size) +
2864                le32_to_cpu(merge_lcm->lcm_size) - sizeof(*cur_lcm);
2865
2866         memset(buf, 0, sizeof(*buf));
2867         lu_buf_alloc(buf, size);
2868         if (buf->lb_buf == NULL)
2869                 RETURN(-ENOMEM);
2870
2871         lcm = buf->lb_buf;
2872         memcpy(lcm, cur_lcm, sizeof(*lcm) + cur_entry_count * sizeof(*lcme));
2873
2874         offset = sizeof(*lcm) +
2875                  sizeof(*lcme) * (cur_entry_count + merge_entry_count);
2876         for (i = 0; i < cur_entry_count; i++) {
2877                 struct lov_comp_md_entry_v1 *cur_lcme;
2878
2879                 lcme = &lcm->lcm_entries[i];
2880                 cur_lcme = &cur_lcm->lcm_entries[i];
2881
2882                 lcme->lcme_offset = cpu_to_le32(offset);
2883                 memcpy((char *)lcm + offset,
2884                        (char *)cur_lcm + le32_to_cpu(cur_lcme->lcme_offset),
2885                        le32_to_cpu(lcme->lcme_size));
2886
2887                 offset += le32_to_cpu(lcme->lcme_size);
2888
2889                 if (mirror_count == 1) {
2890                         /* new mirrored file, create new mirror ID */
2891                         id = pflr_id(1, i + 1);
2892                         lcme->lcme_id = cpu_to_le32(id);
2893                 }
2894
2895                 id = MAX(le32_to_cpu(lcme->lcme_id), id);
2896         }
2897
2898         mirror_id = mirror_id_of(id) + 1;
2899         for (i = 0; i < merge_entry_count; i++) {
2900                 struct lov_comp_md_entry_v1 *merge_lcme;
2901
2902                 merge_lcme = &merge_lcm->lcm_entries[i];
2903                 lcme = &lcm->lcm_entries[cur_entry_count + i];
2904
2905                 *lcme = *merge_lcme;
2906                 lcme->lcme_offset = cpu_to_le32(offset);
2907
2908                 id = pflr_id(mirror_id, i + 1);
2909                 lcme->lcme_id = cpu_to_le32(id);
2910
2911                 memcpy((char *)lcm + offset,
2912                        (char *)merge_lcm + le32_to_cpu(merge_lcme->lcme_offset),
2913                        le32_to_cpu(lcme->lcme_size));
2914
2915                 offset += le32_to_cpu(lcme->lcme_size);
2916         }
2917
2918         /* fixup layout information */
2919         lod_obj_inc_layout_gen(lo);
2920         lcm->lcm_layout_gen = cpu_to_le32(lo->ldo_layout_gen);
2921         lcm->lcm_size = cpu_to_le32(size);
2922         lcm->lcm_entry_count = cpu_to_le16(cur_entry_count + merge_entry_count);
2923         lcm->lcm_mirror_count = cpu_to_le16(mirror_count);
2924         if ((le16_to_cpu(lcm->lcm_flags) & LCM_FL_FLR_MASK) == LCM_FL_NONE)
2925                 lcm->lcm_flags = cpu_to_le32(LCM_FL_RDONLY);
2926
2927         rc = lod_striping_reload(env, lo, buf);
2928         if (rc)
2929                 GOTO(out, rc);
2930
2931         rc = lod_sub_declare_xattr_set(env, dt_object_child(dt), buf,
2932                                         XATTR_NAME_LOV, LU_XATTR_REPLACE, th);
2933
2934 out:
2935         lu_buf_free(buf);
2936         RETURN(rc);
2937 }
2938
2939 /**
2940  * Split layouts, just set the LOVEA with the layout from mbuf.
2941  */
2942 static int lod_declare_layout_split(const struct lu_env *env,
2943                 struct dt_object *dt, const struct lu_buf *mbuf,
2944                 struct thandle *th)
2945 {
2946         struct lod_object *lo = lod_dt_obj(dt);
2947         struct lov_comp_md_v1 *lcm = mbuf->lb_buf;
2948         int rc;
2949         ENTRY;
2950
2951         lod_obj_inc_layout_gen(lo);
2952         lcm->lcm_layout_gen = cpu_to_le32(lo->ldo_layout_gen);
2953
2954         rc = lod_striping_reload(env, lo, mbuf);
2955         if (rc)
2956                 RETURN(rc);
2957
2958         rc = lod_sub_declare_xattr_set(env, dt_object_child(dt), mbuf,
2959                                        XATTR_NAME_LOV, LU_XATTR_REPLACE, th);
2960         RETURN(rc);
2961 }
2962
2963 /**
2964  * Implementation of dt_object_operations::do_declare_xattr_set.
2965  *
2966  * \see dt_object_operations::do_declare_xattr_set() in the API description
2967  * for details.
2968  *
2969  * the extension to the API:
2970  *   - declaring LOVEA requests striping creation
2971  *   - LU_XATTR_REPLACE means layout swap
2972  */
2973 static int lod_declare_xattr_set(const struct lu_env *env,
2974                                  struct dt_object *dt,
2975                                  const struct lu_buf *buf,
2976                                  const char *name, int fl,
2977                                  struct thandle *th)
2978 {
2979         struct dt_object *next = dt_object_child(dt);
2980         struct lu_attr   *attr = &lod_env_info(env)->lti_attr;
2981         __u32             mode;
2982         int               rc;
2983         ENTRY;
2984
2985         mode = dt->do_lu.lo_header->loh_attr & S_IFMT;
2986         if ((S_ISREG(mode) || mode == 0) &&
2987             !(fl & (LU_XATTR_REPLACE | LU_XATTR_MERGE | LU_XATTR_SPLIT)) &&
2988             (strcmp(name, XATTR_NAME_LOV) == 0 ||
2989              strcmp(name, XATTR_LUSTRE_LOV) == 0)) {
2990                 /*
2991                  * this is a request to create object's striping.
2992                  *
2993                  * allow to declare predefined striping on a new (!mode) object
2994                  * which is supposed to be replay of regular file creation
2995                  * (when LOV setting is declared)
2996                  *
2997                  * LU_XATTR_REPLACE is set to indicate a layout swap
2998                  */
2999                 if (dt_object_exists(dt)) {
3000                         rc = dt_attr_get(env, next, attr);
3001                         if (rc)
3002                                 RETURN(rc);
3003                 } else {
3004                         memset(attr, 0, sizeof(*attr));
3005                         attr->la_valid = LA_TYPE | LA_MODE;
3006                         attr->la_mode = S_IFREG;
3007                 }
3008                 rc = lod_declare_striped_create(env, dt, attr, buf, th);
3009         } else if (fl & LU_XATTR_MERGE) {
3010                 LASSERT(strcmp(name, XATTR_NAME_LOV) == 0 ||
3011                         strcmp(name, XATTR_LUSTRE_LOV) == 0);
3012                 rc = lod_declare_layout_merge(env, dt, buf, th);
3013         } else if (fl & LU_XATTR_SPLIT) {
3014                 LASSERT(strcmp(name, XATTR_NAME_LOV) == 0 ||
3015                         strcmp(name, XATTR_LUSTRE_LOV) == 0);
3016                 rc = lod_declare_layout_split(env, dt, buf, th);
3017         } else if (S_ISREG(mode) &&
3018                    strlen(name) > strlen(XATTR_LUSTRE_LOV) + 1 &&
3019                    strncmp(name, XATTR_LUSTRE_LOV,
3020                            strlen(XATTR_LUSTRE_LOV)) == 0) {
3021                 /*
3022                  * this is a request to modify object's striping.
3023                  * add/set/del component(s).
3024                  */
3025                 if (!dt_object_exists(dt))
3026                         RETURN(-ENOENT);
3027
3028                 rc = lod_declare_modify_layout(env, dt, name, buf, th);
3029         } else if (S_ISDIR(mode)) {
3030                 rc = lod_dir_declare_xattr_set(env, dt, buf, name, fl, th);
3031         } else if (strcmp(name, XATTR_NAME_FID) == 0) {
3032                 rc = lod_replace_parent_fid(env, dt, th, true);
3033         } else {
3034                 rc = lod_sub_declare_xattr_set(env, next, buf, name, fl, th);
3035         }
3036
3037         RETURN(rc);
3038 }
3039
3040 /**
3041  * Apply xattr changes to the object.
3042  *
3043  * Applies xattr changes to the object and the stripes if the latter exist.
3044  *
3045  * \param[in] env       execution environment
3046  * \param[in] dt        object
3047  * \param[in] buf       buffer pointing to the new value of xattr
3048  * \param[in] name      name of xattr
3049  * \param[in] fl        flags
3050  * \param[in] th        transaction handle
3051  *
3052  * \retval              0 on success
3053  * \retval              negative if failed
3054  */
3055 static int lod_xattr_set_internal(const struct lu_env *env,
3056                                   struct dt_object *dt,
3057                                   const struct lu_buf *buf,
3058                                   const char *name, int fl,
3059                                   struct thandle *th)
3060 {
3061         struct dt_object        *next = dt_object_child(dt);
3062         struct lod_object       *lo = lod_dt_obj(dt);
3063         int                     rc;
3064         int                     i;
3065         ENTRY;
3066
3067         rc = lod_sub_xattr_set(env, next, buf, name, fl, th);
3068         if (rc != 0 || !S_ISDIR(dt->do_lu.lo_header->loh_attr))
3069                 RETURN(rc);
3070
3071         /* Note: Do not set LinkEA on sub-stripes, otherwise
3072          * it will confuse the fid2path process(see mdt_path_current()).
3073          * The linkEA between master and sub-stripes is set in
3074          * lod_xattr_set_lmv(). */
3075         if (lo->ldo_dir_stripe_count == 0 || strcmp(name, XATTR_NAME_LINK) == 0)
3076                 RETURN(0);
3077
3078         for (i = 0; i < lo->ldo_dir_stripe_count; i++) {
3079                 LASSERT(lo->ldo_stripe[i]);
3080
3081                 rc = lod_sub_xattr_set(env, lo->ldo_stripe[i], buf, name,
3082                                        fl, th);
3083                 if (rc != 0)
3084                         break;
3085         }
3086
3087         RETURN(rc);
3088 }
3089
3090 /**
3091  * Delete an extended attribute.
3092  *
3093  * Deletes specified xattr from the object and the stripes if the latter exist.
3094  *
3095  * \param[in] env       execution environment
3096  * \param[in] dt        object
3097  * \param[in] name      name of xattr
3098  * \param[in] th        transaction handle
3099  *
3100  * \retval              0 on success
3101  * \retval              negative if failed
3102  */
3103 static int lod_xattr_del_internal(const struct lu_env *env,
3104                                   struct dt_object *dt,
3105                                   const char *name, struct thandle *th)
3106 {
3107         struct dt_object        *next = dt_object_child(dt);
3108         struct lod_object       *lo = lod_dt_obj(dt);
3109         int                     rc;
3110         int                     i;
3111         ENTRY;
3112
3113         rc = lod_sub_xattr_del(env, next, name, th);
3114         if (rc != 0 || !S_ISDIR(dt->do_lu.lo_header->loh_attr))
3115                 RETURN(rc);
3116
3117         if (lo->ldo_dir_stripe_count == 0)
3118                 RETURN(rc);
3119
3120         for (i = 0; i < lo->ldo_dir_stripe_count; i++) {
3121                 LASSERT(lo->ldo_stripe[i]);
3122
3123                 rc = lod_sub_xattr_del(env, lo->ldo_stripe[i], name, th);
3124                 if (rc != 0)
3125                         break;
3126         }
3127
3128         RETURN(rc);
3129 }
3130
3131 /**
3132  * Set default striping on a directory.
3133  *
3134  * Sets specified striping on a directory object unless it matches the default
3135  * striping (LOVEA_DELETE_VALUES() macro). In the latter case remove existing
3136  * EA. This striping will be used when regular file is being created in this
3137  * directory.
3138  *
3139  * \param[in] env       execution environment
3140  * \param[in] dt        the striped object
3141  * \param[in] buf       buffer with the striping
3142  * \param[in] name      name of EA
3143  * \param[in] fl        xattr flag (see OSD API description)
3144  * \param[in] th        transaction handle
3145  *
3146  * \retval              0 on success
3147  * \retval              negative if failed
3148  */
3149 static int lod_xattr_set_lov_on_dir(const struct lu_env *env,
3150                                     struct dt_object *dt,
3151                                     const struct lu_buf *buf,
3152                                     const char *name, int fl,
3153                                     struct thandle *th)
3154 {
3155         struct lov_user_md_v1   *lum;
3156         struct lov_user_md_v3   *v3 = NULL;
3157         const char              *pool_name = NULL;
3158         int                      rc;
3159         bool                     is_del;
3160         ENTRY;
3161
3162         LASSERT(buf != NULL && buf->lb_buf != NULL);
3163         lum = buf->lb_buf;
3164
3165         switch (lum->lmm_magic) {
3166         case LOV_USER_MAGIC_V3:
3167                 v3 = buf->lb_buf;
3168                 if (v3->lmm_pool_name[0] != '\0')
3169                         pool_name = v3->lmm_pool_name;
3170                 /* fall through */
3171         case LOV_USER_MAGIC_V1:
3172                 /* if { size, offset, count } = { 0, -1, 0 } and no pool
3173                  * (i.e. all default values specified) then delete default
3174                  * striping from dir. */
3175                 CDEBUG(D_LAYOUT,
3176                        "set default striping: sz %u # %u offset %d %s %s\n",
3177                        (unsigned)lum->lmm_stripe_size,
3178                        (unsigned)lum->lmm_stripe_count,
3179                        (int)lum->lmm_stripe_offset,
3180                        v3 ? "from" : "", v3 ? v3->lmm_pool_name : "");
3181
3182                 is_del = LOVEA_DELETE_VALUES(lum->lmm_stripe_size,
3183                                              lum->lmm_stripe_count,
3184                                              lum->lmm_stripe_offset,
3185                                              pool_name);
3186                 break;
3187         case LOV_USER_MAGIC_COMP_V1:
3188                 is_del = false;
3189                 break;
3190         default:
3191                 CERROR("Invalid magic %x\n", lum->lmm_magic);
3192                 RETURN(-EINVAL);
3193         }
3194
3195         if (is_del) {
3196                 rc = lod_xattr_del_internal(env, dt, name, th);
3197                 if (rc == -ENODATA)
3198                         rc = 0;
3199         } else {
3200                 rc = lod_xattr_set_internal(env, dt, buf, name, fl, th);
3201         }
3202
3203         RETURN(rc);
3204 }
3205
3206 /**
3207  * Set default striping on a directory object.
3208  *
3209  * Sets specified striping on a directory object unless it matches the default
3210  * striping (LOVEA_DELETE_VALUES() macro). In the latter case remove existing
3211  * EA. This striping will be used when a new directory is being created in the
3212  * directory.
3213  *
3214  * \param[in] env       execution environment
3215  * \param[in] dt        the striped object
3216  * \param[in] buf       buffer with the striping
3217  * \param[in] name      name of EA
3218  * \param[in] fl        xattr flag (see OSD API description)
3219  * \param[in] th        transaction handle
3220  *
3221  * \retval              0 on success
3222  * \retval              negative if failed
3223  */
3224 static int lod_xattr_set_default_lmv_on_dir(const struct lu_env *env,
3225                                             struct dt_object *dt,
3226                                             const struct lu_buf *buf,
3227                                             const char *name, int fl,
3228                                             struct thandle *th)
3229 {
3230         struct lmv_user_md_v1   *lum;
3231         int                      rc;
3232         ENTRY;
3233
3234         LASSERT(buf != NULL && buf->lb_buf != NULL);
3235         lum = buf->lb_buf;
3236
3237         CDEBUG(D_OTHER, "set default stripe_count # %u stripe_offset %d\n",
3238               le32_to_cpu(lum->lum_stripe_count),
3239               (int)le32_to_cpu(lum->lum_stripe_offset));
3240
3241         if (LMVEA_DELETE_VALUES((le32_to_cpu(lum->lum_stripe_count)),
3242                                  le32_to_cpu(lum->lum_stripe_offset)) &&
3243                                 le32_to_cpu(lum->lum_magic) == LMV_USER_MAGIC) {
3244                 rc = lod_xattr_del_internal(env, dt, name, th);
3245                 if (rc == -ENODATA)
3246                         rc = 0;
3247         } else {
3248                 rc = lod_xattr_set_internal(env, dt, buf, name, fl, th);
3249                 if (rc != 0)
3250                         RETURN(rc);
3251         }
3252
3253         RETURN(rc);
3254 }
3255
3256 /**
3257  * Turn directory into a striped directory.
3258  *
3259  * During replay the client sends the striping created before MDT
3260  * failure, then the layer above LOD sends this defined striping
3261  * using ->do_xattr_set(), so LOD uses this method to replay creation
3262  * of the stripes. Notice the original information for the striping
3263  * (#stripes, FIDs, etc) was transferred in declare path.
3264  *
3265  * \param[in] env       execution environment
3266  * \param[in] dt        the striped object
3267  * \param[in] buf       not used currently
3268  * \param[in] name      not used currently
3269  * \param[in] fl        xattr flag (see OSD API description)
3270  * \param[in] th        transaction handle
3271  *
3272  * \retval              0 on success
3273  * \retval              negative if failed
3274  */
3275 static int lod_xattr_set_lmv(const struct lu_env *env, struct dt_object *dt,
3276                              const struct lu_buf *buf, const char *name,
3277                              int fl, struct thandle *th)
3278 {
3279         struct lod_object       *lo = lod_dt_obj(dt);
3280         struct lod_thread_info  *info = lod_env_info(env);
3281         struct lu_attr          *attr = &info->lti_attr;
3282         struct dt_object_format *dof = &info->lti_format;
3283         struct lu_buf           lmv_buf;
3284         struct lu_buf           slave_lmv_buf;
3285         struct lmv_mds_md_v1    *lmm;
3286         struct lmv_mds_md_v1    *slave_lmm = NULL;
3287         struct dt_insert_rec    *rec = &info->lti_dt_rec;
3288         int                     i;
3289         int                     rc;
3290         ENTRY;
3291
3292         if (!S_ISDIR(dt->do_lu.lo_header->loh_attr))
3293                 RETURN(-ENOTDIR);
3294
3295         /* The stripes are supposed to be allocated in declare phase,
3296          * if there are no stripes being allocated, it will skip */
3297         if (lo->ldo_dir_stripe_count == 0)
3298                 RETURN(0);
3299
3300         rc = dt_attr_get(env, dt_object_child(dt), attr);
3301         if (rc != 0)
3302                 RETURN(rc);
3303
3304         attr->la_valid = LA_ATIME | LA_MTIME | LA_CTIME |
3305                          LA_MODE | LA_UID | LA_GID | LA_TYPE | LA_PROJID;
3306         dof->dof_type = DFT_DIR;
3307
3308         rc = lod_prep_lmv_md(env, dt, &lmv_buf);
3309         if (rc != 0)
3310                 RETURN(rc);
3311         lmm = lmv_buf.lb_buf;
3312
3313         OBD_ALLOC_PTR(slave_lmm);
3314         if (slave_lmm == NULL)
3315                 RETURN(-ENOMEM);
3316
3317         lod_prep_slave_lmv_md(slave_lmm, lmm);
3318         slave_lmv_buf.lb_buf = slave_lmm;
3319         slave_lmv_buf.lb_len = sizeof(*slave_lmm);
3320
3321         rec->rec_type = S_IFDIR;
3322         for (i = 0; i < lo->ldo_dir_stripe_count; i++) {
3323                 struct dt_object *dto;
3324                 char             *stripe_name = info->lti_key;
3325                 struct lu_name          *sname;
3326                 struct linkea_data       ldata          = { NULL };
3327                 struct lu_buf            linkea_buf;
3328
3329                 dto = lo->ldo_stripe[i];
3330
3331                 dt_write_lock(env, dto, MOR_TGT_CHILD);
3332                 rc = lod_sub_create(env, dto, attr, NULL, dof, th);
3333                 if (rc != 0) {
3334                         dt_write_unlock(env, dto);
3335                         GOTO(out, rc);
3336                 }
3337
3338                 rc = lod_sub_ref_add(env, dto, th);
3339                 dt_write_unlock(env, dto);
3340                 if (rc != 0)
3341                         GOTO(out, rc);
3342
3343                 rec->rec_fid = lu_object_fid(&dto->do_lu);
3344                 rc = lod_sub_insert(env, dto, (const struct dt_rec *)rec,
3345                                     (const struct dt_key *)dot, th, 0);
3346                 if (rc != 0)
3347                         GOTO(out, rc);
3348
3349                 rec->rec_fid = lu_object_fid(&dt->do_lu);
3350                 rc = lod_sub_insert(env, dto, (struct dt_rec *)rec,
3351                                     (const struct dt_key *)dotdot, th, 0);
3352                 if (rc != 0)
3353                         GOTO(out, rc);
3354
3355                 if (!OBD_FAIL_CHECK(OBD_FAIL_LFSCK_LOST_SLAVE_LMV) ||
3356                     cfs_fail_val != i) {
3357                         if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_BAD_SLAVE_LMV) &&
3358                             cfs_fail_val == i)
3359                                 slave_lmm->lmv_master_mdt_index =
3360                                                         cpu_to_le32(i + 1);
3361                         else
3362                                 slave_lmm->lmv_master_mdt_index =
3363                                                         cpu_to_le32(i);
3364
3365                         rc = lod_sub_xattr_set(env, dto, &slave_lmv_buf,
3366                                                XATTR_NAME_LMV, fl, th);
3367                         if (rc != 0)
3368                                 GOTO(out, rc);
3369                 }
3370
3371                 if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_BAD_SLAVE_NAME) &&
3372                     cfs_fail_val == i)
3373                         snprintf(stripe_name, sizeof(info->lti_key), DFID":%d",
3374                                  PFID(lu_object_fid(&dto->do_lu)), i + 1);
3375                 else
3376                         snprintf(stripe_name, sizeof(info->lti_key), DFID":%d",
3377                                  PFID(lu_object_fid(&dto->do_lu)), i);
3378
3379                 sname = lod_name_get(env, stripe_name, strlen(stripe_name));
3380                 rc = linkea_links_new(&ldata, &info->lti_linkea_buf,
3381                                       sname, lu_object_fid(&dt->do_lu));
3382                 if (rc != 0)
3383                         GOTO(out, rc);
3384
3385                 linkea_buf.lb_buf = ldata.ld_buf->lb_buf;
3386                 linkea_buf.lb_len = ldata.ld_leh->leh_len;
3387                 rc = lod_sub_xattr_set(env, dto, &linkea_buf,
3388                                        XATTR_NAME_LINK, 0, th);
3389                 if (rc != 0)
3390                         GOTO(out, rc);
3391
3392                 rec->rec_fid = lu_object_fid(&dto->do_lu);
3393                 rc = lod_sub_insert(env, dt_object_child(dt),
3394                                     (const struct dt_rec *)rec,
3395                                     (const struct dt_key *)stripe_name, th, 0);
3396                 if (rc != 0)
3397                         GOTO(out, rc);
3398
3399                 rc = lod_sub_ref_add(env, dt_object_child(dt), th);
3400                 if (rc != 0)
3401                         GOTO(out, rc);
3402         }
3403
3404         if (!OBD_FAIL_CHECK(OBD_FAIL_LFSCK_LOST_MASTER_LMV))
3405                 rc = lod_sub_xattr_set(env, dt_object_child(dt),
3406                                        &lmv_buf, XATTR_NAME_LMV, fl, th);
3407 out:
3408         if (slave_lmm != NULL)
3409                 OBD_FREE_PTR(slave_lmm);
3410
3411         RETURN(rc);
3412 }
3413
3414 /**
3415  * Helper function to declare/execute creation of a striped directory
3416  *
3417  * Called in declare/create object path, prepare striping for a directory
3418  * and prepare defaults data striping for the objects to be created in
3419  * that directory. Notice the function calls "declaration" or "execution"
3420  * methods depending on \a declare param. This is a consequence of the
3421  * current approach while we don't have natural distributed transactions:
3422  * we basically execute non-local updates in the declare phase. So, the
3423  * arguments for the both phases are the same and this is the reason for
3424  * this function to exist.
3425  *
3426  * \param[in] env       execution environment
3427  * \param[in] dt        object
3428  * \param[in] attr      attributes the stripes will be created with
3429  * \param[in] lmu       lmv_user_md if MDT indices are specified
3430  * \param[in] dof       format of stripes (see OSD API description)
3431  * \param[in] th        transaction handle
3432  * \param[in] declare   where to call "declare" or "execute" methods
3433  *
3434  * \retval              0 on success
3435  * \retval              negative if failed
3436  */
3437 static int lod_dir_striping_create_internal(const struct lu_env *env,
3438                                             struct dt_object *dt,
3439                                             struct lu_attr *attr,
3440                                             const struct lu_buf *lmu,
3441                                             struct dt_object_format *dof,
3442                                             struct thandle *th,
3443                                             bool declare)
3444 {
3445         struct lod_thread_info *info = lod_env_info(env);
3446         struct lod_object *lo = lod_dt_obj(dt);
3447         const struct lod_default_striping *lds = lo->ldo_def_striping;
3448         int rc;
3449         ENTRY;
3450
3451         LASSERT(ergo(lds != NULL,
3452                      lds->lds_def_striping_set ||
3453                      lds->lds_dir_def_striping_set));
3454
3455         if (!LMVEA_DELETE_VALUES(lo->ldo_dir_stripe_count,
3456                                  lo->ldo_dir_stripe_offset)) {
3457                 if (!lmu) {
3458                         struct lmv_user_md_v1 *v1 = info->lti_ea_store;
3459                         int stripe_count = lo->ldo_dir_stripe_count;
3460
3461                         if (info->lti_ea_store_size < sizeof(*v1)) {
3462                                 rc = lod_ea_store_resize(info, sizeof(*v1));
3463                                 if (rc != 0)
3464                                         RETURN(rc);
3465                                 v1 = info->lti_ea_store;
3466                         }
3467
3468                         memset(v1, 0, sizeof(*v1));
3469                         v1->lum_magic = cpu_to_le32(LMV_USER_MAGIC);
3470                         v1->lum_stripe_count = cpu_to_le32(stripe_count);
3471                         v1->lum_stripe_offset =
3472                                         cpu_to_le32(lo->ldo_dir_stripe_offset);
3473
3474                         info->lti_buf.lb_buf = v1;
3475                         info->lti_buf.lb_len = sizeof(*v1);
3476                         lmu = &info->lti_buf;
3477                 }
3478
3479                 if (declare)
3480                         rc = lod_declare_xattr_set_lmv(env, dt, attr, lmu, dof,
3481                                                        th);
3482                 else
3483                         rc = lod_xattr_set_lmv(env, dt, lmu, XATTR_NAME_LMV, 0,
3484                                                th);
3485                 if (rc != 0)
3486                         RETURN(rc);
3487         }
3488
3489         /* Transfer default LMV striping from the parent */
3490         if (lds != NULL && lds->lds_dir_def_striping_set &&
3491             !LMVEA_DELETE_VALUES(lds->lds_dir_def_stripe_count,
3492                                  lds->lds_dir_def_stripe_offset)) {
3493                 struct lmv_user_md_v1 *v1 = info->lti_ea_store;
3494
3495                 if (info->lti_ea_store_size < sizeof(*v1)) {
3496                         rc = lod_ea_store_resize(info, sizeof(*v1));
3497                         if (rc != 0)
3498                                 RETURN(rc);
3499                         v1 = info->lti_ea_store;
3500                 }
3501
3502                 memset(v1, 0, sizeof(*v1));
3503                 v1->lum_magic = cpu_to_le32(LMV_USER_MAGIC);
3504                 v1->lum_stripe_count =
3505                         cpu_to_le32(lds->lds_dir_def_stripe_count);
3506                 v1->lum_stripe_offset =
3507                         cpu_to_le32(lds->lds_dir_def_stripe_offset);
3508                 v1->lum_hash_type =
3509                         cpu_to_le32(lds->lds_dir_def_hash_type);
3510
3511                 info->lti_buf.lb_buf = v1;
3512                 info->lti_buf.lb_len = sizeof(*v1);
3513                 if (declare)
3514                         rc = lod_dir_declare_xattr_set(env, dt, &info->lti_buf,
3515                                                        XATTR_NAME_DEFAULT_LMV,
3516                                                        0, th);
3517                 else
3518                         rc = lod_xattr_set_default_lmv_on_dir(env, dt,
3519                                                   &info->lti_buf,
3520                                                   XATTR_NAME_DEFAULT_LMV, 0,
3521                                                   th);
3522                 if (rc != 0)
3523                         RETURN(rc);
3524         }
3525
3526         /* Transfer default LOV striping from the parent */
3527         if (lds != NULL && lds->lds_def_striping_set &&
3528             lds->lds_def_comp_cnt != 0) {
3529                 struct lov_mds_md *lmm;
3530                 int lmm_size = lod_comp_md_size(lo, true);
3531
3532                 if (info->lti_ea_store_size < lmm_size) {
3533                         rc = lod_ea_store_resize(info, lmm_size);
3534                         if (rc != 0)
3535                                 RETURN(rc);
3536                 }
3537                 lmm = info->lti_ea_store;
3538
3539                 rc = lod_generate_lovea(env, lo, lmm, &lmm_size, true);
3540                 if (rc != 0)
3541                         RETURN(rc);
3542
3543                 info->lti_buf.lb_buf = lmm;
3544                 info->lti_buf.lb_len = lmm_size;
3545
3546                 if (declare)
3547                         rc = lod_dir_declare_xattr_set(env, dt, &info->lti_buf,
3548                                                        XATTR_NAME_LOV, 0, th);
3549                 else
3550                         rc = lod_xattr_set_lov_on_dir(env, dt, &info->lti_buf,
3551                                                       XATTR_NAME_LOV, 0, th);
3552                 if (rc != 0)
3553                         RETURN(rc);
3554         }
3555
3556         RETURN(0);
3557 }
3558
3559 static int lod_declare_dir_striping_create(const struct lu_env *env,
3560                                            struct dt_object *dt,
3561                                            struct lu_attr *attr,
3562                                            struct lu_buf *lmu,
3563                                            struct dt_object_format *dof,
3564                                            struct thandle *th)
3565 {
3566         return lod_dir_striping_create_internal(env, dt, attr, lmu, dof, th,
3567                                                 true);
3568 }
3569
3570 static int lod_dir_striping_create(const struct lu_env *env,
3571                                    struct dt_object *dt,
3572                                    struct lu_attr *attr,
3573                                    struct dt_object_format *dof,
3574                                    struct thandle *th)
3575 {
3576         return lod_dir_striping_create_internal(env, dt, attr, NULL, dof, th,
3577                                                 false);
3578 }
3579
3580 /**
3581  * Make LOV EA for striped object.
3582  *
3583  * Generate striping information and store it in the LOV EA of the given
3584  * object. The caller must ensure nobody else is calling the function
3585  * against the object concurrently. The transaction must be started.
3586  * FLDB service must be running as well; it's used to map FID to the target,
3587  * which is stored in LOV EA.
3588  *
3589  * \param[in] env               execution environment for this thread
3590  * \param[in] lo                LOD object
3591  * \param[in] th                transaction handle
3592  *
3593  * \retval                      0 if LOV EA is stored successfully
3594  * \retval                      negative error number on failure
3595  */
3596 static int lod_generate_and_set_lovea(const struct lu_env *env,
3597                                       struct lod_object *lo,
3598                                       struct thandle *th)
3599 {
3600         struct lod_thread_info  *info = lod_env_info(env);
3601         struct dt_object        *next = dt_object_child(&lo->ldo_obj);
3602         struct lov_mds_md_v1    *lmm;
3603         int                      rc, lmm_size;
3604         ENTRY;
3605
3606         LASSERT(lo);
3607
3608         if (lo->ldo_comp_cnt == 0) {
3609                 lod_striping_free(env, lo);
3610                 rc = lod_sub_xattr_del(env, next, XATTR_NAME_LOV, th);
3611                 RETURN(rc);
3612         }
3613
3614         lmm_size = lod_comp_md_size(lo, false);
3615         if (info->lti_ea_store_size < lmm_size) {
3616                 rc = lod_ea_store_resize(info, lmm_size);
3617                 if (rc)
3618                         RETURN(rc);
3619         }
3620         lmm = info->lti_ea_store;
3621
3622         rc = lod_generate_lovea(env, lo, lmm, &lmm_size, false);
3623         if (rc)
3624                 RETURN(rc);
3625
3626         info->lti_buf.lb_buf = lmm;
3627         info->lti_buf.lb_len = lmm_size;
3628         rc = lod_sub_xattr_set(env, next, &info->lti_buf,
3629                                XATTR_NAME_LOV, 0, th);
3630         RETURN(rc);
3631 }
3632
3633 /**
3634  * Delete layout component(s)
3635  *
3636  * \param[in] env       execution environment for this thread
3637  * \param[in] dt        object
3638  * \param[in] th        transaction handle
3639  *
3640  * \retval      0 on success
3641  * \retval      negative error number on failure
3642  */
3643 static int lod_layout_del(const struct lu_env *env, struct dt_object *dt,
3644                           struct thandle *th)
3645 {
3646         struct lod_layout_component     *lod_comp;
3647         struct lod_object       *lo = lod_dt_obj(dt);
3648         struct dt_object        *next = dt_object_child(dt);
3649         struct lu_attr  *attr = &lod_env_info(env)->lti_attr;
3650         int     rc, i, j, left;
3651
3652         LASSERT(lo->ldo_is_composite);
3653         LASSERT(lo->ldo_comp_cnt > 0 && lo->ldo_comp_entries != NULL);
3654
3655         left = lo->ldo_comp_cnt;
3656         for (i = (lo->ldo_comp_cnt - 1); i >= 0; i--) {
3657                 lod_comp = &lo->ldo_comp_entries[i];
3658
3659                 if (lod_comp->llc_id != LCME_ID_INVAL)
3660                         break;
3661                 left--;
3662
3663                 /* Not instantiated component */
3664                 if (lod_comp->llc_stripe == NULL)
3665                         continue;
3666
3667                 LASSERT(lod_comp->llc_stripe_count > 0);
3668                 for (j = 0; j < lod_comp->llc_stripe_count; j++) {
3669                         struct dt_object *obj = lod_comp->llc_stripe[j];
3670
3671                         if (obj == NULL)
3672                                 continue;
3673                         rc = lod_sub_destroy(env, obj, th);
3674                         if (rc)
3675                                 GOTO(out, rc);
3676
3677                         lu_object_put(env, &obj->do_lu);
3678                         lod_comp->llc_stripe[j] = NULL;
3679                 }
3680                 OBD_FREE(lod_comp->llc_stripe, sizeof(struct dt_object *) *
3681                                         lod_comp->llc_stripes_allocated);
3682                 lod_comp->llc_stripe = NULL;
3683                 OBD_FREE(lod_comp->llc_ost_indices,
3684                          sizeof(__u32) * lod_comp->llc_stripes_allocated);
3685                 lod_comp->llc_ost_indices = NULL;
3686                 lod_comp->llc_stripes_allocated = 0;
3687                 lod_obj_set_pool(lo, i, NULL);
3688                 if (lod_comp->llc_ostlist.op_array) {
3689                         OBD_FREE(lod_comp->llc_ostlist.op_array,
3690                                  lod_comp->llc_ostlist.op_size);
3691                         lod_comp->llc_ostlist.op_array = NULL;
3692                         lod_comp->llc_ostlist.op_size = 0;
3693                 }
3694         }
3695
3696         LASSERTF(left >= 0 && left < lo->ldo_comp_cnt, "left = %d\n", left);
3697         if (left > 0) {
3698                 struct lod_layout_component     *comp_array;
3699
3700                 OBD_ALLOC(comp_array, sizeof(*comp_array) * left);
3701                 if (comp_array == NULL)
3702                         GOTO(out, rc = -ENOMEM);
3703
3704                 memcpy(&comp_array[0], &lo->ldo_comp_entries[0],
3705                        sizeof(*comp_array) * left);
3706
3707                 OBD_FREE(lo->ldo_comp_entries,
3708                          sizeof(*comp_array) * lo->ldo_comp_cnt);
3709                 lo->ldo_comp_entries = comp_array;
3710                 lo->ldo_comp_cnt = left;
3711
3712                 LASSERT(lo->ldo_mirror_count == 1);
3713                 lo->ldo_mirrors[0].lme_end = left - 1;
3714                 lod_obj_inc_layout_gen(lo);
3715         } else {
3716                 lod_free_comp_entries(lo);
3717         }
3718
3719         LASSERT(dt_object_exists(dt));
3720         rc = dt_attr_get(env, next, attr);
3721         if (rc)
3722                 GOTO(out, rc);
3723
3724         if (attr->la_size > 0) {
3725                 attr->la_size = 0;
3726                 attr->la_valid = LA_SIZE;
3727                 rc = lod_sub_attr_set(env, next, attr, th);
3728                 if (rc)
3729                         GOTO(out, rc);
3730         }
3731
3732         rc = lod_generate_and_set_lovea(env, lo, th);
3733         EXIT;
3734 out:
3735         if (rc)
3736                 lod_striping_free(env, lo);
3737         return rc;
3738 }
3739
3740
3741 static int lod_get_default_lov_striping(const struct lu_env *env,
3742                                         struct lod_object *lo,
3743                                         struct lod_default_striping *lds);
3744 /**
3745  * Implementation of dt_object_operations::do_xattr_set.
3746  *
3747  * Sets specified extended attribute on the object. Three types of EAs are
3748  * special:
3749  *   LOV EA - stores striping for a regular file or default striping (when set
3750  *            on a directory)
3751  *   LMV EA - stores a marker for the striped directories
3752  *   DMV EA - stores default directory striping
3753  *
3754  * When striping is applied to a non-striped existing object (this is called
3755  * late striping), then LOD notices the caller wants to turn the object into a
3756  * striped one. The stripe objects are created and appropriate EA is set:
3757  * LOV EA storing all the stripes directly or LMV EA storing just a small header
3758  * with striping configuration.
3759  *
3760  * \see dt_object_operations::do_xattr_set() in the API description for details.
3761  */
3762 static int lod_xattr_set(const struct lu_env *env,
3763                          struct dt_object *dt, const struct lu_buf *buf,
3764                          const char *name, int fl, struct thandle *th)
3765 {
3766         struct dt_object        *next = dt_object_child(dt);
3767         int                      rc;
3768         ENTRY;
3769
3770         if (S_ISDIR(dt->do_lu.lo_header->loh_attr) &&
3771             strcmp(name, XATTR_NAME_LMV) == 0) {
3772                 struct lmv_mds_md_v1 *lmm = buf->lb_buf;
3773
3774                 if (lmm != NULL && le32_to_cpu(lmm->lmv_hash_type) &
3775                                                 LMV_HASH_FLAG_MIGRATION)
3776                         rc = lod_sub_xattr_set(env, next, buf, name, fl, th);
3777                 else
3778                         rc = lod_dir_striping_create(env, dt, NULL, NULL, th);
3779
3780                 RETURN(rc);
3781         }
3782
3783         if (S_ISDIR(dt->do_lu.lo_header->loh_attr) &&
3784             strcmp(name, XATTR_NAME_LOV) == 0) {
3785                 struct lod_thread_info *info = lod_env_info(env);
3786                 struct lod_default_striping *lds = &info->lti_def_striping;
3787                 struct lov_user_md_v1 *v1 = buf->lb_buf;
3788                 char pool[LOV_MAXPOOLNAME + 1];
3789                 bool is_del;
3790
3791                 /* get existing striping config */
3792                 rc = lod_get_default_lov_striping(env, lod_dt_obj(dt), lds);
3793                 if (rc)
3794                         RETURN(rc);
3795
3796                 memset(pool, 0, sizeof(pool));
3797                 if (lds->lds_def_striping_set == 1)
3798                         lod_layout_get_pool(lds->lds_def_comp_entries,
3799                                             lds->lds_def_comp_cnt, pool,
3800                                             sizeof(pool));
3801
3802                 is_del = LOVEA_DELETE_VALUES(v1->lmm_stripe_size,
3803                                              v1->lmm_stripe_count,
3804                                              v1->lmm_stripe_offset,
3805                                              NULL);
3806
3807                 /* Retain the pool name if it is not given */
3808                 if (v1->lmm_magic == LOV_USER_MAGIC_V1 && pool[0] != '\0' &&
3809                         !is_del) {
3810                         struct lod_thread_info *info = lod_env_info(env);
3811                         struct lov_user_md_v3 *v3  = info->lti_ea_store;
3812
3813                         memset(v3, 0, sizeof(*v3));
3814                         v3->lmm_magic = cpu_to_le32(LOV_USER_MAGIC_V3);
3815                         v3->lmm_pattern = cpu_to_le32(v1->lmm_pattern);
3816                         v3->lmm_stripe_count =
3817                                         cpu_to_le32(v1->lmm_stripe_count);
3818                         v3->lmm_stripe_offset =
3819                                         cpu_to_le32(v1->lmm_stripe_offset);
3820                         v3->lmm_stripe_size = cpu_to_le32(v1->lmm_stripe_size);
3821
3822                         strlcpy(v3->lmm_pool_name, pool,
3823                                 sizeof(v3->lmm_pool_name));
3824
3825                         info->lti_buf.lb_buf = v3;
3826                         info->lti_buf.lb_len = sizeof(*v3);
3827                         rc = lod_xattr_set_lov_on_dir(env, dt, &info->lti_buf,
3828                                                       name, fl, th);
3829                 } else {
3830                         rc = lod_xattr_set_lov_on_dir(env, dt, buf, name,
3831                                                       fl, th);
3832                 }
3833
3834                 if (lds->lds_def_striping_set == 1 &&
3835                     lds->lds_def_comp_entries != NULL)
3836                         lod_free_def_comp_entries(lds);
3837
3838                 RETURN(rc);
3839         } else if (S_ISDIR(dt->do_lu.lo_header->loh_attr) &&
3840                    strcmp(name, XATTR_NAME_DEFAULT_LMV) == 0) {
3841                 /* default LMVEA */
3842                 rc = lod_xattr_set_default_lmv_on_dir(env, dt, buf, name, fl,
3843                                                       th);
3844                 RETURN(rc);
3845         } else if (S_ISREG(dt->do_lu.lo_header->loh_attr) &&
3846                    (!strcmp(name, XATTR_NAME_LOV) ||
3847                     !strncmp(name, XATTR_LUSTRE_LOV,
3848                              strlen(XATTR_LUSTRE_LOV)))) {
3849                 /* in case of lov EA swap, just set it
3850                  * if not, it is a replay so check striping match what we
3851                  * already have during req replay, declare_xattr_set()
3852                  * defines striping, then create() does the work */
3853                 if (fl & LU_XATTR_REPLACE) {
3854                         /* free stripes, then update disk */
3855                         lod_striping_free(env, lod_dt_obj(dt));
3856
3857                         rc = lod_sub_xattr_set(env, next, buf, name, fl, th);
3858                 } else if (dt_object_remote(dt)) {
3859                         /* This only happens during migration, see
3860                          * mdd_migrate_create(), in which Master MDT will
3861                          * create a remote target object, and only set
3862                          * (migrating) stripe EA on the remote object,
3863                          * and does not need creating each stripes. */
3864                         rc = lod_sub_xattr_set(env, next, buf, name,
3865                                                       fl, th);
3866                 } else if (strcmp(name, XATTR_LUSTRE_LOV".del") == 0) {
3867                         /* delete component(s) */
3868                         LASSERT(lod_dt_obj(dt)->ldo_comp_cached);
3869                         rc = lod_layout_del(env, dt, th);
3870                 } else {
3871                         /*
3872                          * When 'name' is XATTR_LUSTRE_LOV or XATTR_NAME_LOV,
3873                          * it's going to create create file with specified
3874                          * component(s), the striping must have not being
3875                          * cached in this case;
3876                          *
3877                          * Otherwise, it's going to add/change component(s) to
3878                          * an existing file, the striping must have been cached
3879                          * in this case.
3880                          */
3881                         LASSERT(equi(!strcmp(name, XATTR_LUSTRE_LOV) ||
3882                                      !strcmp(name, XATTR_NAME_LOV),
3883                                 !lod_dt_obj(dt)->ldo_comp_cached));
3884
3885                         rc = lod_striped_create(env, dt, NULL, NULL, th);
3886                 }
3887                 RETURN(rc);
3888         } else if (strcmp(name, XATTR_NAME_FID) == 0) {
3889                 rc = lod_replace_parent_fid(env, dt, th, false);
3890
3891                 RETURN(rc);
3892         }
3893
3894         /* then all other xattr */
3895         rc = lod_xattr_set_internal(env, dt, buf, name, fl, th);
3896
3897         RETURN(rc);
3898 }
3899
3900 /**
3901  * Implementation of dt_object_operations::do_declare_xattr_del.
3902  *
3903  * \see dt_object_operations::do_declare_xattr_del() in the API description
3904  * for details.
3905  */
3906 static int lod_declare_xattr_del(const struct lu_env *env,
3907                                  struct dt_object *dt, const char *name,
3908                                  struct thandle *th)
3909 {
3910         struct lod_object       *lo = lod_dt_obj(dt);
3911         int                     rc;
3912         int                     i;
3913         ENTRY;
3914
3915         rc = lod_sub_declare_xattr_del(env, dt_object_child(dt), name, th);
3916         if (rc != 0)
3917                 RETURN(rc);
3918
3919         if (!S_ISDIR(dt->do_lu.lo_header->loh_attr))
3920                 RETURN(0);
3921
3922         /* set xattr to each stripes, if needed */
3923         rc = lod_striping_load(env, lo);
3924         if (rc != 0)
3925                 RETURN(rc);
3926
3927         if (lo->ldo_dir_stripe_count == 0)
3928                 RETURN(0);
3929
3930         for (i = 0; i < lo->ldo_dir_stripe_count; i++) {
3931                 LASSERT(lo->ldo_stripe[i]);
3932                 rc = lod_sub_declare_xattr_del(env, lo->ldo_stripe[i],
3933                                                name, th);
3934                 if (rc != 0)
3935                         break;
3936         }
3937
3938         RETURN(rc);
3939 }
3940
3941 /**
3942  * Implementation of dt_object_operations::do_xattr_del.
3943  *
3944  * If EA storing a regular striping is being deleted, then release
3945  * all the references to the stripe objects in core.
3946  *
3947  * \see dt_object_operations::do_xattr_del() in the API description for details.
3948  */
3949 static int lod_xattr_del(const struct lu_env *env, struct dt_object *dt,
3950                          const char *name, struct thandle *th)
3951 {
3952         struct dt_object        *next = dt_object_child(dt);
3953         struct lod_object       *lo = lod_dt_obj(dt);
3954         int                     rc;
3955         int                     i;
3956         ENTRY;
3957
3958         if (!strcmp(name, XATTR_NAME_LOV))
3959                 lod_striping_free(env, lod_dt_obj(dt));
3960
3961         rc = lod_sub_xattr_del(env, next, name, th);
3962         if (rc != 0 || !S_ISDIR(dt->do_lu.lo_header->loh_attr))
3963                 RETURN(rc);
3964
3965         if (lo->ldo_dir_stripe_count == 0)
3966                 RETURN(0);
3967
3968         for (i = 0; i < lo->ldo_dir_stripe_count; i++) {
3969                 LASSERT(lo->ldo_stripe[i]);
3970
3971                 rc = lod_sub_xattr_del(env, lo->ldo_stripe[i], name, th);
3972                 if (rc != 0)
3973                         break;
3974         }
3975
3976         RETURN(rc);
3977 }
3978
3979 /**
3980  * Implementation of dt_object_operations::do_xattr_list.
3981  *
3982  * \see dt_object_operations::do_xattr_list() in the API description
3983  * for details.
3984  */
3985 static int lod_xattr_list(const struct lu_env *env,
3986                           struct dt_object *dt, const struct lu_buf *buf)
3987 {
3988         return dt_xattr_list(env, dt_object_child(dt), buf);
3989 }
3990
3991 static inline int lod_object_will_be_striped(int is_reg, const struct lu_fid *fid)
3992 {
3993         return (is_reg && fid_seq(fid) != FID_SEQ_LOCAL_FILE);
3994 }
3995
3996
3997 /**
3998  * Get default striping.
3999  *
4000  * \param[in] env               execution environment
4001  * \param[in] lo                object
4002  * \param[out] lds              default striping
4003  *
4004  * \retval              0 on success
4005  * \retval              negative if failed
4006  */
4007 static int lod_get_default_lov_striping(const struct lu_env *env,
4008                                         struct lod_object *lo,
4009                                         struct lod_default_striping *lds)
4010 {
4011         struct lod_thread_info *info = lod_env_info(env);
4012         struct lov_user_md_v1 *v1 = NULL;
4013         struct lov_user_md_v3 *v3 = NULL;
4014         struct lov_comp_md_v1 *comp_v1 = NULL;
4015         __u16   comp_cnt;
4016         __u16   mirror_cnt;
4017         bool    composite;
4018         int     rc, i;
4019         ENTRY;
4020
4021         lds->lds_def_striping_set = 0;
4022
4023         rc = lod_get_lov_ea(env, lo);
4024         if (rc < 0)
4025                 RETURN(rc);
4026
4027         if (rc < (typeof(rc))sizeof(struct lov_user_md))
4028                 RETURN(0);
4029
4030         v1 = info->lti_ea_store;
4031         if (v1->lmm_magic == __swab32(LOV_USER_MAGIC_V1)) {
4032                 lustre_swab_lov_user_md_v1(v1);
4033         } else if (v1->lmm_magic == __swab32(LOV_USER_MAGIC_V3)) {
4034                 v3 = (struct lov_user_md_v3 *)v1;
4035                 lustre_swab_lov_user_md_v3(v3);
4036         } else if (v1->lmm_magic == __swab32(LOV_USER_MAGIC_COMP_V1)) {
4037                 comp_v1 = (struct lov_comp_md_v1 *)v1;
4038                 lustre_swab_lov_comp_md_v1(comp_v1);
4039         }
4040
4041         if (v1->lmm_magic != LOV_MAGIC_V3 && v1->lmm_magic != LOV_MAGIC_V1 &&
4042             v1->lmm_magic != LOV_MAGIC_COMP_V1)
4043                 RETURN(-ENOTSUPP);
4044
4045         if (v1->lmm_magic == LOV_MAGIC_COMP_V1) {
4046                 comp_v1 = (struct lov_comp_md_v1 *)v1;
4047                 comp_cnt = comp_v1->lcm_entry_count;
4048                 if (comp_cnt == 0)
4049                         RETURN(-EINVAL);
4050                 mirror_cnt = comp_v1->lcm_mirror_count + 1;
4051                 composite = true;
4052         } else {
4053                 comp_cnt = 1;
4054                 mirror_cnt = 0;
4055                 composite = false;
4056         }
4057
4058         /* realloc default comp entries if necessary */
4059         rc = lod_def_striping_comp_resize(lds, comp_cnt);
4060         if (rc < 0)
4061                 RETURN(rc);
4062
4063         lds->lds_def_comp_cnt = comp_cnt;
4064         lds->lds_def_striping_is_composite = composite;
4065         lds->lds_def_mirror_cnt = mirror_cnt;
4066
4067         for (i = 0; i < comp_cnt; i++) {
4068                 struct lod_layout_component *lod_comp;
4069                 struct lu_extent *ext;
4070                 char *pool;
4071
4072                 lod_comp = &lds->lds_def_comp_entries[i];
4073                 /*
4074                  * reset lod_comp values, llc_stripes is always NULL in
4075                  * the default striping template, llc_pool will be reset
4076                  * later below.
4077                  */
4078                 memset(lod_comp, 0, offsetof(typeof(*lod_comp), llc_pool));
4079
4080                 if (composite) {
4081                         v1 = (struct lov_user_md *)((char *)comp_v1 +
4082                                         comp_v1->lcm_entries[i].lcme_offset);
4083                         ext = &comp_v1->lcm_entries[i].lcme_extent;
4084                         lod_comp->llc_extent = *ext;
4085                 }
4086
4087                 if (v1->lmm_pattern != LOV_PATTERN_RAID0 &&
4088                     v1->lmm_pattern != LOV_PATTERN_MDT &&
4089                     v1->lmm_pattern != 0) {
4090                         lod_free_def_comp_entries(lds);
4091                         RETURN(-EINVAL);
4092                 }
4093
4094                 CDEBUG(D_LAYOUT, DFID" stripe_count=%d stripe_size=%d "
4095                        "stripe_offset=%d\n",
4096                        PFID(lu_object_fid(&lo->ldo_obj.do_lu)),
4097                        (int)v1->lmm_stripe_count, (int)v1->lmm_stripe_size,
4098                        (int)v1->lmm_stripe_offset);
4099
4100                 lod_comp->llc_stripe_count = v1->lmm_stripe_count;
4101                 lod_comp->llc_stripe_size = v1->lmm_stripe_size;
4102                 lod_comp->llc_stripe_offset = v1->lmm_stripe_offset;
4103                 lod_comp->llc_pattern = v1->lmm_pattern;
4104
4105                 pool = NULL;
4106                 if (v1->lmm_magic == LOV_USER_MAGIC_V3) {
4107                         /* XXX: sanity check here */
4108                         v3 = (struct lov_user_md_v3 *) v1;
4109                         if (v3->lmm_pool_name[0] != '\0')
4110                                 pool = v3->lmm_pool_name;
4111                 }
4112                 lod_set_def_pool(lds, i, pool);
4113         }
4114
4115         lds->lds_def_striping_set = 1;
4116         RETURN(rc);
4117 }
4118
4119 /**
4120  * Get default directory striping.
4121  *
4122  * \param[in] env               execution environment
4123  * \param[in] lo                object
4124  * \param[out] lds              default striping
4125  *
4126  * \retval              0 on success
4127  * \retval              negative if failed
4128  */
4129 static int lod_get_default_lmv_striping(const struct lu_env *env,
4130                                         struct lod_object *lo,
4131                                         struct lod_default_striping *lds)
4132 {
4133         struct lod_thread_info  *info = lod_env_info(env);
4134         struct lmv_user_md_v1   *v1 = NULL;
4135         int                      rc;
4136         ENTRY;
4137
4138         lds->lds_dir_def_striping_set = 0;
4139         rc = lod_get_default_lmv_ea(env, lo);
4140         if (rc < 0)
4141                 RETURN(rc);
4142
4143         if (rc < (typeof(rc))sizeof(struct lmv_user_md))
4144                 RETURN(0);
4145
4146         v1 = info->lti_ea_store;
4147
4148         lds->lds_dir_def_stripe_count = le32_to_cpu(v1->lum_stripe_count);
4149         lds->lds_dir_def_stripe_offset = le32_to_cpu(v1->lum_stripe_offset);
4150         lds->lds_dir_def_hash_type = le32_to_cpu(v1->lum_hash_type);
4151         lds->lds_dir_def_striping_set = 1;
4152
4153         RETURN(0);
4154 }
4155
4156 /**
4157  * Get default striping in the object.
4158  *
4159  * Get object default striping and default directory striping.
4160  *
4161  * \param[in] env               execution environment
4162  * \param[in] lo                object
4163  * \param[out] lds              default striping
4164  *
4165  * \retval              0 on success
4166  * \retval              negative if failed
4167  */
4168 static int lod_get_default_striping(const struct lu_env *env,
4169                                     struct lod_object *lo,
4170                                     struct lod_default_striping *lds)
4171 {
4172         int rc, rc1;
4173
4174         rc = lod_get_default_lov_striping(env, lo, lds);
4175         rc1 = lod_get_default_lmv_striping(env, lo, lds);
4176         if (rc == 0 && rc1 < 0)
4177                 rc = rc1;
4178
4179         return rc;
4180 }
4181
4182 /**
4183  * Apply default striping on object.
4184  *
4185  * If object striping pattern is not set, set to the one in default striping.
4186  * The default striping is from parent or fs.
4187  *
4188  * \param[in] lo                new object
4189  * \param[in] lds               default striping
4190  * \param[in] mode              new object's mode
4191  */
4192 static void lod_striping_from_default(struct lod_object *lo,
4193                                       const struct lod_default_striping *lds,
4194                                       umode_t mode)
4195 {
4196         struct lod_device *d = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
4197         struct lov_desc *desc = &d->lod_desc;
4198         int i, rc;
4199
4200         if (lds->lds_def_striping_set && S_ISREG(mode)) {
4201                 rc = lod_alloc_comp_entries(lo, lds->lds_def_mirror_cnt,
4202                                             lds->lds_def_comp_cnt);
4203                 if (rc != 0)
4204                         return;
4205
4206                 lo->ldo_is_composite = lds->lds_def_striping_is_composite;
4207                 if (lds->lds_def_mirror_cnt > 1)
4208                         lo->ldo_flr_state = LCM_FL_RDONLY;
4209
4210                 for (i = 0; i < lo->ldo_comp_cnt; i++) {
4211                         struct lod_layout_component *obj_comp =
4212                                                 &lo->ldo_comp_entries[i];
4213                         struct lod_layout_component *def_comp =
4214                                                 &lds->lds_def_comp_entries[i];
4215
4216                         CDEBUG(D_LAYOUT, "Inherite from default: size:%hu "
4217                                "nr:%u offset:%u pattern %#x %s\n",
4218                                def_comp->llc_stripe_size,
4219                                def_comp->llc_stripe_count,
4220                                def_comp->llc_stripe_offset,
4221                                def_comp->llc_pattern,
4222                                def_comp->llc_pool ?: "");
4223
4224                         *obj_comp = *def_comp;
4225                         if (def_comp->llc_pool != NULL) {
4226                                 /* pointer was copied from def_comp */
4227                                 obj_comp->llc_pool = NULL;
4228                                 lod_obj_set_pool(lo, i, def_comp->llc_pool);
4229                         }
4230
4231                         /*
4232                          * Don't initialize these fields for plain layout
4233                          * (v1/v3) here, they are inherited in the order of
4234                          * 'parent' -> 'fs default (root)' -> 'global default
4235                          * values for stripe_count & stripe_size'.
4236                          *
4237                          * see lod_ah_init().
4238                          */
4239                         if (!lo->ldo_is_composite)
4240                                 continue;
4241
4242                         lod_adjust_stripe_info(obj_comp, desc);
4243                 }
4244         } else if (lds->lds_dir_def_striping_set && S_ISDIR(mode)) {
4245                 if (lo->ldo_dir_stripe_count == 0)
4246                         lo->ldo_dir_stripe_count =
4247                                 lds->lds_dir_def_stripe_count;
4248                 if (lo->ldo_dir_stripe_offset == -1)
4249                         lo->ldo_dir_stripe_offset =
4250                                 lds->lds_dir_def_stripe_offset;
4251                 if (lo->ldo_dir_hash_type == 0)
4252                         lo->ldo_dir_hash_type = lds->lds_dir_def_hash_type;
4253
4254                 CDEBUG(D_LAYOUT, "striping from default dir: count:%hu, "
4255                        "offset:%u, hash_type:%u\n",
4256                        lo->ldo_dir_stripe_count, lo->ldo_dir_stripe_offset,
4257                        lo->ldo_dir_hash_type);
4258         }
4259 }
4260
4261 static inline bool lod_need_inherit_more(struct lod_object *lo, bool from_root)
4262 {
4263         struct lod_layout_component *lod_comp;
4264
4265         if (lo->ldo_comp_cnt == 0)
4266                 return true;
4267
4268         if (lo->ldo_is_composite)
4269                 return false;
4270
4271         lod_comp = &lo->ldo_comp_entries[0];
4272
4273         if (lod_comp->llc_stripe_count <= 0 ||
4274             lod_comp->llc_stripe_size <= 0)
4275                 return true;
4276
4277         if (from_root && (lod_comp->llc_pool == NULL ||
4278                           lod_comp->llc_stripe_offset == LOV_OFFSET_DEFAULT))
4279                 return true;
4280
4281         return false;
4282 }
4283
4284 /**
4285  * Implementation of dt_object_operations::do_ah_init.
4286  *
4287  * This method is used to make a decision on the striping configuration for the
4288  * object being created. It can be taken from the \a parent object if it exists,
4289  * or filesystem's default. The resulting configuration (number of stripes,
4290  * stripe size/offset, pool name, etc) is stored in the object itself and will
4291  * be used by the methods like ->doo_declare_create().
4292  *
4293  * \see dt_object_operations::do_ah_init() in the API description for details.
4294  */
4295 static void lod_ah_init(const struct lu_env *env,
4296                         struct dt_allocation_hint *ah,
4297                         struct dt_object *parent,
4298                         struct dt_object *child,
4299                         umode_t child_mode)
4300 {
4301         struct lod_device *d = lu2lod_dev(child->do_lu.lo_dev);
4302         struct lod_thread_info *info = lod_env_info(env);
4303         struct lod_default_striping *lds = &info->lti_def_striping;
4304         struct dt_object *nextp = NULL;
4305         struct dt_object *nextc;
4306         struct lod_object *lp = NULL;
4307         struct lod_object *lc;
4308         struct lov_desc *desc;
4309         struct lod_layout_component *lod_comp;
4310         int rc;
4311         ENTRY;
4312
4313         LASSERT(child);
4314
4315         if (likely(parent)) {
4316                 nextp = dt_object_child(parent);
4317                 lp = lod_dt_obj(parent);
4318         }
4319
4320         nextc = dt_object_child(child);
4321         lc = lod_dt_obj(child);
4322
4323         LASSERT(!lod_obj_is_striped(child));
4324         /* default layout template may have been set on the regular file
4325          * when this is called from mdd_create_data() */
4326         if (S_ISREG(child_mode))
4327                 lod_free_comp_entries(lc);
4328
4329         if (!dt_object_exists(nextc))
4330                 nextc->do_ops->do_ah_init(env, ah, nextp, nextc, child_mode);
4331
4332         if (S_ISDIR(child_mode)) {
4333                 const struct lmv_user_md_v1 *lum1 = ah->dah_eadata;
4334
4335                 /* other default values are 0 */
4336                 lc->ldo_dir_stripe_offset = -1;
4337
4338                 /* get default striping from parent object */
4339                 if (likely(lp != NULL))
4340                         lod_get_default_striping(env, lp, lds);
4341
4342                 /* set child default striping info, default value is NULL */
4343                 if (lds->lds_def_striping_set || lds->lds_dir_def_striping_set)
4344                         lc->ldo_def_striping = lds;
4345
4346                 /* It should always honour the specified stripes */
4347                 /* Note: old client (< 2.7)might also do lfs mkdir, whose EA
4348                  * will have old magic. In this case, we should ignore the
4349                  * stripe count and try to create dir by default stripe.
4350                  */
4351                 if (ah->dah_eadata != NULL && ah->dah_eadata_len != 0 &&
4352                     (le32_to_cpu(lum1->lum_magic) == LMV_USER_MAGIC ||
4353                      le32_to_cpu(lum1->lum_magic) == LMV_USER_MAGIC_SPECIFIC)) {
4354                         lc->ldo_dir_stripe_count =
4355                                 le32_to_cpu(lum1->lum_stripe_count);
4356                         lc->ldo_dir_stripe_offset =
4357                                 le32_to_cpu(lum1->lum_stripe_offset);
4358                         lc->ldo_dir_hash_type =
4359                                 le32_to_cpu(lum1->lum_hash_type);
4360                         CDEBUG(D_INFO,
4361                                "set dirstripe: count %hu, offset %d, hash %u\n",
4362                                 lc->ldo_dir_stripe_count,
4363                                 (int)lc->ldo_dir_stripe_offset,
4364                                 lc->ldo_dir_hash_type);
4365                 } else {
4366                         /* transfer defaults LMV to new directory */
4367                         lod_striping_from_default(lc, lds, child_mode);
4368                 }
4369
4370                 /* shrink the stripe_count to the avaible MDT count */
4371                 if (lc->ldo_dir_stripe_count > d->lod_remote_mdt_count + 1 &&
4372                     !OBD_FAIL_CHECK(OBD_FAIL_LARGE_STRIPE))
4373                         lc->ldo_dir_stripe_count = d->lod_remote_mdt_count + 1;
4374
4375                 /* Directory will be striped only if stripe_count > 1, if
4376                  * stripe_count == 1, let's reset stripe_count = 0 to avoid
4377                  * create single master stripe and also help to unify the
4378                  * stripe handling of directories and files */
4379                 if (lc->ldo_dir_stripe_count == 1)
4380                         lc->ldo_dir_stripe_count = 0;
4381
4382                 CDEBUG(D_INFO, "final dir stripe [%hu %d %u]\n",
4383                        lc->ldo_dir_stripe_count,
4384                        (int)lc->ldo_dir_stripe_offset, lc->ldo_dir_hash_type);
4385
4386                 RETURN_EXIT;
4387         }
4388
4389         /* child object regular file*/
4390
4391         if (!lod_object_will_be_striped(S_ISREG(child_mode),
4392                                         lu_object_fid(&child->do_lu)))
4393                 RETURN_EXIT;
4394
4395         /* If object is going to be striped over OSTs, transfer default
4396          * striping information to the child, so that we can use it
4397          * during declaration and creation.
4398          *
4399          * Try from the parent first.
4400          */
4401         if (likely(lp != NULL)) {
4402                 rc = lod_get_default_lov_striping(env, lp, lds);
4403                 if (rc == 0)
4404                         lod_striping_from_default(lc, lds, child_mode);
4405         }
4406
4407         /* Initialize lod_device::lod_md_root object reference */
4408         if (d->lod_md_root == NULL) {
4409                 struct dt_object *root;
4410                 struct lod_object *lroot;
4411
4412                 lu_root_fid(&info->lti_fid);
4413                 root = dt_locate(env, &d->lod_dt_dev, &info->lti_fid);
4414                 if (!IS_ERR(root)) {
4415                         lroot = lod_dt_obj(root);
4416
4417                         spin_lock(&d->lod_lock);
4418                         if (d->lod_md_root != NULL)
4419                                 dt_object_put(env, &d->lod_md_root->ldo_obj);
4420                         d->lod_md_root = lroot;
4421                         spin_unlock(&d->lod_lock);
4422                 }
4423         }
4424
4425         /* try inherit layout from the root object (fs default) when:
4426          *  - parent does not have default layout; or
4427          *  - parent has plain(v1/v3) default layout, and some attributes
4428          *    are not specified in the default layout;
4429          */
4430         if (d->lod_md_root != NULL && lod_need_inherit_more(lc, true)) {
4431                 rc = lod_get_default_lov_striping(env, d->lod_md_root, lds);
4432                 if (rc)
4433                         goto out;
4434                 if (lc->ldo_comp_cnt == 0) {
4435                         lod_striping_from_default(lc, lds, child_mode);
4436                 } else if (!lds->lds_def_striping_is_composite) {
4437                         struct lod_layout_component *def_comp;
4438
4439                         LASSERT(!lc->ldo_is_composite);
4440                         lod_comp = &lc->ldo_comp_entries[0];
4441                         def_comp = &lds->lds_def_comp_entries[0];
4442
4443                         if (lod_comp->llc_stripe_count <= 0)
4444                                 lod_comp->llc_stripe_count =
4445                                         def_comp->llc_stripe_count;
4446                         if (lod_comp->llc_stripe_size <= 0)
4447                                 lod_comp->llc_stripe_size =
4448                                         def_comp->llc_stripe_size;
4449                         if (lod_comp->llc_stripe_offset == LOV_OFFSET_DEFAULT)
4450                                 lod_comp->llc_stripe_offset =
4451                                         def_comp->llc_stripe_offset;
4452                         if (lod_comp->llc_pool == NULL)
4453                                 lod_obj_set_pool(lc, 0, def_comp->llc_pool);
4454                 }
4455         }
4456 out:
4457         /*
4458          * fs default striping may not be explicitly set, or historically set
4459          * in config log, use them.
4460          */
4461         if (lod_need_inherit_more(lc, false)) {
4462                 if (lc->ldo_comp_cnt == 0) {
4463                         rc = lod_alloc_comp_entries(lc, 0, 1);
4464                         if (rc)
4465                                 /* fail to allocate memory, will create a
4466                                  * non-striped file. */
4467                                 RETURN_EXIT;
4468                         lc->ldo_is_composite = 0;
4469                         lod_comp = &lc->ldo_comp_entries[0];
4470                         lod_comp->llc_stripe_offset = LOV_OFFSET_DEFAULT;
4471                 }
4472                 LASSERT(!lc->ldo_is_composite);
4473                 lod_comp = &lc->ldo_comp_entries[0];
4474                 desc = &d->lod_desc;
4475                 lod_adjust_stripe_info(lod_comp, desc);
4476         }
4477
4478         EXIT;
4479 }
4480
4481 #define ll_do_div64(aaa,bbb)    do_div((aaa), (bbb))
4482 /**
4483  * Size initialization on late striping.
4484  *
4485  * Propagate the size of a truncated object to a deferred striping.
4486  * This function handles a special case when truncate was done on a
4487  * non-striped object and now while the striping is being created
4488  * we can't lose that size, so we have to propagate it to the stripes
4489  * being created.
4490  *
4491  * \param[in] env       execution environment
4492  * \param[in] dt        object
4493  * \param[in] th        transaction handle
4494  *
4495  * \retval              0 on success
4496  * \retval              negative if failed
4497  */
4498 static int lod_declare_init_size(const struct lu_env *env,
4499                                  struct dt_object *dt, struct thandle *th)
4500 {
4501         struct dt_object        *next = dt_object_child(dt);
4502         struct lod_object       *lo = lod_dt_obj(dt);
4503         struct dt_object        **objects = NULL;
4504         struct lu_attr  *attr = &lod_env_info(env)->lti_attr;
4505         uint64_t        size, offs;
4506         int     i, rc, stripe, stripe_count = 0, stripe_size = 0;
4507         struct lu_extent size_ext;
4508         ENTRY;
4509
4510         if (!lod_obj_is_striped(dt))
4511                 RETURN(0);
4512
4513         rc = dt_attr_get(env, next, attr);
4514         LASSERT(attr->la_valid & LA_SIZE);
4515         if (rc)
4516                 RETURN(rc);
4517
4518         size = attr->la_size;
4519         if (size == 0)
4520                 RETURN(0);
4521
4522         size_ext = (typeof(size_ext)){ .e_start = size - 1, .e_end = size };
4523         for (i = 0; i < lo->ldo_comp_cnt; i++) {
4524                 struct lod_layout_component *lod_comp;
4525                 struct lu_extent *extent;
4526
4527                 lod_comp = &lo->ldo_comp_entries[i];
4528
4529                 if (lod_comp->llc_stripe == NULL)
4530                         continue;
4531
4532                 extent = &lod_comp->llc_extent;
4533                 CDEBUG(D_INFO, "%lld "DEXT"\n", size, PEXT(extent));
4534                 if (!lo->ldo_is_composite ||
4535                     lu_extent_is_overlapped(extent, &size_ext)) {
4536                         objects = lod_comp->llc_stripe;
4537                         stripe_count = lod_comp->llc_stripe_count;
4538                         stripe_size = lod_comp->llc_stripe_size;
4539
4540                         /* next mirror */
4541                         if (stripe_count == 0)
4542                                 continue;
4543
4544                         LASSERT(objects != NULL && stripe_size != 0);
4545                         /* ll_do_div64(a, b) returns a % b, and a = a / b */
4546                         ll_do_div64(size, (__u64)stripe_size);
4547                         stripe = ll_do_div64(size, (__u64)stripe_count);
4548                         LASSERT(objects[stripe] != NULL);
4549
4550                         size = size * stripe_size;
4551                         offs = attr->la_size;
4552                         size += ll_do_div64(offs, stripe_size);
4553
4554                         attr->la_valid = LA_SIZE;
4555                         attr->la_size = size;
4556
4557                         rc = lod_sub_declare_attr_set(env, objects[stripe],
4558                                                       attr, th);
4559                 }
4560         }
4561
4562         RETURN(rc);
4563 }
4564
4565 /**
4566  * Declare creation of striped object.
4567  *
4568  * The function declares creation stripes for a regular object. The function
4569  * also declares whether the stripes will be created with non-zero size if
4570  * previously size was set non-zero on the master object. If object \a dt is
4571  * not local, then only fully defined striping can be applied in \a lovea.
4572  * Otherwise \a lovea can be in the form of pattern, see lod_qos_parse_config()
4573  * for the details.
4574  *
4575  * \param[in] env       execution environment
4576  * \param[in] dt        object
4577  * \param[in] attr      attributes the stripes will be created with
4578  * \param[in] lovea     a buffer containing striping description
4579  * \param[in] th        transaction handle
4580  *
4581  * \retval              0 on success
4582  * \retval              negative if failed
4583  */
4584 int lod_declare_striped_create(const struct lu_env *env, struct dt_object *dt,
4585                                struct lu_attr *attr,
4586                                const struct lu_buf *lovea, struct thandle *th)
4587 {
4588         struct lod_thread_info  *info = lod_env_info(env);
4589         struct dt_object        *next = dt_object_child(dt);
4590         struct lod_object       *lo = lod_dt_obj(dt);
4591         int                      rc;
4592         ENTRY;
4593
4594         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_ALLOC_OBDO))
4595                 GOTO(out, rc = -ENOMEM);
4596
4597         if (!dt_object_remote(next)) {
4598                 /* choose OST and generate appropriate objects */
4599                 rc = lod_prepare_create(env, lo, attr, lovea, th);
4600                 if (rc)
4601                         GOTO(out, rc);
4602
4603                 /*
4604                  * declare storage for striping data
4605                  */
4606                 info->lti_buf.lb_len = lod_comp_md_size(lo, false);
4607         } else {
4608                 /* LOD can not choose OST objects for remote objects, i.e.
4609                  * stripes must be ready before that. Right now, it can only
4610                  * happen during migrate, i.e. migrate process needs to create
4611                  * remote regular file (mdd_migrate_create), then the migrate
4612                  * process will provide stripeEA. */
4613                 LASSERT(lovea != NULL);
4614                 info->lti_buf = *lovea;
4615         }
4616
4617         rc = lod_sub_declare_xattr_set(env, next, &info->lti_buf,
4618                                        XATTR_NAME_LOV, 0, th);
4619         if (rc)
4620                 GOTO(out, rc);
4621
4622         /*
4623          * if striping is created with local object's size > 0,
4624          * we have to propagate this size to specific object
4625          * the case is possible only when local object was created previously
4626          */
4627         if (dt_object_exists(next))
4628                 rc = lod_declare_init_size(env, dt, th);
4629
4630 out:
4631         /* failed to create striping or to set initial size, let's reset
4632          * config so that others don't get confused */
4633         if (rc)
4634                 lod_striping_free(env, lo);
4635
4636         RETURN(rc);
4637 }
4638
4639 /**
4640  * Implementation of dt_object_operations::do_declare_create.
4641  *
4642  * The method declares creation of a new object. If the object will be striped,
4643  * then helper functions are called to find FIDs for the stripes, declare
4644  * creation of the stripes and declare initialization of the striping
4645  * information to be stored in the master object.
4646  *
4647  * \see dt_object_operations::do_declare_create() in the API description
4648  * for details.
4649  */
4650 static int lod_declare_create(const struct lu_env *env, struct dt_object *dt,
4651                               struct lu_attr *attr,
4652                               struct dt_allocation_hint *hint,
4653                               struct dt_object_format *dof, struct thandle *th)
4654 {
4655         struct dt_object   *next = dt_object_child(dt);
4656         struct lod_object  *lo = lod_dt_obj(dt);
4657         int                 rc;
4658         ENTRY;
4659
4660         LASSERT(dof);
4661         LASSERT(attr);
4662         LASSERT(th);
4663
4664         /*
4665          * first of all, we declare creation of local object
4666          */
4667         rc = lod_sub_declare_create(env, next, attr, hint, dof, th);
4668         if (rc != 0)
4669                 GOTO(out, rc);
4670
4671         /*
4672          * it's lod_ah_init() that has decided the object will be striped
4673          */
4674         if (dof->dof_type == DFT_REGULAR) {
4675                 /* callers don't want stripes */
4676                 /* XXX: all tricky interactions with ->ah_make_hint() decided
4677                  * to use striping, then ->declare_create() behaving differently
4678                  * should be cleaned */
4679                 if (dof->u.dof_reg.striped != 0)
4680                         rc = lod_declare_striped_create(env, dt, attr,
4681                                                         NULL, th);
4682         } else if (dof->dof_type == DFT_DIR) {
4683                 struct seq_server_site *ss;
4684                 struct lu_buf buf = { NULL };
4685                 struct lu_buf *lmu = NULL;
4686
4687                 ss = lu_site2seq(dt->do_lu.lo_dev->ld_site);
4688
4689                 /* If the parent has default stripeEA, and client
4690                  * did not find it before sending create request,
4691                  * then MDT will return -EREMOTE, and client will
4692                  * retrieve the default stripeEA and re-create the
4693                  * sub directory.
4694                  *
4695                  * Note: if dah_eadata != NULL, it means creating the
4696                  * striped directory with specified stripeEA, then it
4697                  * should ignore the default stripeEA */
4698                 if (hint != NULL && hint->dah_eadata == NULL) {
4699                         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_STALE_DIR_LAYOUT))
4700                                 GOTO(out, rc = -EREMOTE);
4701
4702                         if (lo->ldo_dir_stripe_offset == -1) {
4703                                 /* child and parent should be in the same MDT */
4704                                 if (hint->dah_parent != NULL &&
4705                                     dt_object_remote(hint->dah_parent))
4706                                         GOTO(out, rc = -EREMOTE);
4707                         } else if (lo->ldo_dir_stripe_offset !=
4708                                    ss->ss_node_id) {
4709                                 struct lod_device *lod;
4710                                 struct lod_tgt_descs *ltd;
4711                                 struct lod_tgt_desc *tgt = NULL;
4712                                 bool found_mdt = false;
4713                                 int i;
4714
4715                                 lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
4716                                 ltd = &lod->lod_mdt_descs;
4717                                 cfs_foreach_bit(ltd->ltd_tgt_bitmap, i) {
4718                                         tgt = LTD_TGT(ltd, i);
4719                                         if (tgt->ltd_index ==
4720                                                 lo->ldo_dir_stripe_offset) {
4721                                                 found_mdt = true;
4722                                                 break;
4723                                         }
4724                                 }
4725
4726                                 /* If the MDT indicated by stripe_offset can be
4727                                  * found, then tell client to resend the create
4728                                  * request to the correct MDT, otherwise return
4729                                  * error to client */
4730                                 if (found_mdt)
4731                                         GOTO(out, rc = -EREMOTE);
4732                                 else
4733                                         GOTO(out, rc = -EINVAL);
4734                         }
4735                 } else if (hint && hint->dah_eadata) {
4736                         lmu = &buf;
4737                         lmu->lb_buf = (void *)hint->dah_eadata;
4738                         lmu->lb_len = hint->dah_eadata_len;
4739                 }
4740
4741                 rc = lod_declare_dir_striping_create(env, dt, attr, lmu, dof,
4742                                                      th);
4743         }
4744 out:
4745         /* failed to create striping or to set initial size, let's reset
4746          * config so that others don't get confused */
4747         if (rc)
4748                 lod_striping_free(env, lo);
4749         RETURN(rc);
4750 }
4751
4752 /**
4753  * Generate component ID for new created component.
4754  *
4755  * \param[in] lo                LOD object
4756  * \param[in] comp_idx          index of ldo_comp_entries
4757  *
4758  * \retval                      component ID on success
4759  * \retval                      LCME_ID_INVAL on failure
4760  */
4761 static __u32 lod_gen_component_id(struct lod_object *lo,
4762                                   int mirror_id, int comp_idx)
4763 {
4764         struct lod_layout_component *lod_comp;
4765         __u32   id, start, end;
4766         int     i;
4767
4768         LASSERT(lo->ldo_comp_entries[comp_idx].llc_id == LCME_ID_INVAL);
4769
4770         lod_obj_inc_layout_gen(lo);
4771         id = lo->ldo_layout_gen;
4772         if (likely(id <= SEQ_ID_MAX))
4773                 RETURN(pflr_id(mirror_id, id & SEQ_ID_MASK));
4774
4775         /* Layout generation wraps, need to check collisions. */
4776         start = id & SEQ_ID_MASK;
4777         end = SEQ_ID_MAX;
4778 again:
4779         for (id = start; id <= end; id++) {
4780                 for (i = 0; i < lo->ldo_comp_cnt; i++) {
4781                         lod_comp = &lo->ldo_comp_entries[i];
4782                         if (pflr_id(mirror_id, id) == lod_comp->llc_id)
4783                                 break;
4784                 }
4785                 /* Found the ununsed ID */
4786                 if (i == lo->ldo_comp_cnt)
4787                         RETURN(pflr_id(mirror_id, id));
4788         }
4789         if (end == LCME_ID_MAX) {
4790                 start = 1;
4791                 end = min(lo->ldo_layout_gen & LCME_ID_MASK,
4792                           (__u32)(LCME_ID_MAX - 1));
4793                 goto again;
4794         }
4795
4796         RETURN(LCME_ID_INVAL);
4797 }
4798
4799 /**
4800  * Creation of a striped regular object.
4801  *
4802  * The function is called to create the stripe objects for a regular
4803  * striped file. This can happen at the initial object creation or
4804  * when the caller asks LOD to do so using ->do_xattr_set() method
4805  * (so called late striping). Notice all the information are already
4806  * prepared in the form of the list of objects (ldo_stripe field).
4807  * This is done during declare phase.
4808  *
4809  * \param[in] env       execution environment
4810  * \param[in] dt        object
4811  * \param[in] attr      attributes the stripes will be created with
4812  * \param[in] dof       format of stripes (see OSD API description)
4813  * \param[in] th        transaction handle
4814  *
4815  * \retval              0 on success
4816  * \retval              negative if failed
4817  */
4818 int lod_striped_create(const struct lu_env *env, struct dt_object *dt,
4819                        struct lu_attr *attr, struct dt_object_format *dof,
4820                        struct thandle *th)
4821 {
4822         struct lod_layout_component     *lod_comp;
4823         struct lod_object       *lo = lod_dt_obj(dt);
4824         __u16   mirror_id;
4825         int     rc = 0, i, j;
4826         ENTRY;
4827
4828         LASSERT(lo->ldo_comp_cnt != 0 && lo->ldo_comp_entries != NULL);
4829
4830         mirror_id = lo->ldo_mirror_count > 1 ? 1 : 0;
4831
4832         /* create all underlying objects */
4833         for (i = 0; i < lo->ldo_comp_cnt; i++) {
4834                 lod_comp = &lo->ldo_comp_entries[i];
4835
4836                 if (lod_comp->llc_extent.e_start == 0 && i > 0) /* new mirror */
4837                         ++mirror_id;
4838
4839                 if (lod_comp->llc_id == LCME_ID_INVAL) {
4840                         lod_comp->llc_id = lod_gen_component_id(lo,
4841                                                                 mirror_id, i);
4842                         if (lod_comp->llc_id == LCME_ID_INVAL)
4843                                 GOTO(out, rc = -ERANGE);
4844                 }
4845
4846                 if (lod_comp_inited(lod_comp))
4847                         continue;
4848
4849                 if (lod_comp->llc_pattern & LOV_PATTERN_F_RELEASED)
4850                         lod_comp_set_init(lod_comp);
4851
4852                 if (lov_pattern(lod_comp->llc_pattern) == LOV_PATTERN_MDT)
4853                         lod_comp_set_init(lod_comp);
4854
4855                 if (lod_comp->llc_stripe == NULL)
4856                         continue;
4857
4858                 LASSERT(lod_comp->llc_stripe_count);
4859                 for (j = 0; j < lod_comp->llc_stripe_count; j++) {
4860                         struct dt_object *object = lod_comp->llc_stripe[j];
4861                         LASSERT(object != NULL);
4862                         rc = lod_sub_create(env, object, attr, NULL, dof, th);
4863                         if (rc)
4864                                 GOTO(out, rc);
4865                 }
4866                 lod_comp_set_init(lod_comp);
4867         }
4868
4869         rc = lod_fill_mirrors(lo);
4870         if (rc)
4871                 GOTO(out, rc);
4872
4873         rc = lod_generate_and_set_lovea(env, lo, th);
4874         if (rc)
4875                 GOTO(out, rc);
4876
4877         lo->ldo_comp_cached = 1;
4878         RETURN(0);
4879
4880 out:
4881         lod_striping_free(env, lo);
4882         RETURN(rc);
4883 }
4884
4885 /**
4886  * Implementation of dt_object_operations::do_create.
4887  *
4888  * If any of preceeding methods (like ->do_declare_create(),
4889  * ->do_ah_init(), etc) chose to create a striped object,
4890  * then this method will create the master and the stripes.
4891  *
4892  * \see dt_object_operations::do_create() in the API description for details.
4893  */
4894 static int lod_create(const struct lu_env *env, struct dt_object *dt,
4895                       struct lu_attr *attr, struct dt_allocation_hint *hint,
4896                       struct dt_object_format *dof, struct thandle *th)
4897 {
4898         int                 rc;
4899         ENTRY;
4900
4901         /* create local object */
4902         rc = lod_sub_create(env, dt_object_child(dt), attr, hint, dof, th);
4903         if (rc != 0)
4904                 RETURN(rc);
4905
4906         if (S_ISREG(dt->do_lu.lo_header->loh_attr) &&
4907             lod_obj_is_striped(dt) && dof->u.dof_reg.striped != 0) {
4908                 LASSERT(lod_dt_obj(dt)->ldo_comp_cached == 0);
4909                 rc = lod_striped_create(env, dt, attr, dof, th);
4910         }
4911
4912         RETURN(rc);
4913 }
4914
4915 static inline int
4916 lod_obj_stripe_destroy_cb(const struct lu_env *env, struct lod_object *lo,
4917                           struct dt_object *dt, struct thandle *th,
4918                           int comp_idx, int stripe_idx,
4919                           struct lod_obj_stripe_cb_data *data)
4920 {
4921         if (data->locd_declare)
4922                 return lod_sub_declare_destroy(env, dt, th);
4923         else if (!OBD_FAIL_CHECK(OBD_FAIL_LFSCK_LOST_SPEOBJ) ||
4924                  stripe_idx == cfs_fail_val)
4925                 return lod_sub_destroy(env, dt, th);
4926         else
4927                 return 0;
4928 }
4929
4930 /**
4931  * Implementation of dt_object_operations::do_declare_destroy.
4932  *
4933  * If the object is a striped directory, then the function declares reference
4934  * removal from the master object (this is an index) to the stripes and declares
4935  * destroy of all the stripes. In all the cases, it declares an intention to
4936  * destroy the object itself.
4937  *
4938  * \see dt_object_operations::do_declare_destroy() in the API description
4939  * for details.
4940  */
4941 static int lod_declare_destroy(const struct lu_env *env, struct dt_object *dt,
4942                                struct thandle *th)
4943 {
4944         struct dt_object   *next = dt_object_child(dt);
4945         struct lod_object  *lo = lod_dt_obj(dt);
4946         struct lod_thread_info *info = lod_env_info(env);
4947         char               *stripe_name = info->lti_key;
4948         int                 rc, i;
4949         ENTRY;
4950
4951         /*
4952          * load striping information, notice we don't do this when object
4953          * is being initialized as we don't need this information till
4954          * few specific cases like destroy, chown
4955          */
4956         rc = lod_striping_load(env, lo);
4957         if (rc)
4958                 RETURN(rc);
4959
4960         /* declare destroy for all underlying objects */
4961         if (S_ISDIR(dt->do_lu.lo_header->loh_attr)) {
4962                 rc = next->do_ops->do_index_try(env, next,
4963                                                 &dt_directory_features);
4964                 if (rc != 0)
4965                         RETURN(rc);
4966
4967                 for (i = 0; i < lo->ldo_dir_stripe_count; i++) {
4968                         rc = lod_sub_declare_ref_del(env, next, th);
4969                         if (rc != 0)
4970                                 RETURN(rc);
4971
4972                         snprintf(stripe_name, sizeof(info->lti_key), DFID":%d",
4973                                 PFID(lu_object_fid(&lo->ldo_stripe[i]->do_lu)),
4974                                 i);
4975                         rc = lod_sub_declare_delete(env, next,
4976                                         (const struct dt_key *)stripe_name, th);
4977                         if (rc != 0)
4978                                 RETURN(rc);
4979                 }
4980         }
4981
4982         /*
4983          * we declare destroy for the local object
4984          */
4985         rc = lod_sub_declare_destroy(env, next, th);
4986         if (rc)
4987                 RETURN(rc);
4988
4989         if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_LOST_MDTOBJ) ||
4990             OBD_FAIL_CHECK(OBD_FAIL_LFSCK_LOST_MDTOBJ2))
4991                 RETURN(0);
4992
4993         if (!lod_obj_is_striped(dt))
4994                 RETURN(0);
4995
4996         /* declare destroy all striped objects */
4997         if (S_ISDIR(dt->do_lu.lo_header->loh_attr)) {
4998                 for (i = 0; i < lo->ldo_dir_stripe_count; i++) {
4999                         if (lo->ldo_stripe[i] == NULL)
5000                                 continue;
5001
5002                         rc = lod_sub_declare_ref_del(env, lo->ldo_stripe[i],
5003                                                      th);
5004
5005                         rc = lod_sub_declare_destroy(env, lo->ldo_stripe[i],
5006                                                      th);
5007                         if (rc != 0)
5008                                 break;
5009                 }
5010         } else {
5011                 struct lod_obj_stripe_cb_data data = { { 0 } };
5012
5013                 data.locd_declare = true;
5014                 data.locd_stripe_cb = lod_obj_stripe_destroy_cb;
5015                 rc = lod_obj_for_each_stripe(env, lo, th, &data);
5016         }
5017
5018         RETURN(rc);
5019 }
5020
5021 /**
5022  * Implementation of dt_object_operations::do_destroy.
5023  *
5024  * If the object is a striped directory, then the function removes references
5025  * from the master object (this is an index) to the stripes and destroys all
5026  * the stripes. In all the cases, the function destroys the object itself.
5027  *
5028  * \see dt_object_operations::do_destroy() in the API description for details.
5029  */
5030 static int lod_destroy(const struct lu_env *env, struct dt_object *dt,
5031                        struct thandle *th)
5032 {
5033         struct dt_object  *next = dt_object_child(dt);
5034         struct lod_object *lo = lod_dt_obj(dt);
5035         struct lod_thread_info *info = lod_env_info(env);
5036         char               *stripe_name = info->lti_key;
5037         unsigned int       i;
5038         int                rc;
5039         ENTRY;
5040
5041         /* destroy sub-stripe of master object */
5042         if (S_ISDIR(dt->do_lu.lo_header->loh_attr)) {
5043                 rc = next->do_ops->do_index_try(env, next,
5044                                                 &dt_directory_features);
5045                 if (rc != 0)
5046                         RETURN(rc);
5047
5048                 for (i = 0; i < lo->ldo_dir_stripe_count; i++) {
5049                         rc = lod_sub_ref_del(env, next, th);
5050                         if (rc != 0)
5051                                 RETURN(rc);
5052
5053                         snprintf(stripe_name, sizeof(info->lti_key), DFID":%d",
5054                                 PFID(lu_object_fid(&lo->ldo_stripe[i]->do_lu)),
5055                                 i);
5056
5057                         CDEBUG(D_INFO, DFID" delete stripe %s "DFID"\n",
5058                                PFID(lu_object_fid(&dt->do_lu)), stripe_name,
5059                                PFID(lu_object_fid(&lo->ldo_stripe[i]->do_lu)));
5060
5061                         rc = lod_sub_delete(env, next,
5062                                        (const struct dt_key *)stripe_name, th);
5063                         if (rc != 0)
5064                                 RETURN(rc);
5065                 }
5066         }
5067
5068         rc = lod_sub_destroy(env, next, th);
5069         if (rc != 0)
5070                 RETURN(rc);
5071
5072         if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_LOST_MDTOBJ) ||
5073             OBD_FAIL_CHECK(OBD_FAIL_LFSCK_LOST_MDTOBJ2))
5074                 RETURN(0);
5075
5076         if (!lod_obj_is_striped(dt))
5077                 RETURN(0);
5078
5079         /* destroy all striped objects */
5080         if (S_ISDIR(dt->do_lu.lo_header->loh_attr)) {
5081                 for (i = 0; i < lo->ldo_dir_stripe_count; i++) {
5082                         if (lo->ldo_stripe[i] == NULL)
5083                                 continue;
5084                         if (!OBD_FAIL_CHECK(OBD_FAIL_LFSCK_LOST_SPEOBJ) ||
5085                             i == cfs_fail_val) {
5086                                 dt_write_lock(env, lo->ldo_stripe[i],
5087                                               MOR_TGT_CHILD);
5088                                 rc = lod_sub_ref_del(env, lo->ldo_stripe[i],
5089                                                      th);
5090                                 dt_write_unlock(env, lo->ldo_stripe[i]);
5091                                 if (rc != 0)
5092                                         break;
5093
5094                                 rc = lod_sub_destroy(env, lo->ldo_stripe[i],
5095                                                      th);
5096                                 if (rc != 0)
5097                                         break;
5098                         }
5099                 }
5100         } else {
5101                 struct lod_obj_stripe_cb_data data = { { 0 } };
5102
5103                 data.locd_declare = false;
5104                 data.locd_stripe_cb = lod_obj_stripe_destroy_cb;
5105                 rc = lod_obj_for_each_stripe(env, lo, th, &data);
5106         }
5107
5108         RETURN(rc);
5109 }
5110
5111 /**
5112  * Implementation of dt_object_operations::do_declare_ref_add.
5113  *
5114  * \see dt_object_operations::do_declare_ref_add() in the API description
5115  * for details.
5116  */
5117 static int lod_declare_ref_add(const struct lu_env *env,
5118                                struct dt_object *dt, struct thandle *th)
5119 {
5120         return lod_sub_declare_ref_add(env, dt_object_child(dt), th);
5121 }
5122
5123 /**
5124  * Implementation of dt_object_operations::do_ref_add.
5125  *
5126  * \see dt_object_operations::do_ref_add() in the API description for details.
5127  */
5128 static int lod_ref_add(const struct lu_env *env,
5129                        struct dt_object *dt, struct thandle *th)
5130 {
5131         return lod_sub_ref_add(env, dt_object_child(dt), th);
5132 }
5133
5134 /**
5135  * Implementation of dt_object_operations::do_declare_ref_del.
5136  *
5137  * \see dt_object_operations::do_declare_ref_del() in the API description
5138  * for details.
5139  */
5140 static int lod_declare_ref_del(const struct lu_env *env,
5141                                struct dt_object *dt, struct thandle *th)
5142 {
5143         return lod_sub_declare_ref_del(env, dt_object_child(dt), th);
5144 }
5145
5146 /**
5147  * Implementation of dt_object_operations::do_ref_del
5148  *
5149  * \see dt_object_operations::do_ref_del() in the API description for details.
5150  */
5151 static int lod_ref_del(const struct lu_env *env,
5152                        struct dt_object *dt, struct thandle *th)
5153 {
5154         return lod_sub_ref_del(env, dt_object_child(dt), th);
5155 }
5156
5157 /**
5158  * Implementation of dt_object_operations::do_object_sync.
5159  *
5160  * \see dt_object_operations::do_object_sync() in the API description
5161  * for details.
5162  */
5163 static int lod_object_sync(const struct lu_env *env, struct dt_object *dt,
5164                            __u64 start, __u64 end)
5165 {
5166         return dt_object_sync(env, dt_object_child(dt), start, end);
5167 }
5168
5169 /**
5170  * Implementation of dt_object_operations::do_object_unlock.
5171  *
5172  * Used to release LDLM lock(s).
5173  *
5174  * \see dt_object_operations::do_object_unlock() in the API description
5175  * for details.
5176  */
5177 static int lod_object_unlock(const struct lu_env *env, struct dt_object *dt,
5178                              struct ldlm_enqueue_info *einfo,
5179                              union ldlm_policy_data *policy)
5180 {
5181         struct lod_object *lo = lod_dt_obj(dt);
5182         struct lustre_handle_array *slave_locks = einfo->ei_cbdata;
5183         int slave_locks_size;
5184         int i;
5185         ENTRY;
5186
5187         if (slave_locks == NULL)
5188                 RETURN(0);
5189
5190         LASSERT(S_ISDIR(dt->do_lu.lo_header->loh_attr));
5191         LASSERT(lo->ldo_dir_stripe_count > 1);
5192         /* Note: for remote lock for single stripe dir, MDT will cancel
5193          * the lock by lockh directly */
5194         LASSERT(!dt_object_remote(dt_object_child(dt)));
5195
5196         /* locks were unlocked in MDT layer */
5197         for (i = 0; i < slave_locks->ha_count; i++)
5198                 LASSERT(!lustre_handle_is_used(&slave_locks->ha_handles[i]));
5199
5200         /*
5201          * NB, ha_count may not equal to ldo_dir_stripe_count, because dir
5202          * layout may change, e.g., shrink dir layout after migration.
5203          */
5204         for (i = 0; i < lo->ldo_dir_stripe_count; i++)
5205                 dt_invalidate(env, lo->ldo_stripe[i]);
5206
5207         slave_locks_size = offsetof(typeof(*slave_locks),
5208                                     ha_handles[slave_locks->ha_count]);
5209         OBD_FREE(slave_locks, slave_locks_size);
5210         einfo->ei_cbdata = NULL;
5211
5212         RETURN(0);
5213 }
5214
5215 /**
5216  * Implementation of dt_object_operations::do_object_lock.
5217  *
5218  * Used to get LDLM lock on the non-striped and striped objects.
5219  *
5220  * \see dt_object_operations::do_object_lock() in the API description
5221  * for details.
5222  */
5223 static int lod_object_lock(const struct lu_env *env,
5224                            struct dt_object *dt,
5225                            struct lustre_handle *lh,
5226                            struct ldlm_enqueue_info *einfo,
5227                            union ldlm_policy_data *policy)
5228 {
5229         struct lod_object *lo = lod_dt_obj(dt);
5230         int slave_locks_size;
5231         struct lustre_handle_array *slave_locks = NULL;
5232         int i;
5233         int rc;
5234         ENTRY;
5235
5236         /* remote object lock */
5237         if (!einfo->ei_enq_slave) {
5238                 LASSERT(dt_object_remote(dt));
5239                 return dt_object_lock(env, dt_object_child(dt), lh, einfo,
5240                                       policy);
5241         }
5242
5243         if (!S_ISDIR(dt->do_lu.lo_header->loh_attr))
5244                 RETURN(-ENOTDIR);
5245
5246         rc = lod_striping_load(env, lo);
5247         if (rc != 0)
5248                 RETURN(rc);
5249
5250         /* No stripes */
5251         if (lo->ldo_dir_stripe_count <= 1)
5252                 RETURN(0);
5253
5254         slave_locks_size = offsetof(typeof(*slave_locks),
5255                                     ha_handles[lo->ldo_dir_stripe_count]);
5256         /* Freed in lod_object_unlock */
5257         OBD_ALLOC(slave_locks, slave_locks_size);
5258         if (!slave_locks)
5259                 RETURN(-ENOMEM);
5260         slave_locks->ha_count = lo->ldo_dir_stripe_count;
5261
5262         /* striped directory lock */
5263         for (i = 0; i < lo->ldo_dir_stripe_count; i++) {
5264                 struct lustre_handle lockh;
5265                 struct ldlm_res_id *res_id;
5266
5267                 res_id = &lod_env_info(env)->lti_res_id;
5268                 fid_build_reg_res_name(lu_object_fid(&lo->ldo_stripe[i]->do_lu),
5269                                        res_id);
5270                 einfo->ei_res_id = res_id;
5271
5272                 LASSERT(lo->ldo_stripe[i] != NULL);
5273                 if (dt_object_remote(lo->ldo_stripe[i])) {
5274                         set_bit(i, (void *)slave_locks->ha_map);
5275                         rc = dt_object_lock(env, lo->ldo_stripe[i], &lockh,
5276                                             einfo, policy);
5277                 } else {
5278                         struct ldlm_namespace *ns = einfo->ei_namespace;
5279                         ldlm_blocking_callback blocking = einfo->ei_cb_local_bl;
5280                         ldlm_completion_callback completion = einfo->ei_cb_cp;
5281                         __u64 dlmflags = LDLM_FL_ATOMIC_CB;
5282
5283                         if (einfo->ei_mode == LCK_PW ||
5284                             einfo->ei_mode == LCK_EX)
5285                                 dlmflags |= LDLM_FL_COS_INCOMPAT;
5286
5287                         LASSERT(ns != NULL);
5288                         rc = ldlm_cli_enqueue_local(ns, res_id, LDLM_IBITS,
5289                                                     policy, einfo->ei_mode,
5290                                                     &dlmflags, blocking,
5291                                                     completion, NULL,
5292                                                     NULL, 0, LVB_T_NONE,
5293                                                     NULL, &lockh);
5294                 }
5295                 if (rc) {
5296                         while (i--)
5297                                 ldlm_lock_decref_and_cancel(
5298                                                 &slave_locks->ha_handles[i],
5299                                                 einfo->ei_mode);
5300                         OBD_FREE(slave_locks, slave_locks_size);
5301                         RETURN(rc);
5302                 }
5303                 slave_locks->ha_handles[i] = lockh;
5304         }
5305         einfo->ei_cbdata = slave_locks;
5306
5307         RETURN(0);
5308 }
5309
5310 /**
5311  * Implementation of dt_object_operations::do_invalidate.
5312  *
5313  * \see dt_object_operations::do_invalidate() in the API description for details
5314  */
5315 static int lod_invalidate(const struct lu_env *env, struct dt_object *dt)
5316 {
5317         return dt_invalidate(env, dt_object_child(dt));
5318 }
5319
5320 static int lod_layout_data_init(struct lod_thread_info *info, __u32 comp_cnt)
5321 {
5322         ENTRY;
5323
5324         /* clear memory region that will be used for layout change */
5325         memset(&info->lti_layout_attr, 0, sizeof(struct lu_attr));
5326         info->lti_count = 0;
5327
5328         if (info->lti_comp_size >= comp_cnt)
5329                 RETURN(0);
5330
5331         if (info->lti_comp_size > 0) {
5332                 OBD_FREE(info->lti_comp_idx,
5333                          info->lti_comp_size * sizeof(__u32));
5334                 info->lti_comp_size = 0;
5335         }
5336
5337         OBD_ALLOC(info->lti_comp_idx, comp_cnt * sizeof(__u32));
5338         if (!info->lti_comp_idx)
5339                 RETURN(-ENOMEM);
5340
5341         info->lti_comp_size = comp_cnt;
5342         RETURN(0);
5343 }
5344
5345 static int lod_declare_instantiate_components(const struct lu_env *env,
5346                 struct lod_object *lo, struct thandle *th)
5347 {
5348         struct lod_thread_info *info = lod_env_info(env);
5349         struct ost_pool *inuse = &info->lti_inuse_osts;
5350         int i;
5351         int rc = 0;
5352         ENTRY;
5353
5354         LASSERT(info->lti_count < lo->ldo_comp_cnt);
5355         if (info->lti_count > 0) {
5356                 /* Prepare inuse array for composite file */
5357                 rc = lod_prepare_inuse(env, lo);
5358                 if (rc)
5359                         RETURN(rc);
5360         }
5361
5362         for (i = 0; i < info->lti_count; i++) {
5363                 rc = lod_qos_prep_create(env, lo, NULL, th,
5364                                          info->lti_comp_idx[i], inuse);
5365                 if (rc)
5366                         break;
5367         }
5368
5369         if (!rc) {
5370                 info->lti_buf.lb_len = lod_comp_md_size(lo, false);
5371                 rc = lod_sub_declare_xattr_set(env, lod_object_child(lo),
5372                                 &info->lti_buf, XATTR_NAME_LOV, 0, th);
5373         }
5374
5375         RETURN(rc);
5376 }
5377
5378 static int lod_declare_update_plain(const struct lu_env *env,
5379                 struct lod_object *lo, struct layout_intent *layout,
5380                 const struct lu_buf *buf, struct thandle *th)
5381 {
5382         struct lod_thread_info *info = lod_env_info(env);
5383         struct lod_device *d = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
5384         struct lod_layout_component *lod_comp;
5385         struct lov_comp_md_v1 *comp_v1 = NULL;
5386         bool replay = false;
5387         int i, rc;
5388         ENTRY;
5389
5390         LASSERT(lo->ldo_flr_state == LCM_FL_NONE);
5391
5392         /*
5393          * In case the client is passing lovea, which only happens during
5394          * the replay of layout intent write RPC for now, we may need to
5395          * parse the lovea and apply new layout configuration.
5396          */
5397         if (buf && buf->lb_len)  {
5398                 struct lov_user_md_v1 *v1 = buf->lb_buf;
5399
5400                 if (v1->lmm_magic != (LOV_MAGIC_DEFINED | LOV_MAGIC_COMP_V1) &&
5401                     v1->lmm_magic != __swab32(LOV_MAGIC_DEFINED |
5402                                               LOV_MAGIC_COMP_V1)) {
5403                         CERROR("%s: the replay buffer of layout extend "
5404                                "(magic %#x) does not contain expected "
5405                                "composite layout.\n",
5406                                lod2obd(d)->obd_name, v1->lmm_magic);
5407                         GOTO(out, rc = -EINVAL);
5408                 }
5409
5410                 rc = lod_use_defined_striping(env, lo, buf);
5411                 if (rc)
5412                         GOTO(out, rc);
5413
5414                 rc = lod_get_lov_ea(env, lo);
5415                 if (rc <= 0)
5416                         GOTO(out, rc);
5417                 /* old on-disk EA is stored in info->lti_buf */
5418                 comp_v1 = (struct lov_comp_md_v1 *)info->lti_buf.lb_buf;
5419                 replay = true;
5420         } else {
5421                 /* non replay path */
5422                 rc = lod_striping_load(env, lo);
5423                 if (rc)
5424                         GOTO(out, rc);
5425         }
5426
5427         /* Make sure defined layout covers the requested write range. */
5428         lod_comp = &lo->ldo_comp_entries[lo->ldo_comp_cnt - 1];
5429         if (lo->ldo_comp_cnt > 1 &&
5430             lod_comp->llc_extent.e_end != OBD_OBJECT_EOF &&
5431             lod_comp->llc_extent.e_end < layout->li_extent.e_end) {
5432                 CDEBUG(replay ? D_ERROR : D_LAYOUT,
5433                        "%s: the defined layout [0, %#llx) does not covers "
5434                        "the write range "DEXT"\n",
5435                        lod2obd(d)->obd_name, lod_comp->llc_extent.e_end,
5436                        PEXT(&layout->li_extent));
5437                 GOTO(out, rc = -EINVAL);
5438         }
5439
5440         CDEBUG(D_LAYOUT, "%s: "DFID": instantiate components "DEXT"\n",
5441                lod2obd(d)->obd_name, PFID(lod_object_fid(lo)),
5442                PEXT(&layout->li_extent));
5443
5444         /*
5445          * Iterate ld->ldo_comp_entries, find the component whose extent under
5446          * the write range and not instantianted.
5447          */
5448         for (i = 0; i < lo->ldo_comp_cnt; i++) {
5449                 lod_comp = &lo->ldo_comp_entries[i];
5450
5451                 if (lod_comp->llc_extent.e_start >= layout->li_extent.e_end)
5452                         break;
5453
5454                 if (!replay) {
5455                         if (lod_comp_inited(lod_comp))
5456                                 continue;
5457                 } else {
5458                         /**
5459                          * In replay path, lod_comp is the EA passed by
5460                          * client replay buffer,  comp_v1 is the pre-recovery
5461                          * on-disk EA, we'd sift out those components which
5462                          * were init-ed in the on-disk EA.
5463                          */
5464                         if (le32_to_cpu(comp_v1->lcm_entries[i].lcme_flags) &
5465                             LCME_FL_INIT)
5466                                 continue;
5467                 }
5468                 /*
5469                  * this component hasn't instantiated in normal path, or during
5470                  * replay it needs replay the instantiation.
5471                  */
5472
5473                 /* A released component is being extended */
5474                 if (lod_comp->llc_pattern & LOV_PATTERN_F_RELEASED)
5475                         GOTO(out, rc = -EINVAL);
5476
5477                 LASSERT(info->lti_comp_idx != NULL);
5478                 info->lti_comp_idx[info->lti_count++] = i;
5479         }
5480
5481         if (info->lti_count == 0)
5482                 RETURN(-EALREADY);
5483
5484         lod_obj_inc_layout_gen(lo);
5485         rc = lod_declare_instantiate_components(env, lo, th);
5486 out:
5487         if (rc)
5488                 lod_striping_free(env, lo);
5489         RETURN(rc);
5490 }
5491
5492 static inline int lod_comp_index(struct lod_object *lo,
5493                                  struct lod_layout_component *lod_comp)
5494 {
5495         LASSERT(lod_comp >= lo->ldo_comp_entries &&
5496                 lod_comp <= &lo->ldo_comp_entries[lo->ldo_comp_cnt - 1]);
5497
5498         return lod_comp - lo->ldo_comp_entries;
5499 }
5500
5501 /**
5502  * Stale other mirrors by writing extent.
5503  */
5504 static void lod_stale_components(struct lod_object *lo, int primary,
5505                                  struct lu_extent *extent)
5506 {
5507         struct lod_layout_component *pri_comp, *lod_comp;
5508         int i;
5509
5510         /* The writing extent decides which components in the primary
5511          * are affected... */
5512         CDEBUG(D_LAYOUT, "primary mirror %d, "DEXT"\n", primary, PEXT(extent));
5513         lod_foreach_mirror_comp(pri_comp, lo, primary) {
5514                 if (!lu_extent_is_overlapped(extent, &pri_comp->llc_extent))
5515                         continue;
5516
5517                 CDEBUG(D_LAYOUT, "primary comp %u "DEXT"\n",
5518                        lod_comp_index(lo, pri_comp),
5519                        PEXT(&pri_comp->llc_extent));
5520
5521                 for (i = 0; i < lo->ldo_mirror_count; i++) {
5522                         if (i == primary)
5523                                 continue;
5524
5525                         /* ... and then stale other components that are
5526                          * overlapping with primary components */
5527                         lod_foreach_mirror_comp(lod_comp, lo, i) {
5528                                 if (!lu_extent_is_overlapped(
5529                                                         &pri_comp->llc_extent,
5530                                                         &lod_comp->llc_extent))
5531                                         continue;
5532
5533                                 CDEBUG(D_LAYOUT, "stale: %u / %u\n",
5534                                       i, lod_comp_index(lo, lod_comp));
5535
5536                                 lod_comp->llc_flags |= LCME_FL_STALE;
5537                                 lo->ldo_mirrors[i].lme_stale = 1;
5538                         }
5539                 }
5540         }
5541 }
5542
5543 /**
5544  * check an OST's availability
5545  * \param[in] env       execution environment
5546  * \param[in] lo        lod object
5547  * \param[in] dt        dt object
5548  * \param[in] index     mirror index
5549  *
5550  * \retval      negative if failed
5551  * \retval      1 if \a dt is available
5552  * \retval      0 if \a dt is not available
5553  */
5554 static inline int lod_check_ost_avail(const struct lu_env *env,
5555                                       struct lod_object *lo,
5556                                       struct dt_object *dt, int index)
5557 {
5558         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
5559         struct lod_tgt_desc *ost;
5560         __u32 idx;
5561         int type = LU_SEQ_RANGE_OST;
5562         int rc;
5563
5564         rc = lod_fld_lookup(env, lod, lu_object_fid(&dt->do_lu), &idx, &type);
5565         if (rc < 0) {
5566                 CERROR("%s: can't locate "DFID":rc = %d\n",
5567                        lod2obd(lod)->obd_name, PFID(lu_object_fid(&dt->do_lu)),
5568                        rc);
5569                 return rc;
5570         }
5571
5572         ost = OST_TGT(lod, idx);
5573         if (ost->ltd_statfs.os_state &
5574                 (OS_STATE_READONLY | OS_STATE_ENOSPC | OS_STATE_ENOINO |
5575                  OS_STATE_NOPRECREATE) ||
5576             ost->ltd_active == 0) {
5577                 CDEBUG(D_LAYOUT, DFID ": mirror %d OST%d unavail, rc = %d\n",
5578                        PFID(lod_object_fid(lo)), index, idx, rc);
5579                 return 0;
5580         }
5581
5582         return 1;
5583 }
5584
5585 /**
5586  * Pick primary mirror for write
5587  * \param[in] env       execution environment
5588  * \param[in] lo        object
5589  * \param[in] extent    write range
5590  */
5591 static int lod_primary_pick(const struct lu_env *env, struct lod_object *lo,
5592                             struct lu_extent *extent)
5593 {
5594         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
5595         unsigned int seq = 0;
5596         struct lod_layout_component *lod_comp;
5597         int i, j, rc;
5598         int picked = -1, second_pick = -1, third_pick = -1;
5599         ENTRY;
5600
5601         if (OBD_FAIL_CHECK(OBD_FAIL_FLR_RANDOM_PICK_MIRROR)) {
5602                 get_random_bytes(&seq, sizeof(seq));
5603                 seq %= lo->ldo_mirror_count;
5604         }
5605
5606         /**
5607          * Pick a mirror as the primary, and check the availability of OSTs.
5608          *
5609          * This algo can be revised later after knowing the topology of
5610          * cluster.
5611          */
5612         lod_qos_statfs_update(env, lod);
5613         for (i = 0; i < lo->ldo_mirror_count; i++) {
5614                 bool ost_avail = true;
5615                 int index = (i + seq) % lo->ldo_mirror_count;
5616
5617                 if (lo->ldo_mirrors[index].lme_stale) {
5618                         CDEBUG(D_LAYOUT, DFID": mirror %d stale\n",
5619                                PFID(lod_object_fid(lo)), index);
5620                         continue;
5621                 }
5622
5623                 /* 2nd pick is for the primary mirror containing unavail OST */
5624                 if (lo->ldo_mirrors[index].lme_primary && second_pick < 0)
5625                         second_pick = index;
5626
5627                 /* 3rd pick is for non-primary mirror containing unavail OST */
5628                 if (second_pick < 0 && third_pick < 0)
5629                         third_pick = index;
5630
5631                 /**
5632                  * we found a non-primary 1st pick, we'd like to find a
5633                  * potential pirmary mirror.
5634                  */
5635                 if (picked >= 0 && !lo->ldo_mirrors[index].lme_primary)
5636                         continue;
5637
5638                 /* check the availability of OSTs */
5639                 lod_foreach_mirror_comp(lod_comp, lo, index) {
5640                         if (!lod_comp_inited(lod_comp) || !lod_comp->llc_stripe)
5641                                 continue;
5642
5643                         for (j = 0; j < lod_comp->llc_stripe_count; j++) {
5644                                 struct dt_object *dt = lod_comp->llc_stripe[j];
5645
5646                                 rc = lod_check_ost_avail(env, lo, dt, index);
5647                                 if (rc < 0)
5648                                         RETURN(rc);
5649
5650                                 ost_avail = !!rc;
5651                                 if (!ost_avail)
5652                                         break;
5653                         } /* for all dt object in one component */
5654                         if (!ost_avail)
5655                                 break;
5656                 } /* for all components in a mirror */
5657
5658                 /**
5659                  * the OSTs where allocated objects locates in the components
5660                  * of the mirror are available.
5661                  */
5662                 if (!ost_avail)
5663                         continue;
5664
5665                 /* this mirror has all OSTs available */
5666                 picked = index;
5667
5668                 /**
5669                  * primary with all OSTs are available, this is the perfect
5670                  * 1st pick.
5671                  */
5672                 if (lo->ldo_mirrors[index].lme_primary)
5673                         break;
5674         } /* for all mirrors */
5675
5676         /* failed to pick a sound mirror, lower our expectation */
5677         if (picked < 0)
5678                 picked = second_pick;
5679         if (picked < 0)
5680                 picked = third_pick;
5681         if (picked < 0)
5682                 RETURN(-ENODATA);
5683
5684         RETURN(picked);
5685 }
5686
5687 /**
5688  * figure out the components should be instantiated for resync.
5689  */
5690 static int lod_prepare_resync(const struct lu_env *env, struct lod_object *lo,
5691                               struct lu_extent *extent)
5692 {
5693         struct lod_thread_info *info = lod_env_info(env);
5694         struct lod_layout_component *lod_comp;
5695         unsigned int need_sync = 0;
5696         int i;
5697
5698         CDEBUG(D_LAYOUT,
5699                DFID": instantiate all stale components in "DEXT"\n",
5700                PFID(lod_object_fid(lo)), PEXT(extent));
5701
5702         /**
5703          * instantiate all components within this extent, even non-stale
5704          * components.
5705          */
5706         for (i = 0; i < lo->ldo_mirror_count; i++) {
5707                 if (!lo->ldo_mirrors[i].lme_stale)
5708                         continue;
5709
5710                 lod_foreach_mirror_comp(lod_comp, lo, i) {
5711                         if (!lu_extent_is_overlapped(extent,
5712                                                 &lod_comp->llc_extent))
5713                                 break;
5714
5715                         need_sync++;
5716
5717                         if (lod_comp_inited(lod_comp))
5718                                 continue;
5719
5720                         CDEBUG(D_LAYOUT, "resync instantiate %d / %d\n",
5721                                i, lod_comp_index(lo, lod_comp));
5722                         info->lti_comp_idx[info->lti_count++] =
5723                                         lod_comp_index(lo, lod_comp);
5724                 }
5725         }
5726
5727         return need_sync ? 0 : -EALREADY;
5728 }
5729
5730 static int lod_declare_update_rdonly(const struct lu_env *env,
5731                 struct lod_object *lo, struct md_layout_change *mlc,
5732                 struct thandle *th)
5733 {
5734         struct lod_thread_info *info = lod_env_info(env);
5735         struct lu_attr *layout_attr = &info->lti_layout_attr;
5736         struct lod_layout_component *lod_comp;
5737         struct lu_extent extent = { 0 };
5738         int rc;
5739         ENTRY;
5740
5741         LASSERT(lo->ldo_flr_state == LCM_FL_RDONLY);
5742         LASSERT(mlc->mlc_opc == MD_LAYOUT_WRITE ||
5743                 mlc->mlc_opc == MD_LAYOUT_RESYNC);
5744         LASSERT(lo->ldo_mirror_count > 0);
5745
5746         if (mlc->mlc_opc == MD_LAYOUT_WRITE) {
5747                 struct layout_intent *layout = mlc->mlc_intent;
5748                 int picked;
5749
5750                 extent = layout->li_extent;
5751                 CDEBUG(D_LAYOUT, DFID": trying to write :"DEXT"\n",
5752                        PFID(lod_object_fid(lo)), PEXT(&extent));
5753
5754                 picked = lod_primary_pick(env, lo, &extent);
5755                 if (picked < 0)
5756                         RETURN(picked);
5757
5758                 CDEBUG(D_LAYOUT, DFID": picked mirror id %u as primary\n",
5759                        PFID(lod_object_fid(lo)),
5760                        lo->ldo_mirrors[picked].lme_id);
5761
5762                 if (layout->li_opc == LAYOUT_INTENT_TRUNC) {
5763                         /**
5764                          * trunc transfers [0, size) in the intent extent, we'd
5765                          * stale components overlapping [size, eof).
5766                          */
5767                         extent.e_start = extent.e_end;
5768                         extent.e_end = OBD_OBJECT_EOF;
5769                 }
5770
5771                 /* stale overlapping components from other mirrors */
5772                 lod_stale_components(lo, picked, &extent);
5773
5774                 /* restore truncate intent extent */
5775                 if (layout->li_opc == LAYOUT_INTENT_TRUNC)
5776                         extent.e_end = extent.e_start;
5777
5778                 /* instantiate components for the picked mirror, start from 0 */
5779                 extent.e_start = 0;
5780
5781                 lod_foreach_mirror_comp(lod_comp, lo, picked) {
5782                         if (!lu_extent_is_overlapped(&extent,
5783                                                      &lod_comp->llc_extent))
5784                                 break;
5785
5786                         if (lod_comp_inited(lod_comp))
5787                                 continue;
5788
5789                         info->lti_comp_idx[info->lti_count++] =
5790                                                 lod_comp_index(lo, lod_comp);
5791                 }
5792
5793                 lo->ldo_flr_state = LCM_FL_WRITE_PENDING;
5794         } else { /* MD_LAYOUT_RESYNC */
5795                 int i;
5796
5797                 /**
5798                  * could contain multiple non-stale mirrors, so we need to
5799                  * prep uninited all components assuming any non-stale mirror
5800                  * could be picked as the primary mirror.
5801                  */
5802                 for (i = 0; i < lo->ldo_mirror_count; i++) {
5803                         if (lo->ldo_mirrors[i].lme_stale)
5804                                 continue;
5805
5806                         lod_foreach_mirror_comp(lod_comp, lo, i) {
5807                                 if (!lod_comp_inited(lod_comp))
5808                                         break;
5809
5810                                 if (extent.e_end < lod_comp->llc_extent.e_end)
5811                                         extent.e_end =
5812                                                 lod_comp->llc_extent.e_end;
5813                         }
5814                 }
5815
5816                 rc = lod_prepare_resync(env, lo, &extent);
5817                 if (rc)
5818                         GOTO(out, rc);
5819                 /* change the file state to SYNC_PENDING */
5820                 lo->ldo_flr_state = LCM_FL_SYNC_PENDING;
5821         }
5822
5823         /* Reset the layout version once it's becoming too large.
5824          * This way it can make sure that the layout version is
5825          * monotonously increased in this writing era. */
5826         lod_obj_inc_layout_gen(lo);
5827         if (lo->ldo_layout_gen > (LCME_ID_MAX >> 1)) {
5828                 __u32 layout_version;
5829
5830                 cfs_get_random_bytes(&layout_version, sizeof(layout_version));
5831                 lo->ldo_layout_gen = layout_version & 0xffff;
5832         }
5833
5834         rc = lod_declare_instantiate_components(env, lo, th);
5835         if (rc)
5836                 GOTO(out, rc);
5837
5838         layout_attr->la_valid = LA_LAYOUT_VERSION;
5839         layout_attr->la_layout_version = 0; /* set current version */
5840         if (mlc->mlc_opc == MD_LAYOUT_RESYNC)
5841                 layout_attr->la_layout_version = LU_LAYOUT_RESYNC;
5842         rc = lod_declare_attr_set(env, &lo->ldo_obj, layout_attr, th);
5843         if (rc)
5844                 GOTO(out, rc);
5845
5846 out:
5847         if (rc)
5848                 lod_striping_free(env, lo);
5849         RETURN(rc);
5850 }
5851
5852 static int lod_declare_update_write_pending(const struct lu_env *env,
5853                 struct lod_object *lo, struct md_layout_change *mlc,
5854                 struct thandle *th)
5855 {
5856         struct lod_thread_info *info = lod_env_info(env);
5857         struct lu_attr *layout_attr = &info->lti_layout_attr;
5858         struct lod_layout_component *lod_comp;
5859         struct lu_extent extent = { 0 };
5860         int primary = -1;
5861         int i;
5862         int rc;
5863         ENTRY;
5864
5865         LASSERT(lo->ldo_flr_state == LCM_FL_WRITE_PENDING);
5866         LASSERT(mlc->mlc_opc == MD_LAYOUT_WRITE ||
5867                 mlc->mlc_opc == MD_LAYOUT_RESYNC);
5868
5869         /* look for the primary mirror */
5870         for (i = 0; i < lo->ldo_mirror_count; i++) {
5871                 if (lo->ldo_mirrors[i].lme_stale)
5872                         continue;
5873
5874                 LASSERTF(primary < 0, DFID " has multiple primary: %u / %u",
5875                          PFID(lod_object_fid(lo)),
5876                          lo->ldo_mirrors[i].lme_id,
5877                          lo->ldo_mirrors[primary].lme_id);
5878
5879                 primary = i;
5880         }
5881         if (primary < 0) {
5882                 CERROR(DFID ": doesn't have a primary mirror\n",
5883                        PFID(lod_object_fid(lo)));
5884                 GOTO(out, rc = -ENODATA);
5885         }
5886
5887         CDEBUG(D_LAYOUT, DFID": found primary %u\n",
5888                PFID(lod_object_fid(lo)), lo->ldo_mirrors[primary].lme_id);
5889
5890         LASSERT(!lo->ldo_mirrors[primary].lme_stale);
5891
5892         /* for LAYOUT_WRITE opc, it has to do the following operations:
5893          * 1. stale overlapping componets from stale mirrors;
5894          * 2. instantiate components of the primary mirror;
5895          * 3. transfter layout version to all objects of the primary;
5896          *
5897          * for LAYOUT_RESYNC opc, it will do:
5898          * 1. instantiate components of all stale mirrors;
5899          * 2. transfer layout version to all objects to close write era. */
5900
5901         if (mlc->mlc_opc == MD_LAYOUT_WRITE) {
5902                 LASSERT(mlc->mlc_intent != NULL);
5903
5904                 extent = mlc->mlc_intent->li_extent;
5905
5906                 CDEBUG(D_LAYOUT, DFID": intent to write: "DEXT"\n",
5907                        PFID(lod_object_fid(lo)), PEXT(&extent));
5908
5909                 if (mlc->mlc_intent->li_opc == LAYOUT_INTENT_TRUNC) {
5910                         /**
5911                          * trunc transfers [0, size) in the intent extent, we'd
5912                          * stale components overlapping [size, eof).
5913                          */
5914                         extent.e_start = extent.e_end;
5915                         extent.e_end = OBD_OBJECT_EOF;
5916                 }
5917                 /* 1. stale overlapping components */
5918                 lod_stale_components(lo, primary, &extent);
5919
5920                 /* 2. find out the components need instantiating.
5921                  * instantiate [0, mlc->mlc_intent->e_end) */
5922
5923                 /* restore truncate intent extent */
5924                 if (mlc->mlc_intent->li_opc == LAYOUT_INTENT_TRUNC)
5925                         extent.e_end = extent.e_start;
5926                 extent.e_start = 0;
5927
5928                 lod_foreach_mirror_comp(lod_comp, lo, primary) {
5929                         if (!lu_extent_is_overlapped(&extent,
5930                                                      &lod_comp->llc_extent))
5931                                 break;
5932
5933                         if (lod_comp_inited(lod_comp))
5934                                 continue;
5935
5936                         CDEBUG(D_LAYOUT, "write instantiate %d / %d\n",
5937                                primary, lod_comp_index(lo, lod_comp));
5938                         info->lti_comp_idx[info->lti_count++] =
5939                                                 lod_comp_index(lo, lod_comp);
5940                 }
5941         } else { /* MD_LAYOUT_RESYNC */
5942                 lod_foreach_mirror_comp(lod_comp, lo, primary) {
5943                         if (!lod_comp_inited(lod_comp))
5944                                 break;
5945
5946                         extent.e_end = lod_comp->llc_extent.e_end;
5947                 }
5948
5949                 rc = lod_prepare_resync(env, lo, &extent);
5950                 if (rc)
5951                         GOTO(out, rc);
5952                 /* change the file state to SYNC_PENDING */
5953                 lo->ldo_flr_state = LCM_FL_SYNC_PENDING;
5954         }
5955
5956         rc = lod_declare_instantiate_components(env, lo, th);
5957         if (rc)
5958                 GOTO(out, rc);
5959
5960         /* 3. transfer layout version to OST objects.
5961          * transfer new layout version to OST objects so that stale writes
5962          * can be denied. It also ends an era of writing by setting
5963          * LU_LAYOUT_RESYNC. Normal client can never use this bit to
5964          * send write RPC; only resync RPCs could do it. */
5965         layout_attr->la_valid = LA_LAYOUT_VERSION;
5966         layout_attr->la_layout_version = 0; /* set current version */
5967         if (mlc->mlc_opc == MD_LAYOUT_RESYNC)
5968                 layout_attr->la_layout_version = LU_LAYOUT_RESYNC;
5969         rc = lod_declare_attr_set(env, &lo->ldo_obj, layout_attr, th);
5970         if (rc)
5971                 GOTO(out, rc);
5972
5973         lod_obj_inc_layout_gen(lo);
5974 out:
5975         if (rc)
5976                 lod_striping_free(env, lo);
5977         RETURN(rc);
5978 }
5979
5980 static int lod_declare_update_sync_pending(const struct lu_env *env,
5981                 struct lod_object *lo, struct md_layout_change *mlc,
5982                 struct thandle *th)
5983 {
5984         struct lod_thread_info  *info = lod_env_info(env);
5985         unsigned sync_components = 0;
5986         unsigned resync_components = 0;
5987         int i;
5988         int rc;
5989         ENTRY;
5990
5991         LASSERT(lo->ldo_flr_state == LCM_FL_SYNC_PENDING);
5992         LASSERT(mlc->mlc_opc == MD_LAYOUT_RESYNC_DONE ||
5993                 mlc->mlc_opc == MD_LAYOUT_WRITE);
5994
5995         CDEBUG(D_LAYOUT, DFID ": received op %d in sync pending\n",
5996                PFID(lod_object_fid(lo)), mlc->mlc_opc);
5997
5998         if (mlc->mlc_opc == MD_LAYOUT_WRITE) {
5999                 CDEBUG(D_LAYOUT, DFID": cocurrent write to sync pending\n",
6000                        PFID(lod_object_fid(lo)));
6001
6002                 lo->ldo_flr_state = LCM_FL_WRITE_PENDING;
6003                 return lod_declare_update_write_pending(env, lo, mlc, th);
6004         }
6005
6006         /* MD_LAYOUT_RESYNC_DONE */
6007
6008         for (i = 0; i < lo->ldo_comp_cnt; i++) {
6009                 struct lod_layout_component *lod_comp;
6010                 int j;
6011
6012                 lod_comp = &lo->ldo_comp_entries[i];
6013
6014                 if (!(lod_comp->llc_flags & LCME_FL_STALE)) {
6015                         sync_components++;
6016                         continue;
6017                 }
6018
6019                 for (j = 0; j < mlc->mlc_resync_count; j++) {
6020                         if (lod_comp->llc_id != mlc->mlc_resync_ids[j])
6021                                 continue;
6022
6023                         mlc->mlc_resync_ids[j] = LCME_ID_INVAL;
6024                         lod_comp->llc_flags &= ~LCME_FL_STALE;
6025                         resync_components++;
6026                         break;
6027                 }
6028         }
6029
6030         /* valid check */
6031         for (i = 0; i < mlc->mlc_resync_count; i++) {
6032                 if (mlc->mlc_resync_ids[i] == LCME_ID_INVAL)
6033                         continue;
6034
6035                 CDEBUG(D_LAYOUT, DFID": lcme id %u (%d / %zd) not exist "
6036                        "or already synced\n", PFID(lod_object_fid(lo)),
6037                        mlc->mlc_resync_ids[i], i, mlc->mlc_resync_count);
6038                 GOTO(out, rc = -EINVAL);
6039         }
6040
6041         if (!sync_components || (mlc->mlc_resync_count && !resync_components)) {
6042                 CDEBUG(D_LAYOUT, DFID": no mirror in sync\n",
6043                        PFID(lod_object_fid(lo)));
6044
6045                 /* tend to return an error code here to prevent
6046                  * the MDT from setting SoM attribute */
6047                 GOTO(out, rc = -EINVAL);
6048         }
6049
6050         CDEBUG(D_LAYOUT, DFID": resynced %u/%zu components\n",
6051                PFID(lod_object_fid(lo)),
6052                resync_components, mlc->mlc_resync_count);
6053
6054         lo->ldo_flr_state = LCM_FL_RDONLY;
6055         lod_obj_inc_layout_gen(lo);
6056
6057         info->lti_buf.lb_len = lod_comp_md_size(lo, false);
6058         rc = lod_sub_declare_xattr_set(env, lod_object_child(lo),
6059                                        &info->lti_buf, XATTR_NAME_LOV, 0, th);
6060         EXIT;
6061
6062 out:
6063         if (rc)
6064                 lod_striping_free(env, lo);
6065         RETURN(rc);
6066 }
6067
6068 static int lod_declare_layout_change(const struct lu_env *env,
6069                 struct dt_object *dt, struct md_layout_change *mlc,
6070                 struct thandle *th)
6071 {
6072         struct lod_thread_info  *info = lod_env_info(env);
6073         struct lod_object *lo = lod_dt_obj(dt);
6074         int rc;
6075         ENTRY;
6076
6077         if (!S_ISREG(dt->do_lu.lo_header->loh_attr) || !dt_object_exists(dt) ||
6078             dt_object_remote(dt_object_child(dt)))
6079                 RETURN(-EINVAL);
6080
6081         rc = lod_striping_load(env, lo);
6082         if (rc)
6083                 GOTO(out, rc);
6084
6085         LASSERT(lo->ldo_comp_cnt > 0);
6086
6087         rc = lod_layout_data_init(info, lo->ldo_comp_cnt);
6088         if (rc)
6089                 GOTO(out, rc);
6090
6091         switch (lo->ldo_flr_state) {
6092         case LCM_FL_NONE:
6093                 rc = lod_declare_update_plain(env, lo, mlc->mlc_intent,
6094                                               &mlc->mlc_buf, th);
6095                 break;
6096         case LCM_FL_RDONLY:
6097                 rc = lod_declare_update_rdonly(env, lo, mlc, th);
6098                 break;
6099         case LCM_FL_WRITE_PENDING:
6100                 rc = lod_declare_update_write_pending(env, lo, mlc, th);
6101                 break;
6102         case LCM_FL_SYNC_PENDING:
6103                 rc = lod_declare_update_sync_pending(env, lo, mlc, th);
6104                 break;
6105         default:
6106                 rc = -ENOTSUPP;
6107                 break;
6108         }
6109 out:
6110         RETURN(rc);
6111 }
6112
6113 /**
6114  * Instantiate layout component objects which covers the intent write offset.
6115  */
6116 static int lod_layout_change(const struct lu_env *env, struct dt_object *dt,
6117                              struct md_layout_change *mlc, struct thandle *th)
6118 {
6119         struct lu_attr *attr = &lod_env_info(env)->lti_attr;
6120         struct lu_attr *layout_attr = &lod_env_info(env)->lti_layout_attr;
6121         struct lod_object *lo = lod_dt_obj(dt);
6122         int rc;
6123
6124         rc = lod_striped_create(env, dt, attr, NULL, th);
6125         if (!rc && layout_attr->la_valid & LA_LAYOUT_VERSION) {
6126                 layout_attr->la_layout_version |= lo->ldo_layout_gen;
6127                 rc = lod_attr_set(env, dt, layout_attr, th);
6128         }
6129
6130         return rc;
6131 }
6132
6133 struct dt_object_operations lod_obj_ops = {
6134         .do_read_lock           = lod_read_lock,
6135         .do_write_lock          = lod_write_lock,
6136         .do_read_unlock         = lod_read_unlock,
6137         .do_write_unlock        = lod_write_unlock,
6138         .do_write_locked        = lod_write_locked,
6139         .do_attr_get            = lod_attr_get,
6140         .do_declare_attr_set    = lod_declare_attr_set,
6141         .do_attr_set            = lod_attr_set,
6142         .do_xattr_get           = lod_xattr_get,
6143         .do_declare_xattr_set   = lod_declare_xattr_set,
6144         .do_xattr_set           = lod_xattr_set,
6145         .do_declare_xattr_del   = lod_declare_xattr_del,
6146         .do_xattr_del           = lod_xattr_del,
6147         .do_xattr_list          = lod_xattr_list,
6148         .do_ah_init             = lod_ah_init,
6149         .do_declare_create      = lod_declare_create,
6150         .do_create              = lod_create,
6151         .do_declare_destroy     = lod_declare_destroy,
6152         .do_destroy             = lod_destroy,
6153         .do_index_try           = lod_index_try,
6154         .do_declare_ref_add     = lod_declare_ref_add,
6155         .do_ref_add             = lod_ref_add,
6156         .do_declare_ref_del     = lod_declare_ref_del,
6157         .do_ref_del             = lod_ref_del,
6158         .do_object_sync         = lod_object_sync,
6159         .do_object_lock         = lod_object_lock,
6160         .do_object_unlock       = lod_object_unlock,
6161         .do_invalidate          = lod_invalidate,
6162         .do_declare_layout_change = lod_declare_layout_change,
6163         .do_layout_change       = lod_layout_change,
6164 };
6165
6166 /**
6167  * Implementation of dt_body_operations::dbo_read.
6168  *
6169  * \see dt_body_operations::dbo_read() in the API description for details.
6170  */
6171 static ssize_t lod_read(const struct lu_env *env, struct dt_object *dt,
6172                         struct lu_buf *buf, loff_t *pos)
6173 {
6174         struct dt_object *next = dt_object_child(dt);
6175
6176         LASSERT(S_ISREG(dt->do_lu.lo_header->loh_attr) ||
6177                 S_ISLNK(dt->do_lu.lo_header->loh_attr));
6178         return next->do_body_ops->dbo_read(env, next, buf, pos);
6179 }
6180
6181 /**
6182  * Implementation of dt_body_operations::dbo_declare_write.
6183  *
6184  * \see dt_body_operations::dbo_declare_write() in the API description
6185  * for details.
6186  */
6187 static ssize_t lod_declare_write(const struct lu_env *env,
6188                                  struct dt_object *dt,
6189                                  const struct lu_buf *buf, loff_t pos,
6190                                  struct thandle *th)
6191 {
6192         return lod_sub_declare_write(env, dt_object_child(dt), buf, pos, th);
6193 }
6194
6195 /**
6196  * Implementation of dt_body_operations::dbo_write.
6197  *
6198  * \see dt_body_operations::dbo_write() in the API description for details.
6199  */
6200 static ssize_t lod_write(const struct lu_env *env, struct dt_object *dt,
6201                          const struct lu_buf *buf, loff_t *pos,
6202                          struct thandle *th, int iq)
6203 {
6204         LASSERT(S_ISREG(dt->do_lu.lo_header->loh_attr) ||
6205                 S_ISLNK(dt->do_lu.lo_header->loh_attr));
6206         return lod_sub_write(env, dt_object_child(dt), buf, pos, th, iq);
6207 }
6208
6209 static int lod_declare_punch(const struct lu_env *env, struct dt_object *dt,
6210                              __u64 start, __u64 end, struct thandle *th)
6211 {
6212         if (dt_object_remote(dt))
6213                 return -ENOTSUPP;
6214
6215         return lod_sub_declare_punch(env, dt_object_child(dt), start, end, th);
6216 }
6217
6218 static int lod_punch(const struct lu_env *env, struct dt_object *dt,
6219                      __u64 start, __u64 end, struct thandle *th)
6220 {
6221         if (dt_object_remote(dt))
6222                 return -ENOTSUPP;
6223
6224         LASSERT(S_ISREG(dt->do_lu.lo_header->loh_attr));
6225         return lod_sub_punch(env, dt_object_child(dt), start, end, th);
6226 }
6227
6228 /*
6229  * different type of files use the same body_ops because object may be created
6230  * in OUT, where there is no chance to set correct body_ops for each type, so
6231  * body_ops themselves will check file type inside, see lod_read/write/punch for
6232  * details.
6233  */
6234 const struct dt_body_operations lod_body_ops = {
6235         .dbo_read               = lod_read,
6236         .dbo_declare_write      = lod_declare_write,
6237         .dbo_write              = lod_write,
6238         .dbo_declare_punch      = lod_declare_punch,
6239         .dbo_punch              = lod_punch,
6240 };
6241
6242 /**
6243  * Implementation of lu_object_operations::loo_object_init.
6244  *
6245  * The function determines the type and the index of the target device using
6246  * sequence of the object's FID. Then passes control down to the
6247  * corresponding device:
6248  *  OSD for the local objects, OSP for remote
6249  *
6250  * \see lu_object_operations::loo_object_init() in the API description
6251  * for details.
6252  */
6253 static int lod_object_init(const struct lu_env *env, struct lu_object *lo,
6254                            const struct lu_object_conf *conf)
6255 {
6256         struct lod_device       *lod    = lu2lod_dev(lo->lo_dev);
6257         struct lu_device        *cdev   = NULL;
6258         struct lu_object        *cobj;
6259         struct lod_tgt_descs    *ltd    = NULL;
6260         struct lod_tgt_desc     *tgt;
6261         u32                      idx    = 0;
6262         int                      type   = LU_SEQ_RANGE_ANY;
6263         int                      rc;
6264         ENTRY;
6265
6266         rc = lod_fld_lookup(env, lod, lu_object_fid(lo), &idx, &type);
6267         if (rc != 0) {
6268                 /* Note: Sometimes, it will Return EAGAIN here, see
6269                  * ptrlpc_import_delay_req(), which might confuse
6270                  * lu_object_find_at() and make it wait there incorrectly.
6271                  * so we convert it to EIO here.*/
6272                 if (rc == -EAGAIN)
6273                         rc = -EIO;
6274
6275                 RETURN(rc);
6276         }
6277
6278         if (type == LU_SEQ_RANGE_MDT &&
6279             idx == lu_site2seq(lo->lo_dev->ld_site)->ss_node_id) {
6280                 cdev = &lod->lod_child->dd_lu_dev;
6281         } else if (type == LU_SEQ_RANGE_MDT) {
6282                 ltd = &lod->lod_mdt_descs;
6283                 lod_getref(ltd);
6284         } else if (type == LU_SEQ_RANGE_OST) {
6285                 ltd = &lod->lod_ost_descs;
6286                 lod_getref(ltd);
6287         } else {
6288                 LBUG();
6289         }
6290
6291         if (ltd != NULL) {
6292                 if (ltd->ltd_tgts_size > idx &&
6293                     cfs_bitmap_check(ltd->ltd_tgt_bitmap, idx)) {
6294                         tgt = LTD_TGT(ltd, idx);
6295
6296                         LASSERT(tgt != NULL);
6297                         LASSERT(tgt->ltd_tgt != NULL);
6298
6299                         cdev = &(tgt->ltd_tgt->dd_lu_dev);
6300                 }
6301                 lod_putref(lod, ltd);
6302         }
6303
6304         if (unlikely(cdev == NULL))
6305                 RETURN(-ENOENT);
6306
6307         cobj = cdev->ld_ops->ldo_object_alloc(env, lo->lo_header, cdev);
6308         if (unlikely(cobj == NULL))
6309                 RETURN(-ENOMEM);
6310
6311         lu2lod_obj(lo)->ldo_obj.do_body_ops = &lod_body_ops;
6312
6313         lu_object_add(lo, cobj);
6314
6315         RETURN(0);
6316 }
6317
6318 /**
6319  *
6320  * Release resources associated with striping.
6321  *
6322  * If the object is striped (regular or directory), then release
6323  * the stripe objects references and free the ldo_stripe array.
6324  *
6325  * \param[in] env       execution environment
6326  * \param[in] lo        object
6327  */
6328 void lod_striping_free_nolock(const struct lu_env *env, struct lod_object *lo)
6329 {
6330         struct lod_layout_component *lod_comp;
6331         int i, j;
6332
6333         if (lo->ldo_stripe != NULL) {
6334                 LASSERT(lo->ldo_comp_entries == NULL);
6335                 LASSERT(lo->ldo_dir_stripes_allocated > 0);
6336
6337                 for (i = 0; i < lo->ldo_dir_stripe_count; i++) {
6338                         if (lo->ldo_stripe[i])
6339                                 dt_object_put(env, lo->ldo_stripe[i]);
6340                 }
6341
6342                 j = sizeof(struct dt_object *) * lo->ldo_dir_stripes_allocated;
6343                 OBD_FREE(lo->ldo_stripe, j);
6344                 lo->ldo_stripe = NULL;
6345                 lo->ldo_dir_stripes_allocated = 0;
6346                 lo->ldo_dir_stripe_loaded = 0;
6347                 lo->ldo_dir_stripe_count = 0;
6348         } else if (lo->ldo_comp_entries != NULL) {
6349                 for (i = 0; i < lo->ldo_comp_cnt; i++) {
6350                         /* free lod_layout_component::llc_stripe array */
6351                         lod_comp = &lo->ldo_comp_entries[i];
6352
6353                         if (lod_comp->llc_stripe == NULL)
6354                                 continue;
6355                         LASSERT(lod_comp->llc_stripes_allocated != 0);
6356                         for (j = 0; j < lod_comp->llc_stripes_allocated; j++) {
6357                                 if (lod_comp->llc_stripe[j] != NULL)
6358                                         lu_object_put(env,
6359                                                &lod_comp->llc_stripe[j]->do_lu);
6360                         }
6361                         OBD_FREE(lod_comp->llc_stripe,
6362                                  sizeof(struct dt_object *) *
6363                                  lod_comp->llc_stripes_allocated);
6364                         lod_comp->llc_stripe = NULL;
6365                         OBD_FREE(lod_comp->llc_ost_indices,
6366                                  sizeof(__u32) *
6367                                  lod_comp->llc_stripes_allocated);
6368                         lod_comp->llc_ost_indices = NULL;
6369                         lod_comp->llc_stripes_allocated = 0;
6370                 }
6371                 lod_free_comp_entries(lo);
6372                 lo->ldo_comp_cached = 0;
6373         }
6374 }
6375
6376 void lod_striping_free(const struct lu_env *env, struct lod_object *lo)
6377 {
6378         mutex_lock(&lo->ldo_layout_mutex);
6379         lod_striping_free_nolock(env, lo);
6380         mutex_unlock(&lo->ldo_layout_mutex);
6381 }
6382
6383 /**
6384  * Implementation of lu_object_operations::loo_object_free.
6385  *
6386  * \see lu_object_operations::loo_object_free() in the API description
6387  * for details.
6388  */
6389 static void lod_object_free(const struct lu_env *env, struct lu_object *o)
6390 {
6391         struct lod_object *lo = lu2lod_obj(o);
6392
6393         /* release all underlying object pinned */
6394         lod_striping_free(env, lo);
6395         lu_object_fini(o);
6396         OBD_SLAB_FREE_PTR(lo, lod_object_kmem);
6397 }
6398
6399 /**
6400  * Implementation of lu_object_operations::loo_object_release.
6401  *
6402  * \see lu_object_operations::loo_object_release() in the API description
6403  * for details.
6404  */
6405 static void lod_object_release(const struct lu_env *env, struct lu_object *o)
6406 {
6407         /* XXX: shouldn't we release everything here in case if object
6408          * creation failed before? */
6409 }
6410
6411 /**
6412  * Implementation of lu_object_operations::loo_object_print.
6413  *
6414  * \see lu_object_operations::loo_object_print() in the API description
6415  * for details.
6416  */
6417 static int lod_object_print(const struct lu_env *env, void *cookie,
6418                             lu_printer_t p, const struct lu_object *l)
6419 {
6420         struct lod_object *o = lu2lod_obj((struct lu_object *) l);
6421
6422         return (*p)(env, cookie, LUSTRE_LOD_NAME"-object@%p", o);
6423 }
6424
6425 struct lu_object_operations lod_lu_obj_ops = {
6426         .loo_object_init        = lod_object_init,
6427         .loo_object_free        = lod_object_free,
6428         .loo_object_release     = lod_object_release,
6429         .loo_object_print       = lod_object_print,
6430 };