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