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