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