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