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