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