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