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