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