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