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