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