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