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