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