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