Whamcloud - gitweb
ed63745f9588e0dee076a0fc878655a6e0a0648f
[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  * Lustre is a trademark of Sun Microsystems, Inc.
31  *
32  * lustre/mdd/mdd_dir.c
33  *
34  * Lustre Metadata Server (mdd) routines
35  *
36  * Author: Wang Di <wangdi@intel.com>
37  */
38
39 #define DEBUG_SUBSYSTEM S_MDS
40
41 #include <obd_class.h>
42 #include <obd_support.h>
43 #include <lustre_mds.h>
44 #include <lustre_fid.h>
45
46 #include "mdd_internal.h"
47
48 static const char dot[] = ".";
49 static const char dotdot[] = "..";
50
51 static struct lu_name lname_dotdot = {
52         .ln_name        = (char *) dotdot,
53         .ln_namelen     = sizeof(dotdot) - 1,
54 };
55
56 static inline int
57 mdd_name_check(struct mdd_device *m, const struct lu_name *ln)
58 {
59         if (!lu_name_is_valid(ln))
60                 return -EINVAL;
61         else if (ln->ln_namelen > m->mdd_dt_conf.ddp_max_name_len)
62                 return -ENAMETOOLONG;
63         else
64                 return 0;
65 }
66
67 /* Get FID from name and parent */
68 static int
69 __mdd_lookup(const struct lu_env *env, struct md_object *pobj,
70              const struct lu_attr *pattr, const struct lu_name *lname,
71              struct lu_fid* fid, int mask)
72 {
73         const char *name                = lname->ln_name;
74         const struct dt_key *key        = (const struct dt_key *)name;
75         struct mdd_object *mdd_obj      = md2mdd_obj(pobj);
76         struct mdd_device *m            = mdo2mdd(pobj);
77         struct dt_object *dir           = mdd_object_child(mdd_obj);
78         int rc;
79         ENTRY;
80
81         if (unlikely(mdd_is_dead_obj(mdd_obj)))
82                 RETURN(-ESTALE);
83
84         if (!mdd_object_exists(mdd_obj))
85                 RETURN(-ESTALE);
86
87         if (mdd_object_remote(mdd_obj)) {
88                 CDEBUG(D_INFO, "%s: Object "DFID" locates on remote server\n",
89                        mdd2obd_dev(m)->obd_name, PFID(mdo2fid(mdd_obj)));
90         }
91
92         rc = mdd_permission_internal_locked(env, mdd_obj, pattr, mask,
93                                             MOR_TGT_PARENT);
94         if (rc)
95                 RETURN(rc);
96
97         if (likely(S_ISDIR(mdd_object_type(mdd_obj)) &&
98                    dt_try_as_dir(env, dir)))
99                 rc = dt_lookup(env, dir, (struct dt_rec *)fid, key);
100         else
101                 rc = -ENOTDIR;
102
103         RETURN(rc);
104 }
105
106 int mdd_lookup(const struct lu_env *env,
107                struct md_object *pobj, const struct lu_name *lname,
108                struct lu_fid *fid, struct md_op_spec *spec)
109 {
110         struct lu_attr *pattr = MDD_ENV_VAR(env, pattr);
111         int rc;
112         ENTRY;
113
114         rc = mdd_la_get(env, md2mdd_obj(pobj), pattr);
115         if (rc != 0)
116                 RETURN(rc);
117
118         rc = __mdd_lookup(env, pobj, pattr, lname, fid,
119                           (spec != NULL && spec->sp_permitted) ? 0 : MAY_EXEC);
120         RETURN(rc);
121 }
122
123 /** Read the link EA into a temp buffer.
124  * Uses the mdd_thread_info::mti_big_buf since it is generally large.
125  * A pointer to the buffer is stored in \a ldata::ld_buf.
126  *
127  * \retval 0 or error
128  */
129 static int __mdd_links_read(const struct lu_env *env,
130                             struct mdd_object *mdd_obj,
131                             struct linkea_data *ldata)
132 {
133         int rc;
134
135         if (!mdd_object_exists(mdd_obj))
136                 return -ENODATA;
137
138         /* First try a small buf */
139         LASSERT(env != NULL);
140         ldata->ld_buf = lu_buf_check_and_alloc(&mdd_env_info(env)->mti_link_buf,
141                                                PAGE_SIZE);
142         if (ldata->ld_buf->lb_buf == NULL)
143                 return -ENOMEM;
144
145         rc = mdo_xattr_get(env, mdd_obj, ldata->ld_buf, XATTR_NAME_LINK);
146         if (rc == -ERANGE) {
147                 /* Buf was too small, figure out what we need. */
148                 lu_buf_free(ldata->ld_buf);
149                 rc = mdo_xattr_get(env, mdd_obj, ldata->ld_buf,
150                                    XATTR_NAME_LINK);
151                 if (rc < 0)
152                         return rc;
153                 ldata->ld_buf = lu_buf_check_and_alloc(ldata->ld_buf, rc);
154                 if (ldata->ld_buf->lb_buf == NULL)
155                         return -ENOMEM;
156                 rc = mdo_xattr_get(env, mdd_obj, ldata->ld_buf,
157                                   XATTR_NAME_LINK);
158         }
159         if (rc < 0) {
160                 lu_buf_free(ldata->ld_buf);
161                 ldata->ld_buf = NULL;
162                 return rc;
163         }
164
165         return linkea_init(ldata);
166 }
167
168 static int mdd_links_read(const struct lu_env *env,
169                           struct mdd_object *mdd_obj,
170                           struct linkea_data *ldata)
171 {
172         int rc;
173
174         rc = __mdd_links_read(env, mdd_obj, ldata);
175         if (!rc)
176                 rc = linkea_init(ldata);
177
178         return rc;
179 }
180
181 static int mdd_links_read_with_rec(const struct lu_env *env,
182                                    struct mdd_object *mdd_obj,
183                                    struct linkea_data *ldata)
184 {
185         int rc;
186
187         rc = __mdd_links_read(env, mdd_obj, ldata);
188         if (!rc)
189                 rc = linkea_init_with_rec(ldata);
190
191         return rc;
192 }
193
194 /**
195  * Get parent FID of the directory
196  *
197  * Read parent FID from linkEA, if that fails, then do lookup
198  * dotdot to get the parent FID.
199  *
200  * \param[in] env       execution environment
201  * \param[in] obj       object from which to find the parent FID
202  * \param[in] attr      attribute of the object
203  * \param[out] fid      fid to get the parent FID
204  *
205  * \retval              0 if getting the parent FID succeeds.
206  * \retval              negative errno if getting the parent FID fails.
207  **/
208 static inline int mdd_parent_fid(const struct lu_env *env,
209                                  struct mdd_object *obj,
210                                  const struct lu_attr *attr,
211                                  struct lu_fid *fid)
212 {
213         struct mdd_thread_info  *info = mdd_env_info(env);
214         struct linkea_data      ldata = { NULL };
215         struct lu_buf           *buf = &info->mti_link_buf;
216         struct lu_name          lname;
217         int                     rc = 0;
218
219         ENTRY;
220
221         LASSERT(S_ISDIR(mdd_object_type(obj)));
222
223         buf = lu_buf_check_and_alloc(buf, PATH_MAX);
224         if (buf->lb_buf == NULL)
225                 GOTO(lookup, rc = 0);
226
227         ldata.ld_buf = buf;
228         rc = mdd_links_read_with_rec(env, obj, &ldata);
229         if (rc != 0)
230                 GOTO(lookup, rc);
231
232         LASSERT(ldata.ld_leh != NULL);
233         /* Directory should only have 1 parent */
234         if (ldata.ld_leh->leh_reccount > 1)
235                 GOTO(lookup, rc);
236
237         ldata.ld_lee = (struct link_ea_entry *)(ldata.ld_leh + 1);
238
239         linkea_entry_unpack(ldata.ld_lee, &ldata.ld_reclen, &lname, fid);
240         if (likely(fid_is_sane(fid)))
241                 RETURN(0);
242 lookup:
243         rc =  __mdd_lookup(env, &obj->mod_obj, attr, &lname_dotdot, fid, 0);
244         RETURN(rc);
245 }
246
247 /*
248  * For root fid use special function, which does not compare version component
249  * of fid. Version component is different for root fids on all MDTs.
250  */
251 int mdd_is_root(struct mdd_device *mdd, const struct lu_fid *fid)
252 {
253         return fid_seq(&mdd->mdd_root_fid) == fid_seq(fid) &&
254                 fid_oid(&mdd->mdd_root_fid) == fid_oid(fid);
255 }
256
257 /*
258  * return 1: if lf is the fid of the ancestor of p1;
259  * return 0: if not;
260  *
261  * return -EREMOTE: if remote object is found, in this
262  * case fid of remote object is saved to @pf;
263  *
264  * otherwise: values < 0, errors.
265  */
266 static int mdd_is_parent(const struct lu_env *env,
267                         struct mdd_device *mdd,
268                         struct mdd_object *p1,
269                         const struct lu_attr *attr,
270                         const struct lu_fid *lf,
271                         struct lu_fid *pf)
272 {
273         struct mdd_object *parent = NULL;
274         struct lu_fid *pfid;
275         int rc;
276         ENTRY;
277
278         LASSERT(!lu_fid_eq(mdo2fid(p1), lf));
279         pfid = &mdd_env_info(env)->mti_fid;
280
281         /* Check for root first. */
282         if (mdd_is_root(mdd, mdo2fid(p1)))
283                 RETURN(0);
284
285         for(;;) {
286                 /* this is done recursively */
287                 rc = mdd_parent_fid(env, p1, attr, pfid);
288                 if (rc)
289                         GOTO(out, rc);
290                 if (mdd_is_root(mdd, pfid))
291                         GOTO(out, rc = 0);
292                 if (lu_fid_eq(pfid, &mdd->mdd_local_root_fid))
293                         GOTO(out, rc = 0);
294                 if (lu_fid_eq(pfid, lf))
295                         GOTO(out, rc = 1);
296                 if (parent != NULL)
297                         mdd_object_put(env, parent);
298
299                 parent = mdd_object_find(env, mdd, pfid);
300                 if (IS_ERR(parent))
301                         GOTO(out, rc = PTR_ERR(parent));
302
303                 if (!mdd_object_exists(parent))
304                         GOTO(out, rc = -EINVAL);
305
306                 p1 = parent;
307         }
308         EXIT;
309 out:
310         if (parent && !IS_ERR(parent))
311                 mdd_object_put(env, parent);
312         return rc;
313 }
314
315 /*
316  * No permission check is needed.
317  *
318  * returns 1: if fid is ancestor of @mo;
319  * returns 0: if fid is not an ancestor of @mo;
320  *
321  * returns EREMOTE if remote object is found, fid of remote object is saved to
322  * @fid;
323  *
324  * returns < 0: if error
325  */
326 int mdd_is_subdir(const struct lu_env *env, struct md_object *mo,
327                   const struct lu_fid *fid, struct lu_fid *sfid)
328 {
329         struct mdd_device *mdd = mdo2mdd(mo);
330         struct lu_attr *attr = MDD_ENV_VAR(env, cattr);
331         int rc;
332         ENTRY;
333
334         if (!S_ISDIR(mdd_object_type(md2mdd_obj(mo))))
335                 RETURN(0);
336
337         rc = mdd_la_get(env, md2mdd_obj(mo), attr);
338         if (rc != 0)
339                 RETURN(rc);
340
341         rc = mdd_is_parent(env, mdd, md2mdd_obj(mo), attr, fid, sfid);
342         if (rc == 0) {
343                 /* found root */
344                 fid_zero(sfid);
345         } else if (rc == 1) {
346                 /* found @fid is parent */
347                 *sfid = *fid;
348                 rc = 0;
349         }
350         RETURN(rc);
351 }
352
353 /*
354  * Check that @dir contains no entries except (possibly) dot and dotdot.
355  *
356  * Returns:
357  *
358  *             0        empty
359  *      -ENOTDIR        not a directory object
360  *    -ENOTEMPTY        not empty
361  *           -ve        other error
362  *
363  */
364 static int mdd_dir_is_empty(const struct lu_env *env,
365                             struct mdd_object *dir)
366 {
367         struct dt_it     *it;
368         struct dt_object *obj;
369         const struct dt_it_ops *iops;
370         int result;
371         ENTRY;
372
373         obj = mdd_object_child(dir);
374         if (!dt_try_as_dir(env, obj))
375                 RETURN(-ENOTDIR);
376
377         iops = &obj->do_index_ops->dio_it;
378         it = iops->init(env, obj, LUDA_64BITHASH);
379         if (!IS_ERR(it)) {
380                 result = iops->get(env, it, (const struct dt_key *)"");
381                 if (result > 0) {
382                         int i;
383                         for (result = 0, i = 0; result == 0 && i < 3; ++i)
384                                 result = iops->next(env, it);
385                         if (result == 0)
386                                 result = -ENOTEMPTY;
387                         else if (result == 1)
388                                 result = 0;
389                 } else if (result == 0)
390                         /*
391                          * Huh? Index contains no zero key?
392                          */
393                         result = -EIO;
394
395                 iops->put(env, it);
396                 iops->fini(env, it);
397         } else
398                 result = PTR_ERR(it);
399         RETURN(result);
400 }
401
402 /**
403  * Determine if the target object can be hard linked, and right now it only
404  * checks if the link count reach the maximum limit. Note: for ldiskfs, the
405  * directory nlink count might exceed the maximum link count(see
406  * osd_object_ref_add), so it only check nlink for non-directories.
407  *
408  * \param[in] env       thread environment
409  * \param[in] obj       object being linked to
410  * \param[in] la        attributes of \a obj
411  *
412  * \retval              0 if \a obj can be hard linked
413  * \retval              negative error if \a obj is a directory or has too
414  *                      many links
415  */
416 static int __mdd_may_link(const struct lu_env *env, struct mdd_object *obj,
417                           const struct lu_attr *la)
418 {
419         struct mdd_device *m = mdd_obj2mdd_dev(obj);
420         ENTRY;
421
422         LASSERT(la != NULL);
423
424         /* Subdir count limitation can be broken through
425          * (see osd_object_ref_add), so only check non-directory here. */
426         if (!S_ISDIR(la->la_mode) &&
427             la->la_nlink >= m->mdd_dt_conf.ddp_max_nlink)
428                 RETURN(-EMLINK);
429
430         RETURN(0);
431 }
432
433 /**
434  * Check whether it may create the cobj under the pobj.
435  *
436  * \param[in] env       execution environment
437  * \param[in] pobj      the parent directory
438  * \param[in] pattr     the attribute of the parent directory
439  * \param[in] cobj      the child to be created
440  * \param[in] check_perm        if check WRITE|EXEC permission for parent
441  *
442  * \retval              = 0 create the child under this dir is allowed
443  * \retval              negative errno create the child under this dir is
444  *                      not allowed
445  */
446 int mdd_may_create(const struct lu_env *env, struct mdd_object *pobj,
447                    const struct lu_attr *pattr, struct mdd_object *cobj,
448                    bool check_perm)
449 {
450         int rc = 0;
451         ENTRY;
452
453         if (cobj && mdd_object_exists(cobj))
454                 RETURN(-EEXIST);
455
456         if (mdd_is_dead_obj(pobj))
457                 RETURN(-ENOENT);
458
459         if (check_perm)
460                 rc = mdd_permission_internal_locked(env, pobj, pattr,
461                                                     MAY_WRITE | MAY_EXEC,
462                                                     MOR_TGT_PARENT);
463         RETURN(rc);
464 }
465
466 /*
467  * Check whether can unlink from the pobj in the case of "cobj == NULL".
468  */
469 int mdd_may_unlink(const struct lu_env *env, struct mdd_object *pobj,
470                    const struct lu_attr *pattr, const struct lu_attr *attr)
471 {
472         int rc;
473         ENTRY;
474
475         if (mdd_is_dead_obj(pobj))
476                 RETURN(-ENOENT);
477
478         if (attr->la_flags & (LUSTRE_APPEND_FL | LUSTRE_IMMUTABLE_FL))
479                 RETURN(-EPERM);
480
481         rc = mdd_permission_internal_locked(env, pobj, pattr,
482                                             MAY_WRITE | MAY_EXEC,
483                                             MOR_TGT_PARENT);
484         if (rc != 0)
485                 RETURN(rc);
486
487         if (pattr->la_flags & LUSTRE_APPEND_FL)
488                 RETURN(-EPERM);
489
490         RETURN(rc);
491 }
492
493 /*
494  * pobj == NULL is remote ops case, under such case, pobj's
495  * VTX feature has been checked already, no need check again.
496  */
497 static inline int mdd_is_sticky(const struct lu_env *env,
498                                 struct mdd_object *pobj,
499                                 const struct lu_attr *pattr,
500                                 struct mdd_object *cobj,
501                                 const struct lu_attr *cattr)
502 {
503         struct lu_ucred *uc = lu_ucred_assert(env);
504
505         if (pobj != NULL) {
506                 LASSERT(pattr != NULL);
507                 if (!(pattr->la_mode & S_ISVTX) ||
508                     (pattr->la_uid == uc->uc_fsuid))
509                         return 0;
510         }
511
512         LASSERT(cattr != NULL);
513         if (cattr->la_uid == uc->uc_fsuid)
514                 return 0;
515
516         return !md_capable(uc, CFS_CAP_FOWNER);
517 }
518
519 static int mdd_may_delete_entry(const struct lu_env *env,
520                                 struct mdd_object *pobj,
521                                 const struct lu_attr *pattr,
522                                 int check_perm)
523 {
524         ENTRY;
525
526         LASSERT(pobj != NULL);
527         if (!mdd_object_exists(pobj))
528                 RETURN(-ENOENT);
529
530         if (mdd_is_dead_obj(pobj))
531                 RETURN(-ENOENT);
532
533         if (check_perm) {
534                 int rc;
535                 rc = mdd_permission_internal_locked(env, pobj, pattr,
536                                             MAY_WRITE | MAY_EXEC,
537                                             MOR_TGT_PARENT);
538                 if (rc)
539                         RETURN(rc);
540         }
541
542         if (pattr->la_flags & LUSTRE_APPEND_FL)
543                 RETURN(-EPERM);
544
545         RETURN(0);
546 }
547
548 /*
549  * Check whether it may delete the cobj from the pobj.
550  * pobj maybe NULL
551  */
552 int mdd_may_delete(const struct lu_env *env, struct mdd_object *tpobj,
553                    const struct lu_attr *tpattr, struct mdd_object *tobj,
554                    const struct lu_attr *tattr, const struct lu_attr *cattr,
555                    int check_perm, int check_empty)
556 {
557         int rc = 0;
558         ENTRY;
559
560         if (tpobj) {
561                 LASSERT(tpattr != NULL);
562                 rc = mdd_may_delete_entry(env, tpobj, tpattr, check_perm);
563                 if (rc != 0)
564                         RETURN(rc);
565         }
566
567         if (tobj == NULL)
568                 RETURN(0);
569
570         if (!mdd_object_exists(tobj))
571                 RETURN(-ENOENT);
572
573         if (mdd_is_dead_obj(tobj))
574                 RETURN(-ESTALE);
575
576         if (mdd_is_sticky(env, tpobj, tpattr, tobj, tattr))
577                 RETURN(-EPERM);
578
579         if (tattr->la_flags & (LUSTRE_APPEND_FL | LUSTRE_IMMUTABLE_FL))
580                 RETURN(-EPERM);
581
582         /* additional check the rename case */
583         if (cattr) {
584                 if (S_ISDIR(cattr->la_mode)) {
585                         struct mdd_device *mdd = mdo2mdd(&tobj->mod_obj);
586
587                         if (!S_ISDIR(tattr->la_mode))
588                                 RETURN(-ENOTDIR);
589
590                         if (lu_fid_eq(mdo2fid(tobj), &mdd->mdd_root_fid))
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(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))
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,
674                                    struct thandle *handle)
675 {
676         struct dt_object *next = mdd_object_child(pobj);
677         int               rc;
678         ENTRY;
679
680         if (dt_try_as_dir(env, next)) {
681                 struct dt_insert_rec    *rec = &mdd_env_info(env)->mti_dt_rec;
682                 struct lu_ucred         *uc  = lu_ucred_check(env);
683                 int                      ignore_quota;
684
685                 rec->rec_fid = lf;
686                 rec->rec_type = type;
687                 ignore_quota = uc ? uc->uc_cap & CFS_CAP_SYS_RESOURCE_MASK : 1;
688                 rc = dt_insert(env, next, (const struct dt_rec *)rec,
689                                (const struct dt_key *)name, handle,
690                                ignore_quota);
691         } else {
692                 rc = -ENOTDIR;
693         }
694         RETURN(rc);
695 }
696
697 /* insert named index, add reference if isdir */
698 static int __mdd_index_insert(const struct lu_env *env, struct mdd_object *pobj,
699                               const struct lu_fid *lf, __u32 type,
700                               const char *name, struct thandle *handle)
701 {
702         int rc;
703         ENTRY;
704
705         rc = __mdd_index_insert_only(env, pobj, lf, type, name, handle);
706         if (rc == 0 && S_ISDIR(type)) {
707                 mdd_write_lock(env, pobj, MOR_TGT_PARENT);
708                 mdo_ref_add(env, pobj, handle);
709                 mdd_write_unlock(env, pobj);
710         }
711
712         RETURN(rc);
713 }
714
715 /* delete named index, drop reference if isdir */
716 static int __mdd_index_delete(const struct lu_env *env, struct mdd_object *pobj,
717                               const char *name, int is_dir,
718                               struct thandle *handle)
719 {
720         int               rc;
721         ENTRY;
722
723         rc = __mdd_index_delete_only(env, pobj, name, handle);
724         if (rc == 0 && is_dir) {
725                 mdd_write_lock(env, pobj, MOR_TGT_PARENT);
726                 mdo_ref_del(env, pobj, handle);
727                 mdd_write_unlock(env, pobj);
728         }
729
730         RETURN(rc);
731 }
732
733 static int mdd_llog_record_calc_size(const struct lu_env *env,
734                                      const struct lu_name *tname,
735                                      const struct lu_name *sname)
736 {
737         const struct lu_ucred   *uc = lu_ucred(env);
738         enum changelog_rec_flags crf = CLF_EXTRA_FLAGS;
739         enum changelog_rec_extra_flags crfe = CLFE_UIDGID;
740
741         if (sname != NULL)
742                 crf |= CLF_RENAME;
743
744         if (uc != NULL && uc->uc_jobid[0] != '\0')
745                 crf |= CLF_JOBID;
746
747         return llog_data_len(LLOG_CHANGELOG_HDR_SZ +
748                              changelog_rec_offset(crf, crfe) +
749                              (tname != NULL ? tname->ln_namelen : 0) +
750                              (sname != NULL ? 1 + sname->ln_namelen : 0));
751 }
752
753 int mdd_declare_changelog_store(const struct lu_env *env,
754                                 struct mdd_device *mdd,
755                                 const struct lu_name *tname,
756                                 const struct lu_name *sname,
757                                 struct thandle *handle)
758 {
759         struct obd_device               *obd = mdd2obd_dev(mdd);
760         struct llog_ctxt                *ctxt;
761         struct llog_changelog_rec       *rec;
762         struct lu_buf                   *buf;
763         struct thandle                  *llog_th;
764         int                              reclen;
765         int                              rc;
766
767         /* Not recording */
768         if (!(mdd->mdd_cl.mc_flags & CLM_ON))
769                 return 0;
770
771         reclen = mdd_llog_record_calc_size(env, tname, sname);
772         buf = lu_buf_check_and_alloc(&mdd_env_info(env)->mti_big_buf, reclen);
773         if (buf->lb_buf == NULL)
774                 return -ENOMEM;
775
776         rec = buf->lb_buf;
777         rec->cr_hdr.lrh_len = reclen;
778         rec->cr_hdr.lrh_type = CHANGELOG_REC;
779
780         ctxt = llog_get_context(obd, LLOG_CHANGELOG_ORIG_CTXT);
781         if (ctxt == NULL)
782                 return -ENXIO;
783
784         llog_th = thandle_get_sub(env, handle, ctxt->loc_handle->lgh_obj);
785         if (IS_ERR(llog_th))
786                 GOTO(out_put, rc = PTR_ERR(llog_th));
787
788         rc = llog_declare_add(env, ctxt->loc_handle, &rec->cr_hdr, llog_th);
789
790 out_put:
791         llog_ctxt_put(ctxt);
792
793         return rc;
794 }
795
796 struct mdd_changelog_gc {
797         struct mdd_device *mcgc_mdd;
798         bool mcgc_found;
799         __u32 mcgc_maxtime;
800         __u64 mcgc_maxindexes;
801         __u32 mcgc_id;
802 };
803
804 /* return first registered ChangeLog user idle since too long
805  * use ChangeLog's user plain LLOG mtime for this */
806 static int mdd_changelog_gc_cb(const struct lu_env *env,
807                                struct llog_handle *llh,
808                                struct llog_rec_hdr *hdr, void *data)
809 {
810         struct llog_changelog_user_rec  *rec;
811         struct mdd_changelog_gc *mcgc = (struct mdd_changelog_gc *)data;
812         struct mdd_device *mdd = mcgc->mcgc_mdd;
813         ENTRY;
814
815         if ((llh->lgh_hdr->llh_flags & LLOG_F_IS_PLAIN) == 0)
816                 RETURN(-ENXIO);
817
818         rec = container_of(hdr, struct llog_changelog_user_rec,
819                            cur_hdr);
820
821         /* find oldest idle user, based on last record update/cancel time (new
822          * behavior), or for old user records, last record index vs current
823          * ChangeLog index. Late users with old record format will be treated
824          * first as we assume they could be idle since longer
825          */
826         if (rec->cur_time != 0) {
827                 __u32 time_now = (__u32)get_seconds();
828                 __u32 time_out = rec->cur_time +
829                                  mdd->mdd_changelog_max_idle_time;
830                 __u32 idle_time = time_now - rec->cur_time;
831
832                 /* treat oldest idle user first, and if no old format user
833                  * has been already selected
834                  */
835                 if (time_after32(time_now, time_out) &&
836                     idle_time > mcgc->mcgc_maxtime &&
837                     mcgc->mcgc_maxindexes == 0) {
838                         mcgc->mcgc_maxtime = idle_time;
839                         mcgc->mcgc_id = rec->cur_id;
840                         mcgc->mcgc_found = true;
841                 }
842         } else {
843                 /* old user record with no idle time stamp, so use empirical
844                  * method based on its current index/position
845                  */
846                 __u64 idle_indexes;
847
848                 idle_indexes = mdd->mdd_cl.mc_index - rec->cur_endrec;
849
850                 /* treat user with the oldest/smallest current index first */
851                 if (idle_indexes >= mdd->mdd_changelog_max_idle_indexes &&
852                     idle_indexes > mcgc->mcgc_maxindexes) {
853                         mcgc->mcgc_maxindexes = idle_indexes;
854                         mcgc->mcgc_id = rec->cur_id;
855                         mcgc->mcgc_found = true;
856                 }
857
858         }
859         RETURN(0);
860 }
861
862 /* recover space from long-term inactive ChangeLog users */
863 static int mdd_chlg_garbage_collect(void *data)
864 {
865         struct mdd_device *mdd = (struct mdd_device *)data;
866         struct lu_env             *env = NULL;
867         int                        rc;
868         struct llog_ctxt *ctxt;
869         struct mdd_changelog_gc mcgc = {
870                 .mcgc_mdd = mdd,
871                 .mcgc_found = false,
872                 .mcgc_maxtime = 0,
873                 .mcgc_maxindexes = 0,
874         };
875         ENTRY;
876
877         CDEBUG(D_HA, "%s: ChangeLog garbage collect thread start\n",
878                mdd2obd_dev(mdd)->obd_name);
879
880         OBD_ALLOC_PTR(env);
881         if (env == NULL)
882                 GOTO(out, rc = -ENOMEM);
883
884         rc = lu_env_init(env, LCT_MD_THREAD);
885         if (rc)
886                 GOTO(out, rc);
887
888         for (;;) {
889                 ctxt = llog_get_context(mdd2obd_dev(mdd),
890                                         LLOG_CHANGELOG_USER_ORIG_CTXT);
891                 if (ctxt == NULL ||
892                     (ctxt->loc_handle->lgh_hdr->llh_flags & LLOG_F_IS_CAT) == 0)
893                         GOTO(out_env, rc = -ENXIO);
894
895                 rc = llog_cat_process(env, ctxt->loc_handle,
896                                       mdd_changelog_gc_cb, &mcgc, 0, 0);
897                 if (rc != 0 || mcgc.mcgc_found == false)
898                         break;
899                 llog_ctxt_put(ctxt);
900
901                 CWARN("%s: Force deregister of ChangeLog user cl%d idle more "
902                       "than %us\n", mdd2obd_dev(mdd)->obd_name, mcgc.mcgc_id,
903                       mcgc.mcgc_maxtime);
904
905                 mdd_changelog_user_purge(env, mdd, mcgc.mcgc_id);
906
907                 /* try again to search for another candidate */
908                 mcgc.mcgc_found = false;
909                 mcgc.mcgc_maxtime = 0;
910                 mcgc.mcgc_maxindexes = 0;
911         }
912
913 out_env:
914         if (ctxt != NULL)
915                 llog_ctxt_put(ctxt);
916
917         lu_env_fini(env);
918         GOTO(out, rc);
919 out:
920         if (env)
921                 OBD_FREE_PTR(env);
922         mdd->mdd_cl.mc_gc_task = NULL;
923         return rc;
924 }
925
926 /** Add a changelog entry \a rec to the changelog llog
927  * \param mdd
928  * \param rec
929  * \param handle - currently ignored since llogs start their own transaction;
930  *              this will hopefully be fixed in llog rewrite
931  * \retval 0 ok
932  */
933 int mdd_changelog_store(const struct lu_env *env, struct mdd_device *mdd,
934                         struct llog_changelog_rec *rec, struct thandle *th)
935 {
936         struct obd_device       *obd = mdd2obd_dev(mdd);
937         struct llog_ctxt        *ctxt;
938         struct thandle          *llog_th;
939         int                      rc;
940         bool                     run_gc_task;
941
942         rec->cr_hdr.lrh_len = llog_data_len(sizeof(*rec) +
943                                             changelog_rec_varsize(&rec->cr));
944
945         /* llog_lvfs_write_rec sets the llog tail len */
946         rec->cr_hdr.lrh_type = CHANGELOG_REC;
947         rec->cr.cr_time = cl_time();
948
949         spin_lock(&mdd->mdd_cl.mc_lock);
950         /* NB: I suppose it's possible llog_add adds out of order wrt cr_index,
951          * but as long as the MDD transactions are ordered correctly for e.g.
952          * rename conflicts, I don't think this should matter. */
953         rec->cr.cr_index = ++mdd->mdd_cl.mc_index;
954         spin_unlock(&mdd->mdd_cl.mc_lock);
955
956         ctxt = llog_get_context(obd, LLOG_CHANGELOG_ORIG_CTXT);
957         if (ctxt == NULL)
958                 return -ENXIO;
959
960         llog_th = thandle_get_sub(env, th, ctxt->loc_handle->lgh_obj);
961         if (IS_ERR(llog_th))
962                 GOTO(out_put, rc = PTR_ERR(llog_th));
963
964         /* nested journal transaction */
965         rc = llog_add(env, ctxt->loc_handle, &rec->cr_hdr, NULL, llog_th);
966
967         /* time to recover some space ?? */
968         spin_lock(&mdd->mdd_cl.mc_lock);
969         if (unlikely(mdd->mdd_changelog_gc && (ktime_get_real_seconds() -
970             mdd->mdd_cl.mc_gc_time > mdd->mdd_changelog_min_gc_interval) &&
971             mdd->mdd_cl.mc_gc_task == NULL &&
972             llog_cat_free_space(ctxt->loc_handle) <=
973                                 mdd->mdd_changelog_min_free_cat_entries)) {
974                 CWARN("%s: low on changelog_catalog free entries, starting "
975                       "ChangeLog garbage collection thread\n", obd->obd_name);
976
977                 /* indicate further kthread run will occur outside right after
978                  * critical section
979                  */
980                 mdd->mdd_cl.mc_gc_task = (struct task_struct *)(-1);
981                 run_gc_task = true;
982         }
983         spin_unlock(&mdd->mdd_cl.mc_lock);
984         if (run_gc_task) {
985                 struct task_struct *gc_task;
986
987                 gc_task = kthread_run(mdd_chlg_garbage_collect, mdd,
988                                       "chlg_gc_thread");
989                 if (IS_ERR(gc_task)) {
990                         CERROR("%s: cannot start ChangeLog garbage collection "
991                                "thread: rc = %ld\n", obd->obd_name,
992                                PTR_ERR(gc_task));
993                         mdd->mdd_cl.mc_gc_task = NULL;
994                 } else {
995                         CDEBUG(D_HA, "%s: ChangeLog garbage collection thread "
996                                "has started with Pid %d\n", obd->obd_name,
997                                gc_task->pid);
998                         mdd->mdd_cl.mc_gc_task = gc_task;
999                         mdd->mdd_cl.mc_gc_time = ktime_get_real_seconds();
1000                 }
1001         }
1002 out_put:
1003         llog_ctxt_put(ctxt);
1004         if (rc > 0)
1005                 rc = 0;
1006         return rc;
1007 }
1008
1009 static void mdd_changelog_rec_ext_rename(struct changelog_rec *rec,
1010                                          const struct lu_fid *sfid,
1011                                          const struct lu_fid *spfid,
1012                                          const struct lu_name *sname)
1013 {
1014         struct changelog_ext_rename *rnm = changelog_rec_rename(rec);
1015         size_t extsize = sname->ln_namelen + 1;
1016
1017         LASSERT(sfid != NULL);
1018         LASSERT(spfid != NULL);
1019         LASSERT(sname != NULL);
1020
1021         rnm->cr_sfid = *sfid;
1022         rnm->cr_spfid = *spfid;
1023
1024         changelog_rec_name(rec)[rec->cr_namelen] = '\0';
1025         strlcpy(changelog_rec_sname(rec), sname->ln_name, extsize);
1026         rec->cr_namelen += extsize;
1027 }
1028
1029 void mdd_changelog_rec_ext_jobid(struct changelog_rec *rec, const char *jobid)
1030 {
1031         struct changelog_ext_jobid *jid = changelog_rec_jobid(rec);
1032
1033         if (jobid == NULL || jobid[0] == '\0')
1034                 return;
1035
1036         strlcpy(jid->cr_jobid, jobid, sizeof(jid->cr_jobid));
1037 }
1038
1039 void mdd_changelog_rec_ext_extra_flags(struct changelog_rec *rec, __u64 eflags)
1040 {
1041         struct changelog_ext_extra_flags *ef = changelog_rec_extra_flags(rec);
1042
1043         ef->cr_extra_flags = eflags;
1044 }
1045
1046 void mdd_changelog_rec_extra_uidgid(struct changelog_rec *rec,
1047                                     __u64 uid, __u64 gid)
1048 {
1049         struct changelog_ext_uidgid *uidgid = changelog_rec_uidgid(rec);
1050
1051         uidgid->cr_uid = uid;
1052         uidgid->cr_gid = gid;
1053 }
1054
1055 /** Store a namespace change changelog record
1056  * If this fails, we must fail the whole transaction; we don't
1057  * want the change to commit without the log entry.
1058  * \param target - mdd_object of change
1059  * \param tpfid - target parent dir/object fid
1060  * \param sfid - source object fid
1061  * \param spfid - source parent fid
1062  * \param tname - target name string
1063  * \param sname - source name string
1064  * \param handle - transaction handle
1065  */
1066 int mdd_changelog_ns_store(const struct lu_env *env,
1067                            struct mdd_device *mdd,
1068                            enum changelog_rec_type type,
1069                            enum changelog_rec_flags crf,
1070                            struct mdd_object *target,
1071                            const struct lu_fid *tpfid,
1072                            const struct lu_fid *sfid,
1073                            const struct lu_fid *spfid,
1074                            const struct lu_name *tname,
1075                            const struct lu_name *sname,
1076                            struct thandle *handle)
1077 {
1078         const struct lu_ucred           *uc = lu_ucred(env);
1079         struct llog_changelog_rec       *rec;
1080         struct lu_buf                   *buf;
1081         int                              reclen;
1082         __u64                            xflags = CLFE_INVALID;
1083         int                              rc;
1084         ENTRY;
1085
1086         /* Not recording */
1087         if (!(mdd->mdd_cl.mc_flags & CLM_ON))
1088                 RETURN(0);
1089
1090         if ((mdd->mdd_cl.mc_mask & (1 << type)) == 0)
1091                 RETURN(0);
1092
1093         LASSERT(tpfid != NULL);
1094         LASSERT(tname != NULL);
1095         LASSERT(handle != NULL);
1096
1097         reclen = mdd_llog_record_calc_size(env, tname, sname);
1098         buf = lu_buf_check_and_alloc(&mdd_env_info(env)->mti_big_buf, reclen);
1099         if (buf->lb_buf == NULL)
1100                 RETURN(-ENOMEM);
1101         rec = buf->lb_buf;
1102
1103         crf &= CLF_FLAGMASK;
1104         crf |= CLF_EXTRA_FLAGS;
1105
1106         if (uc != NULL && uc->uc_jobid[0] != '\0')
1107                 crf |= CLF_JOBID;
1108
1109         if (sname != NULL)
1110                 crf |= CLF_RENAME;
1111         else
1112                 crf |= CLF_VERSION;
1113
1114         xflags |= CLFE_UIDGID;
1115
1116         rec->cr.cr_flags = crf;
1117
1118         if (crf & CLF_EXTRA_FLAGS) {
1119                 mdd_changelog_rec_ext_extra_flags(&rec->cr, xflags);
1120                 if (xflags & CLFE_UIDGID)
1121                         mdd_changelog_rec_extra_uidgid(&rec->cr,
1122                                                        uc->uc_uid, uc->uc_gid);
1123         }
1124
1125         rec->cr.cr_type = (__u32)type;
1126         rec->cr.cr_pfid = *tpfid;
1127         rec->cr.cr_namelen = tname->ln_namelen;
1128         memcpy(changelog_rec_name(&rec->cr), tname->ln_name, tname->ln_namelen);
1129
1130         if (crf & CLF_RENAME)
1131                 mdd_changelog_rec_ext_rename(&rec->cr, sfid, spfid, sname);
1132
1133         if (crf & CLF_JOBID)
1134                 mdd_changelog_rec_ext_jobid(&rec->cr, uc->uc_jobid);
1135
1136         if (likely(target != NULL)) {
1137                 rec->cr.cr_tfid = *mdo2fid(target);
1138                 target->mod_cltime = ktime_get();
1139         } else {
1140                 fid_zero(&rec->cr.cr_tfid);
1141         }
1142
1143         rc = mdd_changelog_store(env, mdd, rec, handle);
1144         if (rc < 0) {
1145                 CERROR("%s: cannot store changelog record: type = %d, "
1146                        "name = '%s', t = "DFID", p = "DFID": rc = %d\n",
1147                        mdd2obd_dev(mdd)->obd_name, type, tname->ln_name,
1148                        PFID(&rec->cr.cr_tfid), PFID(&rec->cr.cr_pfid), rc);
1149                 return -EFAULT;
1150         }
1151
1152         return 0;
1153 }
1154
1155 static int __mdd_links_add(const struct lu_env *env,
1156                            struct mdd_object *mdd_obj,
1157                            struct linkea_data *ldata,
1158                            const struct lu_name *lname,
1159                            const struct lu_fid *pfid,
1160                            int first, int check)
1161 {
1162         int rc;
1163
1164         if (ldata->ld_leh == NULL) {
1165                 rc = first ? -ENODATA : mdd_links_read(env, mdd_obj, ldata);
1166                 if (rc) {
1167                         if (rc != -ENODATA)
1168                                 return rc;
1169                         rc = linkea_data_new(ldata,
1170                                              &mdd_env_info(env)->mti_link_buf);
1171                         if (rc)
1172                                 return rc;
1173                 }
1174         }
1175
1176         if (check) {
1177                 rc = linkea_links_find(ldata, lname, pfid);
1178                 if (rc && rc != -ENOENT)
1179                         return rc;
1180                 if (rc == 0)
1181                         return -EEXIST;
1182         }
1183
1184         if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_LINKEA_MORE)) {
1185                 struct lu_fid *tfid = &mdd_env_info(env)->mti_fid2;
1186
1187                 *tfid = *pfid;
1188                 tfid->f_ver = ~0;
1189                 linkea_add_buf(ldata, lname, tfid);
1190         }
1191
1192         if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_LINKEA_MORE2))
1193                 linkea_add_buf(ldata, lname, pfid);
1194
1195         return linkea_add_buf(ldata, lname, pfid);
1196 }
1197
1198 static int __mdd_links_del(const struct lu_env *env,
1199                            struct mdd_object *mdd_obj,
1200                            struct linkea_data *ldata,
1201                            const struct lu_name *lname,
1202                            const struct lu_fid *pfid)
1203 {
1204         int rc;
1205
1206         if (ldata->ld_leh == NULL) {
1207                 rc = mdd_links_read(env, mdd_obj, ldata);
1208                 if (rc)
1209                         return rc;
1210         }
1211
1212         rc = linkea_links_find(ldata, lname, pfid);
1213         if (rc)
1214                 return rc;
1215
1216         linkea_del_buf(ldata, lname);
1217         return 0;
1218 }
1219
1220 static int mdd_linkea_prepare(const struct lu_env *env,
1221                               struct mdd_object *mdd_obj,
1222                               const struct lu_fid *oldpfid,
1223                               const struct lu_name *oldlname,
1224                               const struct lu_fid *newpfid,
1225                               const struct lu_name *newlname,
1226                               int first, int check,
1227                               struct linkea_data *ldata)
1228 {
1229         int rc = 0;
1230         ENTRY;
1231
1232         if (OBD_FAIL_CHECK(OBD_FAIL_FID_IGIF))
1233                 RETURN(0);
1234
1235         LASSERT(oldpfid != NULL || newpfid != NULL);
1236
1237         if (mdd_obj->mod_flags & DEAD_OBJ)
1238                 /* Unnecessary to update linkEA for dead object.  */
1239                 RETURN(0);
1240
1241         if (oldpfid != NULL) {
1242                 rc = __mdd_links_del(env, mdd_obj, ldata, oldlname, oldpfid);
1243                 if (rc) {
1244                         if ((check == 1) || (rc != -ENODATA && rc != -ENOENT))
1245                                 RETURN(rc);
1246
1247                         /* No changes done. */
1248                         rc = 0;
1249                 }
1250         }
1251
1252         /* If renaming, add the new record */
1253         if (newpfid != NULL)
1254                 rc = __mdd_links_add(env, mdd_obj, ldata, newlname, newpfid,
1255                                      first, check);
1256
1257         RETURN(rc);
1258 }
1259
1260 int mdd_links_rename(const struct lu_env *env,
1261                      struct mdd_object *mdd_obj,
1262                      const struct lu_fid *oldpfid,
1263                      const struct lu_name *oldlname,
1264                      const struct lu_fid *newpfid,
1265                      const struct lu_name *newlname,
1266                      struct thandle *handle,
1267                      struct linkea_data *ldata,
1268                      int first, int check)
1269 {
1270         int rc = 0;
1271         ENTRY;
1272
1273         if (ldata == NULL) {
1274                 ldata = &mdd_env_info(env)->mti_link_data;
1275                 memset(ldata, 0, sizeof(*ldata));
1276                 rc = mdd_linkea_prepare(env, mdd_obj, oldpfid, oldlname,
1277                                         newpfid, newlname, first, check, ldata);
1278                 if (rc)
1279                         GOTO(out, rc);
1280         }
1281
1282         if (!(mdd_obj->mod_flags & DEAD_OBJ))
1283                 rc = mdd_links_write(env, mdd_obj, ldata, handle);
1284
1285         GOTO(out, rc);
1286
1287 out:
1288         if (rc != 0) {
1289                 if (newlname == NULL)
1290                         CERROR("link_ea add failed %d "DFID"\n",
1291                                rc, PFID(mdd_object_fid(mdd_obj)));
1292                 else if (oldpfid == NULL)
1293                         CERROR("link_ea add '%.*s' failed %d "DFID"\n",
1294                                newlname->ln_namelen, newlname->ln_name, rc,
1295                                PFID(mdd_object_fid(mdd_obj)));
1296                 else if (newpfid == NULL)
1297                         CERROR("link_ea del '%.*s' failed %d "DFID"\n",
1298                                oldlname->ln_namelen, oldlname->ln_name, rc,
1299                                PFID(mdd_object_fid(mdd_obj)));
1300                 else
1301                         CERROR("link_ea rename '%.*s'->'%.*s' failed %d "DFID
1302                                "\n", oldlname->ln_namelen, oldlname->ln_name,
1303                                newlname->ln_namelen, newlname->ln_name, rc,
1304                                PFID(mdd_object_fid(mdd_obj)));
1305         }
1306
1307         if (is_vmalloc_addr(ldata->ld_buf))
1308                 /* if we vmalloced a large buffer drop it */
1309                 lu_buf_free(ldata->ld_buf);
1310
1311         return rc;
1312 }
1313
1314 static inline int mdd_links_add(const struct lu_env *env,
1315                                 struct mdd_object *mdd_obj,
1316                                 const struct lu_fid *pfid,
1317                                 const struct lu_name *lname,
1318                                 struct thandle *handle,
1319                                 struct linkea_data *ldata, int first)
1320 {
1321         return mdd_links_rename(env, mdd_obj, NULL, NULL,
1322                                 pfid, lname, handle, ldata, first, 0);
1323 }
1324
1325 static inline int mdd_links_del(const struct lu_env *env,
1326                                 struct mdd_object *mdd_obj,
1327                                 const struct lu_fid *pfid,
1328                                 const struct lu_name *lname,
1329                                 struct thandle *handle)
1330 {
1331         return mdd_links_rename(env, mdd_obj, pfid, lname,
1332                                 NULL, NULL, handle, NULL, 0, 0);
1333 }
1334
1335 /** Read the link EA into a temp buffer.
1336  * Uses the name_buf since it is generally large.
1337  * \retval IS_ERR err
1338  * \retval ptr to \a lu_buf (always \a mti_big_buf)
1339  */
1340 struct lu_buf *mdd_links_get(const struct lu_env *env,
1341                              struct mdd_object *mdd_obj)
1342 {
1343         struct linkea_data ldata = { NULL };
1344         int rc;
1345
1346         rc = mdd_links_read(env, mdd_obj, &ldata);
1347         return rc ? ERR_PTR(rc) : ldata.ld_buf;
1348 }
1349
1350 int mdd_links_write(const struct lu_env *env, struct mdd_object *mdd_obj,
1351                     struct linkea_data *ldata, struct thandle *handle)
1352 {
1353         const struct lu_buf *buf;
1354         int                 rc;
1355
1356         if (ldata == NULL || ldata->ld_buf == NULL ||
1357             ldata->ld_leh == NULL)
1358                 return 0;
1359
1360         if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_NO_LINKEA))
1361                 return 0;
1362
1363 again:
1364         buf = mdd_buf_get_const(env, ldata->ld_buf->lb_buf,
1365                                 ldata->ld_leh->leh_len);
1366         rc = mdo_xattr_set(env, mdd_obj, buf, XATTR_NAME_LINK, 0, handle);
1367         if (unlikely(rc == -ENOSPC)) {
1368                 rc = linkea_overflow_shrink(ldata);
1369                 if (likely(rc > 0))
1370                         goto again;
1371         }
1372
1373         return rc;
1374 }
1375
1376 static int mdd_declare_links_add(const struct lu_env *env,
1377                                  struct mdd_object *mdd_obj,
1378                                  struct thandle *handle,
1379                                  struct linkea_data *ldata)
1380 {
1381         int     rc;
1382         int     ea_len;
1383         void    *linkea;
1384
1385         if (ldata != NULL && ldata->ld_leh != NULL) {
1386                 ea_len = ldata->ld_leh->leh_len;
1387                 linkea = ldata->ld_buf->lb_buf;
1388         } else {
1389                 ea_len = MAX_LINKEA_SIZE;
1390                 linkea = NULL;
1391         }
1392
1393         rc = mdo_declare_xattr_set(env, mdd_obj,
1394                                    mdd_buf_get_const(env, linkea, ea_len),
1395                                    XATTR_NAME_LINK, 0, handle);
1396
1397         return rc;
1398 }
1399
1400 static inline int mdd_declare_links_del(const struct lu_env *env,
1401                                         struct mdd_object *c,
1402                                         struct thandle *handle)
1403 {
1404         int rc = 0;
1405
1406         /* For directory, the linkEA will be removed together
1407          * with the object. */
1408         if (!S_ISDIR(mdd_object_type(c)))
1409                 rc = mdd_declare_links_add(env, c, handle, NULL);
1410
1411         return rc;
1412 }
1413
1414 static int mdd_declare_link(const struct lu_env *env,
1415                             struct mdd_device *mdd,
1416                             struct mdd_object *p,
1417                             struct mdd_object *c,
1418                             const struct lu_name *name,
1419                             struct thandle *handle,
1420                             struct lu_attr *la,
1421                             struct linkea_data *data)
1422 {
1423         struct lu_fid tfid = *mdo2fid(c);
1424         int rc;
1425
1426         if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_DANGLING3))
1427                 tfid.f_oid = cfs_fail_val;
1428
1429         rc = mdo_declare_index_insert(env, p, &tfid, mdd_object_type(c),
1430                                       name->ln_name, handle);
1431         if (rc != 0)
1432                 return rc;
1433
1434         rc = mdo_declare_ref_add(env, c, handle);
1435         if (rc != 0)
1436                 return rc;
1437
1438         la->la_valid = LA_CTIME | LA_MTIME;
1439         rc = mdo_declare_attr_set(env, p, la, handle);
1440         if (rc != 0)
1441                 return rc;
1442
1443         la->la_valid = LA_CTIME;
1444         rc = mdo_declare_attr_set(env, c, la, handle);
1445         if (rc != 0)
1446                 return rc;
1447
1448         rc = mdd_declare_links_add(env, c, handle, data);
1449         if (rc != 0)
1450                 return rc;
1451
1452         rc = mdd_declare_changelog_store(env, mdd, name, NULL, handle);
1453
1454         return rc;
1455 }
1456
1457 static int mdd_link(const struct lu_env *env, struct md_object *tgt_obj,
1458                     struct md_object *src_obj, const struct lu_name *lname,
1459                     struct md_attr *ma)
1460 {
1461         const char *name = lname->ln_name;
1462         struct lu_attr    *la = &mdd_env_info(env)->mti_la_for_fix;
1463         struct mdd_object *mdd_tobj = md2mdd_obj(tgt_obj);
1464         struct mdd_object *mdd_sobj = md2mdd_obj(src_obj);
1465         struct lu_attr    *cattr = MDD_ENV_VAR(env, cattr);
1466         struct lu_attr    *tattr = MDD_ENV_VAR(env, tattr);
1467         struct mdd_device *mdd = mdo2mdd(src_obj);
1468         struct thandle *handle;
1469         struct lu_fid *tfid = &mdd_env_info(env)->mti_fid2;
1470         struct linkea_data *ldata = &mdd_env_info(env)->mti_link_data;
1471         int rc;
1472         ENTRY;
1473
1474         rc = mdd_la_get(env, mdd_sobj, cattr);
1475         if (rc != 0)
1476                 RETURN(rc);
1477
1478         rc = mdd_la_get(env, mdd_tobj, tattr);
1479         if (rc != 0)
1480                 RETURN(rc);
1481
1482         /*
1483          * If we are using project inheritance, we only allow hard link
1484          * creation in our tree when the project IDs are the same;
1485          * otherwise the tree quota mechanism could be circumvented.
1486          */
1487         if ((tattr->la_flags & LUSTRE_PROJINHERIT_FL) &&
1488             (tattr->la_projid != cattr->la_projid))
1489                 RETURN(-EXDEV);
1490
1491         handle = mdd_trans_create(env, mdd);
1492         if (IS_ERR(handle))
1493                 GOTO(out_pending, rc = PTR_ERR(handle));
1494
1495         memset(ldata, 0, sizeof(*ldata));
1496
1497         LASSERT(ma->ma_attr.la_valid & LA_CTIME);
1498         la->la_ctime = la->la_mtime = ma->ma_attr.la_ctime;
1499
1500         /* Note: even this function will change ldata, but it comes from
1501          * thread_info, which is completely temporary and only seen in
1502          * this function, so we do not need reset ldata once it fails.*/
1503         rc = mdd_linkea_prepare(env, mdd_sobj, NULL, NULL, mdo2fid(mdd_tobj),
1504                                 lname, 0, 0, ldata);
1505         if (rc != 0)
1506                 GOTO(stop, rc);
1507
1508         rc = mdd_declare_link(env, mdd, mdd_tobj, mdd_sobj, lname, handle,
1509                               la, ldata);
1510         if (rc)
1511                 GOTO(stop, rc);
1512
1513         rc = mdd_trans_start(env, mdd, handle);
1514         if (rc)
1515                 GOTO(stop, rc);
1516
1517         mdd_write_lock(env, mdd_sobj, MOR_TGT_CHILD);
1518         rc = mdd_link_sanity_check(env, mdd_tobj, tattr, lname, mdd_sobj,
1519                                    cattr);
1520         if (rc)
1521                 GOTO(out_unlock, rc);
1522
1523         if (!OBD_FAIL_CHECK(OBD_FAIL_LFSCK_LESS_NLINK)) {
1524                 rc = mdo_ref_add(env, mdd_sobj, handle);
1525                 if (rc != 0)
1526                         GOTO(out_unlock, rc);
1527         }
1528
1529         *tfid = *mdo2fid(mdd_sobj);
1530         if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_DANGLING3))
1531                 tfid->f_oid = cfs_fail_val;
1532
1533         rc = __mdd_index_insert_only(env, mdd_tobj, tfid,
1534                                      mdd_object_type(mdd_sobj), name, handle);
1535         if (rc != 0) {
1536                 mdo_ref_del(env, mdd_sobj, handle);
1537                 GOTO(out_unlock, rc);
1538         }
1539
1540         la->la_valid = LA_CTIME | LA_MTIME;
1541         rc = mdd_update_time(env, mdd_tobj, tattr, la, handle);
1542         if (rc)
1543                 GOTO(out_unlock, rc);
1544
1545         la->la_valid = LA_CTIME;
1546         rc = mdd_update_time(env, mdd_sobj, cattr, la, handle);
1547         if (rc == 0)
1548                 /* Note: The failure of links_add should not cause the
1549                  * link failure, so do not check return value. */
1550                 mdd_links_add(env, mdd_sobj, mdo2fid(mdd_tobj),
1551                               lname, handle, ldata, 0);
1552
1553         EXIT;
1554 out_unlock:
1555         mdd_write_unlock(env, mdd_sobj);
1556         if (rc == 0)
1557                 rc = mdd_changelog_ns_store(env, mdd, CL_HARDLINK, 0, mdd_sobj,
1558                                             mdo2fid(mdd_tobj), NULL, NULL,
1559                                             lname, NULL, handle);
1560 stop:
1561         rc = mdd_trans_stop(env, mdd, rc, handle);
1562         if (is_vmalloc_addr(ldata->ld_buf))
1563                 /* if we vmalloced a large buffer drop it */
1564                 lu_buf_free(ldata->ld_buf);
1565 out_pending:
1566         return rc;
1567 }
1568
1569 static int mdd_mark_orphan_object(const struct lu_env *env,
1570                                 struct mdd_object *obj, struct thandle *handle,
1571                                 bool declare)
1572 {
1573         struct lu_attr *attr = MDD_ENV_VAR(env, la_for_start);
1574         int rc;
1575
1576         if (!S_ISDIR(mdd_object_type(obj)))
1577                 return 0;
1578
1579         attr->la_valid = LA_FLAGS;
1580         attr->la_flags = LUSTRE_ORPHAN_FL;
1581
1582         if (declare)
1583                 rc = mdo_declare_attr_set(env, obj, attr, handle);
1584         else
1585                 rc = mdo_attr_set(env, obj, attr, handle);
1586
1587         return rc;
1588 }
1589
1590 static int mdd_declare_finish_unlink(const struct lu_env *env,
1591                                      struct mdd_object *obj,
1592                                      struct thandle *handle)
1593 {
1594         int     rc;
1595
1596         /* Sigh, we do not know if the unlink object will become orphan in
1597          * declare phase, but fortunately the flags here does not matter
1598          * in current declare implementation */
1599         rc = mdd_mark_orphan_object(env, obj, handle, true);
1600         if (rc != 0)
1601                 return rc;
1602
1603         rc = mdo_declare_destroy(env, obj, handle);
1604         if (rc != 0)
1605                 return rc;
1606
1607         rc = orph_declare_index_insert(env, obj, mdd_object_type(obj), handle);
1608         if (rc != 0)
1609                 return rc;
1610
1611         return mdd_declare_links_del(env, obj, handle);
1612 }
1613
1614 /* caller should take a lock before calling */
1615 int mdd_finish_unlink(const struct lu_env *env,
1616                       struct mdd_object *obj, struct md_attr *ma,
1617                       const struct mdd_object *pobj,
1618                       const struct lu_name *lname,
1619                       struct thandle *th)
1620 {
1621         int rc = 0;
1622         int is_dir = S_ISDIR(ma->ma_attr.la_mode);
1623         ENTRY;
1624
1625         LASSERT(mdd_write_locked(env, obj) != 0);
1626
1627         if (ma->ma_attr.la_nlink == 0 || is_dir) {
1628                 /* add new orphan and the object
1629                  * will be deleted during mdd_close() */
1630                 obj->mod_flags |= DEAD_OBJ;
1631                 if (obj->mod_count) {
1632                         rc = __mdd_orphan_add(env, obj, th);
1633                         if (rc == 0)
1634                                 CDEBUG(D_HA, "Object "DFID" is inserted into "
1635                                         "orphan list, open count = %d\n",
1636                                         PFID(mdd_object_fid(obj)),
1637                                         obj->mod_count);
1638                         else
1639                                 CERROR("Object "DFID" fail to be an orphan, "
1640                                        "open count = %d, maybe cause failed "
1641                                        "open replay\n",
1642                                         PFID(mdd_object_fid(obj)),
1643                                         obj->mod_count);
1644
1645                         /* mark object as an orphan here, not
1646                          * before __mdd_orphan_add() as racing
1647                          * mdd_la_get() may propagate ORPHAN_OBJ
1648                          * causing the asserition */
1649                         rc = mdd_mark_orphan_object(env, obj, th, false);
1650                 } else {
1651                         rc = mdo_destroy(env, obj, th);
1652                 }
1653         } else if (!is_dir) {
1654                 /* old files may not have link ea; ignore errors */
1655                 mdd_links_del(env, obj, mdo2fid(pobj), lname, th);
1656         }
1657
1658         RETURN(rc);
1659 }
1660
1661 /*
1662  * pobj maybe NULL
1663  * has mdd_write_lock on cobj already, but not on pobj yet
1664  */
1665 int mdd_unlink_sanity_check(const struct lu_env *env, struct mdd_object *pobj,
1666                             const struct lu_attr *pattr,
1667                             struct mdd_object *cobj,
1668                             const struct lu_attr *cattr)
1669 {
1670         int rc;
1671         ENTRY;
1672
1673         rc = mdd_may_delete(env, pobj, pattr, cobj, cattr, NULL, 1, 1);
1674
1675         RETURN(rc);
1676 }
1677
1678 static int mdd_declare_unlink(const struct lu_env *env, struct mdd_device *mdd,
1679                               struct mdd_object *p, struct mdd_object *c,
1680                               const struct lu_name *name, struct md_attr *ma,
1681                               struct thandle *handle, int no_name, int is_dir)
1682 {
1683         struct lu_attr  *la = &mdd_env_info(env)->mti_la_for_fix;
1684         int              rc;
1685
1686         if (!OBD_FAIL_CHECK(OBD_FAIL_LFSCK_DANGLING2)) {
1687                 if (likely(no_name == 0)) {
1688                         rc = mdo_declare_index_delete(env, p, name->ln_name,
1689                                                       handle);
1690                         if (rc != 0)
1691                                 return rc;
1692                 }
1693
1694                 if (is_dir != 0) {
1695                         rc = mdo_declare_ref_del(env, p, handle);
1696                         if (rc != 0)
1697                                 return rc;
1698                 }
1699         }
1700
1701         LASSERT(ma->ma_attr.la_valid & LA_CTIME);
1702         la->la_ctime = la->la_mtime = ma->ma_attr.la_ctime;
1703         la->la_valid = LA_CTIME | LA_MTIME;
1704         rc = mdo_declare_attr_set(env, p, la, handle);
1705         if (rc)
1706                 return rc;
1707
1708         if (c != NULL) {
1709                 rc = mdo_declare_ref_del(env, c, handle);
1710                 if (rc)
1711                         return rc;
1712
1713                 rc = mdo_declare_ref_del(env, c, handle);
1714                 if (rc)
1715                         return rc;
1716
1717                 la->la_valid = LA_CTIME;
1718                 rc = mdo_declare_attr_set(env, c, la, handle);
1719                 if (rc)
1720                         return rc;
1721
1722                 rc = mdd_declare_finish_unlink(env, c, handle);
1723                 if (rc)
1724                         return rc;
1725
1726                 /* FIXME: need changelog for remove entry */
1727                 rc = mdd_declare_changelog_store(env, mdd, name, NULL, handle);
1728         }
1729
1730         return rc;
1731 }
1732
1733 /*
1734  * test if a file has an HSM archive
1735  * if HSM attributes are not found in ma update them from
1736  * HSM xattr
1737  */
1738 static bool mdd_hsm_archive_exists(const struct lu_env *env,
1739                                    struct mdd_object *obj,
1740                                    struct md_attr *ma)
1741 {
1742         ENTRY;
1743
1744         if (!(ma->ma_valid & MA_HSM)) {
1745                 /* no HSM MD provided, read xattr */
1746                 struct lu_buf   *hsm_buf;
1747                 const size_t     buflen = sizeof(struct hsm_attrs);
1748                 int              rc;
1749
1750                 hsm_buf = mdd_buf_get(env, NULL, 0);
1751                 lu_buf_alloc(hsm_buf, buflen);
1752                 rc = mdo_xattr_get(env, obj, hsm_buf, XATTR_NAME_HSM);
1753                 rc = lustre_buf2hsm(hsm_buf->lb_buf, rc, &ma->ma_hsm);
1754                 lu_buf_free(hsm_buf);
1755                 if (rc < 0)
1756                         RETURN(false);
1757
1758                 ma->ma_valid |= MA_HSM;
1759         }
1760         if (ma->ma_hsm.mh_flags & HS_EXISTS)
1761                 RETURN(true);
1762         RETURN(false);
1763 }
1764
1765 /**
1766  * Delete name entry and the object.
1767  * Note: no_name == 1 means it only destory the object, i.e. name_entry
1768  * does not exist for this object, and it could only happen during resending
1769  * of remote unlink. see the comments in mdt_reint_unlink. Unfortunately, lname
1770  * is also needed in this case(needed by changelog), so we have to add another
1771  * parameter(no_name)here. XXX: this is only needed in DNE phase I, on Phase II,
1772  * the ENOENT failure should be able to be fixed by redo mechanism.
1773  */
1774 static int mdd_unlink(const struct lu_env *env, struct md_object *pobj,
1775                       struct md_object *cobj, const struct lu_name *lname,
1776                       struct md_attr *ma, int no_name)
1777 {
1778         const char *name = lname->ln_name;
1779         struct lu_attr *pattr = MDD_ENV_VAR(env, pattr);
1780         struct lu_attr *cattr = MDD_ENV_VAR(env, cattr);
1781         struct lu_attr *la = &mdd_env_info(env)->mti_la_for_fix;
1782         struct mdd_object *mdd_pobj = md2mdd_obj(pobj);
1783         struct mdd_object *mdd_cobj = NULL;
1784         struct mdd_device *mdd = mdo2mdd(pobj);
1785         struct thandle    *handle;
1786         int rc, is_dir = 0, cl_flags = 0;
1787         ENTRY;
1788
1789         /* cobj == NULL means only delete name entry */
1790         if (likely(cobj != NULL)) {
1791                 mdd_cobj = md2mdd_obj(cobj);
1792                 if (mdd_object_exists(mdd_cobj) == 0)
1793                         RETURN(-ENOENT);
1794         }
1795
1796         rc = mdd_la_get(env, mdd_pobj, pattr);
1797         if (rc)
1798                 RETURN(rc);
1799
1800         if (likely(mdd_cobj != NULL)) {
1801                 /* fetch cattr */
1802                 rc = mdd_la_get(env, mdd_cobj, cattr);
1803                 if (rc)
1804                         RETURN(rc);
1805
1806                 is_dir = S_ISDIR(cattr->la_mode);
1807                 /* search for an existing archive.
1808                  * we should check ahead as the object
1809                  * can be destroyed in this transaction */
1810                 if (mdd_hsm_archive_exists(env, mdd_cobj, ma))
1811                         cl_flags |= CLF_UNLINK_HSM_EXISTS;
1812         }
1813
1814         rc = mdd_unlink_sanity_check(env, mdd_pobj, pattr, mdd_cobj, cattr);
1815         if (rc)
1816                 RETURN(rc);
1817
1818         handle = mdd_trans_create(env, mdd);
1819         if (IS_ERR(handle))
1820                 RETURN(PTR_ERR(handle));
1821
1822         rc = mdd_declare_unlink(env, mdd, mdd_pobj, mdd_cobj,
1823                                 lname, ma, handle, no_name, is_dir);
1824         if (rc)
1825                 GOTO(stop, rc);
1826
1827         rc = mdd_trans_start(env, mdd, handle);
1828         if (rc)
1829                 GOTO(stop, rc);
1830
1831         if (likely(mdd_cobj != NULL))
1832                 mdd_write_lock(env, mdd_cobj, MOR_TGT_CHILD);
1833
1834         if (likely(no_name == 0) && !OBD_FAIL_CHECK(OBD_FAIL_LFSCK_DANGLING2)) {
1835                 rc = __mdd_index_delete(env, mdd_pobj, name, is_dir, handle);
1836                 if (rc)
1837                         GOTO(cleanup, rc);
1838         }
1839
1840         if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_MUL_REF) ||
1841             OBD_FAIL_CHECK(OBD_FAIL_LFSCK_NO_NAMEENTRY))
1842                 GOTO(cleanup, rc = 0);
1843
1844         if (likely(mdd_cobj != NULL)) {
1845                 rc = mdo_ref_del(env, mdd_cobj, handle);
1846                 if (rc != 0) {
1847                         __mdd_index_insert_only(env, mdd_pobj,
1848                                                 mdo2fid(mdd_cobj),
1849                                                 mdd_object_type(mdd_cobj),
1850                                                 name, handle);
1851                         GOTO(cleanup, rc);
1852                 }
1853
1854                 if (is_dir)
1855                         /* unlink dot */
1856                         mdo_ref_del(env, mdd_cobj, handle);
1857
1858                 /* fetch updated nlink */
1859                 rc = mdd_la_get(env, mdd_cobj, cattr);
1860                 if (rc)
1861                         GOTO(cleanup, rc);
1862         }
1863
1864         LASSERT(ma->ma_attr.la_valid & LA_CTIME);
1865         la->la_ctime = la->la_mtime = ma->ma_attr.la_ctime;
1866
1867         la->la_valid = LA_CTIME | LA_MTIME;
1868         rc = mdd_update_time(env, mdd_pobj, pattr, la, handle);
1869         if (rc)
1870                 GOTO(cleanup, rc);
1871
1872         /* Enough for only unlink the entry */
1873         if (unlikely(mdd_cobj == NULL))
1874                 GOTO(stop, rc);
1875
1876         if (cattr->la_nlink > 0 || mdd_cobj->mod_count > 0) {
1877                 /* update ctime of an unlinked file only if it is still
1878                  * opened or a link still exists */
1879                 la->la_valid = LA_CTIME;
1880                 rc = mdd_update_time(env, mdd_cobj, cattr, la, handle);
1881                 if (rc)
1882                         GOTO(cleanup, rc);
1883         }
1884
1885         /* XXX: this transfer to ma will be removed with LOD/OSP */
1886         ma->ma_attr = *cattr;
1887         ma->ma_valid |= MA_INODE;
1888         rc = mdd_finish_unlink(env, mdd_cobj, ma, mdd_pobj, lname, handle);
1889         if (rc != 0)
1890                 GOTO(cleanup, rc);
1891
1892         /* fetch updated nlink */
1893         rc = mdd_la_get(env, mdd_cobj, cattr);
1894         /* if object is removed then we can't get its attrs,
1895          * use last get */
1896         if (rc == -ENOENT) {
1897                 cattr->la_nlink = 0;
1898                 rc = 0;
1899         }
1900
1901         if (cattr->la_nlink == 0) {
1902                 ma->ma_attr = *cattr;
1903                 ma->ma_valid |= MA_INODE;
1904         }
1905
1906         EXIT;
1907 cleanup:
1908         if (likely(mdd_cobj != NULL))
1909                 mdd_write_unlock(env, mdd_cobj);
1910
1911         if (rc == 0) {
1912                 if (cattr->la_nlink == 0)
1913                         cl_flags |= CLF_UNLINK_LAST;
1914                 else
1915                         cl_flags &= ~CLF_UNLINK_HSM_EXISTS;
1916
1917                 rc = mdd_changelog_ns_store(env, mdd,
1918                         is_dir ? CL_RMDIR : CL_UNLINK, cl_flags,
1919                         mdd_cobj, mdo2fid(mdd_pobj), NULL, NULL, lname, NULL,
1920                         handle);
1921         }
1922
1923 stop:
1924         rc = mdd_trans_stop(env, mdd, rc, handle);
1925
1926         return rc;
1927 }
1928
1929 /*
1930  * The permission has been checked when obj created, no need check again.
1931  */
1932 static int mdd_cd_sanity_check(const struct lu_env *env,
1933                                struct mdd_object *obj)
1934 {
1935         ENTRY;
1936
1937         /* EEXIST check */
1938         if (!obj || mdd_is_dead_obj(obj))
1939                 RETURN(-ENOENT);
1940
1941         RETURN(0);
1942 }
1943
1944 static int mdd_create_data(const struct lu_env *env,
1945                            struct md_object *pobj,
1946                            struct md_object *cobj,
1947                            const struct md_op_spec *spec,
1948                            struct md_attr *ma)
1949 {
1950         struct mdd_device *mdd = mdo2mdd(cobj);
1951         struct mdd_object *mdd_pobj = md2mdd_obj(pobj);
1952         struct mdd_object *son = md2mdd_obj(cobj);
1953         struct thandle    *handle;
1954         const struct lu_buf *buf;
1955         struct lu_attr    *attr = MDD_ENV_VAR(env, cattr);
1956         struct dt_allocation_hint *hint = &mdd_env_info(env)->mti_hint;
1957         int                rc;
1958         ENTRY;
1959
1960         rc = mdd_cd_sanity_check(env, son);
1961         if (rc)
1962                 RETURN(rc);
1963
1964         if (!md_should_create(spec->sp_cr_flags))
1965                 RETURN(0);
1966
1967         /*
1968          * there are following use cases for this function:
1969          * 1) late striping - file was created with MDS_OPEN_DELAY_CREATE
1970          *    striping can be specified or not
1971          * 2) CMD?
1972          */
1973         rc = mdd_la_get(env, son, attr);
1974         if (rc)
1975                 RETURN(rc);
1976
1977         /* calling ->ah_make_hint() is used to transfer information from parent */
1978         mdd_object_make_hint(env, mdd_pobj, son, attr, spec, hint);
1979
1980         handle = mdd_trans_create(env, mdd);
1981         if (IS_ERR(handle))
1982                 GOTO(out_free, rc = PTR_ERR(handle));
1983
1984         /*
1985          * XXX: Setting the lov ea is not locked but setting the attr is locked?
1986          * Should this be fixed?
1987          */
1988         CDEBUG(D_OTHER, "ea %p/%u, cr_flags %#llo, no_create %u\n",
1989                spec->u.sp_ea.eadata, spec->u.sp_ea.eadatalen,
1990                spec->sp_cr_flags, spec->no_create);
1991
1992         if (spec->no_create || (spec->sp_cr_flags & MDS_OPEN_HAS_EA)) {
1993                 buf = mdd_buf_get_const(env, spec->u.sp_ea.eadata,
1994                                         spec->u.sp_ea.eadatalen);
1995         } else {
1996                 buf = &LU_BUF_NULL;
1997         }
1998
1999         rc = dt_declare_xattr_set(env, mdd_object_child(son), buf,
2000                                   XATTR_NAME_LOV, 0, handle);
2001         if (rc)
2002                 GOTO(stop, rc);
2003
2004         rc = mdd_declare_changelog_store(env, mdd, NULL, NULL, handle);
2005         if (rc)
2006                 GOTO(stop, rc);
2007
2008         rc = mdd_trans_start(env, mdd, handle);
2009         if (rc)
2010                 GOTO(stop, rc);
2011
2012         rc = dt_xattr_set(env, mdd_object_child(son), buf, XATTR_NAME_LOV,
2013                           0, handle);
2014
2015         if (rc)
2016                 GOTO(stop, rc);
2017
2018         rc = mdd_changelog_data_store(env, mdd, CL_LAYOUT, 0, son, handle);
2019
2020 stop:
2021         rc = mdd_trans_stop(env, mdd, rc, handle);
2022
2023 out_free:
2024         RETURN(rc);
2025 }
2026
2027 static int mdd_declare_object_initialize(const struct lu_env *env,
2028                                          struct mdd_object *parent,
2029                                          struct mdd_object *child,
2030                                          const struct lu_attr *attr,
2031                                          struct thandle *handle)
2032 {
2033         int rc;
2034         ENTRY;
2035
2036         LASSERT(attr->la_valid & (LA_MODE | LA_TYPE));
2037         if (!S_ISDIR(attr->la_mode))
2038                 RETURN(0);
2039
2040         rc = mdo_declare_index_insert(env, child, mdo2fid(child), S_IFDIR,
2041                                       dot, handle);
2042         if (rc != 0)
2043                 RETURN(rc);
2044
2045         rc = mdo_declare_ref_add(env, child, handle);
2046         if (rc != 0)
2047                 RETURN(rc);
2048
2049         rc = mdo_declare_index_insert(env, child, mdo2fid(parent), S_IFDIR,
2050                                       dotdot, handle);
2051
2052         RETURN(rc);
2053 }
2054
2055 static int mdd_object_initialize(const struct lu_env *env,
2056                                  const struct lu_fid *pfid,
2057                                  struct mdd_object *child,
2058                                  struct lu_attr *attr, struct thandle *handle,
2059                                  const struct md_op_spec *spec)
2060 {
2061         int rc = 0;
2062         ENTRY;
2063
2064         if (S_ISDIR(attr->la_mode)) {
2065                 /* Add "." and ".." for newly created dir */
2066                 mdo_ref_add(env, child, handle);
2067                 rc = __mdd_index_insert_only(env, child, mdo2fid(child),
2068                                              S_IFDIR, dot, handle);
2069                 if (rc == 0)
2070                         rc = __mdd_index_insert_only(env, child, pfid, S_IFDIR,
2071                                                      dotdot, handle);
2072                 if (rc != 0)
2073                         mdo_ref_del(env, child, handle);
2074         }
2075
2076         RETURN(rc);
2077 }
2078
2079 /**
2080  * This function checks whether it can create a file/dir under the
2081  * directory(@pobj). The directory(@pobj) is not being locked by
2082  * mdd lock.
2083  *
2084  * \param[in] env       execution environment
2085  * \param[in] pobj      the directory to create files
2086  * \param[in] pattr     the attributes of the directory
2087  * \param[in] lname     the name of the created file/dir
2088  * \param[in] cattr     the attributes of the file/dir
2089  * \param[in] spec      create specification
2090  *
2091  * \retval              = 0 it is allowed to create file/dir under
2092  *                      the directory
2093  * \retval              negative error not allowed to create file/dir
2094  *                      under the directory
2095  */
2096 static int mdd_create_sanity_check(const struct lu_env *env,
2097                                    struct md_object *pobj,
2098                                    const struct lu_attr *pattr,
2099                                    const struct lu_name *lname,
2100                                    struct lu_attr *cattr,
2101                                    struct md_op_spec *spec)
2102 {
2103         struct mdd_thread_info *info = mdd_env_info(env);
2104         struct lu_fid     *fid       = &info->mti_fid;
2105         struct mdd_object *obj       = md2mdd_obj(pobj);
2106         struct mdd_device *m         = mdo2mdd(pobj);
2107         bool            check_perm = true;
2108         int rc;
2109         ENTRY;
2110
2111         /* EEXIST check */
2112         if (mdd_is_dead_obj(obj))
2113                 RETURN(-ENOENT);
2114
2115         /*
2116          * In some cases this lookup is not needed - we know before if name
2117          * exists or not because MDT performs lookup for it.
2118          * name length check is done in lookup.
2119          */
2120         if (spec->sp_cr_lookup) {
2121                 /*
2122                  * Check if the name already exist, though it will be checked in
2123                  * _index_insert also, for avoiding rolling back if exists
2124                  * _index_insert.
2125                  */
2126                 rc = __mdd_lookup(env, pobj, pattr, lname, fid,
2127                                   MAY_WRITE | MAY_EXEC);
2128                 if (rc != -ENOENT)
2129                         RETURN(rc ? : -EEXIST);
2130
2131                 /* Permission is already being checked in mdd_lookup */
2132                 check_perm = false;
2133         }
2134
2135         if (S_ISDIR(cattr->la_mode) &&
2136             unlikely(spec != NULL && spec->sp_cr_flags & MDS_OPEN_HAS_EA) &&
2137             spec->u.sp_ea.eadata != NULL && spec->u.sp_ea.eadatalen > 0) {
2138                 const struct lmv_user_md *lum = spec->u.sp_ea.eadata;
2139
2140                 if (le32_to_cpu(lum->lum_magic) != LMV_USER_MAGIC &&
2141                     le32_to_cpu(lum->lum_magic) != LMV_USER_MAGIC_SPECIFIC &&
2142                     le32_to_cpu(lum->lum_magic) != LMV_USER_MAGIC_V0) {
2143                         rc = -EINVAL;
2144                         CERROR("%s: invalid lmv_user_md: magic = %x, "
2145                                "stripe_offset = %d, stripe_count = %u: "
2146                                "rc = %d\n", mdd2obd_dev(m)->obd_name,
2147                                 le32_to_cpu(lum->lum_magic),
2148                                (int)le32_to_cpu(lum->lum_stripe_offset),
2149                                le32_to_cpu(lum->lum_stripe_count), rc);
2150                         return rc;
2151                 }
2152         }
2153
2154         rc = mdd_may_create(env, obj, pattr, NULL, check_perm);
2155         if (rc != 0)
2156                 RETURN(rc);
2157
2158         /* sgid check */
2159         if (pattr->la_mode & S_ISGID) {
2160                 cattr->la_gid = pattr->la_gid;
2161                 if (S_ISDIR(cattr->la_mode)) {
2162                         cattr->la_mode |= S_ISGID;
2163                         cattr->la_valid |= LA_MODE;
2164                 }
2165         }
2166
2167         /* Inherit project ID from parent directory */
2168         if (pattr->la_flags & LUSTRE_PROJINHERIT_FL) {
2169                 cattr->la_projid = pattr->la_projid;
2170                 if (S_ISDIR(cattr->la_mode)) {
2171                         cattr->la_flags |= LUSTRE_PROJINHERIT_FL;
2172                         cattr->la_valid |= LA_FLAGS;
2173                 }
2174                 cattr->la_valid |= LA_PROJID;
2175         }
2176
2177         rc = mdd_name_check(m, lname);
2178         if (rc < 0)
2179                 RETURN(rc);
2180
2181         switch (cattr->la_mode & S_IFMT) {
2182         case S_IFLNK: {
2183                 unsigned int symlen = strlen(spec->u.sp_symname) + 1;
2184
2185                 if (symlen > m->mdd_dt_conf.ddp_symlink_max)
2186                         RETURN(-ENAMETOOLONG);
2187                 else
2188                         RETURN(0);
2189         }
2190         case S_IFDIR:
2191         case S_IFREG:
2192         case S_IFCHR:
2193         case S_IFBLK:
2194         case S_IFIFO:
2195         case S_IFSOCK:
2196                 rc = 0;
2197                 break;
2198         default:
2199                 rc = -EINVAL;
2200                 break;
2201         }
2202         RETURN(rc);
2203 }
2204
2205 static int mdd_declare_create_object(const struct lu_env *env,
2206                                      struct mdd_device *mdd,
2207                                      struct mdd_object *p, struct mdd_object *c,
2208                                      struct lu_attr *attr,
2209                                      struct thandle *handle,
2210                                      const struct md_op_spec *spec,
2211                                      struct lu_buf *def_acl_buf,
2212                                      struct lu_buf *acl_buf,
2213                                      struct dt_allocation_hint *hint)
2214 {
2215         const struct lu_buf *buf;
2216         int rc;
2217
2218         rc = mdd_declare_create_object_internal(env, p, c, attr, handle, spec,
2219                                                 hint);
2220         if (rc)
2221                 GOTO(out, rc);
2222
2223 #ifdef CONFIG_FS_POSIX_ACL
2224         if (def_acl_buf->lb_len > 0 && S_ISDIR(attr->la_mode)) {
2225                 /* if dir, then can inherit default ACl */
2226                 rc = mdo_declare_xattr_set(env, c, def_acl_buf,
2227                                            XATTR_NAME_ACL_DEFAULT,
2228                                            0, handle);
2229                 if (rc)
2230                         GOTO(out, rc);
2231         }
2232
2233         if (acl_buf->lb_len > 0) {
2234                 rc = mdo_declare_attr_set(env, c, attr, handle);
2235                 if (rc)
2236                         GOTO(out, rc);
2237
2238                 rc = mdo_declare_xattr_set(env, c, acl_buf,
2239                                            XATTR_NAME_ACL_ACCESS, 0, handle);
2240                 if (rc)
2241                         GOTO(out, rc);
2242         }
2243 #endif
2244         rc = mdd_declare_object_initialize(env, p, c, attr, handle);
2245         if (rc)
2246                 GOTO(out, rc);
2247
2248         /* replay case, create LOV EA from client data */
2249         if (spec->no_create ||
2250             (spec->sp_cr_flags & MDS_OPEN_HAS_EA && S_ISREG(attr->la_mode))) {
2251                 buf = mdd_buf_get_const(env, spec->u.sp_ea.eadata,
2252                                         spec->u.sp_ea.eadatalen);
2253                 rc = mdo_declare_xattr_set(env, c, buf, XATTR_NAME_LOV, 0,
2254                                            handle);
2255                 if (rc)
2256                         GOTO(out, rc);
2257         }
2258
2259         if (S_ISLNK(attr->la_mode)) {
2260                 const char *target_name = spec->u.sp_symname;
2261                 int sym_len = strlen(target_name);
2262                 const struct lu_buf *buf;
2263
2264                 buf = mdd_buf_get_const(env, target_name, sym_len);
2265                 rc = dt_declare_record_write(env, mdd_object_child(c),
2266                                              buf, 0, handle);
2267                 if (rc)
2268                         GOTO(out, rc);
2269         }
2270
2271         if (spec->sp_cr_file_secctx_name != NULL) {
2272                 buf = mdd_buf_get_const(env, spec->sp_cr_file_secctx,
2273                                         spec->sp_cr_file_secctx_size);
2274                 rc = mdo_declare_xattr_set(env, c, buf,
2275                                            spec->sp_cr_file_secctx_name, 0,
2276                                            handle);
2277                 if (rc < 0)
2278                         GOTO(out, rc);
2279         }
2280 out:
2281         return rc;
2282 }
2283
2284 static int mdd_declare_create(const struct lu_env *env, struct mdd_device *mdd,
2285                               struct mdd_object *p, struct mdd_object *c,
2286                               const struct lu_name *name,
2287                               struct lu_attr *attr,
2288                               struct thandle *handle,
2289                               const struct md_op_spec *spec,
2290                               struct linkea_data *ldata,
2291                               struct lu_buf *def_acl_buf,
2292                               struct lu_buf *acl_buf,
2293                               struct dt_allocation_hint *hint)
2294 {
2295         int rc;
2296
2297         rc = mdd_declare_create_object(env, mdd, p, c, attr, handle, spec,
2298                                        def_acl_buf, acl_buf, hint);
2299         if (rc)
2300                 GOTO(out, rc);
2301
2302         if (S_ISDIR(attr->la_mode)) {
2303                 rc = mdo_declare_ref_add(env, p, handle);
2304                 if (rc)
2305                         GOTO(out, rc);
2306         }
2307
2308         if (unlikely(spec->sp_cr_flags & MDS_OPEN_VOLATILE)) {
2309                 rc = orph_declare_index_insert(env, c, attr->la_mode, handle);
2310                 if (rc)
2311                         GOTO(out, rc);
2312         } else {
2313                 struct lu_attr  *la = &mdd_env_info(env)->mti_la_for_fix;
2314
2315                 rc = mdo_declare_index_insert(env, p, mdo2fid(c), attr->la_mode,
2316                                               name->ln_name, handle);
2317                 if (rc != 0)
2318                         return rc;
2319
2320                 rc = mdd_declare_links_add(env, c, handle, ldata);
2321                 if (rc)
2322                         return rc;
2323
2324                 *la = *attr;
2325                 la->la_valid = LA_CTIME | LA_MTIME;
2326                 rc = mdo_declare_attr_set(env, p, la, handle);
2327                 if (rc)
2328                         return rc;
2329
2330                 rc = mdd_declare_changelog_store(env, mdd, name, NULL, handle);
2331                 if (rc)
2332                         return rc;
2333         }
2334 out:
2335         return rc;
2336 }
2337
2338 static int mdd_acl_init(const struct lu_env *env, struct mdd_object *pobj,
2339                         struct lu_attr *la, struct lu_buf *def_acl_buf,
2340                         struct lu_buf *acl_buf)
2341 {
2342         int     rc;
2343         ENTRY;
2344
2345         if (S_ISLNK(la->la_mode)) {
2346                 acl_buf->lb_len = 0;
2347                 def_acl_buf->lb_len = 0;
2348                 RETURN(0);
2349         }
2350
2351         mdd_read_lock(env, pobj, MOR_TGT_PARENT);
2352         rc = mdo_xattr_get(env, pobj, def_acl_buf,
2353                            XATTR_NAME_ACL_DEFAULT);
2354         mdd_read_unlock(env, pobj);
2355         if (rc > 0) {
2356                 /* If there are default ACL, fix mode/ACL by default ACL */
2357                 def_acl_buf->lb_len = rc;
2358                 LASSERT(def_acl_buf->lb_len <= acl_buf->lb_len);
2359                 memcpy(acl_buf->lb_buf, def_acl_buf->lb_buf, rc);
2360                 acl_buf->lb_len = rc;
2361                 rc = __mdd_fix_mode_acl(env, acl_buf, &la->la_mode);
2362                 if (rc < 0)
2363                         RETURN(rc);
2364         } else if (rc == -ENODATA || rc == -EOPNOTSUPP) {
2365                 /* If there are no default ACL, fix mode by mask */
2366                 struct lu_ucred *uc = lu_ucred(env);
2367
2368                 /* The create triggered by MDT internal events, such as
2369                  * LFSCK reset, will not contain valid "uc". */
2370                 if (unlikely(uc != NULL))
2371                         la->la_mode &= ~uc->uc_umask;
2372                 rc = 0;
2373                 acl_buf->lb_len = 0;
2374                 def_acl_buf->lb_len = 0;
2375         }
2376
2377         RETURN(rc);
2378 }
2379
2380 /**
2381  * Create a metadata object and initialize it, set acl, xattr.
2382  **/
2383 static int mdd_create_object(const struct lu_env *env, struct mdd_object *pobj,
2384                              struct mdd_object *son, struct lu_attr *attr,
2385                              struct md_op_spec *spec, struct lu_buf *acl_buf,
2386                              struct lu_buf *def_acl_buf,
2387                              struct dt_allocation_hint *hint,
2388                              struct thandle *handle)
2389 {
2390         const struct lu_buf *buf;
2391         int rc;
2392
2393         mdd_write_lock(env, son, MOR_TGT_CHILD);
2394         rc = mdd_create_object_internal(env, NULL, son, attr, handle, spec,
2395                                         hint);
2396         if (rc)
2397                 GOTO(unlock, rc);
2398
2399         /* Note: In DNE phase I, for striped dir, though sub-stripes will be
2400          * created in declare phase, they also needs to be added to master
2401          * object as sub-directory entry. So it has to initialize the master
2402          * object, then set dir striped EA.(in mdo_xattr_set) */
2403         rc = mdd_object_initialize(env, mdo2fid(pobj), son, attr, handle,
2404                                    spec);
2405         if (rc != 0)
2406                 GOTO(err_destroy, rc);
2407
2408         /*
2409          * in case of replay we just set LOVEA provided by the client
2410          * XXX: I think it would be interesting to try "old" way where
2411          *      MDT calls this xattr_set(LOV) in a different transaction.
2412          *      probably this way we code can be made better.
2413          */
2414
2415         /* During creation, there are only a few cases we need do xattr_set to
2416          * create stripes.
2417          * 1. regular file: see comments above.
2418          * 2. dir: inherit default striping or pool settings from parent.
2419          * 3. create striped directory with provided stripeEA.
2420          * 4. create striped directory because inherit default layout from the
2421          * parent.
2422          */
2423         if (spec->no_create ||
2424             (S_ISREG(attr->la_mode) && spec->sp_cr_flags & MDS_OPEN_HAS_EA) ||
2425             S_ISDIR(attr->la_mode)) {
2426                 buf = mdd_buf_get_const(env, spec->u.sp_ea.eadata,
2427                                         spec->u.sp_ea.eadatalen);
2428                 rc = mdo_xattr_set(env, son, buf,
2429                                    S_ISDIR(attr->la_mode) ? XATTR_NAME_LMV :
2430                                                             XATTR_NAME_LOV, 0,
2431                                    handle);
2432                 if (rc != 0)
2433                         GOTO(err_destroy, rc);
2434         }
2435
2436 #ifdef CONFIG_FS_POSIX_ACL
2437         if (def_acl_buf != NULL && def_acl_buf->lb_len > 0 &&
2438             S_ISDIR(attr->la_mode)) {
2439                 /* set default acl */
2440                 rc = mdo_xattr_set(env, son, def_acl_buf,
2441                                    XATTR_NAME_ACL_DEFAULT, 0,
2442                                    handle);
2443                 if (rc)
2444                         GOTO(err_destroy, rc);
2445         }
2446         /* set its own acl */
2447         if (acl_buf != NULL && acl_buf->lb_len > 0) {
2448                 rc = mdo_xattr_set(env, son, acl_buf,
2449                                    XATTR_NAME_ACL_ACCESS,
2450                                    0, handle);
2451                 if (rc)
2452                         GOTO(err_destroy, rc);
2453         }
2454 #endif
2455
2456         if (S_ISLNK(attr->la_mode)) {
2457                 struct lu_ucred  *uc = lu_ucred_assert(env);
2458                 struct dt_object *dt = mdd_object_child(son);
2459                 const char *target_name = spec->u.sp_symname;
2460                 int sym_len = strlen(target_name);
2461                 loff_t pos = 0;
2462
2463                 buf = mdd_buf_get_const(env, target_name, sym_len);
2464                 rc = dt->do_body_ops->dbo_write(env, dt, buf, &pos, handle,
2465                                                 uc->uc_cap &
2466                                                 CFS_CAP_SYS_RESOURCE_MASK);
2467
2468                 if (rc == sym_len)
2469                         rc = 0;
2470                 else
2471                         GOTO(err_initlized, rc = -EFAULT);
2472         }
2473
2474         if (spec->sp_cr_file_secctx_name != NULL) {
2475                 buf = mdd_buf_get_const(env, spec->sp_cr_file_secctx,
2476                                         spec->sp_cr_file_secctx_size);
2477                 rc = mdo_xattr_set(env, son, buf, spec->sp_cr_file_secctx_name,
2478                                    0, handle);
2479                 if (rc < 0)
2480                         GOTO(err_initlized, rc);
2481         }
2482
2483 err_initlized:
2484         if (unlikely(rc != 0)) {
2485                 int rc2;
2486                 if (S_ISDIR(attr->la_mode)) {
2487                         /* Drop the reference, no need to delete "."/"..",
2488                          * because the object to be destroied directly. */
2489                         rc2 = mdo_ref_del(env, son, handle);
2490                         if (rc2 != 0)
2491                                 GOTO(unlock, rc);
2492                 }
2493                 rc2 = mdo_ref_del(env, son, handle);
2494                 if (rc2 != 0)
2495                         GOTO(unlock, rc);
2496 err_destroy:
2497                 mdo_destroy(env, son, handle);
2498         }
2499 unlock:
2500         mdd_write_unlock(env, son);
2501         RETURN(rc);
2502 }
2503
2504 static int mdd_index_delete(const struct lu_env *env,
2505                             struct mdd_object *mdd_pobj,
2506                             struct lu_attr *cattr,
2507                             const struct lu_name *lname)
2508 {
2509         struct mdd_device *mdd = mdo2mdd(&mdd_pobj->mod_obj);
2510         struct thandle *handle;
2511         int rc;
2512         ENTRY;
2513
2514         handle = mdd_trans_create(env, mdd);
2515         if (IS_ERR(handle))
2516                 RETURN(PTR_ERR(handle));
2517
2518         rc = mdo_declare_index_delete(env, mdd_pobj, lname->ln_name,
2519                                       handle);
2520         if (rc != 0)
2521                 GOTO(stop, rc);
2522
2523         if (S_ISDIR(cattr->la_mode)) {
2524                 rc = mdo_declare_ref_del(env, mdd_pobj, handle);
2525                 if (rc != 0)
2526                         GOTO(stop, rc);
2527         }
2528
2529         /* Since this will only be used in the error handler path,
2530          * Let's set the thandle to be local and not mess the transno */
2531         handle->th_local = 1;
2532         rc = mdd_trans_start(env, mdd, handle);
2533         if (rc)
2534                 GOTO(stop, rc);
2535
2536         rc = __mdd_index_delete(env, mdd_pobj, lname->ln_name,
2537                                 S_ISDIR(cattr->la_mode), handle);
2538         if (rc)
2539                 GOTO(stop, rc);
2540 stop:
2541         rc = mdd_trans_stop(env, mdd, rc, handle);
2542
2543         RETURN(rc);
2544 }
2545
2546 /**
2547  * Create object and insert it into namespace.
2548  *
2549  * Two operations have to be performed:
2550  *
2551  *  - an allocation of a new object (->do_create()), and
2552  *  - an insertion into a parent index (->dio_insert()).
2553  *
2554  * Due to locking, operation order is not important, when both are
2555  * successful, *but* error handling cases are quite different:
2556  *
2557  *  - if insertion is done first, and following object creation fails,
2558  *  insertion has to be rolled back, but this operation might fail
2559  *  also leaving us with dangling index entry.
2560  *
2561  *  - if creation is done first, is has to be undone if insertion fails,
2562  *  leaving us with leaked space, which is not good but not fatal.
2563  *
2564  * It seems that creation-first is simplest solution, but it is sub-optimal
2565  * in the frequent
2566  *
2567  * $ mkdir foo
2568  * $ mkdir foo
2569  *
2570  * case, because second mkdir is bound to create object, only to
2571  * destroy it immediately.
2572  *
2573  * To avoid this follow local file systems that do double lookup:
2574  *
2575  * 0. lookup -> -EEXIST (mdd_create_sanity_check())
2576  * 1. create            (mdd_create_object_internal())
2577  * 2. insert            (__mdd_index_insert(), lookup again)
2578  *
2579  * \param[in] pobj      parent object
2580  * \param[in] lname     name of child being created
2581  * \param[in,out] child child object being created
2582  * \param[in] spec      additional create parameters
2583  * \param[in] ma        attributes for new child object
2584  *
2585  * \retval              0 on success
2586  * \retval              negative errno on failure
2587  */
2588 static int mdd_create(const struct lu_env *env, struct md_object *pobj,
2589                       const struct lu_name *lname, struct md_object *child,
2590                       struct md_op_spec *spec, struct md_attr *ma)
2591 {
2592         struct mdd_thread_info  *info = mdd_env_info(env);
2593         struct lu_attr          *la = &info->mti_la_for_fix;
2594         struct mdd_object       *mdd_pobj = md2mdd_obj(pobj);
2595         struct mdd_object       *son = md2mdd_obj(child);
2596         struct mdd_device       *mdd = mdo2mdd(pobj);
2597         struct lu_attr          *attr = &ma->ma_attr;
2598         struct thandle          *handle;
2599         struct lu_attr          *pattr = &info->mti_pattr;
2600         struct lu_buf           acl_buf;
2601         struct lu_buf           def_acl_buf;
2602         struct linkea_data      *ldata = &info->mti_link_data;
2603         const char              *name = lname->ln_name;
2604         struct dt_allocation_hint *hint = &mdd_env_info(env)->mti_hint;
2605         int                      rc;
2606         int                      rc2;
2607         ENTRY;
2608
2609         rc = mdd_la_get(env, mdd_pobj, pattr);
2610         if (rc != 0)
2611                 RETURN(rc);
2612
2613         /* Sanity checks before big job. */
2614         rc = mdd_create_sanity_check(env, pobj, pattr, lname, attr, spec);
2615         if (rc)
2616                 RETURN(rc);
2617
2618         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_DQACQ_NET))
2619                 GOTO(out_free, rc = -EINPROGRESS);
2620
2621         handle = mdd_trans_create(env, mdd);
2622         if (IS_ERR(handle))
2623                 GOTO(out_free, rc = PTR_ERR(handle));
2624
2625         lu_buf_check_and_alloc(&info->mti_xattr_buf,
2626                                mdd->mdd_dt_conf.ddp_max_ea_size);
2627         acl_buf = info->mti_xattr_buf;
2628         def_acl_buf.lb_buf = info->mti_key;
2629         def_acl_buf.lb_len = sizeof(info->mti_key);
2630         rc = mdd_acl_init(env, mdd_pobj, attr, &def_acl_buf, &acl_buf);
2631         if (rc < 0)
2632                 GOTO(out_stop, rc);
2633
2634         mdd_object_make_hint(env, mdd_pobj, son, attr, spec, hint);
2635
2636         memset(ldata, 0, sizeof(*ldata));
2637         if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_BAD_PARENT)) {
2638                 struct lu_fid tfid = *mdd_object_fid(mdd_pobj);
2639
2640                 tfid.f_oid--;
2641                 rc = mdd_linkea_prepare(env, son, NULL, NULL,
2642                                         &tfid, lname, 1, 0, ldata);
2643         } else {
2644                 rc = mdd_linkea_prepare(env, son, NULL, NULL,
2645                                         mdd_object_fid(mdd_pobj),
2646                                         lname, 1, 0, ldata);
2647         }
2648
2649         rc = mdd_declare_create(env, mdd, mdd_pobj, son, lname, attr,
2650                                 handle, spec, ldata, &def_acl_buf, &acl_buf,
2651                                 hint);
2652         if (rc)
2653                 GOTO(out_stop, rc);
2654
2655         rc = mdd_trans_start(env, mdd, handle);
2656         if (rc)
2657                 GOTO(out_stop, rc);
2658
2659         rc = mdd_create_object(env, mdd_pobj, son, attr, spec, &acl_buf,
2660                                &def_acl_buf, hint, handle);
2661         if (rc != 0)
2662                 GOTO(out_stop, rc);
2663
2664         if (unlikely(spec->sp_cr_flags & MDS_OPEN_VOLATILE)) {
2665                 mdd_write_lock(env, son, MOR_TGT_CHILD);
2666                 son->mod_flags |= VOLATILE_OBJ;
2667                 rc = __mdd_orphan_add(env, son, handle);
2668                 GOTO(out_volatile, rc);
2669         } else {
2670                 rc = __mdd_index_insert(env, mdd_pobj, mdo2fid(son),
2671                                         attr->la_mode, name, handle);
2672                 if (rc != 0)
2673                         GOTO(err_created, rc);
2674
2675                 mdd_links_add(env, son, mdo2fid(mdd_pobj), lname, handle,
2676                               ldata, 1);
2677
2678                 /* update parent directory mtime/ctime */
2679                 *la = *attr;
2680                 la->la_valid = LA_CTIME | LA_MTIME;
2681                 rc = mdd_update_time(env, mdd_pobj, pattr, la, handle);
2682                 if (rc)
2683                         GOTO(err_insert, rc);
2684         }
2685
2686         EXIT;
2687 err_insert:
2688         if (rc != 0) {
2689                 if (spec->sp_cr_flags & MDS_OPEN_VOLATILE)
2690                         rc2 = __mdd_orphan_del(env, son, handle);
2691                 else
2692                         rc2 = __mdd_index_delete(env, mdd_pobj, name,
2693                                                  S_ISDIR(attr->la_mode),
2694                                                  handle);
2695                 if (rc2 != 0)
2696                         goto out_stop;
2697
2698 err_created:
2699                 mdd_write_lock(env, son, MOR_TGT_CHILD);
2700                 if (S_ISDIR(attr->la_mode)) {
2701                         /* Drop the reference, no need to delete "."/"..",
2702                          * because the object is to be destroyed directly. */
2703                         rc2 = mdo_ref_del(env, son, handle);
2704                         if (rc2 != 0) {
2705                                 mdd_write_unlock(env, son);
2706                                 goto out_stop;
2707                         }
2708                 }
2709 out_volatile:
2710                 /* For volatile files drop one link immediately, since there is
2711                  * no filename in the namespace, and save any error returned. */
2712                 rc2 = mdo_ref_del(env, son, handle);
2713                 if (rc2 != 0) {
2714                         mdd_write_unlock(env, son);
2715                         if (unlikely(rc == 0))
2716                                 rc = rc2;
2717                         goto out_stop;
2718                 }
2719
2720                 /* Don't destroy the volatile object on success */
2721                 if (likely(rc != 0))
2722                         mdo_destroy(env, son, handle);
2723                 mdd_write_unlock(env, son);
2724         }
2725
2726         if (rc == 0 && fid_is_namespace_visible(mdo2fid(son)) &&
2727             likely((spec->sp_cr_flags & MDS_OPEN_VOLATILE) == 0))
2728                 rc = mdd_changelog_ns_store(env, mdd,
2729                                 S_ISDIR(attr->la_mode) ? CL_MKDIR :
2730                                 S_ISREG(attr->la_mode) ? CL_CREATE :
2731                                 S_ISLNK(attr->la_mode) ? CL_SOFTLINK : CL_MKNOD,
2732                                 0, son, mdo2fid(mdd_pobj), NULL, NULL, lname,
2733                                 NULL, handle);
2734 out_stop:
2735         rc2 = mdd_trans_stop(env, mdd, rc, handle);
2736         if (rc == 0) {
2737                 /* If creation fails, it is most likely due to the remote update
2738                  * failure, because local transaction will mostly succeed at
2739                  * this stage. There is no easy way to rollback all of previous
2740                  * updates, so let's remove the object from namespace, and
2741                  * LFSCK should handle the orphan object. */
2742                 if (rc2 < 0 && !mdd_object_remote(mdd_pobj))
2743                         mdd_index_delete(env, mdd_pobj, attr, lname);
2744                 rc = rc2;
2745         }
2746 out_free:
2747         if (is_vmalloc_addr(ldata->ld_buf))
2748                 /* if we vmalloced a large buffer drop it */
2749                 lu_buf_free(ldata->ld_buf);
2750
2751         /* The child object shouldn't be cached anymore */
2752         if (rc)
2753                 set_bit(LU_OBJECT_HEARD_BANSHEE,
2754                         &child->mo_lu.lo_header->loh_flags);
2755         return rc;
2756 }
2757
2758 /*
2759  * Get locks on parents in proper order
2760  * RETURN: < 0 - error, rename_order if successful
2761  */
2762 enum rename_order {
2763         MDD_RN_SAME,
2764         MDD_RN_SRCTGT,
2765         MDD_RN_TGTSRC
2766 };
2767
2768 static int mdd_rename_order(const struct lu_env *env,
2769                             struct mdd_device *mdd,
2770                             struct mdd_object *src_pobj,
2771                             const struct lu_attr *pattr,
2772                             struct mdd_object *tgt_pobj)
2773 {
2774         /* order of locking, 1 - tgt-src, 0 - src-tgt*/
2775         int rc;
2776         ENTRY;
2777
2778         if (src_pobj == tgt_pobj)
2779                 RETURN(MDD_RN_SAME);
2780
2781         /* compared the parent child relationship of src_p&tgt_p */
2782         if (lu_fid_eq(&mdd->mdd_root_fid, mdo2fid(src_pobj))){
2783                 rc = MDD_RN_SRCTGT;
2784         } else if (lu_fid_eq(&mdd->mdd_root_fid, mdo2fid(tgt_pobj))) {
2785                 rc = MDD_RN_TGTSRC;
2786         } else {
2787                 rc = mdd_is_parent(env, mdd, src_pobj, pattr, mdo2fid(tgt_pobj),
2788                                    NULL);
2789                 if (rc == -EREMOTE)
2790                         rc = 0;
2791
2792                 if (rc == 1)
2793                         rc = MDD_RN_TGTSRC;
2794                 else if (rc == 0)
2795                         rc = MDD_RN_SRCTGT;
2796         }
2797
2798         RETURN(rc);
2799 }
2800
2801 /* has not mdd_write{read}_lock on any obj yet. */
2802 static int mdd_rename_sanity_check(const struct lu_env *env,
2803                                    struct mdd_object *src_pobj,
2804                                    const struct lu_attr *pattr,
2805                                    struct mdd_object *tgt_pobj,
2806                                    const struct lu_attr *tpattr,
2807                                    struct mdd_object *sobj,
2808                                    const struct lu_attr *cattr,
2809                                    struct mdd_object *tobj,
2810                                    const struct lu_attr *tattr)
2811 {
2812         int rc = 0;
2813         ENTRY;
2814
2815         /* XXX: when get here, sobj must NOT be NULL,
2816          * the other case has been processed in cld_rename
2817          * before mdd_rename and enable MDS_PERM_BYPASS. */
2818         LASSERT(sobj);
2819
2820         /*
2821          * If we are using project inheritance, we only allow renames
2822          * into our tree when the project IDs are the same; otherwise
2823          * tree quota mechanism would be circumvented.
2824          */
2825         if (((tpattr->la_flags & LUSTRE_PROJINHERIT_FL) &&
2826             tpattr->la_projid != cattr->la_projid) ||
2827             ((pattr->la_flags & LUSTRE_PROJINHERIT_FL) &&
2828             (pattr->la_projid != tpattr->la_projid)))
2829                 RETURN(-EXDEV);
2830
2831         rc = mdd_may_delete(env, src_pobj, pattr, sobj, cattr, NULL, 1, 0);
2832         if (rc)
2833                 RETURN(rc);
2834
2835         /* XXX: when get here, "tobj == NULL" means tobj must
2836          * NOT exist (neither on remote MDS, such case has been
2837          * processed in cld_rename before mdd_rename and enable
2838          * MDS_PERM_BYPASS).
2839          * So check may_create, but not check may_unlink. */
2840         if (tobj == NULL)
2841                 rc = mdd_may_create(env, tgt_pobj, tpattr, NULL,
2842                                     (src_pobj != tgt_pobj));
2843         else
2844                 rc = mdd_may_delete(env, tgt_pobj, tpattr, tobj, tattr, cattr,
2845                                     (src_pobj != tgt_pobj), 1);
2846
2847         if (!rc && !tobj && (src_pobj != tgt_pobj) && S_ISDIR(cattr->la_mode))
2848                 rc = __mdd_may_link(env, tgt_pobj, tpattr);
2849
2850         RETURN(rc);
2851 }
2852
2853 static int mdd_declare_rename(const struct lu_env *env,
2854                               struct mdd_device *mdd,
2855                               struct mdd_object *mdd_spobj,
2856                               struct mdd_object *mdd_tpobj,
2857                               struct mdd_object *mdd_sobj,
2858                               struct mdd_object *mdd_tobj,
2859                               const struct lu_name *sname,
2860                               const struct lu_name *tname,
2861                               struct md_attr *ma,
2862                               struct linkea_data *ldata,
2863                               struct thandle *handle)
2864 {
2865         struct lu_attr    *la = &mdd_env_info(env)->mti_la_for_fix;
2866         int rc;
2867
2868         LASSERT(ma->ma_attr.la_valid & LA_CTIME);
2869         la->la_ctime = la->la_mtime = ma->ma_attr.la_ctime;
2870
2871         LASSERT(mdd_spobj);
2872         LASSERT(mdd_tpobj);
2873         LASSERT(mdd_sobj);
2874
2875         /* name from source dir */
2876         rc = mdo_declare_index_delete(env, mdd_spobj, sname->ln_name, handle);
2877         if (rc)
2878                 return rc;
2879
2880         /* .. from source child */
2881         if (S_ISDIR(mdd_object_type(mdd_sobj))) {
2882                 /* source child can be directory,
2883                  * counted by source dir's nlink */
2884                 rc = mdo_declare_ref_del(env, mdd_spobj, handle);
2885                 if (rc)
2886                         return rc;
2887                 if (mdd_spobj != mdd_tpobj) {
2888                         rc = mdo_declare_index_delete(env, mdd_sobj, dotdot,
2889                                                       handle);
2890                         if (rc != 0)
2891                                 return rc;
2892
2893                         rc = mdo_declare_index_insert(env, mdd_sobj,
2894                                                       mdo2fid(mdd_tpobj),
2895                                                       S_IFDIR, dotdot, handle);
2896                         if (rc != 0)
2897                                 return rc;
2898                 }
2899
2900                 /* new target child can be directory,
2901                  * counted by target dir's nlink */
2902                 rc = mdo_declare_ref_add(env, mdd_tpobj, handle);
2903                 if (rc != 0)
2904                         return rc;
2905         }
2906
2907         la->la_valid = LA_CTIME | LA_MTIME;
2908         rc = mdo_declare_attr_set(env, mdd_spobj, la, handle);
2909         if (rc != 0)
2910                 return rc;
2911
2912         rc = mdo_declare_attr_set(env, mdd_tpobj, la, handle);
2913         if (rc != 0)
2914                 return rc;
2915
2916         la->la_valid = LA_CTIME;
2917         rc = mdo_declare_attr_set(env, mdd_sobj, la, handle);
2918         if (rc)
2919                 return rc;
2920
2921         rc = mdd_declare_links_add(env, mdd_sobj, handle, ldata);
2922         if (rc)
2923                 return rc;
2924
2925         /* new name */
2926         rc = mdo_declare_index_insert(env, mdd_tpobj, mdo2fid(mdd_sobj),
2927                                       mdd_object_type(mdd_sobj),
2928                                       tname->ln_name, handle);
2929         if (rc != 0)
2930                 return rc;
2931
2932         if (mdd_tobj && mdd_object_exists(mdd_tobj)) {
2933                 /* delete target child in target parent directory */
2934                 rc = mdo_declare_index_delete(env, mdd_tpobj, tname->ln_name,
2935                                               handle);
2936                 if (rc)
2937                         return rc;
2938
2939                 rc = mdo_declare_ref_del(env, mdd_tobj, handle);
2940                 if (rc)
2941                         return rc;
2942
2943                 if (S_ISDIR(mdd_object_type(mdd_tobj))) {
2944                         /* target child can be directory,
2945                          * delete "." reference in target child directory */
2946                         rc = mdo_declare_ref_del(env, mdd_tobj, handle);
2947                         if (rc)
2948                                 return rc;
2949
2950                         /* delete ".." reference in target parent directory */
2951                         rc = mdo_declare_ref_del(env, mdd_tpobj, handle);
2952                         if (rc)
2953                                 return rc;
2954                 }
2955
2956                 la->la_valid = LA_CTIME;
2957                 rc = mdo_declare_attr_set(env, mdd_tobj, la, handle);
2958                 if (rc)
2959                         return rc;
2960
2961                 rc = mdd_declare_finish_unlink(env, mdd_tobj, handle);
2962                 if (rc)
2963                         return rc;
2964         }
2965
2966         rc = mdd_declare_changelog_store(env, mdd, tname, sname, handle);
2967         if (rc)
2968                 return rc;
2969
2970         return rc;
2971 }
2972
2973 /* src object can be remote that is why we use only fid and type of object */
2974 static int mdd_rename(const struct lu_env *env,
2975                       struct md_object *src_pobj, struct md_object *tgt_pobj,
2976                       const struct lu_fid *lf, const struct lu_name *lsname,
2977                       struct md_object *tobj, const struct lu_name *ltname,
2978                       struct md_attr *ma)
2979 {
2980         const char *sname = lsname->ln_name;
2981         const char *tname = ltname->ln_name;
2982         struct lu_attr    *la = &mdd_env_info(env)->mti_la_for_fix;
2983         struct mdd_object *mdd_spobj = md2mdd_obj(src_pobj); /* source parent */
2984         struct mdd_object *mdd_tpobj = md2mdd_obj(tgt_pobj);
2985         struct mdd_device *mdd = mdo2mdd(src_pobj);
2986         struct mdd_object *mdd_sobj = NULL;                  /* source object */
2987         struct mdd_object *mdd_tobj = NULL;
2988         struct lu_attr *cattr = MDD_ENV_VAR(env, cattr);
2989         struct lu_attr *pattr = MDD_ENV_VAR(env, pattr);
2990         struct lu_attr *tattr = MDD_ENV_VAR(env, tattr);
2991         struct lu_attr *tpattr = MDD_ENV_VAR(env, tpattr);
2992         struct thandle *handle;
2993         struct linkea_data  *ldata = &mdd_env_info(env)->mti_link_data;
2994         const struct lu_fid *tpobj_fid = mdo2fid(mdd_tpobj);
2995         const struct lu_fid *spobj_fid = mdo2fid(mdd_spobj);
2996         bool is_dir;
2997         bool tobj_ref = 0;
2998         bool tobj_locked = 0;
2999         unsigned cl_flags = 0;
3000         int rc, rc2;
3001         ENTRY;
3002
3003         if (tobj)
3004                 mdd_tobj = md2mdd_obj(tobj);
3005
3006         mdd_sobj = mdd_object_find(env, mdd, lf);
3007         if (IS_ERR(mdd_sobj))
3008                 RETURN(PTR_ERR(mdd_sobj));
3009
3010         rc = mdd_la_get(env, mdd_sobj, cattr);
3011         if (rc)
3012                 GOTO(out_pending, rc);
3013
3014         rc = mdd_la_get(env, mdd_spobj, pattr);
3015         if (rc)
3016                 GOTO(out_pending, rc);
3017
3018         if (mdd_tobj) {
3019                 rc = mdd_la_get(env, mdd_tobj, tattr);
3020                 if (rc)
3021                         GOTO(out_pending, rc);
3022                 /* search for an existing archive.
3023                  * we should check ahead as the object
3024                  * can be destroyed in this transaction */
3025                 if (mdd_hsm_archive_exists(env, mdd_tobj, ma))
3026                         cl_flags |= CLF_RENAME_LAST_EXISTS;
3027         }
3028
3029         rc = mdd_la_get(env, mdd_tpobj, tpattr);
3030         if (rc)
3031                 GOTO(out_pending, rc);
3032
3033         rc = mdd_rename_sanity_check(env, mdd_spobj, pattr, mdd_tpobj, tpattr,
3034                                      mdd_sobj, cattr, mdd_tobj, tattr);
3035         if (rc)
3036                 GOTO(out_pending, rc);
3037
3038         rc = mdd_name_check(mdd, ltname);
3039         if (rc < 0)
3040                 GOTO(out_pending, rc);
3041
3042         /* FIXME: Should consider tobj and sobj too in rename_lock. */
3043         rc = mdd_rename_order(env, mdd, mdd_spobj, pattr, mdd_tpobj);
3044         if (rc < 0)
3045                 GOTO(out_pending, rc);
3046
3047         handle = mdd_trans_create(env, mdd);
3048         if (IS_ERR(handle))
3049                 GOTO(out_pending, rc = PTR_ERR(handle));
3050
3051         memset(ldata, 0, sizeof(*ldata));
3052         rc = mdd_linkea_prepare(env, mdd_sobj, mdd_object_fid(mdd_spobj),
3053                                 lsname, mdd_object_fid(mdd_tpobj), ltname,
3054                                 1, 0, ldata);
3055         if (rc)
3056                 GOTO(stop, rc);
3057
3058         rc = mdd_declare_rename(env, mdd, mdd_spobj, mdd_tpobj, mdd_sobj,
3059                                 mdd_tobj, lsname, ltname, ma, ldata, handle);
3060         if (rc)
3061                 GOTO(stop, rc);
3062
3063         rc = mdd_trans_start(env, mdd, handle);
3064         if (rc)
3065                 GOTO(stop, rc);
3066
3067         is_dir = S_ISDIR(cattr->la_mode);
3068
3069         /* Remove source name from source directory */
3070         rc = __mdd_index_delete(env, mdd_spobj, sname, is_dir, handle);
3071         if (rc != 0)
3072                 GOTO(stop, rc);
3073
3074         /* "mv dir1 dir2" needs "dir1/.." link update */
3075         if (is_dir && !lu_fid_eq(spobj_fid, tpobj_fid)) {
3076                 rc = __mdd_index_delete_only(env, mdd_sobj, dotdot, handle);
3077                 if (rc != 0)
3078                         GOTO(fixup_spobj2, rc);
3079
3080                 rc = __mdd_index_insert_only(env, mdd_sobj, tpobj_fid, S_IFDIR,
3081                                              dotdot, handle);
3082                 if (rc != 0)
3083                         GOTO(fixup_spobj, rc);
3084         }
3085
3086         if (mdd_tobj != NULL && mdd_object_exists(mdd_tobj)) {
3087                 rc = __mdd_index_delete(env, mdd_tpobj, tname, is_dir, handle);
3088                 if (rc != 0)
3089                         /* tname might been renamed to something else */
3090                         GOTO(fixup_spobj, rc);
3091         }
3092
3093         /* Insert new fid with target name into target dir */
3094         rc = __mdd_index_insert(env, mdd_tpobj, lf, cattr->la_mode,
3095                                 tname, handle);
3096         if (rc != 0)
3097                 GOTO(fixup_tpobj, rc);
3098
3099         LASSERT(ma->ma_attr.la_valid & LA_CTIME);
3100         la->la_ctime = la->la_mtime = ma->ma_attr.la_ctime;
3101
3102         /* XXX: mdd_sobj must be local one if it is NOT NULL. */
3103         la->la_valid = LA_CTIME;
3104         rc = mdd_update_time(env, mdd_sobj, cattr, la, handle);
3105         if (rc)
3106                 GOTO(fixup_tpobj, rc);
3107
3108         /* Update the linkEA for the source object */
3109         mdd_write_lock(env, mdd_sobj, MOR_SRC_CHILD);
3110         rc = mdd_links_rename(env, mdd_sobj, mdo2fid(mdd_spobj), lsname,
3111                               mdo2fid(mdd_tpobj), ltname, handle, ldata,
3112                               0, 0);
3113         if (rc == -ENOENT)
3114                 /* Old files might not have EA entry */
3115                 mdd_links_add(env, mdd_sobj, mdo2fid(mdd_spobj),
3116                               lsname, handle, NULL, 0);
3117         mdd_write_unlock(env, mdd_sobj);
3118         /* We don't fail the transaction if the link ea can't be
3119            updated -- fid2path will use alternate lookup method. */
3120         rc = 0;
3121
3122         /* Remove old target object
3123          * For tobj is remote case cmm layer has processed
3124          * and set tobj to NULL then. So when tobj is NOT NULL,
3125          * it must be local one.
3126          */
3127         if (tobj && mdd_object_exists(mdd_tobj)) {
3128                 mdd_write_lock(env, mdd_tobj, MOR_TGT_CHILD);
3129                 tobj_locked = 1;
3130                 if (mdd_is_dead_obj(mdd_tobj)) {
3131                         /* shld not be dead, something is wrong */
3132                         CERROR("tobj is dead, something is wrong\n");
3133                         rc = -EINVAL;
3134                         goto cleanup;
3135                 }
3136                 mdo_ref_del(env, mdd_tobj, handle);
3137
3138                 /* Remove dot reference. */
3139                 if (S_ISDIR(tattr->la_mode))
3140                         mdo_ref_del(env, mdd_tobj, handle);
3141                 tobj_ref = 1;
3142
3143                 /* fetch updated nlink */
3144                 rc = mdd_la_get(env, mdd_tobj, tattr);
3145                 if (rc != 0) {
3146                         CERROR("%s: Failed to get nlink for tobj "
3147                                 DFID": rc = %d\n",
3148                                 mdd2obd_dev(mdd)->obd_name,
3149                                 PFID(tpobj_fid), rc);
3150                         GOTO(fixup_tpobj, rc);
3151                 }
3152
3153                 la->la_valid = LA_CTIME;
3154                 rc = mdd_update_time(env, mdd_tobj, tattr, la, handle);
3155                 if (rc != 0) {
3156                         CERROR("%s: Failed to set ctime for tobj "
3157                                 DFID": rc = %d\n",
3158                                 mdd2obd_dev(mdd)->obd_name,
3159                                 PFID(tpobj_fid), rc);
3160                         GOTO(fixup_tpobj, rc);
3161                 }
3162
3163                 /* XXX: this transfer to ma will be removed with LOD/OSP */
3164                 ma->ma_attr = *tattr;
3165                 ma->ma_valid |= MA_INODE;
3166                 rc = mdd_finish_unlink(env, mdd_tobj, ma, mdd_tpobj, ltname,
3167                                        handle);
3168                 if (rc != 0) {
3169                         CERROR("%s: Failed to unlink tobj "
3170                                 DFID": rc = %d\n",
3171                                 mdd2obd_dev(mdd)->obd_name,
3172                                 PFID(tpobj_fid), rc);
3173                         GOTO(fixup_tpobj, rc);
3174                 }
3175
3176                 /* fetch updated nlink */
3177                 rc = mdd_la_get(env, mdd_tobj, tattr);
3178                 if (rc == -ENOENT) {
3179                         /* the object got removed, let's
3180                          * return the latest known attributes */
3181                         tattr->la_nlink = 0;
3182                         rc = 0;
3183                 } else if (rc != 0) {
3184                         CERROR("%s: Failed to get nlink for tobj "
3185                                 DFID": rc = %d\n",
3186                                 mdd2obd_dev(mdd)->obd_name,
3187                                 PFID(tpobj_fid), rc);
3188                         GOTO(fixup_tpobj, rc);
3189                 }
3190                 /* XXX: this transfer to ma will be removed with LOD/OSP */
3191                 ma->ma_attr = *tattr;
3192                 ma->ma_valid |= MA_INODE;
3193
3194                 if (tattr->la_nlink == 0)
3195                         cl_flags |= CLF_RENAME_LAST;
3196                 else
3197                         cl_flags &= ~CLF_RENAME_LAST_EXISTS;
3198         }
3199
3200         la->la_valid = LA_CTIME | LA_MTIME;
3201         rc = mdd_update_time(env, mdd_spobj, pattr, la, handle);
3202         if (rc)
3203                 GOTO(fixup_tpobj, rc);
3204
3205         if (mdd_spobj != mdd_tpobj) {
3206                 la->la_valid = LA_CTIME | LA_MTIME;
3207                 rc = mdd_update_time(env, mdd_tpobj, tpattr, la, handle);
3208                 if (rc != 0)
3209                         GOTO(fixup_tpobj, rc);
3210         }
3211
3212         EXIT;
3213
3214 fixup_tpobj:
3215         if (rc) {
3216                 rc2 = __mdd_index_delete(env, mdd_tpobj, tname, is_dir, handle);
3217                 if (rc2)
3218                         CWARN("tp obj fix error %d\n",rc2);
3219
3220                 if (mdd_tobj && mdd_object_exists(mdd_tobj) &&
3221                     !mdd_is_dead_obj(mdd_tobj)) {
3222                         if (tobj_ref) {
3223                                 mdo_ref_add(env, mdd_tobj, handle);
3224                                 if (is_dir)
3225                                         mdo_ref_add(env, mdd_tobj, handle);
3226                         }
3227
3228                         rc2 = __mdd_index_insert(env, mdd_tpobj,
3229                                                   mdo2fid(mdd_tobj),
3230                                                   mdd_object_type(mdd_tobj),
3231                                                   tname, handle);
3232                         if (rc2 != 0)
3233                                 CWARN("tp obj fix error: rc = %d\n", rc2);
3234                 }
3235         }
3236
3237 fixup_spobj:
3238         if (rc && is_dir && mdd_sobj && mdd_spobj != mdd_tpobj) {
3239                 rc2 = __mdd_index_delete_only(env, mdd_sobj, dotdot, handle);
3240                 if (rc2)
3241                         CWARN("%s: sp obj dotdot delete error: rc = %d\n",
3242                                mdd2obd_dev(mdd)->obd_name, rc2);
3243
3244
3245                 rc2 = __mdd_index_insert_only(env, mdd_sobj, spobj_fid, S_IFDIR,
3246                                               dotdot, handle);
3247                 if (rc2 != 0)
3248                         CWARN("%s: sp obj dotdot insert error: rc = %d\n",
3249                               mdd2obd_dev(mdd)->obd_name, rc2);
3250         }
3251
3252 fixup_spobj2:
3253         if (rc != 0) {
3254                 rc2 = __mdd_index_insert(env, mdd_spobj, lf,
3255                                          mdd_object_type(mdd_sobj), sname,
3256                                          handle);
3257                 if (rc2 != 0)
3258                         CWARN("sp obj fix error: rc = %d\n", rc2);
3259         }
3260
3261 cleanup:
3262         if (tobj_locked)
3263                 mdd_write_unlock(env, mdd_tobj);
3264
3265         if (rc == 0)
3266                 rc = mdd_changelog_ns_store(env, mdd, CL_RENAME, cl_flags,
3267                                             mdd_tobj, tpobj_fid, lf, spobj_fid,
3268                                             ltname, lsname, handle);
3269
3270 stop:
3271         rc = mdd_trans_stop(env, mdd, rc, handle);
3272
3273 out_pending:
3274         mdd_object_put(env, mdd_sobj);
3275         return rc;
3276 }
3277
3278 /**
3279  * During migration once the parent FID has been changed,
3280  * we need update the parent FID in linkea.
3281  **/
3282 static int mdd_linkea_update_child_internal(const struct lu_env *env,
3283                                             struct mdd_object *parent,
3284                                             struct mdd_object *newparent,
3285                                             struct mdd_object *child,
3286                                             const char *name, int namelen,
3287                                             struct thandle *handle,
3288                                             bool declare)
3289 {
3290         struct mdd_thread_info  *info = mdd_env_info(env);
3291         struct linkea_data      ldata = { NULL };
3292         struct lu_buf           *buf = &info->mti_link_buf;
3293         int                     count;
3294         int                     rc = 0;
3295
3296         ENTRY;
3297
3298         buf = lu_buf_check_and_alloc(buf, PATH_MAX);
3299         if (buf->lb_buf == NULL)
3300                 RETURN(-ENOMEM);
3301
3302         ldata.ld_buf = buf;
3303         rc = mdd_links_read(env, child, &ldata);
3304         if (rc != 0) {
3305                 if (rc == -ENOENT || rc == -ENODATA)
3306                         rc = 0;
3307                 RETURN(rc);
3308         }
3309
3310         LASSERT(ldata.ld_leh != NULL);
3311         ldata.ld_lee = (struct link_ea_entry *)(ldata.ld_leh + 1);
3312         for (count = 0; count < ldata.ld_leh->leh_reccount; count++) {
3313                 struct mdd_device *mdd = mdo2mdd(&child->mod_obj);
3314                 struct lu_name lname;
3315                 struct lu_fid  fid;
3316
3317                 linkea_entry_unpack(ldata.ld_lee, &ldata.ld_reclen,
3318                                     &lname, &fid);
3319
3320                 if (strncmp(lname.ln_name, name, namelen) != 0 ||
3321                     !lu_fid_eq(&fid, mdd_object_fid(parent))) {
3322                         ldata.ld_lee = (struct link_ea_entry *)
3323                                        ((char *)ldata.ld_lee +
3324                                         ldata.ld_reclen);
3325                         continue;
3326                 }
3327
3328                 CDEBUG(D_INFO, "%s: update "DFID" with %.*s:"DFID"\n",
3329                        mdd2obd_dev(mdd)->obd_name, PFID(mdd_object_fid(child)),
3330                        lname.ln_namelen, lname.ln_name,
3331                        PFID(mdd_object_fid(newparent)));
3332                 /* update to the new parent fid */
3333                 linkea_entry_pack(ldata.ld_lee, &lname,
3334                                   mdd_object_fid(newparent));
3335                 if (declare)
3336                         rc = mdd_declare_links_add(env, child, handle, &ldata);
3337                 else
3338                         rc = mdd_links_write(env, child, &ldata, handle);
3339                 break;
3340         }
3341         RETURN(rc);
3342 }
3343
3344 static int mdd_linkea_declare_update_child(const struct lu_env *env,
3345                                            struct mdd_object *parent,
3346                                            struct mdd_object *newparent,
3347                                            struct mdd_object *child,
3348                                            const char *name, int namelen,
3349                                            struct thandle *handle)
3350 {
3351         return mdd_linkea_update_child_internal(env, parent, newparent,
3352                                                 child, name,
3353                                                 namelen, handle, true);
3354 }
3355
3356 static int mdd_linkea_update_child(const struct lu_env *env,
3357                                    struct mdd_object *parent,
3358                                    struct mdd_object *newparent,
3359                                    struct mdd_object *child,
3360                                    const char *name, int namelen,
3361                                    struct thandle *handle)
3362 {
3363         return mdd_linkea_update_child_internal(env, parent, newparent,
3364                                                 child, name,
3365                                                 namelen, handle, false);
3366 }
3367
3368 static int mdd_update_linkea_internal(const struct lu_env *env,
3369                                       struct mdd_object *mdd_pobj,
3370                                       struct mdd_object *mdd_sobj,
3371                                       struct mdd_object *mdd_tobj,
3372                                       const struct lu_name *child_name,
3373                                       struct linkea_data *ldata,
3374                                       struct thandle *handle,
3375                                       int declare)
3376 {
3377         struct mdd_thread_info  *info = mdd_env_info(env);
3378         int                     count;
3379         int                     rc = 0;
3380         ENTRY;
3381
3382         LASSERT(ldata->ld_buf != NULL);
3383         LASSERT(ldata->ld_leh != NULL);
3384
3385         /* If it is mulitple links file, we need update the name entry for
3386          * all parent */
3387         ldata->ld_lee = (struct link_ea_entry *)(ldata->ld_leh + 1);
3388         for (count = 0; count < ldata->ld_leh->leh_reccount; count++) {
3389                 struct mdd_device       *mdd = mdo2mdd(&mdd_sobj->mod_obj);
3390                 struct mdd_object       *pobj;
3391                 struct lu_name          lname;
3392                 struct lu_fid           fid;
3393
3394                 linkea_entry_unpack(ldata->ld_lee, &ldata->ld_reclen,
3395                                     &lname, &fid);
3396                 pobj = mdd_object_find(env, mdd, &fid);
3397                 if (IS_ERR(pobj)) {
3398                         CWARN("%s: cannot find obj "DFID": rc = %ld\n",
3399                               mdd2obd_dev(mdd)->obd_name, PFID(&fid),
3400                               PTR_ERR(pobj));
3401                         continue;
3402                 }
3403
3404                 if (!mdd_object_exists(pobj)) {
3405                         CDEBUG(D_INFO, "%s: obj "DFID" does not exist\n",
3406                               mdd2obd_dev(mdd)->obd_name, PFID(&fid));
3407                         goto next_put;
3408                 }
3409
3410                 if (pobj == mdd_pobj &&
3411                     lname.ln_namelen == child_name->ln_namelen &&
3412                     strncmp(lname.ln_name, child_name->ln_name,
3413                             lname.ln_namelen) == 0) {
3414                         CDEBUG(D_INFO, "%s: skip its own %s: "DFID"\n",
3415                               mdd2obd_dev(mdd)->obd_name, child_name->ln_name,
3416                               PFID(&fid));
3417                         goto next_put;
3418                 }
3419
3420                 CDEBUG(D_INFO, "%s: update "DFID" with "DNAME":"DFID"\n",
3421                        mdd2obd_dev(mdd)->obd_name, PFID(mdd_object_fid(pobj)),
3422                        PNAME(&lname), PFID(mdd_object_fid(mdd_tobj)));
3423
3424                 if (declare) {
3425                         /* Remove source name from source directory */
3426                         /* Insert new fid with target name into target dir */
3427                         rc = mdo_declare_index_delete(env, pobj, lname.ln_name,
3428                                                       handle);
3429                         if (rc != 0)
3430                                 GOTO(next_put, rc);
3431
3432                         rc = mdo_declare_index_insert(env, pobj,
3433                                         mdd_object_fid(mdd_tobj),
3434                                         mdd_object_type(mdd_tobj),
3435                                         lname.ln_name, handle);
3436                         if (rc != 0)
3437                                 GOTO(next_put, rc);
3438
3439                         rc = mdo_declare_ref_add(env, mdd_tobj, handle);
3440                         if (rc)
3441                                 GOTO(next_put, rc);
3442
3443                         rc = mdo_declare_ref_del(env, mdd_sobj, handle);
3444                         if (rc)
3445                                 GOTO(next_put, rc);
3446                 } else {
3447                         char *tmp_name = info->mti_key;
3448
3449                         if (lname.ln_namelen >= sizeof(info->mti_key)) {
3450                                 /* lnamelen is too big(> NAME_MAX + 16),
3451                                  * something wrong about this linkea, let's
3452                                  * skip it */
3453                                 CWARN("%s: the name %.*s is too long under "
3454                                       DFID"\n", mdd2obd_dev(mdd)->obd_name,
3455                                       lname.ln_namelen, lname.ln_name,
3456                                       PFID(&fid));
3457                                 goto next_put;
3458                         }
3459
3460                         /* Note: lname might be without \0 at the end, see
3461                          * linkea_entry_unpack(), let's add extra \0 by
3462                          * snprintf */
3463                         snprintf(tmp_name, sizeof(info->mti_key), "%.*s",
3464                                  lname.ln_namelen, lname.ln_name);
3465                         lname.ln_name = tmp_name;
3466
3467                         /* Let's check if this linkEA still valid, before
3468                          * it might be packed into the RPC buffer. */
3469                         rc = mdd_lookup(env, &pobj->mod_obj, &lname,
3470                                         &info->mti_fid, NULL);
3471                         if (rc < 0 || !lu_fid_eq(&info->mti_fid,
3472                                                  mdd_object_fid(mdd_sobj)))
3473                                 GOTO(next_put, rc == -ENOENT ? 0 : rc);
3474
3475                         rc = __mdd_index_delete(env, pobj, tmp_name, 0, handle);
3476                         if (rc != 0)
3477                                 GOTO(next_put, rc);
3478
3479                         rc = __mdd_index_insert(env, pobj,
3480                                         mdd_object_fid(mdd_tobj),
3481                                         mdd_object_type(mdd_tobj),
3482                                         tmp_name, handle);
3483                         if (rc != 0)
3484                                 GOTO(next_put, rc);
3485
3486                         mdd_write_lock(env, mdd_tobj, MOR_SRC_CHILD);
3487                         rc = mdo_ref_add(env, mdd_tobj, handle);
3488                         mdd_write_unlock(env, mdd_tobj);
3489                         if (rc)
3490                                 GOTO(next_put, rc);
3491
3492                         mdd_write_lock(env, mdd_sobj, MOR_TGT_CHILD);
3493                         mdo_ref_del(env, mdd_sobj, handle);
3494                         mdd_write_unlock(env, mdd_sobj);
3495                 }
3496 next_put:
3497                 mdd_object_put(env, pobj);
3498                 if (rc != 0)
3499                         break;
3500
3501                 ldata->ld_lee = (struct link_ea_entry *)((char *)ldata->ld_lee +
3502                                                          ldata->ld_reclen);
3503         }
3504
3505         RETURN(rc);
3506 }
3507
3508 static int mdd_migrate_xattrs(const struct lu_env *env,
3509                               struct mdd_object *mdd_sobj,
3510                               struct mdd_object *mdd_tobj)
3511 {
3512         struct mdd_thread_info  *info = mdd_env_info(env);
3513         struct mdd_device       *mdd = mdo2mdd(&mdd_sobj->mod_obj);
3514         char                    *xname;
3515         struct thandle          *handle;
3516         struct lu_buf           xbuf;
3517         int                     xlen;
3518         int                     rem;
3519         int                     xsize;
3520         int                     list_xsize;
3521         struct lu_buf           list_xbuf;
3522         int                     rc;
3523
3524         /* retrieve xattr list from the old object */
3525         list_xsize = mdo_xattr_list(env, mdd_sobj, &LU_BUF_NULL);
3526         if (list_xsize == -ENODATA)
3527                 return 0;
3528
3529         if (list_xsize < 0)
3530                 return list_xsize;
3531
3532         lu_buf_check_and_alloc(&info->mti_big_buf, list_xsize);
3533         if (info->mti_big_buf.lb_buf == NULL)
3534                 return -ENOMEM;
3535
3536         list_xbuf.lb_buf = info->mti_big_buf.lb_buf;
3537         list_xbuf.lb_len = list_xsize;
3538         rc = mdo_xattr_list(env, mdd_sobj, &list_xbuf);
3539         if (rc < 0)
3540                 return rc;
3541         rc = 0;
3542         rem = list_xsize;
3543         xname = list_xbuf.lb_buf;
3544         while (rem > 0) {
3545                 xlen = strnlen(xname, rem - 1) + 1;
3546                 if (strcmp(XATTR_NAME_LMA, xname) == 0 ||
3547                     strcmp(XATTR_NAME_LMV, xname) == 0)
3548                         goto next;
3549
3550                 /* For directory, if there are default layout, migrate here */
3551                 if (strcmp(XATTR_NAME_LOV, xname) == 0 &&
3552                     !S_ISDIR(lu_object_attr(&mdd_sobj->mod_obj.mo_lu)))
3553                         goto next;
3554
3555                 xsize = mdo_xattr_get(env, mdd_sobj, &LU_BUF_NULL, xname);
3556                 if (xsize == -ENODATA)
3557                         goto next;
3558                 if (xsize < 0)
3559                         GOTO(out, rc);
3560
3561                 lu_buf_check_and_alloc(&info->mti_link_buf, xsize);
3562                 if (info->mti_link_buf.lb_buf == NULL)
3563                         GOTO(out, rc = -ENOMEM);
3564
3565                 xbuf.lb_len = xsize;
3566                 xbuf.lb_buf = info->mti_link_buf.lb_buf;
3567                 rc = mdo_xattr_get(env, mdd_sobj, &xbuf, xname);
3568                 if (rc == -ENODATA)
3569                         goto next;
3570                 if (rc < 0)
3571                         GOTO(out, rc);
3572
3573                 handle = mdd_trans_create(env, mdd);
3574                 if (IS_ERR(handle))
3575                         GOTO(out, rc = PTR_ERR(handle));
3576
3577                 rc = mdo_declare_xattr_set(env, mdd_tobj, &xbuf, xname, 0,
3578                                            handle);
3579                 if (rc != 0)
3580                         GOTO(stop_trans, rc);
3581                 /* Note: this transaction is part of migration, and it is not
3582                  * the last step of migration, so we set th_local = 1 to avoid
3583                  * update last rcvd for this transaction */
3584                 handle->th_local = 1;
3585                 rc = mdd_trans_start(env, mdd, handle);
3586                 if (rc != 0)
3587                         GOTO(stop_trans, rc);
3588
3589 again:
3590                 rc = mdo_xattr_set(env, mdd_tobj, &xbuf, xname, 0, handle);
3591                 if (rc == -EEXIST)
3592                         GOTO(stop_trans, rc = 0);
3593
3594                 if (unlikely(rc == -ENOSPC &&
3595                              strcmp(xname, XATTR_NAME_LINK) == 0)) {
3596                         rc = linkea_overflow_shrink(
3597                                         (struct linkea_data *)(xbuf.lb_buf));
3598                         if (likely(rc > 0)) {
3599                                 xbuf.lb_len = rc;
3600                                 goto again;
3601                         }
3602                 }
3603
3604                 if (rc != 0)
3605                         GOTO(stop_trans, rc);
3606 stop_trans:
3607                 rc = mdd_trans_stop(env, mdd, rc, handle);
3608                 if (rc != 0)
3609                         GOTO(out, rc);
3610 next:
3611                 rem -= xlen;
3612                 memmove(xname, xname + xlen, rem);
3613         }
3614 out:
3615         return rc;
3616 }
3617
3618 static int mdd_declare_migrate_create(const struct lu_env *env,
3619                                       struct mdd_object *mdd_pobj,
3620                                       struct mdd_object *mdd_sobj,
3621                                       struct mdd_object *mdd_tobj,
3622                                       struct md_op_spec *spec,
3623                                       struct lu_attr *la,
3624                                       union lmv_mds_md *mgr_ea,
3625                                       struct linkea_data *ldata,
3626                                       struct thandle *handle)
3627 {
3628         struct lu_attr          *la_flag = MDD_ENV_VAR(env, la_for_fix);
3629         const struct lu_buf     *buf;
3630         int                     rc;
3631         int                     mgr_easize;
3632
3633         rc = mdd_declare_create_object_internal(env, mdd_pobj, mdd_tobj, la,
3634                                                 handle, spec, NULL);
3635         if (rc != 0)
3636                 return rc;
3637
3638         rc = mdd_declare_object_initialize(env, mdd_pobj, mdd_tobj, la,
3639                                            handle);
3640         if (rc != 0)
3641                 return rc;
3642
3643         if (S_ISLNK(la->la_mode)) {
3644                 const char *target_name = spec->u.sp_symname;
3645                 int sym_len = strlen(target_name);
3646                 const struct lu_buf *buf;
3647
3648                 buf = mdd_buf_get_const(env, target_name, sym_len);
3649                 rc = dt_declare_record_write(env, mdd_object_child(mdd_tobj),
3650                                              buf, 0, handle);
3651                 if (rc != 0)
3652                         return rc;
3653         } else if (S_ISDIR(la->la_mode) && ldata != NULL) {
3654                 rc = mdd_declare_links_add(env, mdd_tobj, handle, ldata);
3655                 if (rc != 0)
3656                         return rc;
3657         }
3658
3659         if (spec->u.sp_ea.eadata != NULL && spec->u.sp_ea.eadatalen != 0) {
3660                 buf = mdd_buf_get_const(env, spec->u.sp_ea.eadata,
3661                                         spec->u.sp_ea.eadatalen);
3662                 rc = mdo_declare_xattr_set(env, mdd_tobj, buf, XATTR_NAME_LOV,
3663                                            0, handle);
3664                 if (rc)
3665                         return rc;
3666         }
3667
3668         mgr_easize = lmv_mds_md_size(2, LMV_MAGIC_V1);
3669         buf = mdd_buf_get_const(env, mgr_ea, mgr_easize);
3670         rc = mdo_declare_xattr_set(env, mdd_sobj, buf, XATTR_NAME_LMV,
3671                                    0, handle);
3672         if (rc)
3673                 return rc;
3674
3675         la_flag->la_valid = LA_FLAGS;
3676         la_flag->la_flags = la->la_flags | LUSTRE_IMMUTABLE_FL;
3677         rc = mdo_declare_attr_set(env, mdd_sobj, la_flag, handle);
3678
3679         return rc;
3680 }
3681
3682 static int mdd_migrate_create(const struct lu_env *env,
3683                               struct mdd_object *mdd_pobj,
3684                               struct mdd_object *mdd_sobj,
3685                               struct mdd_object *mdd_tobj,
3686                               const struct lu_name *lname,
3687                               struct lu_attr *la)
3688 {
3689         struct mdd_thread_info  *info = mdd_env_info(env);
3690         struct mdd_device       *mdd = mdo2mdd(&mdd_sobj->mod_obj);
3691         struct md_op_spec       *spec = &info->mti_spec;
3692         struct lu_buf           lmm_buf = { NULL };
3693         struct lu_buf           link_buf = { NULL };
3694         struct lu_buf            mgr_buf;
3695         struct thandle          *handle;
3696         struct lmv_mds_md_v1    *mgr_ea;
3697         struct lu_attr          *la_flag = MDD_ENV_VAR(env, la_for_fix);
3698         struct dt_allocation_hint *hint = &mdd_env_info(env)->mti_hint;
3699         int                     mgr_easize;
3700         struct linkea_data      *ldata = &mdd_env_info(env)->mti_link_data;
3701         int                     rc;
3702         ENTRY;
3703
3704         /* prepare spec for create */
3705         memset(spec, 0, sizeof(*spec));
3706         spec->sp_cr_lookup = 0;
3707         spec->sp_feat = &dt_directory_features;
3708         if (S_ISLNK(la->la_mode)) {
3709                 const struct lu_buf *buf;
3710
3711                 buf = lu_buf_check_and_alloc(
3712                                 &mdd_env_info(env)->mti_big_buf,
3713                                 la->la_size + 1);
3714                 link_buf = *buf;
3715                 link_buf.lb_len = la->la_size + 1;
3716                 memset(link_buf.lb_buf, 0, link_buf.lb_len);
3717                 rc = mdd_readlink(env, &mdd_sobj->mod_obj, &link_buf);
3718                 if (rc <= 0) {
3719                         rc = rc != 0 ? rc : -EFAULT;
3720                         CERROR("%s: "DFID" readlink failed: rc = %d\n",
3721                                mdd2obd_dev(mdd)->obd_name,
3722                                PFID(mdd_object_fid(mdd_sobj)), rc);
3723                         RETURN(rc);
3724                 }
3725                 spec->u.sp_symname = link_buf.lb_buf;
3726         } else if (S_ISREG(la->la_mode)) {
3727                 /* retrieve lov of the old object */
3728                 rc = mdd_get_lov_ea(env, mdd_sobj, &lmm_buf);
3729                 if (rc != 0 && rc != -ENODATA)
3730                         RETURN(rc);
3731                 if (lmm_buf.lb_buf != NULL && lmm_buf.lb_len != 0) {
3732                         spec->u.sp_ea.eadata = lmm_buf.lb_buf;
3733                         spec->u.sp_ea.eadatalen = lmm_buf.lb_len;
3734                         spec->sp_cr_flags |= MDS_OPEN_HAS_EA;
3735                 }
3736         } else if (S_ISDIR(la->la_mode)) {
3737                 rc = mdd_links_read_with_rec(env, mdd_sobj, ldata);
3738                 if (rc == -ENODATA) {
3739                         /* ignore the non-linkEA error */
3740                         ldata = NULL;
3741                         rc = 0;
3742                 }
3743                 if (rc < 0)
3744                         RETURN(rc);
3745         }
3746
3747         mgr_easize = lmv_mds_md_size(2, LMV_MAGIC_V1);
3748         lu_buf_check_and_alloc(&info->mti_xattr_buf, mgr_easize);
3749         mgr_buf.lb_buf = info->mti_xattr_buf.lb_buf;
3750         mgr_buf.lb_len = mgr_easize;
3751         mgr_ea = mgr_buf.lb_buf;
3752         memset(mgr_ea, 0, sizeof(*mgr_ea));
3753         mgr_ea->lmv_magic = cpu_to_le32(LMV_MAGIC_V1);
3754         mgr_ea->lmv_stripe_count = cpu_to_le32(2);
3755         mgr_ea->lmv_master_mdt_index = mdd_seq_site(mdd)->ss_node_id;
3756         mgr_ea->lmv_hash_type = cpu_to_le32(LMV_HASH_FLAG_MIGRATION);
3757         fid_cpu_to_le(&mgr_ea->lmv_stripe_fids[0], mdd_object_fid(mdd_sobj));
3758         fid_cpu_to_le(&mgr_ea->lmv_stripe_fids[1], mdd_object_fid(mdd_tobj));
3759
3760         mdd_object_make_hint(env, mdd_pobj, mdd_tobj, la, spec, hint);
3761
3762         handle = mdd_trans_create(env, mdd);
3763         if (IS_ERR(handle))
3764                 GOTO(out_free, rc = PTR_ERR(handle));
3765
3766         /* Note: this transaction is part of migration, and it is not
3767          * the last step of migration, so we set th_local = 1 to avoid
3768          * update last rcvd for this transaction */
3769         handle->th_local = 1;
3770         rc = mdd_declare_migrate_create(env, mdd_pobj, mdd_sobj, mdd_tobj, spec,
3771                                         la, mgr_buf.lb_buf, ldata, handle);
3772         if (rc != 0)
3773                 GOTO(stop_trans, rc);
3774
3775         rc = mdd_trans_start(env, mdd, handle);
3776         if (rc != 0)
3777                 GOTO(stop_trans, rc);
3778
3779         /* don't set nlink from the original object */
3780         la->la_valid &= ~LA_NLINK;
3781
3782         /* create the target object */
3783         rc = mdd_create_object(env, mdd_pobj, mdd_tobj, la, spec, NULL, NULL,
3784                                hint, handle);
3785         if (rc != 0)
3786                 GOTO(stop_trans, rc);
3787
3788         if (S_ISDIR(la->la_mode) && ldata != NULL) {
3789                 rc = mdd_links_write(env, mdd_tobj, ldata, handle);
3790                 if (rc != 0)
3791                         GOTO(stop_trans, rc);
3792         }
3793
3794         /* Set MIGRATE EA on the source inode, so once the migration needs
3795          * to be re-done during failover, the re-do process can locate the
3796          * target object which is already being created. */
3797         rc = mdo_xattr_set(env, mdd_sobj, &mgr_buf, XATTR_NAME_LMV, 0, handle);
3798         if (rc != 0)
3799                 GOTO(stop_trans, rc);
3800
3801         /* Set immutable flag, so any modification is disabled until
3802          * the migration is done. Once the migration is interrupted,
3803          * if the resume process find the migrating object has both
3804          * IMMUTALBE flag and MIGRATE EA, it need to clear IMMUTABLE
3805          * flag and approve the migration */
3806         la_flag->la_valid = LA_FLAGS;
3807         la_flag->la_flags = la->la_flags | LUSTRE_IMMUTABLE_FL;
3808         rc = mdo_attr_set(env, mdd_sobj, la_flag, handle);
3809 stop_trans:
3810         if (handle != NULL)
3811                 rc = mdd_trans_stop(env, mdd, rc, handle);
3812 out_free:
3813         if (lmm_buf.lb_buf != NULL)
3814                 OBD_FREE(lmm_buf.lb_buf, lmm_buf.lb_len);
3815         RETURN(rc);
3816 }
3817
3818 static int mdd_migrate_entries(const struct lu_env *env,
3819                                struct mdd_object *mdd_sobj,
3820                                struct mdd_object *mdd_tobj)
3821 {
3822         struct dt_object        *next = mdd_object_child(mdd_sobj);
3823         struct mdd_device       *mdd = mdo2mdd(&mdd_sobj->mod_obj);
3824         struct dt_object        *dt_tobj = mdd_object_child(mdd_tobj);
3825         struct thandle          *handle;
3826         struct dt_it            *it;
3827         const struct dt_it_ops  *iops;
3828         int                      result;
3829         struct lu_dirent        *ent;
3830         int                      rc;
3831         ENTRY;
3832
3833         OBD_ALLOC(ent, NAME_MAX + sizeof(*ent) + 1);
3834         if (ent == NULL)
3835                 RETURN(-ENOMEM);
3836
3837         if (!dt_try_as_dir(env, next))
3838                 GOTO(out_ent, rc = -ENOTDIR);
3839         /*
3840          * iterate directories
3841          */
3842         iops = &next->do_index_ops->dio_it;
3843         it = iops->init(env, next, LUDA_FID | LUDA_TYPE);
3844         if (IS_ERR(it))
3845                 GOTO(out_ent, rc = PTR_ERR(it));
3846
3847         rc = iops->load(env, it, 0);
3848         if (rc == 0)
3849                 rc = iops->next(env, it);
3850         else if (rc > 0)
3851                 rc = 0;
3852         /*
3853          * At this point and across for-loop:
3854          *
3855          *  rc == 0 -> ok, proceed.
3856          *  rc >  0 -> end of directory.
3857          *  rc <  0 -> error.
3858          */
3859         do {
3860                 struct mdd_object       *child;
3861                 char                    *name = mdd_env_info(env)->mti_key;
3862                 int                     len;
3863                 int                     is_dir;
3864                 bool                    target_exist = false;
3865
3866                 len = iops->key_size(env, it);
3867                 if (len == 0)
3868                         goto next;
3869
3870                 result = iops->rec(env, it, (struct dt_rec *)ent,
3871                                    LUDA_FID | LUDA_TYPE);
3872                 if (result == -ESTALE)
3873                         goto next;
3874                 if (result != 0) {
3875                         rc = result;
3876                         goto out;
3877                 }
3878
3879                 fid_le_to_cpu(&ent->lde_fid, &ent->lde_fid);
3880
3881                 /* Insert new fid with target name into target dir */
3882                 if ((ent->lde_namelen == 1 && ent->lde_name[0] == '.') ||
3883                     (ent->lde_namelen == 2 && ent->lde_name[0] == '.' &&
3884                      ent->lde_name[1] == '.'))
3885                         goto next;
3886
3887                 child = mdd_object_find(env, mdd, &ent->lde_fid);
3888                 if (IS_ERR(child))
3889                         GOTO(out, rc = PTR_ERR(child));
3890
3891                 /* child may not exist, but lu_object_attr will assert this,
3892                  * get type from loh_attr directly */
3893                 is_dir = S_ISDIR(child->mod_obj.mo_lu.lo_header->loh_attr);
3894
3895                 mdd_write_lock(env, child, MOR_SRC_CHILD);
3896
3897                 snprintf(name, ent->lde_namelen + 1, "%s", ent->lde_name);
3898
3899                 /* Check whether the name has been inserted to the target */
3900                 if (dt_try_as_dir(env, dt_tobj)) {
3901                         struct lu_fid *fid = &mdd_env_info(env)->mti_fid2;
3902
3903                         rc = dt_lookup(env, dt_tobj, (struct dt_rec *)fid,
3904                                        (struct dt_key *)name);
3905                         if (unlikely(rc == 0))
3906                                 target_exist = true;
3907                 }
3908
3909                 handle = mdd_trans_create(env, mdd);
3910                 if (IS_ERR(handle))
3911                         GOTO(out_put, rc = PTR_ERR(handle));
3912
3913                 /* Note: this transaction is part of migration, and it is not
3914                  * the last step of migration, so we set th_local = 1 to avoid
3915                  * updating last rcvd for this transaction */
3916                 handle->th_local = 1;
3917                 if (likely(!target_exist)) {
3918                         rc = mdo_declare_index_insert(env, mdd_tobj,
3919                                 &ent->lde_fid,
3920                                 child->mod_obj.mo_lu.lo_header->loh_attr,
3921                                 name, handle);
3922                         if (rc != 0)
3923                                 GOTO(out_put, rc);
3924
3925                         if (is_dir) {
3926                                 rc = mdo_declare_ref_add(env, mdd_tobj, handle);
3927                                 if (rc != 0)
3928                                         GOTO(out_put, rc);
3929                         }
3930                 }
3931
3932                 rc = mdo_declare_index_delete(env, mdd_sobj, name, handle);
3933                 if (rc != 0)
3934                         GOTO(out_put, rc);
3935
3936                 if (is_dir) {
3937                         rc = mdo_declare_ref_del(env, mdd_sobj, handle);
3938                         if (rc != 0)
3939                                 GOTO(out_put, rc);
3940
3941                         /* Update .. for child */
3942                         rc = mdo_declare_index_delete(env, child, dotdot,
3943                                                       handle);
3944                         if (rc != 0)
3945                                 GOTO(out_put, rc);
3946
3947                         rc = mdo_declare_index_insert(env, child,
3948                                                       mdd_object_fid(mdd_tobj),
3949                                                       S_IFDIR, dotdot, handle);
3950                         if (rc != 0)
3951                                 GOTO(out_put, rc);
3952                 }
3953
3954                 rc = mdd_linkea_declare_update_child(env, mdd_sobj,mdd_tobj,
3955                                                      child, name,
3956                                                      strlen(name),
3957                                                      handle);
3958                 if (rc != 0)
3959                         GOTO(out_put, rc);
3960
3961                 rc = mdd_trans_start(env, mdd, handle);
3962                 if (rc != 0) {
3963                         CERROR("%s: transaction start failed: rc = %d\n",
3964                                mdd2obd_dev(mdd)->obd_name, rc);
3965                         GOTO(out_put, rc);
3966                 }
3967
3968                 if (likely(!target_exist)) {
3969                         rc = __mdd_index_insert(env, mdd_tobj, &ent->lde_fid,
3970                                 child->mod_obj.mo_lu.lo_header->loh_attr, name,
3971                                 handle);
3972                         if (rc != 0)
3973                                 GOTO(out_put, rc);
3974                 }
3975
3976                 rc = __mdd_index_delete(env, mdd_sobj, name, is_dir, handle);
3977                 if (rc != 0)
3978                         GOTO(out_put, rc);
3979
3980                 if (is_dir) {
3981                         rc = __mdd_index_delete_only(env, child, dotdot,
3982                                                      handle);
3983                         if (rc != 0)
3984                                 GOTO(out_put, rc);
3985
3986                         rc = __mdd_index_insert_only(env, child,
3987                                          mdd_object_fid(mdd_tobj), S_IFDIR,
3988                                          dotdot, handle);
3989                         if (rc != 0)
3990                                 GOTO(out_put, rc);
3991                 }
3992
3993                 rc = mdd_linkea_update_child(env, mdd_sobj, mdd_tobj,
3994                                              child, name,
3995                                              strlen(name), handle);
3996
3997 out_put:
3998                 mdd_write_unlock(env, child);
3999                 mdd_object_put(env, child);
4000                 rc = mdd_trans_stop(env, mdd, rc, handle);
4001                 if (rc != 0)
4002                         GOTO(out, rc);
4003 next:
4004                 result = iops->next(env, it);
4005                 if (OBD_FAIL_CHECK(OBD_FAIL_MIGRATE_ENTRIES))
4006                         GOTO(out, rc = -EINTR);
4007
4008                 if (result == -ESTALE)
4009                         goto next;
4010         } while (result == 0);
4011 out:
4012         iops->put(env, it);
4013         iops->fini(env, it);
4014 out_ent:
4015         OBD_FREE(ent, NAME_MAX + sizeof(*ent) + 1);
4016         RETURN(rc);
4017 }
4018
4019 static int mdd_declare_update_linkea(const struct lu_env *env,
4020                                      struct mdd_object *mdd_pobj,
4021                                      struct mdd_object *mdd_sobj,
4022                                      struct mdd_object *mdd_tobj,
4023                                      const struct lu_name *child_name,
4024                                      struct linkea_data *ldata,
4025                                      struct thandle *handle)
4026 {
4027         return mdd_update_linkea_internal(env, mdd_pobj, mdd_sobj, mdd_tobj,
4028                                           child_name, ldata, handle, 1);
4029 }
4030
4031 static int mdd_update_linkea(const struct lu_env *env,
4032                              struct mdd_object *mdd_pobj,
4033                              struct mdd_object *mdd_sobj,
4034                              struct mdd_object *mdd_tobj,
4035                              const struct lu_name *child_name,
4036                              struct linkea_data *ldata,
4037                              struct thandle *handle)
4038 {
4039         return mdd_update_linkea_internal(env, mdd_pobj, mdd_sobj, mdd_tobj,
4040                                           child_name, ldata, handle, 0);
4041 }
4042
4043 static int mdd_declare_migrate_update_name(const struct lu_env *env,
4044                                            struct mdd_object *mdd_pobj,
4045                                            struct mdd_object *mdd_sobj,
4046                                            struct mdd_object *mdd_tobj,
4047                                            const struct lu_name *lname,
4048                                            struct lu_attr *la,
4049                                            struct lu_attr *parent_la,
4050                                            struct linkea_data *ldata,
4051                                            struct thandle *handle)
4052 {
4053         struct mdd_device *mdd = mdo2mdd(&mdd_sobj->mod_obj);
4054         struct lu_attr *la_flag = MDD_ENV_VAR(env, tattr);
4055         int rc;
4056
4057         /* Revert IMMUTABLE flag */
4058         la_flag->la_valid = LA_FLAGS;
4059         la_flag->la_flags = la->la_flags & ~LUSTRE_IMMUTABLE_FL;
4060         rc = mdo_declare_attr_set(env, mdd_sobj, la_flag, handle);
4061         if (rc != 0)
4062                 return rc;
4063
4064         /* delete entry from source dir */
4065         rc = mdo_declare_index_delete(env, mdd_pobj, lname->ln_name, handle);
4066         if (rc != 0)
4067                 return rc;
4068
4069         if (ldata->ld_buf != NULL) {
4070                 rc = mdd_declare_update_linkea(env, mdd_pobj, mdd_sobj,
4071                                                mdd_tobj, lname, ldata, handle);
4072                 if (rc != 0)
4073                         return rc;
4074         }
4075
4076         if (S_ISREG(mdd_object_type(mdd_sobj))) {
4077                 rc = mdo_declare_xattr_del(env, mdd_sobj, XATTR_NAME_LOV,
4078                                            handle);
4079                 if (rc != 0)
4080                         return rc;
4081
4082                 handle->th_complex = 1;
4083                 rc = mdo_declare_xattr_set(env, mdd_tobj, NULL,
4084                                            XATTR_NAME_FID,
4085                                            LU_XATTR_REPLACE, handle);
4086                 if (rc < 0)
4087                         return rc;
4088         }
4089
4090         if (S_ISDIR(mdd_object_type(mdd_sobj))) {
4091                 rc = mdo_declare_ref_del(env, mdd_pobj, handle);
4092                 if (rc != 0)
4093                         return rc;
4094         }
4095
4096         /* new name */
4097         rc = mdo_declare_index_insert(env, mdd_pobj, mdo2fid(mdd_tobj),
4098                                       mdd_object_type(mdd_tobj),
4099                                       lname->ln_name, handle);
4100         if (rc != 0)
4101                 return rc;
4102
4103         rc = mdd_declare_links_add(env, mdd_tobj, handle, NULL);
4104         if (rc != 0)
4105                 return rc;
4106
4107         if (S_ISDIR(mdd_object_type(mdd_sobj))) {
4108                 rc = mdo_declare_ref_add(env, mdd_pobj, handle);
4109                 if (rc != 0)
4110                         return rc;
4111         }
4112
4113         /* delete old object */
4114         rc = mdo_declare_ref_del(env, mdd_sobj, handle);
4115         if (rc != 0)
4116                 return rc;
4117
4118         if (S_ISDIR(mdd_object_type(mdd_sobj))) {
4119                 /* delete old object */
4120                 rc = mdo_declare_ref_del(env, mdd_sobj, handle);
4121                 if (rc != 0)
4122                         return rc;
4123                 /* set nlink to 0 */
4124                 rc = mdo_declare_attr_set(env, mdd_sobj, la, handle);
4125                 if (rc != 0)
4126                         return rc;
4127         }
4128
4129         rc = mdd_declare_finish_unlink(env, mdd_sobj, handle);
4130         if (rc)
4131                 return rc;
4132
4133         rc = mdo_declare_attr_set(env, mdd_pobj, parent_la, handle);
4134         if (rc != 0)
4135                 return rc;
4136
4137         rc = mdd_declare_changelog_store(env, mdd, lname, NULL, handle);
4138
4139         return rc;
4140 }
4141
4142 static int mdd_migrate_update_name(const struct lu_env *env,
4143                                    struct mdd_object *mdd_pobj,
4144                                    struct mdd_object *mdd_sobj,
4145                                    struct mdd_object *mdd_tobj,
4146                                    const struct lu_name *lname,
4147                                    struct md_attr *ma)
4148 {
4149         struct lu_attr          *p_la = MDD_ENV_VAR(env, la_for_fix);
4150         struct lu_attr          *so_attr = MDD_ENV_VAR(env, cattr);
4151         struct lu_attr          *la_flag = MDD_ENV_VAR(env, tattr);
4152         struct mdd_device       *mdd = mdo2mdd(&mdd_sobj->mod_obj);
4153         struct linkea_data      *ldata = &mdd_env_info(env)->mti_link_data;
4154         struct thandle          *handle;
4155         int                     is_dir = S_ISDIR(mdd_object_type(mdd_sobj));
4156         const char              *name = lname->ln_name;
4157         int                     rc;
4158         ENTRY;
4159
4160         /* update time for parent */
4161         LASSERT(ma->ma_attr.la_valid & LA_CTIME);
4162         p_la->la_ctime = p_la->la_mtime = ma->ma_attr.la_ctime;
4163         p_la->la_valid = LA_CTIME;
4164
4165         rc = mdd_la_get(env, mdd_sobj, so_attr);
4166         if (rc != 0)
4167                 RETURN(rc);
4168
4169         ldata->ld_buf = NULL;
4170         rc = mdd_links_read(env, mdd_sobj, ldata);
4171         if (rc != 0 && rc != -ENOENT && rc != -ENODATA)
4172                 RETURN(rc);
4173
4174         handle = mdd_trans_create(env, mdd);
4175         if (IS_ERR(handle))
4176                 RETURN(PTR_ERR(handle));
4177
4178         rc = mdd_declare_migrate_update_name(env, mdd_pobj, mdd_sobj, mdd_tobj,
4179                                              lname, so_attr, p_la, ldata,
4180                                              handle);
4181         if (rc != 0) {
4182                 /* If the migration can not be fit in one transaction, just
4183                  * leave it in the original MDT */
4184                 if (rc == -E2BIG)
4185                         GOTO(stop_trans, rc = 0);
4186                 else
4187                         GOTO(stop_trans, rc);
4188         }
4189
4190         CDEBUG(D_INFO, "%s: update "DFID"/"DFID" with %s:"DFID"\n",
4191                mdd2obd_dev(mdd)->obd_name, PFID(mdd_object_fid(mdd_pobj)),
4192                PFID(mdd_object_fid(mdd_sobj)), lname->ln_name,
4193                PFID(mdd_object_fid(mdd_tobj)));
4194
4195         rc = mdd_trans_start(env, mdd, handle);
4196         if (rc != 0)
4197                 GOTO(stop_trans, rc);
4198
4199         /* Revert IMMUTABLE flag */
4200         la_flag->la_valid = LA_FLAGS;
4201         la_flag->la_flags = so_attr->la_flags & ~LUSTRE_IMMUTABLE_FL;
4202         rc = mdo_attr_set(env, mdd_sobj, la_flag, handle);
4203         if (rc != 0)
4204                 GOTO(stop_trans, rc);
4205
4206         /* Remove source name from source directory */
4207         rc = __mdd_index_delete(env, mdd_pobj, name, is_dir, handle);
4208         if (rc != 0)
4209                 GOTO(stop_trans, rc);
4210
4211         if (ldata->ld_buf != NULL) {
4212                 rc = mdd_update_linkea(env, mdd_pobj, mdd_sobj, mdd_tobj,
4213                                        lname, ldata, handle);
4214                 if (rc != 0)
4215                         GOTO(stop_trans, rc);
4216
4217                 /*  linkea update might decrease the source object
4218                  *  nlink, let's get the attr again after ref_del */
4219                 rc = mdd_la_get(env, mdd_sobj, so_attr);
4220                 if (rc != 0)
4221                         GOTO(stop_trans, rc);
4222         }
4223
4224         if (S_ISREG(so_attr->la_mode)) {
4225                 if (so_attr->la_nlink == 1) {
4226                         rc = mdo_xattr_del(env, mdd_sobj, XATTR_NAME_LOV,
4227                                            handle);
4228                         if (rc != 0 && rc != -ENODATA)
4229                                 GOTO(stop_trans, rc);
4230
4231                         rc = mdo_xattr_set(env, mdd_tobj, NULL,
4232                                            XATTR_NAME_FID,
4233                                            LU_XATTR_REPLACE, handle);
4234                         if (rc < 0)
4235                                 GOTO(stop_trans, rc);
4236                 }
4237         }
4238
4239         /* Insert new fid with target name into target dir */
4240         rc = __mdd_index_insert(env, mdd_pobj, mdd_object_fid(mdd_tobj),
4241                                 mdd_object_type(mdd_tobj), name, handle);
4242         if (rc != 0)
4243                 GOTO(stop_trans, rc);
4244
4245         mdd_write_lock(env, mdd_sobj, MOR_TGT_CHILD);
4246
4247         mdd_sobj->mod_flags |= DEAD_OBJ;
4248         rc = mdd_mark_orphan_object(env, mdd_sobj, handle, false);
4249         if (rc != 0)
4250                 GOTO(out_unlock, rc);
4251
4252         rc = __mdd_orphan_add(env, mdd_sobj, handle);
4253         if (rc != 0)
4254                 GOTO(out_unlock, rc);
4255
4256         mdo_ref_del(env, mdd_sobj, handle);
4257         if (is_dir)
4258                 mdo_ref_del(env, mdd_sobj, handle);
4259
4260         /* Get the attr again after ref_del */
4261         rc = mdd_la_get(env, mdd_sobj, so_attr);
4262         if (rc != 0)
4263                 GOTO(out_unlock, rc);
4264
4265         ma->ma_attr = *so_attr;
4266         ma->ma_valid |= MA_INODE;
4267
4268         rc = mdd_attr_set_internal(env, mdd_pobj, p_la, handle, 0);
4269         if (rc != 0)
4270                 GOTO(out_unlock, rc);
4271
4272         rc = mdd_changelog_ns_store(env, mdd, CL_MIGRATE, 0, mdd_tobj,
4273                                mdo2fid(mdd_pobj), mdo2fid(mdd_sobj),
4274                                mdo2fid(mdd_pobj), lname, lname, handle);
4275         if (rc != 0) {
4276                 CWARN("%s: changelog for migrate %s "DFID
4277                       "under "DFID" failed: rc = %d\n",
4278                       mdd2obd_dev(mdd)->obd_name, lname->ln_name,
4279                       PFID(mdd_object_fid(mdd_sobj)),
4280                       PFID(mdd_object_fid(mdd_pobj)), rc);
4281                 /* Sigh, there are no easy way to migrate back the object, so
4282                  * let's reset the result to 0 for now XXX */
4283                 rc = 0;
4284         }
4285 out_unlock:
4286         mdd_write_unlock(env, mdd_sobj);
4287
4288 stop_trans:
4289         rc = mdd_trans_stop(env, mdd, rc, handle);
4290
4291         RETURN(rc);
4292 }
4293
4294 static int mdd_fld_lookup(const struct lu_env *env, struct mdd_device *mdd,
4295                           const struct lu_fid *fid, __u32 *mdt_index)
4296 {
4297         struct lu_seq_range *range = &mdd_env_info(env)->mti_range;
4298         struct seq_server_site *ss;
4299         int rc;
4300
4301         ss = mdd->mdd_md_dev.md_lu_dev.ld_site->ld_seq_site;
4302
4303         range->lsr_flags = LU_SEQ_RANGE_MDT;
4304         rc = fld_server_lookup(env, ss->ss_server_fld, fid->f_seq, range);
4305         if (rc != 0)
4306                 return rc;
4307
4308         *mdt_index = range->lsr_index;
4309
4310         return 0;
4311 }
4312 /**
4313  * Check whether we should migrate the file/dir
4314  * return val
4315  *      < 0  permission check failed or other error.
4316  *      = 0  the file can be migrated.
4317  *      > 0  the file does not need to be migrated, mostly
4318  *           for multiple link file
4319  **/
4320 static int mdd_migrate_sanity_check(const struct lu_env *env,
4321                                     struct mdd_object *pobj,
4322                                     const struct lu_attr *pattr,
4323                                     struct mdd_object *sobj,
4324                                     struct lu_attr *sattr)
4325 {
4326         struct mdd_thread_info  *info = mdd_env_info(env);
4327         struct linkea_data      *ldata = &info->mti_link_data;
4328         struct mdd_device       *mdd = mdo2mdd(&pobj->mod_obj);
4329         int                     mgr_easize;
4330         struct lu_buf           *mgr_buf;
4331         int                     count;
4332         int                     rc;
4333         __u64 mdt_index;
4334         ENTRY;
4335
4336         mgr_easize = lmv_mds_md_size(2, LMV_MAGIC_V1);
4337         mgr_buf = lu_buf_check_and_alloc(&info->mti_big_buf, mgr_easize);
4338         if (mgr_buf->lb_buf == NULL)
4339                 RETURN(-ENOMEM);
4340
4341         rc = mdo_xattr_get(env, sobj, mgr_buf, XATTR_NAME_LMV);
4342         if (rc > 0) {
4343                 union lmv_mds_md *lmm = mgr_buf->lb_buf;
4344
4345                 /* If the object has migrateEA, it means IMMUTE flag
4346                  * is being set by previous migration process, so it
4347                  * needs to override the IMMUTE flag, otherwise the
4348                  * following sanity check will fail */
4349                 if (le32_to_cpu(lmm->lmv_md_v1.lmv_hash_type) &
4350                                                 LMV_HASH_FLAG_MIGRATION) {
4351                         struct mdd_device *mdd = mdo2mdd(&sobj->mod_obj);
4352
4353                         sattr->la_flags &= ~LUSTRE_IMMUTABLE_FL;
4354                         CDEBUG(D_HA, "%s: "DFID" override IMMUTE FLAG\n",
4355                                mdd2obd_dev(mdd)->obd_name,
4356                                PFID(mdd_object_fid(sobj)));
4357                 }
4358         }
4359
4360         rc = mdd_rename_sanity_check(env, pobj, pattr, pobj, pattr,
4361                                      sobj, sattr, NULL, NULL);
4362         if (rc != 0)
4363                 RETURN(rc);
4364
4365         /* Then it will check if the file should be migrated. If the file
4366          * has mulitple links, we only need migrate the file if all of its
4367          * entries has been migrated to the remote MDT */
4368         if (!S_ISREG(sattr->la_mode) || sattr->la_nlink < 2)
4369                 RETURN(0);
4370
4371         rc = mdd_links_read(env, sobj, ldata);
4372         if (rc != 0) {
4373                 /* For multiple links files, if there are no linkEA data at all,
4374                  * means the file might be created before linkEA is enabled, and
4375                  * all of its links should not be migrated yet, otherwise it
4376                  * should have some linkEA there */
4377                 if (rc == -ENOENT || rc == -ENODATA)
4378                         RETURN(1);
4379                 RETURN(rc);
4380         }
4381
4382         mdt_index = mdd->mdd_md_dev.md_lu_dev.ld_site->ld_seq_site->ss_node_id;
4383         /* If there are still links locally, then the file will not be
4384          * migrated. */
4385         LASSERT(ldata->ld_leh != NULL);
4386
4387         /* If the linkEA is overflow, then means there are some unknown name
4388          * entries under unknown parents, that will prevent the migration. */
4389         if (unlikely(ldata->ld_leh->leh_overflow_time))
4390                 RETURN(1);
4391
4392         ldata->ld_lee = (struct link_ea_entry *)(ldata->ld_leh + 1);
4393         for (count = 0; count < ldata->ld_leh->leh_reccount; count++) {
4394                 struct lu_name          lname;
4395                 struct lu_fid           fid;
4396                 __u32                   parent_mdt_index;
4397
4398                 linkea_entry_unpack(ldata->ld_lee, &ldata->ld_reclen,
4399                                     &lname, &fid);
4400                 ldata->ld_lee = (struct link_ea_entry *)((char *)ldata->ld_lee +
4401                                                          ldata->ld_reclen);
4402
4403                 rc = mdd_fld_lookup(env, mdd, &fid, &parent_mdt_index);
4404                 if (rc != 0)
4405                         RETURN(rc);
4406
4407                 /* Migrate the object only if none of its parents are on the
4408                  * current MDT. */
4409                 if (parent_mdt_index != mdt_index)
4410                         continue;
4411
4412                 CDEBUG(D_INFO, DFID"still has local entry %.*s "DFID"\n",
4413                        PFID(mdd_object_fid(sobj)), lname.ln_namelen,
4414                        lname.ln_name, PFID(&fid));
4415                 rc = 1;
4416                 break;
4417         }
4418
4419         RETURN(rc);
4420 }
4421
4422 static int mdd_migrate(const struct lu_env *env, struct md_object *pobj,
4423                        struct md_object *sobj, const struct lu_name *lname,
4424                        struct md_object *tobj, struct md_attr *ma)
4425 {
4426         struct mdd_object       *mdd_pobj = md2mdd_obj(pobj);
4427         struct mdd_device       *mdd = mdo2mdd(pobj);
4428         struct mdd_object       *mdd_sobj = md2mdd_obj(sobj);
4429         struct mdd_object       *mdd_tobj = md2mdd_obj(tobj);
4430         struct lu_attr          *so_attr = MDD_ENV_VAR(env, cattr);
4431         struct lu_attr          *pattr = MDD_ENV_VAR(env, pattr);
4432         bool                    created = false;
4433         int                     rc;
4434
4435         ENTRY;
4436         /* If the file will being migrated, it will check whether
4437          * the file is being opened by someone else right now */
4438         mdd_read_lock(env, mdd_sobj, MOR_SRC_CHILD);
4439         if (mdd_sobj->mod_count > 0) {
4440                 CDEBUG(D_OTHER,
4441                        "%s: "DFID"%s is already opened count %d: rc = %d\n",
4442                        mdd2obd_dev(mdd)->obd_name,
4443                        PFID(mdd_object_fid(mdd_sobj)), lname->ln_name,
4444                        mdd_sobj->mod_count, -EBUSY);
4445                 mdd_read_unlock(env, mdd_sobj);
4446                 GOTO(put, rc = -EBUSY);
4447         }
4448         mdd_read_unlock(env, mdd_sobj);
4449
4450         rc = mdd_la_get(env, mdd_sobj, so_attr);
4451         if (rc != 0)
4452                 GOTO(put, rc);
4453
4454         rc = mdd_la_get(env, mdd_pobj, pattr);
4455         if (rc != 0)
4456                 GOTO(put, rc);
4457
4458         rc = mdd_migrate_sanity_check(env, mdd_pobj, pattr, mdd_sobj, so_attr);
4459         if (rc != 0) {
4460                 if (rc > 0)
4461                         rc = 0;
4462                 GOTO(put, rc);
4463         }
4464
4465         /* Sigh, it is impossible to finish all of migration in a single
4466          * transaction, for example migrating big directory entries to the
4467          * new MDT, it needs insert all of name entries of children in the
4468          * new directory.
4469          *
4470          * So migration will be done in multiple steps and transactions.
4471          *
4472          * 1. create an orphan object on the remote MDT in one transaction.
4473          * 2. migrate extend attributes to the new target file/directory.
4474          * 3. For directory, migrate the entries to the new MDT and update
4475          * linkEA of each children. Because we can not migrate all entries
4476          * in a single transaction, so the migrating directory will become
4477          * a striped directory during migration, so once the process is
4478          * interrupted, the directory is still accessible. (During lookup,
4479          * client will locate the name by searching both original and target
4480          * object).
4481          * 4. Finally, update the name/FID to point to the new file/directory
4482          * in a separate transaction.
4483          */
4484
4485         /* step 1: Check whether the orphan object has been created, and create
4486          * orphan object on the remote MDT if needed */
4487         if (!mdd_object_exists(mdd_tobj)) {
4488                 rc = mdd_migrate_create(env, mdd_pobj, mdd_sobj, mdd_tobj,
4489                                         lname, so_attr);
4490                 if (rc != 0)
4491                         GOTO(put, rc);
4492                 created = true;
4493         }
4494
4495         LASSERT(mdd_object_exists(mdd_tobj));
4496         /* step 2: migrate xattr */
4497         rc = mdd_migrate_xattrs(env, mdd_sobj, mdd_tobj);
4498         if (rc != 0)
4499                 GOTO(put, rc);
4500
4501         /* step 3: migrate name entries to the orphan object */
4502         if (S_ISDIR(lu_object_attr(&mdd_sobj->mod_obj.mo_lu))) {
4503                 rc = mdd_migrate_entries(env, mdd_sobj, mdd_tobj);
4504                 if (rc != 0)
4505                         GOTO(put, rc);
4506                 if (unlikely(OBD_FAIL_CHECK_RESET(OBD_FAIL_MIGRATE_NET_REP,
4507                                                   OBD_FAIL_MDS_REINT_NET_REP)))
4508                         GOTO(put, rc = 0);
4509         } else {
4510                 OBD_FAIL_TIMEOUT(OBD_FAIL_MIGRATE_DELAY, cfs_fail_val);
4511         }
4512
4513         LASSERT(mdd_object_exists(mdd_tobj));
4514         /* step 4: update name entry to the new object */
4515         rc = mdd_migrate_update_name(env, mdd_pobj, mdd_sobj, mdd_tobj, lname,
4516                                      ma);
4517         if (rc != 0)
4518                 GOTO(put, rc);
4519
4520         /* newly created target was not locked, don't cache its attributes */
4521         if (created)
4522                 mdd_invalidate(env, tobj);
4523 put:
4524         RETURN(rc);
4525 }
4526
4527 const struct md_dir_operations mdd_dir_ops = {
4528         .mdo_is_subdir     = mdd_is_subdir,
4529         .mdo_lookup        = mdd_lookup,
4530         .mdo_create        = mdd_create,
4531         .mdo_rename        = mdd_rename,
4532         .mdo_link          = mdd_link,
4533         .mdo_unlink        = mdd_unlink,
4534         .mdo_create_data   = mdd_create_data,
4535         .mdo_migrate       = mdd_migrate,
4536 };