Whamcloud - gitweb
LU-1187 mdt: add sanity check for rename and link
[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.sun.com/software/products/lustre/docs/GPLv2.pdf
19  *
20  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
21  * CA 95054 USA or visit www.sun.com if you need additional information or
22  * have any questions.
23  *
24  * GPL HEADER END
25  */
26 /*
27  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2011, 2012, Intel Corporation.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * lustre/mdd/mdd_dir.c
37  *
38  * Lustre Metadata Server (mdd) routines
39  *
40  * Author: Wang Di <wangdi@clusterfs.com>
41  */
42
43 #define DEBUG_SUBSYSTEM S_MDS
44
45 #include <obd_class.h>
46 #include <obd_support.h>
47 #include <lustre_mds.h>
48 #include <lustre_fid.h>
49
50 #include "mdd_internal.h"
51
52 static const char dot[] = ".";
53 static const char dotdot[] = "..";
54
55 static struct lu_name lname_dotdot = {
56         (char *) dotdot,
57         sizeof(dotdot) - 1
58 };
59
60 static int __mdd_lookup(const struct lu_env *env, struct md_object *pobj,
61                         const struct lu_name *lname, struct lu_fid* fid,
62                         int mask);
63 static int mdd_declare_links_add(const struct lu_env *env,
64                                  struct mdd_object *mdd_obj,
65                                  struct thandle *handle);
66 static inline int mdd_links_add(const struct lu_env *env,
67                                 struct mdd_object *mdd_obj,
68                                 const struct lu_fid *pfid,
69                                 const struct lu_name *lname,
70                                 struct thandle *handle, int first);
71 static inline int mdd_links_del(const struct lu_env *env,
72                                 struct mdd_object *mdd_obj,
73                                 const struct lu_fid *pfid,
74                                 const struct lu_name *lname,
75                                 struct thandle *handle);
76 static int mdd_links_rename(const struct lu_env *env,
77                             struct mdd_object *mdd_obj,
78                             const struct lu_fid *oldpfid,
79                             const struct lu_name *oldlname,
80                             const struct lu_fid *newpfid,
81                             const struct lu_name *newlname,
82                             struct thandle *handle,
83                             int first, int check);
84
85 static int
86 __mdd_lookup_locked(const struct lu_env *env, struct md_object *pobj,
87                     const struct lu_name *lname, struct lu_fid* fid, int mask)
88 {
89         const char *name = lname->ln_name;
90         struct mdd_object *mdd_obj = md2mdd_obj(pobj);
91         struct dynlock_handle *dlh;
92         int rc;
93
94         dlh = mdd_pdo_read_lock(env, mdd_obj, name, MOR_TGT_PARENT);
95         if (unlikely(dlh == NULL))
96                 return -ENOMEM;
97         rc = __mdd_lookup(env, pobj, lname, fid, mask);
98         mdd_pdo_read_unlock(env, mdd_obj, dlh);
99
100         return rc;
101 }
102
103 int mdd_lookup(const struct lu_env *env,
104                struct md_object *pobj, const struct lu_name *lname,
105                struct lu_fid* fid, struct md_op_spec *spec)
106 {
107         int rc;
108         ENTRY;
109         rc = __mdd_lookup_locked(env, pobj, lname, fid, MAY_EXEC);
110         RETURN(rc);
111 }
112
113 static int mdd_parent_fid(const struct lu_env *env, struct mdd_object *obj,
114                           struct lu_fid *fid)
115 {
116         return __mdd_lookup_locked(env, &obj->mod_obj, &lname_dotdot, fid, 0);
117 }
118
119 /*
120  * For root fid use special function, which does not compare version component
121  * of fid. Version component is different for root fids on all MDTs.
122  */
123 int mdd_is_root(struct mdd_device *mdd, const struct lu_fid *fid)
124 {
125         return fid_seq(&mdd->mdd_root_fid) == fid_seq(fid) &&
126                 fid_oid(&mdd->mdd_root_fid) == fid_oid(fid);
127 }
128
129 /*
130  * return 1: if lf is the fid of the ancestor of p1;
131  * return 0: if not;
132  *
133  * return -EREMOTE: if remote object is found, in this
134  * case fid of remote object is saved to @pf;
135  *
136  * otherwise: values < 0, errors.
137  */
138 static int mdd_is_parent(const struct lu_env *env,
139                          struct mdd_device *mdd,
140                          struct mdd_object *p1,
141                          const struct lu_fid *lf,
142                          struct lu_fid *pf)
143 {
144         struct mdd_object *parent = NULL;
145         struct lu_fid *pfid;
146         int rc;
147         ENTRY;
148
149         LASSERT(!lu_fid_eq(mdo2fid(p1), lf));
150         pfid = &mdd_env_info(env)->mti_fid;
151
152         /* Check for root first. */
153         if (mdd_is_root(mdd, mdo2fid(p1)))
154                 RETURN(0);
155
156         for(;;) {
157                 /* this is done recursively, bypass capa for each obj */
158                 mdd_set_capainfo(env, 4, p1, BYPASS_CAPA);
159                 rc = mdd_parent_fid(env, p1, pfid);
160                 if (rc)
161                         GOTO(out, rc);
162                 if (mdd_is_root(mdd, pfid))
163                         GOTO(out, rc = 0);
164                 if (lu_fid_eq(pfid, lf))
165                         GOTO(out, rc = 1);
166                 if (parent)
167                         mdd_object_put(env, parent);
168
169                 parent = mdd_object_find(env, mdd, pfid);
170                 if (IS_ERR(parent)) {
171                         GOTO(out, rc = PTR_ERR(parent));
172                 } else if (mdd_object_exists(parent) < 0) {
173                         /*FIXME: Because of the restriction of rename in Phase I.
174                          * If the parent is remote, we just assumed lf is not the
175                          * parent of P1 for now */
176                         GOTO(out, rc = 0);
177                 }
178                 p1 = parent;
179         }
180         EXIT;
181 out:
182         if (parent && !IS_ERR(parent))
183                 mdd_object_put(env, parent);
184         return rc;
185 }
186
187 /*
188  * No permission check is needed.
189  *
190  * returns 1: if fid is ancestor of @mo;
191  * returns 0: if fid is not a ancestor of @mo;
192  *
193  * returns EREMOTE if remote object is found, fid of remote object is saved to
194  * @fid;
195  *
196  * returns < 0: if error
197  */
198 int mdd_is_subdir(const struct lu_env *env, struct md_object *mo,
199                   const struct lu_fid *fid, struct lu_fid *sfid)
200 {
201         struct mdd_device *mdd = mdo2mdd(mo);
202         int rc;
203         ENTRY;
204
205         if (!S_ISDIR(mdd_object_type(md2mdd_obj(mo))))
206                 RETURN(0);
207
208         rc = mdd_is_parent(env, mdd, md2mdd_obj(mo), fid, sfid);
209         if (rc == 0) {
210                 /* found root */
211                 fid_zero(sfid);
212         } else if (rc == 1) {
213                 /* found @fid is parent */
214                 *sfid = *fid;
215                 rc = 0;
216         }
217         RETURN(rc);
218 }
219
220 /*
221  * Check that @dir contains no entries except (possibly) dot and dotdot.
222  *
223  * Returns:
224  *
225  *             0        empty
226  *      -ENOTDIR        not a directory object
227  *    -ENOTEMPTY        not empty
228  *           -ve        other error
229  *
230  */
231 static int mdd_dir_is_empty(const struct lu_env *env,
232                             struct mdd_object *dir)
233 {
234         struct dt_it     *it;
235         struct dt_object *obj;
236         const struct dt_it_ops *iops;
237         int result;
238         ENTRY;
239
240         obj = mdd_object_child(dir);
241         if (!dt_try_as_dir(env, obj))
242                 RETURN(-ENOTDIR);
243
244         iops = &obj->do_index_ops->dio_it;
245         it = iops->init(env, obj, LUDA_64BITHASH, BYPASS_CAPA);
246         if (!IS_ERR(it)) {
247                 result = iops->get(env, it, (const void *)"");
248                 if (result > 0) {
249                         int i;
250                         for (result = 0, i = 0; result == 0 && i < 3; ++i)
251                                 result = iops->next(env, it);
252                         if (result == 0)
253                                 result = -ENOTEMPTY;
254                         else if (result == +1)
255                                 result = 0;
256                 } else if (result == 0)
257                         /*
258                          * Huh? Index contains no zero key?
259                          */
260                         result = -EIO;
261
262                 iops->put(env, it);
263                 iops->fini(env, it);
264         } else
265                 result = PTR_ERR(it);
266         RETURN(result);
267 }
268
269 static int __mdd_may_link(const struct lu_env *env, struct mdd_object *obj)
270 {
271         struct mdd_device *m = mdd_obj2mdd_dev(obj);
272         struct lu_attr *la = &mdd_env_info(env)->mti_la;
273         int rc;
274         ENTRY;
275
276         rc = mdd_la_get(env, obj, la, BYPASS_CAPA);
277         if (rc)
278                 RETURN(rc);
279
280         /*
281          * Subdir count limitation can be broken through.
282          */
283         if (la->la_nlink >= m->mdd_dt_conf.ddp_max_nlink &&
284             !S_ISDIR(la->la_mode))
285                 RETURN(-EMLINK);
286         else
287                 RETURN(0);
288 }
289
290 /*
291  * Check whether it may create the cobj under the pobj.
292  * cobj maybe NULL
293  */
294 int mdd_may_create(const struct lu_env *env, struct mdd_object *pobj,
295                    struct mdd_object *cobj, int check_perm, int check_nlink)
296 {
297         int rc = 0;
298         ENTRY;
299
300         if (cobj && mdd_object_exists(cobj))
301                 RETURN(-EEXIST);
302
303         if (mdd_is_dead_obj(pobj))
304                 RETURN(-ENOENT);
305
306         if (check_perm)
307                 rc = mdd_permission_internal_locked(env, pobj, NULL,
308                                                     MAY_WRITE | MAY_EXEC,
309                                                     MOR_TGT_PARENT);
310         if (!rc && check_nlink)
311                 rc = __mdd_may_link(env, pobj);
312
313         RETURN(rc);
314 }
315
316 /*
317  * Check whether can unlink from the pobj in the case of "cobj == NULL".
318  */
319 int mdd_may_unlink(const struct lu_env *env, struct mdd_object *pobj,
320                    const struct lu_attr *attr)
321 {
322         int rc;
323         ENTRY;
324
325         if (mdd_is_dead_obj(pobj))
326                 RETURN(-ENOENT);
327
328         if ((attr->la_valid & LA_FLAGS) &&
329             (attr->la_flags & (LUSTRE_APPEND_FL | LUSTRE_IMMUTABLE_FL)))
330                 RETURN(-EPERM);
331
332         rc = mdd_permission_internal_locked(env, pobj, NULL,
333                                             MAY_WRITE | MAY_EXEC,
334                                             MOR_TGT_PARENT);
335         if (rc)
336                 RETURN(rc);
337
338         if (mdd_is_append(pobj))
339                 RETURN(-EPERM);
340
341         RETURN(rc);
342 }
343
344 /*
345  * pobj == NULL is remote ops case, under such case, pobj's
346  * VTX feature has been checked already, no need check again.
347  */
348 static inline int mdd_is_sticky(const struct lu_env *env,
349                                 struct mdd_object *pobj,
350                                 struct mdd_object *cobj)
351 {
352         struct lu_attr *tmp_la = &mdd_env_info(env)->mti_la;
353         struct lu_ucred *uc = lu_ucred_assert(env);
354         int rc;
355
356         if (pobj) {
357                 rc = mdd_la_get(env, pobj, tmp_la, BYPASS_CAPA);
358                 if (rc)
359                         return rc;
360
361                 if (!(tmp_la->la_mode & S_ISVTX) ||
362                     (tmp_la->la_uid == uc->uc_fsuid))
363                         return 0;
364         }
365
366         rc = mdd_la_get(env, cobj, tmp_la, BYPASS_CAPA);
367         if (rc)
368                 return rc;
369
370         if (tmp_la->la_uid == uc->uc_fsuid)
371                 return 0;
372
373         return !md_capable(uc, CFS_CAP_FOWNER);
374 }
375
376 static int mdd_may_delete_entry(const struct lu_env *env,
377                                 struct mdd_object *pobj, int check_perm)
378 {
379         ENTRY;
380
381         LASSERT(pobj != NULL);
382         if (!mdd_object_exists(pobj))
383                 RETURN(-ENOENT);
384
385         if (mdd_is_dead_obj(pobj))
386                 RETURN(-ENOENT);
387
388         if (check_perm) {
389                 int rc;
390                 rc = mdd_permission_internal_locked(env, pobj, NULL,
391                                             MAY_WRITE | MAY_EXEC,
392                                             MOR_TGT_PARENT);
393                 if (rc)
394                         RETURN(rc);
395         }
396
397         if (mdd_is_append(pobj))
398                 RETURN(-EPERM);
399
400         RETURN(0);
401 }
402
403 /*
404  * Check whether it may delete the cobj from the pobj.
405  * pobj maybe NULL
406  */
407 int mdd_may_delete(const struct lu_env *env, struct mdd_object *pobj,
408                    struct mdd_object *cobj, struct lu_attr *cattr,
409                    struct lu_attr *src_attr, int check_perm, int check_empty)
410 {
411         int rc = 0;
412         ENTRY;
413
414         if (pobj) {
415                 rc = mdd_may_delete_entry(env, pobj, check_perm);
416                 if (rc != 0)
417                         RETURN(rc);
418         }
419
420         if (cobj == NULL)
421                 RETURN(0);
422
423         if (!mdd_object_exists(cobj))
424                 RETURN(-ENOENT);
425
426         if (mdd_is_dead_obj(cobj))
427                 RETURN(-ESTALE);
428
429
430         if (mdd_is_sticky(env, pobj, cobj))
431                 RETURN(-EPERM);
432
433         if (mdd_is_immutable(cobj) || mdd_is_append(cobj))
434                 RETURN(-EPERM);
435
436         if ((cattr->la_valid & LA_FLAGS) &&
437             (cattr->la_flags & (LUSTRE_APPEND_FL | LUSTRE_IMMUTABLE_FL)))
438                 RETURN(-EPERM);
439
440         /* additional check the rename case */
441         if (src_attr) {
442                 if (S_ISDIR(src_attr->la_mode)) {
443                         struct mdd_device *mdd = mdo2mdd(&cobj->mod_obj);
444
445                         if (!S_ISDIR(cattr->la_mode))
446                                 RETURN(-ENOTDIR);
447
448                         if (lu_fid_eq(mdo2fid(cobj), &mdd->mdd_root_fid))
449                                 RETURN(-EBUSY);
450                 } else if (S_ISDIR(cattr->la_mode))
451                         RETURN(-EISDIR);
452         }
453
454         if (S_ISDIR(cattr->la_mode) && check_empty)
455                 rc = mdd_dir_is_empty(env, cobj);
456
457         RETURN(rc);
458 }
459
460 /*
461  * tgt maybe NULL
462  * has mdd_write_lock on src already, but not on tgt yet
463  */
464 int mdd_link_sanity_check(const struct lu_env *env,
465                           struct mdd_object *tgt_obj,
466                           const struct lu_name *lname,
467                           struct mdd_object *src_obj)
468 {
469         struct mdd_device *m = mdd_obj2mdd_dev(src_obj);
470         int rc = 0;
471         ENTRY;
472
473         if (!mdd_object_exists(src_obj))
474                 RETURN(-ENOENT);
475
476         if (mdd_is_dead_obj(src_obj))
477                 RETURN(-ESTALE);
478
479         /* Local ops, no lookup before link, check filename length here. */
480         if (lname && (lname->ln_namelen > m->mdd_dt_conf.ddp_max_name_len))
481                 RETURN(-ENAMETOOLONG);
482
483         if (mdd_is_immutable(src_obj) || mdd_is_append(src_obj))
484                 RETURN(-EPERM);
485
486         if (S_ISDIR(mdd_object_type(src_obj)))
487                 RETURN(-EPERM);
488
489         LASSERT(src_obj != tgt_obj);
490         if (tgt_obj) {
491                 rc = mdd_may_create(env, tgt_obj, NULL, 1, 0);
492                 if (rc)
493                         RETURN(rc);
494         }
495
496         rc = __mdd_may_link(env, src_obj);
497
498         RETURN(rc);
499 }
500
501 static int __mdd_index_delete_only(const struct lu_env *env, struct mdd_object *pobj,
502                                    const char *name, struct thandle *handle,
503                                    struct lustre_capa *capa)
504 {
505         struct dt_object *next = mdd_object_child(pobj);
506         int               rc;
507         ENTRY;
508
509         if (dt_try_as_dir(env, next)) {
510                 rc = next->do_index_ops->dio_delete(env, next,
511                                                     (struct dt_key *)name,
512                                                     handle, capa);
513         } else
514                 rc = -ENOTDIR;
515
516         RETURN(rc);
517 }
518
519 static int __mdd_index_insert_only(const struct lu_env *env,
520                                    struct mdd_object *pobj,
521                                    const struct lu_fid *lf, const char *name,
522                                    struct thandle *handle,
523                                    struct lustre_capa *capa)
524 {
525         struct dt_object *next = mdd_object_child(pobj);
526         int               rc;
527         ENTRY;
528
529         if (dt_try_as_dir(env, next)) {
530                 struct lu_ucred  *uc = lu_ucred_check(env);
531                 int ignore_quota;
532
533                 ignore_quota = uc ? uc->uc_cap & CFS_CAP_SYS_RESOURCE_MASK : 1;
534                 rc = next->do_index_ops->dio_insert(env, next,
535                                                     (struct dt_rec*)lf,
536                                                     (const struct dt_key *)name,
537                                                     handle, capa, ignore_quota);
538         } else {
539                 rc = -ENOTDIR;
540         }
541         RETURN(rc);
542 }
543
544 /* insert named index, add reference if isdir */
545 static int __mdd_index_insert(const struct lu_env *env, struct mdd_object *pobj,
546                               const struct lu_fid *lf, const char *name, int is_dir,
547                               struct thandle *handle, struct lustre_capa *capa)
548 {
549         int               rc;
550         ENTRY;
551
552         rc = __mdd_index_insert_only(env, pobj, lf, name, handle, capa);
553         if (rc == 0 && is_dir) {
554                 mdd_write_lock(env, pobj, MOR_TGT_PARENT);
555                 mdo_ref_add(env, pobj, handle);
556                 mdd_write_unlock(env, pobj);
557         }
558         RETURN(rc);
559 }
560
561 /* delete named index, drop reference if isdir */
562 static int __mdd_index_delete(const struct lu_env *env, struct mdd_object *pobj,
563                               const char *name, int is_dir, struct thandle *handle,
564                               struct lustre_capa *capa)
565 {
566         int               rc;
567         ENTRY;
568
569         rc = __mdd_index_delete_only(env, pobj, name, handle, capa);
570         if (rc == 0 && is_dir) {
571                 mdd_write_lock(env, pobj, MOR_TGT_PARENT);
572                 mdo_ref_del(env, pobj, handle);
573                 mdd_write_unlock(env, pobj);
574         }
575
576         RETURN(rc);
577 }
578
579 int mdd_declare_llog_record(const struct lu_env *env, struct mdd_device *mdd,
580                             int reclen, struct thandle *handle)
581 {
582         int rc;
583
584         /* XXX: this is a temporary solution to declare llog changes
585          *      will be fixed in 2.3 with new llog implementation */
586
587         LASSERT(mdd->mdd_capa);
588
589         /* XXX: Since we use the 'mdd_capa' as fake llog object here, we
590          *      have to set the parameter 'size' as INT_MAX or 0 to inform
591          *      OSD that this record write is for a llog write or catalog
592          *      header update, and osd declare function will reserve less
593          *      credits for optimization purpose.
594          *
595          *      Reserve 6 blocks for a llog write, since the llog file is
596          *      usually small, reserve 2 blocks for catalog header update,
597          *      because we know for sure that catalog header is already
598          *      allocated.
599          *
600          *      This hack should be removed in 2.3.
601          */
602
603         /* record itself */
604         rc = dt_declare_record_write(env, mdd->mdd_capa,
605                                      DECLARE_LLOG_WRITE, 0, handle);
606         if (rc)
607                 return rc;
608
609         /* header will be updated as well */
610         rc = dt_declare_record_write(env, mdd->mdd_capa,
611                                      DECLARE_LLOG_WRITE, 0, handle);
612         if (rc)
613                 return rc;
614
615         /* also we should be able to create new plain log */
616         rc = dt_declare_create(env, mdd->mdd_capa, NULL, NULL, NULL, handle);
617         if (rc)
618                 return rc;
619
620         /* new record referencing new plain llog */
621         rc = dt_declare_record_write(env, mdd->mdd_capa,
622                                      DECLARE_LLOG_WRITE, 0, handle);
623         if (rc)
624                 return rc;
625
626         /* catalog's header will be updated as well */
627         rc = dt_declare_record_write(env, mdd->mdd_capa,
628                                      DECLARE_LLOG_REWRITE, 0, handle);
629
630         return rc;
631 }
632
633 int mdd_declare_changelog_store(const struct lu_env *env,
634                                 struct mdd_device *mdd,
635                                 const struct lu_name *fname,
636                                 struct thandle *handle)
637 {
638         struct obd_device               *obd = mdd2obd_dev(mdd);
639         struct llog_ctxt                *ctxt;
640         struct llog_changelog_rec       *rec;
641         struct lu_buf                   *buf;
642         int                              reclen;
643         int                              rc;
644
645         /* Not recording */
646         if (!(mdd->mdd_cl.mc_flags & CLM_ON))
647                 return 0;
648
649         reclen = llog_data_len(sizeof(*rec) +
650                                (fname != NULL ? fname->ln_namelen : 0));
651         buf = mdd_buf_alloc(env, reclen);
652         if (buf->lb_buf == NULL)
653                 return -ENOMEM;
654
655         rec = buf->lb_buf;
656         rec->cr_hdr.lrh_len = reclen;
657         rec->cr_hdr.lrh_type = CHANGELOG_REC;
658
659         ctxt = llog_get_context(obd, LLOG_CHANGELOG_ORIG_CTXT);
660         if (ctxt == NULL)
661                 return -ENXIO;
662
663         rc = llog_declare_add(env, ctxt->loc_handle, &rec->cr_hdr, handle);
664         llog_ctxt_put(ctxt);
665
666         return rc;
667 }
668
669 static int mdd_declare_changelog_ext_store(const struct lu_env *env,
670                                            struct mdd_device *mdd,
671                                            const struct lu_name *tname,
672                                            const struct lu_name *sname,
673                                            struct thandle *handle)
674 {
675         struct obd_device               *obd = mdd2obd_dev(mdd);
676         struct llog_ctxt                *ctxt;
677         struct llog_changelog_ext_rec   *rec;
678         struct lu_buf                   *buf;
679         int                              reclen;
680         int                              rc;
681
682         /* Not recording */
683         if (!(mdd->mdd_cl.mc_flags & CLM_ON))
684                 return 0;
685
686         reclen = llog_data_len(sizeof(*rec) +
687                                (tname != NULL ? tname->ln_namelen : 0) +
688                                (sname != NULL ? 1 + sname->ln_namelen : 0));
689         buf = mdd_buf_alloc(env, reclen);
690         if (buf->lb_buf == NULL)
691                 return -ENOMEM;
692
693         rec = buf->lb_buf;
694         rec->cr_hdr.lrh_len = reclen;
695         rec->cr_hdr.lrh_type = CHANGELOG_REC;
696
697         ctxt = llog_get_context(obd, LLOG_CHANGELOG_ORIG_CTXT);
698         if (ctxt == NULL)
699                 return -ENXIO;
700
701         rc = llog_declare_add(env, ctxt->loc_handle, &rec->cr_hdr, handle);
702         llog_ctxt_put(ctxt);
703
704         return rc;
705 }
706
707 /** Add a changelog entry \a rec to the changelog llog
708  * \param mdd
709  * \param rec
710  * \param handle - currently ignored since llogs start their own transaction;
711  *                 this will hopefully be fixed in llog rewrite
712  * \retval 0 ok
713  */
714 int mdd_changelog_store(const struct lu_env *env, struct mdd_device *mdd,
715                         struct llog_changelog_rec *rec, struct thandle *th)
716 {
717         struct obd_device       *obd = mdd2obd_dev(mdd);
718         struct llog_ctxt        *ctxt;
719         int                      rc;
720
721         rec->cr_hdr.lrh_len = llog_data_len(sizeof(*rec) + rec->cr.cr_namelen);
722         rec->cr_hdr.lrh_type = CHANGELOG_REC;
723         rec->cr.cr_time = cl_time();
724
725         spin_lock(&mdd->mdd_cl.mc_lock);
726         /* NB: I suppose it's possible llog_add adds out of order wrt cr_index,
727          * but as long as the MDD transactions are ordered correctly for e.g.
728          * rename conflicts, I don't think this should matter. */
729         rec->cr.cr_index = ++mdd->mdd_cl.mc_index;
730         spin_unlock(&mdd->mdd_cl.mc_lock);
731
732         ctxt = llog_get_context(obd, LLOG_CHANGELOG_ORIG_CTXT);
733         if (ctxt == NULL)
734                 return -ENXIO;
735
736         rc = llog_add(env, ctxt->loc_handle, &rec->cr_hdr, NULL, NULL, th);
737         llog_ctxt_put(ctxt);
738         if (rc > 0)
739                 rc = 0;
740         return rc;
741 }
742
743 /** Add a changelog_ext entry \a rec to the changelog llog
744  * \param mdd
745  * \param rec
746  * \param handle - currently ignored since llogs start their own transaction;
747  *              this will hopefully be fixed in llog rewrite
748  * \retval 0 ok
749  */
750 int mdd_changelog_ext_store(const struct lu_env *env, struct mdd_device *mdd,
751                             struct llog_changelog_ext_rec *rec,
752                             struct thandle *th)
753 {
754         struct obd_device       *obd = mdd2obd_dev(mdd);
755         struct llog_ctxt        *ctxt;
756         int                      rc;
757
758         rec->cr_hdr.lrh_len = llog_data_len(sizeof(*rec) + rec->cr.cr_namelen);
759         /* llog_lvfs_write_rec sets the llog tail len */
760         rec->cr_hdr.lrh_type = CHANGELOG_REC;
761         rec->cr.cr_time = cl_time();
762
763         spin_lock(&mdd->mdd_cl.mc_lock);
764         /* NB: I suppose it's possible llog_add adds out of order wrt cr_index,
765          * but as long as the MDD transactions are ordered correctly for e.g.
766          * rename conflicts, I don't think this should matter. */
767         rec->cr.cr_index = ++mdd->mdd_cl.mc_index;
768         spin_unlock(&mdd->mdd_cl.mc_lock);
769
770         ctxt = llog_get_context(obd, LLOG_CHANGELOG_ORIG_CTXT);
771         if (ctxt == NULL)
772                 return -ENXIO;
773
774         /* nested journal transaction */
775         rc = llog_add(env, ctxt->loc_handle, &rec->cr_hdr, NULL, NULL, th);
776         llog_ctxt_put(ctxt);
777         if (rc > 0)
778                 rc = 0;
779
780         return rc;
781 }
782
783 /** Store a namespace change changelog record
784  * If this fails, we must fail the whole transaction; we don't
785  * want the change to commit without the log entry.
786  * \param target - mdd_object of change
787  * \param parent - parent dir/object
788  * \param tname - target name string
789  * \param handle - transacion handle
790  */
791 static int mdd_changelog_ns_store(const struct lu_env  *env,
792                                   struct mdd_device    *mdd,
793                                   enum changelog_rec_type type,
794                                   unsigned flags,
795                                   struct mdd_object    *target,
796                                   struct mdd_object    *parent,
797                                   const struct lu_name *tname,
798                                   struct thandle *handle)
799 {
800         struct llog_changelog_rec *rec;
801         struct lu_buf *buf;
802         int reclen;
803         int rc;
804         ENTRY;
805
806         /* Not recording */
807         if (!(mdd->mdd_cl.mc_flags & CLM_ON))
808                 RETURN(0);
809         if ((mdd->mdd_cl.mc_mask & (1 << type)) == 0)
810                 RETURN(0);
811
812         LASSERT(target != NULL);
813         LASSERT(parent != NULL);
814         LASSERT(tname != NULL);
815         LASSERT(handle != NULL);
816
817         reclen = llog_data_len(sizeof(*rec) + tname->ln_namelen);
818         buf = mdd_buf_alloc(env, reclen);
819         if (buf->lb_buf == NULL)
820                 RETURN(-ENOMEM);
821         rec = buf->lb_buf;
822
823         rec->cr.cr_flags = CLF_VERSION | (CLF_FLAGMASK & flags);
824         rec->cr.cr_type = (__u32)type;
825         rec->cr.cr_tfid = *mdo2fid(target);
826         rec->cr.cr_pfid = *mdo2fid(parent);
827         rec->cr.cr_namelen = tname->ln_namelen;
828         memcpy(rec->cr.cr_name, tname->ln_name, tname->ln_namelen);
829
830         target->mod_cltime = cfs_time_current_64();
831
832         rc = mdd_changelog_store(env, mdd, rec, handle);
833         if (rc < 0) {
834                 CERROR("changelog failed: rc=%d, op%d %s c"DFID" p"DFID"\n",
835                         rc, type, tname->ln_name, PFID(&rec->cr.cr_tfid),
836                         PFID(&rec->cr.cr_pfid));
837                 RETURN(-EFAULT);
838         }
839
840         RETURN(0);
841 }
842
843
844 /** Store a namespace change changelog record
845  * If this fails, we must fail the whole transaction; we don't
846  * want the change to commit without the log entry.
847  * \param target - mdd_object of change
848  * \param tpfid - target parent dir/object fid
849  * \param sfid - source object fid
850  * \param spfid - source parent fid
851  * \param tname - target name string
852  * \param sname - source name string
853  * \param handle - transacion handle
854  */
855 static int mdd_changelog_ext_ns_store(const struct lu_env  *env,
856                                       struct mdd_device    *mdd,
857                                       enum changelog_rec_type type,
858                                       unsigned flags,
859                                       struct mdd_object    *target,
860                                       const struct lu_fid  *tpfid,
861                                       const struct lu_fid  *sfid,
862                                       const struct lu_fid  *spfid,
863                                       const struct lu_name *tname,
864                                       const struct lu_name *sname,
865                                       struct thandle *handle)
866 {
867         struct llog_changelog_ext_rec *rec;
868         struct lu_buf *buf;
869         int reclen;
870         int rc;
871         ENTRY;
872
873         /* Not recording */
874         if (!(mdd->mdd_cl.mc_flags & CLM_ON))
875                 RETURN(0);
876         if ((mdd->mdd_cl.mc_mask & (1 << type)) == 0)
877                 RETURN(0);
878
879         LASSERT(sfid != NULL);
880         LASSERT(tpfid != NULL);
881         LASSERT(tname != NULL);
882         LASSERT(handle != NULL);
883
884         reclen = llog_data_len(sizeof(*rec) +
885                                sname != NULL ? 1 + sname->ln_namelen : 0);
886         buf = mdd_buf_alloc(env, reclen);
887         if (buf->lb_buf == NULL)
888                 RETURN(-ENOMEM);
889         rec = buf->lb_buf;
890
891         rec->cr.cr_flags = CLF_EXT_VERSION | (CLF_FLAGMASK & flags);
892         rec->cr.cr_type = (__u32)type;
893         rec->cr.cr_pfid = *tpfid;
894         rec->cr.cr_sfid = *sfid;
895         rec->cr.cr_spfid = *spfid;
896         rec->cr.cr_namelen = tname->ln_namelen;
897         memcpy(rec->cr.cr_name, tname->ln_name, tname->ln_namelen);
898         if (sname) {
899                 rec->cr.cr_name[tname->ln_namelen] = '\0';
900                 memcpy(rec->cr.cr_name + tname->ln_namelen + 1, sname->ln_name,
901                         sname->ln_namelen);
902                 rec->cr.cr_namelen += 1 + sname->ln_namelen;
903         }
904
905         if (likely(target != NULL)) {
906                 rec->cr.cr_tfid = *mdo2fid(target);
907                 target->mod_cltime = cfs_time_current_64();
908         } else {
909                 fid_zero(&rec->cr.cr_tfid);
910         }
911
912         rc = mdd_changelog_ext_store(env, mdd, rec, handle);
913         if (rc < 0) {
914                 CERROR("changelog failed: rc=%d, op%d %s c"DFID" p"DFID"\n",
915                         rc, type, tname->ln_name, PFID(sfid), PFID(tpfid));
916                 return -EFAULT;
917         }
918
919         return 0;
920 }
921
922 static int mdd_declare_link(const struct lu_env *env,
923                             struct mdd_device *mdd,
924                             struct mdd_object *p,
925                             struct mdd_object *c,
926                             const struct lu_name *name,
927                             struct thandle *handle)
928 {
929         int rc;
930
931         rc = mdo_declare_index_insert(env, p, mdo2fid(c), name->ln_name,handle);
932         if (rc)
933                 return rc;
934
935         rc = mdo_declare_ref_add(env, c, handle);
936         if (rc)
937                 return rc;
938
939         rc = mdo_declare_attr_set(env, p, NULL, handle);
940         if (rc)
941                 return rc;
942
943         rc = mdo_declare_attr_set(env, c, NULL, handle);
944         if (rc)
945                 return rc;
946
947         rc = mdd_declare_links_add(env, c, handle);
948         if (rc)
949                 return rc;
950
951         rc = mdd_declare_changelog_store(env, mdd, name, handle);
952
953         return rc;
954 }
955
956 static int mdd_link(const struct lu_env *env, struct md_object *tgt_obj,
957                     struct md_object *src_obj, const struct lu_name *lname,
958                     struct md_attr *ma)
959 {
960         const char *name = lname->ln_name;
961         struct lu_attr    *la = &mdd_env_info(env)->mti_la_for_fix;
962         struct mdd_object *mdd_tobj = md2mdd_obj(tgt_obj);
963         struct mdd_object *mdd_sobj = md2mdd_obj(src_obj);
964         struct mdd_device *mdd = mdo2mdd(src_obj);
965         struct dynlock_handle *dlh;
966         struct thandle *handle;
967         int rc;
968         ENTRY;
969
970         handle = mdd_trans_create(env, mdd);
971         if (IS_ERR(handle))
972                 GOTO(out_pending, rc = PTR_ERR(handle));
973
974         rc = mdd_declare_link(env, mdd, mdd_tobj, mdd_sobj, lname, handle);
975         if (rc)
976                 GOTO(stop, rc);
977
978         rc = mdd_trans_start(env, mdd, handle);
979         if (rc)
980                 GOTO(stop, rc);
981
982         dlh = mdd_pdo_write_lock(env, mdd_tobj, name, MOR_TGT_CHILD);
983         if (dlh == NULL)
984                 GOTO(out_trans, rc = -ENOMEM);
985         mdd_write_lock(env, mdd_sobj, MOR_TGT_CHILD);
986
987         rc = mdd_link_sanity_check(env, mdd_tobj, lname, mdd_sobj);
988         if (rc)
989                 GOTO(out_unlock, rc);
990
991         rc = mdo_ref_add(env, mdd_sobj, handle);
992         if (rc)
993                 GOTO(out_unlock, rc);
994
995
996         rc = __mdd_index_insert_only(env, mdd_tobj, mdo2fid(mdd_sobj),
997                                      name, handle,
998                                      mdd_object_capa(env, mdd_tobj));
999         if (rc != 0) {
1000                 mdo_ref_del(env, mdd_sobj, handle);
1001                 GOTO(out_unlock, rc);
1002         }
1003
1004         LASSERT(ma->ma_attr.la_valid & LA_CTIME);
1005         la->la_ctime = la->la_mtime = ma->ma_attr.la_ctime;
1006
1007         la->la_valid = LA_CTIME | LA_MTIME;
1008         rc = mdd_attr_check_set_internal(env, mdd_tobj, la, handle, 0);
1009         if (rc)
1010                 GOTO(out_unlock, rc);
1011
1012         la->la_valid = LA_CTIME;
1013         rc = mdd_attr_check_set_internal(env, mdd_sobj, la, handle, 0);
1014         if (rc == 0) {
1015                 mdd_links_add(env, mdd_sobj,
1016                               mdo2fid(mdd_tobj), lname, handle, 0);
1017         }
1018
1019         EXIT;
1020 out_unlock:
1021         mdd_write_unlock(env, mdd_sobj);
1022         mdd_pdo_write_unlock(env, mdd_tobj, dlh);
1023 out_trans:
1024         if (rc == 0)
1025                 rc = mdd_changelog_ns_store(env, mdd, CL_HARDLINK, 0, mdd_sobj,
1026                                             mdd_tobj, lname, handle);
1027 stop:
1028         mdd_trans_stop(env, mdd, rc, handle);
1029 out_pending:
1030         return rc;
1031 }
1032
1033 int mdd_declare_finish_unlink(const struct lu_env *env,
1034                               struct mdd_object *obj,
1035                               struct md_attr *ma,
1036                               struct thandle *handle)
1037 {
1038         int     rc;
1039
1040         rc = orph_declare_index_insert(env, obj, mdd_object_type(obj), handle);
1041         if (rc)
1042                 return rc;
1043
1044         return mdo_declare_destroy(env, obj, handle);
1045 }
1046
1047 /* caller should take a lock before calling */
1048 int mdd_finish_unlink(const struct lu_env *env,
1049                       struct mdd_object *obj, struct md_attr *ma,
1050                       struct thandle *th)
1051 {
1052         int rc = 0;
1053         int is_dir = S_ISDIR(ma->ma_attr.la_mode);
1054         ENTRY;
1055
1056         LASSERT(mdd_write_locked(env, obj) != 0);
1057
1058         if (rc == 0 && (ma->ma_attr.la_nlink == 0 || is_dir)) {
1059                 obj->mod_flags |= DEAD_OBJ;
1060                 /* add new orphan and the object
1061                  * will be deleted during mdd_close() */
1062                 if (obj->mod_count) {
1063                         rc = __mdd_orphan_add(env, obj, th);
1064                         if (rc == 0)
1065                                 CDEBUG(D_HA, "Object "DFID" is inserted into "
1066                                         "orphan list, open count = %d\n",
1067                                         PFID(mdd_object_fid(obj)),
1068                                         obj->mod_count);
1069                         else
1070                                 CERROR("Object "DFID" fail to be an orphan, "
1071                                        "open count = %d, maybe cause failed "
1072                                        "open replay\n",
1073                                         PFID(mdd_object_fid(obj)),
1074                                         obj->mod_count);
1075                 } else {
1076                         rc = mdo_destroy(env, obj, th);
1077                 }
1078         }
1079
1080         RETURN(rc);
1081 }
1082
1083 /*
1084  * pobj maybe NULL
1085  * has mdd_write_lock on cobj already, but not on pobj yet
1086  */
1087 int mdd_unlink_sanity_check(const struct lu_env *env, struct mdd_object *pobj,
1088                             struct mdd_object *cobj, struct lu_attr *cattr)
1089 {
1090         int rc;
1091         ENTRY;
1092
1093         rc = mdd_may_delete(env, pobj, cobj, cattr, NULL, 1, 1);
1094
1095         RETURN(rc);
1096 }
1097
1098 static inline int mdd_declare_links_del(const struct lu_env *env,
1099                                         struct mdd_object *c,
1100                                         struct thandle *handle)
1101 {
1102         int rc = 0;
1103
1104         /* For directory, the linkEA will be removed together with the object. */
1105         if (!S_ISDIR(mdd_object_type(c)))
1106                 rc = mdd_declare_links_add(env, c, handle);
1107
1108         return rc;
1109 }
1110
1111 static int mdd_declare_unlink(const struct lu_env *env, struct mdd_device *mdd,
1112                               struct mdd_object *p, struct mdd_object *c,
1113                               const struct lu_name *name, struct md_attr *ma,
1114                               struct thandle *handle)
1115 {
1116         struct lu_attr     *la = &mdd_env_info(env)->mti_la_for_fix;
1117         int rc;
1118
1119         rc = mdo_declare_index_delete(env, p, name->ln_name, handle);
1120         if (rc)
1121                 return rc;
1122
1123         rc = mdo_declare_ref_del(env, p, handle);
1124         if (rc)
1125                 return rc;
1126
1127         LASSERT(ma->ma_attr.la_valid & LA_CTIME);
1128         la->la_ctime = la->la_mtime = ma->ma_attr.la_ctime;
1129         la->la_valid = LA_CTIME | LA_MTIME;
1130         rc = mdo_declare_attr_set(env, p, la, handle);
1131         if (rc)
1132                 return rc;
1133
1134         if (c != NULL) {
1135                 rc = mdo_declare_ref_del(env, c, handle);
1136                 if (rc)
1137                         return rc;
1138
1139                 rc = mdo_declare_ref_del(env, c, handle);
1140                 if (rc)
1141                         return rc;
1142
1143                 rc = mdo_declare_attr_set(env, c, NULL, handle);
1144                 if (rc)
1145                         return rc;
1146
1147                 rc = mdd_declare_finish_unlink(env, c, ma, handle);
1148                 if (rc)
1149                         return rc;
1150
1151                 rc = mdd_declare_links_del(env, c, handle);
1152                 if (rc != 0)
1153                         return rc;
1154
1155                 /* FIXME: need changelog for remove entry */
1156                 rc = mdd_declare_changelog_store(env, mdd, name, handle);
1157         }
1158
1159         return rc;
1160 }
1161
1162 static int mdd_unlink(const struct lu_env *env, struct md_object *pobj,
1163                       struct md_object *cobj, const struct lu_name *lname,
1164                       struct md_attr *ma)
1165 {
1166         const char *name = lname->ln_name;
1167         struct lu_attr     *cattr = &mdd_env_info(env)->mti_cattr;
1168         struct lu_attr    *la = &mdd_env_info(env)->mti_la_for_fix;
1169         struct mdd_object *mdd_pobj = md2mdd_obj(pobj);
1170         struct mdd_object *mdd_cobj = NULL;
1171         struct mdd_device *mdd = mdo2mdd(pobj);
1172         struct dynlock_handle *dlh;
1173         struct thandle    *handle;
1174         int rc, is_dir = 0;
1175         ENTRY;
1176
1177         /* cobj == NULL means only delete name entry */
1178         if (likely(cobj != NULL)) {
1179                 mdd_cobj = md2mdd_obj(cobj);
1180                 if (mdd_object_exists(mdd_cobj) == 0)
1181                         RETURN(-ENOENT);
1182                 /* currently it is assume, it could only delete
1183                  * name entry of remote directory */
1184                 is_dir = 1;
1185         }
1186
1187         handle = mdd_trans_create(env, mdd);
1188         if (IS_ERR(handle))
1189                 RETURN(PTR_ERR(handle));
1190
1191         rc = mdd_declare_unlink(env, mdd, mdd_pobj, mdd_cobj,
1192                                 lname, ma, handle);
1193         if (rc)
1194                 GOTO(stop, rc);
1195
1196         rc = mdd_trans_start(env, mdd, handle);
1197         if (rc)
1198                 GOTO(stop, rc);
1199
1200         dlh = mdd_pdo_write_lock(env, mdd_pobj, name, MOR_TGT_PARENT);
1201         if (dlh == NULL)
1202                 GOTO(stop, rc = -ENOMEM);
1203
1204         if (likely(mdd_cobj != NULL)) {
1205                 mdd_write_lock(env, mdd_cobj, MOR_TGT_CHILD);
1206
1207                 /* fetch cattr */
1208                 rc = mdd_la_get(env, mdd_cobj, cattr,
1209                                 mdd_object_capa(env, mdd_cobj));
1210                 if (rc)
1211                         GOTO(cleanup, rc);
1212
1213                 is_dir = S_ISDIR(cattr->la_mode);
1214
1215         }
1216
1217         rc = mdd_unlink_sanity_check(env, mdd_pobj, mdd_cobj, cattr);
1218         if (rc)
1219                 GOTO(cleanup, rc);
1220
1221         rc = __mdd_index_delete(env, mdd_pobj, name, is_dir, handle,
1222                                 mdd_object_capa(env, mdd_pobj));
1223         if (rc)
1224                 GOTO(cleanup, rc);
1225
1226         if (likely(mdd_cobj != NULL)) {
1227                 rc = mdo_ref_del(env, mdd_cobj, handle);
1228                 if (rc != 0) {
1229                         __mdd_index_insert_only(env, mdd_pobj,
1230                                                 mdo2fid(mdd_cobj),
1231                                                 name, handle,
1232                                                 mdd_object_capa(env, mdd_pobj));
1233                         GOTO(cleanup, rc);
1234                 }
1235
1236                 if (is_dir)
1237                         /* unlink dot */
1238                         mdo_ref_del(env, mdd_cobj, handle);
1239
1240                 /* fetch updated nlink */
1241                 rc = mdd_la_get(env, mdd_cobj, cattr,
1242                                 mdd_object_capa(env, mdd_cobj));
1243                 if (rc)
1244                         GOTO(cleanup, rc);
1245         }
1246
1247         LASSERT(ma->ma_attr.la_valid & LA_CTIME);
1248         la->la_ctime = la->la_mtime = ma->ma_attr.la_ctime;
1249
1250         la->la_valid = LA_CTIME | LA_MTIME;
1251         rc = mdd_attr_check_set_internal(env, mdd_pobj, la, handle, 0);
1252         if (rc)
1253                 GOTO(cleanup, rc);
1254
1255         /* Enough for only unlink the entry */
1256         if (unlikely(mdd_cobj == NULL)) {
1257                 mdd_pdo_write_unlock(env, mdd_pobj, dlh);
1258                 GOTO(stop, rc);
1259         }
1260
1261         if (cattr->la_nlink > 0 || mdd_cobj->mod_count > 0) {
1262                 /* update ctime of an unlinked file only if it is still
1263                  * opened or a link still exists */
1264                 la->la_valid = LA_CTIME;
1265                 rc = mdd_attr_check_set_internal(env, mdd_cobj, la, handle, 0);
1266                 if (rc)
1267                         GOTO(cleanup, rc);
1268         }
1269
1270         /* XXX: this transfer to ma will be removed with LOD/OSP */
1271         ma->ma_attr = *cattr;
1272         ma->ma_valid |= MA_INODE;
1273         rc = mdd_finish_unlink(env, mdd_cobj, ma, handle);
1274
1275         /* fetch updated nlink */
1276         if (rc == 0)
1277                 rc = mdd_la_get(env, mdd_cobj, cattr,
1278                                 mdd_object_capa(env, mdd_cobj));
1279
1280         if (!is_dir)
1281                 /* old files may not have link ea; ignore errors */
1282                 mdd_links_del(env, mdd_cobj, mdo2fid(mdd_pobj), lname, handle);
1283
1284         /* if object is removed then we can't get its attrs, use last get */
1285         if (cattr->la_nlink == 0) {
1286                 ma->ma_attr = *cattr;
1287                 ma->ma_valid |= MA_INODE;
1288         }
1289         EXIT;
1290 cleanup:
1291         mdd_write_unlock(env, mdd_cobj);
1292         mdd_pdo_write_unlock(env, mdd_pobj, dlh);
1293         if (rc == 0) {
1294                 int cl_flags;
1295
1296                 cl_flags = (cattr->la_nlink == 0) ? CLF_UNLINK_LAST : 0;
1297                 if ((ma->ma_valid & MA_HSM) &&
1298                     (ma->ma_hsm.mh_flags & HS_EXISTS))
1299                         cl_flags |= CLF_UNLINK_HSM_EXISTS;
1300
1301                 rc = mdd_changelog_ns_store(env, mdd,
1302                         is_dir ? CL_RMDIR : CL_UNLINK, cl_flags,
1303                         mdd_cobj, mdd_pobj, lname, handle);
1304         }
1305
1306 stop:
1307         mdd_trans_stop(env, mdd, rc, handle);
1308
1309         return rc;
1310 }
1311
1312 /*
1313  * The permission has been checked when obj created, no need check again.
1314  */
1315 static int mdd_cd_sanity_check(const struct lu_env *env,
1316                                struct mdd_object *obj)
1317 {
1318         ENTRY;
1319
1320         /* EEXIST check */
1321         if (!obj || mdd_is_dead_obj(obj))
1322                 RETURN(-ENOENT);
1323
1324         RETURN(0);
1325
1326 }
1327
1328 static int mdd_create_data(const struct lu_env *env, struct md_object *pobj,
1329                            struct md_object *cobj, const struct md_op_spec *spec,
1330                            struct md_attr *ma)
1331 {
1332         struct mdd_device *mdd = mdo2mdd(cobj);
1333         struct mdd_object *mdd_pobj = md2mdd_obj(pobj);
1334         struct mdd_object *son = md2mdd_obj(cobj);
1335         struct thandle    *handle;
1336         const struct lu_buf *buf;
1337         struct lu_attr    *attr = &mdd_env_info(env)->mti_cattr;
1338         int                rc;
1339         ENTRY;
1340
1341         /* do not let users to create stripes via .lustre/
1342          * mdd_obf_setup() sets IMMUTE_OBJ on this directory */
1343         if (pobj && mdd_pobj->mod_flags & IMMUTE_OBJ)
1344                 RETURN(-ENOENT);
1345
1346         rc = mdd_cd_sanity_check(env, son);
1347         if (rc)
1348                 RETURN(rc);
1349
1350         if (!md_should_create(spec->sp_cr_flags))
1351                 RETURN(0);
1352
1353         /*
1354          * there are following use cases for this function:
1355          * 1) late striping - file was created with MDS_OPEN_DELAY_CREATE
1356          *    striping can be specified or not
1357          * 2) CMD?
1358          */
1359         rc = mdd_la_get(env, son, attr, mdd_object_capa(env, son));
1360         if (rc)
1361                 RETURN(rc);
1362
1363         /* calling ->ah_make_hint() is used to transfer information from parent */
1364         mdd_object_make_hint(env, mdd_pobj, son, attr);
1365
1366         handle = mdd_trans_create(env, mdd);
1367         if (IS_ERR(handle))
1368                 GOTO(out_free, rc = PTR_ERR(handle));
1369
1370         /*
1371          * XXX: Setting the lov ea is not locked but setting the attr is locked?
1372          * Should this be fixed?
1373          */
1374         CDEBUG(D_OTHER, "ea %p/%u, cr_flags %Lo, no_create %u\n",
1375                spec->u.sp_ea.eadata, spec->u.sp_ea.eadatalen,
1376                spec->sp_cr_flags, spec->no_create);
1377
1378         if (spec->no_create || spec->sp_cr_flags & MDS_OPEN_HAS_EA) {
1379                 /* replay case or lfs setstripe */
1380                 buf = mdd_buf_get_const(env, spec->u.sp_ea.eadata,
1381                                         spec->u.sp_ea.eadatalen);
1382         } else {
1383                 buf = &LU_BUF_NULL;
1384         }
1385
1386         rc = dt_declare_xattr_set(env, mdd_object_child(son), buf,
1387                                   XATTR_NAME_LOV, 0, handle);
1388         if (rc)
1389                 GOTO(stop, rc);
1390
1391         rc = mdd_trans_start(env, mdd, handle);
1392         if (rc)
1393                 GOTO(stop, rc);
1394
1395         rc = dt_xattr_set(env, mdd_object_child(son), buf, XATTR_NAME_LOV,
1396                           0, handle, mdd_object_capa(env, son));
1397 stop:
1398         mdd_trans_stop(env, mdd, rc, handle);
1399 out_free:
1400         RETURN(rc);
1401 }
1402
1403 /* Get fid from name and parent */
1404 static int
1405 __mdd_lookup(const struct lu_env *env, struct md_object *pobj,
1406              const struct lu_name *lname, struct lu_fid* fid, int mask)
1407 {
1408         const char          *name = lname->ln_name;
1409         const struct dt_key *key = (const struct dt_key *)name;
1410         struct mdd_object   *mdd_obj = md2mdd_obj(pobj);
1411         struct mdd_device   *m = mdo2mdd(pobj);
1412         struct dt_object    *dir = mdd_object_child(mdd_obj);
1413         int rc;
1414         ENTRY;
1415
1416         if (unlikely(mdd_is_dead_obj(mdd_obj)))
1417                 RETURN(-ESTALE);
1418
1419         rc = mdd_object_exists(mdd_obj);
1420         if (unlikely(rc == 0))
1421                 RETURN(-ESTALE);
1422         else if (unlikely(rc < 0)) {
1423                 CERROR("Object "DFID" locates on remote server\n",
1424                         PFID(mdo2fid(mdd_obj)));
1425                 RETURN(-EINVAL);
1426         }
1427
1428         /* The common filename length check. */
1429         if (unlikely(lname->ln_namelen > m->mdd_dt_conf.ddp_max_name_len))
1430                 RETURN(-ENAMETOOLONG);
1431
1432         rc = mdd_permission_internal_locked(env, mdd_obj, NULL, mask,
1433                                             MOR_TGT_PARENT);
1434         if (rc)
1435                 RETURN(rc);
1436
1437         if (likely(S_ISDIR(mdd_object_type(mdd_obj)) &&
1438                    dt_try_as_dir(env, dir))) {
1439
1440                 rc = dir->do_index_ops->dio_lookup(env, dir,
1441                                                  (struct dt_rec *)fid, key,
1442                                                  mdd_object_capa(env, mdd_obj));
1443                 if (rc > 0)
1444                         rc = 0;
1445                 else if (rc == 0)
1446                         rc = -ENOENT;
1447         } else
1448                 rc = -ENOTDIR;
1449
1450         RETURN(rc);
1451 }
1452
1453 int mdd_declare_object_initialize(const struct lu_env *env,
1454                                   struct mdd_object *child,
1455                                   struct lu_attr *attr,
1456                                   struct thandle *handle)
1457 {
1458         int rc;
1459
1460         /*
1461          * inode mode has been set in creation time, and it's based on umask,
1462          * la_mode and acl, don't set here again! (which will go wrong
1463          * because below function doesn't consider umask).
1464          * I'd suggest set all object attributes in creation time, see above.
1465          */
1466         LASSERT(attr->la_valid & (LA_MODE | LA_TYPE));
1467         attr->la_valid &= ~(LA_MODE | LA_TYPE);
1468         rc = mdo_declare_attr_set(env, child, attr, handle);
1469         attr->la_valid |= LA_MODE | LA_TYPE;
1470         if (rc == 0 && S_ISDIR(attr->la_mode)) {
1471                 rc = mdo_declare_index_insert(env, child, mdo2fid(child),
1472                                               dot, handle);
1473                 if (rc == 0)
1474                         rc = mdo_declare_ref_add(env, child, handle);
1475         }
1476
1477         if (rc == 0)
1478                 mdd_declare_links_add(env, child, handle);
1479
1480         return rc;
1481 }
1482
1483 int mdd_object_initialize(const struct lu_env *env, const struct lu_fid *pfid,
1484                           const struct lu_name *lname, struct mdd_object *child,
1485                           struct lu_attr *attr, struct thandle *handle,
1486                           const struct md_op_spec *spec)
1487 {
1488         int rc;
1489         ENTRY;
1490
1491         /*
1492          * Update attributes for child.
1493          *
1494          * FIXME:
1495          *  (1) the valid bits should be converted between Lustre and Linux;
1496          *  (2) maybe, the child attributes should be set in OSD when creation.
1497          */
1498
1499         /*
1500          * inode mode has been set in creation time, and it's based on umask,
1501          * la_mode and acl, don't set here again! (which will go wrong
1502          * because below function doesn't consider umask).
1503          * I'd suggest set all object attributes in creation time, see above.
1504          */
1505         LASSERT(attr->la_valid & (LA_MODE | LA_TYPE));
1506         attr->la_valid &= ~(LA_MODE | LA_TYPE);
1507         rc = mdd_attr_set_internal(env, child, attr, handle, 0);
1508         /* arguments are supposed to stay the same */
1509         attr->la_valid |= LA_MODE | LA_TYPE;
1510         if (rc != 0)
1511                 RETURN(rc);
1512
1513         if (S_ISDIR(attr->la_mode)) {
1514                 /* Add "." and ".." for newly created dir */
1515                 mdo_ref_add(env, child, handle);
1516                 rc = __mdd_index_insert_only(env, child, mdo2fid(child),
1517                                              dot, handle, BYPASS_CAPA);
1518                 if (rc == 0)
1519                         rc = __mdd_index_insert_only(env, child, pfid,
1520                                                      dotdot, handle,
1521                                                      BYPASS_CAPA);
1522                 if (rc != 0)
1523                         mdo_ref_del(env, child, handle);
1524         }
1525         if (rc == 0)
1526                 mdd_links_add(env, child, pfid, lname, handle, 1);
1527
1528         RETURN(rc);
1529 }
1530
1531 /* has not lock on pobj yet */
1532 static int mdd_create_sanity_check(const struct lu_env *env,
1533                                    struct md_object *pobj,
1534                                    struct lu_attr *pattr,
1535                                    const struct lu_name *lname,
1536                                    struct lu_attr *cattr,
1537                                    struct md_op_spec *spec)
1538 {
1539         struct mdd_thread_info *info = mdd_env_info(env);
1540         struct lu_fid     *fid       = &info->mti_fid;
1541         struct mdd_object *obj       = md2mdd_obj(pobj);
1542         struct mdd_device *m         = mdo2mdd(pobj);
1543         int rc;
1544         ENTRY;
1545
1546         /* EEXIST check */
1547         if (mdd_is_dead_obj(obj))
1548                 RETURN(-ENOENT);
1549
1550         /*
1551          * In some cases this lookup is not needed - we know before if name
1552          * exists or not because MDT performs lookup for it.
1553          * name length check is done in lookup.
1554          */
1555         if (spec->sp_cr_lookup) {
1556                 /*
1557                  * Check if the name already exist, though it will be checked in
1558                  * _index_insert also, for avoiding rolling back if exists
1559                  * _index_insert.
1560                  */
1561                 rc = __mdd_lookup_locked(env, pobj, lname, fid,
1562                                          MAY_WRITE | MAY_EXEC);
1563                 if (rc != -ENOENT)
1564                         RETURN(rc ? : -EEXIST);
1565         } else {
1566                 /*
1567                  * Check WRITE permission for the parent.
1568                  * EXEC permission have been checked
1569                  * when lookup before create already.
1570                  */
1571                 rc = mdd_permission_internal_locked(env, obj, pattr, MAY_WRITE,
1572                                                     MOR_TGT_PARENT);
1573                 if (rc)
1574                         RETURN(rc);
1575         }
1576
1577         /* sgid check */
1578         if (pattr->la_mode & S_ISGID) {
1579                 cattr->la_gid = pattr->la_gid;
1580                 if (S_ISDIR(cattr->la_mode)) {
1581                         cattr->la_mode |= S_ISGID;
1582                         cattr->la_valid |= LA_MODE;
1583                 }
1584         }
1585
1586         switch (cattr->la_mode & S_IFMT) {
1587         case S_IFLNK: {
1588                 unsigned int symlen = strlen(spec->u.sp_symname) + 1;
1589
1590                 if (symlen > (1 << m->mdd_dt_conf.ddp_block_shift))
1591                         RETURN(-ENAMETOOLONG);
1592                 else
1593                         RETURN(0);
1594         }
1595         case S_IFDIR:
1596         case S_IFREG:
1597         case S_IFCHR:
1598         case S_IFBLK:
1599         case S_IFIFO:
1600         case S_IFSOCK:
1601                 rc = 0;
1602                 break;
1603         default:
1604                 rc = -EINVAL;
1605                 break;
1606         }
1607         RETURN(rc);
1608 }
1609
1610 static int mdd_declare_create(const struct lu_env *env, struct mdd_device *mdd,
1611                               struct mdd_object *p, struct mdd_object *c,
1612                               const struct lu_name *name,
1613                               struct lu_attr *attr,
1614                               int got_def_acl,
1615                               struct thandle *handle,
1616                               const struct md_op_spec *spec)
1617 {
1618         int rc;
1619
1620         rc = mdd_declare_object_create_internal(env, p, c, attr, handle, spec);
1621         if (rc)
1622                 GOTO(out, rc);
1623
1624 #ifdef CONFIG_FS_POSIX_ACL
1625         if (got_def_acl > 0) {
1626                 struct lu_buf *acl_buf;
1627
1628                 acl_buf = mdd_buf_get(env, NULL, got_def_acl);
1629                 /* if dir, then can inherit default ACl */
1630                 if (S_ISDIR(attr->la_mode)) {
1631                         rc = mdo_declare_xattr_set(env, c, acl_buf,
1632                                                    XATTR_NAME_ACL_DEFAULT,
1633                                                    0, handle);
1634                         if (rc)
1635                                 GOTO(out, rc);
1636                 }
1637
1638                 rc = mdo_declare_attr_set(env, c, attr, handle);
1639                 if (rc)
1640                         GOTO(out, rc);
1641
1642                 rc = mdo_declare_xattr_set(env, c, acl_buf,
1643                                            XATTR_NAME_ACL_ACCESS, 0, handle);
1644                 if (rc)
1645                         GOTO(out, rc);
1646         }
1647 #endif
1648
1649         if (S_ISDIR(attr->la_mode)) {
1650                 rc = mdo_declare_ref_add(env, p, handle);
1651                 if (rc)
1652                         GOTO(out, rc);
1653         }
1654
1655         rc = mdd_declare_object_initialize(env, c, attr, handle);
1656         if (rc)
1657                 GOTO(out, rc);
1658
1659         if (spec->sp_cr_flags & MDS_OPEN_VOLATILE)
1660                 rc = orph_declare_index_insert(env, c, attr->la_mode, handle);
1661         else
1662                 rc = mdo_declare_index_insert(env, p, mdo2fid(c),
1663                                               name->ln_name, handle);
1664         if (rc)
1665                 GOTO(out, rc);
1666
1667         /* replay case, create LOV EA from client data */
1668         if (spec->no_create || (spec->sp_cr_flags & MDS_OPEN_HAS_EA)) {
1669                 const struct lu_buf *buf;
1670
1671                 buf = mdd_buf_get_const(env, spec->u.sp_ea.eadata,
1672                                         spec->u.sp_ea.eadatalen);
1673                 rc = mdo_declare_xattr_set(env, c, buf, XATTR_NAME_LOV,
1674                                            0, handle);
1675                 if (rc)
1676                         GOTO(out, rc);
1677         }
1678
1679         if (S_ISLNK(attr->la_mode)) {
1680                 rc = dt_declare_record_write(env, mdd_object_child(c),
1681                                              strlen(spec->u.sp_symname), 0,
1682                                              handle);
1683                 if (rc)
1684                         GOTO(out, rc);
1685         }
1686
1687         if (!(spec->sp_cr_flags & MDS_OPEN_VOLATILE)) {
1688                 rc = mdo_declare_attr_set(env, p, attr, handle);
1689                 if (rc)
1690                         return rc;
1691         }
1692
1693         rc = mdd_declare_changelog_store(env, mdd, name, handle);
1694         if (rc)
1695                 return rc;
1696
1697 out:
1698         return rc;
1699 }
1700
1701 /*
1702  * Create object and insert it into namespace.
1703  */
1704 static int mdd_create(const struct lu_env *env, struct md_object *pobj,
1705                       const struct lu_name *lname, struct md_object *child,
1706                       struct md_op_spec *spec, struct md_attr* ma)
1707 {
1708         struct mdd_thread_info  *info = mdd_env_info(env);
1709         struct lu_attr          *la = &info->mti_la_for_fix;
1710         struct mdd_object       *mdd_pobj = md2mdd_obj(pobj);
1711         struct mdd_object       *son = md2mdd_obj(child);
1712         struct mdd_device       *mdd = mdo2mdd(pobj);
1713         struct lu_attr          *attr = &ma->ma_attr;
1714         struct thandle          *handle;
1715         struct lu_attr          *pattr = &info->mti_pattr;
1716         struct dynlock_handle   *dlh;
1717         const char              *name = lname->ln_name;
1718         int                      rc, created = 0, initialized = 0, inserted = 0;
1719         int                      got_def_acl = 0;
1720         ENTRY;
1721
1722         /*
1723          * Two operations have to be performed:
1724          *
1725          *  - an allocation of a new object (->do_create()), and
1726          *
1727          *  - an insertion into a parent index (->dio_insert()).
1728          *
1729          * Due to locking, operation order is not important, when both are
1730          * successful, *but* error handling cases are quite different:
1731          *
1732          *  - if insertion is done first, and following object creation fails,
1733          *  insertion has to be rolled back, but this operation might fail
1734          *  also leaving us with dangling index entry.
1735          *
1736          *  - if creation is done first, is has to be undone if insertion
1737          *  fails, leaving us with leaked space, which is neither good, nor
1738          *  fatal.
1739          *
1740          * It seems that creation-first is simplest solution, but it is
1741          * sub-optimal in the frequent
1742          *
1743          *         $ mkdir foo
1744          *         $ mkdir foo
1745          *
1746          * case, because second mkdir is bound to create object, only to
1747          * destroy it immediately.
1748          *
1749          * To avoid this follow local file systems that do double lookup:
1750          *
1751          *     0. lookup -> -EEXIST (mdd_create_sanity_check())
1752          *
1753          *     1. create            (mdd_object_create_internal())
1754          *
1755          *     2. insert            (__mdd_index_insert(), lookup again)
1756          */
1757
1758         rc = mdd_la_get(env, mdd_pobj, pattr, BYPASS_CAPA);
1759         if (rc != 0)
1760                 RETURN(rc);
1761
1762         /* Sanity checks before big job. */
1763         rc = mdd_create_sanity_check(env, pobj, pattr, lname, attr, spec);
1764         if (rc)
1765                 RETURN(rc);
1766
1767         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_DQACQ_NET))
1768                 GOTO(out_free, rc = -EINPROGRESS);
1769
1770         if (!S_ISLNK(attr->la_mode)) {
1771                 struct lu_buf *acl_buf;
1772
1773                 acl_buf = mdd_buf_get(env, info->mti_xattr_buf,
1774                                 sizeof(info->mti_xattr_buf));
1775                 mdd_read_lock(env, mdd_pobj, MOR_TGT_PARENT);
1776                 rc = mdo_xattr_get(env, mdd_pobj, acl_buf,
1777                                 XATTR_NAME_ACL_DEFAULT, BYPASS_CAPA);
1778                 mdd_read_unlock(env, mdd_pobj);
1779                 if (rc > 0)
1780                         got_def_acl = rc;
1781                 else if (rc < 0 && rc != -EOPNOTSUPP && rc != -ENODATA)
1782                         GOTO(out_free, rc);
1783         }
1784
1785         mdd_object_make_hint(env, mdd_pobj, son, attr);
1786
1787         handle = mdd_trans_create(env, mdd);
1788         if (IS_ERR(handle))
1789                 GOTO(out_free, rc = PTR_ERR(handle));
1790
1791         rc = mdd_declare_create(env, mdd, mdd_pobj, son, lname, attr,
1792                                 got_def_acl, handle, spec);
1793         if (rc)
1794                 GOTO(out_stop, rc);
1795
1796         rc = mdd_trans_start(env, mdd, handle);
1797         if (rc)
1798                 GOTO(out_stop, rc);
1799
1800         dlh = mdd_pdo_write_lock(env, mdd_pobj, name, MOR_TGT_PARENT);
1801         if (dlh == NULL)
1802                 GOTO(out_trans, rc = -ENOMEM);
1803
1804         mdd_write_lock(env, son, MOR_TGT_CHILD);
1805         rc = mdd_object_create_internal(env, NULL, son, attr, handle, spec);
1806         if (rc) {
1807                 mdd_write_unlock(env, son);
1808                 GOTO(cleanup, rc);
1809         }
1810
1811         created = 1;
1812
1813 #ifdef CONFIG_FS_POSIX_ACL
1814         if (got_def_acl) {
1815                 struct lu_buf *acl_buf;
1816
1817                 acl_buf = mdd_buf_get(env, info->mti_xattr_buf, got_def_acl);
1818                 rc = __mdd_acl_init(env, son, acl_buf, &attr->la_mode, handle);
1819                 if (rc) {
1820                         mdd_write_unlock(env, son);
1821                         GOTO(cleanup, rc);
1822                 }
1823         }
1824 #endif
1825
1826         rc = mdd_object_initialize(env, mdo2fid(mdd_pobj), lname,
1827                                    son, attr, handle, spec);
1828
1829         /*
1830          * in case of replay we just set LOVEA provided by the client
1831          * XXX: I think it would be interesting to try "old" way where
1832          *      MDT calls this xattr_set(LOV) in a different transaction.
1833          *      probably this way we code can be made better.
1834          */
1835         if (rc == 0 && (spec->no_create ||
1836                         (spec->sp_cr_flags & MDS_OPEN_HAS_EA))) {
1837                 const struct lu_buf *buf;
1838
1839                 buf = mdd_buf_get_const(env, spec->u.sp_ea.eadata,
1840                                 spec->u.sp_ea.eadatalen);
1841                 rc = mdo_xattr_set(env, son, buf, XATTR_NAME_LOV, 0, handle,
1842                                 BYPASS_CAPA);
1843         }
1844
1845         if (rc == 0 && spec->sp_cr_flags & MDS_OPEN_VOLATILE)
1846                 rc = __mdd_orphan_add(env, son, handle);
1847
1848         mdd_write_unlock(env, son);
1849
1850         if (rc != 0)
1851                 /*
1852                  * Object has no links, so it will be destroyed when last
1853                  * reference is released. (XXX not now.)
1854                  */
1855                 GOTO(cleanup, rc);
1856
1857         initialized = 1;
1858
1859         if (!(spec->sp_cr_flags & MDS_OPEN_VOLATILE))
1860                 rc = __mdd_index_insert(env, mdd_pobj, mdo2fid(son),
1861                                         name, S_ISDIR(attr->la_mode), handle,
1862                                         mdd_object_capa(env, mdd_pobj));
1863
1864         if (rc != 0)
1865                 GOTO(cleanup, rc);
1866
1867         inserted = 1;
1868
1869         if (S_ISLNK(attr->la_mode)) {
1870                 struct lu_ucred  *uc = lu_ucred_assert(env);
1871                 struct dt_object *dt = mdd_object_child(son);
1872                 const char *target_name = spec->u.sp_symname;
1873                 int sym_len = strlen(target_name);
1874                 const struct lu_buf *buf;
1875                 loff_t pos = 0;
1876
1877                 buf = mdd_buf_get_const(env, target_name, sym_len);
1878                 rc = dt->do_body_ops->dbo_write(env, dt, buf, &pos, handle,
1879                                                 mdd_object_capa(env, son),
1880                                                 uc->uc_cap &
1881                                                 CFS_CAP_SYS_RESOURCE_MASK);
1882
1883                 if (rc == sym_len)
1884                         rc = 0;
1885                 else
1886                         GOTO(cleanup, rc = -EFAULT);
1887         }
1888
1889         /* volatile file creation does not update parent directory times */
1890         if (spec->sp_cr_flags & MDS_OPEN_VOLATILE)
1891                 GOTO(cleanup, rc = 0);
1892
1893         /* update parent directory mtime/ctime */
1894         *la = *attr;
1895         la->la_valid = LA_CTIME | LA_MTIME;
1896         rc = mdd_attr_check_set_internal(env, mdd_pobj, la, handle, 0);
1897         if (rc)
1898                 GOTO(cleanup, rc);
1899
1900         EXIT;
1901 cleanup:
1902         if (rc != 0 && created != 0) {
1903                 int rc2;
1904
1905                 if (inserted != 0) {
1906                         if (spec->sp_cr_flags & MDS_OPEN_VOLATILE)
1907                                 rc2 = __mdd_orphan_del(env, son, handle);
1908                         else
1909                                 rc2 = __mdd_index_delete(env, mdd_pobj, name,
1910                                                          S_ISDIR(attr->la_mode),
1911                                                          handle, BYPASS_CAPA);
1912                         if (rc2 != 0)
1913                                 goto out_stop;
1914                 }
1915
1916                 mdd_write_lock(env, son, MOR_TGT_CHILD);
1917                 if (initialized != 0 && S_ISDIR(attr->la_mode)) {
1918                         /* Drop the reference, no need to delete "."/"..",
1919                          * because the object to be destroied directly. */
1920                         rc2 = mdo_ref_del(env, son, handle);
1921                         if (rc2 != 0) {
1922                                 mdd_write_unlock(env, son);
1923                                 goto out_stop;
1924                         }
1925                 }
1926
1927                 rc2 = mdo_ref_del(env, son, handle);
1928                 if (rc2 != 0) {
1929                         mdd_write_unlock(env, son);
1930                         goto out_stop;
1931                 }
1932
1933                 mdo_destroy(env, son, handle);
1934                 mdd_write_unlock(env, son);
1935         }
1936
1937         mdd_pdo_write_unlock(env, mdd_pobj, dlh);
1938 out_trans:
1939         if (rc == 0 && fid_is_client_mdt_visible(mdo2fid(son)))
1940                 rc = mdd_changelog_ns_store(env, mdd,
1941                         S_ISDIR(attr->la_mode) ? CL_MKDIR :
1942                         S_ISREG(attr->la_mode) ? CL_CREATE :
1943                         S_ISLNK(attr->la_mode) ? CL_SOFTLINK : CL_MKNOD,
1944                         0, son, mdd_pobj, lname, handle);
1945 out_stop:
1946         mdd_trans_stop(env, mdd, rc, handle);
1947 out_free:
1948         /* The child object shouldn't be cached anymore */
1949         if (rc)
1950                 set_bit(LU_OBJECT_HEARD_BANSHEE,
1951                             &child->mo_lu.lo_header->loh_flags);
1952         return rc;
1953 }
1954
1955 /*
1956  * Get locks on parents in proper order
1957  * RETURN: < 0 - error, rename_order if successful
1958  */
1959 enum rename_order {
1960         MDD_RN_SAME,
1961         MDD_RN_SRCTGT,
1962         MDD_RN_TGTSRC
1963 };
1964
1965 static int mdd_rename_order(const struct lu_env *env,
1966                             struct mdd_device *mdd,
1967                             struct mdd_object *src_pobj,
1968                             struct mdd_object *tgt_pobj)
1969 {
1970         /* order of locking, 1 - tgt-src, 0 - src-tgt*/
1971         int rc;
1972         ENTRY;
1973
1974         if (src_pobj == tgt_pobj)
1975                 RETURN(MDD_RN_SAME);
1976
1977         /* compared the parent child relationship of src_p&tgt_p */
1978         if (lu_fid_eq(&mdd->mdd_root_fid, mdo2fid(src_pobj))){
1979                 rc = MDD_RN_SRCTGT;
1980         } else if (lu_fid_eq(&mdd->mdd_root_fid, mdo2fid(tgt_pobj))) {
1981                 rc = MDD_RN_TGTSRC;
1982         } else {
1983                 rc = mdd_is_parent(env, mdd, src_pobj, mdo2fid(tgt_pobj), NULL);
1984                 if (rc == -EREMOTE)
1985                         rc = 0;
1986
1987                 if (rc == 1)
1988                         rc = MDD_RN_TGTSRC;
1989                 else if (rc == 0)
1990                         rc = MDD_RN_SRCTGT;
1991         }
1992
1993         RETURN(rc);
1994 }
1995
1996 /* has not mdd_write{read}_lock on any obj yet. */
1997 static int mdd_rename_sanity_check(const struct lu_env *env,
1998                                    struct mdd_object *src_pobj,
1999                                    struct mdd_object *tgt_pobj,
2000                                    struct mdd_object *sobj,
2001                                    struct mdd_object *tobj,
2002                                    struct lu_attr *so_attr,
2003                                    struct lu_attr *tg_attr)
2004 {
2005         int rc = 0;
2006         ENTRY;
2007
2008         /* XXX: when get here, sobj must NOT be NULL,
2009          * the other case has been processed in cml_rename
2010          * before mdd_rename and enable MDS_PERM_BYPASS. */
2011         LASSERT(sobj);
2012
2013         rc = mdd_may_delete(env, src_pobj, sobj, so_attr, NULL, 1, 0);
2014         if (rc)
2015                 RETURN(rc);
2016
2017         /* XXX: when get here, "tobj == NULL" means tobj must
2018          * NOT exist (neither on remote MDS, such case has been
2019          * processed in cml_rename before mdd_rename and enable
2020          * MDS_PERM_BYPASS).
2021          * So check may_create, but not check may_unlink. */
2022         if (!tobj)
2023                 rc = mdd_may_create(env, tgt_pobj, NULL,
2024                                     (src_pobj != tgt_pobj), 0);
2025         else
2026                 rc = mdd_may_delete(env, tgt_pobj, tobj, tg_attr, so_attr,
2027                                     (src_pobj != tgt_pobj), 1);
2028
2029         if (!rc && !tobj && (src_pobj != tgt_pobj) &&
2030             S_ISDIR(so_attr->la_mode))
2031                 rc = __mdd_may_link(env, tgt_pobj);
2032
2033         RETURN(rc);
2034 }
2035
2036 static int mdd_declare_rename(const struct lu_env *env,
2037                               struct mdd_device *mdd,
2038                               struct mdd_object *mdd_spobj,
2039                               struct mdd_object *mdd_tpobj,
2040                               struct mdd_object *mdd_sobj,
2041                               struct mdd_object *mdd_tobj,
2042                               const struct lu_name *tname,
2043                               const struct lu_name *sname,
2044                               struct md_attr *ma,
2045                               struct thandle *handle)
2046 {
2047         int rc;
2048
2049         LASSERT(mdd_spobj);
2050         LASSERT(mdd_tpobj);
2051         LASSERT(mdd_sobj);
2052
2053         /* name from source dir */
2054         rc = mdo_declare_index_delete(env, mdd_spobj, sname->ln_name, handle);
2055         if (rc)
2056                 return rc;
2057
2058         /* .. from source child */
2059         if (S_ISDIR(mdd_object_type(mdd_sobj))) {
2060                 /* source child can be directory,
2061                  * counted by source dir's nlink */
2062                 rc = mdo_declare_ref_del(env, mdd_spobj, handle);
2063                 if (rc)
2064                         return rc;
2065
2066                 rc = mdo_declare_index_delete(env, mdd_sobj, dotdot, handle);
2067                 if (rc)
2068                         return rc;
2069
2070                 rc = mdo_declare_index_insert(env, mdd_sobj, mdo2fid(mdd_tpobj),
2071                                               dotdot, handle);
2072                 if (rc)
2073                         return rc;
2074
2075                 /* new target child can be directory,
2076                  * counted by target dir's nlink */
2077                 rc = mdo_declare_ref_add(env, mdd_tpobj, handle);
2078                 if (rc)
2079                         return rc;
2080
2081         }
2082
2083         rc = mdo_declare_attr_set(env, mdd_spobj, NULL, handle);
2084         if (rc)
2085                 return rc;
2086
2087         rc = mdo_declare_attr_set(env, mdd_sobj, NULL, handle);
2088         if (rc)
2089                 return rc;
2090         mdd_declare_links_add(env, mdd_sobj, handle);
2091         if (rc)
2092                 return rc;
2093
2094         rc = mdo_declare_attr_set(env, mdd_tpobj, NULL, handle);
2095         if (rc)
2096                 return rc;
2097
2098         /* new name */
2099         rc = mdo_declare_index_insert(env, mdd_tpobj, mdo2fid(mdd_sobj),
2100                         tname->ln_name, handle);
2101         if (rc)
2102                 return rc;
2103
2104         /* name from target dir (old name), we declare it unconditionally
2105          * as mdd_rename() calls delete unconditionally as well. so just
2106          * to balance declarations vs calls to change ... */
2107         rc = mdo_declare_index_delete(env, mdd_tpobj, tname->ln_name, handle);
2108         if (rc)
2109                 return rc;
2110
2111         if (mdd_tobj && mdd_object_exists(mdd_tobj)) {
2112                 /* delete target child in target parent directory */
2113                 rc = mdo_declare_ref_del(env, mdd_tobj, handle);
2114                 if (rc)
2115                         return rc;
2116
2117                 if (S_ISDIR(mdd_object_type(mdd_tobj))) {
2118                         /* target child can be directory,
2119                          * delete "." reference in target child directory */
2120                         rc = mdo_declare_ref_del(env, mdd_tobj, handle);
2121                         if (rc)
2122                                 return rc;
2123
2124                         /* delete ".." reference in target parent directory */
2125                         rc = mdo_declare_ref_del(env, mdd_tpobj, handle);
2126                         if (rc)
2127                                 return rc;
2128                 }
2129
2130                 rc = mdo_declare_attr_set(env, mdd_tobj, NULL, handle);
2131                 if (rc)
2132                         return rc;
2133
2134                 mdd_declare_links_add(env, mdd_tobj, handle);
2135                 if (rc)
2136                         return rc;
2137
2138                 rc = mdd_declare_finish_unlink(env, mdd_tobj, ma, handle);
2139                 if (rc)
2140                         return rc;
2141         }
2142
2143         rc = mdd_declare_changelog_ext_store(env, mdd, tname, sname, handle);
2144         if (rc)
2145                 return rc;
2146
2147         return rc;
2148 }
2149
2150 /* src object can be remote that is why we use only fid and type of object */
2151 static int mdd_rename(const struct lu_env *env,
2152                       struct md_object *src_pobj, struct md_object *tgt_pobj,
2153                       const struct lu_fid *lf, const struct lu_name *lsname,
2154                       struct md_object *tobj, const struct lu_name *ltname,
2155                       struct md_attr *ma)
2156 {
2157         const char *sname = lsname->ln_name;
2158         const char *tname = ltname->ln_name;
2159         struct lu_attr    *la = &mdd_env_info(env)->mti_la_for_fix;
2160         struct lu_attr    *so_attr = &mdd_env_info(env)->mti_cattr;
2161         struct lu_attr    *tg_attr = &mdd_env_info(env)->mti_pattr;
2162         struct mdd_object *mdd_spobj = md2mdd_obj(src_pobj); /* source parent */
2163         struct mdd_object *mdd_tpobj = md2mdd_obj(tgt_pobj);
2164         struct mdd_device *mdd = mdo2mdd(src_pobj);
2165         struct mdd_object *mdd_sobj = NULL;                  /* source object */
2166         struct mdd_object *mdd_tobj = NULL;
2167         struct dynlock_handle *sdlh, *tdlh;
2168         struct thandle *handle;
2169         const struct lu_fid *tpobj_fid = mdo2fid(mdd_tpobj);
2170         const struct lu_fid *spobj_fid = mdo2fid(mdd_spobj);
2171         bool is_dir;
2172         bool tobj_ref = 0;
2173         bool tobj_locked = 0;
2174         unsigned cl_flags = 0;
2175         int rc, rc2;
2176         ENTRY;
2177
2178         if (tobj)
2179                 mdd_tobj = md2mdd_obj(tobj);
2180
2181         mdd_sobj = mdd_object_find(env, mdd, lf);
2182
2183         handle = mdd_trans_create(env, mdd);
2184         if (IS_ERR(handle))
2185                 GOTO(out_pending, rc = PTR_ERR(handle));
2186
2187         rc = mdd_declare_rename(env, mdd, mdd_spobj, mdd_tpobj, mdd_sobj,
2188                                 mdd_tobj, lsname, ltname, ma, handle);
2189         if (rc)
2190                 GOTO(stop, rc);
2191
2192         rc = mdd_trans_start(env, mdd, handle);
2193         if (rc)
2194                 GOTO(stop, rc);
2195
2196         /* FIXME: Should consider tobj and sobj too in rename_lock. */
2197         rc = mdd_rename_order(env, mdd, mdd_spobj, mdd_tpobj);
2198         if (rc < 0)
2199                 GOTO(cleanup_unlocked, rc);
2200
2201         /* Get locks in determined order */
2202         if (rc == MDD_RN_SAME) {
2203                 sdlh = mdd_pdo_write_lock(env, mdd_spobj,
2204                                           sname, MOR_SRC_PARENT);
2205                 /* check hashes to determine do we need one lock or two */
2206                 if (mdd_name2hash(sname) != mdd_name2hash(tname))
2207                         tdlh = mdd_pdo_write_lock(env, mdd_tpobj, tname,
2208                                 MOR_TGT_PARENT);
2209                 else
2210                         tdlh = sdlh;
2211         } else if (rc == MDD_RN_SRCTGT) {
2212                 sdlh = mdd_pdo_write_lock(env, mdd_spobj, sname,MOR_SRC_PARENT);
2213                 tdlh = mdd_pdo_write_lock(env, mdd_tpobj, tname,MOR_TGT_PARENT);
2214         } else {
2215                 tdlh = mdd_pdo_write_lock(env, mdd_tpobj, tname,MOR_SRC_PARENT);
2216                 sdlh = mdd_pdo_write_lock(env, mdd_spobj, sname,MOR_TGT_PARENT);
2217         }
2218         if (sdlh == NULL || tdlh == NULL)
2219                 GOTO(cleanup, rc = -ENOMEM);
2220
2221         rc = mdd_la_get(env, mdd_sobj, so_attr,
2222                         mdd_object_capa(env, mdd_sobj));
2223         if (rc)
2224                 GOTO(cleanup, rc);
2225
2226         if (mdd_tobj) {
2227                 rc = mdd_la_get(env, mdd_tobj, tg_attr,
2228                                 mdd_object_capa(env, mdd_tobj));
2229                 if (rc)
2230                         GOTO(cleanup, rc);
2231         }
2232
2233         rc = mdd_rename_sanity_check(env, mdd_spobj, mdd_tpobj, mdd_sobj,
2234                                      mdd_tobj, so_attr, tg_attr);
2235         if (rc)
2236                 GOTO(cleanup, rc);
2237
2238         is_dir = S_ISDIR(so_attr->la_mode);
2239
2240         /* Remove source name from source directory */
2241         rc = __mdd_index_delete(env, mdd_spobj, sname, is_dir, handle,
2242                                 mdd_object_capa(env, mdd_spobj));
2243         if (rc)
2244                 GOTO(cleanup, rc);
2245
2246         /* "mv dir1 dir2" needs "dir1/.." link update */
2247         if (is_dir && mdd_sobj && !lu_fid_eq(spobj_fid, tpobj_fid)) {
2248                 rc = __mdd_index_delete_only(env, mdd_sobj, dotdot, handle,
2249                                         mdd_object_capa(env, mdd_sobj));
2250                 if (rc)
2251                         GOTO(fixup_spobj2, rc);
2252
2253                 rc = __mdd_index_insert_only(env, mdd_sobj, tpobj_fid, dotdot,
2254                                       handle, mdd_object_capa(env, mdd_sobj));
2255                 if (rc)
2256                         GOTO(fixup_spobj, rc);
2257         }
2258
2259         /* Remove target name from target directory
2260          * Here tobj can be remote one, so we do index_delete unconditionally
2261          * and -ENOENT is allowed.
2262          */
2263         rc = __mdd_index_delete(env, mdd_tpobj, tname, is_dir, handle,
2264                                 mdd_object_capa(env, mdd_tpobj));
2265         if (rc != 0) {
2266                 if (mdd_tobj) {
2267                         /* tname might been renamed to something else */
2268                         GOTO(fixup_spobj, rc);
2269                 }
2270                 if (rc != -ENOENT)
2271                         GOTO(fixup_spobj, rc);
2272         }
2273
2274         /* Insert new fid with target name into target dir */
2275         rc = __mdd_index_insert(env, mdd_tpobj, lf, tname, is_dir, handle,
2276                                 mdd_object_capa(env, mdd_tpobj));
2277         if (rc)
2278                 GOTO(fixup_tpobj, rc);
2279
2280         LASSERT(ma->ma_attr.la_valid & LA_CTIME);
2281         la->la_ctime = la->la_mtime = ma->ma_attr.la_ctime;
2282
2283         /* XXX: mdd_sobj must be local one if it is NOT NULL. */
2284         if (mdd_sobj) {
2285                 la->la_valid = LA_CTIME;
2286                 rc = mdd_attr_check_set_internal(env, mdd_sobj, la, handle, 0);
2287                 if (rc)
2288                         GOTO(fixup_tpobj, rc);
2289         }
2290
2291         /* Remove old target object
2292          * For tobj is remote case cmm layer has processed
2293          * and set tobj to NULL then. So when tobj is NOT NULL,
2294          * it must be local one.
2295          */
2296         if (tobj && mdd_object_exists(mdd_tobj)) {
2297                 mdd_write_lock(env, mdd_tobj, MOR_TGT_CHILD);
2298                 tobj_locked = 1;
2299                 if (mdd_is_dead_obj(mdd_tobj)) {
2300                         /* shld not be dead, something is wrong */
2301                         CERROR("tobj is dead, something is wrong\n");
2302                         rc = -EINVAL;
2303                         goto cleanup;
2304                 }
2305                 mdo_ref_del(env, mdd_tobj, handle);
2306
2307                 /* Remove dot reference. */
2308                 if (S_ISDIR(tg_attr->la_mode))
2309                         mdo_ref_del(env, mdd_tobj, handle);
2310                 tobj_ref = 1;
2311
2312                 /* fetch updated nlink */
2313                 rc = mdd_la_get(env, mdd_tobj, tg_attr,
2314                                 mdd_object_capa(env, mdd_tobj));
2315                 if (rc != 0) {
2316                         CERROR("%s: Failed to get nlink for tobj "
2317                                 DFID": rc = %d\n",
2318                                 mdd2obd_dev(mdd)->obd_name,
2319                                 PFID(tpobj_fid), rc);
2320                         GOTO(fixup_tpobj, rc);
2321                 }
2322
2323                 la->la_valid = LA_CTIME;
2324                 rc = mdd_attr_check_set_internal(env, mdd_tobj, la, handle, 0);
2325                 if (rc != 0) {
2326                         CERROR("%s: Failed to set ctime for tobj "
2327                                 DFID": rc = %d\n",
2328                                 mdd2obd_dev(mdd)->obd_name,
2329                                 PFID(tpobj_fid), rc);
2330                         GOTO(fixup_tpobj, rc);
2331                 }
2332
2333                 /* XXX: this transfer to ma will be removed with LOD/OSP */
2334                 ma->ma_attr = *tg_attr;
2335                 ma->ma_valid |= MA_INODE;
2336                 rc = mdd_finish_unlink(env, mdd_tobj, ma, handle);
2337                 if (rc != 0) {
2338                         CERROR("%s: Failed to unlink tobj "
2339                                 DFID": rc = %d\n",
2340                                 mdd2obd_dev(mdd)->obd_name,
2341                                 PFID(tpobj_fid), rc);
2342                         GOTO(fixup_tpobj, rc);
2343                 }
2344
2345                 /* fetch updated nlink */
2346                 rc = mdd_la_get(env, mdd_tobj, tg_attr,
2347                                 mdd_object_capa(env, mdd_tobj));
2348                 if (rc != 0) {
2349                         CERROR("%s: Failed to get nlink for tobj "
2350                                 DFID": rc = %d\n",
2351                                 mdd2obd_dev(mdd)->obd_name,
2352                                 PFID(tpobj_fid), rc);
2353                         GOTO(fixup_tpobj, rc);
2354                 }
2355                 /* XXX: this transfer to ma will be removed with LOD/OSP */
2356                 ma->ma_attr = *tg_attr;
2357                 ma->ma_valid |= MA_INODE;
2358
2359                 if (so_attr->la_nlink == 0)
2360                         cl_flags |= CLF_RENAME_LAST;
2361         }
2362
2363         la->la_valid = LA_CTIME | LA_MTIME;
2364         rc = mdd_attr_check_set_internal(env, mdd_spobj, la, handle, 0);
2365         if (rc)
2366                 GOTO(fixup_tpobj, rc);
2367
2368         if (mdd_spobj != mdd_tpobj) {
2369                 la->la_valid = LA_CTIME | LA_MTIME;
2370                 rc = mdd_attr_check_set_internal(env, mdd_tpobj, la,
2371                                                  handle, 0);
2372         }
2373
2374         if (rc == 0 && mdd_sobj) {
2375                 mdd_write_lock(env, mdd_sobj, MOR_SRC_CHILD);
2376                 rc = mdd_links_rename(env, mdd_sobj, mdo2fid(mdd_spobj), lsname,
2377                                       mdo2fid(mdd_tpobj), ltname, handle, 0, 0);
2378                 if (rc == -ENOENT)
2379                         /* Old files might not have EA entry */
2380                         mdd_links_add(env, mdd_sobj, mdo2fid(mdd_spobj),
2381                                       lsname, handle, 0);
2382                 mdd_write_unlock(env, mdd_sobj);
2383                 /* We don't fail the transaction if the link ea can't be
2384                    updated -- fid2path will use alternate lookup method. */
2385                 rc = 0;
2386         }
2387
2388         EXIT;
2389
2390 fixup_tpobj:
2391         if (rc) {
2392                 rc2 = __mdd_index_delete(env, mdd_tpobj, tname, is_dir, handle,
2393                                          BYPASS_CAPA);
2394                 if (rc2)
2395                         CWARN("tp obj fix error %d\n",rc2);
2396
2397                 if (mdd_tobj && mdd_object_exists(mdd_tobj) &&
2398                     !mdd_is_dead_obj(mdd_tobj)) {
2399                         if (tobj_ref) {
2400                                 mdo_ref_add(env, mdd_tobj, handle);
2401                                 if (is_dir)
2402                                         mdo_ref_add(env, mdd_tobj, handle);
2403                         }
2404
2405                         rc2 = __mdd_index_insert(env, mdd_tpobj,
2406                                          mdo2fid(mdd_tobj), tname,
2407                                          is_dir, handle,
2408                                          BYPASS_CAPA);
2409
2410                         if (rc2)
2411                                 CWARN("tp obj fix error %d\n",rc2);
2412                 }
2413         }
2414
2415 fixup_spobj:
2416         if (rc && is_dir && mdd_sobj) {
2417                 rc2 = __mdd_index_delete_only(env, mdd_sobj, dotdot, handle,
2418                                               BYPASS_CAPA);
2419
2420                 if (rc2)
2421                         CWARN("sp obj dotdot delete error %d\n",rc2);
2422
2423
2424                 rc2 = __mdd_index_insert_only(env, mdd_sobj, spobj_fid,
2425                                               dotdot, handle, BYPASS_CAPA);
2426                 if (rc2)
2427                         CWARN("sp obj dotdot insert error %d\n",rc2);
2428         }
2429
2430 fixup_spobj2:
2431         if (rc) {
2432                 rc2 = __mdd_index_insert(env, mdd_spobj,
2433                                          lf, sname, is_dir, handle, BYPASS_CAPA);
2434                 if (rc2)
2435                         CWARN("sp obj fix error %d\n",rc2);
2436         }
2437 cleanup:
2438         if (tobj_locked)
2439                 mdd_write_unlock(env, mdd_tobj);
2440         if (likely(tdlh) && sdlh != tdlh)
2441                 mdd_pdo_write_unlock(env, mdd_tpobj, tdlh);
2442         if (likely(sdlh))
2443                 mdd_pdo_write_unlock(env, mdd_spobj, sdlh);
2444 cleanup_unlocked:
2445         if (rc == 0)
2446                 rc = mdd_changelog_ext_ns_store(env, mdd, CL_RENAME, cl_flags,
2447                                                 mdd_tobj, tpobj_fid, lf,
2448                                                 spobj_fid, ltname, lsname,
2449                                                 handle);
2450
2451 stop:
2452         mdd_trans_stop(env, mdd, rc, handle);
2453         if (mdd_sobj)
2454                 mdd_object_put(env, mdd_sobj);
2455 out_pending:
2456         return rc;
2457 }
2458
2459 /**
2460  * The data that link search is done on.
2461  */
2462 struct mdd_link_data {
2463         /**
2464          * Buffer to keep link EA body.
2465          */
2466         struct lu_buf           *ml_buf;
2467         /**
2468          * The matched header, entry and its lenght in the EA
2469          */
2470         struct link_ea_header   *ml_leh;
2471         struct link_ea_entry    *ml_lee;
2472         int                      ml_reclen;
2473 };
2474
2475 static int mdd_links_new(const struct lu_env *env,
2476                          struct mdd_link_data *ldata)
2477 {
2478         ldata->ml_buf = mdd_buf_alloc(env, CFS_PAGE_SIZE);
2479         if (ldata->ml_buf->lb_buf == NULL)
2480                 return -ENOMEM;
2481         ldata->ml_leh = ldata->ml_buf->lb_buf;
2482         ldata->ml_leh->leh_magic = LINK_EA_MAGIC;
2483         ldata->ml_leh->leh_len = sizeof(struct link_ea_header);
2484         ldata->ml_leh->leh_reccount = 0;
2485         return 0;
2486 }
2487
2488 /** Read the link EA into a temp buffer.
2489  * Uses the mdd_thread_info::mti_big_buf since it is generally large.
2490  * A pointer to the buffer is stored in \a ldata::ml_buf.
2491  *
2492  * \retval 0 or error
2493  */
2494 int mdd_links_read(const struct lu_env *env,
2495                    struct mdd_object *mdd_obj,
2496                    struct mdd_link_data *ldata)
2497 {
2498         struct lustre_capa *capa;
2499         struct link_ea_header *leh;
2500         int rc;
2501
2502         /* First try a small buf */
2503         LASSERT(env != NULL);
2504         ldata->ml_buf = mdd_buf_alloc(env, CFS_PAGE_SIZE);
2505         if (ldata->ml_buf->lb_buf == NULL)
2506                 return -ENOMEM;
2507
2508         if (!mdd_object_exists(mdd_obj))
2509                 return -ENODATA;
2510
2511         capa = mdd_object_capa(env, mdd_obj);
2512         rc = mdo_xattr_get(env, mdd_obj, ldata->ml_buf,
2513                            XATTR_NAME_LINK, capa);
2514         if (rc == -ERANGE) {
2515                 /* Buf was too small, figure out what we need. */
2516                 mdd_buf_put(ldata->ml_buf);
2517                 rc = mdo_xattr_get(env, mdd_obj, ldata->ml_buf,
2518                                    XATTR_NAME_LINK, capa);
2519                 if (rc < 0)
2520                         return rc;
2521                 ldata->ml_buf = mdd_buf_alloc(env, rc);
2522                 if (ldata->ml_buf->lb_buf == NULL)
2523                         return -ENOMEM;
2524                 rc = mdo_xattr_get(env, mdd_obj, ldata->ml_buf,
2525                                    XATTR_NAME_LINK, capa);
2526         }
2527         if (rc < 0)
2528                 return rc;
2529
2530         leh = ldata->ml_buf->lb_buf;
2531         if (leh->leh_magic == __swab32(LINK_EA_MAGIC)) {
2532                 leh->leh_magic = LINK_EA_MAGIC;
2533                 leh->leh_reccount = __swab32(leh->leh_reccount);
2534                 leh->leh_len = __swab64(leh->leh_len);
2535                 /* entries are swabbed by mdd_lee_unpack */
2536         }
2537         if (leh->leh_magic != LINK_EA_MAGIC)
2538                 return -EINVAL;
2539         if (leh->leh_reccount == 0)
2540                 return -ENODATA;
2541
2542         ldata->ml_leh = leh;
2543         return 0;
2544 }
2545
2546 /** Read the link EA into a temp buffer.
2547  * Uses the name_buf since it is generally large.
2548  * \retval IS_ERR err
2549  * \retval ptr to \a lu_buf (always \a mti_big_buf)
2550  */
2551 struct lu_buf *mdd_links_get(const struct lu_env *env,
2552                              struct mdd_object *mdd_obj)
2553 {
2554         struct mdd_link_data ldata = { 0 };
2555         int rc;
2556
2557         rc = mdd_links_read(env, mdd_obj, &ldata);
2558         return rc ? ERR_PTR(rc) : ldata.ml_buf;
2559 }
2560
2561 static int mdd_links_write(const struct lu_env *env,
2562                            struct mdd_object *mdd_obj,
2563                            struct mdd_link_data *ldata,
2564                            struct thandle *handle)
2565 {
2566         const struct lu_buf *buf = mdd_buf_get_const(env, ldata->ml_buf->lb_buf,
2567                                                      ldata->ml_leh->leh_len);
2568         return mdo_xattr_set(env, mdd_obj, buf, XATTR_NAME_LINK, 0, handle,
2569                              mdd_object_capa(env, mdd_obj));
2570 }
2571
2572 /** Pack a link_ea_entry.
2573  * All elements are stored as chars to avoid alignment issues.
2574  * Numbers are always big-endian
2575  * \retval record length
2576  */
2577 static int mdd_lee_pack(struct link_ea_entry *lee, const struct lu_name *lname,
2578                         const struct lu_fid *pfid)
2579 {
2580         struct lu_fid   tmpfid;
2581         int             reclen;
2582
2583         fid_cpu_to_be(&tmpfid, pfid);
2584         memcpy(&lee->lee_parent_fid, &tmpfid, sizeof(tmpfid));
2585         memcpy(lee->lee_name, lname->ln_name, lname->ln_namelen);
2586         reclen = sizeof(struct link_ea_entry) + lname->ln_namelen;
2587
2588         lee->lee_reclen[0] = (reclen >> 8) & 0xff;
2589         lee->lee_reclen[1] = reclen & 0xff;
2590         return reclen;
2591 }
2592
2593 void mdd_lee_unpack(const struct link_ea_entry *lee, int *reclen,
2594                     struct lu_name *lname, struct lu_fid *pfid)
2595 {
2596         *reclen = (lee->lee_reclen[0] << 8) | lee->lee_reclen[1];
2597         memcpy(pfid, &lee->lee_parent_fid, sizeof(*pfid));
2598         fid_be_to_cpu(pfid, pfid);
2599         lname->ln_name = lee->lee_name;
2600         lname->ln_namelen = *reclen - sizeof(struct link_ea_entry);
2601 }
2602
2603 static int mdd_declare_links_add(const struct lu_env *env,
2604                                  struct mdd_object *mdd_obj,
2605                                  struct thandle *handle)
2606 {
2607         int rc;
2608
2609         /* XXX: max size? */
2610         rc = mdo_declare_xattr_set(env, mdd_obj,
2611                              mdd_buf_get_const(env, NULL, 4096),
2612                              XATTR_NAME_LINK, 0, handle);
2613
2614         return rc;
2615 }
2616
2617 /* For pathologic linkers, we don't want to spend lots of time scanning the
2618  * link ea.  Limit ourseleves to something reasonable; links not in the EA
2619  * can be looked up via (slower) parent lookup.
2620  */
2621 #define LINKEA_MAX_COUNT 128
2622
2623 /** Add a record to the end of link ea buf */
2624 static int mdd_links_add_buf(const struct lu_env *env,
2625                              struct mdd_link_data *ldata,
2626                              const struct lu_name *lname,
2627                              const struct lu_fid *pfid)
2628 {
2629         LASSERT(ldata->ml_leh != NULL);
2630
2631         if (lname == NULL || pfid == NULL)
2632                 return -EINVAL;
2633
2634         /* Make sure our buf is big enough for the new one */
2635         if (ldata->ml_leh->leh_reccount > LINKEA_MAX_COUNT)
2636                 return -EOVERFLOW;
2637
2638         ldata->ml_reclen = lname->ln_namelen + sizeof(struct link_ea_entry);
2639         if (ldata->ml_leh->leh_len + ldata->ml_reclen >
2640             ldata->ml_buf->lb_len) {
2641                 if (mdd_buf_grow(env, ldata->ml_leh->leh_len +
2642                                  ldata->ml_reclen) < 0)
2643                         return -ENOMEM;
2644         }
2645
2646         ldata->ml_leh = ldata->ml_buf->lb_buf;
2647         ldata->ml_lee = ldata->ml_buf->lb_buf + ldata->ml_leh->leh_len;
2648         ldata->ml_reclen = mdd_lee_pack(ldata->ml_lee, lname, pfid);
2649         ldata->ml_leh->leh_len += ldata->ml_reclen;
2650         ldata->ml_leh->leh_reccount++;
2651         CDEBUG(D_INODE, "New link_ea name '%.*s' is added\n",
2652                lname->ln_namelen, lname->ln_name);
2653         return 0;
2654 }
2655
2656 /** Del the current record from the link ea buf */
2657 static void mdd_links_del_buf(const struct lu_env *env,
2658                               struct mdd_link_data *ldata,
2659                               const struct lu_name *lname)
2660 {
2661         LASSERT(ldata->ml_leh != NULL);
2662
2663         ldata->ml_leh->leh_reccount--;
2664         ldata->ml_leh->leh_len -= ldata->ml_reclen;
2665         memmove(ldata->ml_lee, (char *)ldata->ml_lee + ldata->ml_reclen,
2666                 (char *)ldata->ml_leh + ldata->ml_leh->leh_len -
2667                 (char *)ldata->ml_lee);
2668         CDEBUG(D_INODE, "Old link_ea name '%.*s' is removed\n",
2669                lname->ln_namelen, lname->ln_name);
2670
2671 }
2672
2673 /**
2674  * Check if such a link exists in linkEA.
2675  *
2676  * \param mdd_obj object being handled
2677  * \param pfid parent fid the link to be found for
2678  * \param lname name in the parent's directory entry pointing to this object
2679  * \param ldata link data the search to be done on
2680  *
2681  * \retval   0 success
2682  * \retval -ENOENT link does not exist
2683  * \retval -ve on error
2684  */
2685 static int mdd_links_find(const struct lu_env  *env,
2686                           struct mdd_object    *mdd_obj,
2687                           struct mdd_link_data *ldata,
2688                           const struct lu_name *lname,
2689                           const struct lu_fid  *pfid)
2690 {
2691         struct lu_name *tmpname = &mdd_env_info(env)->mti_name2;
2692         struct lu_fid  *tmpfid = &mdd_env_info(env)->mti_fid;
2693         int count;
2694
2695         LASSERT(ldata->ml_leh != NULL);
2696
2697         /* link #0 */
2698         ldata->ml_lee = (struct link_ea_entry *)(ldata->ml_leh + 1);
2699
2700         for (count = 0; count < ldata->ml_leh->leh_reccount; count++) {
2701                 mdd_lee_unpack(ldata->ml_lee, &ldata->ml_reclen,
2702                                tmpname, tmpfid);
2703                 if (tmpname->ln_namelen == lname->ln_namelen &&
2704                     lu_fid_eq(tmpfid, pfid) &&
2705                     (strncmp(tmpname->ln_name, lname->ln_name,
2706                              tmpname->ln_namelen) == 0))
2707                         break;
2708                 ldata->ml_lee = (struct link_ea_entry *)((char *)ldata->ml_lee +
2709                                                          ldata->ml_reclen);
2710         }
2711
2712         if (count == ldata->ml_leh->leh_reccount) {
2713                 CDEBUG(D_INODE, "Old link_ea name '%.*s' not found\n",
2714                        lname->ln_namelen, lname->ln_name);
2715                 return -ENOENT;
2716         }
2717         return 0;
2718 }
2719
2720 static int __mdd_links_add(const struct lu_env *env,
2721                            struct mdd_object *mdd_obj,
2722                            struct mdd_link_data *ldata,
2723                            const struct lu_name *lname,
2724                            const struct lu_fid *pfid,
2725                            int first, int check)
2726 {
2727         int rc;
2728
2729         if (ldata->ml_leh == NULL) {
2730                 rc = first ? -ENODATA : mdd_links_read(env, mdd_obj, ldata);
2731                 if (rc) {
2732                         if (rc != -ENODATA)
2733                                 return rc;
2734                         rc = mdd_links_new(env, ldata);
2735                         if (rc)
2736                                 return rc;
2737                 }
2738         }
2739
2740         if (check) {
2741                 rc = mdd_links_find(env, mdd_obj, ldata, lname, pfid);
2742                 if (rc && rc != -ENOENT)
2743                         return rc;
2744                 if (rc == 0)
2745                         return -EEXIST;
2746         }
2747
2748         return mdd_links_add_buf(env, ldata, lname, pfid);
2749 }
2750
2751 static int __mdd_links_del(const struct lu_env *env,
2752                            struct mdd_object *mdd_obj,
2753                            struct mdd_link_data *ldata,
2754                            const struct lu_name *lname,
2755                            const struct lu_fid *pfid)
2756 {
2757         int rc;
2758
2759         if (ldata->ml_leh == NULL) {
2760                 rc = mdd_links_read(env, mdd_obj, ldata);
2761                 if (rc)
2762                         return rc;
2763         }
2764
2765         rc = mdd_links_find(env, mdd_obj, ldata, lname, pfid);
2766         if (rc)
2767                 return rc;
2768
2769         mdd_links_del_buf(env, ldata, lname);
2770         return 0;
2771 }
2772
2773 static int mdd_links_rename(const struct lu_env *env,
2774                             struct mdd_object *mdd_obj,
2775                             const struct lu_fid *oldpfid,
2776                             const struct lu_name *oldlname,
2777                             const struct lu_fid *newpfid,
2778                             const struct lu_name *newlname,
2779                             struct thandle *handle,
2780                             int first, int check)
2781 {
2782         struct mdd_link_data ldata = { 0 };
2783         int updated = 0;
2784         int rc2 = 0;
2785         int rc = 0;
2786         ENTRY;
2787
2788         LASSERT(oldpfid != NULL || newpfid != NULL);
2789
2790         if (mdd_obj->mod_flags & DEAD_OBJ)
2791                 /* No more links, don't bother */
2792                 RETURN(0);
2793
2794         if (oldpfid != NULL) {
2795                 rc = __mdd_links_del(env, mdd_obj, &ldata,
2796                                      oldlname, oldpfid);
2797                 if (rc) {
2798                         if ((check == 0) ||
2799                             (rc != -ENODATA && rc != -ENOENT))
2800                                 GOTO(out, rc);
2801                         /* No changes done. */
2802                         rc = 0;
2803                 } else {
2804                         updated = 1;
2805                 }
2806         }
2807
2808         /* If renaming, add the new record */
2809         if (newpfid != NULL) {
2810                 /* even if the add fails, we still delete the out-of-date
2811                  * old link */
2812                 rc2 = __mdd_links_add(env, mdd_obj, &ldata,
2813                                       newlname, newpfid, first, check);
2814                 if (rc2 == -EEXIST)
2815                         rc2 = 0;
2816                 else if (rc2 == 0)
2817                         updated = 1;
2818         }
2819
2820         if (updated)
2821                 rc = mdd_links_write(env, mdd_obj, &ldata, handle);
2822         EXIT;
2823 out:
2824         if (rc == 0)
2825                 rc = rc2;
2826         if (rc) {
2827                 int error = 1;
2828                 if (rc == -EOVERFLOW || rc == - ENOENT)
2829                         error = 0;
2830                 if (oldpfid == NULL)
2831                         CDEBUG(error ? D_ERROR : D_OTHER,
2832                                "link_ea add '%.*s' failed %d "DFID"\n",
2833                                newlname->ln_namelen, newlname->ln_name,
2834                                rc, PFID(mdd_object_fid(mdd_obj)));
2835                 else if (newpfid == NULL)
2836                         CDEBUG(error ? D_ERROR : D_OTHER,
2837                                "link_ea del '%.*s' failed %d "DFID"\n",
2838                                oldlname->ln_namelen, oldlname->ln_name,
2839                                rc, PFID(mdd_object_fid(mdd_obj)));
2840                 else
2841                         CDEBUG(error ? D_ERROR : D_OTHER,
2842                                "link_ea rename '%.*s'->'%.*s' failed %d "
2843                                DFID"\n",
2844                                oldlname->ln_namelen, oldlname->ln_name,
2845                                newlname->ln_namelen, newlname->ln_name,
2846                                rc, PFID(mdd_object_fid(mdd_obj)));
2847         }
2848
2849         if (ldata.ml_buf && ldata.ml_buf->lb_len > OBD_ALLOC_BIG)
2850                 /* if we vmalloced a large buffer drop it */
2851                 mdd_buf_put(ldata.ml_buf);
2852
2853         return rc;
2854 }
2855
2856 static inline int mdd_links_add(const struct lu_env *env,
2857                                 struct mdd_object *mdd_obj,
2858                                 const struct lu_fid *pfid,
2859                                 const struct lu_name *lname,
2860                                 struct thandle *handle, int first)
2861 {
2862         return mdd_links_rename(env, mdd_obj, NULL, NULL,
2863                                 pfid, lname, handle, first, 0);
2864 }
2865
2866 static inline int mdd_links_del(const struct lu_env *env,
2867                                 struct mdd_object *mdd_obj,
2868                                 const struct lu_fid *pfid,
2869                                 const struct lu_name *lname,
2870                                 struct thandle *handle)
2871 {
2872         return mdd_links_rename(env, mdd_obj, pfid, lname,
2873                                 NULL, NULL, handle, 0, 0);
2874 }
2875
2876 const struct md_dir_operations mdd_dir_ops = {
2877         .mdo_is_subdir     = mdd_is_subdir,
2878         .mdo_lookup        = mdd_lookup,
2879         .mdo_create        = mdd_create,
2880         .mdo_rename        = mdd_rename,
2881         .mdo_link          = mdd_link,
2882         .mdo_unlink        = mdd_unlink,
2883         .mdo_create_data   = mdd_create_data,
2884 };