Whamcloud - gitweb
LU-17048 mdd: protect layout change in MDD layer
[fs/lustre-release.git] / lustre / mdd / mdd_dir.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, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  *
31  * lustre/mdd/mdd_dir.c
32  *
33  * Lustre Metadata Server (mdd) routines
34  *
35  * Author: Wang Di <wangdi@intel.com>
36  */
37
38 #define DEBUG_SUBSYSTEM S_MDS
39
40 #include <obd_class.h>
41 #include <obd_support.h>
42 #include <lustre_mds.h>
43 #include <lustre_fid.h>
44 #include <lustre_lmv.h>
45 #include <lustre_idmap.h>
46
47 #include "mdd_internal.h"
48
49 static const char dot[] = ".";
50 static const char dotdot[] = "..";
51
52 static struct lu_name lname_dotdot = {
53         .ln_name        = (char *) dotdot,
54         .ln_namelen     = sizeof(dotdot) - 1,
55 };
56
57 static inline int
58 mdd_name_check(const struct lu_env *env, struct mdd_device *m,
59                const struct lu_name *ln)
60 {
61         struct mdd_thread_info *info = mdd_env_info(env);
62         bool enc = info->mdi_pattr.la_valid & LA_FLAGS &&
63                 info->mdi_pattr.la_flags & LUSTRE_ENCRYPT_FL;
64
65         if (!lu_name_is_valid(ln))
66                 return -EINVAL;
67         else if (!enc && ln->ln_namelen > m->mdd_dt_conf.ddp_max_name_len)
68                 return -ENAMETOOLONG;
69         else
70                 return 0;
71 }
72
73 /* Get FID from name and parent */
74 static int
75 __mdd_lookup(const struct lu_env *env, struct md_object *pobj,
76              const struct lu_attr *pattr, const struct lu_name *lname,
77              struct lu_fid *fid, unsigned int may_mask)
78 {
79         const char *name = lname->ln_name;
80         const struct dt_key *key = (const struct dt_key *)name;
81         struct mdd_object *mdd_obj = md2mdd_obj(pobj);
82         struct dt_object *dir = mdd_object_child(mdd_obj);
83         int rc;
84
85         ENTRY;
86
87         if (unlikely(mdd_is_dead_obj(mdd_obj)))
88                 RETURN(-ESTALE);
89
90         if (!mdd_object_exists(mdd_obj))
91                 RETURN(-ESTALE);
92
93         if (mdd_object_remote(mdd_obj)) {
94                 CDEBUG(D_INFO, "%s: Object "DFID" located on remote server\n",
95                        mdd_obj_dev_name(mdd_obj),
96                        PFID(mdd_object_fid(mdd_obj)));
97         }
98
99         rc = mdd_permission_internal_locked(env, mdd_obj, pattr, may_mask,
100                                             DT_TGT_PARENT);
101         if (rc)
102                 RETURN(rc);
103
104         if (likely(dt_try_as_dir(env, dir, true)))
105                 rc = dt_lookup(env, dir, (struct dt_rec *)fid, key);
106         else
107                 rc = -ENOTDIR;
108
109         RETURN(rc);
110 }
111
112 int mdd_lookup(const struct lu_env *env,
113                struct md_object *pobj, const struct lu_name *lname,
114                struct lu_fid *fid, struct md_op_spec *spec)
115 {
116         struct lu_attr *pattr = MDD_ENV_VAR(env, pattr);
117         int rc;
118         ENTRY;
119
120         rc = mdd_la_get(env, md2mdd_obj(pobj), pattr);
121         if (rc != 0)
122                 RETURN(rc);
123
124         rc = __mdd_lookup(env, pobj, pattr, lname, fid,
125                           (spec != NULL && spec->sp_permitted) ? 0 : MAY_EXEC);
126         RETURN(rc);
127 }
128
129 /** Read the link EA into a temp buffer.
130  * Uses the mdd_thread_info::mdi_link_buf since it is generally large.
131  * A pointer to the buffer is stored in \a ldata::ld_buf.
132  *
133  * \retval 0 or error
134  */
135 static int __mdd_links_read(const struct lu_env *env,
136                             struct mdd_object *mdd_obj,
137                             struct linkea_data *ldata)
138 {
139         int rc;
140
141         if (!mdd_object_exists(mdd_obj))
142                 return -ENODATA;
143
144         /* First try a small buf */
145         LASSERT(env != NULL);
146         ldata->ld_buf = lu_buf_check_and_alloc(&mdd_env_info(env)->mdi_link_buf,
147                                                PAGE_SIZE);
148         if (ldata->ld_buf->lb_buf == NULL)
149                 return -ENOMEM;
150
151         rc = mdo_xattr_get(env, mdd_obj, ldata->ld_buf, XATTR_NAME_LINK);
152         if (rc == -ERANGE) {
153                 /* Buf was too small, figure out what we need. */
154                 lu_buf_free(ldata->ld_buf);
155                 rc = mdo_xattr_get(env, mdd_obj, ldata->ld_buf,
156                                    XATTR_NAME_LINK);
157                 if (rc < 0)
158                         return rc;
159                 ldata->ld_buf = lu_buf_check_and_alloc(ldata->ld_buf, rc);
160                 if (ldata->ld_buf->lb_buf == NULL)
161                         return -ENOMEM;
162                 rc = mdo_xattr_get(env, mdd_obj, ldata->ld_buf,
163                                   XATTR_NAME_LINK);
164         }
165         if (rc < 0) {
166                 lu_buf_free(ldata->ld_buf);
167                 ldata->ld_buf = NULL;
168                 return rc;
169         }
170
171         return linkea_init(ldata);
172 }
173
174 int mdd_links_read(const struct lu_env *env,
175                    struct mdd_object *mdd_obj,
176                    struct linkea_data *ldata)
177 {
178         int rc;
179
180         rc = __mdd_links_read(env, mdd_obj, ldata);
181         if (!rc)
182                 rc = linkea_init(ldata);
183
184         return rc;
185 }
186
187 static int mdd_links_read_with_rec(const struct lu_env *env,
188                                    struct mdd_object *mdd_obj,
189                                    struct linkea_data *ldata)
190 {
191         int rc;
192
193         rc = __mdd_links_read(env, mdd_obj, ldata);
194         if (!rc)
195                 rc = linkea_init_with_rec(ldata);
196
197         return rc;
198 }
199
200 /**
201  * Get parent FID of the directory
202  *
203  * Read parent FID from linkEA, if that fails, then do lookup
204  * dotdot to get the parent FID.
205  *
206  * \param[in] env       execution environment
207  * \param[in] obj       object from which to find the parent FID
208  * \param[in] attr      attribute of the object
209  * \param[out] fid      fid to get the parent FID
210  *
211  * \retval              0 if getting the parent FID succeeds.
212  * \retval              negative errno if getting the parent FID fails.
213  **/
214 static inline int mdd_parent_fid(const struct lu_env *env,
215                                  struct mdd_object *obj,
216                                  const struct lu_attr *attr,
217                                  struct lu_fid *fid)
218 {
219         struct mdd_thread_info *info = mdd_env_info(env);
220         struct linkea_data ldata = { NULL };
221         struct lu_buf *buf = &info->mdi_link_buf;
222         struct lu_name lname;
223         int rc = 0;
224
225         ENTRY;
226
227         LASSERTF(S_ISDIR(mdd_object_type(obj)),
228                  "%s: FID "DFID" is not a directory type = %o\n",
229                  mdd_obj_dev_name(obj), PFID(mdd_object_fid(obj)),
230                  mdd_object_type(obj));
231
232         buf = lu_buf_check_and_alloc(buf, PATH_MAX);
233         if (buf->lb_buf == NULL)
234                 GOTO(lookup, rc = 0);
235
236         ldata.ld_buf = buf;
237         rc = mdd_links_read_with_rec(env, obj, &ldata);
238         if (rc != 0)
239                 GOTO(lookup, rc);
240
241         /* the obj is not locked, don't cache attributes */
242         mdd_invalidate(env, &obj->mod_obj);
243
244         LASSERT(ldata.ld_leh != NULL);
245         /* Directory should only have 1 parent */
246         if (ldata.ld_leh->leh_reccount > 1)
247                 GOTO(lookup, rc);
248
249         ldata.ld_lee = (struct link_ea_entry *)(ldata.ld_leh + 1);
250
251         linkea_entry_unpack(ldata.ld_lee, &ldata.ld_reclen, &lname, fid);
252         if (likely(fid_is_sane(fid)))
253                 RETURN(0);
254 lookup:
255         rc =  __mdd_lookup(env, &obj->mod_obj, attr, &lname_dotdot, fid, 0);
256         RETURN(rc);
257 }
258
259 /*
260  * For root fid use special function, which does not compare version component
261  * of fid. Version component is different for root fids on all MDTs.
262  */
263 int mdd_is_root(struct mdd_device *mdd, const struct lu_fid *fid)
264 {
265         return fid_seq(&mdd->mdd_root_fid) == fid_seq(fid) &&
266                 fid_oid(&mdd->mdd_root_fid) == fid_oid(fid);
267 }
268
269 /*
270  * return 1: if \a tfid is the fid of the ancestor of \a mo;
271  * return 0: if not;
272  * otherwise: values < 0, errors.
273  */
274 static int mdd_is_parent(const struct lu_env *env,
275                         struct mdd_device *mdd,
276                         struct mdd_object *mo,
277                         const struct lu_attr *attr,
278                         const struct lu_fid *tfid)
279 {
280         struct mdd_object *mp;
281         struct lu_fid *pfid;
282         int rc;
283
284         LASSERT(!lu_fid_eq(mdd_object_fid(mo), tfid));
285         pfid = &mdd_env_info(env)->mdi_fid;
286
287         if (mdd_is_root(mdd, mdd_object_fid(mo)))
288                 return 0;
289
290         if (mdd_is_root(mdd, tfid))
291                 return 1;
292
293         rc = mdd_parent_fid(env, mo, attr, pfid);
294         if (rc)
295                 return rc;
296
297         while (1) {
298                 if (lu_fid_eq(pfid, tfid))
299                         return 1;
300
301                 if (mdd_is_root(mdd, pfid))
302                         return 0;
303
304                 mp = mdd_object_find(env, mdd, pfid);
305                 if (IS_ERR(mp))
306                         return PTR_ERR(mp);
307
308                 if (!mdd_object_exists(mp)) {
309                         mdd_object_put(env, mp);
310                         return -ENOENT;
311                 }
312
313                 rc = mdd_parent_fid(env, mp, attr, pfid);
314                 mdd_object_put(env, mp);
315                 if (rc)
316                         return rc;
317         }
318
319         return 0;
320 }
321
322 /*
323  * No permission check is needed.
324  *
325  * returns 1: if fid is ancestor of @mo;
326  * returns 0: if fid is not an ancestor of @mo;
327  * returns < 0: if error
328  */
329 static int mdd_is_subdir(const struct lu_env *env, struct md_object *mo,
330                          const struct lu_fid *fid)
331 {
332         struct mdd_device *mdd = mdo2mdd(mo);
333         struct lu_attr *attr = MDD_ENV_VAR(env, cattr);
334         int rc;
335         ENTRY;
336
337         if (!mdd_object_exists(md2mdd_obj(mo)))
338                 RETURN(-ENOENT);
339
340         if (!S_ISDIR(mdd_object_type(md2mdd_obj(mo))))
341                 RETURN(-ENOTDIR);
342
343         rc = mdd_la_get(env, md2mdd_obj(mo), attr);
344         if (rc != 0)
345                 RETURN(rc);
346
347         rc = mdd_is_parent(env, mdd, md2mdd_obj(mo), attr, fid);
348         RETURN(rc);
349 }
350
351 /*
352  * Check that @dir contains no entries except (possibly) dot and dotdot.
353  *
354  * Returns:
355  *
356  *             0        empty
357  *      -ENOTDIR        not a directory object
358  *    -ENOTEMPTY        not empty
359  *           -ve        other error
360  *
361  */
362 int mdd_dir_is_empty(const struct lu_env *env, struct mdd_object *dir)
363 {
364         struct dt_it     *it;
365         struct dt_object *obj;
366         const struct dt_it_ops *iops;
367         int result;
368         ENTRY;
369
370         obj = mdd_object_child(dir);
371         if (!dt_try_as_dir(env, obj, true))
372                 RETURN(-ENOTDIR);
373
374         iops = &obj->do_index_ops->dio_it;
375         it = iops->init(env, obj, LUDA_64BITHASH);
376         if (!IS_ERR(it)) {
377                 result = iops->get(env, it, (const struct dt_key *)"");
378                 if (result > 0) {
379                         int i;
380                         for (result = 0, i = 0; result == 0 && i < 3; ++i)
381                                 result = iops->next(env, it);
382                         if (result == 0)
383                                 result = -ENOTEMPTY;
384                         else if (result == 1)
385                                 result = 0;
386                 } else if (result == 0)
387                         /*
388                          * Huh? Index contains no zero key?
389                          */
390                         result = -EIO;
391
392                 iops->put(env, it);
393                 iops->fini(env, it);
394         } else {
395                 result = PTR_ERR(it);
396                 /* -ENODEV means no valid stripe */
397                 if (result == -ENODEV)
398                         RETURN(0);
399         }
400         RETURN(result);
401 }
402
403 /**
404  * Determine if the target object can be hard linked, and right now it only
405  * checks if the link count reach the maximum limit. Note: for ldiskfs, the
406  * directory nlink count might exceed the maximum link count(see
407  * osd_object_ref_add), so it only check nlink for non-directories.
408  *
409  * \param[in] env       thread environment
410  * \param[in] obj       object being linked to
411  * \param[in] la        attributes of \a obj
412  *
413  * \retval              0 if \a obj can be hard linked
414  * \retval              negative error if \a obj is a directory or has too
415  *                      many links
416  */
417 static int __mdd_may_link(const struct lu_env *env, struct mdd_object *obj,
418                           const struct lu_attr *la)
419 {
420         struct mdd_device *m = mdd_obj2mdd_dev(obj);
421         ENTRY;
422
423         LASSERT(la != NULL);
424
425         /* Subdir count limitation can be broken through
426          * (see osd_object_ref_add), so only check non-directory here. */
427         if (!S_ISDIR(la->la_mode) &&
428             la->la_nlink >= m->mdd_dt_conf.ddp_max_nlink)
429                 RETURN(-EMLINK);
430
431         RETURN(0);
432 }
433
434 /**
435  * Check whether it may create the cobj under the pobj.
436  *
437  * \param[in] env       execution environment
438  * \param[in] pobj      the parent directory
439  * \param[in] pattr     the attribute of the parent directory
440  * \param[in] cobj      the child to be created
441  * \param[in] check_perm        if check WRITE|EXEC permission for parent
442  *
443  * \retval              = 0 create the child under this dir is allowed
444  * \retval              negative errno create the child under this dir is
445  *                      not allowed
446  */
447 int mdd_may_create(const struct lu_env *env, struct mdd_object *pobj,
448                    const struct lu_attr *pattr, struct mdd_object *cobj,
449                    bool check_perm)
450 {
451         int rc = 0;
452         ENTRY;
453
454         if (cobj && mdd_object_exists(cobj))
455                 RETURN(-EEXIST);
456
457         if (mdd_is_dead_obj(pobj))
458                 RETURN(-ENOENT);
459
460         if (check_perm)
461                 rc = mdd_permission_internal_locked(env, pobj, pattr,
462                                                     MAY_WRITE | MAY_EXEC,
463                                                     DT_TGT_PARENT);
464         RETURN(rc);
465 }
466
467 /*
468  * Check whether can unlink from the pobj in the case of "cobj == NULL".
469  */
470 int mdd_may_unlink(const struct lu_env *env, struct mdd_object *pobj,
471                    const struct lu_attr *pattr, const struct lu_attr *attr)
472 {
473         int rc;
474         ENTRY;
475
476         if (mdd_is_dead_obj(pobj))
477                 RETURN(-ENOENT);
478
479         if (attr->la_flags & (LUSTRE_APPEND_FL | LUSTRE_IMMUTABLE_FL))
480                 RETURN(-EPERM);
481
482         rc = mdd_permission_internal_locked(env, pobj, pattr,
483                                             MAY_WRITE | MAY_EXEC,
484                                             DT_TGT_PARENT);
485         if (rc != 0)
486                 RETURN(rc);
487
488         if (pattr->la_flags & LUSTRE_APPEND_FL)
489                 RETURN(-EPERM);
490
491         RETURN(rc);
492 }
493
494 /*
495  * pobj == NULL is remote ops case, under such case, pobj's
496  * VTX feature has been checked already, no need check again.
497  */
498 static inline int mdd_is_sticky(const struct lu_env *env,
499                                 struct mdd_object *pobj,
500                                 const struct lu_attr *pattr,
501                                 struct mdd_object *cobj,
502                                 const struct lu_attr *cattr)
503 {
504         struct lu_ucred *uc = lu_ucred_assert(env);
505
506         if (pobj != NULL) {
507                 LASSERT(pattr != NULL);
508                 if (!(pattr->la_mode & S_ISVTX) ||
509                     (pattr->la_uid == uc->uc_fsuid))
510                         return 0;
511         }
512
513         LASSERT(cattr != NULL);
514         if (cattr->la_uid == uc->uc_fsuid)
515                 return 0;
516
517         return !cap_raised(uc->uc_cap, CAP_FOWNER);
518 }
519
520 static int mdd_may_delete_entry(const struct lu_env *env,
521                                 struct mdd_object *pobj,
522                                 const struct lu_attr *pattr,
523                                 int check_perm)
524 {
525         ENTRY;
526
527         LASSERT(pobj != NULL);
528         if (!mdd_object_exists(pobj))
529                 RETURN(-ENOENT);
530
531         if (mdd_is_dead_obj(pobj))
532                 RETURN(-ENOENT);
533
534         if (check_perm) {
535                 int rc;
536                 rc = mdd_permission_internal_locked(env, pobj, pattr,
537                                             MAY_WRITE | MAY_EXEC,
538                                             DT_TGT_PARENT);
539                 if (rc)
540                         RETURN(rc);
541         }
542
543         if (pattr->la_flags & LUSTRE_APPEND_FL)
544                 RETURN(-EPERM);
545
546         RETURN(0);
547 }
548
549 /*
550  * Check whether it may delete the cobj from the pobj.
551  * pobj maybe NULL
552  */
553 int mdd_may_delete(const struct lu_env *env, struct mdd_object *tpobj,
554                    const struct lu_attr *tpattr, struct mdd_object *tobj,
555                    const struct lu_attr *tattr, const struct lu_attr *cattr,
556                    int check_perm, int check_empty)
557 {
558         int rc = 0;
559         ENTRY;
560
561         if (tpobj) {
562                 LASSERT(tpattr != NULL);
563                 rc = mdd_may_delete_entry(env, tpobj, tpattr, check_perm);
564                 if (rc != 0)
565                         RETURN(rc);
566         }
567
568         if (tobj == NULL)
569                 RETURN(0);
570
571         if (!mdd_object_exists(tobj))
572                 RETURN(-ENOENT);
573
574         if (mdd_is_dead_obj(tobj))
575                 RETURN(-ESTALE);
576
577         if (mdd_is_sticky(env, tpobj, tpattr, tobj, tattr))
578                 RETURN(-EPERM);
579
580         if (tattr->la_flags & (LUSTRE_APPEND_FL | LUSTRE_IMMUTABLE_FL))
581                 RETURN(-EPERM);
582
583         /* additional check the rename case */
584         if (cattr) {
585                 if (S_ISDIR(cattr->la_mode)) {
586                         if (!S_ISDIR(tattr->la_mode))
587                                 RETURN(-ENOTDIR);
588
589                         if (mdd_is_root(mdo2mdd(&tobj->mod_obj),
590                                         mdd_object_fid(tobj)))
591                                 RETURN(-EBUSY);
592                 } else if (S_ISDIR(tattr->la_mode))
593                         RETURN(-EISDIR);
594         }
595
596         if (S_ISDIR(tattr->la_mode) && check_empty)
597                 rc = mdd_dir_is_empty(env, tobj);
598
599         RETURN(rc);
600 }
601
602 /**
603  * Check whether it can create the link file(linked to @src_obj) under
604  * the target directory(@tgt_obj), and src_obj has been locked by
605  * mdd_write_lock.
606  *
607  * \param[in] env       execution environment
608  * \param[in] tgt_obj   the target directory
609  * \param[in] tattr     attributes of target directory
610  * \param[in] lname     the link name
611  * \param[in] src_obj   source object for link
612  * \param[in] cattr     attributes for source object
613  *
614  * \retval              = 0 it is allowed to create the link file under tgt_obj
615  * \retval              negative error not allowed to create the link file
616  */
617 static int mdd_link_sanity_check(const struct lu_env *env,
618                                  struct mdd_object *tgt_obj,
619                                  const struct lu_attr *tattr,
620                                  const struct lu_name *lname,
621                                  struct mdd_object *src_obj,
622                                  const struct lu_attr *cattr)
623 {
624         struct mdd_device *m = mdd_obj2mdd_dev(src_obj);
625         int rc = 0;
626         ENTRY;
627
628         if (!mdd_object_exists(src_obj))
629                 RETURN(-ENOENT);
630
631         if (mdd_is_dead_obj(src_obj))
632                 RETURN(-ESTALE);
633
634         /* Local ops, no lookup before link, check filename length here. */
635         rc = mdd_name_check(env, m, lname);
636         if (rc < 0)
637                 RETURN(rc);
638
639         if (cattr->la_flags & (LUSTRE_IMMUTABLE_FL | LUSTRE_APPEND_FL))
640                 RETURN(-EPERM);
641
642         if (S_ISDIR(mdd_object_type(src_obj)))
643                 RETURN(-EPERM);
644
645         LASSERT(src_obj != tgt_obj);
646         rc = mdd_may_create(env, tgt_obj, tattr, NULL, true);
647         if (rc != 0)
648                 RETURN(rc);
649
650         rc = __mdd_may_link(env, src_obj, cattr);
651
652         RETURN(rc);
653 }
654
655 static int __mdd_index_delete_only(const struct lu_env *env, struct mdd_object *pobj,
656                                    const char *name, struct thandle *handle)
657 {
658         struct dt_object *next = mdd_object_child(pobj);
659         int rc;
660         ENTRY;
661
662         if (dt_try_as_dir(env, next, true))
663                 rc = dt_delete(env, next, (struct dt_key *)name, handle);
664         else
665                 rc = -ENOTDIR;
666
667         RETURN(rc);
668 }
669
670 static int __mdd_index_insert_only(const struct lu_env *env,
671                                    struct mdd_object *pobj,
672                                    const struct lu_fid *lf, __u32 type,
673                                    const char *name, struct thandle *handle)
674 {
675         struct dt_object *next = mdd_object_child(pobj);
676         int rc;
677         ENTRY;
678
679         if (dt_try_as_dir(env, next, true)) {
680                 struct dt_insert_rec *rec = &mdd_env_info(env)->mdi_dt_rec;
681
682                 rec->rec_fid = lf;
683                 rec->rec_type = type;
684                 rc = dt_insert(env, next, (const struct dt_rec *)rec,
685                                (const struct dt_key *)name, handle);
686         } else {
687                 rc = -ENOTDIR;
688         }
689         RETURN(rc);
690 }
691
692 /* insert named index, add reference if isdir */
693 static int __mdd_index_insert(const struct lu_env *env, struct mdd_object *pobj,
694                               const struct lu_fid *lf, __u32 type,
695                               const char *name, struct thandle *handle)
696 {
697         int rc;
698         ENTRY;
699
700         rc = __mdd_index_insert_only(env, pobj, lf, type, name, handle);
701         if (rc == 0 && S_ISDIR(type)) {
702                 mdd_write_lock(env, pobj, DT_TGT_PARENT);
703                 mdo_ref_add(env, pobj, handle);
704                 mdd_write_unlock(env, pobj);
705         }
706
707         RETURN(rc);
708 }
709
710 /* delete named index, drop reference if isdir */
711 static int __mdd_index_delete(const struct lu_env *env, struct mdd_object *pobj,
712                               const char *name, int is_dir,
713                               struct thandle *handle)
714 {
715         int rc;
716         ENTRY;
717
718         rc = __mdd_index_delete_only(env, pobj, name, handle);
719         if (rc == 0 && is_dir) {
720                 mdd_write_lock(env, pobj, DT_TGT_PARENT);
721                 mdo_ref_del(env, pobj, handle);
722                 mdd_write_unlock(env, pobj);
723         }
724
725         RETURN(rc);
726 }
727
728 static int mdd_llog_record_calc_size(const struct lu_env *env,
729                                      const struct lu_name *tname,
730                                      const struct lu_name *sname)
731 {
732         const struct lu_ucred   *uc = lu_ucred(env);
733         enum changelog_rec_flags clf_flags = CLF_EXTRA_FLAGS;
734         enum changelog_rec_extra_flags crfe = CLFE_UIDGID | CLFE_NID;
735
736         if (sname != NULL)
737                 clf_flags |= CLF_RENAME;
738
739         if (uc != NULL && uc->uc_jobid[0] != '\0')
740                 clf_flags |= CLF_JOBID;
741
742         return llog_data_len(LLOG_CHANGELOG_HDR_SZ +
743                              changelog_rec_offset(clf_flags, crfe) +
744                              (tname != NULL ? tname->ln_namelen : 0) +
745                              (sname != NULL ? 1 + sname->ln_namelen : 0));
746 }
747
748 int mdd_declare_changelog_store(const struct lu_env *env,
749                                 struct mdd_device *mdd,
750                                 enum changelog_rec_type type,
751                                 const struct lu_name *tname,
752                                 const struct lu_name *sname,
753                                 struct thandle *handle)
754 {
755         struct obd_device *obd = mdd2obd_dev(mdd);
756         struct llog_ctxt *ctxt;
757         struct llog_rec_hdr rec_hdr;
758         struct thandle *llog_th;
759         int rc;
760
761         if (!mdd_changelog_enabled(env, mdd, type))
762                 return 0;
763
764         rec_hdr.lrh_len = mdd_llog_record_calc_size(env, tname, sname);
765         rec_hdr.lrh_type = CHANGELOG_REC;
766
767         ctxt = llog_get_context(obd, LLOG_CHANGELOG_ORIG_CTXT);
768         if (ctxt == NULL)
769                 return -ENXIO;
770
771         llog_th = thandle_get_sub(env, handle, ctxt->loc_handle->lgh_obj);
772         if (IS_ERR(llog_th))
773                 GOTO(out_put, rc = PTR_ERR(llog_th));
774
775         rc = llog_declare_add(env, ctxt->loc_handle, &rec_hdr, llog_th);
776
777 out_put:
778         llog_ctxt_put(ctxt);
779
780         return rc;
781 }
782
783 int mdd_changelog_write_rec(const struct lu_env *env,
784                             struct llog_handle *loghandle,
785                             struct llog_rec_hdr *r,
786                             struct llog_cookie *cookie,
787                             int idx, struct thandle *th)
788 {
789         int rc;
790
791         if (r->lrh_type == CHANGELOG_REC) {
792                 struct mdd_device *mdd;
793                 struct llog_changelog_rec *rec;
794
795                 mdd = lu2mdd_dev(loghandle->lgh_ctxt->loc_obd->obd_lu_dev);
796                 rec = container_of(r, struct llog_changelog_rec, cr_hdr);
797
798                 spin_lock(&mdd->mdd_cl.mc_lock);
799                 rec->cr.cr_index = mdd->mdd_cl.mc_index + 1;
800                 spin_unlock(&mdd->mdd_cl.mc_lock);
801
802                 rc = llog_osd_ops.lop_write_rec(env, loghandle, r,
803                                                 cookie, idx, th);
804
805                 /*
806                  * if current llog is full, we will generate a new
807                  * llog, and since it's actually not an error, let's
808                  * avoid increasing index so that userspace apps
809                  * should not see a gap in the changelog sequence
810                  */
811                 if (!(rc == -ENOSPC && llog_is_full(loghandle))) {
812                         spin_lock(&mdd->mdd_cl.mc_lock);
813                         ++mdd->mdd_cl.mc_index;
814                         spin_unlock(&mdd->mdd_cl.mc_lock);
815                 }
816         } else {
817                 rc = llog_osd_ops.lop_write_rec(env, loghandle, r,
818                                                 cookie, idx, th);
819         }
820
821         return rc;
822 }
823
824 /**
825  * Checks that changelog consumes safe amount of space comparing
826  * with FS free space
827  *
828  * \param env - current lu_env
829  * \param mdd - current MDD device
830  * \param lgh - changelog catalog llog handle
831  * \param estimate - get exact llog size or estimate it.
832  *
833  * \retval true/false
834  */
835 bool mdd_changelog_is_space_safe(const struct lu_env *env,
836                                  struct mdd_device *mdd,
837                                  struct llog_handle *lgh,
838                                  bool estimate)
839 {
840         struct obd_statfs sfs;
841         unsigned long long free_space_limit;
842         unsigned long long llog_size;
843         int rc;
844
845         rc = dt_statfs(env, mdd->mdd_bottom, &sfs);
846         if (rc)
847                 /* check is ignored if OSD is not healthy for any reason */
848                 return true;
849
850         /*
851          * if changelog consumes more than 1/4 of available space then start
852          * emergency cleanup.
853          */
854         if (CFS_FAIL_CHECK(OBD_FAIL_MDS_CHANGELOG_ENOSPC))
855                 free_space_limit = cfs_fail_val;
856         else
857                 free_space_limit = (sfs.os_bfree * sfs.os_bsize) >> 2;
858
859         /* if \estimate parameter is used then calculate llog size from
860          * number of used catalog entries and plain llog maximum size.
861          * Plain llog maximum size if set as 1/64 of FS free space limited
862          * by 128MB as maximum and 2MB as minimum, see llog_cat_new_log()
863          * Estimation helps to avoid full llog processing to get exact size
864          * by llog_cat_size().
865          */
866         if (estimate) {
867                 /* use 1/64 of FS size but keep it between 2MB and 128MB */
868                 llog_size = clamp_t(unsigned long long,
869                                     (sfs.os_blocks * sfs.os_bsize) >> 6,
870                                     2 << 20, 128 << 20);
871                 /*
872                  * llog_cat_free_space() gives free slots, we need occupied,
873                  * so subtruct free from total slots minus one for header
874                  */
875                 llog_size *= LLOG_HDR_BITMAP_SIZE(lgh->lgh_hdr) - 1 -
876                              llog_cat_free_space(lgh);
877         } else {
878                 /* get exact llog size */
879                 llog_size = llog_cat_size(env, lgh);
880         }
881         CDEBUG(D_HA, "%s:%s changelog size is %lluMB, space limit is %lluMB\n",
882                mdd2obd_dev(mdd)->obd_name, estimate ? " estimated" : "",
883                llog_size >> 20, free_space_limit >> 20);
884
885         if (llog_size > free_space_limit) {
886                 CWARN("%s: changelog uses %lluMB with %lluMB space limit\n",
887                       mdd2obd_dev(mdd)->obd_name, llog_size >> 20,
888                       free_space_limit >> 20);
889                 return false;
890         }
891
892         return true;
893 }
894
895 /**
896  * Checks if there is enough space in changelog itself and in FS and force
897  * emergency changelog cleanup if needed. It will purge users one by one
898  * from the oldest one while emergency conditions are true.
899  *
900  * \param env - current lu_env
901  * \param mdd - current MDD device
902  * \param lgh - changelog catalog llog handle
903  *
904  * \retval true if emergency cleanup is needed for changelog
905  */
906 static bool mdd_changelog_emrg_cleanup(const struct lu_env *env,
907                                        struct mdd_device *mdd,
908                                        struct llog_handle *lgh)
909 {
910         unsigned long free_entries = llog_cat_free_space(lgh);
911
912         /* free space GC is disabled or is in progress already */
913         if (!mdd->mdd_changelog_free_space_gc || mdd->mdd_changelog_emrg_gc)
914                 return false;
915
916         if (free_entries <= mdd->mdd_changelog_min_free_cat_entries) {
917                 CWARN("%s: changelog has only %lu free catalog entries\n",
918                       mdd2obd_dev(mdd)->obd_name, free_entries);
919                 mdd->mdd_changelog_emrg_gc = true;
920                 return true;
921         }
922
923         if (!mdd_changelog_is_space_safe(env, mdd, lgh, true)) {
924                 mdd->mdd_changelog_emrg_gc = true;
925                 return true;
926         }
927
928         return false;
929 }
930
931 static bool mdd_changelog_need_gc(const struct lu_env *env,
932                                   struct mdd_device *mdd,
933                                   struct llog_handle *lgh)
934 {
935         struct mdd_changelog *mc = &mdd->mdd_cl;
936
937         return mdd_changelog_emrg_cleanup(env, mdd, lgh) ||
938                mdd_changelog_is_too_idle(mdd, mc->mc_minrec, mc->mc_mintime) ||
939                CFS_FAIL_CHECK(OBD_FAIL_FORCE_GC_THREAD);
940 }
941
942 /** Add a changelog entry \a rec to the changelog llog
943  * \param mdd
944  * \param rec
945  * \param handle - currently ignored since llogs start their own transaction;
946  *              this will hopefully be fixed in llog rewrite
947  * \retval 0 ok
948  */
949 int mdd_changelog_store(const struct lu_env *env, struct mdd_device *mdd,
950                         struct llog_changelog_rec *rec, struct thandle *th)
951 {
952         struct obd_device *obd = mdd2obd_dev(mdd);
953         struct llog_ctxt *ctxt;
954         struct thandle *llog_th;
955         int rc;
956         bool need_gc;
957
958         rec->cr_hdr.lrh_len = llog_data_len(sizeof(*rec) +
959                                             changelog_rec_varsize(&rec->cr));
960
961         /* llog_lvfs_write_rec sets the llog tail len */
962         rec->cr_hdr.lrh_type = CHANGELOG_REC;
963         rec->cr.cr_time = cl_time();
964
965         ctxt = llog_get_context(obd, LLOG_CHANGELOG_ORIG_CTXT);
966         if (ctxt == NULL)
967                 return -ENXIO;
968
969         llog_th = thandle_get_sub(env, th, ctxt->loc_handle->lgh_obj);
970         if (IS_ERR(llog_th))
971                 GOTO(out_put, rc = PTR_ERR(llog_th));
972
973         CFS_FAIL_TIMEOUT(OBD_FAIL_MDS_CHANGELOG_REORDER, cfs_fail_val);
974         /* nested journal transaction */
975         rc = llog_add(env, ctxt->loc_handle, &rec->cr_hdr, NULL, llog_th);
976
977         /* time to recover some space ?? */
978         if (likely(!mdd->mdd_changelog_gc ||
979                    mdd->mdd_cl.mc_gc_task != MDD_CHLG_GC_NONE ||
980                    mdd->mdd_changelog_min_gc_interval >=
981                         ktime_get_real_seconds() - mdd->mdd_cl.mc_gc_time))
982                 /* save a spin_lock trip */
983                 goto out_put;
984
985         if (CFS_FAIL_PRECHECK(OBD_FAIL_MDS_CHANGELOG_IDX_PUMP)) {
986                 spin_lock(&mdd->mdd_cl.mc_lock);
987                 mdd->mdd_cl.mc_index += cfs_fail_val;
988                 spin_unlock(&mdd->mdd_cl.mc_lock);
989         }
990
991         need_gc = mdd_changelog_need_gc(env, mdd, ctxt->loc_handle);
992         spin_lock(&mdd->mdd_cl.mc_lock);
993         if (likely(mdd->mdd_changelog_gc &&
994                      mdd->mdd_cl.mc_gc_task == MDD_CHLG_GC_NONE &&
995                      ktime_get_real_seconds() - mdd->mdd_cl.mc_gc_time >
996                         mdd->mdd_changelog_min_gc_interval)) {
997                 if (unlikely(need_gc)) {
998                         CWARN("%s:%s starting changelog garbage collection\n",
999                               obd->obd_name,
1000                               CFS_FAIL_CHECK(OBD_FAIL_FORCE_GC_THREAD) ?
1001                               " simulate" : "");
1002                         /* indicate further kthread run will occur outside
1003                          * right after current journal transaction filling has
1004                          * completed
1005                          */
1006                         mdd->mdd_cl.mc_gc_task = MDD_CHLG_GC_NEED;
1007                 }
1008                 /* next check in mdd_changelog_min_gc_interval anyway
1009                  */
1010                 mdd->mdd_cl.mc_gc_time = ktime_get_real_seconds();
1011         }
1012         spin_unlock(&mdd->mdd_cl.mc_lock);
1013 out_put:
1014         llog_ctxt_put(ctxt);
1015         if (rc > 0)
1016                 rc = 0;
1017         return rc;
1018 }
1019
1020 static void mdd_changelog_rec_ext_rename(struct changelog_rec *rec,
1021                                          const struct lu_fid *sfid,
1022                                          const struct lu_fid *spfid,
1023                                          const struct lu_name *sname)
1024 {
1025         struct changelog_ext_rename *rnm = changelog_rec_rename(rec);
1026         size_t extsize;
1027
1028         LASSERT(sfid != NULL);
1029         LASSERT(spfid != NULL);
1030         LASSERT(sname != NULL);
1031
1032         extsize = sname->ln_namelen + 1;
1033
1034         rnm->cr_sfid = *sfid;
1035         rnm->cr_spfid = *spfid;
1036
1037         changelog_rec_name(rec)[rec->cr_namelen] = '\0';
1038         strlcpy(changelog_rec_sname(rec), sname->ln_name, extsize);
1039         rec->cr_namelen += extsize;
1040 }
1041
1042 void mdd_changelog_rec_ext_jobid(struct changelog_rec *rec, const char *jobid)
1043 {
1044         struct changelog_ext_jobid *jid = changelog_rec_jobid(rec);
1045
1046         if (jobid == NULL || jobid[0] == '\0')
1047                 return;
1048
1049         strlcpy(jid->cr_jobid, jobid, sizeof(jid->cr_jobid));
1050 }
1051
1052 void mdd_changelog_rec_ext_extra_flags(struct changelog_rec *rec, __u64 eflags)
1053 {
1054         struct changelog_ext_extra_flags *ef = changelog_rec_extra_flags(rec);
1055
1056         ef->cr_extra_flags = eflags;
1057 }
1058
1059 void mdd_changelog_rec_extra_uidgid(struct changelog_rec *rec,
1060                                     __u64 uid, __u64 gid)
1061 {
1062         struct changelog_ext_uidgid *uidgid = changelog_rec_uidgid(rec);
1063
1064         uidgid->cr_uid = uid;
1065         uidgid->cr_gid = gid;
1066 }
1067
1068 void mdd_changelog_rec_extra_nid(struct changelog_rec *rec,
1069                                  lnet_nid_t nid)
1070 {
1071         struct changelog_ext_nid *clnid = changelog_rec_nid(rec);
1072
1073         clnid->cr_nid = nid;
1074 }
1075
1076 void mdd_changelog_rec_extra_omode(struct changelog_rec *rec, u32 flags)
1077 {
1078         struct changelog_ext_openmode *omd = changelog_rec_openmode(rec);
1079
1080         omd->cr_openflags = flags;
1081 }
1082
1083 void mdd_changelog_rec_extra_xattr(struct changelog_rec *rec,
1084                                    const char *xattr_name)
1085 {
1086         struct changelog_ext_xattr *xattr = changelog_rec_xattr(rec);
1087
1088         strlcpy(xattr->cr_xattr, xattr_name, sizeof(xattr->cr_xattr));
1089 }
1090
1091 /**
1092  * Set the parent FID at \a pfid for a namespace change changelog record, using
1093  * XATTR_NAME_LMV and linkEA from the remote object to obtain the correct
1094  * parent FID for striped directories
1095  *
1096  * \param[in] env - environment
1097  * \param[in] mdd - mdd device
1098  * \param[in] parent - parent object
1099  * \param[in] pattr - parent attribute
1100  * \param[out] pfid - parent fid
1101  *
1102  * \retval 0 success
1103  * \retval -errno failure
1104  */
1105 int mdd_changelog_ns_pfid_set(const struct lu_env *env, struct mdd_device *mdd,
1106                               struct mdd_object *parent,
1107                               const struct lu_attr *pattr, struct lu_fid *pfid)
1108 {
1109         int rc = 0;
1110
1111         /* Certain userspace tools might rely on the previous behavior of
1112          * displaying the shard's parent FID, on some changelog records related
1113          * to striped directories, so use that for compatibility if needed
1114          */
1115         if (mdd->mdd_cl.mc_enable_shard_pfid) {
1116                 *pfid = *mdd_object_fid(parent);
1117                 return 0;
1118         }
1119
1120         if (!fid_is_zero(&parent->mod_striped_pfid)) {
1121                 *pfid = parent->mod_striped_pfid;
1122                 return 0;
1123         }
1124
1125         /* is the parent dir striped? */
1126         rc = mdo_xattr_get(env, parent, &LU_BUF_NULL, XATTR_NAME_LMV);
1127         if (rc == -ENODATA) {
1128                 *pfid = *mdd_object_fid(parent);
1129                 parent->mod_striped_pfid = *pfid;
1130                 return 0;
1131         }
1132
1133         if (rc < 0)
1134                 return rc;
1135
1136         LASSERT(!mdd_is_root(mdo2mdd(&parent->mod_obj),
1137                              mdd_object_fid(parent)));
1138
1139         /* hide shard FID */
1140         rc = mdd_parent_fid(env, parent, pattr, pfid);
1141         if (!rc)
1142                 parent->mod_striped_pfid = *pfid;
1143
1144         return rc;
1145 }
1146
1147 /** Store a namespace change changelog record
1148  * If this fails, we must fail the whole transaction; we don't
1149  * want the change to commit without the log entry.
1150  * \param target - mdd_object of change
1151  * \param parent - target parent object
1152  * \param pattr - target parent attribute
1153  * \param sfid - source object fid
1154  * \param sparent - source parent object
1155  * \param spattr - source parent attribute
1156  * \param tname - target name string
1157  * \param sname - source name string
1158  * \param handle - transaction handle
1159  */
1160 int mdd_changelog_ns_store(const struct lu_env *env,
1161                            struct mdd_device *mdd,
1162                            enum changelog_rec_type type,
1163                            enum changelog_rec_flags clf_flags,
1164                            struct mdd_object *target,
1165                            struct mdd_object *parent,
1166                            const struct lu_attr *pattr,
1167                            const struct lu_fid *sfid,
1168                            struct mdd_object *sparent,
1169                            const struct lu_attr *spattr,
1170                            const struct lu_name *tname,
1171                            const struct lu_name *sname,
1172                            struct thandle *handle)
1173 {
1174         const struct lu_ucred           *uc = lu_ucred(env);
1175         struct llog_changelog_rec       *rec;
1176         struct lu_buf                   *buf;
1177         int                              reclen;
1178         __u64                            xflags = CLFE_INVALID;
1179         int                              rc;
1180         ENTRY;
1181
1182         if (!mdd_changelog_enabled(env, mdd, type))
1183                 RETURN(0);
1184
1185         LASSERT(S_ISDIR(mdd_object_type(parent)));
1186         LASSERT(tname != NULL);
1187         LASSERT(handle != NULL);
1188
1189         reclen = mdd_llog_record_calc_size(env, tname, sname);
1190         buf = lu_buf_check_and_alloc(&mdd_env_info(env)->mdi_chlg_buf, reclen);
1191         if (buf->lb_buf == NULL)
1192                 RETURN(-ENOMEM);
1193         rec = buf->lb_buf;
1194
1195         clf_flags &= CLF_FLAGMASK;
1196         clf_flags |= CLF_EXTRA_FLAGS;
1197
1198         if (uc) {
1199                 if (uc->uc_jobid[0] != '\0')
1200                         clf_flags |= CLF_JOBID;
1201                 xflags |= CLFE_UIDGID;
1202                 xflags |= CLFE_NID;
1203         }
1204
1205         if (sname != NULL)
1206                 clf_flags |= CLF_RENAME;
1207         else
1208                 clf_flags |= CLF_VERSION;
1209
1210         rec->cr.cr_flags = clf_flags;
1211
1212         if (clf_flags & CLF_EXTRA_FLAGS) {
1213                 mdd_changelog_rec_ext_extra_flags(&rec->cr, xflags);
1214                 if (xflags & CLFE_UIDGID)
1215                         mdd_changelog_rec_extra_uidgid(&rec->cr,
1216                                                        uc->uc_uid, uc->uc_gid);
1217                 if (xflags & CLFE_NID)
1218                         mdd_changelog_rec_extra_nid(&rec->cr, uc->uc_nid);
1219         }
1220
1221         rec->cr.cr_type = (__u32)type;
1222
1223         rc = mdd_changelog_ns_pfid_set(env, mdd, parent, pattr,
1224                                        &rec->cr.cr_pfid);
1225         if (rc < 0)
1226                 RETURN(rc);
1227
1228         rec->cr.cr_namelen = tname->ln_namelen;
1229         memcpy(changelog_rec_name(&rec->cr), tname->ln_name, tname->ln_namelen);
1230
1231         if (clf_flags & CLF_RENAME) {
1232                 struct lu_fid spfid;
1233
1234                 rc = mdd_changelog_ns_pfid_set(env, mdd, sparent, spattr,
1235                                                &spfid);
1236                 if (rc < 0)
1237                         RETURN(rc);
1238
1239                 mdd_changelog_rec_ext_rename(&rec->cr, sfid, &spfid, sname);
1240         }
1241
1242         if (clf_flags & CLF_JOBID)
1243                 mdd_changelog_rec_ext_jobid(&rec->cr, uc->uc_jobid);
1244
1245         if (likely(target != NULL)) {
1246                 rec->cr.cr_tfid = *mdd_object_fid(target);
1247                 target->mod_cltime = ktime_get();
1248         } else {
1249                 fid_zero(&rec->cr.cr_tfid);
1250         }
1251
1252         rc = mdd_changelog_store(env, mdd, rec, handle);
1253         if (rc < 0) {
1254                 CERROR("%s: cannot store changelog record: type = %d, "
1255                        "name = '%s', t = "DFID", p = "DFID": rc = %d\n",
1256                        mdd2obd_dev(mdd)->obd_name, type, tname->ln_name,
1257                        PFID(&rec->cr.cr_tfid), PFID(&rec->cr.cr_pfid), rc);
1258                 return -EFAULT;
1259         }
1260
1261         return 0;
1262 }
1263
1264 static int __mdd_links_add(const struct lu_env *env,
1265                            struct mdd_object *mdd_obj,
1266                            struct linkea_data *ldata,
1267                            const struct lu_name *lname,
1268                            const struct lu_fid *pfid,
1269                            int first, int check)
1270 {
1271         /* cattr is set in mdd_link */
1272         struct lu_attr *cattr = MDD_ENV_VAR(env, cattr);
1273         int rc;
1274
1275         if (ldata->ld_leh == NULL) {
1276                 rc = first ? -ENODATA : mdd_links_read(env, mdd_obj, ldata);
1277                 if (rc) {
1278                         if (rc != -ENODATA)
1279                                 return rc;
1280                         rc = linkea_data_new(ldata,
1281                                              &mdd_env_info(env)->mdi_link_buf);
1282                         if (rc)
1283                                 return rc;
1284                 }
1285         }
1286
1287         if (check) {
1288                 rc = linkea_links_find(ldata, lname, pfid);
1289                 if (rc && rc != -ENOENT)
1290                         return rc;
1291                 if (rc == 0)
1292                         return -EEXIST;
1293         }
1294
1295         if (CFS_FAIL_CHECK(OBD_FAIL_LFSCK_LINKEA_MORE)) {
1296                 struct lu_fid *tfid = &mdd_env_info(env)->mdi_fid2;
1297
1298                 *tfid = *pfid;
1299                 tfid->f_ver = ~0;
1300                 linkea_add_buf(ldata, lname, tfid, false);
1301         }
1302
1303         if (CFS_FAIL_CHECK(OBD_FAIL_LFSCK_LINKEA_MORE2))
1304                 linkea_add_buf(ldata, lname, pfid, false);
1305
1306         /* For encrypted file, we want to limit number of hard links to what
1307          * linkEA can contain. So ask to return error in case of overflow.
1308          * Currently linkEA stores 4KiB of links, that is 14 NAME_MAX links,
1309          * or 119 16-byte names.
1310          */
1311         return linkea_add_buf(ldata, lname, pfid,
1312                               cattr->la_valid & LA_FLAGS &&
1313                               cattr->la_flags & LUSTRE_ENCRYPT_FL);
1314 }
1315
1316 static int __mdd_links_del(const struct lu_env *env,
1317                            struct mdd_object *mdd_obj,
1318                            struct linkea_data *ldata,
1319                            const struct lu_name *lname,
1320                            const struct lu_fid *pfid)
1321 {
1322         /* cattr is set in mdd_link */
1323         struct lu_attr *cattr = MDD_ENV_VAR(env, cattr);
1324         int rc;
1325
1326         if (ldata->ld_leh == NULL) {
1327                 rc = mdd_links_read(env, mdd_obj, ldata);
1328                 if (rc)
1329                         return rc;
1330         }
1331
1332         rc = linkea_links_find(ldata, lname, pfid);
1333         if (rc)
1334                 return rc;
1335
1336         linkea_del_buf(ldata, lname,
1337                        cattr->la_valid & LA_FLAGS &&
1338                        cattr->la_flags & LUSTRE_ENCRYPT_FL);
1339         return 0;
1340 }
1341
1342 static int mdd_linkea_prepare(const struct lu_env *env,
1343                               struct mdd_object *mdd_obj,
1344                               const struct lu_fid *oldpfid,
1345                               const struct lu_name *oldlname,
1346                               const struct lu_fid *newpfid,
1347                               const struct lu_name *newlname,
1348                               int first, int check,
1349                               struct linkea_data *ldata)
1350 {
1351         int rc = 0;
1352         ENTRY;
1353
1354         if (CFS_FAIL_CHECK(OBD_FAIL_FID_IGIF))
1355                 RETURN(0);
1356
1357         LASSERT(oldpfid != NULL || newpfid != NULL);
1358
1359         if (mdd_obj->mod_flags & DEAD_OBJ)
1360                 /* Unnecessary to update linkEA for dead object.  */
1361                 RETURN(0);
1362
1363         if (oldpfid != NULL) {
1364                 rc = __mdd_links_del(env, mdd_obj, ldata, oldlname, oldpfid);
1365                 if (rc) {
1366                         if ((check == 1) || (rc != -ENODATA && rc != -ENOENT))
1367                                 RETURN(rc);
1368
1369                         /* No changes done. */
1370                         rc = 0;
1371                 }
1372         }
1373
1374         /* If renaming, add the new record */
1375         if (newpfid != NULL)
1376                 rc = __mdd_links_add(env, mdd_obj, ldata, newlname, newpfid,
1377                                      first, check);
1378
1379         RETURN(rc);
1380 }
1381
1382 int mdd_links_rename(const struct lu_env *env,
1383                      struct mdd_object *mdd_obj,
1384                      const struct lu_fid *oldpfid,
1385                      const struct lu_name *oldlname,
1386                      const struct lu_fid *newpfid,
1387                      const struct lu_name *newlname,
1388                      struct thandle *handle,
1389                      struct linkea_data *ldata,
1390                      int first, int check)
1391 {
1392         int rc = 0;
1393         ENTRY;
1394
1395         if (ldata == NULL) {
1396                 ldata = &mdd_env_info(env)->mdi_link_data;
1397                 memset(ldata, 0, sizeof(*ldata));
1398                 rc = mdd_linkea_prepare(env, mdd_obj, oldpfid, oldlname,
1399                                         newpfid, newlname, first, check, ldata);
1400                 if (rc)
1401                         GOTO(out, rc);
1402         }
1403
1404         if (!(mdd_obj->mod_flags & DEAD_OBJ))
1405                 rc = mdd_links_write(env, mdd_obj, ldata, handle);
1406
1407         GOTO(out, rc);
1408
1409 out:
1410         if (rc != 0) {
1411                 if (newlname == NULL)
1412                         CERROR("link_ea add failed %d "DFID"\n",
1413                                rc, PFID(mdd_object_fid(mdd_obj)));
1414                 else if (oldpfid == NULL)
1415                         CERROR("link_ea add '%.*s' failed %d "DFID"\n",
1416                                newlname->ln_namelen, newlname->ln_name, rc,
1417                                PFID(mdd_object_fid(mdd_obj)));
1418                 else if (newpfid == NULL)
1419                         CERROR("link_ea del '%.*s' failed %d "DFID"\n",
1420                                oldlname->ln_namelen, oldlname->ln_name, rc,
1421                                PFID(mdd_object_fid(mdd_obj)));
1422                 else
1423                         CERROR("link_ea rename '%.*s'->'%.*s' failed %d "DFID
1424                                "\n", oldlname->ln_namelen, oldlname->ln_name,
1425                                newlname->ln_namelen, newlname->ln_name, rc,
1426                                PFID(mdd_object_fid(mdd_obj)));
1427         }
1428
1429         if (is_vmalloc_addr(ldata->ld_buf))
1430                 /* if we vmalloced a large buffer drop it */
1431                 lu_buf_free(ldata->ld_buf);
1432
1433         return rc;
1434 }
1435
1436 static inline int mdd_links_add(const struct lu_env *env,
1437                                 struct mdd_object *mdd_obj,
1438                                 const struct lu_fid *pfid,
1439                                 const struct lu_name *lname,
1440                                 struct thandle *handle,
1441                                 struct linkea_data *ldata, int first)
1442 {
1443         return mdd_links_rename(env, mdd_obj, NULL, NULL,
1444                                 pfid, lname, handle, ldata, first, 0);
1445 }
1446
1447 static inline int mdd_links_del(const struct lu_env *env,
1448                                 struct mdd_object *mdd_obj,
1449                                 const struct lu_fid *pfid,
1450                                 const struct lu_name *lname,
1451                                 struct thandle *handle)
1452 {
1453         return mdd_links_rename(env, mdd_obj, pfid, lname,
1454                                 NULL, NULL, handle, NULL, 0, 0);
1455 }
1456
1457 /** Read the link EA into a temp buffer.
1458  * Uses the name_buf since it is generally large.
1459  * \retval IS_ERR err
1460  * \retval ptr to \a lu_buf (always \a mdi_link_buf)
1461  */
1462 struct lu_buf *mdd_links_get(const struct lu_env *env,
1463                              struct mdd_object *mdd_obj)
1464 {
1465         struct linkea_data ldata = { NULL };
1466         int rc;
1467
1468         rc = mdd_links_read(env, mdd_obj, &ldata);
1469         return rc ? ERR_PTR(rc) : ldata.ld_buf;
1470 }
1471
1472 int mdd_links_write(const struct lu_env *env, struct mdd_object *mdd_obj,
1473                     struct linkea_data *ldata, struct thandle *handle)
1474 {
1475         const struct lu_buf *buf;
1476         int                 rc;
1477
1478         if (ldata == NULL || ldata->ld_buf == NULL ||
1479             ldata->ld_leh == NULL)
1480                 return 0;
1481
1482         if (CFS_FAIL_CHECK(OBD_FAIL_LFSCK_NO_LINKEA))
1483                 return 0;
1484
1485 again:
1486         buf = mdd_buf_get_const(env, ldata->ld_buf->lb_buf,
1487                                 ldata->ld_leh->leh_len);
1488         rc = mdo_xattr_set(env, mdd_obj, buf, XATTR_NAME_LINK, 0, handle);
1489         if (unlikely(rc == -ENOSPC)) {
1490                 rc = linkea_overflow_shrink(ldata);
1491                 if (likely(rc > 0))
1492                         goto again;
1493         }
1494
1495         return rc;
1496 }
1497
1498 static int mdd_declare_links_add(const struct lu_env *env,
1499                                  struct mdd_object *mdd_obj,
1500                                  struct thandle *handle,
1501                                  struct linkea_data *ldata)
1502 {
1503         int     rc;
1504         int     ea_len;
1505         void    *linkea;
1506
1507         if (ldata != NULL && ldata->ld_leh != NULL) {
1508                 ea_len = ldata->ld_leh->leh_len;
1509                 linkea = ldata->ld_buf->lb_buf;
1510         } else {
1511                 ea_len = MAX_LINKEA_SIZE;
1512                 linkea = NULL;
1513         }
1514
1515         rc = mdo_declare_xattr_set(env, mdd_obj,
1516                                    mdd_buf_get_const(env, linkea, ea_len),
1517                                    XATTR_NAME_LINK, 0, handle);
1518
1519         return rc;
1520 }
1521
1522 static inline int mdd_declare_links_del(const struct lu_env *env,
1523                                         struct mdd_object *c,
1524                                         struct thandle *handle)
1525 {
1526         int rc = 0;
1527
1528         /* For directory, the linkEA will be removed together
1529          * with the object. */
1530         if (!S_ISDIR(mdd_object_type(c)))
1531                 rc = mdd_declare_links_add(env, c, handle, NULL);
1532
1533         return rc;
1534 }
1535
1536 static int mdd_declare_link(const struct lu_env *env,
1537                             struct mdd_device *mdd,
1538                             struct mdd_object *p,
1539                             struct mdd_object *c,
1540                             const struct lu_name *name,
1541                             struct thandle *handle,
1542                             struct lu_attr *la,
1543                             struct linkea_data *data)
1544 {
1545         struct lu_fid tfid = *mdd_object_fid(c);
1546         int rc;
1547
1548         if (CFS_FAIL_CHECK(OBD_FAIL_LFSCK_DANGLING3))
1549                 tfid.f_oid = cfs_fail_val;
1550
1551         rc = mdo_declare_index_insert(env, p, &tfid, mdd_object_type(c),
1552                                       name->ln_name, handle);
1553         if (rc != 0)
1554                 return rc;
1555
1556         rc = mdo_declare_ref_add(env, c, handle);
1557         if (rc != 0)
1558                 return rc;
1559
1560         la->la_valid = LA_CTIME | LA_MTIME;
1561         rc = mdo_declare_attr_set(env, p, la, handle);
1562         if (rc != 0)
1563                 return rc;
1564
1565         la->la_valid = LA_CTIME;
1566         rc = mdo_declare_attr_set(env, c, la, handle);
1567         if (rc != 0)
1568                 return rc;
1569
1570         rc = mdd_declare_links_add(env, c, handle, data);
1571         if (rc != 0)
1572                 return rc;
1573
1574         rc = mdd_declare_changelog_store(env, mdd, CL_HARDLINK, name, NULL,
1575                                          handle);
1576
1577         return rc;
1578 }
1579
1580 static int mdd_link(const struct lu_env *env, struct md_object *tgt_obj,
1581                     struct md_object *src_obj, const struct lu_name *lname,
1582                     struct md_attr *ma)
1583 {
1584         const char *name = lname->ln_name;
1585         struct lu_attr *la = &mdd_env_info(env)->mdi_la_for_fix;
1586         struct mdd_object *mdd_tobj = md2mdd_obj(tgt_obj);
1587         struct mdd_object *mdd_sobj = md2mdd_obj(src_obj);
1588         struct lu_attr *cattr = MDD_ENV_VAR(env, cattr);
1589         struct lu_attr *tattr = MDD_ENV_VAR(env, tattr);
1590         struct mdd_device *mdd = mdo2mdd(src_obj);
1591         struct thandle *handle;
1592         struct lu_fid *tfid = &mdd_env_info(env)->mdi_fid2;
1593         struct linkea_data *ldata = &mdd_env_info(env)->mdi_link_data;
1594         int rc;
1595         ENTRY;
1596
1597         rc = mdd_la_get(env, mdd_sobj, cattr);
1598         if (rc != 0)
1599                 RETURN(rc);
1600
1601         rc = mdd_la_get(env, mdd_tobj, tattr);
1602         if (rc != 0)
1603                 RETURN(rc);
1604
1605         /*
1606          * If we are using project inheritance, we only allow hard link
1607          * creation in our tree when the project IDs are the same;
1608          * otherwise the tree quota mechanism could be circumvented.
1609          */
1610         if ((tattr->la_flags & LUSTRE_PROJINHERIT_FL) &&
1611             (tattr->la_projid != cattr->la_projid))
1612                 RETURN(-EXDEV);
1613
1614         handle = mdd_trans_create(env, mdd);
1615         if (IS_ERR(handle))
1616                 GOTO(out_pending, rc = PTR_ERR(handle));
1617
1618         memset(ldata, 0, sizeof(*ldata));
1619
1620         LASSERT(ma->ma_attr.la_valid & LA_CTIME);
1621         la->la_ctime = la->la_mtime = ma->ma_attr.la_ctime;
1622
1623         /* Note: even this function will change ldata, but it comes from
1624          * thread_info, which is completely temporary and only seen in
1625          * this function, so we do not need reset ldata once it fails.*/
1626         rc = mdd_linkea_prepare(env, mdd_sobj, NULL, NULL,
1627                                 mdd_object_fid(mdd_tobj), lname, 0, 0, ldata);
1628         if (rc != 0)
1629                 GOTO(stop, rc);
1630
1631         rc = mdd_declare_link(env, mdd, mdd_tobj, mdd_sobj, lname, handle,
1632                               la, ldata);
1633         if (rc)
1634                 GOTO(stop, rc);
1635
1636         rc = mdd_trans_start(env, mdd, handle);
1637         if (rc)
1638                 GOTO(stop, rc);
1639
1640         mdd_write_lock(env, mdd_sobj, DT_TGT_CHILD);
1641         rc = mdd_link_sanity_check(env, mdd_tobj, tattr, lname, mdd_sobj,
1642                                    cattr);
1643         if (rc)
1644                 GOTO(out_unlock, rc);
1645
1646         if (!CFS_FAIL_CHECK(OBD_FAIL_LFSCK_LESS_NLINK)) {
1647                 rc = mdo_ref_add(env, mdd_sobj, handle);
1648                 if (rc != 0)
1649                         GOTO(out_unlock, rc);
1650         }
1651
1652         *tfid = *mdd_object_fid(mdd_sobj);
1653         if (CFS_FAIL_CHECK(OBD_FAIL_LFSCK_DANGLING3))
1654                 tfid->f_oid = cfs_fail_val;
1655
1656         rc = __mdd_index_insert_only(env, mdd_tobj, tfid,
1657                                      mdd_object_type(mdd_sobj), name, handle);
1658         if (rc != 0) {
1659                 mdo_ref_del(env, mdd_sobj, handle);
1660                 GOTO(out_unlock, rc);
1661         }
1662
1663         la->la_valid = LA_CTIME | LA_MTIME;
1664         rc = mdd_update_time(env, mdd_tobj, tattr, la, handle);
1665         if (rc)
1666                 GOTO(out_unlock, rc);
1667
1668         la->la_valid = LA_CTIME;
1669         rc = mdd_update_time(env, mdd_sobj, cattr, la, handle);
1670         if (rc == 0)
1671                 /* Note: The failure of links_add should not cause the
1672                  * link failure, so do not check return value. */
1673                 mdd_links_add(env, mdd_sobj, mdd_object_fid(mdd_tobj),
1674                               lname, handle, ldata, 0);
1675
1676         EXIT;
1677 out_unlock:
1678         mdd_write_unlock(env, mdd_sobj);
1679         if (rc == 0)
1680                 rc = mdd_changelog_ns_store(env, mdd, CL_HARDLINK, 0, mdd_sobj,
1681                                             mdd_tobj, tattr, NULL,
1682                                             NULL, NULL, lname, NULL, handle);
1683 stop:
1684         rc = mdd_trans_stop(env, mdd, rc, handle);
1685         if (is_vmalloc_addr(ldata->ld_buf))
1686                 /* if we vmalloced a large buffer drop it */
1687                 lu_buf_free(ldata->ld_buf);
1688 out_pending:
1689         return rc;
1690 }
1691
1692 static int mdd_mark_orphan_object(const struct lu_env *env,
1693                                 struct mdd_object *obj, struct thandle *handle,
1694                                 bool declare)
1695 {
1696         struct lu_attr *attr = MDD_ENV_VAR(env, la_for_start);
1697         int rc;
1698
1699         attr->la_valid = LA_FLAGS;
1700         attr->la_flags = LUSTRE_ORPHAN_FL;
1701
1702         if (declare)
1703                 rc = mdo_declare_attr_set(env, obj, attr, handle);
1704         else
1705                 rc = mdo_attr_set(env, obj, attr, handle);
1706
1707         return rc;
1708 }
1709
1710 static int mdd_declare_finish_unlink(const struct lu_env *env,
1711                                      struct mdd_object *obj,
1712                                      struct thandle *handle)
1713 {
1714         int rc;
1715
1716         /* Sigh, we do not know if the unlink object will become orphan in
1717          * declare phase, but fortunately the flags here does not matter
1718          * in current declare implementation */
1719         rc = mdd_mark_orphan_object(env, obj, handle, true);
1720         if (rc != 0)
1721                 return rc;
1722
1723         rc = mdo_declare_destroy(env, obj, handle);
1724         if (rc != 0)
1725                 return rc;
1726
1727         rc = mdd_orphan_declare_insert(env, obj, mdd_object_type(obj), handle);
1728         if (rc != 0)
1729                 return rc;
1730
1731         return mdd_declare_links_del(env, obj, handle);
1732 }
1733
1734 /* caller should take a lock before calling */
1735 int mdd_finish_unlink(const struct lu_env *env,
1736                       struct mdd_object *obj, struct md_attr *ma,
1737                       struct mdd_object *pobj,
1738                       const struct lu_name *lname,
1739                       struct thandle *th)
1740 {
1741         int rc = 0;
1742         int is_dir = S_ISDIR(ma->ma_attr.la_mode);
1743         ENTRY;
1744
1745         LASSERT(mdd_write_locked(env, obj) != 0);
1746
1747         if (ma->ma_attr.la_nlink == 0 || is_dir) {
1748                 /* add new orphan and the object
1749                  * will be deleted during mdd_close() */
1750                 obj->mod_flags |= DEAD_OBJ;
1751                 if (obj->mod_count) {
1752                         rc = mdd_orphan_insert(env, obj, th);
1753                         if (rc == 0)
1754                                 CDEBUG(D_HA, "Object "DFID" is inserted into "
1755                                         "orphan list, open count = %d\n",
1756                                         PFID(mdd_object_fid(obj)),
1757                                         obj->mod_count);
1758                         else
1759                                 CERROR("Object "DFID" fail to be an orphan, "
1760                                        "open count = %d, maybe cause failed "
1761                                        "open replay\n",
1762                                         PFID(mdd_object_fid(obj)),
1763                                         obj->mod_count);
1764
1765                         /* mark object as an orphan here, not
1766                          * before mdd_orphan_insert() as racing
1767                          * mdd_la_get() may propagate ORPHAN_OBJ
1768                          * causing the asserition */
1769                         rc = mdd_mark_orphan_object(env, obj, th, false);
1770                 } else {
1771                         rc = mdo_destroy(env, obj, th);
1772                 }
1773         } else if (!is_dir) {
1774                 /* old files may not have link ea; ignore errors */
1775                 mdd_links_del(env, obj, mdd_object_fid(pobj), lname, th);
1776         }
1777
1778         RETURN(rc);
1779 }
1780
1781 /*
1782  * pobj maybe NULL
1783  * has mdd_write_lock on cobj already, but not on pobj yet
1784  */
1785 int mdd_unlink_sanity_check(const struct lu_env *env, struct mdd_object *pobj,
1786                             const struct lu_attr *pattr,
1787                             struct mdd_object *cobj,
1788                             const struct lu_attr *cattr)
1789 {
1790         int rc;
1791         ENTRY;
1792
1793         rc = mdd_may_delete(env, pobj, pattr, cobj, cattr, NULL, 1, 1);
1794
1795         RETURN(rc);
1796 }
1797
1798 static int mdd_declare_unlink(const struct lu_env *env, struct mdd_device *mdd,
1799                               struct mdd_object *p, struct mdd_object *c,
1800                               const struct lu_name *name, struct md_attr *ma,
1801                               struct thandle *handle, int no_name, int is_dir)
1802 {
1803         struct lu_attr *la = &mdd_env_info(env)->mdi_la_for_fix;
1804         int rc;
1805
1806         if (!CFS_FAIL_CHECK(OBD_FAIL_LFSCK_DANGLING2)) {
1807                 if (likely(no_name == 0)) {
1808                         rc = mdo_declare_index_delete(env, p, name->ln_name,
1809                                                       handle);
1810                         if (rc != 0)
1811                                 return rc;
1812                 }
1813
1814                 if (is_dir != 0) {
1815                         rc = mdo_declare_ref_del(env, p, handle);
1816                         if (rc != 0)
1817                                 return rc;
1818                 }
1819         }
1820
1821         LASSERT(ma->ma_attr.la_valid & LA_CTIME);
1822         la->la_ctime = la->la_mtime = ma->ma_attr.la_ctime;
1823         la->la_valid = LA_CTIME | LA_MTIME;
1824         rc = mdo_declare_attr_set(env, p, la, handle);
1825         if (rc)
1826                 return rc;
1827
1828         if (c != NULL) {
1829                 rc = mdo_declare_ref_del(env, c, handle);
1830                 if (rc)
1831                         return rc;
1832
1833                 rc = mdo_declare_ref_del(env, c, handle);
1834                 if (rc)
1835                         return rc;
1836
1837                 la->la_valid = LA_CTIME;
1838                 rc = mdo_declare_attr_set(env, c, la, handle);
1839                 if (rc)
1840                         return rc;
1841
1842                 rc = mdd_declare_finish_unlink(env, c, handle);
1843                 if (rc)
1844                         return rc;
1845
1846                 /* FIXME: need changelog for remove entry */
1847                 rc = mdd_declare_changelog_store(env, mdd, CL_UNLINK, name,
1848                                                  NULL, handle);
1849         }
1850
1851         return rc;
1852 }
1853
1854 /*
1855  * test if a file has an HSM archive
1856  * if HSM attributes are not found in ma update them from
1857  * HSM xattr
1858  */
1859 static bool mdd_hsm_archive_exists(const struct lu_env *env,
1860                                    struct mdd_object *obj,
1861                                    struct md_attr *ma)
1862 {
1863         ENTRY;
1864
1865         if (!(ma->ma_valid & MA_HSM)) {
1866                 /* no HSM MD provided, read xattr */
1867                 struct lu_buf   *hsm_buf;
1868                 const size_t     buflen = sizeof(struct hsm_attrs);
1869                 int              rc;
1870
1871                 hsm_buf = mdd_buf_get(env, NULL, 0);
1872                 lu_buf_alloc(hsm_buf, buflen);
1873                 rc = mdo_xattr_get(env, obj, hsm_buf, XATTR_NAME_HSM);
1874                 rc = lustre_buf2hsm(hsm_buf->lb_buf, rc, &ma->ma_hsm);
1875                 lu_buf_free(hsm_buf);
1876                 if (rc < 0)
1877                         RETURN(false);
1878
1879                 ma->ma_valid |= MA_HSM;
1880         }
1881         if (ma->ma_hsm.mh_flags & HS_EXISTS)
1882                 RETURN(true);
1883         RETURN(false);
1884 }
1885
1886 /**
1887  * Delete name entry and the object.
1888  * Note: no_name == 1 means it only destory the object, i.e. name_entry
1889  * does not exist for this object, and it could only happen during resending
1890  * of remote unlink. see the comments in mdt_reint_unlink. Unfortunately, lname
1891  * is also needed in this case(needed by changelog), so we have to add another
1892  * parameter(no_name)here. XXX: this is only needed in DNE phase I, on Phase II,
1893  * the ENOENT failure should be able to be fixed by redo mechanism.
1894  */
1895 static int mdd_unlink(const struct lu_env *env, struct md_object *pobj,
1896                       struct md_object *cobj, const struct lu_name *lname,
1897                       struct md_attr *ma, int no_name)
1898 {
1899         char *name = (char *)lname->ln_name;
1900         struct lu_attr *pattr = MDD_ENV_VAR(env, pattr);
1901         struct lu_attr *cattr = MDD_ENV_VAR(env, cattr);
1902         struct lu_attr *la = &mdd_env_info(env)->mdi_la_for_fix;
1903         struct mdd_object *mdd_pobj = md2mdd_obj(pobj);
1904         struct mdd_object *mdd_cobj = NULL;
1905         struct mdd_device *mdd = mdo2mdd(pobj);
1906         struct thandle    *handle;
1907         int rc, is_dir = 0, cl_flags = 0;
1908         ENTRY;
1909
1910         /* let shutdown to start */
1911         CFS_FAIL_TIMEOUT(OBD_FAIL_TGT_REPLY_DATA_RACE, 1);
1912
1913         /* cobj == NULL means only delete name entry */
1914         if (likely(cobj != NULL)) {
1915                 mdd_cobj = md2mdd_obj(cobj);
1916                 if (mdd_object_exists(mdd_cobj) == 0)
1917                         RETURN(-ENOENT);
1918         }
1919
1920         rc = mdd_la_get(env, mdd_pobj, pattr);
1921         if (rc)
1922                 RETURN(rc);
1923
1924         if (likely(mdd_cobj != NULL)) {
1925                 /* fetch cattr */
1926                 rc = mdd_la_get(env, mdd_cobj, cattr);
1927                 if (rc)
1928                         RETURN(rc);
1929
1930                 is_dir = S_ISDIR(cattr->la_mode);
1931                 /* search for an existing archive.
1932                  * we should check ahead as the object
1933                  * can be destroyed in this transaction */
1934                 if (mdd_hsm_archive_exists(env, mdd_cobj, ma))
1935                         cl_flags |= CLF_UNLINK_HSM_EXISTS;
1936         }
1937
1938         rc = mdd_unlink_sanity_check(env, mdd_pobj, pattr, mdd_cobj, cattr);
1939         if (rc)
1940                 RETURN(rc);
1941
1942         handle = mdd_trans_create(env, mdd);
1943         if (IS_ERR(handle))
1944                 RETURN(PTR_ERR(handle));
1945
1946         rc = mdd_declare_unlink(env, mdd, mdd_pobj, mdd_cobj,
1947                                 lname, ma, handle, no_name, is_dir);
1948         if (rc)
1949                 GOTO(stop, rc);
1950
1951         rc = mdd_trans_start(env, mdd, handle);
1952         if (rc)
1953                 GOTO(stop, rc);
1954
1955         if (likely(mdd_cobj != NULL))
1956                 mdd_write_lock(env, mdd_cobj, DT_TGT_CHILD);
1957
1958         if (lname->ln_name[lname->ln_namelen] != '\0') {
1959                 /* lname->ln_name is not necessarily NUL terminated */
1960                 name = kmalloc(lname->ln_namelen + 1, GFP_NOFS);
1961                 if (!name)
1962                         GOTO(cleanup, rc = -ENOMEM);
1963
1964                 memcpy(name, lname->ln_name, lname->ln_namelen);
1965                 name[lname->ln_namelen] = '\0';
1966         }
1967
1968         if (likely(no_name == 0) && !CFS_FAIL_CHECK(OBD_FAIL_LFSCK_DANGLING2)) {
1969                 rc = __mdd_index_delete(env, mdd_pobj, name, is_dir, handle);
1970                 if (rc)
1971                         GOTO(cleanup, rc);
1972         }
1973
1974         if (CFS_FAIL_CHECK(OBD_FAIL_LFSCK_MUL_REF) ||
1975             CFS_FAIL_CHECK(OBD_FAIL_LFSCK_NO_NAMEENTRY))
1976                 GOTO(cleanup, rc = 0);
1977
1978         if (likely(mdd_cobj != NULL)) {
1979                 rc = mdo_ref_del(env, mdd_cobj, handle);
1980                 if (rc != 0) {
1981                         __mdd_index_insert_only(env, mdd_pobj,
1982                                                 mdd_object_fid(mdd_cobj),
1983                                                 mdd_object_type(mdd_cobj),
1984                                                 name, handle);
1985                         GOTO(cleanup, rc);
1986                 }
1987
1988                 if (is_dir)
1989                         /* unlink dot */
1990                         mdo_ref_del(env, mdd_cobj, handle);
1991
1992                 /* fetch updated nlink */
1993                 rc = mdd_la_get(env, mdd_cobj, cattr);
1994                 if (rc)
1995                         GOTO(cleanup, rc);
1996         }
1997
1998         LASSERT(ma->ma_attr.la_valid & LA_CTIME);
1999         la->la_ctime = la->la_mtime = ma->ma_attr.la_ctime;
2000
2001         la->la_valid = LA_CTIME | LA_MTIME;
2002         rc = mdd_update_time(env, mdd_pobj, pattr, la, handle);
2003         if (rc)
2004                 GOTO(cleanup, rc);
2005
2006         /* Enough for only unlink the entry */
2007         if (unlikely(mdd_cobj == NULL))
2008                 GOTO(cleanup, rc);
2009
2010         if (cattr->la_nlink > 0 || mdd_cobj->mod_count > 0) {
2011                 /* update ctime of an unlinked file only if it is still
2012                  * opened or a link still exists */
2013                 la->la_valid = LA_CTIME;
2014                 rc = mdd_update_time(env, mdd_cobj, cattr, la, handle);
2015                 if (rc)
2016                         GOTO(cleanup, rc);
2017         }
2018
2019         /* XXX: this transfer to ma will be removed with LOD/OSP */
2020         ma->ma_attr = *cattr;
2021         ma->ma_valid |= MA_INODE;
2022         rc = mdd_finish_unlink(env, mdd_cobj, ma, mdd_pobj, lname, handle);
2023         if (rc != 0)
2024                 GOTO(cleanup, rc);
2025
2026         /* fetch updated nlink */
2027         rc = mdd_la_get(env, mdd_cobj, cattr);
2028         /* if object is removed then we can't get its attrs,
2029          * use last get */
2030         if (rc == -ENOENT) {
2031                 cattr->la_nlink = 0;
2032                 rc = 0;
2033         }
2034
2035         if (cattr->la_nlink == 0) {
2036                 ma->ma_attr = *cattr;
2037                 ma->ma_valid |= MA_INODE;
2038         }
2039
2040         EXIT;
2041 cleanup:
2042         if (name != lname->ln_name)
2043                 kfree(name);
2044
2045         if (likely(mdd_cobj != NULL))
2046                 mdd_write_unlock(env, mdd_cobj);
2047
2048         if (rc == 0) {
2049                 if (cattr->la_nlink == 0)
2050                         cl_flags |= CLF_UNLINK_LAST;
2051                 else
2052                         cl_flags &= ~CLF_UNLINK_HSM_EXISTS;
2053
2054                 rc = mdd_changelog_ns_store(env, mdd,
2055                         is_dir ? CL_RMDIR : CL_UNLINK, cl_flags,
2056                         mdd_cobj, mdd_pobj, pattr, NULL,
2057                         NULL, NULL, lname, NULL, handle);
2058         }
2059
2060 stop:
2061         rc = mdd_trans_stop(env, mdd, rc, handle);
2062
2063         return rc;
2064 }
2065
2066 /*
2067  * The permission has been checked when obj created, no need check again.
2068  */
2069 static int mdd_cd_sanity_check(const struct lu_env *env,
2070                                struct mdd_object *obj)
2071 {
2072         ENTRY;
2073
2074         /* EEXIST check */
2075         if (!obj || mdd_is_dead_obj(obj))
2076                 RETURN(-ENOENT);
2077
2078         RETURN(0);
2079 }
2080
2081 static int mdd_create_data(const struct lu_env *env, struct md_object *pobj,
2082                            struct md_object *cobj,
2083                            const struct md_op_spec *spec, struct md_attr *ma)
2084 {
2085         struct mdd_device *mdd = mdo2mdd(cobj);
2086         struct mdd_object *mdd_pobj = md2mdd_obj(pobj);
2087         struct mdd_object *son = md2mdd_obj(cobj);
2088         struct thandle *handle;
2089         const struct lu_buf *buf;
2090         struct lu_attr *attr = MDD_ENV_VAR(env, cattr);
2091         struct dt_allocation_hint *hint = &mdd_env_info(env)->mdi_hint;
2092         int rc;
2093         ENTRY;
2094
2095         rc = mdd_cd_sanity_check(env, son);
2096         if (rc)
2097                 RETURN(rc);
2098
2099         if (!md_should_create(spec->sp_cr_flags))
2100                 RETURN(0);
2101
2102         /*
2103          * there are following use cases for this function:
2104          * 1) late striping - file was created with MDS_OPEN_DELAY_CREATE
2105          *    striping can be specified or not
2106          * 2) CMD?
2107          */
2108         rc = mdd_la_get(env, son, attr);
2109         if (rc)
2110                 RETURN(rc);
2111
2112         /* calling ->ah_make_hint() is used to transfer information from parent */
2113         mdd_object_make_hint(env, mdd_pobj, son, attr, spec, hint);
2114
2115         handle = mdd_trans_create(env, mdd);
2116         if (IS_ERR(handle))
2117                 GOTO(out_free, rc = PTR_ERR(handle));
2118
2119         /*
2120          * XXX: Setting the lov ea is not locked but setting the attr is locked?
2121          * Should this be fixed?
2122          */
2123         CDEBUG(D_OTHER, "ea %p/%u, cr_flags %#llo, no_create %u\n",
2124                spec->u.sp_ea.eadata, spec->u.sp_ea.eadatalen,
2125                spec->sp_cr_flags, spec->no_create);
2126
2127         if (spec->no_create || (spec->sp_cr_flags & MDS_OPEN_HAS_EA)) {
2128                 buf = mdd_buf_get_const(env, spec->u.sp_ea.eadata,
2129                                         spec->u.sp_ea.eadatalen);
2130         } else {
2131                 buf = &LU_BUF_NULL;
2132         }
2133
2134         rc = dt_declare_xattr_set(env, mdd_object_child(son), buf,
2135                                   XATTR_NAME_LOV, 0, handle);
2136         if (rc)
2137                 GOTO(stop, rc);
2138
2139         rc = mdd_declare_changelog_store(env, mdd, CL_LAYOUT, NULL, NULL,
2140                                          handle);
2141         if (rc)
2142                 GOTO(stop, rc);
2143
2144         rc = mdd_trans_start(env, mdd, handle);
2145         if (rc)
2146                 GOTO(stop, rc);
2147
2148         rc = dt_xattr_set(env, mdd_object_child(son), buf, XATTR_NAME_LOV,
2149                           0, handle);
2150
2151         if (rc)
2152                 GOTO(stop, rc);
2153
2154         rc = mdd_changelog_data_store(env, mdd, CL_LAYOUT, 0, son, handle,
2155                                       NULL);
2156
2157 stop:
2158         rc = mdd_trans_stop(env, mdd, rc, handle);
2159
2160 out_free:
2161         RETURN(rc);
2162 }
2163
2164 static int mdd_declare_object_initialize(const struct lu_env *env,
2165                                          struct mdd_object *parent,
2166                                          struct mdd_object *child,
2167                                          const struct lu_attr *attr,
2168                                          struct thandle *handle)
2169 {
2170         int rc;
2171         ENTRY;
2172
2173         LASSERT(attr->la_valid & (LA_MODE | LA_TYPE));
2174         if (!S_ISDIR(attr->la_mode))
2175                 RETURN(0);
2176
2177         rc = mdo_declare_index_insert(env, child, mdd_object_fid(child),
2178                                       S_IFDIR, dot, handle);
2179         if (rc != 0)
2180                 RETURN(rc);
2181
2182         rc = mdo_declare_ref_add(env, child, handle);
2183         if (rc != 0)
2184                 RETURN(rc);
2185
2186         rc = mdo_declare_index_insert(env, child, mdd_object_fid(parent),
2187                                       S_IFDIR, dotdot, handle);
2188
2189         RETURN(rc);
2190 }
2191
2192 static int mdd_object_initialize(const struct lu_env *env,
2193                                  const struct lu_fid *pfid,
2194                                  struct mdd_object *child,
2195                                  struct lu_attr *attr,
2196                                  struct thandle *handle)
2197 {
2198         int rc = 0;
2199         ENTRY;
2200
2201         if (S_ISDIR(attr->la_mode)) {
2202                 /* Add "." and ".." for newly created dir */
2203                 mdo_ref_add(env, child, handle);
2204                 rc = __mdd_index_insert_only(env, child, mdd_object_fid(child),
2205                                              S_IFDIR, dot, handle);
2206                 if (rc == 0)
2207                         rc = __mdd_index_insert_only(env, child, pfid, S_IFDIR,
2208                                                      dotdot, handle);
2209                 if (rc != 0)
2210                         mdo_ref_del(env, child, handle);
2211         }
2212
2213         RETURN(rc);
2214 }
2215
2216 /**
2217  * This function checks whether it can create a file/dir under the
2218  * directory(@pobj). The directory(@pobj) is not being locked by
2219  * mdd lock.
2220  *
2221  * \param[in] env       execution environment
2222  * \param[in] pobj      the directory to create files
2223  * \param[in] pattr     the attributes of the directory
2224  * \param[in] lname     the name of the created file/dir
2225  * \param[in] cattr     the attributes of the file/dir
2226  * \param[in] spec      create specification
2227  *
2228  * \retval              = 0 it is allowed to create file/dir under
2229  *                      the directory
2230  * \retval              negative error not allowed to create file/dir
2231  *                      under the directory
2232  */
2233 static int mdd_create_sanity_check(const struct lu_env *env,
2234                                    struct md_object *pobj,
2235                                    const struct lu_attr *pattr,
2236                                    const struct lu_name *lname,
2237                                    struct lu_attr *cattr,
2238                                    struct md_op_spec *spec)
2239 {
2240         struct mdd_thread_info *info = mdd_env_info(env);
2241         struct lu_fid *fid = &info->mdi_fid;
2242         struct mdd_object *obj = md2mdd_obj(pobj);
2243         struct mdd_device *m = mdo2mdd(pobj);
2244         bool check_perm = true;
2245         int rc;
2246         ENTRY;
2247
2248         /* EEXIST check */
2249         if (mdd_is_dead_obj(obj))
2250                 RETURN(-ENOENT);
2251
2252         /*
2253          * In some cases this lookup is not needed - we know before if name
2254          * exists or not because MDT performs lookup for it.
2255          * name length check is done in lookup.
2256          */
2257         if (spec->sp_cr_lookup) {
2258                 /*
2259                  * Check if the name already exist, though it will be checked in
2260                  * _index_insert also, for avoiding rolling back if exists
2261                  * _index_insert.
2262                  */
2263                 rc = __mdd_lookup(env, pobj, pattr, lname, fid,
2264                                   MAY_WRITE | MAY_EXEC);
2265                 if (rc != -ENOENT)
2266                         RETURN(rc ? : -EEXIST);
2267
2268                 /* Permission is already being checked in mdd_lookup */
2269                 check_perm = false;
2270         }
2271
2272         if (S_ISDIR(cattr->la_mode) &&
2273             unlikely(spec != NULL && spec->sp_cr_flags & MDS_OPEN_HAS_EA) &&
2274             spec->u.sp_ea.eadata != NULL && spec->u.sp_ea.eadatalen > 0) {
2275                 const struct lmv_user_md *lum = spec->u.sp_ea.eadata;
2276
2277                 if (!lmv_user_magic_supported(le32_to_cpu(lum->lum_magic)) &&
2278                     !(spec->sp_replay &&
2279                       lum->lum_magic == cpu_to_le32(LMV_MAGIC_V1))) {
2280                         rc = -EINVAL;
2281                         CERROR("%s: invalid lmv_user_md: magic=%x hash=%x stripe_offset=%d stripe_count=%u: rc = %d\n",
2282                                mdd2obd_dev(m)->obd_name,
2283                                le32_to_cpu(lum->lum_magic),
2284                                le32_to_cpu(lum->lum_hash_type),
2285                                (int)le32_to_cpu(lum->lum_stripe_offset),
2286                                le32_to_cpu(lum->lum_stripe_count), rc);
2287                         RETURN(rc);
2288                 }
2289         }
2290
2291         rc = mdd_may_create(env, obj, pattr, NULL, check_perm);
2292         if (rc != 0)
2293                 RETURN(rc);
2294
2295         /* sgid check */
2296         if (pattr->la_mode & S_ISGID) {
2297                 struct lu_ucred *uc = lu_ucred(env);
2298
2299                 cattr->la_gid = pattr->la_gid;
2300
2301                 /* Directories are special, and always inherit S_ISGID */
2302                 if (S_ISDIR(cattr->la_mode)) {
2303                         cattr->la_mode |= S_ISGID;
2304                         cattr->la_valid |= LA_MODE;
2305                 } else if ((cattr->la_mode & (S_ISGID | S_IXGRP))
2306                                 == (S_ISGID | S_IXGRP) &&
2307                            !lustre_in_group_p(uc,
2308                                               (cattr->la_valid & LA_GID) ?
2309                                               cattr->la_gid : pattr->la_gid) &&
2310                            !cap_raised(uc->uc_cap, CAP_FSETID)) {
2311                         cattr->la_mode &= ~S_ISGID;
2312                         cattr->la_valid |= LA_MODE;
2313                 }
2314         }
2315
2316         /* Inherit project ID from parent directory */
2317         if (pattr->la_flags & LUSTRE_PROJINHERIT_FL) {
2318                 cattr->la_projid = pattr->la_projid;
2319                 if (S_ISDIR(cattr->la_mode)) {
2320                         cattr->la_flags |= LUSTRE_PROJINHERIT_FL;
2321                         cattr->la_valid |= LA_FLAGS;
2322                 }
2323                 cattr->la_valid |= LA_PROJID;
2324         }
2325
2326         rc = mdd_name_check(env, m, lname);
2327         if (rc < 0)
2328                 RETURN(rc);
2329
2330         switch (cattr->la_mode & S_IFMT) {
2331         case S_IFLNK: {
2332                 unsigned int symlen = spec->u.sp_symname.ln_namelen + 1;
2333
2334                 if (symlen > m->mdd_dt_conf.ddp_symlink_max)
2335                         RETURN(-ENAMETOOLONG);
2336                 else
2337                         RETURN(0);
2338         }
2339         case S_IFDIR:
2340         case S_IFREG:
2341         case S_IFCHR:
2342         case S_IFBLK:
2343         case S_IFIFO:
2344         case S_IFSOCK:
2345                 rc = 0;
2346                 break;
2347         default:
2348                 rc = -EINVAL;
2349                 break;
2350         }
2351         RETURN(rc);
2352 }
2353
2354 static int mdd_declare_create_object(const struct lu_env *env,
2355                                      struct mdd_device *mdd,
2356                                      struct mdd_object *p, struct mdd_object *c,
2357                                      struct lu_attr *attr,
2358                                      struct thandle *handle,
2359                                      const struct md_op_spec *spec,
2360                                      struct lu_buf *def_acl_buf,
2361                                      struct lu_buf *acl_buf,
2362                                      struct lu_buf *hsm_buf,
2363                                      struct dt_allocation_hint *hint)
2364 {
2365         const struct lu_buf *buf;
2366         int rc;
2367
2368 #ifdef CONFIG_LUSTRE_FS_POSIX_ACL
2369         /* ldiskfs OSD needs this information for credit allocation */
2370         if (def_acl_buf)
2371                 hint->dah_acl_len = def_acl_buf->lb_len;
2372 #endif
2373         rc = mdd_declare_create_object_internal(env, p, c, attr, handle, spec,
2374                                                 hint);
2375         if (rc)
2376                 GOTO(out, rc);
2377
2378 #ifdef CONFIG_LUSTRE_FS_POSIX_ACL
2379         if (def_acl_buf && def_acl_buf->lb_len > 0 && S_ISDIR(attr->la_mode)) {
2380                 /* if dir, then can inherit default ACl */
2381                 rc = mdo_declare_xattr_set(env, c, def_acl_buf,
2382                                            XATTR_NAME_ACL_DEFAULT,
2383                                            0, handle);
2384                 if (rc)
2385                         GOTO(out, rc);
2386         }
2387
2388         if (acl_buf && acl_buf->lb_len > 0) {
2389                 rc = mdo_declare_attr_set(env, c, attr, handle);
2390                 if (rc)
2391                         GOTO(out, rc);
2392
2393                 rc = mdo_declare_xattr_set(env, c, acl_buf,
2394                                            XATTR_NAME_ACL_ACCESS, 0, handle);
2395                 if (rc)
2396                         GOTO(out, rc);
2397         }
2398 #endif
2399         rc = mdd_declare_object_initialize(env, p, c, attr, handle);
2400         if (rc)
2401                 GOTO(out, rc);
2402
2403         /* replay case, create LOV EA from client data */
2404         if ((!(spec->sp_cr_flags & MDS_OPEN_DELAY_CREATE) && spec->no_create) ||
2405             (spec->sp_cr_flags & MDS_OPEN_HAS_EA && S_ISREG(attr->la_mode))) {
2406                 buf = mdd_buf_get_const(env, spec->u.sp_ea.eadata,
2407                                         spec->u.sp_ea.eadatalen);
2408                 rc = mdo_declare_xattr_set(env, c, buf,
2409                                            S_ISDIR(attr->la_mode) ?
2410                                                 XATTR_NAME_LMV : XATTR_NAME_LOV,
2411                                            LU_XATTR_CREATE, handle);
2412                 if (rc)
2413                         GOTO(out, rc);
2414
2415                 if (spec->sp_cr_flags & MDS_OPEN_PCC) {
2416                         rc = mdo_declare_xattr_set(env, c, hsm_buf,
2417                                                    XATTR_NAME_HSM,
2418                                                    0, handle);
2419                         if (rc)
2420                                 GOTO(out, rc);
2421                 }
2422         }
2423
2424         if (S_ISLNK(attr->la_mode)) {
2425                 const char *target_name = spec->u.sp_symname.ln_name;
2426                 int sym_len = spec->u.sp_symname.ln_namelen;
2427                 const struct lu_buf *buf;
2428
2429                 buf = mdd_buf_get_const(env, target_name, sym_len);
2430                 rc = dt_declare_record_write(env, mdd_object_child(c),
2431                                              buf, 0, handle);
2432                 if (rc)
2433                         GOTO(out, rc);
2434         }
2435
2436         if (spec->sp_cr_file_secctx_name != NULL) {
2437                 buf = mdd_buf_get_const(env, spec->sp_cr_file_secctx,
2438                                         spec->sp_cr_file_secctx_size);
2439                 rc = mdo_declare_xattr_set(env, c, buf,
2440                                            spec->sp_cr_file_secctx_name, 0,
2441                                            handle);
2442                 if (rc < 0)
2443                         GOTO(out, rc);
2444         }
2445
2446         if (spec->sp_cr_file_encctx != NULL) {
2447                 buf = mdd_buf_get_const(env, spec->sp_cr_file_encctx,
2448                                         spec->sp_cr_file_encctx_size);
2449                 rc = mdo_declare_xattr_set(env, c, buf,
2450                                            LL_XATTR_NAME_ENCRYPTION_CONTEXT, 0,
2451                                            handle);
2452                 if (rc < 0)
2453                         GOTO(out, rc);
2454         }
2455 out:
2456         return rc;
2457 }
2458
2459 static int mdd_declare_create(const struct lu_env *env, struct mdd_device *mdd,
2460                               struct mdd_object *p, struct mdd_object *c,
2461                               const struct lu_name *name,
2462                               struct lu_attr *attr,
2463                               struct thandle *handle,
2464                               const struct md_op_spec *spec,
2465                               struct linkea_data *ldata,
2466                               struct lu_buf *def_acl_buf,
2467                               struct lu_buf *acl_buf,
2468                               struct lu_buf *hsm_buf,
2469                               struct dt_allocation_hint *hint)
2470 {
2471         int rc;
2472
2473         rc = mdd_declare_create_object(env, mdd, p, c, attr, handle, spec,
2474                                        def_acl_buf, acl_buf, hsm_buf, hint);
2475         if (rc)
2476                 GOTO(out, rc);
2477
2478         if (S_ISDIR(attr->la_mode)) {
2479                 rc = mdo_declare_ref_add(env, p, handle);
2480                 if (rc)
2481                         GOTO(out, rc);
2482         }
2483
2484         if (unlikely(spec->sp_cr_flags & MDS_OPEN_VOLATILE)) {
2485                 rc = mdd_orphan_declare_insert(env, c, attr->la_mode, handle);
2486                 if (rc)
2487                         GOTO(out, rc);
2488         } else {
2489                 struct lu_attr *la = &mdd_env_info(env)->mdi_la_for_fix;
2490                 enum changelog_rec_type type;
2491
2492                 rc = mdo_declare_index_insert(env, p, mdd_object_fid(c),
2493                                               attr->la_mode, name->ln_name,
2494                                               handle);
2495                 if (rc != 0)
2496                         return rc;
2497
2498                 rc = mdd_declare_links_add(env, c, handle, ldata);
2499                 if (rc)
2500                         return rc;
2501
2502                 *la = *attr;
2503                 la->la_valid = LA_CTIME | LA_MTIME;
2504                 rc = mdo_declare_attr_set(env, p, la, handle);
2505                 if (rc)
2506                         return rc;
2507
2508                 type = S_ISDIR(attr->la_mode) ? CL_MKDIR :
2509                        S_ISREG(attr->la_mode) ? CL_CREATE :
2510                        S_ISLNK(attr->la_mode) ? CL_SOFTLINK : CL_MKNOD;
2511
2512                 rc = mdd_declare_changelog_store(env, mdd, type, name, NULL,
2513                                                  handle);
2514                 if (rc)
2515                         return rc;
2516         }
2517 out:
2518         return rc;
2519 }
2520
2521 static int mdd_acl_init(const struct lu_env *env, struct mdd_object *pobj,
2522                         struct lu_attr *la, struct lu_buf *def_acl_buf,
2523                         struct lu_buf *acl_buf)
2524 {
2525         int     rc;
2526
2527         ENTRY;
2528
2529         if (S_ISLNK(la->la_mode)) {
2530                 acl_buf->lb_len = 0;
2531                 def_acl_buf->lb_len = 0;
2532                 RETURN(0);
2533         }
2534
2535         mdd_read_lock(env, pobj, DT_TGT_PARENT);
2536         rc = mdo_xattr_get(env, pobj, def_acl_buf,
2537                            XATTR_NAME_ACL_DEFAULT);
2538         mdd_read_unlock(env, pobj);
2539         if (rc > 0) {
2540                 /* ACL buffer size is not enough, need realloc */
2541                 if (rc > acl_buf->lb_len)
2542                         RETURN(-ERANGE);
2543
2544                 /* If there are default ACL, fix mode/ACL by default ACL */
2545                 def_acl_buf->lb_len = rc;
2546                 memcpy(acl_buf->lb_buf, def_acl_buf->lb_buf, rc);
2547                 acl_buf->lb_len = rc;
2548                 rc = __mdd_fix_mode_acl(env, acl_buf, &la->la_mode);
2549                 if (rc < 0)
2550                         RETURN(rc);
2551         } else if (rc == -ENODATA || rc == -EOPNOTSUPP) {
2552                 /* If there are no default ACL, fix mode by mask */
2553                 struct lu_ucred *uc = lu_ucred(env);
2554
2555                 /* The create triggered by MDT internal events, such as
2556                  * LFSCK reset, will not contain valid "uc". */
2557                 if (unlikely(uc != NULL))
2558                         la->la_mode &= ~uc->uc_umask;
2559                 rc = 0;
2560                 acl_buf->lb_len = 0;
2561                 def_acl_buf->lb_len = 0;
2562         }
2563
2564         RETURN(rc);
2565 }
2566
2567 /**
2568  * Create a metadata object and initialize it, set acl, xattr.
2569  **/
2570 static int mdd_create_object(const struct lu_env *env, struct mdd_object *pobj,
2571                              struct mdd_object *son, struct lu_attr *attr,
2572                              struct md_op_spec *spec, struct lu_buf *acl_buf,
2573                              struct lu_buf *def_acl_buf,
2574                              struct lu_buf *hsm_buf,
2575                              struct dt_allocation_hint *hint,
2576                              struct thandle *handle, bool initial_create)
2577 {
2578         const struct lu_fid *son_fid = mdd_object_fid(son);
2579         const struct lu_ucred *uc = lu_ucred(env);
2580         const char *jobid = uc->uc_jobid;
2581         const struct lu_buf *buf;
2582         size_t jobid_len;
2583         int rc;
2584
2585         mdd_write_lock(env, son, DT_TGT_CHILD);
2586         rc = mdd_create_object_internal(env, NULL, son, attr, handle, spec,
2587                                         hint);
2588         if (rc)
2589                 GOTO(unlock, rc);
2590
2591         /* Note: In DNE phase I, for striped dir, though sub-stripes will be
2592          * created in declare phase, they also needs to be added to master
2593          * object as sub-directory entry. So it has to initialize the master
2594          * object, then set dir striped EA.(in mdo_xattr_set) */
2595         rc = mdd_object_initialize(env, mdd_object_fid(pobj), son, attr,
2596                                    handle);
2597         if (rc != 0)
2598                 GOTO(err_destroy, rc);
2599
2600         /*
2601          * in case of replay we just set LOVEA provided by the client
2602          * XXX: I think it would be interesting to try "old" way where
2603          *      MDT calls this xattr_set(LOV) in a different transaction.
2604          *      probably this way we code can be made better.
2605          */
2606
2607         /* During creation, there are only a few cases we need do xattr_set to
2608          * create stripes.
2609          * 1. regular file: see comments above.
2610          * 2. dir: inherit default striping or pool settings from parent.
2611          * 3. create striped directory with provided stripeEA.
2612          * 4. create striped directory because inherit default layout from the
2613          * parent.
2614          */
2615         if (spec->no_create ||
2616             (S_ISREG(attr->la_mode) && spec->sp_cr_flags & MDS_OPEN_HAS_EA) ||
2617             S_ISDIR(attr->la_mode)) {
2618                 buf = mdd_buf_get_const(env, spec->u.sp_ea.eadata,
2619                                         spec->u.sp_ea.eadatalen);
2620                 rc = mdo_xattr_set(env, son, buf,
2621                                    S_ISDIR(attr->la_mode) ? XATTR_NAME_LMV :
2622                                                             XATTR_NAME_LOV,
2623                                    LU_XATTR_CREATE, handle);
2624                 if (rc != 0)
2625                         GOTO(err_destroy, rc);
2626         }
2627
2628         if (S_ISREG(attr->la_mode) && spec->sp_cr_flags & MDS_OPEN_PCC) {
2629                 struct md_hsm mh;
2630
2631                 memset(&mh, 0, sizeof(mh));
2632                 mh.mh_flags = HS_EXISTS | HS_ARCHIVED | HS_RELEASED;
2633                 mh.mh_arch_id = spec->sp_archive_id;
2634                 lustre_hsm2buf(hsm_buf->lb_buf, &mh);
2635                 rc = mdo_xattr_set(env, son, hsm_buf, XATTR_NAME_HSM,
2636                                    0, handle);
2637                 if (rc != 0)
2638                         GOTO(err_destroy, rc);
2639         }
2640
2641 #ifdef CONFIG_LUSTRE_FS_POSIX_ACL
2642         if (def_acl_buf != NULL && def_acl_buf->lb_len > 0 &&
2643             S_ISDIR(attr->la_mode)) {
2644                 /* set default acl */
2645                 rc = mdo_xattr_set(env, son, def_acl_buf,
2646                                    XATTR_NAME_ACL_DEFAULT, 0,
2647                                    handle);
2648                 if (rc)
2649                         GOTO(err_destroy, rc);
2650         }
2651         /* set its own acl */
2652         if (acl_buf != NULL && acl_buf->lb_len > 0) {
2653                 rc = mdo_xattr_set(env, son, acl_buf,
2654                                    XATTR_NAME_ACL_ACCESS,
2655                                    0, handle);
2656                 if (rc)
2657                         GOTO(err_destroy, rc);
2658         }
2659 #endif
2660
2661         if (S_ISLNK(attr->la_mode)) {
2662                 struct dt_object *dt = mdd_object_child(son);
2663                 const char *target_name = spec->u.sp_symname.ln_name;
2664                 int sym_len = spec->u.sp_symname.ln_namelen;
2665                 loff_t pos = 0;
2666
2667                 buf = mdd_buf_get_const(env, target_name, sym_len);
2668                 rc = dt->do_body_ops->dbo_write(env, dt, buf, &pos, handle);
2669                 if (rc == sym_len)
2670                         rc = 0;
2671                 else
2672                         GOTO(err_initlized, rc = -EFAULT);
2673         }
2674
2675         if (initial_create && spec->sp_cr_file_secctx_name != NULL) {
2676                 buf = mdd_buf_get_const(env, spec->sp_cr_file_secctx,
2677                                         spec->sp_cr_file_secctx_size);
2678                 rc = mdo_xattr_set(env, son, buf, spec->sp_cr_file_secctx_name,
2679                                    0, handle);
2680                 if (rc < 0)
2681                         GOTO(err_initlized, rc);
2682         }
2683
2684         if (spec->sp_cr_file_encctx != NULL) {
2685                 buf = mdd_buf_get_const(env, spec->sp_cr_file_encctx,
2686                                         spec->sp_cr_file_encctx_size);
2687                 rc = mdo_xattr_set(env, son, buf,
2688                                    LL_XATTR_NAME_ENCRYPTION_CONTEXT, 0,
2689                                    handle);
2690                 if (rc < 0)
2691                         GOTO(err_initlized, rc);
2692         }
2693
2694         if (initial_create &&
2695             spec->sp_cr_job_xattr[0] != '\0' &&
2696             jobid[0] != '\0' &&
2697             (S_ISREG(attr->la_mode) || S_ISDIR(attr->la_mode))) {
2698                 jobid_len = strnlen(jobid, LUSTRE_JOBID_SIZE);
2699                 buf = mdd_buf_get_const(env, jobid, jobid_len);
2700
2701                 rc = mdo_xattr_set(env, son, buf, spec->sp_cr_job_xattr, 0,
2702                                    handle);
2703                 /* this xattr is nonessential, so ignore errors. */
2704                 if (rc != 0) {
2705                         CDEBUG(D_INODE,
2706                                DFID" failed to set xattr '%s': rc = %d\n",
2707                                PFID(son_fid), spec->sp_cr_job_xattr, rc);
2708                         rc = 0;
2709                 }
2710         }
2711
2712 err_initlized:
2713         if (unlikely(rc != 0)) {
2714                 int rc2;
2715                 if (S_ISDIR(attr->la_mode)) {
2716                         /* Drop the reference, no need to delete "."/"..",
2717                          * because the object to be destroyed directly. */
2718                         rc2 = mdo_ref_del(env, son, handle);
2719                         if (rc2 != 0)
2720                                 GOTO(unlock, rc);
2721                 }
2722                 rc2 = mdo_ref_del(env, son, handle);
2723                 if (rc2 != 0)
2724                         GOTO(unlock, rc);
2725 err_destroy:
2726                 mdo_destroy(env, son, handle);
2727         }
2728 unlock:
2729         mdd_write_unlock(env, son);
2730         RETURN(rc);
2731 }
2732
2733 static int mdd_index_delete(const struct lu_env *env,
2734                             struct mdd_object *mdd_pobj,
2735                             struct lu_attr *cattr,
2736                             const struct lu_name *lname)
2737 {
2738         struct mdd_device *mdd = mdo2mdd(&mdd_pobj->mod_obj);
2739         struct thandle *handle;
2740         int rc;
2741         ENTRY;
2742
2743         handle = mdd_trans_create(env, mdd);
2744         if (IS_ERR(handle))
2745                 RETURN(PTR_ERR(handle));
2746
2747         rc = mdo_declare_index_delete(env, mdd_pobj, lname->ln_name,
2748                                       handle);
2749         if (rc != 0)
2750                 GOTO(stop, rc);
2751
2752         if (S_ISDIR(cattr->la_mode)) {
2753                 rc = mdo_declare_ref_del(env, mdd_pobj, handle);
2754                 if (rc != 0)
2755                         GOTO(stop, rc);
2756         }
2757
2758         /* Since this will only be used in the error handler path,
2759          * Let's set the thandle to be local and not mess the transno */
2760         handle->th_local = 1;
2761         rc = mdd_trans_start(env, mdd, handle);
2762         if (rc)
2763                 GOTO(stop, rc);
2764
2765         rc = __mdd_index_delete(env, mdd_pobj, lname->ln_name,
2766                                 S_ISDIR(cattr->la_mode), handle);
2767         if (rc)
2768                 GOTO(stop, rc);
2769 stop:
2770         rc = mdd_trans_stop(env, mdd, rc, handle);
2771
2772         RETURN(rc);
2773 }
2774
2775 /**
2776  * Create object and insert it into namespace.
2777  *
2778  * Two operations have to be performed:
2779  *
2780  *  - an allocation of a new object (->do_create()), and
2781  *  - an insertion into a parent index (->dio_insert()).
2782  *
2783  * Due to locking, operation order is not important, when both are
2784  * successful, *but* error handling cases are quite different:
2785  *
2786  *  - if insertion is done first, and following object creation fails,
2787  *  insertion has to be rolled back, but this operation might fail
2788  *  also leaving us with dangling index entry.
2789  *
2790  *  - if creation is done first, is has to be undone if insertion fails,
2791  *  leaving us with leaked space, which is not good but not fatal.
2792  *
2793  * It seems that creation-first is simplest solution, but it is sub-optimal
2794  * in the frequent
2795  *
2796  * $ mkdir foo
2797  * $ mkdir foo
2798  *
2799  * case, because second mkdir is bound to create object, only to
2800  * destroy it immediately.
2801  *
2802  * To avoid this follow local file systems that do double lookup:
2803  *
2804  * 0. lookup -> -EEXIST (mdd_create_sanity_check())
2805  * 1. create            (mdd_create_object_internal())
2806  * 2. insert            (__mdd_index_insert(), lookup again)
2807  *
2808  * \param[in] pobj      parent object
2809  * \param[in] lname     name of child being created
2810  * \param[in,out] child child object being created
2811  * \param[in] spec      additional create parameters
2812  * \param[in] ma        attributes for new child object
2813  *
2814  * \retval              0 on success
2815  * \retval              negative errno on failure
2816  */
2817 int mdd_create(const struct lu_env *env, struct md_object *pobj,
2818                       const struct lu_name *lname, struct md_object *child,
2819                       struct md_op_spec *spec, struct md_attr *ma)
2820 {
2821         struct mdd_thread_info *info = mdd_env_info(env);
2822         struct lu_attr *la = &info->mdi_la_for_fix;
2823         struct mdd_object *mdd_pobj = md2mdd_obj(pobj);
2824         struct mdd_object *son = md2mdd_obj(child);
2825         struct mdd_device *mdd = mdo2mdd(pobj);
2826         struct lu_attr *attr = &ma->ma_attr;
2827         struct thandle *handle;
2828         struct lu_attr *pattr = &info->mdi_pattr;
2829         struct lu_buf acl_buf;
2830         struct lu_buf def_acl_buf;
2831         struct lu_buf hsm_buf;
2832         struct linkea_data *ldata = &info->mdi_link_data;
2833         const char *name = lname->ln_name;
2834         struct dt_allocation_hint *hint = &mdd_env_info(env)->mdi_hint;
2835         int acl_size = LUSTRE_POSIX_ACL_MAX_SIZE_OLD;
2836         bool name_inserted = false;
2837         int rc, rc2;
2838
2839         ENTRY;
2840
2841         rc = mdd_la_get(env, mdd_pobj, pattr);
2842         if (rc != 0)
2843                 RETURN(rc);
2844
2845         /* Sanity checks before big job. */
2846         rc = mdd_create_sanity_check(env, pobj, pattr, lname, attr, spec);
2847         if (unlikely(rc == -EEXIST && S_ISDIR(attr->la_mode) &&
2848                      spec->sp_replay && mdd_object_remote(mdd_pobj)))
2849                 /* if it's replay by client request, and name is found in
2850                  * parent directory on remote MDT, it means mkdir was partially
2851                  * executed: name was successfully added, but target not.
2852                  */
2853                 name_inserted = true;
2854         else if (rc)
2855                 RETURN(rc);
2856
2857         if (CFS_FAIL_CHECK(OBD_FAIL_MDS_DQACQ_NET))
2858                 GOTO(out_free, rc = -EINPROGRESS);
2859
2860         handle = mdd_trans_create(env, mdd);
2861         if (IS_ERR(handle))
2862                 GOTO(out_free, rc = PTR_ERR(handle));
2863
2864 use_bigger_buffer:
2865         acl_buf = *lu_buf_check_and_alloc(&info->mdi_xattr_buf, acl_size);
2866         if (!acl_buf.lb_buf)
2867                 GOTO(out_stop, rc = -ENOMEM);
2868
2869         def_acl_buf = *lu_buf_check_and_alloc(&info->mdi_big_buf, acl_size);
2870         if (!def_acl_buf.lb_buf)
2871                 GOTO(out_stop, rc = -ENOMEM);
2872
2873         rc = mdd_acl_init(env, mdd_pobj, attr, &def_acl_buf, &acl_buf);
2874         if (unlikely(rc == -ERANGE &&
2875                      acl_size == LUSTRE_POSIX_ACL_MAX_SIZE_OLD)) {
2876                 /* use maximum-sized xattr buffer for too-big default ACL */
2877                 acl_size = min_t(unsigned int, mdd->mdd_dt_conf.ddp_max_ea_size,
2878                                  XATTR_SIZE_MAX);
2879                 goto use_bigger_buffer;
2880         }
2881         if (rc < 0)
2882                 GOTO(out_stop, rc);
2883
2884         /* adjust stripe count to 0 for 'lfs mkdir -c 1 ...' to avoid creating
2885          * 1-stripe directory, MDS_OPEN_DEFAULT_LMV means ea is default LMV.
2886          */
2887         if (unlikely(S_ISDIR(attr->la_mode) && spec->u.sp_ea.eadata &&
2888                      !(spec->sp_cr_flags & MDS_OPEN_DEFAULT_LMV))) {
2889                 struct lmv_user_md *lmu = spec->u.sp_ea.eadata;
2890
2891                 /* migrate may create 1-stripe directory, adjust stripe count
2892                  * before lod_ah_init().
2893                  */
2894                 if (lmu && lmu->lum_magic == cpu_to_le32(LMV_USER_MAGIC) &&
2895                     lmu->lum_stripe_count == cpu_to_le32(1))
2896                         lmu->lum_stripe_count = 0;
2897         }
2898
2899         mdd_object_make_hint(env, mdd_pobj, son, attr, spec, hint);
2900
2901         memset(ldata, 0, sizeof(*ldata));
2902         if (CFS_FAIL_CHECK(OBD_FAIL_LFSCK_BAD_PARENT)) {
2903                 struct lu_fid tfid = *mdd_object_fid(mdd_pobj);
2904
2905                 tfid.f_oid--;
2906                 rc = mdd_linkea_prepare(env, son, NULL, NULL,
2907                                         &tfid, lname, 1, 0, ldata);
2908         } else {
2909                 rc = mdd_linkea_prepare(env, son, NULL, NULL,
2910                                         mdd_object_fid(mdd_pobj),
2911                                         lname, 1, 0, ldata);
2912         }
2913
2914         if (spec->sp_cr_flags & MDS_OPEN_PCC) {
2915                 LASSERT(spec->sp_cr_flags & MDS_OPEN_HAS_EA);
2916
2917                 memset(&hsm_buf, 0, sizeof(hsm_buf));
2918                 lu_buf_alloc(&hsm_buf, sizeof(struct hsm_attrs));
2919                 if (hsm_buf.lb_buf == NULL)
2920                         GOTO(out_stop, rc = -ENOMEM);
2921         }
2922
2923         rc = mdd_declare_create(env, mdd, mdd_pobj, son, lname, attr,
2924                                 handle, spec, ldata, &def_acl_buf, &acl_buf,
2925                                 &hsm_buf, hint);
2926         if (rc)
2927                 GOTO(out_stop, rc);
2928
2929         rc = mdd_trans_start(env, mdd, handle);
2930         if (rc)
2931                 GOTO(out_stop, rc);
2932
2933         rc = mdd_create_object(env, mdd_pobj, son, attr, spec, &acl_buf,
2934                                &def_acl_buf, &hsm_buf, hint, handle, true);
2935         if (rc != 0)
2936                 GOTO(out_stop, rc);
2937
2938         if (unlikely(spec->sp_cr_flags & MDS_OPEN_VOLATILE)) {
2939                 mdd_write_lock(env, son, DT_TGT_CHILD);
2940                 son->mod_flags |= VOLATILE_OBJ;
2941                 rc = mdd_orphan_insert(env, son, handle);
2942                 GOTO(out_volatile, rc);
2943         } else {
2944                 if (likely(!name_inserted)) {
2945                         rc = __mdd_index_insert(env, mdd_pobj,
2946                                                 mdd_object_fid(son),
2947                                                 attr->la_mode, name, handle);
2948                         if (rc != 0)
2949                                 GOTO(err_created, rc);
2950                 }
2951
2952                 mdd_links_add(env, son, mdd_object_fid(mdd_pobj), lname,
2953                               handle, ldata, 1);
2954
2955                 /* update parent directory mtime/ctime */
2956                 *la = *attr;
2957                 la->la_valid = LA_CTIME | LA_MTIME;
2958                 rc = mdd_update_time(env, mdd_pobj, pattr, la, handle);
2959                 if (rc)
2960                         GOTO(err_insert, rc);
2961         }
2962
2963         EXIT;
2964 err_insert:
2965         if (rc != 0) {
2966                 if (spec->sp_cr_flags & MDS_OPEN_VOLATILE)
2967                         rc2 = mdd_orphan_delete(env, son, handle);
2968                 else
2969                         rc2 = __mdd_index_delete(env, mdd_pobj, name,
2970                                                  S_ISDIR(attr->la_mode),
2971                                                  handle);
2972                 if (rc2 != 0)
2973                         goto out_stop;
2974
2975 err_created:
2976                 mdd_write_lock(env, son, DT_TGT_CHILD);
2977                 if (S_ISDIR(attr->la_mode)) {
2978                         /* Drop the reference, no need to delete "."/"..",
2979                          * because the object is to be destroyed directly. */
2980                         rc2 = mdo_ref_del(env, son, handle);
2981                         if (rc2 != 0) {
2982                                 mdd_write_unlock(env, son);
2983                                 goto out_stop;
2984                         }
2985                 }
2986 out_volatile:
2987                 /* For volatile files drop one link immediately, since there is
2988                  * no filename in the namespace, and save any error returned. */
2989                 rc2 = mdo_ref_del(env, son, handle);
2990                 if (rc2 != 0) {
2991                         mdd_write_unlock(env, son);
2992                         if (unlikely(rc == 0))
2993                                 rc = rc2;
2994                         goto out_stop;
2995                 }
2996
2997                 /* Don't destroy the volatile object on success */
2998                 if (likely(rc != 0))
2999                         mdo_destroy(env, son, handle);
3000                 mdd_write_unlock(env, son);
3001         }
3002
3003         if (rc == 0 && fid_is_namespace_visible(mdd_object_fid(son)) &&
3004             likely((spec->sp_cr_flags & MDS_OPEN_VOLATILE) == 0))
3005                 rc = mdd_changelog_ns_store(env, mdd,
3006                                 S_ISDIR(attr->la_mode) ? CL_MKDIR :
3007                                 S_ISREG(attr->la_mode) ? CL_CREATE :
3008                                 S_ISLNK(attr->la_mode) ? CL_SOFTLINK : CL_MKNOD,
3009                                 0, son, mdd_pobj, pattr, NULL, NULL, NULL,
3010                                 lname, NULL, handle);
3011 out_stop:
3012         rc2 = mdd_trans_stop(env, mdd, rc, handle);
3013         if (rc == 0) {
3014                 /* If creation fails, it is most likely due to the remote update
3015                  * failure, because local transaction will mostly succeed at
3016                  * this stage. There is no easy way to rollback all of previous
3017                  * updates, so let's remove the object from namespace, and
3018                  * LFSCK should handle the orphan object. */
3019                 if (rc2 < 0 && !mdd_object_remote(mdd_pobj))
3020                         mdd_index_delete(env, mdd_pobj, attr, lname);
3021                 rc = rc2;
3022         }
3023 out_free:
3024         if (is_vmalloc_addr(ldata->ld_buf))
3025                 /* if we vmalloced a large buffer drop it */
3026                 lu_buf_free(ldata->ld_buf);
3027
3028         if (spec->sp_cr_flags & MDS_OPEN_PCC)
3029                 lu_buf_free(&hsm_buf);
3030
3031         /* The child object shouldn't be cached anymore */
3032         if (rc)
3033                 set_bit(LU_OBJECT_HEARD_BANSHEE,
3034                         &child->mo_lu.lo_header->loh_flags);
3035         return rc;
3036 }
3037
3038 /* has not mdd_write{read}_lock on any obj yet. */
3039 static int mdd_rename_sanity_check(const struct lu_env *env,
3040                                    struct mdd_object *src_pobj,
3041                                    const struct lu_attr *pattr,
3042                                    struct mdd_object *tgt_pobj,
3043                                    const struct lu_attr *tpattr,
3044                                    struct mdd_object *sobj,
3045                                    const struct lu_attr *cattr,
3046                                    struct mdd_object *tobj,
3047                                    const struct lu_attr *tattr)
3048 {
3049         int rc = 0;
3050         ENTRY;
3051
3052         /* XXX: when get here, sobj must NOT be NULL,
3053          * the other case has been processed in cld_rename
3054          * before mdd_rename and enable MDS_PERM_BYPASS. */
3055         LASSERT(sobj);
3056
3057         /*
3058          * If we are using project inheritance, we only allow renames
3059          * into our tree when the project IDs are the same; otherwise
3060          * tree quota mechanism would be circumvented.
3061          */
3062         if ((((tpattr->la_flags & LUSTRE_PROJINHERIT_FL) &&
3063             tpattr->la_projid != cattr->la_projid) ||
3064             ((pattr->la_flags & LUSTRE_PROJINHERIT_FL) &&
3065             (pattr->la_projid != tpattr->la_projid))) &&
3066             S_ISDIR(cattr->la_mode))
3067                 RETURN(-EXDEV);
3068
3069         /* we prevent an encrypted file from being renamed
3070          * into an unencrypted dir
3071          */
3072         if ((pattr->la_valid & LA_FLAGS &&
3073              pattr->la_flags & LUSTRE_ENCRYPT_FL) &&
3074             !(tpattr->la_valid & LA_FLAGS &&
3075               tpattr->la_flags & LUSTRE_ENCRYPT_FL))
3076                 RETURN(-EXDEV);
3077
3078         rc = mdd_may_delete(env, src_pobj, pattr, sobj, cattr, NULL, 1, 0);
3079         if (rc)
3080                 RETURN(rc);
3081
3082         /* XXX: when get here, "tobj == NULL" means tobj must
3083          * NOT exist (neither on remote MDS, such case has been
3084          * processed in cld_rename before mdd_rename and enable
3085          * MDS_PERM_BYPASS).
3086          * So check may_create, but not check may_unlink. */
3087         if (tobj == NULL)
3088                 rc = mdd_may_create(env, tgt_pobj, tpattr, NULL,
3089                                     (src_pobj != tgt_pobj));
3090         else
3091                 rc = mdd_may_delete(env, tgt_pobj, tpattr, tobj, tattr, cattr,
3092                                     (src_pobj != tgt_pobj), 1);
3093
3094         if (!rc && !tobj && (src_pobj != tgt_pobj) && S_ISDIR(cattr->la_mode))
3095                 rc = __mdd_may_link(env, tgt_pobj, tpattr);
3096
3097         RETURN(rc);
3098 }
3099
3100 static int mdd_declare_rename(const struct lu_env *env,
3101                               struct mdd_device *mdd,
3102                               struct mdd_object *mdd_spobj,
3103                               struct mdd_object *mdd_tpobj,
3104                               struct mdd_object *mdd_sobj,
3105                               struct mdd_object *mdd_tobj,
3106                               const struct lu_name *sname,
3107                               const struct lu_name *tname,
3108                               struct md_attr *ma,
3109                               struct linkea_data *ldata, bool change_projid,
3110                               struct thandle *handle)
3111 {
3112         struct lu_attr *la = &mdd_env_info(env)->mdi_la_for_fix;
3113         int rc;
3114
3115         LASSERT(ma->ma_attr.la_valid & LA_CTIME);
3116         la->la_ctime = la->la_mtime = ma->ma_attr.la_ctime;
3117
3118         LASSERT(mdd_spobj);
3119         LASSERT(mdd_tpobj);
3120         LASSERT(mdd_sobj);
3121
3122         /* name from source dir */
3123         rc = mdo_declare_index_delete(env, mdd_spobj, sname->ln_name, handle);
3124         if (rc)
3125                 return rc;
3126
3127         /* .. from source child */
3128         if (S_ISDIR(mdd_object_type(mdd_sobj))) {
3129                 /* source child can be directory, count by source dir's nlink */
3130                 rc = mdo_declare_ref_del(env, mdd_spobj, handle);
3131                 if (rc)
3132                         return rc;
3133                 if (mdd_spobj != mdd_tpobj) {
3134                         rc = mdo_declare_index_delete(env, mdd_sobj, dotdot,
3135                                                       handle);
3136                         if (rc != 0)
3137                                 return rc;
3138
3139                         rc = mdo_declare_index_insert(env, mdd_sobj,
3140                                                       mdd_object_fid(mdd_tpobj),
3141                                                       S_IFDIR, dotdot, handle);
3142                         if (rc != 0)
3143                                 return rc;
3144                 }
3145
3146                 /* new target child can be directory,
3147                  * counted by target dir's nlink */
3148                 rc = mdo_declare_ref_add(env, mdd_tpobj, handle);
3149                 if (rc != 0)
3150                         return rc;
3151         }
3152
3153         la->la_valid = LA_CTIME | LA_MTIME;
3154         rc = mdo_declare_attr_set(env, mdd_spobj, la, handle);
3155         if (rc != 0)
3156                 return rc;
3157
3158         rc = mdo_declare_attr_set(env, mdd_tpobj, la, handle);
3159         if (rc != 0)
3160                 return rc;
3161
3162         la->la_valid = LA_CTIME;
3163         if (change_projid)
3164                 la->la_valid |= LA_PROJID;
3165         rc = mdo_declare_attr_set(env, mdd_sobj, la, handle);
3166         if (rc)
3167                 return rc;
3168
3169         rc = mdd_declare_links_add(env, mdd_sobj, handle, ldata);
3170         if (rc)
3171                 return rc;
3172
3173         /* new name */
3174         rc = mdo_declare_index_insert(env, mdd_tpobj, mdd_object_fid(mdd_sobj),
3175                                       mdd_object_type(mdd_sobj),
3176                                       tname->ln_name, handle);
3177         if (rc != 0)
3178                 return rc;
3179
3180         if (mdd_tobj && mdd_object_exists(mdd_tobj)) {
3181                 /* delete target child in target parent directory */
3182                 rc = mdo_declare_index_delete(env, mdd_tpobj, tname->ln_name,
3183                                               handle);
3184                 if (rc)
3185                         return rc;
3186
3187                 rc = mdo_declare_ref_del(env, mdd_tobj, handle);
3188                 if (rc)
3189                         return rc;
3190
3191                 if (S_ISDIR(mdd_object_type(mdd_tobj))) {
3192                         /* target child can be directory,
3193                          * delete "." reference in target child directory */
3194                         rc = mdo_declare_ref_del(env, mdd_tobj, handle);
3195                         if (rc)
3196                                 return rc;
3197
3198                         /* delete ".." reference in target parent directory */
3199                         rc = mdo_declare_ref_del(env, mdd_tpobj, handle);
3200                         if (rc)
3201                                 return rc;
3202                 }
3203
3204                 la->la_valid = LA_CTIME;
3205                 rc = mdo_declare_attr_set(env, mdd_tobj, la, handle);
3206                 if (rc)
3207                         return rc;
3208
3209                 rc = mdd_declare_finish_unlink(env, mdd_tobj, handle);
3210                 if (rc)
3211                         return rc;
3212         }
3213
3214         rc = mdd_declare_changelog_store(env, mdd, CL_RENAME, tname, sname,
3215                                          handle);
3216         if (rc)
3217                 return rc;
3218
3219         return rc;
3220 }
3221
3222 static int mdd_migrate_object(const struct lu_env *env,
3223                               struct mdd_object *spobj,
3224                               struct mdd_object *tpobj,
3225                               struct mdd_object *sobj,
3226                               struct mdd_object *tobj,
3227                               const struct lu_name *sname,
3228                               const struct lu_name *tname,
3229                               struct md_op_spec *spec,
3230                               struct md_attr *ma);
3231
3232 /* src object can be remote that is why we use only fid and type of object */
3233 static int mdd_rename(const struct lu_env *env,
3234                       struct md_object *src_pobj, struct md_object *tgt_pobj,
3235                       const struct lu_fid *lf, const struct lu_name *lsname,
3236                       struct md_object *tobj, const struct lu_name *ltname,
3237                       struct md_attr *ma)
3238 {
3239         const char *sname = lsname->ln_name;
3240         const char *tname = ltname->ln_name;
3241         struct lu_attr    *la = &mdd_env_info(env)->mdi_la_for_fix;
3242         struct mdd_object *mdd_spobj = md2mdd_obj(src_pobj); /* source parent */
3243         struct mdd_object *mdd_tpobj = md2mdd_obj(tgt_pobj);
3244         struct mdd_device *mdd = mdo2mdd(src_pobj);
3245         struct mdd_object *mdd_sobj = NULL;                  /* source object */
3246         struct mdd_object *mdd_tobj = NULL;
3247         struct lu_attr *cattr = MDD_ENV_VAR(env, cattr);
3248         struct lu_attr *pattr = MDD_ENV_VAR(env, pattr);
3249         struct lu_attr *tattr = MDD_ENV_VAR(env, tattr);
3250         struct lu_attr *tpattr = MDD_ENV_VAR(env, tpattr);
3251         struct thandle *handle;
3252         struct linkea_data  *ldata = &mdd_env_info(env)->mdi_link_data;
3253         const struct lu_fid *tpobj_fid = mdd_object_fid(mdd_tpobj);
3254         const struct lu_fid *spobj_fid = mdd_object_fid(mdd_spobj);
3255         bool is_dir;
3256         bool tobj_ref = 0;
3257         bool tobj_locked = 0;
3258         bool change_projid = false;
3259         unsigned cl_flags = 0;
3260         int rc, rc2;
3261         ENTRY;
3262
3263         /* let unlink to complete and commit */
3264         CFS_FAIL_TIMEOUT(OBD_FAIL_TGT_REPLY_DATA_RACE, 2 + cfs_fail_val);
3265
3266         if (tobj)
3267                 mdd_tobj = md2mdd_obj(tobj);
3268
3269         mdd_sobj = mdd_object_find(env, mdd, lf);
3270         if (IS_ERR(mdd_sobj))
3271                 RETURN(PTR_ERR(mdd_sobj));
3272
3273         rc = mdd_la_get(env, mdd_sobj, cattr);
3274         if (rc)
3275                 GOTO(out_pending, rc);
3276
3277         /* if rename is cross MDTs, migrate symlink if it doesn't have other
3278          * hard links, and target doesn't exist.
3279          */
3280         if (mdd_object_remote(mdd_sobj) && S_ISLNK(cattr->la_mode) &&
3281             cattr->la_nlink == 1 && !tobj) {
3282                 struct md_op_spec *spec = &mdd_env_info(env)->mdi_spec;
3283                 struct lu_device *ld = &mdd->mdd_md_dev.md_lu_dev;
3284                 struct lu_fid tfid;
3285
3286                 rc = ld->ld_ops->ldo_fid_alloc(env, ld, &tfid, &tgt_pobj->mo_lu,
3287                                                NULL);
3288                 if (rc < 0)
3289                         GOTO(out_pending, rc);
3290
3291                 mdd_tobj = mdd_object_find(env, mdd, &tfid);
3292                 if (IS_ERR(mdd_tobj))
3293                         GOTO(out_pending, rc = PTR_ERR(mdd_tobj));
3294
3295                 memset(spec, 0, sizeof(*spec));
3296                 rc = mdd_migrate_object(env, mdd_spobj, mdd_tpobj, mdd_sobj,
3297                                         mdd_tobj, lsname, ltname, spec, ma);
3298                 mdd_object_put(env, mdd_tobj);
3299                 GOTO(out_pending, rc);
3300         }
3301
3302         rc = mdd_la_get(env, mdd_spobj, pattr);
3303         if (rc)
3304                 GOTO(out_pending, rc);
3305
3306         if (mdd_tobj) {
3307                 rc = mdd_la_get(env, mdd_tobj, tattr);
3308                 if (rc)
3309                         GOTO(out_pending, rc);
3310                 /* search for an existing archive.
3311                  * we should check ahead as the object
3312                  * can be destroyed in this transaction */
3313                 if (mdd_hsm_archive_exists(env, mdd_tobj, ma))
3314                         cl_flags |= CLF_RENAME_LAST_EXISTS;
3315         }
3316
3317         rc = mdd_la_get(env, mdd_tpobj, tpattr);
3318         if (rc)
3319                 GOTO(out_pending, rc);
3320
3321         rc = mdd_rename_sanity_check(env, mdd_spobj, pattr, mdd_tpobj, tpattr,
3322                                      mdd_sobj, cattr, mdd_tobj, tattr);
3323         if (rc)
3324                 GOTO(out_pending, rc);
3325
3326         rc = mdd_name_check(env, mdd, ltname);
3327         if (rc < 0)
3328                 GOTO(out_pending, rc);
3329
3330         handle = mdd_trans_create(env, mdd);
3331         if (IS_ERR(handle))
3332                 GOTO(out_pending, rc = PTR_ERR(handle));
3333
3334         memset(ldata, 0, sizeof(*ldata));
3335         rc = mdd_linkea_prepare(env, mdd_sobj, mdd_object_fid(mdd_spobj),
3336                                 lsname, mdd_object_fid(mdd_tpobj), ltname,
3337                                 1, 0, ldata);
3338         if (rc)
3339                 GOTO(stop, rc);
3340
3341         if (tpattr->la_projid != cattr->la_projid &&
3342             tpattr->la_flags & LUSTRE_PROJINHERIT_FL)
3343                 change_projid = true;
3344
3345         rc = mdd_declare_rename(env, mdd, mdd_spobj, mdd_tpobj, mdd_sobj,
3346                                 mdd_tobj, lsname, ltname, ma, ldata,
3347                                 change_projid, handle);
3348         if (rc)
3349                 GOTO(stop, rc);
3350
3351         rc = mdd_trans_start(env, mdd, handle);
3352         if (rc)
3353                 GOTO(stop, rc);
3354
3355         is_dir = S_ISDIR(cattr->la_mode);
3356
3357         /* Remove source name from source directory */
3358         rc = __mdd_index_delete(env, mdd_spobj, sname, is_dir, handle);
3359         if (rc != 0)
3360                 GOTO(stop, rc);
3361
3362         /* "mv dir1 dir2" needs "dir1/.." link update */
3363         if (is_dir && !lu_fid_eq(spobj_fid, tpobj_fid)) {
3364                 rc = __mdd_index_delete_only(env, mdd_sobj, dotdot, handle);
3365                 if (rc != 0)
3366                         GOTO(fixup_spobj2, rc);
3367
3368                 rc = __mdd_index_insert_only(env, mdd_sobj, tpobj_fid, S_IFDIR,
3369                                              dotdot, handle);
3370                 if (rc != 0)
3371                         GOTO(fixup_spobj, rc);
3372         }
3373
3374         if (mdd_tobj != NULL && mdd_object_exists(mdd_tobj)) {
3375                 rc = __mdd_index_delete(env, mdd_tpobj, tname, is_dir, handle);
3376                 if (rc != 0)
3377                         /* tname might been renamed to something else */
3378                         GOTO(fixup_spobj, rc);
3379         }
3380
3381         /* Insert new fid with target name into target dir */
3382         rc = __mdd_index_insert(env, mdd_tpobj, lf, cattr->la_mode,
3383                                 tname, handle);
3384         if (rc != 0)
3385                 GOTO(fixup_tpobj, rc);
3386
3387         LASSERT(ma->ma_attr.la_valid & LA_CTIME);
3388         la->la_ctime = la->la_mtime = ma->ma_attr.la_ctime;
3389
3390         /* XXX: mdd_sobj must be local one if it is NOT NULL. */
3391         la->la_valid = LA_CTIME;
3392         if (change_projid) {
3393                 /* mdd_update_time honors other valid flags except TIME ones */
3394                 la->la_valid |= LA_PROJID;
3395                 la->la_projid = tpattr->la_projid;
3396         }
3397         rc = mdd_update_time(env, mdd_sobj, cattr, la, handle);
3398         if (rc)
3399                 GOTO(fixup_tpobj, rc);
3400
3401         /* Update the linkEA for the source object */
3402         mdd_write_lock(env, mdd_sobj, DT_SRC_CHILD);
3403         rc = mdd_links_rename(env, mdd_sobj, mdd_object_fid(mdd_spobj),
3404                               lsname, mdd_object_fid(mdd_tpobj), ltname,
3405                               handle, ldata, 0, 0);
3406         if (rc == -ENOENT)
3407                 /* Old files might not have EA entry */
3408                 mdd_links_add(env, mdd_sobj, mdd_object_fid(mdd_spobj),
3409                               lsname, handle, NULL, 0);
3410         mdd_write_unlock(env, mdd_sobj);
3411         /* We don't fail the transaction if the link ea can't be
3412            updated -- fid2path will use alternate lookup method. */
3413         rc = 0;
3414
3415         /* Remove old target object
3416          * For tobj is remote case cmm layer has processed
3417          * and set tobj to NULL then. So when tobj is NOT NULL,
3418          * it must be local one.
3419          */
3420         if (tobj && mdd_object_exists(mdd_tobj)) {
3421                 mdd_write_lock(env, mdd_tobj, DT_TGT_CHILD);
3422                 tobj_locked = 1;
3423                 if (mdd_is_dead_obj(mdd_tobj)) {
3424                         /* shld not be dead, something is wrong */
3425                         CERROR("tobj is dead, something is wrong\n");
3426                         rc = -EINVAL;
3427                         goto cleanup;
3428                 }
3429                 mdo_ref_del(env, mdd_tobj, handle);
3430
3431                 /* Remove dot reference. */
3432                 if (S_ISDIR(tattr->la_mode))
3433                         mdo_ref_del(env, mdd_tobj, handle);
3434                 tobj_ref = 1;
3435
3436                 /* fetch updated nlink */
3437                 rc = mdd_la_get(env, mdd_tobj, tattr);
3438                 if (rc != 0) {
3439                         CERROR("%s: Failed to get nlink for tobj "
3440                                 DFID": rc = %d\n",
3441                                 mdd2obd_dev(mdd)->obd_name,
3442                                 PFID(tpobj_fid), rc);
3443                         GOTO(fixup_tpobj, rc);
3444                 }
3445
3446                 la->la_valid = LA_CTIME;
3447                 rc = mdd_update_time(env, mdd_tobj, tattr, la, handle);
3448                 if (rc != 0) {
3449                         CERROR("%s: Failed to set ctime for tobj "
3450                                 DFID": rc = %d\n",
3451                                 mdd2obd_dev(mdd)->obd_name,
3452                                 PFID(tpobj_fid), rc);
3453                         GOTO(fixup_tpobj, rc);
3454                 }
3455
3456                 /* XXX: this transfer to ma will be removed with LOD/OSP */
3457                 ma->ma_attr = *tattr;
3458                 ma->ma_valid |= MA_INODE;
3459                 rc = mdd_finish_unlink(env, mdd_tobj, ma, mdd_tpobj, ltname,
3460                                        handle);
3461                 if (rc != 0) {
3462                         CERROR("%s: Failed to unlink tobj "
3463                                 DFID": rc = %d\n",
3464                                 mdd2obd_dev(mdd)->obd_name,
3465                                 PFID(tpobj_fid), rc);
3466                         GOTO(fixup_tpobj, rc);
3467                 }
3468
3469                 /* fetch updated nlink */
3470                 rc = mdd_la_get(env, mdd_tobj, tattr);
3471                 if (rc == -ENOENT) {
3472                         /* the object got removed, let's
3473                          * return the latest known attributes */
3474                         tattr->la_nlink = 0;
3475                         rc = 0;
3476                 } else if (rc != 0) {
3477                         CERROR("%s: Failed to get nlink for tobj "
3478                                 DFID": rc = %d\n",
3479                                 mdd2obd_dev(mdd)->obd_name,
3480                                 PFID(tpobj_fid), rc);
3481                         GOTO(fixup_tpobj, rc);
3482                 }
3483                 /* XXX: this transfer to ma will be removed with LOD/OSP */
3484                 ma->ma_attr = *tattr;
3485                 ma->ma_valid |= MA_INODE;
3486
3487                 if (tattr->la_nlink == 0)
3488                         cl_flags |= CLF_RENAME_LAST;
3489                 else
3490                         cl_flags &= ~CLF_RENAME_LAST_EXISTS;
3491         }
3492
3493         la->la_valid = LA_CTIME | LA_MTIME;
3494         rc = mdd_update_time(env, mdd_spobj, pattr, la, handle);
3495         if (rc)
3496                 GOTO(fixup_tpobj, rc);
3497
3498         if (mdd_spobj != mdd_tpobj) {
3499                 la->la_valid = LA_CTIME | LA_MTIME;
3500                 rc = mdd_update_time(env, mdd_tpobj, tpattr, la, handle);
3501                 if (rc != 0)
3502                         GOTO(fixup_tpobj, rc);
3503         }
3504
3505         EXIT;
3506
3507 fixup_tpobj:
3508         if (rc) {
3509                 rc2 = __mdd_index_delete(env, mdd_tpobj, tname, is_dir, handle);
3510                 if (rc2)
3511                         CWARN("tp obj fix error %d\n",rc2);
3512
3513                 if (mdd_tobj && mdd_object_exists(mdd_tobj) &&
3514                     !mdd_is_dead_obj(mdd_tobj)) {
3515                         if (tobj_ref) {
3516                                 mdo_ref_add(env, mdd_tobj, handle);
3517                                 if (is_dir)
3518                                         mdo_ref_add(env, mdd_tobj, handle);
3519                         }
3520
3521                         rc2 = __mdd_index_insert(env, mdd_tpobj,
3522                                                  mdd_object_fid(mdd_tobj),
3523                                                  mdd_object_type(mdd_tobj),
3524                                                  tname, handle);
3525                         if (rc2 != 0)
3526                                 CWARN("tp obj fix error: rc = %d\n", rc2);
3527                 }
3528         }
3529
3530 fixup_spobj:
3531         if (rc && is_dir && mdd_sobj && mdd_spobj != mdd_tpobj) {
3532                 rc2 = __mdd_index_delete_only(env, mdd_sobj, dotdot, handle);
3533                 if (rc2)
3534                         CWARN("%s: sp obj dotdot delete error: rc = %d\n",
3535                                mdd2obd_dev(mdd)->obd_name, rc2);
3536
3537
3538                 rc2 = __mdd_index_insert_only(env, mdd_sobj, spobj_fid, S_IFDIR,
3539                                               dotdot, handle);
3540                 if (rc2 != 0)
3541                         CWARN("%s: sp obj dotdot insert error: rc = %d\n",
3542                               mdd2obd_dev(mdd)->obd_name, rc2);
3543         }
3544
3545 fixup_spobj2:
3546         if (rc != 0) {
3547                 rc2 = __mdd_index_insert(env, mdd_spobj, lf,
3548                                          mdd_object_type(mdd_sobj), sname,
3549                                          handle);
3550                 if (rc2 != 0)
3551                         CWARN("sp obj fix error: rc = %d\n", rc2);
3552         }
3553
3554 cleanup:
3555         if (tobj_locked)
3556                 mdd_write_unlock(env, mdd_tobj);
3557
3558         if (rc == 0)
3559                 rc = mdd_changelog_ns_store(env, mdd, CL_RENAME, cl_flags,
3560                                             mdd_tobj, mdd_tpobj, tpattr, lf,
3561                                             mdd_spobj, pattr, ltname, lsname,
3562                                             handle);
3563
3564 stop:
3565         rc = mdd_trans_stop(env, mdd, rc, handle);
3566
3567 out_pending:
3568         mdd_object_put(env, mdd_sobj);
3569         return rc;
3570 }
3571
3572 /**
3573  * Check whether we should migrate the file/dir
3574  * return val
3575  *      < 0  permission check failed or other error.
3576  *      = 0  the file can be migrated.
3577  **/
3578 static int mdd_migrate_sanity_check(const struct lu_env *env,
3579                                     struct mdd_device *mdd,
3580                                     struct mdd_object *spobj,
3581                                     struct mdd_object *tpobj,
3582                                     struct mdd_object *sobj,
3583                                     struct mdd_object *tobj,
3584                                     const struct lu_attr *spattr,
3585                                     const struct lu_attr *tpattr,
3586                                     const struct lu_attr *attr)
3587 {
3588         int rc;
3589
3590         ENTRY;
3591
3592         if (!mdd_object_remote(sobj)) {
3593                 mdd_read_lock(env, sobj, DT_SRC_CHILD);
3594                 if (sobj->mod_count > 0) {
3595                         CDEBUG(D_INFO, "%s: "DFID" is opened, count %d\n",
3596                                mdd_obj_dev_name(sobj),
3597                                PFID(mdd_object_fid(sobj)),
3598                                sobj->mod_count);
3599                         mdd_read_unlock(env, sobj);
3600                         RETURN(-EBUSY);
3601                 }
3602                 mdd_read_unlock(env, sobj);
3603         }
3604
3605         if (mdd_object_exists(tobj))
3606                 RETURN(-EEXIST);
3607
3608         rc = mdd_may_delete(env, spobj, spattr, sobj, attr, NULL, 1, 0);
3609         if (rc)
3610                 RETURN(rc);
3611
3612         rc = mdd_may_create(env, tpobj, tpattr, NULL, true);
3613
3614         RETURN(rc);
3615 }
3616
3617 struct mdd_xattr_entry {
3618         struct list_head        mxe_linkage;
3619         char                   *mxe_name;
3620         struct lu_buf           mxe_buf;
3621 };
3622
3623 struct mdd_xattrs {
3624         struct lu_buf           mx_namebuf;
3625         struct list_head        mx_list;
3626 };
3627
3628 static inline void mdd_xattrs_init(struct mdd_xattrs *xattrs)
3629 {
3630         INIT_LIST_HEAD(&xattrs->mx_list);
3631         xattrs->mx_namebuf.lb_buf = NULL;
3632         xattrs->mx_namebuf.lb_len = 0;
3633 }
3634
3635 static inline void mdd_xattrs_fini(struct mdd_xattrs *xattrs)
3636 {
3637         struct mdd_xattr_entry *entry;
3638         struct mdd_xattr_entry *tmp;
3639
3640         list_for_each_entry_safe(entry, tmp, &xattrs->mx_list, mxe_linkage) {
3641                 lu_buf_free(&entry->mxe_buf);
3642                 list_del(&entry->mxe_linkage);
3643                 OBD_FREE_PTR(entry);
3644         }
3645
3646         lu_buf_free(&xattrs->mx_namebuf);
3647 }
3648
3649 /* read xattrs into buf, but skip LMA, LMV, LINKEA if 'skip_linkea' is
3650  * set, and DMV if 'skip_dmv" is set.
3651  */
3652 static int mdd_xattrs_migrate_prep(const struct lu_env *env,
3653                                    struct mdd_xattrs *xattrs,
3654                                    struct mdd_object *sobj,
3655                                    bool skip_linkea,
3656                                    bool skip_dmv)
3657 {
3658         struct lu_attr *attr = MDD_ENV_VAR(env, cattr);
3659         struct mdd_xattr_entry *entry;
3660         bool needencxattr = false;
3661         bool encxattrfound = false;
3662         char *xname;
3663         int list_xsize;
3664         int xlen;
3665         int rem;
3666         int xsize;
3667         int rc;
3668
3669         ENTRY;
3670
3671         list_xsize = mdo_xattr_list(env, sobj, &LU_BUF_NULL);
3672         if (list_xsize == -ENODATA)
3673                 RETURN(0);
3674
3675         if (list_xsize < 0)
3676                 RETURN(list_xsize);
3677
3678         if (attr->la_valid & LA_FLAGS &&
3679             attr->la_flags & LUSTRE_ENCRYPT_FL) {
3680                 needencxattr = true;
3681                 list_xsize +=
3682                         strlen(LL_XATTR_NAME_ENCRYPTION_CONTEXT) + 1;
3683         }
3684
3685         lu_buf_alloc(&xattrs->mx_namebuf, list_xsize);
3686         if (xattrs->mx_namebuf.lb_buf == NULL)
3687                 RETURN(-ENOMEM);
3688
3689         rc = mdo_xattr_list(env, sobj, &xattrs->mx_namebuf);
3690         if (rc < 0)
3691                 GOTO(fini, rc);
3692
3693         rem = rc;
3694         rc = 0;
3695         xname = xattrs->mx_namebuf.lb_buf;
3696 reloop:
3697         for (; rem > 0; xname += xlen, rem -= xlen) {
3698                 if (needencxattr &&
3699                     strcmp(xname, LL_XATTR_NAME_ENCRYPTION_CONTEXT) == 0)
3700                         encxattrfound = true;
3701                 xlen = strnlen(xname, rem - 1) + 1;
3702                 if (strcmp(XATTR_NAME_LMA, xname) == 0 ||
3703                     strcmp(XATTR_NAME_LMV, xname) == 0)
3704                         continue;
3705
3706                 if (skip_linkea &&
3707                     strcmp(XATTR_NAME_LINK, xname) == 0)
3708                         continue;
3709
3710                 if (skip_dmv &&
3711                     strcmp(XATTR_NAME_DEFAULT_LMV, xname) == 0)
3712                         continue;
3713
3714                 xsize = mdo_xattr_get(env, sobj, &LU_BUF_NULL, xname);
3715                 if (xsize == -ENODATA)
3716                         continue;
3717                 if (xsize < 0)
3718                         GOTO(fini, rc = xsize);
3719
3720                 OBD_ALLOC_PTR(entry);
3721                 if (!entry)
3722                         GOTO(fini, rc = -ENOMEM);
3723
3724                 lu_buf_alloc(&entry->mxe_buf, xsize);
3725                 if (!entry->mxe_buf.lb_buf) {
3726                         OBD_FREE_PTR(entry);
3727                         GOTO(fini, rc = -ENOMEM);
3728                 }
3729
3730                 rc = mdo_xattr_get(env, sobj, &entry->mxe_buf, xname);
3731                 if (rc < 0) {
3732                         lu_buf_free(&entry->mxe_buf);
3733                         OBD_FREE_PTR(entry);
3734                         if (rc == -ENODATA)
3735                                 continue;
3736                         GOTO(fini, rc);
3737                 }
3738
3739                 entry->mxe_name = xname;
3740                 list_add_tail(&entry->mxe_linkage, &xattrs->mx_list);
3741         }
3742
3743         if (needencxattr && !encxattrfound) {
3744                 xlen = strlen(LL_XATTR_NAME_ENCRYPTION_CONTEXT) + 1;
3745                 strncpy(xname, LL_XATTR_NAME_ENCRYPTION_CONTEXT, xlen);
3746                 rem = xlen;
3747                 GOTO(reloop, 0);
3748         }
3749
3750         RETURN(0);
3751 fini:
3752         mdd_xattrs_fini(xattrs);
3753         RETURN(rc);
3754 }
3755
3756 typedef int (*mdd_xattr_cb)(const struct lu_env *env,
3757                             struct mdd_object *obj,
3758                             const struct lu_buf *buf,
3759                             const char *name,
3760                             int fl, struct thandle *handle);
3761
3762 static int mdd_foreach_xattr(const struct lu_env *env,
3763                              struct mdd_object *tobj,
3764                              struct mdd_xattrs *xattrs,
3765                              struct thandle *handle,
3766                              mdd_xattr_cb cb)
3767 {
3768         struct mdd_xattr_entry *entry;
3769         int rc;
3770
3771         list_for_each_entry(entry, &xattrs->mx_list, mxe_linkage) {
3772                 rc = cb(env, tobj, &entry->mxe_buf, entry->mxe_name, 0, handle);
3773                 if (rc)
3774                         return rc;
3775         }
3776
3777         return 0;
3778 }
3779
3780 typedef int (*mdd_linkea_cb)(const struct lu_env *env,
3781                              struct mdd_object *sobj,
3782                              struct mdd_object *tobj,
3783                              const struct lu_name *sname,
3784                              const struct lu_fid *sfid,
3785                              const struct lu_name *lname,
3786                              const struct lu_fid *fid,
3787                              void *opaque,
3788                              struct thandle *handle);
3789
3790 static int mdd_declare_update_link(const struct lu_env *env,
3791                                    struct mdd_object *sobj,
3792                                    struct mdd_object *tobj,
3793                                    const struct lu_name *tname,
3794                                    const struct lu_fid *tpfid,
3795                                    const struct lu_name *lname,
3796                                    const struct lu_fid *fid,
3797                                    void *unused,
3798                                    struct thandle *handle)
3799 {
3800         struct mdd_device *mdd = mdo2mdd(&sobj->mod_obj);
3801         struct mdd_object *pobj;
3802         int rc;
3803
3804         /* ignore tobj */
3805         if (lu_fid_eq(tpfid, fid) && tname->ln_namelen == lname->ln_namelen &&
3806             !strcmp(tname->ln_name, lname->ln_name))
3807                 return 0;
3808
3809         pobj = mdd_object_find(env, mdd, fid);
3810         if (IS_ERR(pobj))
3811                 return PTR_ERR(pobj);
3812
3813
3814         rc = mdo_declare_index_delete(env, pobj, lname->ln_name, handle);
3815         if (!rc)
3816                 rc = mdo_declare_index_insert(env, pobj, mdd_object_fid(tobj),
3817                                               mdd_object_type(sobj),
3818                                               lname->ln_name, handle);
3819         mdd_object_put(env, pobj);
3820         if (rc)
3821                 return rc;
3822
3823         rc = mdo_declare_ref_add(env, tobj, handle);
3824         if (rc)
3825                 return rc;
3826
3827         rc = mdo_declare_ref_del(env, sobj, handle);
3828         return rc;
3829 }
3830
3831 static int mdd_update_link(const struct lu_env *env,
3832                            struct mdd_object *sobj,
3833                            struct mdd_object *tobj,
3834                            const struct lu_name *tname,
3835                            const struct lu_fid *tpfid,
3836                            const struct lu_name *lname,
3837                            const struct lu_fid *fid,
3838                            void *unused,
3839                            struct thandle *handle)
3840 {
3841         struct mdd_device *mdd = mdo2mdd(&sobj->mod_obj);
3842         struct mdd_object *pobj;
3843         int rc;
3844
3845         ENTRY;
3846
3847         /* ignore tobj */
3848         if (lu_fid_eq(tpfid, fid) && tname->ln_namelen == lname->ln_namelen &&
3849             !memcmp(tname->ln_name, lname->ln_name, lname->ln_namelen))
3850                 RETURN(0);
3851
3852         CDEBUG(D_INFO, "update "DFID"/"DNAME":"DFID"\n",
3853                PFID(fid), PNAME(lname), PFID(mdd_object_fid(tobj)));
3854
3855         pobj = mdd_object_find(env, mdd, fid);
3856         if (IS_ERR(pobj)) {
3857                 CWARN("%s: cannot find obj "DFID": %ld\n",
3858                       mdd2obd_dev(mdd)->obd_name, PFID(fid), PTR_ERR(pobj));
3859                 RETURN(PTR_ERR(pobj));
3860         }
3861
3862         if (!mdd_object_exists(pobj)) {
3863                 CDEBUG(D_INFO, DFID" doesn't exist\n", PFID(fid));
3864                 mdd_object_put(env, pobj);
3865                 RETURN(-ENOENT);
3866         }
3867
3868         mdd_write_lock(env, pobj, DT_TGT_PARENT);
3869         rc = __mdd_index_delete_only(env, pobj, lname->ln_name, handle);
3870         if (!rc)
3871                 rc = __mdd_index_insert_only(env, pobj, mdd_object_fid(tobj),
3872                                              mdd_object_type(sobj),
3873                                              lname->ln_name, handle);
3874         mdd_write_unlock(env, pobj);
3875         mdd_object_put(env, pobj);
3876         if (rc)
3877                 RETURN(rc);
3878
3879         mdd_write_lock(env, tobj, DT_TGT_CHILD);
3880         rc = mdo_ref_add(env, tobj, handle);
3881         mdd_write_unlock(env, tobj);
3882         if (rc)
3883                 RETURN(rc);
3884
3885         mdd_write_lock(env, sobj, DT_SRC_CHILD);
3886         rc = mdo_ref_del(env, sobj, handle);
3887         mdd_write_unlock(env, sobj);
3888
3889         RETURN(rc);
3890 }
3891
3892 static inline int mdd_fld_lookup(const struct lu_env *env,
3893                                  struct mdd_device *mdd,
3894                                  const struct lu_fid *fid,
3895                                  __u32 *mdt_index)
3896 {
3897         struct lu_seq_range *range = &mdd_env_info(env)->mdi_range;
3898         struct seq_server_site *ss;
3899         int rc;
3900
3901         ss = mdd->mdd_md_dev.md_lu_dev.ld_site->ld_seq_site;
3902
3903         range->lsr_flags = LU_SEQ_RANGE_MDT;
3904         rc = fld_server_lookup(env, ss->ss_server_fld, fid->f_seq, range);
3905         if (rc)
3906                 return rc;
3907
3908         *mdt_index = range->lsr_index;
3909
3910         return 0;
3911 }
3912
3913 static int mdd_is_link_on_source_mdt(const struct lu_env *env,
3914                                      struct mdd_object *sobj,
3915                                      struct mdd_object *tobj,
3916                                      const struct lu_name *tname,
3917                                      const struct lu_fid *tpfid,
3918                                      const struct lu_name *lname,
3919                                      const struct lu_fid *fid,
3920                                      void *opaque,
3921                                      struct thandle *handle)
3922 {
3923         struct mdd_device *mdd = mdo2mdd(&sobj->mod_obj);
3924         __u32 source_mdt_index = *(__u32 *)opaque;
3925         __u32 link_mdt_index;
3926         int rc;
3927
3928         ENTRY;
3929
3930         /* ignore tobj */
3931         if (lu_fid_eq(tpfid, fid) && tname->ln_namelen == lname->ln_namelen &&
3932             !memcmp(tname->ln_name, lname->ln_name, lname->ln_namelen))
3933                 return 0;
3934
3935         rc = mdd_fld_lookup(env, mdd, fid, &link_mdt_index);
3936         if (rc)
3937                 RETURN(rc);
3938
3939         RETURN(link_mdt_index == source_mdt_index);
3940 }
3941
3942 static int mdd_iterate_linkea(const struct lu_env *env,
3943                               struct mdd_object *sobj,
3944                               struct mdd_object *tobj,
3945                               const struct lu_name *tname,
3946                               const struct lu_fid *tpfid,
3947                               struct linkea_data *ldata,
3948                               void *opaque,
3949                               struct thandle *handle,
3950                               mdd_linkea_cb cb)
3951 {
3952         struct mdd_thread_info *info = mdd_env_info(env);
3953         char *filename = info->mdi_name;
3954         struct lu_name lname;
3955         struct lu_fid fid;
3956         int rc = 0;
3957
3958         if (!ldata->ld_buf)
3959                 return 0;
3960
3961         for (linkea_first_entry(ldata); ldata->ld_lee && !rc;
3962              linkea_next_entry(ldata)) {
3963                 linkea_entry_unpack(ldata->ld_lee, &ldata->ld_reclen, &lname,
3964                                     &fid);
3965
3966                 /* Note: lname might miss \0 at the end */
3967                 snprintf(filename, sizeof(info->mdi_name), "%.*s",
3968                          lname.ln_namelen, lname.ln_name);
3969                 lname.ln_name = filename;
3970
3971                 CDEBUG(D_INFO, DFID"/"DNAME"\n", PFID(&fid), PNAME(&lname));
3972
3973                 rc = cb(env, sobj, tobj, tname, tpfid, &lname, &fid, opaque,
3974                         handle);
3975         }
3976
3977         return rc;
3978 }
3979
3980 /**
3981  * Prepare linkea, and check whether file needs migrate: if source still has
3982  * link on source MDT, no need to migrate, just update namespace on source and
3983  * target parents.
3984  *
3985  * \retval      0 do migrate
3986  * \retval      1 don't migrate
3987  * \retval      -errno on failure
3988  */
3989 static int mdd_migrate_linkea_prepare(const struct lu_env *env,
3990                                       struct mdd_device *mdd,
3991                                       struct mdd_object *spobj,
3992                                       struct mdd_object *tpobj,
3993                                       struct mdd_object *sobj,
3994                                       const struct lu_name *sname,
3995                                       const struct lu_name *tname,
3996                                       const struct lu_attr *attr,
3997                                       struct linkea_data *ldata)
3998 {
3999         __u32 source_mdt_index;
4000         int rc;
4001
4002         ENTRY;
4003
4004         memset(ldata, 0, sizeof(*ldata));
4005         rc = mdd_linkea_prepare(env, sobj, mdd_object_fid(spobj), sname,
4006                                 mdd_object_fid(tpobj), tname, 1, 0, ldata);
4007         if (rc)
4008                 RETURN(rc);
4009
4010         /*
4011          * Then it will check if the file should be migrated. If the file has
4012          * mulitple links, we only need migrate the file if all of its entries
4013          * has been migrated to the remote MDT.
4014          */
4015         if (S_ISDIR(attr->la_mode) || attr->la_nlink < 2)
4016                 RETURN(0);
4017
4018         /* If there are still links locally, don't migrate this file */
4019         LASSERT(ldata->ld_leh != NULL);
4020
4021         /*
4022          * If linkEA is overflow, it means there are some unknown name entries
4023          * under unknown parents, which will prevent the migration.
4024          */
4025         if (unlikely(ldata->ld_leh->leh_overflow_time))
4026                 RETURN(-EOVERFLOW);
4027
4028         rc = mdd_fld_lookup(env, mdd, mdd_object_fid(sobj), &source_mdt_index);
4029         if (rc)
4030                 RETURN(rc);
4031
4032         rc = mdd_iterate_linkea(env, sobj, NULL, tname, mdd_object_fid(tpobj),
4033                                 ldata, &source_mdt_index, NULL,
4034                                 mdd_is_link_on_source_mdt);
4035         RETURN(rc);
4036 }
4037
4038 static int mdd_declare_migrate_update(const struct lu_env *env,
4039                                       struct mdd_object *spobj,
4040                                       struct mdd_object *tpobj,
4041                                       struct mdd_object *obj,
4042                                       const struct lu_name *sname,
4043                                       const struct lu_name *tname,
4044                                       struct lu_attr *attr,
4045                                       struct lu_attr *spattr,
4046                                       struct lu_attr *tpattr,
4047                                       struct linkea_data *ldata,
4048                                       struct md_attr *ma,
4049                                       struct thandle *handle)
4050 {
4051         struct mdd_thread_info *info = mdd_env_info(env);
4052         struct lu_attr *la = &info->mdi_la_for_fix;
4053         int rc;
4054
4055         rc = mdo_declare_index_delete(env, spobj, sname->ln_name, handle);
4056         if (rc)
4057                 return rc;
4058
4059         if (S_ISDIR(attr->la_mode)) {
4060                 rc = mdo_declare_ref_del(env, spobj, handle);
4061                 if (rc)
4062                         return rc;
4063         }
4064
4065         rc = mdo_declare_index_insert(env, tpobj, mdd_object_fid(obj),
4066                                       attr->la_mode & S_IFMT,
4067                                       tname->ln_name, handle);
4068         if (rc)
4069                 return rc;
4070
4071         rc = mdd_declare_links_add(env, obj, handle, ldata);
4072         if (rc)
4073                 return rc;
4074
4075         if (S_ISDIR(attr->la_mode)) {
4076                 rc = mdo_declare_ref_add(env, tpobj, handle);
4077                 if (rc)
4078                         return rc;
4079         }
4080
4081         la->la_valid = LA_CTIME | LA_MTIME;
4082         rc = mdo_declare_attr_set(env, spobj, la, handle);
4083         if (rc)
4084                 return rc;
4085
4086         if (tpobj != spobj) {
4087                 rc = mdo_declare_attr_set(env, tpobj, la, handle);
4088                 if (rc)
4089                         return rc;
4090         }
4091
4092         return rc;
4093 }
4094
4095 static int mdd_declare_migrate_create(const struct lu_env *env,
4096                                       struct mdd_object *spobj,
4097                                       struct mdd_object *tpobj,
4098                                       struct mdd_object *sobj,
4099                                       struct mdd_object *tobj,
4100                                       const struct lu_name *sname,
4101                                       const struct lu_name *tname,
4102                                       struct lu_attr *spattr,
4103                                       struct lu_attr *tpattr,
4104                                       struct lu_attr *attr,
4105                                       struct lu_buf *sbuf,
4106                                       struct linkea_data *ldata,
4107                                       struct mdd_xattrs *xattrs,
4108                                       struct md_attr *ma,
4109                                       struct md_op_spec *spec,
4110                                       struct dt_allocation_hint *hint,
4111                                       struct thandle *handle)
4112 {
4113         struct mdd_thread_info *info = mdd_env_info(env);
4114         struct md_layout_change *mlc = &info->mdi_mlc;
4115         struct lmv_mds_md_v1 *lmv = sbuf->lb_buf;
4116         int rc;
4117
4118         ENTRY;
4119
4120         if (S_ISDIR(attr->la_mode)) {
4121                 struct lmv_user_md *lum = spec->u.sp_ea.eadata;
4122
4123                 mlc->mlc_opc = MD_LAYOUT_DETACH;
4124                 rc = mdo_declare_layout_change(env, sobj, mlc, handle);
4125                 if (rc)
4126                         return rc;
4127
4128                 lum->lum_hash_type |= cpu_to_le32(LMV_HASH_FLAG_MIGRATION);
4129         } else if (S_ISLNK(attr->la_mode)) {
4130                 spec->u.sp_symname.ln_name = sbuf->lb_buf;
4131                 /* don't count NUL */
4132                 spec->u.sp_symname.ln_namelen = sbuf->lb_len - 1;
4133         } else if (S_ISREG(attr->la_mode)) {
4134                 spec->sp_cr_flags |= MDS_OPEN_DELAY_CREATE;
4135                 spec->sp_cr_flags &= ~MDS_OPEN_HAS_EA;
4136         }
4137
4138         mdd_object_make_hint(env, tpobj, tobj, attr, spec, hint);
4139
4140         rc = mdd_declare_create(env, mdo2mdd(&tpobj->mod_obj), tpobj, tobj,
4141                                 tname, attr, handle, spec, ldata, NULL, NULL,
4142                                 NULL, hint);
4143         if (rc)
4144                 return rc;
4145
4146         /*
4147          * tobj mode will be used in mdo_declare_layout_change(), but it's not
4148          * createb yet, copy from sobj.
4149          */
4150         tobj->mod_obj.mo_lu.lo_header->loh_attr &= ~S_IFMT;
4151         tobj->mod_obj.mo_lu.lo_header->loh_attr |=
4152                 sobj->mod_obj.mo_lu.lo_header->loh_attr & S_IFMT;
4153
4154         if (S_ISDIR(attr->la_mode)) {
4155                 if (!lmv) {
4156                         /* if sobj is not striped, fake a 1-stripe LMV */
4157                         LASSERT(sizeof(info->mdi_key) >
4158                                 lmv_mds_md_size(1, LMV_MAGIC_V1));
4159                         lmv = (typeof(lmv))info->mdi_key;
4160                         memset(lmv, 0, sizeof(*lmv));
4161                         lmv->lmv_magic = cpu_to_le32(LMV_MAGIC_V1);
4162                         lmv->lmv_stripe_count = cpu_to_le32(1);
4163                         lmv->lmv_hash_type = cpu_to_le32(LMV_HASH_TYPE_DEFAULT);
4164                         fid_le_to_cpu(&lmv->lmv_stripe_fids[0],
4165                                       mdd_object_fid(sobj));
4166                         mlc->mlc_buf.lb_buf = lmv;
4167                         mlc->mlc_buf.lb_len = lmv_mds_md_size(1, LMV_MAGIC_V1);
4168                 } else {
4169                         mlc->mlc_buf = *sbuf;
4170                 }
4171                 mlc->mlc_opc = MD_LAYOUT_ATTACH;
4172                 rc = mdo_declare_layout_change(env, tobj, mlc, handle);
4173                 if (rc)
4174                         return rc;
4175         }
4176
4177         rc = mdd_foreach_xattr(env, tobj, xattrs, handle,
4178                                mdo_declare_xattr_set);
4179         if (rc)
4180                 return rc;
4181
4182         if (S_ISREG(attr->la_mode)) {
4183                 struct lu_buf fid_buf;
4184
4185                 handle->th_complex = 1;
4186
4187                 /* target may be remote, update PFID via sobj. */
4188                 fid_buf.lb_buf = (void *)mdd_object_fid(tobj);
4189                 fid_buf.lb_len = sizeof(struct lu_fid);
4190                 rc = mdo_declare_xattr_set(env, sobj, &fid_buf, XATTR_NAME_FID,
4191                                            0, handle);
4192                 if (rc)
4193                         return rc;
4194
4195                 rc = mdo_declare_xattr_del(env, sobj, XATTR_NAME_LOV, handle);
4196                 if (rc)
4197                         return rc;
4198         }
4199
4200         if (!S_ISDIR(attr->la_mode)) {
4201                 rc = mdd_iterate_linkea(env, sobj, tobj, tname,
4202                                         mdd_object_fid(tpobj), ldata, NULL,
4203                                         handle, mdd_declare_update_link);
4204                 if (rc)
4205                         return rc;
4206         }
4207
4208         if (!S_ISDIR(attr->la_mode) || lmv) {
4209                 rc = mdo_declare_ref_del(env, sobj, handle);
4210                 if (rc)
4211                         return rc;
4212
4213                 if (S_ISDIR(attr->la_mode)) {
4214                         rc = mdo_declare_ref_del(env, sobj, handle);
4215                         if (rc)
4216                                 return rc;
4217                 }
4218
4219                 rc = mdo_declare_destroy(env, sobj, handle);
4220                 if (rc)
4221                         return rc;
4222         }
4223
4224         rc = mdd_declare_migrate_update(env, spobj, tpobj, tobj, sname, tname,
4225                                         attr, spattr, tpattr, ldata, ma,
4226                                         handle);
4227         return rc;
4228 }
4229
4230 /**
4231  * migrate dirent from \a spobj to \a tpobj.
4232  **/
4233 static int mdd_migrate_update(const struct lu_env *env,
4234                               struct mdd_object *spobj,
4235                               struct mdd_object *tpobj,
4236                               struct mdd_object *obj,
4237                               const struct lu_name *sname,
4238                               const struct lu_name *tname,
4239                               struct lu_attr *attr,
4240                               struct lu_attr *spattr,
4241                               struct lu_attr *tpattr,
4242                               struct linkea_data *ldata,
4243                               struct md_attr *ma,
4244                               struct thandle *handle)
4245 {
4246         struct mdd_thread_info *info = mdd_env_info(env);
4247         struct lu_attr *la = &info->mdi_la_for_fix;
4248         int rc;
4249
4250         ENTRY;
4251
4252         CDEBUG(D_INFO, "update "DFID" from "DFID"/%s to "DFID"/%s\n",
4253                PFID(mdd_object_fid(obj)), PFID(mdd_object_fid(spobj)),
4254                sname->ln_name, PFID(mdd_object_fid(tpobj)), tname->ln_name);
4255
4256         rc = __mdd_index_delete(env, spobj, sname->ln_name,
4257                                 S_ISDIR(attr->la_mode), handle);
4258         if (rc)
4259                 RETURN(rc);
4260
4261         rc = __mdd_index_insert(env, tpobj, mdd_object_fid(obj),
4262                                 attr->la_mode & S_IFMT,
4263                                 tname->ln_name, handle);
4264         if (rc)
4265                 RETURN(rc);
4266
4267         rc = mdd_links_write(env, obj, ldata, handle);
4268         if (rc)
4269                 RETURN(rc);
4270
4271         la->la_ctime = la->la_mtime = ma->ma_attr.la_ctime;
4272         la->la_valid = LA_CTIME | LA_MTIME;
4273         mdd_write_lock(env, spobj, DT_SRC_PARENT);
4274         rc = mdd_update_time(env, spobj, spattr, la, handle);
4275         mdd_write_unlock(env, spobj);
4276         if (rc)
4277                 RETURN(rc);
4278
4279         if (tpobj != spobj) {
4280                 la->la_valid = LA_CTIME | LA_MTIME;
4281                 mdd_write_lock(env, tpobj, DT_TGT_PARENT);
4282                 rc = mdd_update_time(env, tpobj, tpattr, la, handle);
4283                 mdd_write_unlock(env, tpobj);
4284                 if (rc)
4285                         RETURN(rc);
4286         }
4287
4288         RETURN(rc);
4289 }
4290
4291 /**
4292  * Migrate file/dir to target MDT.
4293  *
4294  * Create target according to \a spec, and then migrate xattrs, if it's
4295  * directory, migrate source stripes to target.
4296  *
4297  * \param[in] env       execution environment
4298  * \param[in] spobj     source parent object
4299  * \param[in] tpobj     target parent object
4300  * \param[in] sobj      source object
4301  * \param[in] tobj      target object
4302  * \param[in] lname     file name
4303  * \param[in] spattr    source parent attributes
4304  * \param[in] tpattr    target parent attributes
4305  * \param[in] attr      source attributes
4306  * \param[in] sbuf      source LMV buf
4307  * \param[in] spec      migrate create spec
4308  * \param[in] hint      target creation hint
4309  * \param[in] handle    tranasction handle
4310  *
4311  * \retval      0 on success
4312  * \retval      -errno on failure
4313  **/
4314 static int mdd_migrate_create(const struct lu_env *env,
4315                               struct mdd_object *spobj,
4316                               struct mdd_object *tpobj,
4317                               struct mdd_object *sobj,
4318                               struct mdd_object *tobj,
4319                               const struct lu_name *sname,
4320                               const struct lu_name *tname,
4321                               struct lu_attr *spattr,
4322                               struct lu_attr *tpattr,
4323                               struct lu_attr *attr,
4324                               const struct lu_buf *sbuf,
4325                               struct linkea_data *ldata,
4326                               struct mdd_xattrs *xattrs,
4327                               struct md_attr *ma,
4328                               struct md_op_spec *spec,
4329                               struct dt_allocation_hint *hint,
4330                               struct thandle *handle)
4331 {
4332         int rc;
4333
4334         ENTRY;
4335
4336         /*
4337          * migrate sobj stripes to tobj if it's directory:
4338          * 1. detach stripes from sobj.
4339          * 2. attach stripes to tobj, see mdd_declare_migrate_mdt().
4340          * 3. create stripes for tobj, see lod_xattr_set_lmv().
4341          */
4342         if (S_ISDIR(attr->la_mode)) {
4343                 struct mdd_thread_info *info = mdd_env_info(env);
4344                 struct md_layout_change *mlc = &info->mdi_mlc;
4345
4346                 mlc->mlc_opc = MD_LAYOUT_DETACH;
4347
4348                 mdd_write_lock(env, sobj, DT_SRC_PARENT);
4349                 rc = mdo_layout_change(env, sobj, mlc, handle);
4350                 mdd_write_unlock(env, sobj);
4351                 if (rc)
4352                         RETURN(rc);
4353         }
4354
4355         /* don't set nlink from sobj */
4356         attr->la_valid &= ~LA_NLINK;
4357
4358         rc = mdd_create_object(env, tpobj, tobj, attr, spec, NULL, NULL, NULL,
4359                                hint, handle, false);
4360         if (rc)
4361                 RETURN(rc);
4362
4363         mdd_write_lock(env, tobj, DT_TGT_CHILD);
4364         rc = mdd_foreach_xattr(env, tobj, xattrs, handle, mdo_xattr_set);
4365         mdd_write_unlock(env, tobj);
4366         if (rc)
4367                 RETURN(rc);
4368
4369         /* for regular file, update OST objects XATTR_NAME_FID */
4370         if (S_ISREG(attr->la_mode)) {
4371                 struct lu_buf fid_buf;
4372
4373                 /* target may be remote, update PFID via sobj. */
4374                 fid_buf.lb_buf = (void *)mdd_object_fid(tobj);
4375                 fid_buf.lb_len = sizeof(struct lu_fid);
4376                 rc = mdo_xattr_set(env, sobj, &fid_buf, XATTR_NAME_FID, 0,
4377                                    handle);
4378                 if (rc)
4379                         RETURN(rc);
4380
4381                 /* delete LOV to avoid deleting OST objs when destroying sobj */
4382                 mdd_write_lock(env, sobj, DT_SRC_CHILD);
4383                 rc = mdo_xattr_del(env, sobj, XATTR_NAME_LOV, handle);
4384                 mdd_write_unlock(env, sobj);
4385                 /* O_DELAY_CREATE file may not have LOV, ignore -ENODATA */
4386                 if (rc && rc != -ENODATA)
4387                         RETURN(rc);
4388                 rc = 0;
4389         }
4390
4391         /* update links FID */
4392         if (!S_ISDIR(attr->la_mode)) {
4393                 rc = mdd_iterate_linkea(env, sobj, tobj, tname,
4394                                         mdd_object_fid(tpobj), ldata,
4395                                         NULL, handle, mdd_update_link);
4396                 if (rc)
4397                         RETURN(rc);
4398         }
4399
4400         /* don't destroy sobj if it's plain directory */
4401         if (!S_ISDIR(attr->la_mode) || sbuf->lb_buf) {
4402                 mdd_write_lock(env, sobj, DT_SRC_CHILD);
4403                 rc = mdo_ref_del(env, sobj, handle);
4404                 if (!rc) {
4405                         if (S_ISDIR(attr->la_mode))
4406                                 rc = mdo_ref_del(env, sobj, handle);
4407                         if (!rc)
4408                                 rc = mdo_destroy(env, sobj, handle);
4409                 }
4410                 mdd_write_unlock(env, sobj);
4411                 if (rc)
4412                         RETURN(rc);
4413         }
4414
4415         rc = mdd_migrate_update(env, spobj, tpobj, tobj, sname, tname, attr,
4416                                 spattr, tpattr, ldata, ma, handle);
4417
4418         RETURN(rc);
4419 }
4420
4421 /* NB: if user issued different migrate command, we can't adjust it silently
4422  * here, because this command will decide target MDT in subdir migration in
4423  * LMV.
4424  */
4425 static int mdd_migrate_cmd_check(struct mdd_device *mdd,
4426                                  const struct lmv_mds_md_v1 *lmv,
4427                                  const struct lmv_user_md_v1 *lum,
4428                                  const struct lu_name *lname)
4429 {
4430         __u32 lum_stripe_count = lum->lum_stripe_count;
4431         __u32 lum_hash_type = lum->lum_hash_type &
4432                               cpu_to_le32(LMV_HASH_TYPE_MASK);
4433         __u32 lmv_hash_type = lmv->lmv_hash_type &
4434                               cpu_to_le32(LMV_HASH_TYPE_MASK);
4435
4436         if (!lmv_is_sane(lmv))
4437                 return -EBADF;
4438
4439         /* if stripe_count unspecified, set to 1 */
4440         if (!lum_stripe_count)
4441                 lum_stripe_count = cpu_to_le32(1);
4442
4443         /* TODO: check specific MDTs */
4444         if (lum_stripe_count != lmv->lmv_migrate_offset ||
4445             lum->lum_stripe_offset != lmv->lmv_master_mdt_index ||
4446             (lum_hash_type && lum_hash_type != lmv_hash_type)) {
4447                 CERROR("%s: '"DNAME"' migration was interrupted, run 'lfs migrate -m %d -c %d -H %s "DNAME"' to finish migration.\n",
4448                         mdd2obd_dev(mdd)->obd_name, PNAME(lname),
4449                         le32_to_cpu(lmv->lmv_master_mdt_index),
4450                         le32_to_cpu(lmv->lmv_migrate_offset),
4451                         mdt_hash_name[le32_to_cpu(lmv_hash_type)],
4452                         PNAME(lname));
4453                 return -EPERM;
4454         }
4455
4456         return -EALREADY;
4457 }
4458
4459 /**
4460  * Internal function to migrate directory or file between MDTs.
4461  *
4462  * migrate source to target in following steps:
4463  *   1. create target, append source stripes after target's if it's directory,
4464  *      migrate xattrs and update fid of source links.
4465  *   2. update namespace: migrate dirent from source parent to target parent,
4466  *      update file linkea, and destroy source if it's not needed any more.
4467  *
4468  * \param[in] env       execution environment
4469  * \param[in] spobj     source parent object
4470  * \param[in] tpobj     target parent object
4471  * \param[in] sobj      source object
4472  * \param[in] tobj      target object
4473  * \param[in] sname     source file name
4474  * \param[in] tname     target file name
4475  * \param[in] spec      target creation spec
4476  * \param[in] ma        used to update \a pobj mtime and ctime
4477  *
4478  * \retval              0 on success
4479  * \retval              -errno on failure
4480  */
4481 static int mdd_migrate_object(const struct lu_env *env,
4482                               struct mdd_object *spobj,
4483                               struct mdd_object *tpobj,
4484                               struct mdd_object *sobj,
4485                               struct mdd_object *tobj,
4486                               const struct lu_name *sname,
4487                               const struct lu_name *tname,
4488                               struct md_op_spec *spec,
4489                               struct md_attr *ma)
4490 {
4491         struct mdd_thread_info *info = mdd_env_info(env);
4492         struct mdd_device *mdd = mdo2mdd(&spobj->mod_obj);
4493         struct lu_attr *spattr = &info->mdi_pattr;
4494         struct lu_attr *tpattr = &info->mdi_tpattr;
4495         struct lu_attr *attr = &info->mdi_cattr;
4496         struct linkea_data *ldata = &info->mdi_link_data;
4497         struct dt_allocation_hint *hint = &info->mdi_hint;
4498         struct lu_buf sbuf = { NULL };
4499         struct mdd_xattrs xattrs;
4500         struct lmv_mds_md_v1 *lmv;
4501         struct thandle *handle;
4502         int retried = 0;
4503         int rc;
4504
4505         ENTRY;
4506
4507         CDEBUG(D_INFO, "migrate %s from "DFID"/"DFID" to "DFID"/"DFID"\n",
4508                sname->ln_name, PFID(mdd_object_fid(spobj)),
4509                PFID(mdd_object_fid(sobj)), PFID(mdd_object_fid(tpobj)),
4510                PFID(mdd_object_fid(tobj)));
4511
4512 retry:
4513         rc = mdd_la_get(env, sobj, attr);
4514         if (rc)
4515                 RETURN(rc);
4516
4517         rc = mdd_la_get(env, spobj, spattr);
4518         if (rc)
4519                 RETURN(rc);
4520
4521         rc = mdd_la_get(env, tpobj, tpattr);
4522         if (rc)
4523                 RETURN(rc);
4524
4525         rc = mdd_migrate_sanity_check(env, mdd, spobj, tpobj, sobj, tobj,
4526                                       spattr, tpattr, attr);
4527         if (rc)
4528                 RETURN(rc);
4529
4530         mdd_xattrs_init(&xattrs);
4531
4532         if (S_ISDIR(attr->la_mode) && !spec->sp_migrate_nsonly) {
4533                 struct lmv_user_md_v1 *lum = spec->u.sp_ea.eadata;
4534
4535                 LASSERT(lum);
4536
4537                 /* if user use default value '0' for stripe_count, we need to
4538                  * adjust it to '1' to create a 1-stripe directory.
4539                  */
4540                 if (lum->lum_stripe_count == 0)
4541                         lum->lum_stripe_count = cpu_to_le32(1);
4542
4543                 rc = mdd_stripe_get(env, sobj, &sbuf, XATTR_NAME_LMV);
4544                 if (rc && rc != -ENODATA)
4545                         GOTO(out, rc);
4546
4547                 lmv = sbuf.lb_buf;
4548                 if (lmv) {
4549                         if (!lmv_is_sane(lmv))
4550                                 GOTO(out, rc = -EBADF);
4551                         if (lmv_is_migrating(lmv)) {
4552                                 rc = mdd_migrate_cmd_check(mdd, lmv, lum,
4553                                                            sname);
4554                                 GOTO(out, rc);
4555                         }
4556                 }
4557         } else if (!S_ISDIR(attr->la_mode)) {
4558                 if (spobj == tpobj)
4559                         GOTO(out, rc = -EALREADY);
4560
4561                 /* update namespace only if @sobj is on MDT where @tpobj is. */
4562                 if (!mdd_object_remote(tpobj) && !mdd_object_remote(sobj))
4563                         spec->sp_migrate_nsonly = true;
4564
4565                 if (S_ISLNK(attr->la_mode)) {
4566                         lu_buf_check_and_alloc(&sbuf, attr->la_size + 1);
4567                         if (!sbuf.lb_buf)
4568                                 GOTO(out, rc = -ENOMEM);
4569
4570                         rc = mdd_readlink(env, &sobj->mod_obj, &sbuf);
4571                         if (rc <= 0) {
4572                                 rc = rc ?: -EFAULT;
4573                                 CERROR("%s: "DFID" readlink failed: rc = %d\n",
4574                                        mdd2obd_dev(mdd)->obd_name,
4575                                        PFID(mdd_object_fid(sobj)), rc);
4576                                 GOTO(out, rc);
4577                         }
4578                 }
4579         }
4580
4581         /* linkea needs update upon FID or parent stripe change */
4582         rc = mdd_migrate_linkea_prepare(env, mdd, spobj, tpobj, sobj, sname,
4583                                         tname, attr, ldata);
4584         if (rc > 0)
4585                 /* update namespace only if @sobj has link on its MDT. */
4586                 spec->sp_migrate_nsonly = true;
4587         else if (rc < 0)
4588                 GOTO(out, rc);
4589
4590         /* migrate inode will migrate xattrs, prepare xattrs early to avoid
4591          * RPCs inside transaction.
4592          */
4593         if (!spec->sp_migrate_nsonly) {
4594                 rc = mdd_xattrs_migrate_prep(env, &xattrs, sobj, true, true);
4595                 if (rc)
4596                         GOTO(out, rc);
4597         }
4598
4599         handle = mdd_trans_create(env, mdd);
4600         if (IS_ERR(handle))
4601                 GOTO(out, rc = PTR_ERR(handle));
4602
4603         if (spec->sp_migrate_nsonly)
4604                 rc = mdd_declare_migrate_update(env, spobj, tpobj, sobj, sname,
4605                                                 tname, attr, spattr, tpattr,
4606                                                 ldata, ma, handle);
4607         else
4608                 rc = mdd_declare_migrate_create(env, spobj, tpobj, sobj, tobj,
4609                                                 sname, tname, spattr, tpattr,
4610                                                 attr, &sbuf, ldata, &xattrs, ma,
4611                                                 spec, hint, handle);
4612         if (rc)
4613                 GOTO(stop, rc);
4614
4615         rc = mdd_declare_changelog_store(env, mdd, CL_MIGRATE, tname, sname,
4616                                          handle);
4617         if (rc)
4618                 GOTO(stop, rc);
4619
4620         rc = mdd_trans_start(env, mdd, handle);
4621         if (rc)
4622                 GOTO(stop, rc);
4623
4624         if (spec->sp_migrate_nsonly)
4625                 rc = mdd_migrate_update(env, spobj, tpobj, sobj, sname, tname,
4626                                         attr, spattr, tpattr, ldata, ma,
4627                                         handle);
4628         else
4629                 rc = mdd_migrate_create(env, spobj, tpobj, sobj, tobj, sname,
4630                                         tname, spattr, tpattr, attr, &sbuf,
4631                                         ldata, &xattrs, ma, spec, hint, handle);
4632         if (rc)
4633                 GOTO(stop, rc);
4634
4635         rc = mdd_changelog_ns_store(env, mdd, CL_MIGRATE, 0,
4636                                     spec->sp_migrate_nsonly ? sobj : tobj,
4637                                     spobj, spattr, mdd_object_fid(sobj),
4638                                     tpobj, tpattr, tname, sname,
4639                                     handle);
4640
4641 stop:
4642         rc = mdd_trans_stop(env, mdd, rc, handle);
4643 out:
4644         mdd_xattrs_fini(&xattrs);
4645         lu_buf_free(&sbuf);
4646
4647         /**
4648          * -EAGAIN means transaction execution phase detect the layout
4649          * has been changed by others.
4650          */
4651         if (rc == -EAGAIN && retried++ < MAX_TRANS_RETRIED)
4652                 GOTO(retry, retried);
4653
4654         RETURN(rc);
4655 }
4656
4657 /**
4658  * Migrate directory or file between MDTs.
4659  *
4660  * \param[in] env       execution environment
4661  * \param[in] md_spobj  source parent object
4662  * \param[in] md_tpobj  target parent object
4663  * \param[in] md_sobj   source object
4664  * \param[in] lname     file name
4665  * \param[in] md_tobj   target object
4666  * \param[in] spec      target creation spec
4667  * \param[in] ma        used to update \a pobj mtime and ctime
4668  *
4669  * \retval              0 on success
4670  * \retval              -errno on failure
4671  */
4672 static int mdd_migrate(const struct lu_env *env, struct md_object *md_spobj,
4673                        struct md_object *md_tpobj, struct md_object *md_sobj,
4674                        struct md_object *md_tobj, const struct lu_name *lname,
4675                        struct md_op_spec *spec, struct md_attr *ma)
4676 {
4677         return mdd_migrate_object(env, md2mdd_obj(md_spobj),
4678                                   md2mdd_obj(md_tpobj), md2mdd_obj(md_sobj),
4679                                   md2mdd_obj(md_tobj), lname, lname, spec, ma);
4680 }
4681
4682 static int mdd_declare_1sd_collapse(const struct lu_env *env,
4683                                     struct mdd_object *pobj,
4684                                     struct mdd_object *obj,
4685                                     struct mdd_object *stripe,
4686                                     struct lu_attr *attr,
4687                                     struct mdd_xattrs *xattrs,
4688                                     struct md_layout_change *mlc,
4689                                     struct lu_name *lname,
4690                                     struct thandle *handle)
4691 {
4692         int rc;
4693
4694         mlc->mlc_opc = MD_LAYOUT_DETACH;
4695         rc = mdo_declare_layout_change(env, obj, mlc, handle);
4696         if (rc)
4697                 return rc;
4698
4699         rc = mdo_declare_index_insert(env, stripe, mdd_object_fid(pobj),
4700                                       S_IFDIR, dotdot, handle);
4701         if (rc)
4702                 return rc;
4703
4704         rc = mdd_foreach_xattr(env, stripe, xattrs, handle,
4705                                mdo_declare_xattr_set);
4706         if (rc)
4707                 return rc;
4708
4709         rc = mdo_declare_xattr_del(env, stripe, XATTR_NAME_LMV, handle);
4710         if (rc)
4711                 return rc;
4712
4713         rc = mdo_declare_attr_set(env, stripe, attr, handle);
4714         if (rc)
4715                 return rc;
4716
4717         rc = mdo_declare_index_delete(env, pobj, lname->ln_name, handle);
4718         if (rc)
4719                 return rc;
4720
4721         rc = mdo_declare_index_insert(env, pobj, mdd_object_fid(stripe),
4722                                       attr->la_mode, lname->ln_name, handle);
4723         if (rc)
4724                 return rc;
4725
4726         rc = mdo_declare_ref_del(env, obj, handle);
4727         if (rc)
4728                 return rc;
4729
4730         rc = mdo_declare_ref_del(env, obj, handle);
4731         if (rc)
4732                 return rc;
4733
4734         rc = mdo_declare_destroy(env, obj, handle);
4735         if (rc)
4736                 return rc;
4737
4738         return rc;
4739 }
4740
4741 /* transform one-stripe directory to a plain directory */
4742 static int mdd_1sd_collapse(const struct lu_env *env,
4743                             struct mdd_object *pobj,
4744                             struct mdd_object *obj,
4745                             struct mdd_object *stripe,
4746                             struct lu_attr *attr,
4747                             struct mdd_xattrs *xattrs,
4748                             struct md_layout_change *mlc,
4749                             struct lu_name *lname,
4750                             struct thandle *handle)
4751 {
4752         int rc;
4753
4754         ENTRY;
4755
4756         /* replace 1-stripe directory with its stripe */
4757         mlc->mlc_opc = MD_LAYOUT_DETACH;
4758
4759         mdd_write_lock(env, obj, DT_SRC_PARENT);
4760         rc = mdo_layout_change(env, obj, mlc, handle);
4761         mdd_write_unlock(env, obj);
4762         if (rc)
4763                 RETURN(rc);
4764
4765         mdd_write_lock(env, pobj, DT_SRC_PARENT);
4766         mdd_write_lock(env, obj, DT_SRC_CHILD);
4767
4768         /* insert dotdot to stripe which points to parent */
4769         rc = __mdd_index_insert_only(env, stripe, mdd_object_fid(pobj),
4770                                      S_IFDIR, dotdot, handle);
4771         if (rc)
4772                 GOTO(out, rc);
4773
4774         rc = mdd_foreach_xattr(env, stripe, xattrs, handle, mdo_xattr_set);
4775         if (rc)
4776                 GOTO(out, rc);
4777
4778         /* delete LMV */
4779         rc = mdo_xattr_del(env, stripe, XATTR_NAME_LMV, handle);
4780         if (rc)
4781                 GOTO(out, rc);
4782
4783         /* don't set nlink from parent */
4784         attr->la_valid &= ~LA_NLINK;
4785
4786         rc = mdo_attr_set(env, stripe, attr, handle);
4787         if (rc)
4788                 GOTO(out, rc);
4789
4790         /* delete dir name from parent */
4791         rc = __mdd_index_delete_only(env, pobj, lname->ln_name, handle);
4792         if (rc)
4793                 GOTO(out, rc);
4794
4795         /* insert stripe to parent with dir name */
4796         rc = __mdd_index_insert_only(env, pobj, mdd_object_fid(stripe),
4797                                      attr->la_mode, lname->ln_name, handle);
4798         if (rc)
4799                 GOTO(out, rc);
4800
4801         /* destroy dir obj */
4802         rc = mdo_ref_del(env, obj, handle);
4803         if (rc)
4804                 GOTO(out, rc);
4805
4806         rc = mdo_ref_del(env, obj, handle);
4807         if (rc)
4808                 GOTO(out, rc);
4809
4810         rc = mdo_destroy(env, obj, handle);
4811         if (rc)
4812                 GOTO(out, rc);
4813
4814         EXIT;
4815 out:
4816         mdd_write_unlock(env, obj);
4817         mdd_write_unlock(env, pobj);
4818
4819         return rc;
4820 }
4821
4822 /*
4823  * shrink directory stripes after migration/merge
4824  */
4825 int mdd_dir_layout_shrink(const struct lu_env *env,
4826                           struct md_object *md_obj,
4827                           struct md_layout_change *mlc)
4828 {
4829         struct mdd_device *mdd = mdo2mdd(md_obj);
4830         struct mdd_thread_info *info = mdd_env_info(env);
4831         struct mdd_object *obj = md2mdd_obj(md_obj);
4832         struct mdd_object *pobj = NULL;
4833         struct mdd_object *stripe = NULL;
4834         struct lu_attr *attr = &info->mdi_pattr;
4835         struct lu_fid *fid = &info->mdi_fid2;
4836         struct lu_name lname = { NULL };
4837         struct lu_buf lmv_buf = { NULL };
4838         struct mdd_xattrs xattrs;
4839         struct lmv_mds_md_v1 *lmv;
4840         struct lmv_user_md *lmu;
4841         struct thandle *handle;
4842         int rc;
4843
4844         ENTRY;
4845
4846         rc = mdd_la_get(env, obj, attr);
4847         if (rc)
4848                 RETURN(rc);
4849
4850         if (!S_ISDIR(attr->la_mode))
4851                 RETURN(-ENOTDIR);
4852
4853         rc = mdd_stripe_get(env, obj, &lmv_buf, XATTR_NAME_LMV);
4854         if (rc < 0)
4855                 RETURN(rc);
4856
4857         lmv = lmv_buf.lb_buf;
4858         if (!lmv_is_sane(lmv))
4859                 RETURN(-EBADF);
4860
4861         lmu = mlc->mlc_buf.lb_buf;
4862
4863         /* adjust the default value '0' to '1' */
4864         if (lmu->lum_stripe_count == 0)
4865                 lmu->lum_stripe_count = cpu_to_le32(1);
4866
4867         /* these were checked in MDT */
4868         LASSERT(le32_to_cpu(lmu->lum_stripe_count) <
4869                 le32_to_cpu(lmv->lmv_stripe_count));
4870         LASSERT(!lmv_is_splitting(lmv));
4871         LASSERT(lmv_is_migrating(lmv) || lmv_is_merging(lmv));
4872
4873         mdd_xattrs_init(&xattrs);
4874
4875         /* if dir stripe count will be shrunk to 1, it needs to be transformed
4876          * to a plain dir, which will cause FID change and namespace update.
4877          */
4878         if (le32_to_cpu(lmu->lum_stripe_count) == 1) {
4879                 struct linkea_data *ldata = &info->mdi_link_data;
4880                 char *filename = info->mdi_name;
4881
4882                 rc = mdd_links_read(env, obj, ldata);
4883                 if (rc)
4884                         GOTO(out, rc);
4885
4886                 if (ldata->ld_leh->leh_reccount > 1)
4887                         GOTO(out, rc = -EINVAL);
4888
4889                 linkea_first_entry(ldata);
4890                 if (!ldata->ld_lee)
4891                         GOTO(out, rc = -ENODATA);
4892
4893                 linkea_entry_unpack(ldata->ld_lee, &ldata->ld_reclen, &lname,
4894                                     fid);
4895
4896                 /* Note: lname might miss \0 at the end */
4897                 snprintf(filename, sizeof(info->mdi_name), "%.*s",
4898                          lname.ln_namelen, lname.ln_name);
4899                 lname.ln_name = filename;
4900
4901                 pobj = mdd_object_find(env, mdd, fid);
4902                 if (IS_ERR(pobj)) {
4903                         rc = PTR_ERR(pobj);
4904                         pobj = NULL;
4905                         GOTO(out, rc);
4906                 }
4907
4908                 fid_le_to_cpu(fid, &lmv->lmv_stripe_fids[0]);
4909
4910                 stripe = mdd_object_find(env, mdd, fid);
4911                 if (IS_ERR(stripe)) {
4912                         mdd_object_put(env, pobj);
4913                         pobj = NULL;
4914                         GOTO(out, rc = PTR_ERR(stripe));
4915                 }
4916
4917                 if (!lmv_is_fixed(lmv))
4918                         rc = mdd_xattrs_migrate_prep(env, &xattrs, obj, false,
4919                                                      false);
4920         }
4921
4922         handle = mdd_trans_create(env, mdd);
4923         if (IS_ERR(handle))
4924                 GOTO(out, rc = PTR_ERR(handle));
4925
4926         mlc->mlc_opc = MD_LAYOUT_SHRINK;
4927         rc = mdo_declare_layout_change(env, obj, mlc, handle);
4928         if (rc)
4929                 GOTO(stop_trans, rc);
4930
4931         if (le32_to_cpu(lmu->lum_stripe_count) == 1 && !lmv_is_fixed(lmv)) {
4932                 rc = mdd_declare_1sd_collapse(env, pobj, obj, stripe, attr,
4933                                               &xattrs, mlc, &lname, handle);
4934                 if (rc)
4935                         GOTO(stop_trans, rc);
4936         }
4937
4938         rc = mdd_declare_changelog_store(env, mdd, CL_LAYOUT, NULL, NULL,
4939                                          handle);
4940         if (rc)
4941                 GOTO(stop_trans, rc);
4942
4943         rc = mdd_trans_start(env, mdd, handle);
4944         if (rc)
4945                 GOTO(stop_trans, rc);
4946
4947         mdd_write_lock(env, obj, DT_SRC_PARENT);
4948         mlc->mlc_opc = MD_LAYOUT_SHRINK;
4949         rc = mdo_layout_change(env, obj, mlc, handle);
4950         mdd_write_unlock(env, obj);
4951         if (rc)
4952                 GOTO(stop_trans, rc);
4953
4954         if (le32_to_cpu(lmu->lum_stripe_count) == 1 && !lmv_is_fixed(lmv)) {
4955                 rc = mdd_1sd_collapse(env, pobj, obj, stripe, attr, &xattrs,
4956                                       mlc, &lname, handle);
4957                 if (rc)
4958                         GOTO(stop_trans, rc);
4959         }
4960
4961         rc = mdd_changelog_data_store_xattr(env, mdd, CL_LAYOUT, 0, obj,
4962                                             XATTR_NAME_LMV, handle);
4963         GOTO(stop_trans, rc);
4964
4965 stop_trans:
4966         rc = mdd_trans_stop(env, mdd, rc, handle);
4967 out:
4968         mdd_xattrs_fini(&xattrs);
4969         if (pobj) {
4970                 mdd_object_put(env, stripe);
4971                 mdd_object_put(env, pobj);
4972         }
4973         lu_buf_free(&lmv_buf);
4974         return rc;
4975 }
4976
4977 static int mdd_dir_declare_split_plain(const struct lu_env *env,
4978                                         struct mdd_device *mdd,
4979                                         struct mdd_object *pobj,
4980                                         struct mdd_object *obj,
4981                                         struct mdd_object *tobj,
4982                                         struct mdd_xattrs *xattrs,
4983                                         struct md_layout_change *mlc,
4984                                         struct dt_allocation_hint *hint,
4985                                         struct thandle *handle)
4986 {
4987         struct mdd_thread_info *info = mdd_env_info(env);
4988         const struct lu_name *lname = mlc->mlc_name;
4989         struct lu_attr *la = &info->mdi_la_for_fix;
4990         struct lmv_user_md_v1 *lum = mlc->mlc_spec->u.sp_ea.eadata;
4991         struct linkea_data *ldata = &info->mdi_link_data;
4992         struct lmv_mds_md_v1 *lmv;
4993         __u32 count;
4994         int rc;
4995
4996         mlc->mlc_opc = MD_LAYOUT_DETACH;
4997         rc = mdo_declare_layout_change(env, obj, mlc, handle);
4998         if (rc)
4999                 return rc;
5000
5001         memset(ldata, 0, sizeof(*ldata));
5002         rc = mdd_linkea_prepare(env, obj, NULL, NULL, mdd_object_fid(pobj),
5003                                 lname, 1, 0, ldata);
5004         if (rc)
5005                 return rc;
5006
5007         count = lum->lum_stripe_count;
5008         lum->lum_stripe_count = 0;
5009         /* don't set default LMV since it will become a striped dir  */
5010         lum->lum_max_inherit = LMV_INHERIT_NONE;
5011         mdd_object_make_hint(env, pobj, tobj, mlc->mlc_attr, mlc->mlc_spec,
5012                              hint);
5013         rc = mdd_declare_create(env, mdo2mdd(&pobj->mod_obj), pobj, tobj,
5014                                 lname, mlc->mlc_attr, handle, mlc->mlc_spec,
5015                                 ldata, NULL, NULL, NULL, hint);
5016         if (rc)
5017                 return rc;
5018
5019         /* tobj mode will be used in lod_declare_xattr_set(), but it's not
5020          * created yet.
5021          */
5022         tobj->mod_obj.mo_lu.lo_header->loh_attr |= S_IFDIR;
5023
5024         lmv = (typeof(lmv))info->mdi_key;
5025         memset(lmv, 0, sizeof(*lmv));
5026         lmv->lmv_magic = cpu_to_le32(LMV_MAGIC_V1);
5027         lmv->lmv_stripe_count = cpu_to_le32(1);
5028         lmv->lmv_hash_type = cpu_to_le32(LMV_HASH_TYPE_DEFAULT);
5029         fid_le_to_cpu(&lmv->lmv_stripe_fids[0], mdd_object_fid(obj));
5030
5031         mlc->mlc_opc = MD_LAYOUT_ATTACH;
5032         mlc->mlc_buf.lb_buf = lmv;
5033         mlc->mlc_buf.lb_len = lmv_mds_md_size(1, LMV_MAGIC_V1);
5034         rc = mdo_declare_layout_change(env, tobj, mlc, handle);
5035         if (rc)
5036                 return rc;
5037
5038         rc = mdd_foreach_xattr(env, tobj, xattrs, handle,
5039                                mdo_declare_xattr_set);
5040         if (rc)
5041                 return rc;
5042
5043         lum->lum_stripe_count = count;
5044         mlc->mlc_opc = MD_LAYOUT_SPLIT;
5045         rc = mdo_declare_layout_change(env, tobj, mlc, handle);
5046         if (rc)
5047                 return rc;
5048
5049         rc = mdo_declare_index_delete(env, pobj, lname->ln_name, handle);
5050         if (rc)
5051                 return rc;
5052
5053         rc = mdo_declare_index_insert(env, pobj, mdd_object_fid(tobj),
5054                                       S_IFDIR, lname->ln_name, handle);
5055         if (rc)
5056                 return rc;
5057
5058         la->la_valid = LA_CTIME | LA_MTIME;
5059         rc = mdo_declare_attr_set(env, obj, la, handle);
5060         if (rc)
5061                 return rc;
5062
5063         rc = mdo_declare_attr_set(env, pobj, la, handle);
5064         if (rc)
5065                 return rc;
5066
5067         rc = mdd_declare_changelog_store(env, mdd, CL_MIGRATE, lname, NULL,
5068                                          handle);
5069         return rc;
5070 }
5071
5072 /**
5073  * plain directory split:
5074  * 1. create \a tobj as plain directory.
5075  * 2. append \a obj as first stripe of \a tobj.
5076  * 3. migrate xattrs from \a obj to \a tobj.
5077  * 4. split \a tobj to specific stripe count.
5078  */
5079 static int mdd_dir_split_plain(const struct lu_env *env,
5080                                 struct mdd_device *mdd,
5081                                 struct mdd_object *pobj,
5082                                 struct mdd_object *obj,
5083                                 struct mdd_object *tobj,
5084                                 struct mdd_xattrs *xattrs,
5085                                 struct md_layout_change *mlc,
5086                                 struct dt_allocation_hint *hint,
5087                                 struct thandle *handle)
5088 {
5089         struct mdd_thread_info *info = mdd_env_info(env);
5090         struct lu_attr *pattr = &info->mdi_pattr;
5091         struct lu_attr *la = &info->mdi_la_for_fix;
5092         const struct lu_name *lname = mlc->mlc_name;
5093         struct linkea_data *ldata = &info->mdi_link_data;
5094         int rc;
5095
5096         ENTRY;
5097
5098         /* copy linkea out and set on target later */
5099         rc = mdd_links_read(env, obj, ldata);
5100         if (rc)
5101                 RETURN(rc);
5102
5103         mlc->mlc_opc = MD_LAYOUT_DETACH;
5104         rc = mdo_layout_change(env, obj, mlc, handle);
5105         if (rc)
5106                 RETURN(rc);
5107
5108         /* don't set nlink from obj */
5109         mlc->mlc_attr->la_valid &= ~LA_NLINK;
5110
5111         rc = mdd_create_object(env, pobj, tobj, mlc->mlc_attr, mlc->mlc_spec,
5112                                NULL, NULL, NULL, hint, handle, false);
5113         if (rc)
5114                 RETURN(rc);
5115
5116         rc = mdd_foreach_xattr(env, tobj, xattrs, handle, mdo_xattr_set);
5117         if (rc)
5118                 RETURN(rc);
5119
5120         rc = mdd_links_write(env, tobj, ldata, handle);
5121         if (rc)
5122                 RETURN(rc);
5123
5124         rc = __mdd_index_delete(env, pobj, lname->ln_name, true, handle);
5125         if (rc)
5126                 RETURN(rc);
5127
5128         rc = __mdd_index_insert(env, pobj, mdd_object_fid(tobj), S_IFDIR,
5129                                 lname->ln_name, handle);
5130         if (rc)
5131                 RETURN(rc);
5132
5133         la->la_ctime = la->la_mtime = mlc->mlc_attr->la_mtime;
5134         la->la_valid = LA_CTIME | LA_MTIME;
5135
5136         mdd_write_lock(env, obj, DT_SRC_CHILD);
5137         rc = mdd_update_time(env, tobj, mlc->mlc_attr, la, handle);
5138         mdd_write_unlock(env, obj);
5139         if (rc)
5140                 RETURN(rc);
5141
5142         rc = mdd_la_get(env, pobj, pattr);
5143         if (rc)
5144                 RETURN(rc);
5145
5146         la->la_valid = LA_CTIME | LA_MTIME;
5147
5148         mdd_write_lock(env, pobj, DT_SRC_PARENT);
5149         rc = mdd_update_time(env, pobj, pattr, la, handle);
5150         mdd_write_unlock(env, pobj);
5151         if (rc)
5152                 RETURN(rc);
5153
5154         /* FID changes, record it as CL_MIGRATE */
5155         rc = mdd_changelog_ns_store(env, mdd, CL_MIGRATE, 0, tobj,
5156                                     pobj, pattr, mdd_object_fid(obj),
5157                                     pobj, pattr, lname, lname, handle);
5158         RETURN(rc);
5159 }
5160
5161 int mdd_dir_layout_split(const struct lu_env *env, struct md_object *o,
5162                          struct md_layout_change *mlc)
5163 {
5164         struct mdd_thread_info *info = mdd_env_info(env);
5165         struct mdd_device *mdd = mdo2mdd(o);
5166         struct mdd_object *obj = md2mdd_obj(o);
5167         struct mdd_object *pobj = md2mdd_obj(mlc->mlc_parent);
5168         struct mdd_object *tobj = md2mdd_obj(mlc->mlc_target);
5169         struct dt_allocation_hint *hint = &info->mdi_hint;
5170         bool is_plain = false;
5171         struct mdd_xattrs xattrs;
5172         struct thandle *handle;
5173         int rc;
5174
5175         ENTRY;
5176
5177         LASSERT(S_ISDIR(mdd_object_type(obj)));
5178
5179         rc = mdo_xattr_get(env, obj, &LU_BUF_NULL, XATTR_NAME_LMV);
5180         if (rc == -ENODATA)
5181                 is_plain = true;
5182         else if (rc < 0)
5183                 RETURN(rc);
5184
5185         mdd_xattrs_init(&xattrs);
5186         if (is_plain)
5187                 rc = mdd_xattrs_migrate_prep(env, &xattrs, obj, true, true);
5188
5189         handle = mdd_trans_create(env, mdd);
5190         if (IS_ERR(handle))
5191                 GOTO(out, rc = PTR_ERR(handle));
5192
5193         if (is_plain) {
5194                 rc = mdd_dir_declare_split_plain(env, mdd, pobj, obj, tobj,
5195                                                  &xattrs, mlc, hint, handle);
5196         } else {
5197                 mlc->mlc_opc = MD_LAYOUT_SPLIT;
5198                 rc = mdo_declare_layout_change(env, obj, mlc, handle);
5199                 if (rc)
5200                         GOTO(stop_trans, rc);
5201
5202                 rc = mdd_declare_changelog_store(env, mdd, CL_LAYOUT, NULL,
5203                                                  NULL, handle);
5204         }
5205         if (rc)
5206                 GOTO(stop_trans, rc);
5207
5208         rc = mdd_trans_start(env, mdd, handle);
5209         if (rc)
5210                 GOTO(stop_trans, rc);
5211
5212         if (is_plain) {
5213                 rc = mdd_dir_split_plain(env, mdd, pobj, obj, tobj, &xattrs,
5214                                          mlc, hint, handle);
5215         } else {
5216                 struct lu_buf *buf = &info->mdi_buf[0];
5217
5218                 buf->lb_buf = mlc->mlc_spec->u.sp_ea.eadata;
5219                 buf->lb_len = mlc->mlc_spec->u.sp_ea.eadatalen;
5220
5221                 mdd_write_lock(env, obj, DT_TGT_CHILD);
5222                 rc = mdo_xattr_set(env, obj, buf, XATTR_NAME_LMV,
5223                                    LU_XATTR_CREATE, handle);
5224                 mdd_write_unlock(env, obj);
5225                 if (rc)
5226                         GOTO(stop_trans, rc);
5227
5228                 rc = mdd_changelog_data_store_xattr(env, mdd, CL_LAYOUT, 0, obj,
5229                                                     XATTR_NAME_LMV, handle);
5230         }
5231         if (rc)
5232                 GOTO(stop_trans, rc);
5233
5234         EXIT;
5235
5236 stop_trans:
5237         rc = mdd_trans_stop(env, mdd, rc, handle);
5238 out:
5239         mdd_xattrs_fini(&xattrs);
5240
5241         return rc;
5242 }
5243
5244 const struct md_dir_operations mdd_dir_ops = {
5245         .mdo_is_subdir     = mdd_is_subdir,
5246         .mdo_lookup        = mdd_lookup,
5247         .mdo_create        = mdd_create,
5248         .mdo_rename        = mdd_rename,
5249         .mdo_link          = mdd_link,
5250         .mdo_unlink        = mdd_unlink,
5251         .mdo_create_data   = mdd_create_data,
5252         .mdo_migrate       = mdd_migrate,
5253 };