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