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