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