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