Whamcloud - gitweb
acf1bd24a9c205ef4e6ea3eae12f4e1168796611
[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 | CLFE_NID;
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                                 enum changelog_rec_type type,
758                                 const struct lu_name *tname,
759                                 const struct lu_name *sname,
760                                 struct thandle *handle)
761 {
762         struct obd_device               *obd = mdd2obd_dev(mdd);
763         struct llog_ctxt                *ctxt;
764         struct llog_changelog_rec       *rec;
765         struct lu_buf                   *buf;
766         struct thandle                  *llog_th;
767         int                              reclen;
768         int                              rc;
769
770         if (!mdd_changelog_enabled(env, mdd, type))
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 = false;
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 void mdd_changelog_rec_extra_nid(struct changelog_rec *rec,
1058                                  lnet_nid_t nid)
1059 {
1060         struct changelog_ext_nid *clnid = changelog_rec_nid(rec);
1061
1062         clnid->cr_nid = nid;
1063 }
1064
1065 void mdd_changelog_rec_extra_omode(struct changelog_rec *rec, int flags)
1066 {
1067         struct changelog_ext_openmode *omd = changelog_rec_openmode(rec);
1068
1069         omd->cr_openflags = (__u32)flags;
1070 }
1071
1072 void mdd_changelog_rec_extra_xattr(struct changelog_rec *rec,
1073                                    const char *xattr_name)
1074 {
1075         struct changelog_ext_xattr    *xattr = changelog_rec_xattr(rec);
1076
1077         strlcpy(xattr->cr_xattr, xattr_name, sizeof(xattr->cr_xattr));
1078 }
1079
1080 /** Store a namespace change changelog record
1081  * If this fails, we must fail the whole transaction; we don't
1082  * want the change to commit without the log entry.
1083  * \param target - mdd_object of change
1084  * \param tpfid - target parent dir/object fid
1085  * \param sfid - source object fid
1086  * \param spfid - source parent fid
1087  * \param tname - target name string
1088  * \param sname - source name string
1089  * \param handle - transaction handle
1090  */
1091 int mdd_changelog_ns_store(const struct lu_env *env,
1092                            struct mdd_device *mdd,
1093                            enum changelog_rec_type type,
1094                            enum changelog_rec_flags crf,
1095                            struct mdd_object *target,
1096                            const struct lu_fid *tpfid,
1097                            const struct lu_fid *sfid,
1098                            const struct lu_fid *spfid,
1099                            const struct lu_name *tname,
1100                            const struct lu_name *sname,
1101                            struct thandle *handle)
1102 {
1103         const struct lu_ucred           *uc = lu_ucred(env);
1104         struct llog_changelog_rec       *rec;
1105         struct lu_buf                   *buf;
1106         int                              reclen;
1107         __u64                            xflags = CLFE_INVALID;
1108         int                              rc;
1109         ENTRY;
1110
1111         if (!mdd_changelog_enabled(env, mdd, type))
1112                 RETURN(0);
1113
1114         LASSERT(tpfid != NULL);
1115         LASSERT(tname != NULL);
1116         LASSERT(handle != NULL);
1117
1118         reclen = mdd_llog_record_calc_size(env, tname, sname);
1119         buf = lu_buf_check_and_alloc(&mdd_env_info(env)->mti_big_buf, reclen);
1120         if (buf->lb_buf == NULL)
1121                 RETURN(-ENOMEM);
1122         rec = buf->lb_buf;
1123
1124         crf &= CLF_FLAGMASK;
1125         crf |= CLF_EXTRA_FLAGS;
1126
1127         if (uc) {
1128                 if (uc->uc_jobid[0] != '\0')
1129                         crf |= CLF_JOBID;
1130                 xflags |= CLFE_UIDGID;
1131                 xflags |= CLFE_NID;
1132         }
1133
1134         if (sname != NULL)
1135                 crf |= CLF_RENAME;
1136         else
1137                 crf |= CLF_VERSION;
1138
1139         rec->cr.cr_flags = crf;
1140
1141         if (crf & CLF_EXTRA_FLAGS) {
1142                 mdd_changelog_rec_ext_extra_flags(&rec->cr, xflags);
1143                 if (xflags & CLFE_UIDGID)
1144                         mdd_changelog_rec_extra_uidgid(&rec->cr,
1145                                                        uc->uc_uid, uc->uc_gid);
1146                 if (xflags & CLFE_NID)
1147                         mdd_changelog_rec_extra_nid(&rec->cr, uc->uc_nid);
1148         }
1149
1150         rec->cr.cr_type = (__u32)type;
1151         rec->cr.cr_pfid = *tpfid;
1152         rec->cr.cr_namelen = tname->ln_namelen;
1153         memcpy(changelog_rec_name(&rec->cr), tname->ln_name, tname->ln_namelen);
1154
1155         if (crf & CLF_RENAME)
1156                 mdd_changelog_rec_ext_rename(&rec->cr, sfid, spfid, sname);
1157
1158         if (crf & CLF_JOBID)
1159                 mdd_changelog_rec_ext_jobid(&rec->cr, uc->uc_jobid);
1160
1161         if (likely(target != NULL)) {
1162                 rec->cr.cr_tfid = *mdo2fid(target);
1163                 target->mod_cltime = ktime_get();
1164         } else {
1165                 fid_zero(&rec->cr.cr_tfid);
1166         }
1167
1168         rc = mdd_changelog_store(env, mdd, rec, handle);
1169         if (rc < 0) {
1170                 CERROR("%s: cannot store changelog record: type = %d, "
1171                        "name = '%s', t = "DFID", p = "DFID": rc = %d\n",
1172                        mdd2obd_dev(mdd)->obd_name, type, tname->ln_name,
1173                        PFID(&rec->cr.cr_tfid), PFID(&rec->cr.cr_pfid), rc);
1174                 return -EFAULT;
1175         }
1176
1177         return 0;
1178 }
1179
1180 static int __mdd_links_add(const struct lu_env *env,
1181                            struct mdd_object *mdd_obj,
1182                            struct linkea_data *ldata,
1183                            const struct lu_name *lname,
1184                            const struct lu_fid *pfid,
1185                            int first, int check)
1186 {
1187         int rc;
1188
1189         if (ldata->ld_leh == NULL) {
1190                 rc = first ? -ENODATA : mdd_links_read(env, mdd_obj, ldata);
1191                 if (rc) {
1192                         if (rc != -ENODATA)
1193                                 return rc;
1194                         rc = linkea_data_new(ldata,
1195                                              &mdd_env_info(env)->mti_link_buf);
1196                         if (rc)
1197                                 return rc;
1198                 }
1199         }
1200
1201         if (check) {
1202                 rc = linkea_links_find(ldata, lname, pfid);
1203                 if (rc && rc != -ENOENT)
1204                         return rc;
1205                 if (rc == 0)
1206                         return -EEXIST;
1207         }
1208
1209         if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_LINKEA_MORE)) {
1210                 struct lu_fid *tfid = &mdd_env_info(env)->mti_fid2;
1211
1212                 *tfid = *pfid;
1213                 tfid->f_ver = ~0;
1214                 linkea_add_buf(ldata, lname, tfid);
1215         }
1216
1217         if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_LINKEA_MORE2))
1218                 linkea_add_buf(ldata, lname, pfid);
1219
1220         return linkea_add_buf(ldata, lname, pfid);
1221 }
1222
1223 static int __mdd_links_del(const struct lu_env *env,
1224                            struct mdd_object *mdd_obj,
1225                            struct linkea_data *ldata,
1226                            const struct lu_name *lname,
1227                            const struct lu_fid *pfid)
1228 {
1229         int rc;
1230
1231         if (ldata->ld_leh == NULL) {
1232                 rc = mdd_links_read(env, mdd_obj, ldata);
1233                 if (rc)
1234                         return rc;
1235         }
1236
1237         rc = linkea_links_find(ldata, lname, pfid);
1238         if (rc)
1239                 return rc;
1240
1241         linkea_del_buf(ldata, lname);
1242         return 0;
1243 }
1244
1245 static int mdd_linkea_prepare(const struct lu_env *env,
1246                               struct mdd_object *mdd_obj,
1247                               const struct lu_fid *oldpfid,
1248                               const struct lu_name *oldlname,
1249                               const struct lu_fid *newpfid,
1250                               const struct lu_name *newlname,
1251                               int first, int check,
1252                               struct linkea_data *ldata)
1253 {
1254         int rc = 0;
1255         ENTRY;
1256
1257         if (OBD_FAIL_CHECK(OBD_FAIL_FID_IGIF))
1258                 RETURN(0);
1259
1260         LASSERT(oldpfid != NULL || newpfid != NULL);
1261
1262         if (mdd_obj->mod_flags & DEAD_OBJ)
1263                 /* Unnecessary to update linkEA for dead object.  */
1264                 RETURN(0);
1265
1266         if (oldpfid != NULL) {
1267                 rc = __mdd_links_del(env, mdd_obj, ldata, oldlname, oldpfid);
1268                 if (rc) {
1269                         if ((check == 1) || (rc != -ENODATA && rc != -ENOENT))
1270                                 RETURN(rc);
1271
1272                         /* No changes done. */
1273                         rc = 0;
1274                 }
1275         }
1276
1277         /* If renaming, add the new record */
1278         if (newpfid != NULL)
1279                 rc = __mdd_links_add(env, mdd_obj, ldata, newlname, newpfid,
1280                                      first, check);
1281
1282         RETURN(rc);
1283 }
1284
1285 int mdd_links_rename(const struct lu_env *env,
1286                      struct mdd_object *mdd_obj,
1287                      const struct lu_fid *oldpfid,
1288                      const struct lu_name *oldlname,
1289                      const struct lu_fid *newpfid,
1290                      const struct lu_name *newlname,
1291                      struct thandle *handle,
1292                      struct linkea_data *ldata,
1293                      int first, int check)
1294 {
1295         int rc = 0;
1296         ENTRY;
1297
1298         if (ldata == NULL) {
1299                 ldata = &mdd_env_info(env)->mti_link_data;
1300                 memset(ldata, 0, sizeof(*ldata));
1301                 rc = mdd_linkea_prepare(env, mdd_obj, oldpfid, oldlname,
1302                                         newpfid, newlname, first, check, ldata);
1303                 if (rc)
1304                         GOTO(out, rc);
1305         }
1306
1307         if (!(mdd_obj->mod_flags & DEAD_OBJ))
1308                 rc = mdd_links_write(env, mdd_obj, ldata, handle);
1309
1310         GOTO(out, rc);
1311
1312 out:
1313         if (rc != 0) {
1314                 if (newlname == NULL)
1315                         CERROR("link_ea add failed %d "DFID"\n",
1316                                rc, PFID(mdd_object_fid(mdd_obj)));
1317                 else if (oldpfid == NULL)
1318                         CERROR("link_ea add '%.*s' failed %d "DFID"\n",
1319                                newlname->ln_namelen, newlname->ln_name, rc,
1320                                PFID(mdd_object_fid(mdd_obj)));
1321                 else if (newpfid == NULL)
1322                         CERROR("link_ea del '%.*s' failed %d "DFID"\n",
1323                                oldlname->ln_namelen, oldlname->ln_name, rc,
1324                                PFID(mdd_object_fid(mdd_obj)));
1325                 else
1326                         CERROR("link_ea rename '%.*s'->'%.*s' failed %d "DFID
1327                                "\n", oldlname->ln_namelen, oldlname->ln_name,
1328                                newlname->ln_namelen, newlname->ln_name, rc,
1329                                PFID(mdd_object_fid(mdd_obj)));
1330         }
1331
1332         if (is_vmalloc_addr(ldata->ld_buf))
1333                 /* if we vmalloced a large buffer drop it */
1334                 lu_buf_free(ldata->ld_buf);
1335
1336         return rc;
1337 }
1338
1339 static inline int mdd_links_add(const struct lu_env *env,
1340                                 struct mdd_object *mdd_obj,
1341                                 const struct lu_fid *pfid,
1342                                 const struct lu_name *lname,
1343                                 struct thandle *handle,
1344                                 struct linkea_data *ldata, int first)
1345 {
1346         return mdd_links_rename(env, mdd_obj, NULL, NULL,
1347                                 pfid, lname, handle, ldata, first, 0);
1348 }
1349
1350 static inline int mdd_links_del(const struct lu_env *env,
1351                                 struct mdd_object *mdd_obj,
1352                                 const struct lu_fid *pfid,
1353                                 const struct lu_name *lname,
1354                                 struct thandle *handle)
1355 {
1356         return mdd_links_rename(env, mdd_obj, pfid, lname,
1357                                 NULL, NULL, handle, NULL, 0, 0);
1358 }
1359
1360 /** Read the link EA into a temp buffer.
1361  * Uses the name_buf since it is generally large.
1362  * \retval IS_ERR err
1363  * \retval ptr to \a lu_buf (always \a mti_big_buf)
1364  */
1365 struct lu_buf *mdd_links_get(const struct lu_env *env,
1366                              struct mdd_object *mdd_obj)
1367 {
1368         struct linkea_data ldata = { NULL };
1369         int rc;
1370
1371         rc = mdd_links_read(env, mdd_obj, &ldata);
1372         return rc ? ERR_PTR(rc) : ldata.ld_buf;
1373 }
1374
1375 int mdd_links_write(const struct lu_env *env, struct mdd_object *mdd_obj,
1376                     struct linkea_data *ldata, struct thandle *handle)
1377 {
1378         const struct lu_buf *buf;
1379         int                 rc;
1380
1381         if (ldata == NULL || ldata->ld_buf == NULL ||
1382             ldata->ld_leh == NULL)
1383                 return 0;
1384
1385         if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_NO_LINKEA))
1386                 return 0;
1387
1388 again:
1389         buf = mdd_buf_get_const(env, ldata->ld_buf->lb_buf,
1390                                 ldata->ld_leh->leh_len);
1391         rc = mdo_xattr_set(env, mdd_obj, buf, XATTR_NAME_LINK, 0, handle);
1392         if (unlikely(rc == -ENOSPC)) {
1393                 rc = linkea_overflow_shrink(ldata);
1394                 if (likely(rc > 0))
1395                         goto again;
1396         }
1397
1398         return rc;
1399 }
1400
1401 static int mdd_declare_links_add(const struct lu_env *env,
1402                                  struct mdd_object *mdd_obj,
1403                                  struct thandle *handle,
1404                                  struct linkea_data *ldata)
1405 {
1406         int     rc;
1407         int     ea_len;
1408         void    *linkea;
1409
1410         if (ldata != NULL && ldata->ld_leh != NULL) {
1411                 ea_len = ldata->ld_leh->leh_len;
1412                 linkea = ldata->ld_buf->lb_buf;
1413         } else {
1414                 ea_len = MAX_LINKEA_SIZE;
1415                 linkea = NULL;
1416         }
1417
1418         rc = mdo_declare_xattr_set(env, mdd_obj,
1419                                    mdd_buf_get_const(env, linkea, ea_len),
1420                                    XATTR_NAME_LINK, 0, handle);
1421
1422         return rc;
1423 }
1424
1425 static inline int mdd_declare_links_del(const struct lu_env *env,
1426                                         struct mdd_object *c,
1427                                         struct thandle *handle)
1428 {
1429         int rc = 0;
1430
1431         /* For directory, the linkEA will be removed together
1432          * with the object. */
1433         if (!S_ISDIR(mdd_object_type(c)))
1434                 rc = mdd_declare_links_add(env, c, handle, NULL);
1435
1436         return rc;
1437 }
1438
1439 static int mdd_declare_link(const struct lu_env *env,
1440                             struct mdd_device *mdd,
1441                             struct mdd_object *p,
1442                             struct mdd_object *c,
1443                             const struct lu_name *name,
1444                             struct thandle *handle,
1445                             struct lu_attr *la,
1446                             struct linkea_data *data)
1447 {
1448         struct lu_fid tfid = *mdo2fid(c);
1449         int rc;
1450
1451         if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_DANGLING3))
1452                 tfid.f_oid = cfs_fail_val;
1453
1454         rc = mdo_declare_index_insert(env, p, &tfid, mdd_object_type(c),
1455                                       name->ln_name, handle);
1456         if (rc != 0)
1457                 return rc;
1458
1459         rc = mdo_declare_ref_add(env, c, handle);
1460         if (rc != 0)
1461                 return rc;
1462
1463         la->la_valid = LA_CTIME | LA_MTIME;
1464         rc = mdo_declare_attr_set(env, p, la, handle);
1465         if (rc != 0)
1466                 return rc;
1467
1468         la->la_valid = LA_CTIME;
1469         rc = mdo_declare_attr_set(env, c, la, handle);
1470         if (rc != 0)
1471                 return rc;
1472
1473         rc = mdd_declare_links_add(env, c, handle, data);
1474         if (rc != 0)
1475                 return rc;
1476
1477         rc = mdd_declare_changelog_store(env, mdd, CL_HARDLINK, name, NULL,
1478                                          handle);
1479
1480         return rc;
1481 }
1482
1483 static int mdd_link(const struct lu_env *env, struct md_object *tgt_obj,
1484                     struct md_object *src_obj, const struct lu_name *lname,
1485                     struct md_attr *ma)
1486 {
1487         const char *name = lname->ln_name;
1488         struct lu_attr    *la = &mdd_env_info(env)->mti_la_for_fix;
1489         struct mdd_object *mdd_tobj = md2mdd_obj(tgt_obj);
1490         struct mdd_object *mdd_sobj = md2mdd_obj(src_obj);
1491         struct lu_attr    *cattr = MDD_ENV_VAR(env, cattr);
1492         struct lu_attr    *tattr = MDD_ENV_VAR(env, tattr);
1493         struct mdd_device *mdd = mdo2mdd(src_obj);
1494         struct thandle *handle;
1495         struct lu_fid *tfid = &mdd_env_info(env)->mti_fid2;
1496         struct linkea_data *ldata = &mdd_env_info(env)->mti_link_data;
1497         int rc;
1498         ENTRY;
1499
1500         rc = mdd_la_get(env, mdd_sobj, cattr);
1501         if (rc != 0)
1502                 RETURN(rc);
1503
1504         rc = mdd_la_get(env, mdd_tobj, tattr);
1505         if (rc != 0)
1506                 RETURN(rc);
1507
1508         /*
1509          * If we are using project inheritance, we only allow hard link
1510          * creation in our tree when the project IDs are the same;
1511          * otherwise the tree quota mechanism could be circumvented.
1512          */
1513         if ((tattr->la_flags & LUSTRE_PROJINHERIT_FL) &&
1514             (tattr->la_projid != cattr->la_projid))
1515                 RETURN(-EXDEV);
1516
1517         handle = mdd_trans_create(env, mdd);
1518         if (IS_ERR(handle))
1519                 GOTO(out_pending, rc = PTR_ERR(handle));
1520
1521         memset(ldata, 0, sizeof(*ldata));
1522
1523         LASSERT(ma->ma_attr.la_valid & LA_CTIME);
1524         la->la_ctime = la->la_mtime = ma->ma_attr.la_ctime;
1525
1526         /* Note: even this function will change ldata, but it comes from
1527          * thread_info, which is completely temporary and only seen in
1528          * this function, so we do not need reset ldata once it fails.*/
1529         rc = mdd_linkea_prepare(env, mdd_sobj, NULL, NULL, mdo2fid(mdd_tobj),
1530                                 lname, 0, 0, ldata);
1531         if (rc != 0)
1532                 GOTO(stop, rc);
1533
1534         rc = mdd_declare_link(env, mdd, mdd_tobj, mdd_sobj, lname, handle,
1535                               la, ldata);
1536         if (rc)
1537                 GOTO(stop, rc);
1538
1539         rc = mdd_trans_start(env, mdd, handle);
1540         if (rc)
1541                 GOTO(stop, rc);
1542
1543         mdd_write_lock(env, mdd_sobj, MOR_TGT_CHILD);
1544         rc = mdd_link_sanity_check(env, mdd_tobj, tattr, lname, mdd_sobj,
1545                                    cattr);
1546         if (rc)
1547                 GOTO(out_unlock, rc);
1548
1549         if (!OBD_FAIL_CHECK(OBD_FAIL_LFSCK_LESS_NLINK)) {
1550                 rc = mdo_ref_add(env, mdd_sobj, handle);
1551                 if (rc != 0)
1552                         GOTO(out_unlock, rc);
1553         }
1554
1555         *tfid = *mdo2fid(mdd_sobj);
1556         if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_DANGLING3))
1557                 tfid->f_oid = cfs_fail_val;
1558
1559         rc = __mdd_index_insert_only(env, mdd_tobj, tfid,
1560                                      mdd_object_type(mdd_sobj), name, handle);
1561         if (rc != 0) {
1562                 mdo_ref_del(env, mdd_sobj, handle);
1563                 GOTO(out_unlock, rc);
1564         }
1565
1566         la->la_valid = LA_CTIME | LA_MTIME;
1567         rc = mdd_update_time(env, mdd_tobj, tattr, la, handle);
1568         if (rc)
1569                 GOTO(out_unlock, rc);
1570
1571         la->la_valid = LA_CTIME;
1572         rc = mdd_update_time(env, mdd_sobj, cattr, la, handle);
1573         if (rc == 0)
1574                 /* Note: The failure of links_add should not cause the
1575                  * link failure, so do not check return value. */
1576                 mdd_links_add(env, mdd_sobj, mdo2fid(mdd_tobj),
1577                               lname, handle, ldata, 0);
1578
1579         EXIT;
1580 out_unlock:
1581         mdd_write_unlock(env, mdd_sobj);
1582         if (rc == 0)
1583                 rc = mdd_changelog_ns_store(env, mdd, CL_HARDLINK, 0, mdd_sobj,
1584                                             mdo2fid(mdd_tobj), NULL, NULL,
1585                                             lname, NULL, handle);
1586 stop:
1587         rc = mdd_trans_stop(env, mdd, rc, handle);
1588         if (is_vmalloc_addr(ldata->ld_buf))
1589                 /* if we vmalloced a large buffer drop it */
1590                 lu_buf_free(ldata->ld_buf);
1591 out_pending:
1592         return rc;
1593 }
1594
1595 static int mdd_mark_orphan_object(const struct lu_env *env,
1596                                 struct mdd_object *obj, struct thandle *handle,
1597                                 bool declare)
1598 {
1599         struct lu_attr *attr = MDD_ENV_VAR(env, la_for_start);
1600         int rc;
1601
1602         if (!S_ISDIR(mdd_object_type(obj)))
1603                 return 0;
1604
1605         attr->la_valid = LA_FLAGS;
1606         attr->la_flags = LUSTRE_ORPHAN_FL;
1607
1608         if (declare)
1609                 rc = mdo_declare_attr_set(env, obj, attr, handle);
1610         else
1611                 rc = mdo_attr_set(env, obj, attr, handle);
1612
1613         return rc;
1614 }
1615
1616 static int mdd_declare_finish_unlink(const struct lu_env *env,
1617                                      struct mdd_object *obj,
1618                                      struct thandle *handle)
1619 {
1620         int rc;
1621
1622         /* Sigh, we do not know if the unlink object will become orphan in
1623          * declare phase, but fortunately the flags here does not matter
1624          * in current declare implementation */
1625         rc = mdd_mark_orphan_object(env, obj, handle, true);
1626         if (rc != 0)
1627                 return rc;
1628
1629         rc = mdo_declare_destroy(env, obj, handle);
1630         if (rc != 0)
1631                 return rc;
1632
1633         rc = mdd_orphan_declare_insert(env, obj, mdd_object_type(obj), handle);
1634         if (rc != 0)
1635                 return rc;
1636
1637         return mdd_declare_links_del(env, obj, handle);
1638 }
1639
1640 /* caller should take a lock before calling */
1641 int mdd_finish_unlink(const struct lu_env *env,
1642                       struct mdd_object *obj, struct md_attr *ma,
1643                       const struct mdd_object *pobj,
1644                       const struct lu_name *lname,
1645                       struct thandle *th)
1646 {
1647         int rc = 0;
1648         int is_dir = S_ISDIR(ma->ma_attr.la_mode);
1649         ENTRY;
1650
1651         LASSERT(mdd_write_locked(env, obj) != 0);
1652
1653         if (ma->ma_attr.la_nlink == 0 || is_dir) {
1654                 /* add new orphan and the object
1655                  * will be deleted during mdd_close() */
1656                 obj->mod_flags |= DEAD_OBJ;
1657                 if (obj->mod_count) {
1658                         rc = mdd_orphan_insert(env, obj, th);
1659                         if (rc == 0)
1660                                 CDEBUG(D_HA, "Object "DFID" is inserted into "
1661                                         "orphan list, open count = %d\n",
1662                                         PFID(mdd_object_fid(obj)),
1663                                         obj->mod_count);
1664                         else
1665                                 CERROR("Object "DFID" fail to be an orphan, "
1666                                        "open count = %d, maybe cause failed "
1667                                        "open replay\n",
1668                                         PFID(mdd_object_fid(obj)),
1669                                         obj->mod_count);
1670
1671                         /* mark object as an orphan here, not
1672                          * before mdd_orphan_insert() as racing
1673                          * mdd_la_get() may propagate ORPHAN_OBJ
1674                          * causing the asserition */
1675                         rc = mdd_mark_orphan_object(env, obj, th, false);
1676                 } else {
1677                         rc = mdo_destroy(env, obj, th);
1678                 }
1679         } else if (!is_dir) {
1680                 /* old files may not have link ea; ignore errors */
1681                 mdd_links_del(env, obj, mdo2fid(pobj), lname, th);
1682         }
1683
1684         RETURN(rc);
1685 }
1686
1687 /*
1688  * pobj maybe NULL
1689  * has mdd_write_lock on cobj already, but not on pobj yet
1690  */
1691 int mdd_unlink_sanity_check(const struct lu_env *env, struct mdd_object *pobj,
1692                             const struct lu_attr *pattr,
1693                             struct mdd_object *cobj,
1694                             const struct lu_attr *cattr)
1695 {
1696         int rc;
1697         ENTRY;
1698
1699         rc = mdd_may_delete(env, pobj, pattr, cobj, cattr, NULL, 1, 1);
1700
1701         RETURN(rc);
1702 }
1703
1704 static int mdd_declare_unlink(const struct lu_env *env, struct mdd_device *mdd,
1705                               struct mdd_object *p, struct mdd_object *c,
1706                               const struct lu_name *name, struct md_attr *ma,
1707                               struct thandle *handle, int no_name, int is_dir)
1708 {
1709         struct lu_attr  *la = &mdd_env_info(env)->mti_la_for_fix;
1710         int              rc;
1711
1712         if (!OBD_FAIL_CHECK(OBD_FAIL_LFSCK_DANGLING2)) {
1713                 if (likely(no_name == 0)) {
1714                         rc = mdo_declare_index_delete(env, p, name->ln_name,
1715                                                       handle);
1716                         if (rc != 0)
1717                                 return rc;
1718                 }
1719
1720                 if (is_dir != 0) {
1721                         rc = mdo_declare_ref_del(env, p, handle);
1722                         if (rc != 0)
1723                                 return rc;
1724                 }
1725         }
1726
1727         LASSERT(ma->ma_attr.la_valid & LA_CTIME);
1728         la->la_ctime = la->la_mtime = ma->ma_attr.la_ctime;
1729         la->la_valid = LA_CTIME | LA_MTIME;
1730         rc = mdo_declare_attr_set(env, p, la, handle);
1731         if (rc)
1732                 return rc;
1733
1734         if (c != NULL) {
1735                 rc = mdo_declare_ref_del(env, c, handle);
1736                 if (rc)
1737                         return rc;
1738
1739                 rc = mdo_declare_ref_del(env, c, handle);
1740                 if (rc)
1741                         return rc;
1742
1743                 la->la_valid = LA_CTIME;
1744                 rc = mdo_declare_attr_set(env, c, la, handle);
1745                 if (rc)
1746                         return rc;
1747
1748                 rc = mdd_declare_finish_unlink(env, c, handle);
1749                 if (rc)
1750                         return rc;
1751
1752                 /* FIXME: need changelog for remove entry */
1753                 rc = mdd_declare_changelog_store(env, mdd, CL_UNLINK, name,
1754                                                  NULL, handle);
1755         }
1756
1757         return rc;
1758 }
1759
1760 /*
1761  * test if a file has an HSM archive
1762  * if HSM attributes are not found in ma update them from
1763  * HSM xattr
1764  */
1765 static bool mdd_hsm_archive_exists(const struct lu_env *env,
1766                                    struct mdd_object *obj,
1767                                    struct md_attr *ma)
1768 {
1769         ENTRY;
1770
1771         if (!(ma->ma_valid & MA_HSM)) {
1772                 /* no HSM MD provided, read xattr */
1773                 struct lu_buf   *hsm_buf;
1774                 const size_t     buflen = sizeof(struct hsm_attrs);
1775                 int              rc;
1776
1777                 hsm_buf = mdd_buf_get(env, NULL, 0);
1778                 lu_buf_alloc(hsm_buf, buflen);
1779                 rc = mdo_xattr_get(env, obj, hsm_buf, XATTR_NAME_HSM);
1780                 rc = lustre_buf2hsm(hsm_buf->lb_buf, rc, &ma->ma_hsm);
1781                 lu_buf_free(hsm_buf);
1782                 if (rc < 0)
1783                         RETURN(false);
1784
1785                 ma->ma_valid |= MA_HSM;
1786         }
1787         if (ma->ma_hsm.mh_flags & HS_EXISTS)
1788                 RETURN(true);
1789         RETURN(false);
1790 }
1791
1792 /**
1793  * Delete name entry and the object.
1794  * Note: no_name == 1 means it only destory the object, i.e. name_entry
1795  * does not exist for this object, and it could only happen during resending
1796  * of remote unlink. see the comments in mdt_reint_unlink. Unfortunately, lname
1797  * is also needed in this case(needed by changelog), so we have to add another
1798  * parameter(no_name)here. XXX: this is only needed in DNE phase I, on Phase II,
1799  * the ENOENT failure should be able to be fixed by redo mechanism.
1800  */
1801 static int mdd_unlink(const struct lu_env *env, struct md_object *pobj,
1802                       struct md_object *cobj, const struct lu_name *lname,
1803                       struct md_attr *ma, int no_name)
1804 {
1805         const char *name = lname->ln_name;
1806         struct lu_attr *pattr = MDD_ENV_VAR(env, pattr);
1807         struct lu_attr *cattr = MDD_ENV_VAR(env, cattr);
1808         struct lu_attr *la = &mdd_env_info(env)->mti_la_for_fix;
1809         struct mdd_object *mdd_pobj = md2mdd_obj(pobj);
1810         struct mdd_object *mdd_cobj = NULL;
1811         struct mdd_device *mdd = mdo2mdd(pobj);
1812         struct thandle    *handle;
1813         int rc, is_dir = 0, cl_flags = 0;
1814         ENTRY;
1815
1816         /* cobj == NULL means only delete name entry */
1817         if (likely(cobj != NULL)) {
1818                 mdd_cobj = md2mdd_obj(cobj);
1819                 if (mdd_object_exists(mdd_cobj) == 0)
1820                         RETURN(-ENOENT);
1821         }
1822
1823         rc = mdd_la_get(env, mdd_pobj, pattr);
1824         if (rc)
1825                 RETURN(rc);
1826
1827         if (likely(mdd_cobj != NULL)) {
1828                 /* fetch cattr */
1829                 rc = mdd_la_get(env, mdd_cobj, cattr);
1830                 if (rc)
1831                         RETURN(rc);
1832
1833                 is_dir = S_ISDIR(cattr->la_mode);
1834                 /* search for an existing archive.
1835                  * we should check ahead as the object
1836                  * can be destroyed in this transaction */
1837                 if (mdd_hsm_archive_exists(env, mdd_cobj, ma))
1838                         cl_flags |= CLF_UNLINK_HSM_EXISTS;
1839         }
1840
1841         rc = mdd_unlink_sanity_check(env, mdd_pobj, pattr, mdd_cobj, cattr);
1842         if (rc)
1843                 RETURN(rc);
1844
1845         handle = mdd_trans_create(env, mdd);
1846         if (IS_ERR(handle))
1847                 RETURN(PTR_ERR(handle));
1848
1849         rc = mdd_declare_unlink(env, mdd, mdd_pobj, mdd_cobj,
1850                                 lname, ma, handle, no_name, is_dir);
1851         if (rc)
1852                 GOTO(stop, rc);
1853
1854         rc = mdd_trans_start(env, mdd, handle);
1855         if (rc)
1856                 GOTO(stop, rc);
1857
1858         if (likely(mdd_cobj != NULL))
1859                 mdd_write_lock(env, mdd_cobj, MOR_TGT_CHILD);
1860
1861         if (likely(no_name == 0) && !OBD_FAIL_CHECK(OBD_FAIL_LFSCK_DANGLING2)) {
1862                 rc = __mdd_index_delete(env, mdd_pobj, name, is_dir, handle);
1863                 if (rc)
1864                         GOTO(cleanup, rc);
1865         }
1866
1867         if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_MUL_REF) ||
1868             OBD_FAIL_CHECK(OBD_FAIL_LFSCK_NO_NAMEENTRY))
1869                 GOTO(cleanup, rc = 0);
1870
1871         if (likely(mdd_cobj != NULL)) {
1872                 rc = mdo_ref_del(env, mdd_cobj, handle);
1873                 if (rc != 0) {
1874                         __mdd_index_insert_only(env, mdd_pobj,
1875                                                 mdo2fid(mdd_cobj),
1876                                                 mdd_object_type(mdd_cobj),
1877                                                 name, handle);
1878                         GOTO(cleanup, rc);
1879                 }
1880
1881                 if (is_dir)
1882                         /* unlink dot */
1883                         mdo_ref_del(env, mdd_cobj, handle);
1884
1885                 /* fetch updated nlink */
1886                 rc = mdd_la_get(env, mdd_cobj, cattr);
1887                 if (rc)
1888                         GOTO(cleanup, rc);
1889         }
1890
1891         LASSERT(ma->ma_attr.la_valid & LA_CTIME);
1892         la->la_ctime = la->la_mtime = ma->ma_attr.la_ctime;
1893
1894         la->la_valid = LA_CTIME | LA_MTIME;
1895         rc = mdd_update_time(env, mdd_pobj, pattr, la, handle);
1896         if (rc)
1897                 GOTO(cleanup, rc);
1898
1899         /* Enough for only unlink the entry */
1900         if (unlikely(mdd_cobj == NULL))
1901                 GOTO(stop, rc);
1902
1903         if (cattr->la_nlink > 0 || mdd_cobj->mod_count > 0) {
1904                 /* update ctime of an unlinked file only if it is still
1905                  * opened or a link still exists */
1906                 la->la_valid = LA_CTIME;
1907                 rc = mdd_update_time(env, mdd_cobj, cattr, la, handle);
1908                 if (rc)
1909                         GOTO(cleanup, rc);
1910         }
1911
1912         /* XXX: this transfer to ma will be removed with LOD/OSP */
1913         ma->ma_attr = *cattr;
1914         ma->ma_valid |= MA_INODE;
1915         rc = mdd_finish_unlink(env, mdd_cobj, ma, mdd_pobj, lname, handle);
1916         if (rc != 0)
1917                 GOTO(cleanup, rc);
1918
1919         /* fetch updated nlink */
1920         rc = mdd_la_get(env, mdd_cobj, cattr);
1921         /* if object is removed then we can't get its attrs,
1922          * use last get */
1923         if (rc == -ENOENT) {
1924                 cattr->la_nlink = 0;
1925                 rc = 0;
1926         }
1927
1928         if (cattr->la_nlink == 0) {
1929                 ma->ma_attr = *cattr;
1930                 ma->ma_valid |= MA_INODE;
1931         }
1932
1933         EXIT;
1934 cleanup:
1935         if (likely(mdd_cobj != NULL))
1936                 mdd_write_unlock(env, mdd_cobj);
1937
1938         if (rc == 0) {
1939                 if (cattr->la_nlink == 0)
1940                         cl_flags |= CLF_UNLINK_LAST;
1941                 else
1942                         cl_flags &= ~CLF_UNLINK_HSM_EXISTS;
1943
1944                 rc = mdd_changelog_ns_store(env, mdd,
1945                         is_dir ? CL_RMDIR : CL_UNLINK, cl_flags,
1946                         mdd_cobj, mdo2fid(mdd_pobj), NULL, NULL, lname, NULL,
1947                         handle);
1948         }
1949
1950 stop:
1951         rc = mdd_trans_stop(env, mdd, rc, handle);
1952
1953         return rc;
1954 }
1955
1956 /*
1957  * The permission has been checked when obj created, no need check again.
1958  */
1959 static int mdd_cd_sanity_check(const struct lu_env *env,
1960                                struct mdd_object *obj)
1961 {
1962         ENTRY;
1963
1964         /* EEXIST check */
1965         if (!obj || mdd_is_dead_obj(obj))
1966                 RETURN(-ENOENT);
1967
1968         RETURN(0);
1969 }
1970
1971 static int mdd_create_data(const struct lu_env *env,
1972                            struct md_object *pobj,
1973                            struct md_object *cobj,
1974                            const struct md_op_spec *spec,
1975                            struct md_attr *ma)
1976 {
1977         struct mdd_device *mdd = mdo2mdd(cobj);
1978         struct mdd_object *mdd_pobj = md2mdd_obj(pobj);
1979         struct mdd_object *son = md2mdd_obj(cobj);
1980         struct thandle    *handle;
1981         const struct lu_buf *buf;
1982         struct lu_attr    *attr = MDD_ENV_VAR(env, cattr);
1983         struct dt_allocation_hint *hint = &mdd_env_info(env)->mti_hint;
1984         int                rc;
1985         ENTRY;
1986
1987         rc = mdd_cd_sanity_check(env, son);
1988         if (rc)
1989                 RETURN(rc);
1990
1991         if (!md_should_create(spec->sp_cr_flags))
1992                 RETURN(0);
1993
1994         /*
1995          * there are following use cases for this function:
1996          * 1) late striping - file was created with MDS_OPEN_DELAY_CREATE
1997          *    striping can be specified or not
1998          * 2) CMD?
1999          */
2000         rc = mdd_la_get(env, son, attr);
2001         if (rc)
2002                 RETURN(rc);
2003
2004         /* calling ->ah_make_hint() is used to transfer information from parent */
2005         mdd_object_make_hint(env, mdd_pobj, son, attr, spec, hint);
2006
2007         handle = mdd_trans_create(env, mdd);
2008         if (IS_ERR(handle))
2009                 GOTO(out_free, rc = PTR_ERR(handle));
2010
2011         /*
2012          * XXX: Setting the lov ea is not locked but setting the attr is locked?
2013          * Should this be fixed?
2014          */
2015         CDEBUG(D_OTHER, "ea %p/%u, cr_flags %#llo, no_create %u\n",
2016                spec->u.sp_ea.eadata, spec->u.sp_ea.eadatalen,
2017                spec->sp_cr_flags, spec->no_create);
2018
2019         if (spec->no_create || (spec->sp_cr_flags & MDS_OPEN_HAS_EA)) {
2020                 buf = mdd_buf_get_const(env, spec->u.sp_ea.eadata,
2021                                         spec->u.sp_ea.eadatalen);
2022         } else {
2023                 buf = &LU_BUF_NULL;
2024         }
2025
2026         rc = dt_declare_xattr_set(env, mdd_object_child(son), buf,
2027                                   XATTR_NAME_LOV, 0, handle);
2028         if (rc)
2029                 GOTO(stop, rc);
2030
2031         rc = mdd_declare_changelog_store(env, mdd, CL_LAYOUT, NULL, NULL,
2032                                          handle);
2033         if (rc)
2034                 GOTO(stop, rc);
2035
2036         rc = mdd_trans_start(env, mdd, handle);
2037         if (rc)
2038                 GOTO(stop, rc);
2039
2040         rc = dt_xattr_set(env, mdd_object_child(son), buf, XATTR_NAME_LOV,
2041                           0, handle);
2042
2043         if (rc)
2044                 GOTO(stop, rc);
2045
2046         rc = mdd_changelog_data_store(env, mdd, CL_LAYOUT, 0, son, handle);
2047
2048 stop:
2049         rc = mdd_trans_stop(env, mdd, rc, handle);
2050
2051 out_free:
2052         RETURN(rc);
2053 }
2054
2055 static int mdd_declare_object_initialize(const struct lu_env *env,
2056                                          struct mdd_object *parent,
2057                                          struct mdd_object *child,
2058                                          const struct lu_attr *attr,
2059                                          struct thandle *handle)
2060 {
2061         int rc;
2062         ENTRY;
2063
2064         LASSERT(attr->la_valid & (LA_MODE | LA_TYPE));
2065         if (!S_ISDIR(attr->la_mode))
2066                 RETURN(0);
2067
2068         rc = mdo_declare_index_insert(env, child, mdo2fid(child), S_IFDIR,
2069                                       dot, handle);
2070         if (rc != 0)
2071                 RETURN(rc);
2072
2073         rc = mdo_declare_ref_add(env, child, handle);
2074         if (rc != 0)
2075                 RETURN(rc);
2076
2077         rc = mdo_declare_index_insert(env, child, mdo2fid(parent), S_IFDIR,
2078                                       dotdot, handle);
2079
2080         RETURN(rc);
2081 }
2082
2083 static int mdd_object_initialize(const struct lu_env *env,
2084                                  const struct lu_fid *pfid,
2085                                  struct mdd_object *child,
2086                                  struct lu_attr *attr, struct thandle *handle,
2087                                  const struct md_op_spec *spec)
2088 {
2089         int rc = 0;
2090         ENTRY;
2091
2092         if (S_ISDIR(attr->la_mode)) {
2093                 /* Add "." and ".." for newly created dir */
2094                 mdo_ref_add(env, child, handle);
2095                 rc = __mdd_index_insert_only(env, child, mdo2fid(child),
2096                                              S_IFDIR, dot, handle);
2097                 if (rc == 0)
2098                         rc = __mdd_index_insert_only(env, child, pfid, S_IFDIR,
2099                                                      dotdot, handle);
2100                 if (rc != 0)
2101                         mdo_ref_del(env, child, handle);
2102         }
2103
2104         RETURN(rc);
2105 }
2106
2107 /**
2108  * This function checks whether it can create a file/dir under the
2109  * directory(@pobj). The directory(@pobj) is not being locked by
2110  * mdd lock.
2111  *
2112  * \param[in] env       execution environment
2113  * \param[in] pobj      the directory to create files
2114  * \param[in] pattr     the attributes of the directory
2115  * \param[in] lname     the name of the created file/dir
2116  * \param[in] cattr     the attributes of the file/dir
2117  * \param[in] spec      create specification
2118  *
2119  * \retval              = 0 it is allowed to create file/dir under
2120  *                      the directory
2121  * \retval              negative error not allowed to create file/dir
2122  *                      under the directory
2123  */
2124 static int mdd_create_sanity_check(const struct lu_env *env,
2125                                    struct md_object *pobj,
2126                                    const struct lu_attr *pattr,
2127                                    const struct lu_name *lname,
2128                                    struct lu_attr *cattr,
2129                                    struct md_op_spec *spec)
2130 {
2131         struct mdd_thread_info *info = mdd_env_info(env);
2132         struct lu_fid     *fid       = &info->mti_fid;
2133         struct mdd_object *obj       = md2mdd_obj(pobj);
2134         struct mdd_device *m         = mdo2mdd(pobj);
2135         bool            check_perm = true;
2136         int rc;
2137         ENTRY;
2138
2139         /* EEXIST check */
2140         if (mdd_is_dead_obj(obj))
2141                 RETURN(-ENOENT);
2142
2143         /*
2144          * In some cases this lookup is not needed - we know before if name
2145          * exists or not because MDT performs lookup for it.
2146          * name length check is done in lookup.
2147          */
2148         if (spec->sp_cr_lookup) {
2149                 /*
2150                  * Check if the name already exist, though it will be checked in
2151                  * _index_insert also, for avoiding rolling back if exists
2152                  * _index_insert.
2153                  */
2154                 rc = __mdd_lookup(env, pobj, pattr, lname, fid,
2155                                   MAY_WRITE | MAY_EXEC);
2156                 if (rc != -ENOENT)
2157                         RETURN(rc ? : -EEXIST);
2158
2159                 /* Permission is already being checked in mdd_lookup */
2160                 check_perm = false;
2161         }
2162
2163         if (S_ISDIR(cattr->la_mode) &&
2164             unlikely(spec != NULL && spec->sp_cr_flags & MDS_OPEN_HAS_EA) &&
2165             spec->u.sp_ea.eadata != NULL && spec->u.sp_ea.eadatalen > 0) {
2166                 const struct lmv_user_md *lum = spec->u.sp_ea.eadata;
2167
2168                 if (le32_to_cpu(lum->lum_magic) != LMV_USER_MAGIC &&
2169                     le32_to_cpu(lum->lum_magic) != LMV_USER_MAGIC_SPECIFIC &&
2170                     le32_to_cpu(lum->lum_magic) != LMV_USER_MAGIC_V0) {
2171                         rc = -EINVAL;
2172                         CERROR("%s: invalid lmv_user_md: magic = %x, "
2173                                "stripe_offset = %d, stripe_count = %u: "
2174                                "rc = %d\n", mdd2obd_dev(m)->obd_name,
2175                                 le32_to_cpu(lum->lum_magic),
2176                                (int)le32_to_cpu(lum->lum_stripe_offset),
2177                                le32_to_cpu(lum->lum_stripe_count), rc);
2178                         return rc;
2179                 }
2180         }
2181
2182         rc = mdd_may_create(env, obj, pattr, NULL, check_perm);
2183         if (rc != 0)
2184                 RETURN(rc);
2185
2186         /* sgid check */
2187         if (pattr->la_mode & S_ISGID) {
2188                 cattr->la_gid = pattr->la_gid;
2189                 if (S_ISDIR(cattr->la_mode)) {
2190                         cattr->la_mode |= S_ISGID;
2191                         cattr->la_valid |= LA_MODE;
2192                 }
2193         }
2194
2195         /* Inherit project ID from parent directory */
2196         if (pattr->la_flags & LUSTRE_PROJINHERIT_FL) {
2197                 cattr->la_projid = pattr->la_projid;
2198                 if (S_ISDIR(cattr->la_mode)) {
2199                         cattr->la_flags |= LUSTRE_PROJINHERIT_FL;
2200                         cattr->la_valid |= LA_FLAGS;
2201                 }
2202                 cattr->la_valid |= LA_PROJID;
2203         }
2204
2205         rc = mdd_name_check(m, lname);
2206         if (rc < 0)
2207                 RETURN(rc);
2208
2209         switch (cattr->la_mode & S_IFMT) {
2210         case S_IFLNK: {
2211                 unsigned int symlen = strlen(spec->u.sp_symname) + 1;
2212
2213                 if (symlen > m->mdd_dt_conf.ddp_symlink_max)
2214                         RETURN(-ENAMETOOLONG);
2215                 else
2216                         RETURN(0);
2217         }
2218         case S_IFDIR:
2219         case S_IFREG:
2220         case S_IFCHR:
2221         case S_IFBLK:
2222         case S_IFIFO:
2223         case S_IFSOCK:
2224                 rc = 0;
2225                 break;
2226         default:
2227                 rc = -EINVAL;
2228                 break;
2229         }
2230         RETURN(rc);
2231 }
2232
2233 static int mdd_declare_create_object(const struct lu_env *env,
2234                                      struct mdd_device *mdd,
2235                                      struct mdd_object *p, struct mdd_object *c,
2236                                      struct lu_attr *attr,
2237                                      struct thandle *handle,
2238                                      const struct md_op_spec *spec,
2239                                      struct lu_buf *def_acl_buf,
2240                                      struct lu_buf *acl_buf,
2241                                      struct dt_allocation_hint *hint)
2242 {
2243         const struct lu_buf *buf;
2244         int rc;
2245
2246         rc = mdd_declare_create_object_internal(env, p, c, attr, handle, spec,
2247                                                 hint);
2248         if (rc)
2249                 GOTO(out, rc);
2250
2251 #ifdef CONFIG_FS_POSIX_ACL
2252         if (def_acl_buf->lb_len > 0 && S_ISDIR(attr->la_mode)) {
2253                 /* if dir, then can inherit default ACl */
2254                 rc = mdo_declare_xattr_set(env, c, def_acl_buf,
2255                                            XATTR_NAME_ACL_DEFAULT,
2256                                            0, handle);
2257                 if (rc)
2258                         GOTO(out, rc);
2259         }
2260
2261         if (acl_buf->lb_len > 0) {
2262                 rc = mdo_declare_attr_set(env, c, attr, handle);
2263                 if (rc)
2264                         GOTO(out, rc);
2265
2266                 rc = mdo_declare_xattr_set(env, c, acl_buf,
2267                                            XATTR_NAME_ACL_ACCESS, 0, handle);
2268                 if (rc)
2269                         GOTO(out, rc);
2270         }
2271 #endif
2272         rc = mdd_declare_object_initialize(env, p, c, attr, handle);
2273         if (rc)
2274                 GOTO(out, rc);
2275
2276         /* replay case, create LOV EA from client data */
2277         if ((!(spec->sp_cr_flags & MDS_OPEN_DELAY_CREATE) && spec->no_create) ||
2278             (spec->sp_cr_flags & MDS_OPEN_HAS_EA && S_ISREG(attr->la_mode))) {
2279                 buf = mdd_buf_get_const(env, spec->u.sp_ea.eadata,
2280                                         spec->u.sp_ea.eadatalen);
2281                 rc = mdo_declare_xattr_set(env, c, buf, XATTR_NAME_LOV, 0,
2282                                            handle);
2283                 if (rc)
2284                         GOTO(out, rc);
2285         }
2286
2287         if (S_ISLNK(attr->la_mode)) {
2288                 const char *target_name = spec->u.sp_symname;
2289                 int sym_len = strlen(target_name);
2290                 const struct lu_buf *buf;
2291
2292                 buf = mdd_buf_get_const(env, target_name, sym_len);
2293                 rc = dt_declare_record_write(env, mdd_object_child(c),
2294                                              buf, 0, handle);
2295                 if (rc)
2296                         GOTO(out, rc);
2297         }
2298
2299         if (spec->sp_cr_file_secctx_name != NULL) {
2300                 buf = mdd_buf_get_const(env, spec->sp_cr_file_secctx,
2301                                         spec->sp_cr_file_secctx_size);
2302                 rc = mdo_declare_xattr_set(env, c, buf,
2303                                            spec->sp_cr_file_secctx_name, 0,
2304                                            handle);
2305                 if (rc < 0)
2306                         GOTO(out, rc);
2307         }
2308 out:
2309         return rc;
2310 }
2311
2312 static int mdd_declare_create(const struct lu_env *env, struct mdd_device *mdd,
2313                               struct mdd_object *p, struct mdd_object *c,
2314                               const struct lu_name *name,
2315                               struct lu_attr *attr,
2316                               struct thandle *handle,
2317                               const struct md_op_spec *spec,
2318                               struct linkea_data *ldata,
2319                               struct lu_buf *def_acl_buf,
2320                               struct lu_buf *acl_buf,
2321                               struct dt_allocation_hint *hint)
2322 {
2323         int rc;
2324
2325         rc = mdd_declare_create_object(env, mdd, p, c, attr, handle, spec,
2326                                        def_acl_buf, acl_buf, hint);
2327         if (rc)
2328                 GOTO(out, rc);
2329
2330         if (S_ISDIR(attr->la_mode)) {
2331                 rc = mdo_declare_ref_add(env, p, handle);
2332                 if (rc)
2333                         GOTO(out, rc);
2334         }
2335
2336         if (unlikely(spec->sp_cr_flags & MDS_OPEN_VOLATILE)) {
2337                 rc = mdd_orphan_declare_insert(env, c, attr->la_mode, handle);
2338                 if (rc)
2339                         GOTO(out, rc);
2340         } else {
2341                 struct lu_attr *la = &mdd_env_info(env)->mti_la_for_fix;
2342                 enum changelog_rec_type type;
2343
2344                 rc = mdo_declare_index_insert(env, p, mdo2fid(c), attr->la_mode,
2345                                               name->ln_name, handle);
2346                 if (rc != 0)
2347                         return rc;
2348
2349                 rc = mdd_declare_links_add(env, c, handle, ldata);
2350                 if (rc)
2351                         return rc;
2352
2353                 *la = *attr;
2354                 la->la_valid = LA_CTIME | LA_MTIME;
2355                 rc = mdo_declare_attr_set(env, p, la, handle);
2356                 if (rc)
2357                         return rc;
2358
2359                 type = S_ISDIR(attr->la_mode) ? CL_MKDIR :
2360                        S_ISREG(attr->la_mode) ? CL_CREATE :
2361                        S_ISLNK(attr->la_mode) ? CL_SOFTLINK : CL_MKNOD;
2362
2363                 rc = mdd_declare_changelog_store(env, mdd, type, name, NULL,
2364                                                  handle);
2365                 if (rc)
2366                         return rc;
2367         }
2368 out:
2369         return rc;
2370 }
2371
2372 static int mdd_acl_init(const struct lu_env *env, struct mdd_object *pobj,
2373                         struct lu_attr *la, struct lu_buf *def_acl_buf,
2374                         struct lu_buf *acl_buf)
2375 {
2376         int     rc;
2377         ENTRY;
2378
2379         if (S_ISLNK(la->la_mode)) {
2380                 acl_buf->lb_len = 0;
2381                 def_acl_buf->lb_len = 0;
2382                 RETURN(0);
2383         }
2384
2385         mdd_read_lock(env, pobj, MOR_TGT_PARENT);
2386         rc = mdo_xattr_get(env, pobj, def_acl_buf,
2387                            XATTR_NAME_ACL_DEFAULT);
2388         mdd_read_unlock(env, pobj);
2389         if (rc > 0) {
2390                 /* If there are default ACL, fix mode/ACL by default ACL */
2391                 def_acl_buf->lb_len = rc;
2392                 LASSERT(def_acl_buf->lb_len <= acl_buf->lb_len);
2393                 memcpy(acl_buf->lb_buf, def_acl_buf->lb_buf, rc);
2394                 acl_buf->lb_len = rc;
2395                 rc = __mdd_fix_mode_acl(env, acl_buf, &la->la_mode);
2396                 if (rc < 0)
2397                         RETURN(rc);
2398         } else if (rc == -ENODATA || rc == -EOPNOTSUPP) {
2399                 /* If there are no default ACL, fix mode by mask */
2400                 struct lu_ucred *uc = lu_ucred(env);
2401
2402                 /* The create triggered by MDT internal events, such as
2403                  * LFSCK reset, will not contain valid "uc". */
2404                 if (unlikely(uc != NULL))
2405                         la->la_mode &= ~uc->uc_umask;
2406                 rc = 0;
2407                 acl_buf->lb_len = 0;
2408                 def_acl_buf->lb_len = 0;
2409         }
2410
2411         RETURN(rc);
2412 }
2413
2414 /**
2415  * Create a metadata object and initialize it, set acl, xattr.
2416  **/
2417 static int mdd_create_object(const struct lu_env *env, struct mdd_object *pobj,
2418                              struct mdd_object *son, struct lu_attr *attr,
2419                              struct md_op_spec *spec, struct lu_buf *acl_buf,
2420                              struct lu_buf *def_acl_buf,
2421                              struct dt_allocation_hint *hint,
2422                              struct thandle *handle)
2423 {
2424         const struct lu_buf *buf;
2425         int rc;
2426
2427         mdd_write_lock(env, son, MOR_TGT_CHILD);
2428         rc = mdd_create_object_internal(env, NULL, son, attr, handle, spec,
2429                                         hint);
2430         if (rc)
2431                 GOTO(unlock, rc);
2432
2433         /* Note: In DNE phase I, for striped dir, though sub-stripes will be
2434          * created in declare phase, they also needs to be added to master
2435          * object as sub-directory entry. So it has to initialize the master
2436          * object, then set dir striped EA.(in mdo_xattr_set) */
2437         rc = mdd_object_initialize(env, mdo2fid(pobj), son, attr, handle,
2438                                    spec);
2439         if (rc != 0)
2440                 GOTO(err_destroy, rc);
2441
2442         /*
2443          * in case of replay we just set LOVEA provided by the client
2444          * XXX: I think it would be interesting to try "old" way where
2445          *      MDT calls this xattr_set(LOV) in a different transaction.
2446          *      probably this way we code can be made better.
2447          */
2448
2449         /* During creation, there are only a few cases we need do xattr_set to
2450          * create stripes.
2451          * 1. regular file: see comments above.
2452          * 2. dir: inherit default striping or pool settings from parent.
2453          * 3. create striped directory with provided stripeEA.
2454          * 4. create striped directory because inherit default layout from the
2455          * parent.
2456          */
2457         if (spec->no_create ||
2458             (S_ISREG(attr->la_mode) && spec->sp_cr_flags & MDS_OPEN_HAS_EA) ||
2459             S_ISDIR(attr->la_mode)) {
2460                 buf = mdd_buf_get_const(env, spec->u.sp_ea.eadata,
2461                                         spec->u.sp_ea.eadatalen);
2462                 rc = mdo_xattr_set(env, son, buf,
2463                                    S_ISDIR(attr->la_mode) ? XATTR_NAME_LMV :
2464                                                             XATTR_NAME_LOV, 0,
2465                                    handle);
2466                 if (rc != 0)
2467                         GOTO(err_destroy, rc);
2468         }
2469
2470 #ifdef CONFIG_FS_POSIX_ACL
2471         if (def_acl_buf != NULL && def_acl_buf->lb_len > 0 &&
2472             S_ISDIR(attr->la_mode)) {
2473                 /* set default acl */
2474                 rc = mdo_xattr_set(env, son, def_acl_buf,
2475                                    XATTR_NAME_ACL_DEFAULT, 0,
2476                                    handle);
2477                 if (rc)
2478                         GOTO(err_destroy, rc);
2479         }
2480         /* set its own acl */
2481         if (acl_buf != NULL && acl_buf->lb_len > 0) {
2482                 rc = mdo_xattr_set(env, son, acl_buf,
2483                                    XATTR_NAME_ACL_ACCESS,
2484                                    0, handle);
2485                 if (rc)
2486                         GOTO(err_destroy, rc);
2487         }
2488 #endif
2489
2490         if (S_ISLNK(attr->la_mode)) {
2491                 struct lu_ucred  *uc = lu_ucred_assert(env);
2492                 struct dt_object *dt = mdd_object_child(son);
2493                 const char *target_name = spec->u.sp_symname;
2494                 int sym_len = strlen(target_name);
2495                 loff_t pos = 0;
2496
2497                 buf = mdd_buf_get_const(env, target_name, sym_len);
2498                 rc = dt->do_body_ops->dbo_write(env, dt, buf, &pos, handle,
2499                                                 uc->uc_cap &
2500                                                 CFS_CAP_SYS_RESOURCE_MASK);
2501
2502                 if (rc == sym_len)
2503                         rc = 0;
2504                 else
2505                         GOTO(err_initlized, rc = -EFAULT);
2506         }
2507
2508         if (spec->sp_cr_file_secctx_name != NULL) {
2509                 buf = mdd_buf_get_const(env, spec->sp_cr_file_secctx,
2510                                         spec->sp_cr_file_secctx_size);
2511                 rc = mdo_xattr_set(env, son, buf, spec->sp_cr_file_secctx_name,
2512                                    0, handle);
2513                 if (rc < 0)
2514                         GOTO(err_initlized, rc);
2515         }
2516
2517 err_initlized:
2518         if (unlikely(rc != 0)) {
2519                 int rc2;
2520                 if (S_ISDIR(attr->la_mode)) {
2521                         /* Drop the reference, no need to delete "."/"..",
2522                          * because the object to be destroied directly. */
2523                         rc2 = mdo_ref_del(env, son, handle);
2524                         if (rc2 != 0)
2525                                 GOTO(unlock, rc);
2526                 }
2527                 rc2 = mdo_ref_del(env, son, handle);
2528                 if (rc2 != 0)
2529                         GOTO(unlock, rc);
2530 err_destroy:
2531                 mdo_destroy(env, son, handle);
2532         }
2533 unlock:
2534         mdd_write_unlock(env, son);
2535         RETURN(rc);
2536 }
2537
2538 static int mdd_index_delete(const struct lu_env *env,
2539                             struct mdd_object *mdd_pobj,
2540                             struct lu_attr *cattr,
2541                             const struct lu_name *lname)
2542 {
2543         struct mdd_device *mdd = mdo2mdd(&mdd_pobj->mod_obj);
2544         struct thandle *handle;
2545         int rc;
2546         ENTRY;
2547
2548         handle = mdd_trans_create(env, mdd);
2549         if (IS_ERR(handle))
2550                 RETURN(PTR_ERR(handle));
2551
2552         rc = mdo_declare_index_delete(env, mdd_pobj, lname->ln_name,
2553                                       handle);
2554         if (rc != 0)
2555                 GOTO(stop, rc);
2556
2557         if (S_ISDIR(cattr->la_mode)) {
2558                 rc = mdo_declare_ref_del(env, mdd_pobj, handle);
2559                 if (rc != 0)
2560                         GOTO(stop, rc);
2561         }
2562
2563         /* Since this will only be used in the error handler path,
2564          * Let's set the thandle to be local and not mess the transno */
2565         handle->th_local = 1;
2566         rc = mdd_trans_start(env, mdd, handle);
2567         if (rc)
2568                 GOTO(stop, rc);
2569
2570         rc = __mdd_index_delete(env, mdd_pobj, lname->ln_name,
2571                                 S_ISDIR(cattr->la_mode), handle);
2572         if (rc)
2573                 GOTO(stop, rc);
2574 stop:
2575         rc = mdd_trans_stop(env, mdd, rc, handle);
2576
2577         RETURN(rc);
2578 }
2579
2580 /**
2581  * Create object and insert it into namespace.
2582  *
2583  * Two operations have to be performed:
2584  *
2585  *  - an allocation of a new object (->do_create()), and
2586  *  - an insertion into a parent index (->dio_insert()).
2587  *
2588  * Due to locking, operation order is not important, when both are
2589  * successful, *but* error handling cases are quite different:
2590  *
2591  *  - if insertion is done first, and following object creation fails,
2592  *  insertion has to be rolled back, but this operation might fail
2593  *  also leaving us with dangling index entry.
2594  *
2595  *  - if creation is done first, is has to be undone if insertion fails,
2596  *  leaving us with leaked space, which is not good but not fatal.
2597  *
2598  * It seems that creation-first is simplest solution, but it is sub-optimal
2599  * in the frequent
2600  *
2601  * $ mkdir foo
2602  * $ mkdir foo
2603  *
2604  * case, because second mkdir is bound to create object, only to
2605  * destroy it immediately.
2606  *
2607  * To avoid this follow local file systems that do double lookup:
2608  *
2609  * 0. lookup -> -EEXIST (mdd_create_sanity_check())
2610  * 1. create            (mdd_create_object_internal())
2611  * 2. insert            (__mdd_index_insert(), lookup again)
2612  *
2613  * \param[in] pobj      parent object
2614  * \param[in] lname     name of child being created
2615  * \param[in,out] child child object being created
2616  * \param[in] spec      additional create parameters
2617  * \param[in] ma        attributes for new child object
2618  *
2619  * \retval              0 on success
2620  * \retval              negative errno on failure
2621  */
2622 static int mdd_create(const struct lu_env *env, struct md_object *pobj,
2623                       const struct lu_name *lname, struct md_object *child,
2624                       struct md_op_spec *spec, struct md_attr *ma)
2625 {
2626         struct mdd_thread_info  *info = mdd_env_info(env);
2627         struct lu_attr          *la = &info->mti_la_for_fix;
2628         struct mdd_object       *mdd_pobj = md2mdd_obj(pobj);
2629         struct mdd_object       *son = md2mdd_obj(child);
2630         struct mdd_device       *mdd = mdo2mdd(pobj);
2631         struct lu_attr          *attr = &ma->ma_attr;
2632         struct thandle          *handle;
2633         struct lu_attr          *pattr = &info->mti_pattr;
2634         struct lu_buf           acl_buf;
2635         struct lu_buf           def_acl_buf;
2636         struct linkea_data      *ldata = &info->mti_link_data;
2637         const char              *name = lname->ln_name;
2638         struct dt_allocation_hint *hint = &mdd_env_info(env)->mti_hint;
2639         int                      rc;
2640         int                      rc2;
2641         ENTRY;
2642
2643         rc = mdd_la_get(env, mdd_pobj, pattr);
2644         if (rc != 0)
2645                 RETURN(rc);
2646
2647         /* Sanity checks before big job. */
2648         rc = mdd_create_sanity_check(env, pobj, pattr, lname, attr, spec);
2649         if (rc)
2650                 RETURN(rc);
2651
2652         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_DQACQ_NET))
2653                 GOTO(out_free, rc = -EINPROGRESS);
2654
2655         handle = mdd_trans_create(env, mdd);
2656         if (IS_ERR(handle))
2657                 GOTO(out_free, rc = PTR_ERR(handle));
2658
2659         lu_buf_check_and_alloc(&info->mti_xattr_buf,
2660                                mdd->mdd_dt_conf.ddp_max_ea_size);
2661         acl_buf = info->mti_xattr_buf;
2662         def_acl_buf.lb_buf = info->mti_key;
2663         def_acl_buf.lb_len = sizeof(info->mti_key);
2664         rc = mdd_acl_init(env, mdd_pobj, attr, &def_acl_buf, &acl_buf);
2665         if (rc < 0)
2666                 GOTO(out_stop, rc);
2667
2668         mdd_object_make_hint(env, mdd_pobj, son, attr, spec, hint);
2669
2670         memset(ldata, 0, sizeof(*ldata));
2671         if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_BAD_PARENT)) {
2672                 struct lu_fid tfid = *mdd_object_fid(mdd_pobj);
2673
2674                 tfid.f_oid--;
2675                 rc = mdd_linkea_prepare(env, son, NULL, NULL,
2676                                         &tfid, lname, 1, 0, ldata);
2677         } else {
2678                 rc = mdd_linkea_prepare(env, son, NULL, NULL,
2679                                         mdd_object_fid(mdd_pobj),
2680                                         lname, 1, 0, ldata);
2681         }
2682
2683         rc = mdd_declare_create(env, mdd, mdd_pobj, son, lname, attr,
2684                                 handle, spec, ldata, &def_acl_buf, &acl_buf,
2685                                 hint);
2686         if (rc)
2687                 GOTO(out_stop, rc);
2688
2689         rc = mdd_trans_start(env, mdd, handle);
2690         if (rc)
2691                 GOTO(out_stop, rc);
2692
2693         rc = mdd_create_object(env, mdd_pobj, son, attr, spec, &acl_buf,
2694                                &def_acl_buf, hint, handle);
2695         if (rc != 0)
2696                 GOTO(out_stop, rc);
2697
2698         if (unlikely(spec->sp_cr_flags & MDS_OPEN_VOLATILE)) {
2699                 mdd_write_lock(env, son, MOR_TGT_CHILD);
2700                 son->mod_flags |= VOLATILE_OBJ;
2701                 rc = mdd_orphan_insert(env, son, handle);
2702                 GOTO(out_volatile, rc);
2703         } else {
2704                 rc = __mdd_index_insert(env, mdd_pobj, mdo2fid(son),
2705                                       attr->la_mode, name, handle);
2706                 if (rc != 0)
2707                         GOTO(err_created, rc);
2708
2709                 mdd_links_add(env, son, mdo2fid(mdd_pobj), lname, handle,
2710                               ldata, 1);
2711
2712                 /* update parent directory mtime/ctime */
2713                 *la = *attr;
2714                 la->la_valid = LA_CTIME | LA_MTIME;
2715                 rc = mdd_update_time(env, mdd_pobj, pattr, la, handle);
2716                 if (rc)
2717                         GOTO(err_insert, rc);
2718         }
2719
2720         EXIT;
2721 err_insert:
2722         if (rc != 0) {
2723                 if (spec->sp_cr_flags & MDS_OPEN_VOLATILE)
2724                         rc2 = mdd_orphan_delete(env, son, handle);
2725                 else
2726                         rc2 = __mdd_index_delete(env, mdd_pobj, name,
2727                                                  S_ISDIR(attr->la_mode),
2728                                                  handle);
2729                 if (rc2 != 0)
2730                         goto out_stop;
2731
2732 err_created:
2733                 mdd_write_lock(env, son, MOR_TGT_CHILD);
2734                 if (S_ISDIR(attr->la_mode)) {
2735                         /* Drop the reference, no need to delete "."/"..",
2736                          * because the object is to be destroyed directly. */
2737                         rc2 = mdo_ref_del(env, son, handle);
2738                         if (rc2 != 0) {
2739                                 mdd_write_unlock(env, son);
2740                                 goto out_stop;
2741                         }
2742                 }
2743 out_volatile:
2744                 /* For volatile files drop one link immediately, since there is
2745                  * no filename in the namespace, and save any error returned. */
2746                 rc2 = mdo_ref_del(env, son, handle);
2747                 if (rc2 != 0) {
2748                         mdd_write_unlock(env, son);
2749                         if (unlikely(rc == 0))
2750                                 rc = rc2;
2751                         goto out_stop;
2752                 }
2753
2754                 /* Don't destroy the volatile object on success */
2755                 if (likely(rc != 0))
2756                         mdo_destroy(env, son, handle);
2757                 mdd_write_unlock(env, son);
2758         }
2759
2760         if (rc == 0 && fid_is_namespace_visible(mdo2fid(son)) &&
2761             likely((spec->sp_cr_flags & MDS_OPEN_VOLATILE) == 0))
2762                 rc = mdd_changelog_ns_store(env, mdd,
2763                                 S_ISDIR(attr->la_mode) ? CL_MKDIR :
2764                                 S_ISREG(attr->la_mode) ? CL_CREATE :
2765                                 S_ISLNK(attr->la_mode) ? CL_SOFTLINK : CL_MKNOD,
2766                                 0, son, mdo2fid(mdd_pobj), NULL, NULL, lname,
2767                                 NULL, handle);
2768 out_stop:
2769         rc2 = mdd_trans_stop(env, mdd, rc, handle);
2770         if (rc == 0) {
2771                 /* If creation fails, it is most likely due to the remote update
2772                  * failure, because local transaction will mostly succeed at
2773                  * this stage. There is no easy way to rollback all of previous
2774                  * updates, so let's remove the object from namespace, and
2775                  * LFSCK should handle the orphan object. */
2776                 if (rc2 < 0 && !mdd_object_remote(mdd_pobj))
2777                         mdd_index_delete(env, mdd_pobj, attr, lname);
2778                 rc = rc2;
2779         }
2780 out_free:
2781         if (is_vmalloc_addr(ldata->ld_buf))
2782                 /* if we vmalloced a large buffer drop it */
2783                 lu_buf_free(ldata->ld_buf);
2784
2785         /* The child object shouldn't be cached anymore */
2786         if (rc)
2787                 set_bit(LU_OBJECT_HEARD_BANSHEE,
2788                         &child->mo_lu.lo_header->loh_flags);
2789         return rc;
2790 }
2791
2792 /*
2793  * Get locks on parents in proper order
2794  * RETURN: < 0 - error, rename_order if successful
2795  */
2796 enum rename_order {
2797         MDD_RN_SAME,
2798         MDD_RN_SRCTGT,
2799         MDD_RN_TGTSRC
2800 };
2801
2802 static int mdd_rename_order(const struct lu_env *env,
2803                             struct mdd_device *mdd,
2804                             struct mdd_object *src_pobj,
2805                             const struct lu_attr *pattr,
2806                             struct mdd_object *tgt_pobj)
2807 {
2808         /* order of locking, 1 - tgt-src, 0 - src-tgt*/
2809         int rc;
2810         ENTRY;
2811
2812         if (src_pobj == tgt_pobj)
2813                 RETURN(MDD_RN_SAME);
2814
2815         /* compared the parent child relationship of src_p&tgt_p */
2816         if (lu_fid_eq(&mdd->mdd_root_fid, mdo2fid(src_pobj))){
2817                 rc = MDD_RN_SRCTGT;
2818         } else if (lu_fid_eq(&mdd->mdd_root_fid, mdo2fid(tgt_pobj))) {
2819                 rc = MDD_RN_TGTSRC;
2820         } else {
2821                 rc = mdd_is_parent(env, mdd, src_pobj, pattr, mdo2fid(tgt_pobj),
2822                                    NULL);
2823                 if (rc == -EREMOTE)
2824                         rc = 0;
2825
2826                 if (rc == 1)
2827                         rc = MDD_RN_TGTSRC;
2828                 else if (rc == 0)
2829                         rc = MDD_RN_SRCTGT;
2830         }
2831
2832         RETURN(rc);
2833 }
2834
2835 /* has not mdd_write{read}_lock on any obj yet. */
2836 static int mdd_rename_sanity_check(const struct lu_env *env,
2837                                    struct mdd_object *src_pobj,
2838                                    const struct lu_attr *pattr,
2839                                    struct mdd_object *tgt_pobj,
2840                                    const struct lu_attr *tpattr,
2841                                    struct mdd_object *sobj,
2842                                    const struct lu_attr *cattr,
2843                                    struct mdd_object *tobj,
2844                                    const struct lu_attr *tattr)
2845 {
2846         int rc = 0;
2847         ENTRY;
2848
2849         /* XXX: when get here, sobj must NOT be NULL,
2850          * the other case has been processed in cld_rename
2851          * before mdd_rename and enable MDS_PERM_BYPASS. */
2852         LASSERT(sobj);
2853
2854         /*
2855          * If we are using project inheritance, we only allow renames
2856          * into our tree when the project IDs are the same; otherwise
2857          * tree quota mechanism would be circumvented.
2858          */
2859         if (((tpattr->la_flags & LUSTRE_PROJINHERIT_FL) &&
2860             tpattr->la_projid != cattr->la_projid) ||
2861             ((pattr->la_flags & LUSTRE_PROJINHERIT_FL) &&
2862             (pattr->la_projid != tpattr->la_projid)))
2863                 RETURN(-EXDEV);
2864
2865         rc = mdd_may_delete(env, src_pobj, pattr, sobj, cattr, NULL, 1, 0);
2866         if (rc)
2867                 RETURN(rc);
2868
2869         /* XXX: when get here, "tobj == NULL" means tobj must
2870          * NOT exist (neither on remote MDS, such case has been
2871          * processed in cld_rename before mdd_rename and enable
2872          * MDS_PERM_BYPASS).
2873          * So check may_create, but not check may_unlink. */
2874         if (tobj == NULL)
2875                 rc = mdd_may_create(env, tgt_pobj, tpattr, NULL,
2876                                     (src_pobj != tgt_pobj));
2877         else
2878                 rc = mdd_may_delete(env, tgt_pobj, tpattr, tobj, tattr, cattr,
2879                                     (src_pobj != tgt_pobj), 1);
2880
2881         if (!rc && !tobj && (src_pobj != tgt_pobj) && S_ISDIR(cattr->la_mode))
2882                 rc = __mdd_may_link(env, tgt_pobj, tpattr);
2883
2884         RETURN(rc);
2885 }
2886
2887 static int mdd_declare_rename(const struct lu_env *env,
2888                               struct mdd_device *mdd,
2889                               struct mdd_object *mdd_spobj,
2890                               struct mdd_object *mdd_tpobj,
2891                               struct mdd_object *mdd_sobj,
2892                               struct mdd_object *mdd_tobj,
2893                               const struct lu_name *sname,
2894                               const struct lu_name *tname,
2895                               struct md_attr *ma,
2896                               struct linkea_data *ldata,
2897                               struct thandle *handle)
2898 {
2899         struct lu_attr    *la = &mdd_env_info(env)->mti_la_for_fix;
2900         int rc;
2901
2902         LASSERT(ma->ma_attr.la_valid & LA_CTIME);
2903         la->la_ctime = la->la_mtime = ma->ma_attr.la_ctime;
2904
2905         LASSERT(mdd_spobj);
2906         LASSERT(mdd_tpobj);
2907         LASSERT(mdd_sobj);
2908
2909         /* name from source dir */
2910         rc = mdo_declare_index_delete(env, mdd_spobj, sname->ln_name, handle);
2911         if (rc)
2912                 return rc;
2913
2914         /* .. from source child */
2915         if (S_ISDIR(mdd_object_type(mdd_sobj))) {
2916                 /* source child can be directory,
2917                  * counted by source dir's nlink */
2918                 rc = mdo_declare_ref_del(env, mdd_spobj, handle);
2919                 if (rc)
2920                         return rc;
2921                 if (mdd_spobj != mdd_tpobj) {
2922                         rc = mdo_declare_index_delete(env, mdd_sobj, dotdot,
2923                                                       handle);
2924                         if (rc != 0)
2925                                 return rc;
2926
2927                         rc = mdo_declare_index_insert(env, mdd_sobj,
2928                                                       mdo2fid(mdd_tpobj),
2929                                                       S_IFDIR, dotdot, handle);
2930                         if (rc != 0)
2931                                 return rc;
2932                 }
2933
2934                 /* new target child can be directory,
2935                  * counted by target dir's nlink */
2936                 rc = mdo_declare_ref_add(env, mdd_tpobj, handle);
2937                 if (rc != 0)
2938                         return rc;
2939         }
2940
2941         la->la_valid = LA_CTIME | LA_MTIME;
2942         rc = mdo_declare_attr_set(env, mdd_spobj, la, handle);
2943         if (rc != 0)
2944                 return rc;
2945
2946         rc = mdo_declare_attr_set(env, mdd_tpobj, la, handle);
2947         if (rc != 0)
2948                 return rc;
2949
2950         la->la_valid = LA_CTIME;
2951         rc = mdo_declare_attr_set(env, mdd_sobj, la, handle);
2952         if (rc)
2953                 return rc;
2954
2955         rc = mdd_declare_links_add(env, mdd_sobj, handle, ldata);
2956         if (rc)
2957                 return rc;
2958
2959         /* new name */
2960         rc = mdo_declare_index_insert(env, mdd_tpobj, mdo2fid(mdd_sobj),
2961                                       mdd_object_type(mdd_sobj),
2962                                       tname->ln_name, handle);
2963         if (rc != 0)
2964                 return rc;
2965
2966         if (mdd_tobj && mdd_object_exists(mdd_tobj)) {
2967                 /* delete target child in target parent directory */
2968                 rc = mdo_declare_index_delete(env, mdd_tpobj, tname->ln_name,
2969                                               handle);
2970                 if (rc)
2971                         return rc;
2972
2973                 rc = mdo_declare_ref_del(env, mdd_tobj, handle);
2974                 if (rc)
2975                         return rc;
2976
2977                 if (S_ISDIR(mdd_object_type(mdd_tobj))) {
2978                         /* target child can be directory,
2979                          * delete "." reference in target child directory */
2980                         rc = mdo_declare_ref_del(env, mdd_tobj, handle);
2981                         if (rc)
2982                                 return rc;
2983
2984                         /* delete ".." reference in target parent directory */
2985                         rc = mdo_declare_ref_del(env, mdd_tpobj, handle);
2986                         if (rc)
2987                                 return rc;
2988                 }
2989
2990                 la->la_valid = LA_CTIME;
2991                 rc = mdo_declare_attr_set(env, mdd_tobj, la, handle);
2992                 if (rc)
2993                         return rc;
2994
2995                 rc = mdd_declare_finish_unlink(env, mdd_tobj, handle);
2996                 if (rc)
2997                         return rc;
2998         }
2999
3000         rc = mdd_declare_changelog_store(env, mdd, CL_RENAME, tname, sname,
3001                                          handle);
3002         if (rc)
3003                 return rc;
3004
3005         return rc;
3006 }
3007
3008 /* src object can be remote that is why we use only fid and type of object */
3009 static int mdd_rename(const struct lu_env *env,
3010                       struct md_object *src_pobj, struct md_object *tgt_pobj,
3011                       const struct lu_fid *lf, const struct lu_name *lsname,
3012                       struct md_object *tobj, const struct lu_name *ltname,
3013                       struct md_attr *ma)
3014 {
3015         const char *sname = lsname->ln_name;
3016         const char *tname = ltname->ln_name;
3017         struct lu_attr    *la = &mdd_env_info(env)->mti_la_for_fix;
3018         struct mdd_object *mdd_spobj = md2mdd_obj(src_pobj); /* source parent */
3019         struct mdd_object *mdd_tpobj = md2mdd_obj(tgt_pobj);
3020         struct mdd_device *mdd = mdo2mdd(src_pobj);
3021         struct mdd_object *mdd_sobj = NULL;                  /* source object */
3022         struct mdd_object *mdd_tobj = NULL;
3023         struct lu_attr *cattr = MDD_ENV_VAR(env, cattr);
3024         struct lu_attr *pattr = MDD_ENV_VAR(env, pattr);
3025         struct lu_attr *tattr = MDD_ENV_VAR(env, tattr);
3026         struct lu_attr *tpattr = MDD_ENV_VAR(env, tpattr);
3027         struct thandle *handle;
3028         struct linkea_data  *ldata = &mdd_env_info(env)->mti_link_data;
3029         const struct lu_fid *tpobj_fid = mdo2fid(mdd_tpobj);
3030         const struct lu_fid *spobj_fid = mdo2fid(mdd_spobj);
3031         bool is_dir;
3032         bool tobj_ref = 0;
3033         bool tobj_locked = 0;
3034         unsigned cl_flags = 0;
3035         int rc, rc2;
3036         ENTRY;
3037
3038         if (tobj)
3039                 mdd_tobj = md2mdd_obj(tobj);
3040
3041         mdd_sobj = mdd_object_find(env, mdd, lf);
3042         if (IS_ERR(mdd_sobj))
3043                 RETURN(PTR_ERR(mdd_sobj));
3044
3045         rc = mdd_la_get(env, mdd_sobj, cattr);
3046         if (rc)
3047                 GOTO(out_pending, rc);
3048
3049         rc = mdd_la_get(env, mdd_spobj, pattr);
3050         if (rc)
3051                 GOTO(out_pending, rc);
3052
3053         if (mdd_tobj) {
3054                 rc = mdd_la_get(env, mdd_tobj, tattr);
3055                 if (rc)
3056                         GOTO(out_pending, rc);
3057                 /* search for an existing archive.
3058                  * we should check ahead as the object
3059                  * can be destroyed in this transaction */
3060                 if (mdd_hsm_archive_exists(env, mdd_tobj, ma))
3061                         cl_flags |= CLF_RENAME_LAST_EXISTS;
3062         }
3063
3064         rc = mdd_la_get(env, mdd_tpobj, tpattr);
3065         if (rc)
3066                 GOTO(out_pending, rc);
3067
3068         rc = mdd_rename_sanity_check(env, mdd_spobj, pattr, mdd_tpobj, tpattr,
3069                                      mdd_sobj, cattr, mdd_tobj, tattr);
3070         if (rc)
3071                 GOTO(out_pending, rc);
3072
3073         rc = mdd_name_check(mdd, ltname);
3074         if (rc < 0)
3075                 GOTO(out_pending, rc);
3076
3077         /* FIXME: Should consider tobj and sobj too in rename_lock. */
3078         rc = mdd_rename_order(env, mdd, mdd_spobj, pattr, mdd_tpobj);
3079         if (rc < 0)
3080                 GOTO(out_pending, rc);
3081
3082         handle = mdd_trans_create(env, mdd);
3083         if (IS_ERR(handle))
3084                 GOTO(out_pending, rc = PTR_ERR(handle));
3085
3086         memset(ldata, 0, sizeof(*ldata));
3087         rc = mdd_linkea_prepare(env, mdd_sobj, mdd_object_fid(mdd_spobj),
3088                                 lsname, mdd_object_fid(mdd_tpobj), ltname,
3089                                 1, 0, ldata);
3090         if (rc)
3091                 GOTO(stop, rc);
3092
3093         rc = mdd_declare_rename(env, mdd, mdd_spobj, mdd_tpobj, mdd_sobj,
3094                                 mdd_tobj, lsname, ltname, ma, ldata, handle);
3095         if (rc)
3096                 GOTO(stop, rc);
3097
3098         rc = mdd_trans_start(env, mdd, handle);
3099         if (rc)
3100                 GOTO(stop, rc);
3101
3102         is_dir = S_ISDIR(cattr->la_mode);
3103
3104         /* Remove source name from source directory */
3105         rc = __mdd_index_delete(env, mdd_spobj, sname, is_dir, handle);
3106         if (rc != 0)
3107                 GOTO(stop, rc);
3108
3109         /* "mv dir1 dir2" needs "dir1/.." link update */
3110         if (is_dir && !lu_fid_eq(spobj_fid, tpobj_fid)) {
3111                 rc = __mdd_index_delete_only(env, mdd_sobj, dotdot, handle);
3112                 if (rc != 0)
3113                         GOTO(fixup_spobj2, rc);
3114
3115                 rc = __mdd_index_insert_only(env, mdd_sobj, tpobj_fid, S_IFDIR,
3116                                              dotdot, handle);
3117                 if (rc != 0)
3118                         GOTO(fixup_spobj, rc);
3119         }
3120
3121         if (mdd_tobj != NULL && mdd_object_exists(mdd_tobj)) {
3122                 rc = __mdd_index_delete(env, mdd_tpobj, tname, is_dir, handle);
3123                 if (rc != 0)
3124                         /* tname might been renamed to something else */
3125                         GOTO(fixup_spobj, rc);
3126         }
3127
3128         /* Insert new fid with target name into target dir */
3129         rc = __mdd_index_insert(env, mdd_tpobj, lf, cattr->la_mode,
3130                                 tname, handle);
3131         if (rc != 0)
3132                 GOTO(fixup_tpobj, rc);
3133
3134         LASSERT(ma->ma_attr.la_valid & LA_CTIME);
3135         la->la_ctime = la->la_mtime = ma->ma_attr.la_ctime;
3136
3137         /* XXX: mdd_sobj must be local one if it is NOT NULL. */
3138         la->la_valid = LA_CTIME;
3139         rc = mdd_update_time(env, mdd_sobj, cattr, la, handle);
3140         if (rc)
3141                 GOTO(fixup_tpobj, rc);
3142
3143         /* Update the linkEA for the source object */
3144         mdd_write_lock(env, mdd_sobj, MOR_SRC_CHILD);
3145         rc = mdd_links_rename(env, mdd_sobj, mdo2fid(mdd_spobj), lsname,
3146                               mdo2fid(mdd_tpobj), ltname, handle, ldata,
3147                               0, 0);
3148         if (rc == -ENOENT)
3149                 /* Old files might not have EA entry */
3150                 mdd_links_add(env, mdd_sobj, mdo2fid(mdd_spobj),
3151                               lsname, handle, NULL, 0);
3152         mdd_write_unlock(env, mdd_sobj);
3153         /* We don't fail the transaction if the link ea can't be
3154            updated -- fid2path will use alternate lookup method. */
3155         rc = 0;
3156
3157         /* Remove old target object
3158          * For tobj is remote case cmm layer has processed
3159          * and set tobj to NULL then. So when tobj is NOT NULL,
3160          * it must be local one.
3161          */
3162         if (tobj && mdd_object_exists(mdd_tobj)) {
3163                 mdd_write_lock(env, mdd_tobj, MOR_TGT_CHILD);
3164                 tobj_locked = 1;
3165                 if (mdd_is_dead_obj(mdd_tobj)) {
3166                         /* shld not be dead, something is wrong */
3167                         CERROR("tobj is dead, something is wrong\n");
3168                         rc = -EINVAL;
3169                         goto cleanup;
3170                 }
3171                 mdo_ref_del(env, mdd_tobj, handle);
3172
3173                 /* Remove dot reference. */
3174                 if (S_ISDIR(tattr->la_mode))
3175                         mdo_ref_del(env, mdd_tobj, handle);
3176                 tobj_ref = 1;
3177
3178                 /* fetch updated nlink */
3179                 rc = mdd_la_get(env, mdd_tobj, tattr);
3180                 if (rc != 0) {
3181                         CERROR("%s: Failed to get nlink for tobj "
3182                                 DFID": rc = %d\n",
3183                                 mdd2obd_dev(mdd)->obd_name,
3184                                 PFID(tpobj_fid), rc);
3185                         GOTO(fixup_tpobj, rc);
3186                 }
3187
3188                 la->la_valid = LA_CTIME;
3189                 rc = mdd_update_time(env, mdd_tobj, tattr, la, handle);
3190                 if (rc != 0) {
3191                         CERROR("%s: Failed to set ctime for tobj "
3192                                 DFID": rc = %d\n",
3193                                 mdd2obd_dev(mdd)->obd_name,
3194                                 PFID(tpobj_fid), rc);
3195                         GOTO(fixup_tpobj, rc);
3196                 }
3197
3198                 /* XXX: this transfer to ma will be removed with LOD/OSP */
3199                 ma->ma_attr = *tattr;
3200                 ma->ma_valid |= MA_INODE;
3201                 rc = mdd_finish_unlink(env, mdd_tobj, ma, mdd_tpobj, ltname,
3202                                        handle);
3203                 if (rc != 0) {
3204                         CERROR("%s: Failed to unlink tobj "
3205                                 DFID": rc = %d\n",
3206                                 mdd2obd_dev(mdd)->obd_name,
3207                                 PFID(tpobj_fid), rc);
3208                         GOTO(fixup_tpobj, rc);
3209                 }
3210
3211                 /* fetch updated nlink */
3212                 rc = mdd_la_get(env, mdd_tobj, tattr);
3213                 if (rc == -ENOENT) {
3214                         /* the object got removed, let's
3215                          * return the latest known attributes */
3216                         tattr->la_nlink = 0;
3217                         rc = 0;
3218                 } else if (rc != 0) {
3219                         CERROR("%s: Failed to get nlink for tobj "
3220                                 DFID": rc = %d\n",
3221                                 mdd2obd_dev(mdd)->obd_name,
3222                                 PFID(tpobj_fid), rc);
3223                         GOTO(fixup_tpobj, rc);
3224                 }
3225                 /* XXX: this transfer to ma will be removed with LOD/OSP */
3226                 ma->ma_attr = *tattr;
3227                 ma->ma_valid |= MA_INODE;
3228
3229                 if (tattr->la_nlink == 0)
3230                         cl_flags |= CLF_RENAME_LAST;
3231                 else
3232                         cl_flags &= ~CLF_RENAME_LAST_EXISTS;
3233         }
3234
3235         la->la_valid = LA_CTIME | LA_MTIME;
3236         rc = mdd_update_time(env, mdd_spobj, pattr, la, handle);
3237         if (rc)
3238                 GOTO(fixup_tpobj, rc);
3239
3240         if (mdd_spobj != mdd_tpobj) {
3241                 la->la_valid = LA_CTIME | LA_MTIME;
3242                 rc = mdd_update_time(env, mdd_tpobj, tpattr, la, handle);
3243                 if (rc != 0)
3244                         GOTO(fixup_tpobj, rc);
3245         }
3246
3247         EXIT;
3248
3249 fixup_tpobj:
3250         if (rc) {
3251                 rc2 = __mdd_index_delete(env, mdd_tpobj, tname, is_dir, handle);
3252                 if (rc2)
3253                         CWARN("tp obj fix error %d\n",rc2);
3254
3255                 if (mdd_tobj && mdd_object_exists(mdd_tobj) &&
3256                     !mdd_is_dead_obj(mdd_tobj)) {
3257                         if (tobj_ref) {
3258                                 mdo_ref_add(env, mdd_tobj, handle);
3259                                 if (is_dir)
3260                                         mdo_ref_add(env, mdd_tobj, handle);
3261                         }
3262
3263                         rc2 = __mdd_index_insert(env, mdd_tpobj,
3264                                                   mdo2fid(mdd_tobj),
3265                                                   mdd_object_type(mdd_tobj),
3266                                                   tname, handle);
3267                         if (rc2 != 0)
3268                                 CWARN("tp obj fix error: rc = %d\n", rc2);
3269                 }
3270         }
3271
3272 fixup_spobj:
3273         if (rc && is_dir && mdd_sobj && mdd_spobj != mdd_tpobj) {
3274                 rc2 = __mdd_index_delete_only(env, mdd_sobj, dotdot, handle);
3275                 if (rc2)
3276                         CWARN("%s: sp obj dotdot delete error: rc = %d\n",
3277                                mdd2obd_dev(mdd)->obd_name, rc2);
3278
3279
3280                 rc2 = __mdd_index_insert_only(env, mdd_sobj, spobj_fid, S_IFDIR,
3281                                               dotdot, handle);
3282                 if (rc2 != 0)
3283                         CWARN("%s: sp obj dotdot insert error: rc = %d\n",
3284                               mdd2obd_dev(mdd)->obd_name, rc2);
3285         }
3286
3287 fixup_spobj2:
3288         if (rc != 0) {
3289                 rc2 = __mdd_index_insert(env, mdd_spobj, lf,
3290                                          mdd_object_type(mdd_sobj), sname,
3291                                          handle);
3292                 if (rc2 != 0)
3293                         CWARN("sp obj fix error: rc = %d\n", rc2);
3294         }
3295
3296 cleanup:
3297         if (tobj_locked)
3298                 mdd_write_unlock(env, mdd_tobj);
3299
3300         if (rc == 0)
3301                 rc = mdd_changelog_ns_store(env, mdd, CL_RENAME, cl_flags,
3302                                             mdd_tobj, tpobj_fid, lf, spobj_fid,
3303                                             ltname, lsname, handle);
3304
3305 stop:
3306         rc = mdd_trans_stop(env, mdd, rc, handle);
3307
3308 out_pending:
3309         mdd_object_put(env, mdd_sobj);
3310         return rc;
3311 }
3312
3313 /**
3314  * During migration once the parent FID has been changed,
3315  * we need update the parent FID in linkea.
3316  **/
3317 static int mdd_linkea_update_child_internal(const struct lu_env *env,
3318                                             struct mdd_object *parent,
3319                                             struct mdd_object *newparent,
3320                                             struct mdd_object *child,
3321                                             const char *name, int namelen,
3322                                             struct thandle *handle,
3323                                             bool declare)
3324 {
3325         struct mdd_thread_info  *info = mdd_env_info(env);
3326         struct linkea_data      ldata = { NULL };
3327         struct lu_buf           *buf = &info->mti_link_buf;
3328         int                     count;
3329         int                     rc = 0;
3330
3331         ENTRY;
3332
3333         buf = lu_buf_check_and_alloc(buf, PATH_MAX);
3334         if (buf->lb_buf == NULL)
3335                 RETURN(-ENOMEM);
3336
3337         ldata.ld_buf = buf;
3338         rc = mdd_links_read(env, child, &ldata);
3339         if (rc != 0) {
3340                 if (rc == -ENOENT || rc == -ENODATA)
3341                         rc = 0;
3342                 RETURN(rc);
3343         }
3344
3345         LASSERT(ldata.ld_leh != NULL);
3346         ldata.ld_lee = (struct link_ea_entry *)(ldata.ld_leh + 1);
3347         for (count = 0; count < ldata.ld_leh->leh_reccount; count++) {
3348                 struct mdd_device *mdd = mdo2mdd(&child->mod_obj);
3349                 struct lu_name lname;
3350                 struct lu_fid  fid;
3351
3352                 linkea_entry_unpack(ldata.ld_lee, &ldata.ld_reclen,
3353                                     &lname, &fid);
3354
3355                 if (strncmp(lname.ln_name, name, namelen) != 0 ||
3356                     !lu_fid_eq(&fid, mdd_object_fid(parent))) {
3357                         ldata.ld_lee = (struct link_ea_entry *)
3358                                        ((char *)ldata.ld_lee +
3359                                         ldata.ld_reclen);
3360                         continue;
3361                 }
3362
3363                 CDEBUG(D_INFO, "%s: update "DFID" with %.*s:"DFID"\n",
3364                        mdd2obd_dev(mdd)->obd_name, PFID(mdd_object_fid(child)),
3365                        lname.ln_namelen, lname.ln_name,
3366                        PFID(mdd_object_fid(newparent)));
3367                 /* update to the new parent fid */
3368                 linkea_entry_pack(ldata.ld_lee, &lname,
3369                                   mdd_object_fid(newparent));
3370                 if (declare)
3371                         rc = mdd_declare_links_add(env, child, handle, &ldata);
3372                 else
3373                         rc = mdd_links_write(env, child, &ldata, handle);
3374                 break;
3375         }
3376         RETURN(rc);
3377 }
3378
3379 static int mdd_linkea_declare_update_child(const struct lu_env *env,
3380                                            struct mdd_object *parent,
3381                                            struct mdd_object *newparent,
3382                                            struct mdd_object *child,
3383                                            const char *name, int namelen,
3384                                            struct thandle *handle)
3385 {
3386         return mdd_linkea_update_child_internal(env, parent, newparent,
3387                                                 child, name,
3388                                                 namelen, handle, true);
3389 }
3390
3391 static int mdd_linkea_update_child(const struct lu_env *env,
3392                                    struct mdd_object *parent,
3393                                    struct mdd_object *newparent,
3394                                    struct mdd_object *child,
3395                                    const char *name, int namelen,
3396                                    struct thandle *handle)
3397 {
3398         return mdd_linkea_update_child_internal(env, parent, newparent,
3399                                                 child, name,
3400                                                 namelen, handle, false);
3401 }
3402
3403 static int mdd_update_linkea_internal(const struct lu_env *env,
3404                                       struct mdd_object *mdd_pobj,
3405                                       struct mdd_object *mdd_sobj,
3406                                       struct mdd_object *mdd_tobj,
3407                                       const struct lu_name *child_name,
3408                                       struct linkea_data *ldata,
3409                                       struct thandle *handle,
3410                                       int declare)
3411 {
3412         struct mdd_thread_info  *info = mdd_env_info(env);
3413         int                     count;
3414         int                     rc = 0;
3415         ENTRY;
3416
3417         LASSERT(ldata->ld_buf != NULL);
3418         LASSERT(ldata->ld_leh != NULL);
3419
3420         /* If it is mulitple links file, we need update the name entry for
3421          * all parent */
3422         ldata->ld_lee = (struct link_ea_entry *)(ldata->ld_leh + 1);
3423         for (count = 0; count < ldata->ld_leh->leh_reccount; count++) {
3424                 struct mdd_device       *mdd = mdo2mdd(&mdd_sobj->mod_obj);
3425                 struct mdd_object       *pobj;
3426                 struct lu_name          lname;
3427                 struct lu_fid           fid;
3428
3429                 linkea_entry_unpack(ldata->ld_lee, &ldata->ld_reclen,
3430                                     &lname, &fid);
3431                 pobj = mdd_object_find(env, mdd, &fid);
3432                 if (IS_ERR(pobj)) {
3433                         CWARN("%s: cannot find obj "DFID": rc = %ld\n",
3434                               mdd2obd_dev(mdd)->obd_name, PFID(&fid),
3435                               PTR_ERR(pobj));
3436                         continue;
3437                 }
3438
3439                 if (!mdd_object_exists(pobj)) {
3440                         CDEBUG(D_INFO, "%s: obj "DFID" does not exist\n",
3441                               mdd2obd_dev(mdd)->obd_name, PFID(&fid));
3442                         goto next_put;
3443                 }
3444
3445                 if (pobj == mdd_pobj &&
3446                     lname.ln_namelen == child_name->ln_namelen &&
3447                     strncmp(lname.ln_name, child_name->ln_name,
3448                             lname.ln_namelen) == 0) {
3449                         CDEBUG(D_INFO, "%s: skip its own %s: "DFID"\n",
3450                               mdd2obd_dev(mdd)->obd_name, child_name->ln_name,
3451                               PFID(&fid));
3452                         goto next_put;
3453                 }
3454
3455                 CDEBUG(D_INFO, "%s: update "DFID" with "DNAME":"DFID"\n",
3456                        mdd2obd_dev(mdd)->obd_name, PFID(mdd_object_fid(pobj)),
3457                        PNAME(&lname), PFID(mdd_object_fid(mdd_tobj)));
3458
3459                 if (declare) {
3460                         /* Remove source name from source directory */
3461                         /* Insert new fid with target name into target dir */
3462                         rc = mdo_declare_index_delete(env, pobj, lname.ln_name,
3463                                                       handle);
3464                         if (rc != 0)
3465                                 GOTO(next_put, rc);
3466
3467                         rc = mdo_declare_index_insert(env, pobj,
3468                                         mdd_object_fid(mdd_tobj),
3469                                         mdd_object_type(mdd_tobj),
3470                                         lname.ln_name, handle);
3471                         if (rc != 0)
3472                                 GOTO(next_put, rc);
3473
3474                         rc = mdo_declare_ref_add(env, mdd_tobj, handle);
3475                         if (rc)
3476                                 GOTO(next_put, rc);
3477
3478                         rc = mdo_declare_ref_del(env, mdd_sobj, handle);
3479                         if (rc)
3480                                 GOTO(next_put, rc);
3481                 } else {
3482                         char *tmp_name = info->mti_key;
3483
3484                         if (lname.ln_namelen >= sizeof(info->mti_key)) {
3485                                 /* lnamelen is too big(> NAME_MAX + 16),
3486                                  * something wrong about this linkea, let's
3487                                  * skip it */
3488                                 CWARN("%s: the name %.*s is too long under "
3489                                       DFID"\n", mdd2obd_dev(mdd)->obd_name,
3490                                       lname.ln_namelen, lname.ln_name,
3491                                       PFID(&fid));
3492                                 goto next_put;
3493                         }
3494
3495                         /* Note: lname might be without \0 at the end, see
3496                          * linkea_entry_unpack(), let's add extra \0 by
3497                          * snprintf */
3498                         snprintf(tmp_name, sizeof(info->mti_key), "%.*s",
3499                                  lname.ln_namelen, lname.ln_name);
3500                         lname.ln_name = tmp_name;
3501
3502                         /* Let's check if this linkEA still valid, before
3503                          * it might be packed into the RPC buffer. */
3504                         rc = mdd_lookup(env, &pobj->mod_obj, &lname,
3505                                         &info->mti_fid, NULL);
3506                         if (rc < 0 || !lu_fid_eq(&info->mti_fid,
3507                                                  mdd_object_fid(mdd_sobj)))
3508                                 GOTO(next_put, rc == -ENOENT ? 0 : rc);
3509
3510                         rc = __mdd_index_delete(env, pobj, tmp_name, 0, handle);
3511                         if (rc != 0)
3512                                 GOTO(next_put, rc);
3513
3514                         rc = __mdd_index_insert(env, pobj,
3515                                         mdd_object_fid(mdd_tobj),
3516                                         mdd_object_type(mdd_tobj),
3517                                         tmp_name, handle);
3518                         if (rc != 0)
3519                                 GOTO(next_put, rc);
3520
3521                         mdd_write_lock(env, mdd_tobj, MOR_SRC_CHILD);
3522                         rc = mdo_ref_add(env, mdd_tobj, handle);
3523                         mdd_write_unlock(env, mdd_tobj);
3524                         if (rc)
3525                                 GOTO(next_put, rc);
3526
3527                         mdd_write_lock(env, mdd_sobj, MOR_TGT_CHILD);
3528                         mdo_ref_del(env, mdd_sobj, handle);
3529                         mdd_write_unlock(env, mdd_sobj);
3530                 }
3531 next_put:
3532                 mdd_object_put(env, pobj);
3533                 if (rc != 0)
3534                         break;
3535
3536                 ldata->ld_lee = (struct link_ea_entry *)((char *)ldata->ld_lee +
3537                                                          ldata->ld_reclen);
3538         }
3539
3540         RETURN(rc);
3541 }
3542
3543 static int mdd_migrate_xattrs(const struct lu_env *env,
3544                               struct mdd_object *mdd_sobj,
3545                               struct mdd_object *mdd_tobj)
3546 {
3547         struct mdd_thread_info  *info = mdd_env_info(env);
3548         struct mdd_device       *mdd = mdo2mdd(&mdd_sobj->mod_obj);
3549         char                    *xname;
3550         struct thandle          *handle;
3551         struct lu_buf           xbuf;
3552         int                     xlen;
3553         int                     rem;
3554         int                     xsize;
3555         int                     list_xsize;
3556         struct lu_buf           list_xbuf;
3557         int                     rc;
3558
3559         /* retrieve xattr list from the old object */
3560         list_xsize = mdo_xattr_list(env, mdd_sobj, &LU_BUF_NULL);
3561         if (list_xsize == -ENODATA)
3562                 return 0;
3563
3564         if (list_xsize < 0)
3565                 return list_xsize;
3566
3567         lu_buf_check_and_alloc(&info->mti_big_buf, list_xsize);
3568         if (info->mti_big_buf.lb_buf == NULL)
3569                 return -ENOMEM;
3570
3571         list_xbuf.lb_buf = info->mti_big_buf.lb_buf;
3572         list_xbuf.lb_len = list_xsize;
3573         rc = mdo_xattr_list(env, mdd_sobj, &list_xbuf);
3574         if (rc < 0)
3575                 return rc;
3576         rc = 0;
3577         rem = list_xsize;
3578         xname = list_xbuf.lb_buf;
3579         while (rem > 0) {
3580                 xlen = strnlen(xname, rem - 1) + 1;
3581                 if (strcmp(XATTR_NAME_LMA, xname) == 0 ||
3582                     strcmp(XATTR_NAME_LMV, xname) == 0)
3583                         goto next;
3584
3585                 /* For directory, if there are default layout, migrate here */
3586                 if (strcmp(XATTR_NAME_LOV, xname) == 0 &&
3587                     !S_ISDIR(lu_object_attr(&mdd_sobj->mod_obj.mo_lu)))
3588                         goto next;
3589
3590                 xsize = mdo_xattr_get(env, mdd_sobj, &LU_BUF_NULL, xname);
3591                 if (xsize == -ENODATA)
3592                         goto next;
3593                 if (xsize < 0)
3594                         GOTO(out, rc);
3595
3596                 lu_buf_check_and_alloc(&info->mti_link_buf, xsize);
3597                 if (info->mti_link_buf.lb_buf == NULL)
3598                         GOTO(out, rc = -ENOMEM);
3599
3600                 xbuf.lb_len = xsize;
3601                 xbuf.lb_buf = info->mti_link_buf.lb_buf;
3602                 rc = mdo_xattr_get(env, mdd_sobj, &xbuf, xname);
3603                 if (rc == -ENODATA)
3604                         goto next;
3605                 if (rc < 0)
3606                         GOTO(out, rc);
3607
3608                 handle = mdd_trans_create(env, mdd);
3609                 if (IS_ERR(handle))
3610                         GOTO(out, rc = PTR_ERR(handle));
3611
3612                 rc = mdo_declare_xattr_set(env, mdd_tobj, &xbuf, xname, 0,
3613                                            handle);
3614                 if (rc != 0)
3615                         GOTO(stop_trans, rc);
3616                 /* Note: this transaction is part of migration, and it is not
3617                  * the last step of migration, so we set th_local = 1 to avoid
3618                  * update last rcvd for this transaction */
3619                 handle->th_local = 1;
3620                 rc = mdd_trans_start(env, mdd, handle);
3621                 if (rc != 0)
3622                         GOTO(stop_trans, rc);
3623
3624 again:
3625                 rc = mdo_xattr_set(env, mdd_tobj, &xbuf, xname, 0, handle);
3626                 if (rc == -EEXIST)
3627                         GOTO(stop_trans, rc = 0);
3628
3629                 if (unlikely(rc == -ENOSPC &&
3630                              strcmp(xname, XATTR_NAME_LINK) == 0)) {
3631                         rc = linkea_overflow_shrink(
3632                                         (struct linkea_data *)(xbuf.lb_buf));
3633                         if (likely(rc > 0)) {
3634                                 xbuf.lb_len = rc;
3635                                 goto again;
3636                         }
3637                 }
3638
3639                 if (rc != 0)
3640                         GOTO(stop_trans, rc);
3641 stop_trans:
3642                 rc = mdd_trans_stop(env, mdd, rc, handle);
3643                 if (rc != 0)
3644                         GOTO(out, rc);
3645 next:
3646                 rem -= xlen;
3647                 memmove(xname, xname + xlen, rem);
3648         }
3649 out:
3650         return rc;
3651 }
3652
3653 static int mdd_declare_migrate_create(const struct lu_env *env,
3654                                       struct mdd_object *mdd_pobj,
3655                                       struct mdd_object *mdd_sobj,
3656                                       struct mdd_object *mdd_tobj,
3657                                       struct md_op_spec *spec,
3658                                       struct lu_attr *la,
3659                                       union lmv_mds_md *mgr_ea,
3660                                       struct linkea_data *ldata,
3661                                       struct thandle *handle)
3662 {
3663         struct lu_attr          *la_flag = MDD_ENV_VAR(env, la_for_fix);
3664         const struct lu_buf     *buf;
3665         int                     rc;
3666         int                     mgr_easize;
3667
3668         rc = mdd_declare_create_object_internal(env, mdd_pobj, mdd_tobj, la,
3669                                                 handle, spec, NULL);
3670         if (rc != 0)
3671                 return rc;
3672
3673         rc = mdd_declare_object_initialize(env, mdd_pobj, mdd_tobj, la,
3674                                            handle);
3675         if (rc != 0)
3676                 return rc;
3677
3678         if (S_ISLNK(la->la_mode)) {
3679                 const char *target_name = spec->u.sp_symname;
3680                 int sym_len = strlen(target_name);
3681                 const struct lu_buf *buf;
3682
3683                 buf = mdd_buf_get_const(env, target_name, sym_len);
3684                 rc = dt_declare_record_write(env, mdd_object_child(mdd_tobj),
3685                                              buf, 0, handle);
3686                 if (rc != 0)
3687                         return rc;
3688         } else if (S_ISDIR(la->la_mode) && ldata != NULL) {
3689                 rc = mdd_declare_links_add(env, mdd_tobj, handle, ldata);
3690                 if (rc != 0)
3691                         return rc;
3692         }
3693
3694         if (spec->u.sp_ea.eadata != NULL && spec->u.sp_ea.eadatalen != 0) {
3695                 buf = mdd_buf_get_const(env, spec->u.sp_ea.eadata,
3696                                         spec->u.sp_ea.eadatalen);
3697                 rc = mdo_declare_xattr_set(env, mdd_tobj, buf, XATTR_NAME_LOV,
3698                                            0, handle);
3699                 if (rc)
3700                         return rc;
3701         }
3702
3703         mgr_easize = lmv_mds_md_size(2, LMV_MAGIC_V1);
3704         buf = mdd_buf_get_const(env, mgr_ea, mgr_easize);
3705         rc = mdo_declare_xattr_set(env, mdd_sobj, buf, XATTR_NAME_LMV,
3706                                    0, handle);
3707         if (rc)
3708                 return rc;
3709
3710         la_flag->la_valid = LA_FLAGS;
3711         la_flag->la_flags = la->la_flags | LUSTRE_IMMUTABLE_FL;
3712         rc = mdo_declare_attr_set(env, mdd_sobj, la_flag, handle);
3713
3714         return rc;
3715 }
3716
3717 static int mdd_migrate_create(const struct lu_env *env,
3718                               struct mdd_object *mdd_pobj,
3719                               struct mdd_object *mdd_sobj,
3720                               struct mdd_object *mdd_tobj,
3721                               const struct lu_name *lname,
3722                               struct lu_attr *la)
3723 {
3724         struct mdd_thread_info  *info = mdd_env_info(env);
3725         struct mdd_device       *mdd = mdo2mdd(&mdd_sobj->mod_obj);
3726         struct md_op_spec       *spec = &info->mti_spec;
3727         struct lu_buf           lmm_buf = { NULL };
3728         struct lu_buf           link_buf = { NULL };
3729         struct lu_buf            mgr_buf;
3730         struct thandle          *handle;
3731         struct lmv_mds_md_v1    *mgr_ea;
3732         struct lu_attr          *la_flag = MDD_ENV_VAR(env, la_for_fix);
3733         struct dt_allocation_hint *hint = &mdd_env_info(env)->mti_hint;
3734         int                     mgr_easize;
3735         struct linkea_data      *ldata = &mdd_env_info(env)->mti_link_data;
3736         int                     rc;
3737         ENTRY;
3738
3739         /* prepare spec for create */
3740         memset(spec, 0, sizeof(*spec));
3741         spec->sp_cr_lookup = 0;
3742         spec->sp_feat = &dt_directory_features;
3743         if (S_ISLNK(la->la_mode)) {
3744                 const struct lu_buf *buf;
3745
3746                 buf = lu_buf_check_and_alloc(
3747                                 &mdd_env_info(env)->mti_big_buf,
3748                                 la->la_size + 1);
3749                 link_buf = *buf;
3750                 link_buf.lb_len = la->la_size + 1;
3751                 memset(link_buf.lb_buf, 0, link_buf.lb_len);
3752                 rc = mdd_readlink(env, &mdd_sobj->mod_obj, &link_buf);
3753                 if (rc <= 0) {
3754                         rc = rc != 0 ? rc : -EFAULT;
3755                         CERROR("%s: "DFID" readlink failed: rc = %d\n",
3756                                mdd2obd_dev(mdd)->obd_name,
3757                                PFID(mdd_object_fid(mdd_sobj)), rc);
3758                         RETURN(rc);
3759                 }
3760                 spec->u.sp_symname = link_buf.lb_buf;
3761         } else if (S_ISREG(la->la_mode)) {
3762                 /* retrieve lov of the old object */
3763                 rc = mdd_get_lov_ea(env, mdd_sobj, &lmm_buf);
3764                 if (rc != 0 && rc != -ENODATA)
3765                         RETURN(rc);
3766                 if (lmm_buf.lb_buf != NULL && lmm_buf.lb_len != 0) {
3767                         spec->u.sp_ea.eadata = lmm_buf.lb_buf;
3768                         spec->u.sp_ea.eadatalen = lmm_buf.lb_len;
3769                         spec->sp_cr_flags |= MDS_OPEN_HAS_EA;
3770                 }
3771         } else if (S_ISDIR(la->la_mode)) {
3772                 rc = mdd_links_read_with_rec(env, mdd_sobj, ldata);
3773                 if (rc == -ENODATA) {
3774                         /* ignore the non-linkEA error */
3775                         ldata = NULL;
3776                         rc = 0;
3777                 }
3778                 if (rc < 0)
3779                         RETURN(rc);
3780         }
3781
3782         mgr_easize = lmv_mds_md_size(2, LMV_MAGIC_V1);
3783         lu_buf_check_and_alloc(&info->mti_xattr_buf, mgr_easize);
3784         mgr_buf.lb_buf = info->mti_xattr_buf.lb_buf;
3785         mgr_buf.lb_len = mgr_easize;
3786         mgr_ea = mgr_buf.lb_buf;
3787         memset(mgr_ea, 0, sizeof(*mgr_ea));
3788         mgr_ea->lmv_magic = cpu_to_le32(LMV_MAGIC_V1);
3789         mgr_ea->lmv_stripe_count = cpu_to_le32(2);
3790         mgr_ea->lmv_master_mdt_index = mdd_seq_site(mdd)->ss_node_id;
3791         mgr_ea->lmv_hash_type = cpu_to_le32(LMV_HASH_FLAG_MIGRATION);
3792         fid_cpu_to_le(&mgr_ea->lmv_stripe_fids[0], mdd_object_fid(mdd_sobj));
3793         fid_cpu_to_le(&mgr_ea->lmv_stripe_fids[1], mdd_object_fid(mdd_tobj));
3794
3795         mdd_object_make_hint(env, mdd_pobj, mdd_tobj, la, spec, hint);
3796
3797         handle = mdd_trans_create(env, mdd);
3798         if (IS_ERR(handle))
3799                 GOTO(out_free, rc = PTR_ERR(handle));
3800
3801         /* Note: this transaction is part of migration, and it is not
3802          * the last step of migration, so we set th_local = 1 to avoid
3803          * update last rcvd for this transaction */
3804         handle->th_local = 1;
3805         rc = mdd_declare_migrate_create(env, mdd_pobj, mdd_sobj, mdd_tobj, spec,
3806                                         la, mgr_buf.lb_buf, ldata, handle);
3807         if (rc != 0)
3808                 GOTO(stop_trans, rc);
3809
3810         rc = mdd_trans_start(env, mdd, handle);
3811         if (rc != 0)
3812                 GOTO(stop_trans, rc);
3813
3814         /* don't set nlink from the original object */
3815         la->la_valid &= ~LA_NLINK;
3816
3817         /* create the target object */
3818         rc = mdd_create_object(env, mdd_pobj, mdd_tobj, la, spec, NULL, NULL,
3819                                hint, handle);
3820         if (rc != 0)
3821                 GOTO(stop_trans, rc);
3822
3823         if (S_ISDIR(la->la_mode) && ldata != NULL) {
3824                 rc = mdd_links_write(env, mdd_tobj, ldata, handle);
3825                 if (rc != 0)
3826                         GOTO(stop_trans, rc);
3827         }
3828
3829         /* Set MIGRATE EA on the source inode, so once the migration needs
3830          * to be re-done during failover, the re-do process can locate the
3831          * target object which is already being created. */
3832         rc = mdo_xattr_set(env, mdd_sobj, &mgr_buf, XATTR_NAME_LMV, 0, handle);
3833         if (rc != 0)
3834                 GOTO(stop_trans, rc);
3835
3836         /* Set immutable flag, so any modification is disabled until
3837          * the migration is done. Once the migration is interrupted,
3838          * if the resume process find the migrating object has both
3839          * IMMUTALBE flag and MIGRATE EA, it need to clear IMMUTABLE
3840          * flag and approve the migration */
3841         la_flag->la_valid = LA_FLAGS;
3842         la_flag->la_flags = la->la_flags | LUSTRE_IMMUTABLE_FL;
3843         rc = mdo_attr_set(env, mdd_sobj, la_flag, handle);
3844 stop_trans:
3845         if (handle != NULL)
3846                 rc = mdd_trans_stop(env, mdd, rc, handle);
3847 out_free:
3848         if (lmm_buf.lb_buf != NULL)
3849                 OBD_FREE(lmm_buf.lb_buf, lmm_buf.lb_len);
3850         RETURN(rc);
3851 }
3852
3853 static int mdd_migrate_entries(const struct lu_env *env,
3854                                struct mdd_object *mdd_sobj,
3855                                struct mdd_object *mdd_tobj)
3856 {
3857         struct dt_object        *next = mdd_object_child(mdd_sobj);
3858         struct mdd_device       *mdd = mdo2mdd(&mdd_sobj->mod_obj);
3859         struct dt_object        *dt_tobj = mdd_object_child(mdd_tobj);
3860         struct thandle          *handle;
3861         struct dt_it            *it;
3862         const struct dt_it_ops  *iops;
3863         int                      result;
3864         struct lu_dirent        *ent;
3865         int                      rc;
3866         ENTRY;
3867
3868         OBD_ALLOC(ent, NAME_MAX + sizeof(*ent) + 1);
3869         if (ent == NULL)
3870                 RETURN(-ENOMEM);
3871
3872         if (!dt_try_as_dir(env, next))
3873                 GOTO(out_ent, rc = -ENOTDIR);
3874         /*
3875          * iterate directories
3876          */
3877         iops = &next->do_index_ops->dio_it;
3878         it = iops->init(env, next, LUDA_FID | LUDA_TYPE);
3879         if (IS_ERR(it))
3880                 GOTO(out_ent, rc = PTR_ERR(it));
3881
3882         rc = iops->load(env, it, 0);
3883         if (rc == 0)
3884                 rc = iops->next(env, it);
3885         else if (rc > 0)
3886                 rc = 0;
3887         /*
3888          * At this point and across for-loop:
3889          *
3890          *  rc == 0 -> ok, proceed.
3891          *  rc >  0 -> end of directory.
3892          *  rc <  0 -> error.
3893          */
3894         do {
3895                 struct mdd_object       *child;
3896                 char                    *name = mdd_env_info(env)->mti_key;
3897                 int                     len;
3898                 int                     is_dir;
3899                 bool                    target_exist = false;
3900
3901                 len = iops->key_size(env, it);
3902                 if (len == 0)
3903                         goto next;
3904
3905                 result = iops->rec(env, it, (struct dt_rec *)ent,
3906                                    LUDA_FID | LUDA_TYPE);
3907                 if (result == -ESTALE)
3908                         goto next;
3909                 if (result != 0) {
3910                         rc = result;
3911                         goto out;
3912                 }
3913
3914                 fid_le_to_cpu(&ent->lde_fid, &ent->lde_fid);
3915
3916                 /* Insert new fid with target name into target dir */
3917                 if ((ent->lde_namelen == 1 && ent->lde_name[0] == '.') ||
3918                     (ent->lde_namelen == 2 && ent->lde_name[0] == '.' &&
3919                      ent->lde_name[1] == '.'))
3920                         goto next;
3921
3922                 child = mdd_object_find(env, mdd, &ent->lde_fid);
3923                 if (IS_ERR(child))
3924                         GOTO(out, rc = PTR_ERR(child));
3925
3926                 /* child may not exist, but lu_object_attr will assert this,
3927                  * get type from loh_attr directly */
3928                 is_dir = S_ISDIR(child->mod_obj.mo_lu.lo_header->loh_attr);
3929
3930                 mdd_write_lock(env, child, MOR_SRC_CHILD);
3931
3932                 snprintf(name, ent->lde_namelen + 1, "%s", ent->lde_name);
3933
3934                 /* Check whether the name has been inserted to the target */
3935                 if (dt_try_as_dir(env, dt_tobj)) {
3936                         struct lu_fid *fid = &mdd_env_info(env)->mti_fid2;
3937
3938                         rc = dt_lookup(env, dt_tobj, (struct dt_rec *)fid,
3939                                        (struct dt_key *)name);
3940                         if (unlikely(rc == 0))
3941                                 target_exist = true;
3942                 }
3943
3944                 handle = mdd_trans_create(env, mdd);
3945                 if (IS_ERR(handle))
3946                         GOTO(out_put, rc = PTR_ERR(handle));
3947
3948                 /* Note: this transaction is part of migration, and it is not
3949                  * the last step of migration, so we set th_local = 1 to avoid
3950                  * updating last rcvd for this transaction */
3951                 handle->th_local = 1;
3952                 if (likely(!target_exist)) {
3953                         rc = mdo_declare_index_insert(env, mdd_tobj,
3954                                 &ent->lde_fid,
3955                                 child->mod_obj.mo_lu.lo_header->loh_attr,
3956                                 name, handle);
3957                         if (rc != 0)
3958                                 GOTO(out_put, rc);
3959
3960                         if (is_dir) {
3961                                 rc = mdo_declare_ref_add(env, mdd_tobj, handle);
3962                                 if (rc != 0)
3963                                         GOTO(out_put, rc);
3964                         }
3965                 }
3966
3967                 rc = mdo_declare_index_delete(env, mdd_sobj, name, handle);
3968                 if (rc != 0)
3969                         GOTO(out_put, rc);
3970
3971                 if (is_dir) {
3972                         rc = mdo_declare_ref_del(env, mdd_sobj, handle);
3973                         if (rc != 0)
3974                                 GOTO(out_put, rc);
3975
3976                         /* Update .. for child */
3977                         rc = mdo_declare_index_delete(env, child, dotdot,
3978                                                       handle);
3979                         if (rc != 0)
3980                                 GOTO(out_put, rc);
3981
3982                         rc = mdo_declare_index_insert(env, child,
3983                                                       mdd_object_fid(mdd_tobj),
3984                                                       S_IFDIR, dotdot, handle);
3985                         if (rc != 0)
3986                                 GOTO(out_put, rc);
3987                 }
3988
3989                 rc = mdd_linkea_declare_update_child(env, mdd_sobj,mdd_tobj,
3990                                                      child, name,
3991                                                      strlen(name),
3992                                                      handle);
3993                 if (rc != 0)
3994                         GOTO(out_put, rc);
3995
3996                 rc = mdd_trans_start(env, mdd, handle);
3997                 if (rc != 0) {
3998                         CERROR("%s: transaction start failed: rc = %d\n",
3999                                mdd2obd_dev(mdd)->obd_name, rc);
4000                         GOTO(out_put, rc);
4001                 }
4002
4003                 if (likely(!target_exist)) {
4004                         rc = __mdd_index_insert(env, mdd_tobj, &ent->lde_fid,
4005                                 child->mod_obj.mo_lu.lo_header->loh_attr, name,
4006                                 handle);
4007                         if (rc != 0)
4008                                 GOTO(out_put, rc);
4009                 }
4010
4011                 rc = __mdd_index_delete(env, mdd_sobj, name, is_dir, handle);
4012                 if (rc != 0)
4013                         GOTO(out_put, rc);
4014
4015                 if (is_dir) {
4016                         rc = __mdd_index_delete_only(env, child, dotdot,
4017                                                      handle);
4018                         if (rc != 0)
4019                                 GOTO(out_put, rc);
4020
4021                         rc = __mdd_index_insert_only(env, child,
4022                                          mdd_object_fid(mdd_tobj), S_IFDIR,
4023                                          dotdot, handle);
4024                         if (rc != 0)
4025                                 GOTO(out_put, rc);
4026                 }
4027
4028                 rc = mdd_linkea_update_child(env, mdd_sobj, mdd_tobj,
4029                                              child, name,
4030                                              strlen(name), handle);
4031
4032 out_put:
4033                 mdd_write_unlock(env, child);
4034                 mdd_object_put(env, child);
4035                 rc = mdd_trans_stop(env, mdd, rc, handle);
4036                 if (rc != 0)
4037                         GOTO(out, rc);
4038 next:
4039                 result = iops->next(env, it);
4040                 if (OBD_FAIL_CHECK(OBD_FAIL_MIGRATE_ENTRIES))
4041                         GOTO(out, rc = -EINTR);
4042
4043                 if (result == -ESTALE)
4044                         goto next;
4045         } while (result == 0);
4046 out:
4047         iops->put(env, it);
4048         iops->fini(env, it);
4049 out_ent:
4050         OBD_FREE(ent, NAME_MAX + sizeof(*ent) + 1);
4051         RETURN(rc);
4052 }
4053
4054 static int mdd_declare_update_linkea(const struct lu_env *env,
4055                                      struct mdd_object *mdd_pobj,
4056                                      struct mdd_object *mdd_sobj,
4057                                      struct mdd_object *mdd_tobj,
4058                                      const struct lu_name *child_name,
4059                                      struct linkea_data *ldata,
4060                                      struct thandle *handle)
4061 {
4062         return mdd_update_linkea_internal(env, mdd_pobj, mdd_sobj, mdd_tobj,
4063                                           child_name, ldata, handle, 1);
4064 }
4065
4066 static int mdd_update_linkea(const struct lu_env *env,
4067                              struct mdd_object *mdd_pobj,
4068                              struct mdd_object *mdd_sobj,
4069                              struct mdd_object *mdd_tobj,
4070                              const struct lu_name *child_name,
4071                              struct linkea_data *ldata,
4072                              struct thandle *handle)
4073 {
4074         return mdd_update_linkea_internal(env, mdd_pobj, mdd_sobj, mdd_tobj,
4075                                           child_name, ldata, handle, 0);
4076 }
4077
4078 static int mdd_declare_migrate_update_name(const struct lu_env *env,
4079                                            struct mdd_object *mdd_pobj,
4080                                            struct mdd_object *mdd_sobj,
4081                                            struct mdd_object *mdd_tobj,
4082                                            const struct lu_name *lname,
4083                                            struct lu_attr *la,
4084                                            struct lu_attr *parent_la,
4085                                            struct linkea_data *ldata,
4086                                            struct thandle *handle)
4087 {
4088         struct mdd_device *mdd = mdo2mdd(&mdd_sobj->mod_obj);
4089         struct lu_attr *la_flag = MDD_ENV_VAR(env, tattr);
4090         int rc;
4091
4092         /* Revert IMMUTABLE flag */
4093         la_flag->la_valid = LA_FLAGS;
4094         la_flag->la_flags = la->la_flags & ~LUSTRE_IMMUTABLE_FL;
4095         rc = mdo_declare_attr_set(env, mdd_sobj, la_flag, handle);
4096         if (rc != 0)
4097                 return rc;
4098
4099         /* delete entry from source dir */
4100         rc = mdo_declare_index_delete(env, mdd_pobj, lname->ln_name, handle);
4101         if (rc != 0)
4102                 return rc;
4103
4104         if (ldata->ld_buf != NULL) {
4105                 rc = mdd_declare_update_linkea(env, mdd_pobj, mdd_sobj,
4106                                                mdd_tobj, lname, ldata, handle);
4107                 if (rc != 0)
4108                         return rc;
4109         }
4110
4111         if (S_ISREG(mdd_object_type(mdd_sobj))) {
4112                 rc = mdo_declare_xattr_del(env, mdd_sobj, XATTR_NAME_LOV,
4113                                            handle);
4114                 if (rc != 0)
4115                         return rc;
4116
4117                 handle->th_complex = 1;
4118                 rc = mdo_declare_xattr_set(env, mdd_tobj, NULL,
4119                                            XATTR_NAME_FID,
4120                                            LU_XATTR_REPLACE, handle);
4121                 if (rc < 0)
4122                         return rc;
4123         }
4124
4125         if (S_ISDIR(mdd_object_type(mdd_sobj))) {
4126                 rc = mdo_declare_ref_del(env, mdd_pobj, handle);
4127                 if (rc != 0)
4128                         return rc;
4129         }
4130
4131         /* new name */
4132         rc = mdo_declare_index_insert(env, mdd_pobj, mdo2fid(mdd_tobj),
4133                                       mdd_object_type(mdd_tobj),
4134                                       lname->ln_name, handle);
4135         if (rc != 0)
4136                 return rc;
4137
4138         rc = mdd_declare_links_add(env, mdd_tobj, handle, NULL);
4139         if (rc != 0)
4140                 return rc;
4141
4142         if (S_ISDIR(mdd_object_type(mdd_sobj))) {
4143                 rc = mdo_declare_ref_add(env, mdd_pobj, handle);
4144                 if (rc != 0)
4145                         return rc;
4146         }
4147
4148         /* delete old object */
4149         rc = mdo_declare_ref_del(env, mdd_sobj, handle);
4150         if (rc != 0)
4151                 return rc;
4152
4153         if (S_ISDIR(mdd_object_type(mdd_sobj))) {
4154                 /* delete old object */
4155                 rc = mdo_declare_ref_del(env, mdd_sobj, handle);
4156                 if (rc != 0)
4157                         return rc;
4158                 /* set nlink to 0 */
4159                 rc = mdo_declare_attr_set(env, mdd_sobj, la, handle);
4160                 if (rc != 0)
4161                         return rc;
4162         }
4163
4164         rc = mdd_declare_finish_unlink(env, mdd_sobj, handle);
4165         if (rc)
4166                 return rc;
4167
4168         rc = mdo_declare_attr_set(env, mdd_pobj, parent_la, handle);
4169         if (rc != 0)
4170                 return rc;
4171
4172         rc = mdd_declare_changelog_store(env, mdd, CL_MIGRATE, lname, NULL,
4173                                          handle);
4174
4175         return rc;
4176 }
4177
4178 static int mdd_migrate_update_name(const struct lu_env *env,
4179                                    struct mdd_object *mdd_pobj,
4180                                    struct mdd_object *mdd_sobj,
4181                                    struct mdd_object *mdd_tobj,
4182                                    const struct lu_name *lname,
4183                                    struct md_attr *ma)
4184 {
4185         struct lu_attr          *p_la = MDD_ENV_VAR(env, la_for_fix);
4186         struct lu_attr          *so_attr = MDD_ENV_VAR(env, cattr);
4187         struct lu_attr          *la_flag = MDD_ENV_VAR(env, tattr);
4188         struct mdd_device       *mdd = mdo2mdd(&mdd_sobj->mod_obj);
4189         struct linkea_data      *ldata = &mdd_env_info(env)->mti_link_data;
4190         struct thandle          *handle;
4191         int                     is_dir = S_ISDIR(mdd_object_type(mdd_sobj));
4192         const char              *name = lname->ln_name;
4193         int                     rc;
4194         ENTRY;
4195
4196         /* update time for parent */
4197         LASSERT(ma->ma_attr.la_valid & LA_CTIME);
4198         p_la->la_ctime = p_la->la_mtime = ma->ma_attr.la_ctime;
4199         p_la->la_valid = LA_CTIME;
4200
4201         rc = mdd_la_get(env, mdd_sobj, so_attr);
4202         if (rc != 0)
4203                 RETURN(rc);
4204
4205         ldata->ld_buf = NULL;
4206         rc = mdd_links_read(env, mdd_sobj, ldata);
4207         if (rc != 0 && rc != -ENOENT && rc != -ENODATA)
4208                 RETURN(rc);
4209
4210         handle = mdd_trans_create(env, mdd);
4211         if (IS_ERR(handle))
4212                 RETURN(PTR_ERR(handle));
4213
4214         rc = mdd_declare_migrate_update_name(env, mdd_pobj, mdd_sobj, mdd_tobj,
4215                                              lname, so_attr, p_la, ldata,
4216                                              handle);
4217         if (rc != 0) {
4218                 /* If the migration can not be fit in one transaction, just
4219                  * leave it in the original MDT */
4220                 if (rc == -E2BIG)
4221                         GOTO(stop_trans, rc = 0);
4222                 else
4223                         GOTO(stop_trans, rc);
4224         }
4225
4226         CDEBUG(D_INFO, "%s: update "DFID"/"DFID" with %s:"DFID"\n",
4227                mdd2obd_dev(mdd)->obd_name, PFID(mdd_object_fid(mdd_pobj)),
4228                PFID(mdd_object_fid(mdd_sobj)), lname->ln_name,
4229                PFID(mdd_object_fid(mdd_tobj)));
4230
4231         rc = mdd_trans_start(env, mdd, handle);
4232         if (rc != 0)
4233                 GOTO(stop_trans, rc);
4234
4235         /* Revert IMMUTABLE flag */
4236         la_flag->la_valid = LA_FLAGS;
4237         la_flag->la_flags = so_attr->la_flags & ~LUSTRE_IMMUTABLE_FL;
4238         rc = mdo_attr_set(env, mdd_sobj, la_flag, handle);
4239         if (rc != 0)
4240                 GOTO(stop_trans, rc);
4241
4242         /* Remove source name from source directory */
4243         rc = __mdd_index_delete(env, mdd_pobj, name, is_dir, handle);
4244         if (rc != 0)
4245                 GOTO(stop_trans, rc);
4246
4247         if (ldata->ld_buf != NULL) {
4248                 rc = mdd_update_linkea(env, mdd_pobj, mdd_sobj, mdd_tobj,
4249                                        lname, ldata, handle);
4250                 if (rc != 0)
4251                         GOTO(stop_trans, rc);
4252
4253                 /*  linkea update might decrease the source object
4254                  *  nlink, let's get the attr again after ref_del */
4255                 rc = mdd_la_get(env, mdd_sobj, so_attr);
4256                 if (rc != 0)
4257                         GOTO(stop_trans, rc);
4258         }
4259
4260         if (S_ISREG(so_attr->la_mode)) {
4261                 if (so_attr->la_nlink == 1) {
4262                         rc = mdo_xattr_del(env, mdd_sobj, XATTR_NAME_LOV,
4263                                            handle);
4264                         if (rc != 0 && rc != -ENODATA)
4265                                 GOTO(stop_trans, rc);
4266
4267                         rc = mdo_xattr_set(env, mdd_tobj, NULL,
4268                                            XATTR_NAME_FID,
4269                                            LU_XATTR_REPLACE, handle);
4270                         if (rc < 0)
4271                                 GOTO(stop_trans, rc);
4272                 }
4273         }
4274
4275         /* Insert new fid with target name into target dir */
4276         rc = __mdd_index_insert(env, mdd_pobj, mdd_object_fid(mdd_tobj),
4277                                 mdd_object_type(mdd_tobj), name, handle);
4278         if (rc != 0)
4279                 GOTO(stop_trans, rc);
4280
4281         mdd_write_lock(env, mdd_sobj, MOR_TGT_CHILD);
4282
4283         mdd_sobj->mod_flags |= DEAD_OBJ;
4284         rc = mdd_mark_orphan_object(env, mdd_sobj, handle, false);
4285         if (rc != 0)
4286                 GOTO(out_unlock, rc);
4287
4288         rc = mdd_orphan_insert(env, mdd_sobj, handle);
4289         if (rc != 0)
4290                 GOTO(out_unlock, rc);
4291
4292         mdo_ref_del(env, mdd_sobj, handle);
4293         if (is_dir)
4294                 mdo_ref_del(env, mdd_sobj, handle);
4295
4296         /* Get the attr again after ref_del */
4297         rc = mdd_la_get(env, mdd_sobj, so_attr);
4298         if (rc != 0)
4299                 GOTO(out_unlock, rc);
4300
4301         ma->ma_attr = *so_attr;
4302         ma->ma_valid |= MA_INODE;
4303
4304         rc = mdd_attr_set_internal(env, mdd_pobj, p_la, handle, 0);
4305         if (rc != 0)
4306                 GOTO(out_unlock, rc);
4307
4308         rc = mdd_changelog_ns_store(env, mdd, CL_MIGRATE, 0, mdd_tobj,
4309                                mdo2fid(mdd_pobj), mdo2fid(mdd_sobj),
4310                                mdo2fid(mdd_pobj), lname, lname, handle);
4311         if (rc != 0) {
4312                 CWARN("%s: changelog for migrate %s "DFID
4313                       "under "DFID" failed: rc = %d\n",
4314                       mdd2obd_dev(mdd)->obd_name, lname->ln_name,
4315                       PFID(mdd_object_fid(mdd_sobj)),
4316                       PFID(mdd_object_fid(mdd_pobj)), rc);
4317                 /* Sigh, there are no easy way to migrate back the object, so
4318                  * let's reset the result to 0 for now XXX */
4319                 rc = 0;
4320         }
4321 out_unlock:
4322         mdd_write_unlock(env, mdd_sobj);
4323
4324 stop_trans:
4325         rc = mdd_trans_stop(env, mdd, rc, handle);
4326
4327         RETURN(rc);
4328 }
4329
4330 static int mdd_fld_lookup(const struct lu_env *env, struct mdd_device *mdd,
4331                           const struct lu_fid *fid, __u32 *mdt_index)
4332 {
4333         struct lu_seq_range *range = &mdd_env_info(env)->mti_range;
4334         struct seq_server_site *ss;
4335         int rc;
4336
4337         ss = mdd->mdd_md_dev.md_lu_dev.ld_site->ld_seq_site;
4338
4339         range->lsr_flags = LU_SEQ_RANGE_MDT;
4340         rc = fld_server_lookup(env, ss->ss_server_fld, fid->f_seq, range);
4341         if (rc != 0)
4342                 return rc;
4343
4344         *mdt_index = range->lsr_index;
4345
4346         return 0;
4347 }
4348 /**
4349  * Check whether we should migrate the file/dir
4350  * return val
4351  *      < 0  permission check failed or other error.
4352  *      = 0  the file can be migrated.
4353  *      > 0  the file does not need to be migrated, mostly
4354  *           for multiple link file
4355  **/
4356 static int mdd_migrate_sanity_check(const struct lu_env *env,
4357                                     struct mdd_object *pobj,
4358                                     const struct lu_attr *pattr,
4359                                     struct mdd_object *sobj,
4360                                     struct lu_attr *sattr)
4361 {
4362         struct mdd_thread_info  *info = mdd_env_info(env);
4363         struct linkea_data      *ldata = &info->mti_link_data;
4364         struct mdd_device       *mdd = mdo2mdd(&pobj->mod_obj);
4365         int                     mgr_easize;
4366         struct lu_buf           *mgr_buf;
4367         int                     count;
4368         int                     rc;
4369         __u64 mdt_index;
4370         ENTRY;
4371
4372         mgr_easize = lmv_mds_md_size(2, LMV_MAGIC_V1);
4373         mgr_buf = lu_buf_check_and_alloc(&info->mti_big_buf, mgr_easize);
4374         if (mgr_buf->lb_buf == NULL)
4375                 RETURN(-ENOMEM);
4376
4377         rc = mdo_xattr_get(env, sobj, mgr_buf, XATTR_NAME_LMV);
4378         if (rc > 0) {
4379                 union lmv_mds_md *lmm = mgr_buf->lb_buf;
4380
4381                 /* If the object has migrateEA, it means IMMUTE flag
4382                  * is being set by previous migration process, so it
4383                  * needs to override the IMMUTE flag, otherwise the
4384                  * following sanity check will fail */
4385                 if (le32_to_cpu(lmm->lmv_md_v1.lmv_hash_type) &
4386                                                 LMV_HASH_FLAG_MIGRATION) {
4387                         struct mdd_device *mdd = mdo2mdd(&sobj->mod_obj);
4388
4389                         sattr->la_flags &= ~LUSTRE_IMMUTABLE_FL;
4390                         CDEBUG(D_HA, "%s: "DFID" override IMMUTE FLAG\n",
4391                                mdd2obd_dev(mdd)->obd_name,
4392                                PFID(mdd_object_fid(sobj)));
4393                 }
4394         }
4395
4396         rc = mdd_rename_sanity_check(env, pobj, pattr, pobj, pattr,
4397                                      sobj, sattr, NULL, NULL);
4398         if (rc != 0)
4399                 RETURN(rc);
4400
4401         /* Then it will check if the file should be migrated. If the file
4402          * has mulitple links, we only need migrate the file if all of its
4403          * entries has been migrated to the remote MDT */
4404         if (!S_ISREG(sattr->la_mode) || sattr->la_nlink < 2)
4405                 RETURN(0);
4406
4407         rc = mdd_links_read(env, sobj, ldata);
4408         if (rc != 0) {
4409                 /* For multiple links files, if there are no linkEA data at all,
4410                  * means the file might be created before linkEA is enabled, and
4411                  * all of its links should not be migrated yet, otherwise it
4412                  * should have some linkEA there */
4413                 if (rc == -ENOENT || rc == -ENODATA)
4414                         RETURN(1);
4415                 RETURN(rc);
4416         }
4417
4418         mdt_index = mdd->mdd_md_dev.md_lu_dev.ld_site->ld_seq_site->ss_node_id;
4419         /* If there are still links locally, then the file will not be
4420          * migrated. */
4421         LASSERT(ldata->ld_leh != NULL);
4422
4423         /* If the linkEA is overflow, then means there are some unknown name
4424          * entries under unknown parents, that will prevent the migration. */
4425         if (unlikely(ldata->ld_leh->leh_overflow_time))
4426                 RETURN(1);
4427
4428         ldata->ld_lee = (struct link_ea_entry *)(ldata->ld_leh + 1);
4429         for (count = 0; count < ldata->ld_leh->leh_reccount; count++) {
4430                 struct lu_name          lname;
4431                 struct lu_fid           fid;
4432                 __u32                   parent_mdt_index;
4433
4434                 linkea_entry_unpack(ldata->ld_lee, &ldata->ld_reclen,
4435                                     &lname, &fid);
4436                 ldata->ld_lee = (struct link_ea_entry *)((char *)ldata->ld_lee +
4437                                                          ldata->ld_reclen);
4438
4439                 rc = mdd_fld_lookup(env, mdd, &fid, &parent_mdt_index);
4440                 if (rc != 0)
4441                         RETURN(rc);
4442
4443                 /* Migrate the object only if none of its parents are on the
4444                  * current MDT. */
4445                 if (parent_mdt_index != mdt_index)
4446                         continue;
4447
4448                 CDEBUG(D_INFO, DFID"still has local entry %.*s "DFID"\n",
4449                        PFID(mdd_object_fid(sobj)), lname.ln_namelen,
4450                        lname.ln_name, PFID(&fid));
4451                 rc = 1;
4452                 break;
4453         }
4454
4455         RETURN(rc);
4456 }
4457
4458 static int mdd_migrate(const struct lu_env *env, struct md_object *pobj,
4459                        struct md_object *sobj, const struct lu_name *lname,
4460                        struct md_object *tobj, struct md_attr *ma)
4461 {
4462         struct mdd_object       *mdd_pobj = md2mdd_obj(pobj);
4463         struct mdd_device       *mdd = mdo2mdd(pobj);
4464         struct mdd_object       *mdd_sobj = md2mdd_obj(sobj);
4465         struct mdd_object       *mdd_tobj = md2mdd_obj(tobj);
4466         struct lu_attr          *so_attr = MDD_ENV_VAR(env, cattr);
4467         struct lu_attr          *pattr = MDD_ENV_VAR(env, pattr);
4468         bool                    created = false;
4469         int                     rc;
4470
4471         ENTRY;
4472         /* If the file will being migrated, it will check whether
4473          * the file is being opened by someone else right now */
4474         mdd_read_lock(env, mdd_sobj, MOR_SRC_CHILD);
4475         if (mdd_sobj->mod_count > 0) {
4476                 CDEBUG(D_OTHER,
4477                        "%s: "DFID"%s is already opened count %d: rc = %d\n",
4478                        mdd2obd_dev(mdd)->obd_name,
4479                        PFID(mdd_object_fid(mdd_sobj)), lname->ln_name,
4480                        mdd_sobj->mod_count, -EBUSY);
4481                 mdd_read_unlock(env, mdd_sobj);
4482                 GOTO(put, rc = -EBUSY);
4483         }
4484         mdd_read_unlock(env, mdd_sobj);
4485
4486         rc = mdd_la_get(env, mdd_sobj, so_attr);
4487         if (rc != 0)
4488                 GOTO(put, rc);
4489
4490         rc = mdd_la_get(env, mdd_pobj, pattr);
4491         if (rc != 0)
4492                 GOTO(put, rc);
4493
4494         rc = mdd_migrate_sanity_check(env, mdd_pobj, pattr, mdd_sobj, so_attr);
4495         if (rc != 0) {
4496                 if (rc > 0)
4497                         rc = 0;
4498                 GOTO(put, rc);
4499         }
4500
4501         /* Sigh, it is impossible to finish all of migration in a single
4502          * transaction, for example migrating big directory entries to the
4503          * new MDT, it needs insert all of name entries of children in the
4504          * new directory.
4505          *
4506          * So migration will be done in multiple steps and transactions.
4507          *
4508          * 1. create an orphan object on the remote MDT in one transaction.
4509          * 2. migrate extend attributes to the new target file/directory.
4510          * 3. For directory, migrate the entries to the new MDT and update
4511          * linkEA of each children. Because we can not migrate all entries
4512          * in a single transaction, so the migrating directory will become
4513          * a striped directory during migration, so once the process is
4514          * interrupted, the directory is still accessible. (During lookup,
4515          * client will locate the name by searching both original and target
4516          * object).
4517          * 4. Finally, update the name/FID to point to the new file/directory
4518          * in a separate transaction.
4519          */
4520
4521         /* step 1: Check whether the orphan object has been created, and create
4522          * orphan object on the remote MDT if needed */
4523         if (!mdd_object_exists(mdd_tobj)) {
4524                 rc = mdd_migrate_create(env, mdd_pobj, mdd_sobj, mdd_tobj,
4525                                         lname, so_attr);
4526                 if (rc != 0)
4527                         GOTO(put, rc);
4528                 created = true;
4529         }
4530
4531         LASSERT(mdd_object_exists(mdd_tobj));
4532         /* step 2: migrate xattr */
4533         rc = mdd_migrate_xattrs(env, mdd_sobj, mdd_tobj);
4534         if (rc != 0)
4535                 GOTO(put, rc);
4536
4537         /* step 3: migrate name entries to the orphan object */
4538         if (S_ISDIR(lu_object_attr(&mdd_sobj->mod_obj.mo_lu))) {
4539                 rc = mdd_migrate_entries(env, mdd_sobj, mdd_tobj);
4540                 if (rc != 0)
4541                         GOTO(put, rc);
4542                 if (unlikely(OBD_FAIL_CHECK_RESET(OBD_FAIL_MIGRATE_NET_REP,
4543                                                   OBD_FAIL_MDS_REINT_NET_REP)))
4544                         GOTO(put, rc = 0);
4545         } else {
4546                 OBD_FAIL_TIMEOUT(OBD_FAIL_MIGRATE_DELAY, cfs_fail_val);
4547         }
4548
4549         LASSERT(mdd_object_exists(mdd_tobj));
4550         /* step 4: update name entry to the new object */
4551         rc = mdd_migrate_update_name(env, mdd_pobj, mdd_sobj, mdd_tobj, lname,
4552                                      ma);
4553         if (rc != 0)
4554                 GOTO(put, rc);
4555
4556         /* newly created target was not locked, don't cache its attributes */
4557         if (created)
4558                 mdd_invalidate(env, tobj);
4559 put:
4560         RETURN(rc);
4561 }
4562
4563 const struct md_dir_operations mdd_dir_ops = {
4564         .mdo_is_subdir     = mdd_is_subdir,
4565         .mdo_lookup        = mdd_lookup,
4566         .mdo_create        = mdd_create,
4567         .mdo_rename        = mdd_rename,
4568         .mdo_link          = mdd_link,
4569         .mdo_unlink        = mdd_unlink,
4570         .mdo_create_data   = mdd_create_data,
4571         .mdo_migrate       = mdd_migrate,
4572 };