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