Whamcloud - gitweb
cd49c3c0cae0a7c83cf05fe2c9a1736fd57a60e9
[fs/lustre-release.git] / lustre / mds / mds_reint.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  *  linux/mds/mds_reint.c
5  *  Lustre Metadata Server (mds) reintegration routines
6  *
7  *  Copyright (C) 2002, 2003 Cluster File Systems, Inc.
8  *   Author: Peter Braam <braam@clusterfs.com>
9  *   Author: Andreas Dilger <adilger@clusterfs.com>
10  *   Author: Phil Schwan <phil@clusterfs.com>
11  *
12  *   This file is part of Lustre, http://www.lustre.org.
13  *
14  *   Lustre is free software; you can redistribute it and/or
15  *   modify it under the terms of version 2 of the GNU General Public
16  *   License as published by the Free Software Foundation.
17  *
18  *   Lustre is distributed in the hope that it will be useful,
19  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
20  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  *   GNU General Public License for more details.
22  *
23  *   You should have received a copy of the GNU General Public License
24  *   along with Lustre; if not, write to the Free Software
25  *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
26  */
27
28 #ifndef EXPORT_SYMTAB
29 # define EXPORT_SYMTAB
30 #endif
31 #define DEBUG_SUBSYSTEM S_MDS
32
33 #include <linux/fs.h>
34 #include <linux/jbd.h>
35 #include <linux/namei.h>
36 #include <linux/ext3_fs.h>
37 #include <linux/obd_support.h>
38 #include <linux/obd_class.h>
39 #include <linux/obd.h>
40 #include <linux/lustre_lib.h>
41 #include <linux/lustre_idl.h>
42 #include <linux/lustre_mds.h>
43 #include <linux/lustre_dlm.h>
44 #include <linux/lustre_log.h>
45 #include <linux/lustre_fsfilt.h>
46 #include <linux/lustre_lite.h>
47 #include "mds_internal.h"
48
49 struct mds_logcancel_data {
50         struct lov_mds_md      *mlcd_lmm;
51         int                     mlcd_size;
52         int                     mlcd_cookielen;
53         int                     mlcd_eadatalen;
54         struct llog_cookie      mlcd_cookies[0];
55 };
56
57 static void mds_cancel_cookies_cb(struct obd_device *obd,
58                                   __u64 transno, void *cb_data,
59                                   int error)
60 {
61         struct mds_logcancel_data *mlcd = cb_data;
62         struct lov_stripe_md *lsm = NULL;
63         struct llog_ctxt *ctxt;
64         int rc;
65
66         obd_transno_commit_cb(obd, transno, error);
67
68         CDEBUG(D_HA, "cancelling %d cookies\n",
69                (int)(mlcd->mlcd_cookielen / sizeof(*mlcd->mlcd_cookies)));
70
71         rc = obd_unpackmd(obd->u.mds.mds_dt_exp, &lsm, mlcd->mlcd_lmm,
72                           mlcd->mlcd_eadatalen);
73         if (rc < 0) {
74                 CERROR("bad LSM cancelling %d log cookies: rc %d\n",
75                        (int)(mlcd->mlcd_cookielen/sizeof(*mlcd->mlcd_cookies)),
76                        rc);
77         } else {
78                 ///* XXX 0 normally, SENDNOW for debug */);
79                 ctxt = llog_get_context(&obd->obd_llogs,
80                                         mlcd->mlcd_cookies[0].lgc_subsys + 1);
81                 rc = llog_cancel(ctxt, mlcd->mlcd_cookielen /
82                                  sizeof(*mlcd->mlcd_cookies),
83                                  mlcd->mlcd_cookies, OBD_LLOG_FL_SENDNOW, lsm);
84                 if (rc)
85                         CERROR("error cancelling %d log cookies: rc %d\n",
86                                (int)(mlcd->mlcd_cookielen /
87                                      sizeof(*mlcd->mlcd_cookies)), rc);
88                 obd_free_memmd(obd->u.mds.mds_dt_exp, &lsm);
89         }
90
91         OBD_FREE(mlcd, mlcd->mlcd_size);
92 }
93
94 /* Assumes caller has already pushed us into the kernel context. */
95 int mds_finish_transno(struct mds_obd *mds, struct inode *inode, void *handle,
96                        struct ptlrpc_request *req, int rc, __u32 op_data)
97 {
98         struct mds_export_data *med = &req->rq_export->exp_mds_data;
99         struct obd_device *obd = req->rq_export->exp_obd;
100         struct mds_client_data *mcd = med->med_mcd;
101         int err, log_pri = D_HA;
102         __u64 transno;
103         loff_t off;
104         ENTRY;
105
106         /* if the export has already been failed, we have no last_rcvd slot */
107         if (req->rq_export->exp_failed) {
108                 CERROR("committing transaction for disconnected client\n");
109                 if (handle)
110                         GOTO(out_commit, rc);
111                 RETURN(rc);
112         }
113
114         if (IS_ERR(handle))
115                 RETURN(rc);
116
117         if (handle == NULL) {
118                 /* if we're starting our own xaction, use our own inode */
119                 inode = mds->mds_rcvd_filp->f_dentry->d_inode;
120                 handle = fsfilt_start(obd, inode, FSFILT_OP_SETATTR, NULL);
121                 if (IS_ERR(handle)) {
122                         CERROR("fsfilt_start: %ld\n", PTR_ERR(handle));
123                         RETURN(PTR_ERR(handle));
124                 }
125         }
126
127         off = med->med_off;
128
129         transno = req->rq_reqmsg->transno;
130         if (rc != 0) {
131                 LASSERTF(transno == 0, "BUG 3934, t"LPU64" rc %d\n", transno, rc);
132         } else if (transno == 0) {
133                 spin_lock(&mds->mds_transno_lock);
134                 transno = ++mds->mds_last_transno;
135                 spin_unlock(&mds->mds_transno_lock);
136         } else {
137                 spin_lock(&mds->mds_transno_lock);
138                 if (transno > mds->mds_last_transno)
139                         mds->mds_last_transno = transno;
140                 spin_unlock(&mds->mds_transno_lock);
141         }
142         req->rq_repmsg->transno = req->rq_transno = transno;
143         if (req->rq_reqmsg->opc == MDS_CLOSE) {
144                 mcd->mcd_last_close_transno = cpu_to_le64(transno);
145                 mcd->mcd_last_close_xid = cpu_to_le64(req->rq_xid);
146                 mcd->mcd_last_close_result = cpu_to_le32(rc);
147                 mcd->mcd_last_close_data = cpu_to_le32(op_data);
148         } else {
149                 mcd->mcd_last_transno = cpu_to_le64(transno);
150                 mcd->mcd_last_xid = cpu_to_le64(req->rq_xid);
151                 mcd->mcd_last_result = cpu_to_le32(rc);
152                 mcd->mcd_last_data = cpu_to_le32(op_data);
153         }
154
155         fsfilt_add_journal_cb(obd, mds->mds_sb, transno, handle,
156                               mds_commit_last_transno_cb, NULL);
157         
158         err = fsfilt_write_record(obd, mds->mds_rcvd_filp, mcd,
159                                   sizeof(*mcd), &off, 0);
160
161         if (err) {
162                 log_pri = D_ERROR;
163                 if (rc == 0)
164                         rc = err;
165         }
166
167         DEBUG_REQ(log_pri, req,
168                   "wrote trans #"LPU64" client %s at idx %u: err = %d",
169                   transno, mcd->mcd_uuid, med->med_idx, err);
170
171         err = mds_update_last_fid(obd, handle, 0);
172         if (err) {
173                 log_pri = D_ERROR;
174                 if (rc == 0)
175                         rc = err;
176         }
177                 
178         err = mds_dt_write_objids(obd);
179         if (err) {
180                 log_pri = D_ERROR;
181                 if (rc == 0)
182                         rc = err;
183         }
184         CDEBUG(log_pri, "wrote objids: err = %d\n", err);
185
186         EXIT;
187 out_commit:
188         err = fsfilt_commit(obd, mds->mds_sb, inode, handle, 
189                             req->rq_export->exp_sync);
190         if (err) {
191                 CERROR("error committing transaction: %d\n", err);
192                 if (!rc)
193                         rc = err;
194         }
195
196         return rc;
197 }
198
199 /* this gives the same functionality as the code between
200  * sys_chmod and inode_setattr
201  * chown_common and inode_setattr
202  * utimes and inode_setattr
203  */
204 #ifndef ATTR_RAW
205 /* Just for the case if we have some clients that know about ATTR_RAW */
206 #define ATTR_RAW 8192
207 #endif
208 int mds_fix_attr(struct inode *inode, struct mds_update_record *rec)
209 {
210         time_t now = LTIME_S(CURRENT_TIME);
211         struct iattr *attr = &rec->ur_iattr;
212         unsigned int ia_valid = attr->ia_valid;
213         int error;
214         ENTRY;
215
216         /* only fix up attrs if the client VFS didn't already */
217
218         if (!(ia_valid & ATTR_RAW))
219                 RETURN(0);
220
221         if (!(ia_valid & ATTR_CTIME_SET))
222                 LTIME_S(attr->ia_ctime) = now;
223         if (!(ia_valid & ATTR_ATIME_SET))
224                 LTIME_S(attr->ia_atime) = now;
225         if (!(ia_valid & ATTR_MTIME_SET))
226                 LTIME_S(attr->ia_mtime) = now;
227
228         if (IS_IMMUTABLE(inode) || IS_APPEND(inode))
229                 RETURN(-EPERM);
230
231         /* times */
232         if ((ia_valid & (ATTR_MTIME|ATTR_ATIME)) == (ATTR_MTIME|ATTR_ATIME)) {
233                 if (rec->ur_fsuid != inode->i_uid &&
234                     (error = ll_permission(inode, MAY_WRITE, NULL)) != 0)
235                         RETURN(error);
236         }
237
238         if (ia_valid & ATTR_SIZE) {
239                 if ((error = ll_permission(inode, MAY_WRITE, NULL)) != 0)
240                         RETURN(error);
241         }
242
243         if (ia_valid & ATTR_UID) {
244                 /* chown */
245                 error = -EPERM;
246                 if (IS_IMMUTABLE(inode) || IS_APPEND(inode))
247                         RETURN(-EPERM);
248                 if (attr->ia_uid == (uid_t) -1)
249                         attr->ia_uid = inode->i_uid;
250                 if (attr->ia_gid == (gid_t) -1)
251                         attr->ia_gid = inode->i_gid;
252                 attr->ia_mode = inode->i_mode;
253                 /*
254                  * If the user or group of a non-directory has been
255                  * changed by a non-root user, remove the setuid bit.
256                  * 19981026 David C Niemi <niemi@tux.org>
257                  *
258                  * Changed this to apply to all users, including root,
259                  * to avoid some races. This is the behavior we had in
260                  * 2.0. The check for non-root was definitely wrong
261                  * for 2.2 anyway, as it should have been using
262                  * CAP_FSETID rather than fsuid -- 19990830 SD.
263                  */
264                 if ((inode->i_mode & S_ISUID) == S_ISUID &&
265                     !S_ISDIR(inode->i_mode)) {
266                         attr->ia_mode &= ~S_ISUID;
267                         attr->ia_valid |= ATTR_MODE;
268                 }
269                 /*
270                  * Likewise, if the user or group of a non-directory
271                  * has been changed by a non-root user, remove the
272                  * setgid bit UNLESS there is no group execute bit
273                  * (this would be a file marked for mandatory
274                  * locking).  19981026 David C Niemi <niemi@tux.org>
275                  *
276                  * Removed the fsuid check (see the comment above) --
277                  * 19990830 SD.
278                  */
279                 if (((inode->i_mode & (S_ISGID | S_IXGRP)) ==
280                      (S_ISGID | S_IXGRP)) && !S_ISDIR(inode->i_mode)) {
281                         attr->ia_mode &= ~S_ISGID;
282                         attr->ia_valid |= ATTR_MODE;
283                 }
284         } else if (ia_valid & ATTR_MODE) {
285                 int mode = attr->ia_mode;
286                 /* chmod */
287                 if (attr->ia_mode == (mode_t) -1)
288                         attr->ia_mode = inode->i_mode;
289                 attr->ia_mode =
290                         (mode & S_IALLUGO) | (inode->i_mode & ~S_IALLUGO);
291         }
292         RETURN(0);
293 }
294
295 void mds_steal_ack_locks(struct ptlrpc_request *req)
296 {
297         struct obd_export         *exp = req->rq_export;
298         char                       str[PTL_NALFMT_SIZE];
299         struct list_head          *tmp;
300         struct ptlrpc_reply_state *oldrep;
301         struct ptlrpc_service     *svc;
302         struct llog_create_locks  *lcl;
303         unsigned long              flags;
304         int                        i;
305
306         /* CAVEAT EMPTOR: spinlock order */
307         spin_lock_irqsave (&exp->exp_lock, flags);
308         list_for_each (tmp, &exp->exp_outstanding_replies) {
309                 oldrep = list_entry(tmp, struct ptlrpc_reply_state,rs_exp_list);
310
311                 if (oldrep->rs_xid != req->rq_xid)
312                         continue;
313
314                 if (oldrep->rs_msg->opc != req->rq_reqmsg->opc)
315                         CERROR ("Resent req xid "LPX64" has mismatched opc: "
316                                 "new %d old %d\n", req->rq_xid,
317                                 req->rq_reqmsg->opc, oldrep->rs_msg->opc);
318
319                 svc = oldrep->rs_srv_ni->sni_service;
320                 spin_lock (&svc->srv_lock);
321
322                 list_del_init (&oldrep->rs_exp_list);
323
324                 CWARN("Stealing %d locks from rs %p x"LPD64".t"LPD64
325                       " o%d NID %s\n", oldrep->rs_nlocks, oldrep,
326                       oldrep->rs_xid, oldrep->rs_transno, oldrep->rs_msg->opc,
327                       ptlrpc_peernid2str(&exp->exp_connection->c_peer, str));
328
329                 for (i = 0; i < oldrep->rs_nlocks; i++)
330                         ptlrpc_save_lock(req,
331                                          &oldrep->rs_locks[i],
332                                          oldrep->rs_modes[i]);
333                 oldrep->rs_nlocks = 0;
334
335                 lcl = oldrep->rs_llog_locks;
336                 oldrep->rs_llog_locks = NULL;
337                 if (lcl != NULL)
338                         ptlrpc_save_llog_lock(req, lcl);
339
340                 DEBUG_REQ(D_HA, req, "stole locks for");
341                 ptlrpc_schedule_difficult_reply (oldrep);
342
343                 spin_unlock (&svc->srv_lock);
344                 spin_unlock_irqrestore (&exp->exp_lock, flags);
345                 return;
346         }
347         spin_unlock_irqrestore (&exp->exp_lock, flags);
348 }
349
350 void mds_req_from_mcd(struct ptlrpc_request *req, struct mds_client_data *mcd)
351 {
352         if (req->rq_reqmsg->opc == MDS_CLOSE) {
353                 DEBUG_REQ(D_HA, req, "restoring transno "LPD64"/status %d",
354                           mcd->mcd_last_close_transno, mcd->mcd_last_close_result);
355                 req->rq_repmsg->transno = req->rq_transno = mcd->mcd_last_close_transno;
356                 req->rq_repmsg->status = req->rq_status = mcd->mcd_last_close_result;
357         } else {
358                 DEBUG_REQ(D_HA, req, "restoring transno "LPD64"/status %d",
359                           mcd->mcd_last_transno, mcd->mcd_last_result);
360                 req->rq_repmsg->transno = req->rq_transno = mcd->mcd_last_transno;
361                 req->rq_repmsg->status = req->rq_status = mcd->mcd_last_result;
362         }
363
364         mds_steal_ack_locks(req);
365 }
366
367 static void reconstruct_reint_setattr(struct mds_update_record *rec,
368                                       int offset, struct ptlrpc_request *req)
369 {
370         struct mds_export_data *med = &req->rq_export->exp_mds_data;
371         struct mds_body *body;
372         struct dentry *de;
373
374         mds_req_from_mcd(req, med->med_mcd);
375
376         de = mds_id2dentry(req2obd(req), rec->ur_id1, NULL);
377         if (IS_ERR(de)) {
378                 LASSERT(PTR_ERR(de) == req->rq_status);
379                 return;
380         }
381
382         body = lustre_msg_buf(req->rq_repmsg, 0, sizeof(*body));
383         mds_pack_inode2body(req2obd(req), body, de->d_inode, 1);
384
385         /* Don't return OST-specific attributes if we didn't just set them */
386         if (rec->ur_iattr.ia_valid & ATTR_SIZE)
387                 body->valid |= OBD_MD_FLSIZE | OBD_MD_FLBLOCKS;
388         if (rec->ur_iattr.ia_valid & (ATTR_MTIME | ATTR_MTIME_SET))
389                 body->valid |= OBD_MD_FLMTIME;
390         if (rec->ur_iattr.ia_valid & (ATTR_ATIME | ATTR_ATIME_SET))
391                 body->valid |= OBD_MD_FLATIME;
392
393         l_dput(de);
394 }
395
396 /* In the raw-setattr case, we lock the child inode.
397  * In the write-back case or if being called from open, the client holds a lock
398  * already.
399  *
400  * We use the ATTR_FROM_OPEN flag to tell these cases apart. */
401 static int mds_reint_setattr(struct mds_update_record *rec, int offset,
402                              struct ptlrpc_request *req, struct lustre_handle *lh)
403 {
404         struct mds_obd *mds = mds_req2mds(req);
405         struct obd_device *obd = req->rq_export->exp_obd;
406         struct mds_export_data *med = &req->rq_export->u.eu_mds_data;
407         struct mds_body *body;
408         struct dentry *de;
409         struct inode *inode = NULL;
410         struct lustre_handle lockh[2] = {{0}, {0}};
411         int parent_mode;
412         void *handle = NULL;
413         struct mds_logcancel_data *mlcd = NULL;
414         int rc = 0, cleanup_phase = 0, err;
415         int locked = 0;
416         ENTRY;
417
418         LASSERT(offset == 1);
419
420         DEBUG_REQ(D_INODE, req, "setattr "LPU64"/%u %x",
421                   id_ino(rec->ur_id1), id_gen(rec->ur_id1),
422                   rec->ur_iattr.ia_valid);
423
424         MDS_CHECK_RESENT(req, reconstruct_reint_setattr(rec, offset, req));
425         MD_COUNTER_INCREMENT(obd, setattr);
426
427         if (med->med_remote) {
428                 if (rec->ur_iattr.ia_valid & ATTR_GID) {
429                         CWARN("Deny chgrp from remote client\n");
430                         GOTO(cleanup, rc = -EPERM);
431                 }
432                 if (rec->ur_iattr.ia_valid & ATTR_UID) {
433                         uid_t uid;
434
435                         uid = mds_idmap_lookup_uid(med->med_idmap, 0,
436                                                    rec->ur_iattr.ia_uid);
437                         if (uid == MDS_IDMAP_NOTFOUND) {
438                                 CWARN("Deny chown to uid %u\n",
439                                       rec->ur_iattr.ia_uid);
440                                 GOTO(cleanup, rc = -EPERM);
441                         }
442                         rec->ur_iattr.ia_uid = uid;
443                 }
444         }
445
446         if (rec->ur_iattr.ia_valid & ATTR_FROM_OPEN) {
447                 de = mds_id2dentry(obd, rec->ur_id1, NULL);
448                 if (IS_ERR(de))
449                         GOTO(cleanup, rc = PTR_ERR(de));
450         } else {
451                 __u64 lockpart = MDS_INODELOCK_UPDATE;
452                 if (rec->ur_iattr.ia_valid & (ATTR_MODE | ATTR_UID | ATTR_GID))
453                         lockpart |= MDS_INODELOCK_LOOKUP;
454                 de = mds_id2locked_dentry(obd, rec->ur_id1, NULL, LCK_PW,
455                                           lockh, &parent_mode, NULL, 0, lockpart);
456                 if (IS_ERR(de))
457                         GOTO(cleanup, rc = PTR_ERR(de));
458                 locked = 1;
459         }
460
461         cleanup_phase = 1;
462
463         inode = de->d_inode;
464         LASSERT(inode);
465         if ((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode)) &&
466             rec->ur_eadata != NULL)
467                 down(&inode->i_sem);
468
469         OBD_FAIL_WRITE(OBD_FAIL_MDS_REINT_SETATTR_WRITE, inode->i_sb);
470
471         handle = fsfilt_start(obd, inode, FSFILT_OP_SETATTR, NULL);
472         if (IS_ERR(handle))
473                 GOTO(cleanup, rc = PTR_ERR(handle));
474
475         if (rec->ur_iattr.ia_valid & (ATTR_MTIME | ATTR_CTIME))
476                 CDEBUG(D_INODE, "setting mtime %lu, ctime %lu\n",
477                        LTIME_S(rec->ur_iattr.ia_mtime),
478                        LTIME_S(rec->ur_iattr.ia_ctime));
479         rc = mds_fix_attr(inode, rec);
480         if (rc)
481                 GOTO(cleanup, rc);
482
483         if (rec->ur_iattr.ia_valid & ATTR_ATTR_FLAG)    /* ioctl */
484                 rc = fsfilt_iocontrol(obd, inode, NULL, EXT3_IOC_SETFLAGS,
485                                       (long)&rec->ur_iattr.ia_attr_flags);
486         else                                            /* setattr */
487                 rc = fsfilt_setattr(obd, de, handle, &rec->ur_iattr, 0);
488
489         if (rc == 0) {
490                 if (rec->ur_iattr.ia_valid & ATTR_EA) {
491                         int flags = (int)rec->ur_iattr.ia_attr_flags;
492
493                         rc = -EOPNOTSUPP;
494                         if (inode->i_op && inode->i_op->setxattr) 
495                                 rc = inode->i_op->setxattr(de, rec->ur_eadata,
496                                        rec->ur_ea2data, rec->ur_ea2datalen,
497                                        flags);
498                 } else if (rec->ur_iattr.ia_valid & ATTR_EA_RM) {
499                         rc = -EOPNOTSUPP;
500                         if (inode->i_op && inode->i_op->removexattr) 
501                                 rc = inode->i_op->removexattr(de,
502                                                     rec->ur_eadata);
503                 } else if ((S_ISREG(inode->i_mode) ||
504                             S_ISDIR(inode->i_mode)) && rec->ur_eadata != NULL) {
505                         struct lov_stripe_md *lsm = NULL;
506                         struct lov_user_md *lum = NULL;
507                         
508                         rc = ll_permission(inode, MAY_WRITE, NULL);
509                         if (rc < 0)
510                                 GOTO(cleanup, rc);
511
512                         lum = rec->ur_eadata;
513                         /* if lmm_stripe_size is -1 delete default stripe from dir */
514                         if (S_ISDIR(inode->i_mode) &&
515                             lum->lmm_stripe_size == (typeof(lum->lmm_stripe_size))(-1)){
516                                 rc = fsfilt_set_md(obd, inode, handle, NULL, 0, EA_LOV);
517                                 if (rc)
518                                         GOTO(cleanup, rc);
519                         } else {
520                                 rc = obd_iocontrol(OBD_IOC_LOV_SETSTRIPE, mds->mds_dt_exp,
521                                                    0, &lsm, rec->ur_eadata);
522                                 if (rc)
523                                         GOTO(cleanup, rc);
524                                 
525                                 obd_free_memmd(mds->mds_dt_exp, &lsm);
526                                 rc = fsfilt_set_md(obd, inode, handle, rec->ur_eadata,
527                                                    rec->ur_eadatalen, EA_LOV);
528                                 if (rc)
529                                         GOTO(cleanup, rc);
530                         }
531                 }    
532         }
533
534         body = lustre_msg_buf(req->rq_repmsg, 0, sizeof (*body));
535         mds_pack_inode2body(obd, body, inode, 1);
536
537         /* Don't return OST-specific attributes if we didn't just set them */
538         if (rec->ur_iattr.ia_valid & ATTR_SIZE)
539                 body->valid |= OBD_MD_FLSIZE | OBD_MD_FLBLOCKS;
540         if (rec->ur_iattr.ia_valid & (ATTR_MTIME | ATTR_MTIME_SET))
541                 body->valid |= OBD_MD_FLMTIME;
542         if (rec->ur_iattr.ia_valid & (ATTR_ATIME | ATTR_ATIME_SET))
543                 body->valid |= OBD_MD_FLATIME;
544
545         mds_body_do_reverse_map(med, body);
546
547         /* The logcookie should be no use anymore, why nobody remove
548          * following code block?
549          */
550         LASSERT(rec->ur_cookielen == 0);
551         if (rc == 0 && rec->ur_cookielen && !IS_ERR(mds->mds_dt_obd)) {
552                 OBD_ALLOC(mlcd, sizeof(*mlcd) + rec->ur_cookielen +
553                           rec->ur_eadatalen);
554                 if (mlcd) {
555                         mlcd->mlcd_size = sizeof(*mlcd) + rec->ur_cookielen +
556                                 rec->ur_eadatalen;
557                         mlcd->mlcd_eadatalen = rec->ur_eadatalen;
558                         mlcd->mlcd_cookielen = rec->ur_cookielen;
559                         mlcd->mlcd_lmm = (void *)&mlcd->mlcd_cookies +
560                                 mlcd->mlcd_cookielen;
561                         memcpy(&mlcd->mlcd_cookies, rec->ur_logcookies,
562                                mlcd->mlcd_cookielen);
563                         memcpy(mlcd->mlcd_lmm, rec->ur_eadata,
564                                mlcd->mlcd_eadatalen);
565                 } else {
566                         CERROR("unable to allocate log cancel data\n");
567                 }
568         }
569         EXIT;
570  cleanup:
571         if (mlcd != NULL)
572                 fsfilt_add_journal_cb(req->rq_export->exp_obd, mds->mds_sb, 0,
573                                       handle, mds_cancel_cookies_cb, mlcd);
574         err = mds_finish_transno(mds, inode, handle, req, rc, 0);
575         switch (cleanup_phase) {
576         case 1:
577                 if ((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode)) &&
578                     rec->ur_eadata != NULL)
579                         up(&inode->i_sem);
580                 l_dput(de);
581                 if (locked) {
582 #ifdef S_PDIROPS
583                         if (lockh[1].cookie != 0)
584                                 ldlm_lock_decref(lockh + 1, parent_mode);
585 #endif
586                         if (rc) {
587                                 ldlm_lock_decref(lockh, LCK_PW);
588                         } else {
589                                 ptlrpc_save_lock (req, lockh, LCK_PW);
590                         }
591                 }
592         case 0:
593                 break;
594         default:
595                 LBUG();
596         }
597         if (err && !rc)
598                 rc = err;
599
600         req->rq_status = rc;
601         return 0;
602 }
603
604 static void reconstruct_reint_create(struct mds_update_record *rec, int offset,
605                                      struct ptlrpc_request *req)
606 {
607         struct mds_export_data *med = &req->rq_export->exp_mds_data;
608         struct dentry *parent, *child;
609         struct mds_body *body;
610         ENTRY;
611
612         mds_req_from_mcd(req, med->med_mcd);
613
614         if (req->rq_status) {
615                 EXIT;
616                 return;
617         }
618
619         parent = mds_id2dentry(req2obd(req), rec->ur_id1, NULL);
620         LASSERT(!IS_ERR(parent));
621         child = ll_lookup_one_len(rec->ur_name, parent,
622                                   rec->ur_namelen - 1);
623         LASSERT(!IS_ERR(child));
624         if ((child->d_flags & DCACHE_CROSS_REF)) {
625                 LASSERTF(child->d_inode == NULL, "BUG 3869\n");
626                 body = lustre_msg_buf(req->rq_repmsg, 0, sizeof(*body));
627                 mds_pack_dentry2body(req2obd(req), body, child, 1);
628         } else if (child->d_inode == NULL) {
629                 DEBUG_REQ(D_ERROR, req, "parent "DLID4" name %s mode %o",
630                           OLID4(rec->ur_id1), rec->ur_name, rec->ur_mode);
631                 LASSERTF(child->d_inode != NULL, "BUG 3869\n");
632         } else {
633                 body = lustre_msg_buf(req->rq_repmsg, 0, sizeof(*body));
634                 mds_pack_inode2body(req2obd(req), body, child->d_inode, 1);
635         }
636         l_dput(parent);
637         l_dput(child);
638         EXIT;
639 }
640
641 static int mds_reint_create(struct mds_update_record *rec, int offset,
642                             struct ptlrpc_request *req,
643                             struct lustre_handle *lh)
644 {
645         struct dentry *dparent = NULL;
646         struct mds_obd *mds = mds_req2mds(req);
647         struct obd_device *obd = req->rq_export->exp_obd;
648         struct dentry *dchild = NULL;
649         struct inode *dir = NULL;
650         void *handle = NULL;
651         struct lustre_handle lockh[2] = {{0}, {0}};
652         int parent_mode;
653         int rc = 0, err, type = rec->ur_mode & S_IFMT, cleanup_phase = 0;
654         int created = 0;
655         struct dentry_params dp;
656         struct mea *mea = NULL;
657         int mea_size;
658         ENTRY;
659
660         LASSERT(offset == 1);
661         
662         LASSERT(!strcmp(req->rq_export->exp_obd->obd_type->typ_name,
663                         LUSTRE_MDS_NAME));
664
665         DEBUG_REQ(D_INODE, req, "parent "LPU64"/%u name %s mode %o",
666                   id_ino(rec->ur_id1), id_gen(rec->ur_id1),
667                   rec->ur_name, rec->ur_mode);
668
669         MDS_CHECK_RESENT(req, reconstruct_reint_create(rec, offset, req));
670
671         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_REINT_CREATE))
672                 GOTO(cleanup, rc = -ESTALE);
673
674         dparent = mds_id2locked_dentry(obd, rec->ur_id1, NULL, LCK_PW,
675                                        lockh, &parent_mode, rec->ur_name,
676                                        rec->ur_namelen - 1, MDS_INODELOCK_UPDATE);
677         if (IS_ERR(dparent)) {
678                 rc = PTR_ERR(dparent);
679                 CERROR("parent lookup error %d\n", rc);
680                 GOTO(cleanup, rc);
681         }
682         cleanup_phase = 1; /* locked parent dentry */
683         dir = dparent->d_inode;
684         LASSERT(dir);
685
686         ldlm_lock_dump_handle(D_OTHER, lockh);
687
688         /* try to retrieve MEA data for this dir */
689         rc = mds_md_get_attr(obd, dparent->d_inode, &mea, &mea_size);
690         if (rc)
691                 GOTO(cleanup, rc);
692
693         if (mea != NULL) {
694                 /*
695                  * dir is already splitted, check is requested filename should
696                  * live at this MDS or at another one.
697                  */
698                 int i = mea_name2idx(mea, rec->ur_name, rec->ur_namelen - 1);
699                 if (mea->mea_master != id_group(&mea->mea_ids[i])) {
700                         CDEBUG(D_OTHER, "inapropriate MDS(%d) for %lu/%u:%s."
701                                " should be %lu(%d)\n",
702                                mea->mea_master, dparent->d_inode->i_ino,
703                                dparent->d_inode->i_generation, rec->ur_name,
704                                (unsigned long)id_group(&mea->mea_ids[i]), i);
705                         GOTO(cleanup, rc = -ERESTART);
706                 }
707         }
708
709         dchild = ll_lookup_one_len(rec->ur_name, dparent, 
710                                    rec->ur_namelen - 1);
711         if (IS_ERR(dchild)) {
712                 rc = PTR_ERR(dchild);
713                 CERROR("Can't find "DLID4"/%s, error %d\n",
714                        OLID4(rec->ur_id1), rec->ur_name, rc);
715                 GOTO(cleanup, rc);
716         }
717
718         cleanup_phase = 2; /* child dentry */
719
720         OBD_FAIL_WRITE(OBD_FAIL_MDS_REINT_CREATE_WRITE, dir->i_sb);
721
722         if (type == S_IFREG || type == S_IFDIR) {
723                 rc = mds_try_to_split_dir(obd, dparent, &mea, 0, parent_mode);
724                 CDEBUG(D_OTHER, "%s: splitted %lu/%u - %d/%d\n",
725                        obd->obd_name, dparent->d_inode->i_ino,
726                        dparent->d_inode->i_generation, rc, parent_mode);
727                 if (rc > 0) {
728                         /* dir got splitted */
729                         GOTO(cleanup, rc = -ERESTART);
730                 } else if (rc < 0) {
731                         /* error happened during spitting. */
732                         GOTO(cleanup, rc);
733                 }
734         }
735
736         if (dir->i_mode & S_ISGID) {
737                 if (S_ISDIR(rec->ur_mode))
738                         rec->ur_mode |= S_ISGID;
739         }
740
741         /*
742          * here inode number should be used only in the case of replaying. It is
743          * needed to check if object already created in the case of creating
744          * remote inode.
745          */
746         dchild->d_fsdata = (void *)&dp;
747         dp.p_inum = (unsigned long)id_ino(rec->ur_id2);
748         dp.p_ptr = req;
749
750         switch (type) {
751         case S_IFREG: {
752                 handle = fsfilt_start(obd, dir, FSFILT_OP_CREATE, NULL);
753                 if (IS_ERR(handle))
754                         GOTO(cleanup, rc = PTR_ERR(handle));
755                 rc = ll_vfs_create(dir, dchild, rec->ur_mode, NULL);
756                 EXIT;
757                 break;
758         }
759         case S_IFDIR: {
760                 int i, nstripes = 0;
761                 
762                 /*
763                  * as Peter asked, mkdir() should distribute new directories
764                  * over the whole cluster in order to distribute namespace
765                  * processing load. first, we calculate which MDS to use to put
766                  * new directory's inode in.
767                  */
768                 i = mds_choose_mdsnum(obd, rec->ur_name, rec->ur_namelen - 1, 
769                                       rec->ur_flags);
770                 if (i == mds->mds_num) {
771                         /* inode will be created locally */
772                         handle = fsfilt_start(obd, dir, FSFILT_OP_MKDIR, NULL);
773                         if (IS_ERR(handle))
774                                 GOTO(cleanup, rc = PTR_ERR(handle));
775
776                         rc = vfs_mkdir(dir, dchild, rec->ur_mode);
777                         if (rc) {
778                                 CERROR("Can't create dir \"%s\", rc = %d\n",
779                                        dchild->d_name.name, rc);
780                                 GOTO(cleanup, rc);
781                         }
782
783                         down(&dchild->d_inode->i_sem);
784                         if (dp.p_inum) {
785                                 rc = mds_update_inode_sid(obd, dchild->d_inode,
786                                                           handle, rec->ur_id2);
787                                 if (rc) {
788                                         CERROR("mds_update_inode_sid() failed, inode %lu, "
789                                                "rc %d\n", dchild->d_inode->i_ino, rc);
790                                 }
791
792                                 /* 
793                                  * make sure, that fid is up-to-date.
794                                  */
795                                 mds_set_last_fid(obd, id_fid(rec->ur_id2));
796                         } else {
797                                 rc = mds_alloc_inode_sid(obd, dchild->d_inode,
798                                                          handle, NULL);
799                                 if (rc) {
800                                         CERROR("mds_alloc_inode_sid() failed, inode %lu, "
801                                                "rc %d\n", dchild->d_inode->i_ino, rc);
802                                 }
803                         }
804                         up(&dchild->d_inode->i_sem);
805                         
806                         if (rc)
807                                 GOTO(cleanup, rc);
808                         
809                         if (rec->ur_eadata)
810                                 nstripes = *(u16 *)rec->ur_eadata;
811
812                         if (rc == 0 && nstripes) {
813                                 /*
814                                  * we pass LCK_EX to split routine to signal,
815                                  * that we have exclusive access to the
816                                  * directory. Simple because nobody knows it
817                                  * already exists -bzzz
818                                  */
819                                 rc = mds_try_to_split_dir(obd, dchild,
820                                                           NULL, nstripes,
821                                                           LCK_EX);
822                                 if (rc > 0) {
823                                         /* dir got splitted */
824                                         rc = 0;
825                                 } else if (rc < 0) {
826                                         /* an error occured during
827                                          * splitting. */
828                                         GOTO(cleanup, rc);
829                                 }
830                         }
831                 } else if (!DENTRY_VALID(dchild)) {
832                         /* inode will be created on another MDS */
833                         struct obdo *oa = NULL;
834                         struct mds_body *body;
835                         
836                         /* first, create that inode */
837                         oa = obdo_alloc();
838                         if (!oa)
839                                 GOTO(cleanup, rc = -ENOMEM);
840
841                         oa->o_mds = i;
842                         oa->o_easize = 0;
843
844                         if (rec->ur_eadata) {
845                                 /* user asks for creating splitted dir */
846                                 oa->o_easize = *((u16 *) rec->ur_eadata);
847                         }
848
849                         obdo_from_inode(oa, dir, OBD_MD_FLATIME |
850                                         OBD_MD_FLMTIME | OBD_MD_FLCTIME);
851
852                         /* adjust the uid/gid/mode bits */
853                         oa->o_mode = rec->ur_mode;
854                         oa->o_uid = current->fsuid;
855                         oa->o_gid = (dir->i_mode & S_ISGID) ?
856                                                 dir->i_gid : current->fsgid;
857                         oa->o_valid |= OBD_MD_FLTYPE|OBD_MD_FLUID|OBD_MD_FLGID;
858
859                         CDEBUG(D_OTHER, "%s: create dir on MDS %u\n",
860                                obd->obd_name, i);
861
862                         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY) {
863                                 /*
864                                  * here inode number and generation are
865                                  * important, as this is replay request and we
866                                  * need them to check if such an object is
867                                  * already created.
868                                  */
869                                 CDEBUG(D_HA, "%s: replay dir creation %*s -> %u/%u\n",
870                                        obd->obd_name, rec->ur_namelen - 1,
871                                        rec->ur_name, (unsigned)id_ino(rec->ur_id2),
872                                        (unsigned)id_gen(rec->ur_id2));
873                                 oa->o_id = id_ino(rec->ur_id2);
874                                 oa->o_fid = id_fid(rec->ur_id2);
875                                 oa->o_generation = id_gen(rec->ur_id2);
876                                 oa->o_flags |= OBD_FL_RECREATE_OBJS;
877                                 LASSERT(oa->o_fid != 0);
878                         }
879
880                         /* 
881                          * before obd_create() is called, o_fid is not known if
882                          * this is not recovery of cause.
883                          */
884                         rc = obd_create(mds->mds_md_exp, oa, NULL, NULL);
885                         if (rc) {
886                                 CERROR("can't create remote inode: %d\n", rc);
887                                 DEBUG_REQ(D_ERROR, req, "parent "LPU64"/%u name %s mode %o",
888                                           id_ino(rec->ur_id1), id_gen(rec->ur_id1),
889                                           rec->ur_name, rec->ur_mode);
890                                 obdo_free(oa);
891                                 GOTO(cleanup, rc);
892                         }
893
894                         LASSERT(oa->o_fid != 0);
895                         
896                         /* now, add new dir entry for it */
897                         handle = fsfilt_start(obd, dir, FSFILT_OP_MKDIR, NULL);
898                         if (IS_ERR(handle)) {
899                                 obdo_free(oa);
900                                 GOTO(cleanup, rc = PTR_ERR(handle));
901                         }
902
903                         /* creating local dentry for remote inode. */
904                         rc = fsfilt_add_dir_entry(obd, dparent, rec->ur_name,
905                                                   rec->ur_namelen - 1, oa->o_id,
906                                                   oa->o_generation, i, oa->o_fid);
907
908                         if (rc) {
909                                 CERROR("Can't create local entry %*s for "
910                                        "remote inode.\n", rec->ur_namelen - 1,
911                                         rec->ur_name);
912                                 GOTO(cleanup, rc);
913                         }
914
915                         /* fill reply */
916                         body = lustre_msg_buf(req->rq_repmsg,
917                                               0, sizeof(*body));
918                         body->valid |= OBD_MD_FLID | OBD_MD_MDS | OBD_MD_FID;
919
920                         obdo2id(&body->id1, oa);
921                         obdo_free(oa);
922                 } else {
923                         /* requested name exists in the directory */
924                         rc = -EEXIST;
925                 }
926                 EXIT;
927                 break;
928         }
929         case S_IFLNK:{
930                 handle = fsfilt_start(obd, dir, FSFILT_OP_SYMLINK, NULL);
931                 if (IS_ERR(handle))
932                         GOTO(cleanup, rc = PTR_ERR(handle));
933                 if (rec->ur_tgt == NULL)        /* no target supplied */
934                         rc = -EINVAL;           /* -EPROTO? */
935                 else
936                         rc = ll_vfs_symlink(dir, dchild, rec->ur_tgt, S_IALLUGO);
937                 EXIT;
938                 break;
939         }
940         case S_IFCHR:
941         case S_IFBLK:
942         case S_IFIFO:
943         case S_IFSOCK:{
944                 int rdev = rec->ur_rdev;
945                 handle = fsfilt_start(obd, dir, FSFILT_OP_MKNOD, NULL);
946                 if (IS_ERR(handle))
947                         GOTO(cleanup, (handle = NULL, rc = PTR_ERR(handle)));
948                 rc = vfs_mknod(dir, dchild, rec->ur_mode, rdev);
949                 EXIT;
950                 break;
951         }
952         default:
953                 CERROR("bad file type %o creating %s\n", type, rec->ur_name);
954                 dchild->d_fsdata = NULL;
955                 GOTO(cleanup, rc = -EINVAL);
956         }
957
958         /* In case we stored the desired inum in here, we want to clean up. */
959         if (dchild->d_fsdata == (void *)(unsigned long)id_ino(rec->ur_id2))
960                 dchild->d_fsdata = NULL;
961
962         if (rc) {
963                 CDEBUG(D_INODE, "error during create: %d\n", rc);
964                 GOTO(cleanup, rc);
965         } else if (dchild->d_inode) {
966                 struct mds_export_data *med = &req->rq_export->u.eu_mds_data;
967                 struct iattr iattr;
968                 struct mds_body *body;
969                 struct inode *inode = dchild->d_inode;
970
971                 created = 1;
972                 iattr.ia_uid = rec->ur_fsuid;
973                 LTIME_S(iattr.ia_atime) = rec->ur_time;
974                 LTIME_S(iattr.ia_ctime) = rec->ur_time;
975                 LTIME_S(iattr.ia_mtime) = rec->ur_time;
976
977                 if (dir->i_mode & S_ISGID)
978                         iattr.ia_gid = dir->i_gid;
979                 else
980                         iattr.ia_gid = rec->ur_fsgid;
981
982                 iattr.ia_valid = ATTR_UID | ATTR_GID | ATTR_ATIME |
983                         ATTR_MTIME | ATTR_CTIME;
984
985                 if (id_ino(rec->ur_id2)) {
986                         LASSERT(id_ino(rec->ur_id2) == inode->i_ino);
987                         inode->i_generation = id_gen(rec->ur_id2);
988
989                         if (type != S_IFDIR) {
990                                 down(&inode->i_sem);
991                                 rc = mds_update_inode_sid(obd, inode,
992                                                           handle, rec->ur_id2);
993                                 up(&inode->i_sem);
994                                 if (rc) {
995                                         CERROR("Can't update inode self id, "
996                                                "rc = %d.\n", rc);
997                                 }
998
999                                 /* 
1000                                  * make sure, that fid is up-to-date.
1001                                  */
1002                                 mds_set_last_fid(obd, id_fid(rec->ur_id2));
1003                         }
1004                         
1005                         /* dirtied and committed by the upcoming setattr. */
1006                         CDEBUG(D_INODE, "recreated ino %lu with gen %u\n",
1007                                inode->i_ino, inode->i_generation);
1008                 } else {
1009                         struct lustre_handle child_ino_lockh;
1010
1011                         CDEBUG(D_INODE, "created ino %lu with gen %x\n",
1012                                inode->i_ino, inode->i_generation);
1013
1014                         if (type != S_IFDIR) {
1015                                 /* 
1016                                  * allocate new id for @inode if it is not dir,
1017                                  * because for dir it was already done.
1018                                  */
1019                                 down(&inode->i_sem);
1020                                 rc = mds_alloc_inode_sid(obd, inode,
1021                                                          handle, NULL);
1022                                 up(&inode->i_sem);
1023                                 if (rc) {
1024                                         CERROR("mds_alloc_inode_sid() failed, "
1025                                                "inode %lu, rc %d\n", inode->i_ino,
1026                                                rc);
1027                                 }
1028                         }
1029
1030                         if (rc == 0) {
1031                                 /*
1032                                  * the inode we were allocated may have just
1033                                  * been freed by an unlink operation.  We take
1034                                  * this lock to synchronize against the matching
1035                                  * reply-ack-lock taken in unlink, to avoid
1036                                  * replay problems if this reply makes it out to
1037                                  * the client but the unlink's does not.  See
1038                                  * bug 2029 for more detail.
1039                                  */
1040                                 rc = mds_lock_new_child(obd, inode, &child_ino_lockh);
1041                                 if (rc != ELDLM_OK) {
1042                                         CERROR("error locking for unlink/create sync: "
1043                                                "%d\n", rc);
1044                                 } else {
1045                                         ldlm_lock_decref(&child_ino_lockh, LCK_EX);
1046                                 }
1047                         }
1048                 }
1049
1050                 rc = fsfilt_setattr(obd, dchild, handle, &iattr, 0);
1051                 if (rc)
1052                         CERROR("error on child setattr: rc = %d\n", rc);
1053
1054                 iattr.ia_valid = ATTR_MTIME | ATTR_CTIME;
1055                 rc = fsfilt_setattr(obd, dparent, handle, &iattr, 0);
1056                 if (rc)
1057                         CERROR("error on parent setattr: rc = %d\n", rc);
1058                 else
1059                         MD_COUNTER_INCREMENT(obd, create);
1060
1061                 /* take care of default stripe inheritance */
1062                 if (type == S_IFDIR) {
1063                         struct lov_mds_md lmm;
1064                         int lmm_size = sizeof(lmm);
1065
1066                         rc = mds_get_md(obd, dir, &lmm, &lmm_size, 1, 0);
1067                         if (rc > 0) {
1068                                 down(&inode->i_sem);
1069                                 rc = fsfilt_set_md(obd, inode, handle, 
1070                                                    &lmm, lmm_size, EA_LOV);
1071                                 up(&inode->i_sem);
1072                         }
1073                         if (rc) {
1074                                 CERROR("error on copy stripe info: rc = %d\n", 
1075                                        rc);
1076                                 rc = 0;
1077                         }
1078                 }
1079                 
1080                 body = lustre_msg_buf(req->rq_repmsg, 0, sizeof(*body));
1081                 mds_pack_inode2body(obd, body, inode, 1);
1082                 mds_body_do_reverse_map(med, body);
1083         }
1084
1085         EXIT;
1086 cleanup:
1087         err = mds_finish_transno(mds, dir, handle, req, rc, 0);
1088
1089         if (rc && created) {
1090                 /* Destroy the file we just created. This should not need extra
1091                  * journal credits, as we have already modified all of the
1092                  * blocks needed in order to create the file in the first
1093                  * place. */
1094                 switch (type) {
1095                 case S_IFDIR:
1096                         err = vfs_rmdir(dir, dchild);
1097                         if (err)
1098                                 CERROR("rmdir in error path: %d\n", err);
1099                         break;
1100                 default:
1101                         err = vfs_unlink(dir, dchild);
1102                         if (err)
1103                                 CERROR("unlink in error path: %d\n", err);
1104                         break;
1105                 }
1106         } else {
1107                 rc = err;
1108         }
1109         switch (cleanup_phase) {
1110         case 2: /* child dentry */
1111                 l_dput(dchild);
1112         case 1: /* locked parent dentry */
1113 #ifdef S_PDIROPS
1114                 if (lockh[1].cookie != 0)
1115                         ldlm_lock_decref(lockh + 1, parent_mode);
1116 #endif
1117                 if (rc) {
1118                         ldlm_lock_decref(lockh, LCK_PW);
1119                 } else {
1120                         ptlrpc_save_lock(req, lockh, LCK_PW);
1121                 }
1122                 l_dput(dparent);
1123         case 0:
1124                 break;
1125         default:
1126                 CERROR("invalid cleanup_phase %d\n", cleanup_phase);
1127                 LBUG();
1128         }
1129         if (mea)
1130                 OBD_FREE(mea, mea_size);
1131         req->rq_status = rc;
1132         return 0;
1133 }
1134
1135 static inline int
1136 res_gt(struct ldlm_res_id *res1, struct ldlm_res_id *res2,
1137        ldlm_policy_data_t *p1, ldlm_policy_data_t *p2)
1138 {
1139         int i;
1140
1141         for (i = 0; i < RES_NAME_SIZE; i++) {
1142                 /* 
1143                  * this is needed to make zeroed res_id entries to be put at the
1144                  * end of list in *ordered_locks() .
1145                  */
1146                 if (res1->name[i] == 0 && res2->name[i] != 0)
1147                         return 1;
1148                 if (res2->name[i] == 0 && res1->name[i] != 0)
1149                         return 0;
1150                 if (res1->name[i] > res2->name[i])
1151                         return 1;
1152                 if (res1->name[i] < res2->name[i])
1153                         return 0;
1154         }
1155
1156         if (!p1 || !p2)
1157                 return 0;
1158
1159         if (memcmp(p1, p2, sizeof(*p1)) < 0)
1160                 return 1;
1161
1162         return 0;
1163 }
1164
1165 /* This function doesn't use ldlm_match_or_enqueue because we're always called
1166  * with EX or PW locks, and the MDS is no longer allowed to match write locks,
1167  * because they take the place of local semaphores.
1168  *
1169  * One or two locks are taken in numerical order.  A res_id->name[0] of 0 means
1170  * no lock is taken for that res_id.  Must be at least one non-zero res_id. */
1171 int enqueue_ordered_locks(struct obd_device *obd, struct ldlm_res_id *p1_res_id,
1172                           struct lustre_handle *p1_lockh, int p1_lock_mode,
1173                           ldlm_policy_data_t *p1_policy,
1174                           struct ldlm_res_id *p2_res_id,
1175                           struct lustre_handle *p2_lockh, int p2_lock_mode,
1176                           ldlm_policy_data_t *p2_policy)
1177 {
1178         int lock_modes[2] = { p1_lock_mode, p2_lock_mode };
1179         struct ldlm_res_id *res_id[2] = { p1_res_id, p2_res_id };
1180         struct lustre_handle *handles[2] = { p1_lockh, p2_lockh };
1181         ldlm_policy_data_t *policies[2] = { p1_policy, p2_policy };
1182         int rc, flags;
1183         ENTRY;
1184
1185         LASSERT(p1_res_id != NULL && p2_res_id != NULL);
1186
1187         CDEBUG(D_INFO, "locks before: "LPU64"/"LPU64"\n",
1188                res_id[0]->name[0], res_id[1]->name[0]);
1189
1190         if (res_gt(p1_res_id, p2_res_id, p1_policy, p2_policy)) {
1191                 handles[1] = p1_lockh;
1192                 handles[0] = p2_lockh;
1193                 res_id[1] = p1_res_id;
1194                 res_id[0] = p2_res_id;
1195                 lock_modes[1] = p1_lock_mode;
1196                 lock_modes[0] = p2_lock_mode;
1197                 policies[1] = p1_policy;
1198                 policies[0] = p2_policy;
1199         }
1200
1201         CDEBUG(D_DLMTRACE, "lock order: "LPU64"/"LPU64"\n",
1202                res_id[0]->name[0], res_id[1]->name[0]);
1203
1204         flags = LDLM_FL_LOCAL_ONLY;
1205         rc = ldlm_cli_enqueue(NULL, NULL, obd->obd_namespace, *res_id[0],
1206                               LDLM_IBITS, policies[0], lock_modes[0], &flags,
1207                               mds_blocking_ast, ldlm_completion_ast, NULL, NULL,
1208                               NULL, 0, NULL, handles[0]);
1209         if (rc != ELDLM_OK)
1210                 RETURN(-EIO);
1211         ldlm_lock_dump_handle(D_OTHER, handles[0]);
1212
1213         if (!memcmp(res_id[0], res_id[1], sizeof(*res_id[0])) &&
1214             (policies[0]->l_inodebits.bits & policies[1]->l_inodebits.bits)) {
1215                 memcpy(handles[1], handles[0], sizeof(*(handles[1])));
1216                 ldlm_lock_addref(handles[1], lock_modes[1]);
1217         } else if (res_id[1]->name[0] != 0) {
1218                 flags = LDLM_FL_LOCAL_ONLY;
1219                 rc = ldlm_cli_enqueue(NULL, NULL, obd->obd_namespace,
1220                                       *res_id[1], LDLM_IBITS, policies[1],
1221                                       lock_modes[1], &flags, mds_blocking_ast,
1222                                       ldlm_completion_ast, NULL, NULL, NULL, 0,
1223                                       NULL, handles[1]);
1224                 if (rc != ELDLM_OK) {
1225                         ldlm_lock_decref(handles[0], lock_modes[0]);
1226                         RETURN(-EIO);
1227                 }
1228                 ldlm_lock_dump_handle(D_OTHER, handles[1]);
1229         }
1230
1231         RETURN(0);
1232 }
1233
1234 int enqueue_4ordered_locks(struct obd_device *obd,struct ldlm_res_id *p1_res_id,
1235                            struct lustre_handle *p1_lockh, int p1_lock_mode,
1236                            ldlm_policy_data_t *p1_policy,
1237                            struct ldlm_res_id *p2_res_id,
1238                            struct lustre_handle *p2_lockh, int p2_lock_mode,
1239                            ldlm_policy_data_t *p2_policy,
1240                            struct ldlm_res_id *c1_res_id,
1241                            struct lustre_handle *c1_lockh, int c1_lock_mode,
1242                            ldlm_policy_data_t *c1_policy,
1243                            struct ldlm_res_id *c2_res_id,
1244                            struct lustre_handle *c2_lockh, int c2_lock_mode,
1245                            ldlm_policy_data_t *c2_policy)
1246 {
1247         struct ldlm_res_id *res_id[5] = { p1_res_id, p2_res_id,
1248                                           c1_res_id, c2_res_id };
1249         struct lustre_handle *dlm_handles[5] = { p1_lockh, p2_lockh,
1250                                                  c1_lockh, c2_lockh };
1251         int lock_modes[5] = { p1_lock_mode, p2_lock_mode,
1252                               c1_lock_mode, c2_lock_mode };
1253         ldlm_policy_data_t *policies[5] = { p1_policy, p2_policy,
1254                                             c1_policy, c2_policy};
1255         int rc, i, j, sorted, flags;
1256         ENTRY;
1257
1258         CDEBUG(D_DLMTRACE, "locks before: "LPU64"/"LPU64"/"LPU64"/"LPU64"\n",
1259                res_id[0]->name[0], res_id[1]->name[0], res_id[2]->name[0],
1260                res_id[3]->name[0]);
1261
1262         /* 
1263          * simple insertion sort - we have at most 4 elements. Note, that zeroed
1264          * res_id should be at the end of list after sorting is finished.
1265          */
1266         for (i = 1; i < 4; i++) {
1267                 j = i - 1;
1268                 dlm_handles[4] = dlm_handles[i];
1269                 res_id[4] = res_id[i];
1270                 lock_modes[4] = lock_modes[i];
1271                 policies[4] = policies[i];
1272
1273                 sorted = 0;
1274                 do {
1275                         if (res_gt(res_id[j], res_id[4], policies[j],
1276                                    policies[4])) {
1277                                 dlm_handles[j + 1] = dlm_handles[j];
1278                                 res_id[j + 1] = res_id[j];
1279                                 lock_modes[j + 1] = lock_modes[j];
1280                                 policies[j + 1] = policies[j];
1281                                 j--;
1282                         } else {
1283                                 sorted = 1;
1284                         }
1285                 } while (j >= 0 && !sorted);
1286
1287                 dlm_handles[j + 1] = dlm_handles[4];
1288                 res_id[j + 1] = res_id[4];
1289                 lock_modes[j + 1] = lock_modes[4];
1290                 policies[j + 1] = policies[4];
1291         }
1292
1293         CDEBUG(D_DLMTRACE, "lock order: "LPU64"/"LPU64"/"LPU64"/"LPU64"\n",
1294                res_id[0]->name[0], res_id[1]->name[0], res_id[2]->name[0],
1295                res_id[3]->name[0]);
1296
1297         /* XXX we could send ASTs on all these locks first before blocking? */
1298         for (i = 0; i < 4; i++) {
1299                 flags = 0;
1300
1301                 /* 
1302                  * nevertheless zeroed res_ids should be at the end of list, and
1303                  * could use break here, I think, that it is more correctly for
1304                  * clear understanding of code to have continue here, as it
1305                  * clearly means, that zeroed res_id should be skipped and does
1306                  * not mean, that if we meet zeroed res_id we should stop
1307                  * locking loop.
1308                  */
1309                 if (res_id[i]->name[0] == 0)
1310                         continue;
1311                 
1312                 if (i != 0 &&
1313                     !memcmp(res_id[i], res_id[i-1], sizeof(*res_id[i])) &&
1314                     (policies[i]->l_inodebits.bits &
1315                      policies[i-1]->l_inodebits.bits) ) {
1316                         memcpy(dlm_handles[i], dlm_handles[i-1],
1317                                sizeof(*(dlm_handles[i])));
1318                         ldlm_lock_addref(dlm_handles[i], lock_modes[i]);
1319                 } else {
1320                         rc = ldlm_cli_enqueue(NULL, NULL, obd->obd_namespace,
1321                                               *res_id[i], LDLM_IBITS,
1322                                               policies[i],
1323                                               lock_modes[i], &flags,
1324                                               mds_blocking_ast,
1325                                               ldlm_completion_ast, NULL, NULL,
1326                                               NULL, 0, NULL, dlm_handles[i]);
1327                         if (rc != ELDLM_OK)
1328                                 GOTO(out_err, rc = -EIO);
1329                         ldlm_lock_dump_handle(D_OTHER, dlm_handles[i]);
1330                 }
1331         }
1332
1333         RETURN(0);
1334 out_err:
1335         while (i-- > 0)
1336                 ldlm_lock_decref(dlm_handles[i], lock_modes[i]);
1337
1338         return rc;
1339 }
1340
1341 /* In the unlikely case that the child changed while we were waiting
1342  * on the lock, we need to drop the lock on the old child and either:
1343  * - if the child has a lower resource name, then we have to also
1344  *   drop the parent lock and regain the locks in the right order
1345  * - in the rename case, if the child has a lower resource name than one of
1346  *   the other parent/child resources (maxres) we also need to reget the locks
1347  * - if the child has a higher resource name (this is the common case)
1348  *   we can just get the lock on the new child (still in lock order)
1349  *
1350  * Returns 0 if the child did not change or if it changed but could be locked.
1351  * Returns 1 if the child changed and we need to re-lock (no locks held).
1352  * Returns -ve error with a valid dchild (no locks held). */
1353 static int mds_verify_child(struct obd_device *obd,
1354                             struct ldlm_res_id *parent_res_id,
1355                             struct lustre_handle *parent_lockh,
1356                             struct dentry *dparent, int parent_mode,
1357                             struct ldlm_res_id *child_res_id,
1358                             struct lustre_handle *child_lockh,
1359                             struct dentry **dchildp, int child_mode,
1360                             ldlm_policy_data_t *child_policy,
1361                             const char *name, int namelen,
1362                             struct ldlm_res_id *maxres,
1363                             unsigned long child_ino, __u32 child_gen)
1364 {
1365         struct lustre_id sid;
1366         struct dentry *vchild, *dchild = *dchildp;
1367         int rc = 0, cleanup_phase = 2; /* parent, child locks */
1368         ENTRY;
1369
1370         vchild = ll_lookup_one_len(name, dparent, namelen - 1);
1371         if (IS_ERR(vchild))
1372                 GOTO(cleanup, rc = PTR_ERR(vchild));
1373
1374         if ((vchild->d_flags & DCACHE_CROSS_REF)) {
1375                 if (child_gen == vchild->d_generation &&
1376                     child_ino == vchild->d_inum) {
1377                         if (dchild)
1378                                 l_dput(dchild);
1379                         *dchildp = vchild;
1380                         RETURN(0);
1381                 }
1382                 goto changed;
1383         }
1384
1385         if (likely((vchild->d_inode == NULL && child_res_id->name[0] == 0) ||
1386                    (vchild->d_inode != NULL &&
1387                     child_gen == vchild->d_inode->i_generation &&
1388                     child_ino == vchild->d_inode->i_ino))) {
1389                 if (dchild)
1390                         l_dput(dchild);
1391                 *dchildp = vchild;
1392                 RETURN(0);
1393         }
1394
1395 changed:
1396         CDEBUG(D_DLMTRACE, "child inode changed: %p != %p (%lu != "LPU64")\n",
1397                vchild->d_inode, dchild ? dchild->d_inode : 0,
1398                vchild->d_inode ? vchild->d_inode->i_ino : 0,
1399                child_res_id->name[0]);
1400
1401         if (child_res_id->name[0] != 0)
1402                 ldlm_lock_decref(child_lockh, child_mode);
1403         if (dchild)
1404                 l_dput(dchild);
1405
1406         cleanup_phase = 1; /* parent lock only */
1407         *dchildp = dchild = vchild;
1408
1409         if (dchild->d_inode || (dchild->d_flags & DCACHE_CROSS_REF)) {
1410                 int flags = 0;
1411                 
1412                 if (dchild->d_inode) {
1413                         down(&dchild->d_inode->i_sem);
1414                         rc = mds_read_inode_sid(obd, dchild->d_inode, &sid);
1415                         up(&dchild->d_inode->i_sem);
1416                         if (rc) {
1417                                 CERROR("Can't read inode self id, inode %lu,"
1418                                        " rc %d\n",  dchild->d_inode->i_ino, rc);
1419                                 GOTO(cleanup, rc);
1420                         }
1421                         child_res_id->name[0] = id_fid(&sid);
1422                         child_res_id->name[1] = id_group(&sid);
1423                 } else {
1424                         child_res_id->name[0] = dchild->d_fid;
1425                         child_res_id->name[1] = dchild->d_mdsnum;
1426                 }
1427
1428                 if (res_gt(parent_res_id, child_res_id, NULL, NULL) ||
1429                     res_gt(maxres, child_res_id, NULL, NULL)) {
1430                         CDEBUG(D_DLMTRACE, "relock "LPU64"<("LPU64"|"LPU64")\n",
1431                                child_res_id->name[0], parent_res_id->name[0],
1432                                maxres->name[0]);
1433                         GOTO(cleanup, rc = 1);
1434                 }
1435
1436                 rc = ldlm_cli_enqueue(NULL, NULL, obd->obd_namespace,
1437                                       *child_res_id, LDLM_IBITS, child_policy,
1438                                       child_mode, &flags, mds_blocking_ast,
1439                                       ldlm_completion_ast, NULL, NULL, NULL, 0,
1440                                       NULL, child_lockh);
1441                 if (rc != ELDLM_OK)
1442                         GOTO(cleanup, rc = -EIO);
1443
1444         } else {
1445                 memset(child_res_id, 0, sizeof(*child_res_id));
1446         }
1447
1448         EXIT;
1449 cleanup:
1450         if (rc) {
1451                 switch(cleanup_phase) {
1452                 case 2:
1453                         if (child_res_id->name[0] != 0)
1454                                 ldlm_lock_decref(child_lockh, child_mode);
1455                 case 1:
1456                         ldlm_lock_decref(parent_lockh, parent_mode);
1457                 }
1458         }
1459         return rc;
1460 }
1461
1462 int mds_get_parent_child_locked(struct obd_device *obd, struct mds_obd *mds,
1463                                 struct lustre_id *id,
1464                                 struct lustre_handle *parent_lockh,
1465                                 struct dentry **dparentp, int parent_mode,
1466                                 __u64 parent_lockpart, int *update_mode,
1467                                 char *name, int namelen,
1468                                 struct lustre_handle *child_lockh,
1469                                 struct dentry **dchildp, int child_mode,
1470                                 __u64 child_lockpart)
1471 {
1472         ldlm_policy_data_t parent_policy = {.l_inodebits = { parent_lockpart }};
1473         ldlm_policy_data_t child_policy = {.l_inodebits = { child_lockpart }};
1474         struct ldlm_res_id parent_res_id = { .name = {0} };
1475         struct ldlm_res_id child_res_id = { .name = {0} };
1476         unsigned long child_ino = 0; __u32 child_gen = 0;
1477         int rc = 0, cleanup_phase = 0;
1478         struct lustre_id sid;
1479         struct inode *inode;
1480         ENTRY;
1481
1482         /* Step 1: Lookup parent */
1483         *dparentp = mds_id2dentry(obd, id, NULL);
1484         if (IS_ERR(*dparentp)) {
1485                 rc = PTR_ERR(*dparentp);
1486                 *dparentp = NULL;
1487                 RETURN(rc);
1488         }
1489
1490         CDEBUG(D_INODE, "parent ino %lu, name %s\n",
1491                (*dparentp)->d_inode->i_ino, name);
1492
1493         parent_res_id.name[0] = id_fid(id);
1494         parent_res_id.name[1] = id_group(id);
1495         
1496 #ifdef S_PDIROPS
1497         parent_lockh[1].cookie = 0;
1498         if (name && IS_PDIROPS((*dparentp)->d_inode)) {
1499                 struct ldlm_res_id res_id = { .name = {0} };
1500                 ldlm_policy_data_t policy;
1501                 int flags = 0;
1502
1503                 *update_mode = mds_lock_mode_for_dir(obd, *dparentp, parent_mode);
1504                 if (*update_mode) {
1505                         res_id.name[0] = id_fid(id);
1506                         res_id.name[1] = id_group(id);
1507                         policy.l_inodebits.bits = MDS_INODELOCK_UPDATE;
1508
1509                         rc = ldlm_cli_enqueue(NULL, NULL, obd->obd_namespace,
1510                                               res_id, LDLM_IBITS, &policy,
1511                                               *update_mode, &flags,
1512                                               mds_blocking_ast,
1513                                               ldlm_completion_ast,
1514                                               NULL, NULL, NULL, 0, NULL,
1515                                               parent_lockh + 1);
1516                         if (rc != ELDLM_OK)
1517                                 RETURN(-ENOLCK);
1518                 }
1519
1520                 parent_res_id.name[2] = full_name_hash(name, namelen - 1);
1521                 
1522                 CDEBUG(D_INFO, "take lock on %lu:%lu:"LPX64"\n",
1523                        (unsigned long)id_fid(id), (unsigned long)id_group(id),
1524                        parent_res_id.name[2]);
1525         }
1526 #endif
1527
1528         cleanup_phase = 1; /* parent dentry */
1529
1530         /* Step 2: Lookup child (without DLM lock, to get resource name) */
1531         *dchildp = ll_lookup_one_len(name, *dparentp, namelen - 1);
1532         if (IS_ERR(*dchildp)) {
1533                 rc = PTR_ERR(*dchildp);
1534                 CDEBUG(D_INODE, "child lookup error %d\n", rc);
1535                 GOTO(cleanup, rc);
1536         }
1537
1538         if ((*dchildp)->d_flags & DCACHE_CROSS_REF) {
1539                 /*
1540                  * inode lives on another MDS: return * fid/mdsnum and LOOKUP
1541                  * lock. Drop possible UPDATE lock!
1542                  */
1543                 child_policy.l_inodebits.bits &= ~MDS_INODELOCK_UPDATE;
1544                 child_policy.l_inodebits.bits |= MDS_INODELOCK_LOOKUP;
1545
1546                 child_res_id.name[0] = (*dchildp)->d_fid;
1547                 child_res_id.name[1] = (*dchildp)->d_mdsnum;
1548                 child_ino = (*dchildp)->d_inum;
1549                 child_gen = (*dchildp)->d_generation;
1550                 goto retry_locks;
1551         }
1552
1553         inode = (*dchildp)->d_inode;
1554         if (inode != NULL)
1555                 inode = igrab(inode);
1556         if (inode == NULL)
1557                 goto retry_locks;
1558
1559         down(&inode->i_sem);
1560         rc = mds_read_inode_sid(obd, inode, &sid);
1561         up(&inode->i_sem);
1562         if (rc) {
1563                 CERROR("Can't read inode self id, inode %lu, "
1564                        "rc %d\n", inode->i_ino, rc);
1565                 iput(inode);
1566                 GOTO(cleanup, rc);
1567         }
1568         
1569         child_ino = inode->i_ino;
1570         child_gen = inode->i_generation;
1571         child_res_id.name[0] = id_fid(&sid);
1572         child_res_id.name[1] = id_group(&sid);
1573         iput(inode);
1574
1575 retry_locks:
1576         cleanup_phase = 2; /* child dentry */
1577
1578         /* Step 3: Lock parent and child in resource order.  If child doesn't
1579          * exist, we still have to lock the parent and re-lookup. */
1580         rc = enqueue_ordered_locks(obd, &parent_res_id, parent_lockh, parent_mode,
1581                                    &parent_policy, &child_res_id, child_lockh,
1582                                    child_mode, &child_policy);
1583         if (rc)
1584                 GOTO(cleanup, rc);
1585
1586         if ((*dchildp)->d_inode || ((*dchildp)->d_flags & DCACHE_CROSS_REF))
1587                 cleanup_phase = 4; /* child lock */
1588         else
1589                 cleanup_phase = 3; /* parent lock */
1590
1591         /* Step 4: Re-lookup child to verify it hasn't changed since locking */
1592         rc = mds_verify_child(obd, &parent_res_id, parent_lockh, *dparentp,
1593                               parent_mode, &child_res_id, child_lockh, 
1594                               dchildp, child_mode, &child_policy,
1595                               name, namelen, &parent_res_id, child_ino, 
1596                               child_gen);
1597         if (rc > 0)
1598                 goto retry_locks;
1599         if (rc < 0) {
1600                 cleanup_phase = 3;
1601                 GOTO(cleanup, rc);
1602         }
1603
1604         EXIT;
1605 cleanup:
1606         if (rc) {
1607                 switch (cleanup_phase) {
1608                 case 4:
1609                         ldlm_lock_decref(child_lockh, child_mode);
1610                 case 3:
1611                         ldlm_lock_decref(parent_lockh, parent_mode);
1612                 case 2:
1613                         l_dput(*dchildp);
1614                 case 1:
1615 #ifdef S_PDIROPS
1616                         if (parent_lockh[1].cookie)
1617                                 ldlm_lock_decref(parent_lockh + 1, *update_mode);
1618 #endif
1619                         l_dput(*dparentp);
1620                 }
1621         }
1622         return rc;
1623 }
1624
1625 void mds_reconstruct_generic(struct ptlrpc_request *req)
1626 {
1627         struct mds_export_data *med = &req->rq_export->exp_mds_data;
1628         mds_req_from_mcd(req, med->med_mcd);
1629 }
1630
1631 /* If we are unlinking an open file/dir (i.e. creating an orphan) then
1632  * we instead link the inode into the PENDING directory until it is
1633  * finally released.  We can't simply call mds_reint_rename() or some
1634  * part thereof, because we don't have the inode to check for link
1635  * count/open status until after it is locked.
1636  *
1637  * For lock ordering, caller must get child->i_sem first, then pending->i_sem
1638  * before starting journal transaction.
1639  *
1640  * returns 1 on success
1641  * returns 0 if we lost a race and didn't make a new link
1642  * returns negative on error
1643  */
1644 static int mds_orphan_add_link(struct mds_update_record *rec,
1645                                struct obd_device *obd, struct dentry *dentry)
1646 {
1647         struct mds_obd *mds = &obd->u.mds;
1648         struct inode *pending_dir = mds->mds_pending_dir->d_inode;
1649         struct inode *inode = dentry->d_inode;
1650         struct dentry *pending_child;
1651         char idname[LL_ID_NAMELEN];
1652         int idlen = 0, rc, mode;
1653         ENTRY;
1654
1655         LASSERT(inode != NULL);
1656         LASSERT(!mds_inode_is_orphan(inode));
1657 #ifndef HAVE_I_ALLOC_SEM
1658         LASSERT(down_trylock(&inode->i_sem) != 0);
1659 #endif
1660         LASSERT(down_trylock(&pending_dir->i_sem) != 0);
1661
1662         idlen = ll_id2str(idname, inode->i_ino, inode->i_generation);
1663
1664         CDEBUG(D_INODE, "pending destroy of %dx open %d linked %s %s = %s\n",
1665                mds_orphan_open_count(inode), inode->i_nlink,
1666                S_ISDIR(inode->i_mode) ? "dir" :
1667                S_ISREG(inode->i_mode) ? "file" : "other",
1668                rec->ur_name, idname);
1669
1670         if (mds_orphan_open_count(inode) == 0 || inode->i_nlink != 0)
1671                 RETURN(0);
1672
1673         pending_child = lookup_one_len(idname, mds->mds_pending_dir, idlen);
1674         if (IS_ERR(pending_child))
1675                 RETURN(PTR_ERR(pending_child));
1676
1677         if (pending_child->d_inode != NULL) {
1678                 CERROR("re-destroying orphan file %s?\n", rec->ur_name);
1679                 LASSERT(pending_child->d_inode == inode);
1680                 GOTO(out_dput, rc = 0);
1681         }
1682
1683         /* link() is semanticaly-wrong for S_IFDIR, so we set S_IFREG
1684          * for linking and return real mode back then -bzzz */
1685         mode = inode->i_mode;
1686         inode->i_mode = S_IFREG;
1687         rc = vfs_link(dentry, pending_dir, pending_child);
1688         if (rc)
1689                 CERROR("error linking orphan %s to PENDING: rc = %d\n",
1690                        rec->ur_name, rc);
1691         else
1692                 mds_inode_set_orphan(inode);
1693
1694         /* return mode and correct i_nlink if inode is directory */
1695         inode->i_mode = mode;
1696         LASSERTF(inode->i_nlink == 1, "%s nlink == %d\n",
1697                  S_ISDIR(mode) ? "dir" : S_ISREG(mode) ? "file" : "other",
1698                  inode->i_nlink);
1699         if (S_ISDIR(mode)) {
1700                 inode->i_nlink++;
1701                 pending_dir->i_nlink++;
1702                 mark_inode_dirty(inode);
1703                 mark_inode_dirty(pending_dir);
1704         }
1705
1706         EXIT;
1707 out_dput:
1708         l_dput(pending_child);
1709         return rc;
1710 }
1711
1712 int mds_create_local_dentry(struct mds_update_record *rec,
1713                             struct obd_device *obd)
1714 {
1715         struct mds_obd *mds = &obd->u.mds;
1716         struct inode *id_dir = mds->mds_id_dir->d_inode;
1717         int idlen = 0, rc, cleanup_phase = 0;
1718         struct dentry *new_child = NULL;
1719         char *idname = rec->ur_name;
1720         struct dentry *child = NULL;
1721         struct lustre_handle lockh[2] = {{0}, {0}};
1722         struct lustre_id sid;
1723         void *handle;
1724         ENTRY;
1725
1726         down(&id_dir->i_sem);
1727         idlen = ll_id2str(idname, id_ino(rec->ur_id1),
1728                           id_gen(rec->ur_id1));
1729         
1730         CDEBUG(D_OTHER, "look for local dentry '%s' for "DLID4"\n",
1731                idname, OLID4(rec->ur_id1));
1732
1733         new_child = ll_lookup_one_len(idname, mds->mds_id_dir, 
1734                                       idlen);
1735         up(&id_dir->i_sem);
1736         if (IS_ERR(new_child)) {
1737                 CERROR("can't lookup %s: %d\n", idname,
1738                        (int) PTR_ERR(new_child));
1739                 GOTO(cleanup, rc = PTR_ERR(new_child));
1740         }
1741         cleanup_phase = 1;
1742
1743         down(&id_dir->i_sem);
1744         rc = mds_read_inode_sid(obd, id_dir, &sid);
1745         up(&id_dir->i_sem);
1746         if (rc) {
1747                 CERROR("Can't read inode self id, inode %lu, "
1748                        "rc %d\n", id_dir->i_ino, rc);
1749                 GOTO(cleanup, rc);
1750         }
1751         
1752         if (new_child->d_inode != NULL) {
1753                 /* nice. we've already have local dentry! */
1754                 CDEBUG(D_OTHER, "found dentry in FIDS/: %u/%u\n", 
1755                        (unsigned)new_child->d_inode->i_ino,
1756                        (unsigned)new_child->d_inode->i_generation);
1757                 
1758                 id_ino(rec->ur_id1) = id_dir->i_ino;
1759                 id_gen(rec->ur_id1) = id_dir->i_generation;
1760                 rec->ur_namelen = idlen + 1;
1761
1762                 id_fid(rec->ur_id1) = id_fid(&sid);
1763                 id_group(rec->ur_id1) = id_group(&sid);
1764                 
1765                 GOTO(cleanup, rc = 0);
1766         }
1767
1768         /* new, local dentry will be added soon. we need no aliases here */
1769         d_drop(new_child);
1770
1771         if (rec->ur_mode & MDS_MODE_DONT_LOCK) {
1772                 child = mds_id2dentry(obd, rec->ur_id1, NULL);
1773         } else {
1774                 child = mds_id2locked_dentry(obd, rec->ur_id1, NULL,
1775                                              LCK_EX, lockh, NULL, NULL, 0,
1776                                              MDS_INODELOCK_UPDATE);
1777         }
1778
1779         if (IS_ERR(child)) {
1780                 rc = PTR_ERR(child);
1781                 if (rc != -ENOENT || !(rec->ur_mode & MDS_MODE_REPLAY))
1782                         CERROR("can't get victim: %d\n", rc);
1783                 GOTO(cleanup, rc);
1784         }
1785         cleanup_phase = 2;
1786
1787         handle = fsfilt_start(obd, id_dir, FSFILT_OP_LINK, NULL);
1788         if (IS_ERR(handle))
1789                 GOTO(cleanup, rc = PTR_ERR(handle));
1790
1791         rc = fsfilt_add_dir_entry(obd, mds->mds_id_dir, idname,
1792                                   idlen, id_ino(rec->ur_id1),
1793                                   id_gen(rec->ur_id1), mds->mds_num,
1794                                   id_fid(rec->ur_id1));
1795         if (rc)
1796                 CERROR("error linking orphan %lu/%lu to FIDS: rc = %d\n",
1797                        (unsigned long)child->d_inode->i_ino,
1798                        (unsigned long)child->d_inode->i_generation, rc);
1799         else {
1800                 if (S_ISDIR(child->d_inode->i_mode)) {
1801                         id_dir->i_nlink++;
1802                         mark_inode_dirty(id_dir);
1803                 }
1804                 mark_inode_dirty(child->d_inode);
1805         }
1806         fsfilt_commit(obd, mds->mds_sb, id_dir, handle, 0);
1807
1808         id_ino(rec->ur_id1) = id_dir->i_ino;
1809         id_gen(rec->ur_id1) = id_dir->i_generation;
1810         rec->ur_namelen = idlen + 1;
1811
1812         id_fid(rec->ur_id1) = id_fid(&sid);
1813         id_group(rec->ur_id1) = id_group(&sid);
1814
1815         EXIT;
1816 cleanup:
1817         switch(cleanup_phase) {
1818                 case 2:
1819                         if (!(rec->ur_mode & MDS_MODE_DONT_LOCK))
1820                                 ldlm_lock_decref(lockh, LCK_EX);
1821                         dput(child);
1822                 case 1:
1823                         dput(new_child);
1824                 case 0:
1825                        break; 
1826         }
1827         return rc;
1828 }
1829
1830 static int mds_copy_unlink_reply(struct ptlrpc_request *master,
1831                                  struct ptlrpc_request *slave)
1832 {
1833         void *cookie, *cookie2;
1834         struct mds_body *body2;
1835         struct mds_body *body;
1836         void *ea, *ea2;
1837         ENTRY;
1838
1839         body = lustre_msg_buf(slave->rq_repmsg, 0, sizeof(*body));
1840         LASSERT(body != NULL);
1841
1842         body2 = lustre_msg_buf(master->rq_repmsg, 0, sizeof (*body));
1843         LASSERT(body2 != NULL);
1844
1845         if (!(body->valid & (OBD_MD_FLID | OBD_MD_FLGENER)))
1846                 RETURN(0);
1847
1848         memcpy(body2, body, sizeof(*body));
1849         body2->valid &= ~OBD_MD_FLCOOKIE;
1850
1851         if (!(body->valid & OBD_MD_FLEASIZE) &&
1852             !(body->valid & OBD_MD_FLDIREA))
1853                 RETURN(0);
1854
1855         if (body->eadatasize == 0) {
1856                 CERROR("OBD_MD_FLEASIZE set but eadatasize zero\n");
1857                 RETURN(0);
1858         }
1859
1860         LASSERT(master->rq_repmsg->buflens[1] >= body->eadatasize);
1861         
1862         ea = lustre_msg_buf(slave->rq_repmsg, 1, body->eadatasize);
1863         LASSERT(ea != NULL);
1864         
1865         ea2 = lustre_msg_buf(master->rq_repmsg, 1, body->eadatasize);
1866         LASSERT(ea2 != NULL);
1867
1868         memcpy(ea2, ea, body->eadatasize);
1869
1870         if (body->valid & OBD_MD_FLCOOKIE) {
1871                 LASSERT(master->rq_repmsg->buflens[2] >=
1872                                 slave->rq_repmsg->buflens[2]);
1873                 cookie = lustre_msg_buf(slave->rq_repmsg, 2,
1874                                 slave->rq_repmsg->buflens[2]);
1875                 LASSERT(cookie != NULL);
1876
1877                 cookie2 = lustre_msg_buf(master->rq_repmsg, 2,
1878                                 master->rq_repmsg->buflens[2]);
1879                 LASSERT(cookie2 != NULL);
1880                 memcpy(cookie2, cookie, slave->rq_repmsg->buflens[2]);
1881                 body2->valid |= OBD_MD_FLCOOKIE;
1882         }
1883         RETURN(0);
1884 }
1885
1886 static int mds_reint_unlink_remote(struct mds_update_record *rec,
1887                                    int offset, struct ptlrpc_request *req,
1888                                    struct lustre_handle *parent_lockh,
1889                                    int update_mode, struct dentry *dparent,
1890                                    struct lustre_handle *child_lockh,
1891                                    struct dentry *dchild)
1892 {
1893         struct obd_device *obd = req->rq_export->exp_obd;
1894         struct mds_obd *mds = mds_req2mds(req);
1895         struct ptlrpc_request *request = NULL;
1896         int rc = 0, cleanup_phase = 0;
1897         struct mdc_op_data *op_data;
1898         void *handle;
1899         ENTRY;
1900
1901         LASSERT(offset == 1 || offset == 3);
1902
1903         /* time to drop i_nlink on remote MDS */
1904         OBD_ALLOC(op_data, sizeof(*op_data));
1905         if (op_data == NULL)
1906                 RETURN(-ENOMEM);
1907         
1908         memset(op_data, 0, sizeof(*op_data));
1909         mds_pack_dentry2id(obd, &op_data->id1, dchild, 1);
1910         op_data->create_mode = rec->ur_mode;
1911
1912         DEBUG_REQ(D_INODE, req, "unlink %*s (remote inode "DLID4")",
1913                   rec->ur_namelen - 1, rec->ur_name, OLID4(&op_data->id1));
1914         
1915         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY) {
1916                 DEBUG_REQ(D_HA, req, "unlink %*s (remote inode "DLID4")",
1917                           rec->ur_namelen - 1, rec->ur_name, OLID4(&op_data->id1));
1918         }
1919
1920         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY)
1921                 op_data->create_mode |= MDS_MODE_REPLAY;
1922         
1923         rc = md_unlink(mds->mds_md_exp, op_data, &request);
1924         OBD_FREE(op_data, sizeof(*op_data));
1925         cleanup_phase = 2;
1926
1927         if (request) {
1928                 if (rc == 0)
1929                         mds_copy_unlink_reply(req, request);
1930                 ptlrpc_req_finished(request);
1931         }
1932
1933         if (rc == 0) {
1934                 handle = fsfilt_start(obd, dparent->d_inode, FSFILT_OP_RMDIR,
1935                                       NULL);
1936                 if (IS_ERR(handle))
1937                         GOTO(cleanup, rc = PTR_ERR(handle));
1938                 rc = fsfilt_del_dir_entry(req->rq_export->exp_obd, dchild);
1939                 rc = mds_finish_transno(mds, dparent->d_inode, handle, req,
1940                                         rc, 0);
1941         }
1942         EXIT;
1943 cleanup:
1944         req->rq_status = rc;
1945
1946 #ifdef S_PDIROPS
1947         if (parent_lockh[1].cookie != 0)
1948                 ldlm_lock_decref(parent_lockh + 1, update_mode);
1949 #endif
1950         ldlm_lock_decref(child_lockh, LCK_EX);
1951         if (rc)
1952                 ldlm_lock_decref(parent_lockh, LCK_PW);
1953         else
1954                 ptlrpc_save_lock(req, parent_lockh, LCK_PW);
1955         l_dput(dchild);
1956         l_dput(dparent);
1957
1958         return 0;
1959 }
1960
1961 static int mds_reint_unlink(struct mds_update_record *rec, int offset,
1962                             struct ptlrpc_request *req,
1963                             struct lustre_handle *lh)
1964 {
1965         struct dentry *dparent = NULL, *dchild;
1966         struct mds_obd *mds = mds_req2mds(req);
1967         struct obd_device *obd = req->rq_export->exp_obd;
1968         struct mds_body *body = NULL;
1969         struct inode *child_inode = NULL;
1970         struct lustre_handle parent_lockh[2] = {{0}, {0}}; 
1971         struct lustre_handle child_lockh = {0};
1972         struct lustre_handle child_reuse_lockh = {0};
1973         struct lustre_handle *slave_lockh = NULL;
1974         char idname[LL_ID_NAMELEN];
1975         struct llog_create_locks *lcl = NULL;
1976         void *handle = NULL;
1977         int rc = 0, cleanup_phase = 0;
1978         int unlink_by_id = 0;
1979         int update_mode;
1980         ENTRY;
1981
1982         LASSERT(offset == 1 || offset == 3);
1983
1984         DEBUG_REQ(D_INODE, req, "parent ino "LPU64"/%u, child %s",
1985                   id_ino(rec->ur_id1), id_gen(rec->ur_id1),
1986                   rec->ur_name);
1987
1988         MDS_CHECK_RESENT(req, mds_reconstruct_generic(req));
1989
1990         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY) {
1991                 DEBUG_REQ(D_HA, req, "unlink replay");
1992                 LASSERT(offset == 1); /* should not come from intent */
1993                 memcpy(lustre_msg_buf(req->rq_repmsg, 2, 0),
1994                        lustre_msg_buf(req->rq_reqmsg, offset + 2, 0),
1995                        req->rq_repmsg->buflens[2]);
1996         }
1997
1998         MD_COUNTER_INCREMENT(obd, unlink);
1999
2000         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_REINT_UNLINK))
2001                 GOTO(cleanup, rc = -ENOENT);
2002
2003         if (rec->ur_namelen == 1) {
2004                 /* this is request to drop i_nlink on local inode */
2005                 unlink_by_id = 1;
2006                 rec->ur_name = idname;
2007                 rc = mds_create_local_dentry(rec, obd);
2008                 if (rc == -ENOENT || (rec->ur_mode & MDS_MODE_REPLAY)) {
2009                         DEBUG_REQ(D_HA, req,
2010                                   "drop nlink on inode "DLID4" (replay)",
2011                                   OLID4(rec->ur_id1));
2012                         req->rq_status = 0;
2013                         RETURN(0);
2014                 }
2015         }
2016
2017         if (rec->ur_mode & MDS_MODE_DONT_LOCK) {
2018                 /* master mds for directory asks slave removing inode is already
2019                  * locked */
2020                 dparent = mds_id2locked_dentry(obd, rec->ur_id1, NULL,
2021                                                LCK_PW, parent_lockh,
2022                                                &update_mode, rec->ur_name,
2023                                                rec->ur_namelen,
2024                                                MDS_INODELOCK_UPDATE);
2025                 if (IS_ERR(dparent))
2026                         GOTO(cleanup, rc = PTR_ERR(dparent));
2027                 dchild = ll_lookup_one_len(rec->ur_name, dparent, 
2028                                            rec->ur_namelen - 1);
2029                 if (IS_ERR(dchild))
2030                         GOTO(cleanup, rc = PTR_ERR(dchild));
2031                 child_lockh.cookie = 0;
2032                 LASSERT(!(dchild->d_flags & DCACHE_CROSS_REF));
2033                 LASSERT(dchild->d_inode != NULL);
2034                 LASSERT(S_ISDIR(dchild->d_inode->i_mode));
2035         } else {
2036                 rc = mds_get_parent_child_locked(obd, mds, rec->ur_id1,
2037                                                  parent_lockh, &dparent,
2038                                                  LCK_PW, MDS_INODELOCK_UPDATE,
2039                                                  &update_mode, rec->ur_name,
2040                                                  rec->ur_namelen, &child_lockh,
2041                                                  &dchild, LCK_EX,
2042                                                  MDS_INODELOCK_LOOKUP |
2043                                                  MDS_INODELOCK_UPDATE);
2044         }
2045         if (rc)
2046                 GOTO(cleanup, rc);
2047
2048         if (dchild->d_flags & DCACHE_CROSS_REF) {
2049                 /* we should have parent lock only here */
2050                 LASSERT(unlink_by_id == 0);
2051                 LASSERT(dchild->d_mdsnum != mds->mds_num);
2052                 mds_reint_unlink_remote(rec, offset, req, parent_lockh,
2053                                         update_mode, dparent, &child_lockh, dchild);
2054                 RETURN(0);
2055         }
2056
2057         cleanup_phase = 1; /* dchild, dparent, locks */
2058
2059         dget(dchild);
2060         child_inode = dchild->d_inode;
2061         if (child_inode == NULL) {
2062                 CDEBUG(D_INODE, "child doesn't exist (dir %lu, name %s)\n",
2063                        dparent ? dparent->d_inode->i_ino : 0, rec->ur_name);
2064                 GOTO(cleanup, rc = -ENOENT);
2065         }
2066
2067         cleanup_phase = 2; /* dchild has a lock */
2068
2069         /* We have to do these checks ourselves, in case we are making an
2070          * orphan.  The client tells us whether rmdir() or unlink() was called,
2071          * so we need to return appropriate errors (bug 72).
2072          *
2073          * We don't have to check permissions, because vfs_rename (called from
2074          * mds_open_unlink_rename) also calls may_delete. */
2075         if ((rec->ur_mode & S_IFMT) == S_IFDIR) {
2076                 if (!S_ISDIR(child_inode->i_mode))
2077                         GOTO(cleanup, rc = -ENOTDIR);
2078         } else {
2079                 if (S_ISDIR(child_inode->i_mode))
2080                         GOTO(cleanup, rc = -EISDIR);
2081         }
2082
2083         /* handle splitted dir */
2084         rc = mds_lock_slave_objs(obd, dchild, &slave_lockh);
2085         if (rc)
2086                 GOTO(cleanup, rc);
2087
2088         /* Step 4: Get a lock on the ino to sync with creation WRT inode
2089          * reuse (see bug 2029). */
2090         rc = mds_lock_new_child(obd, child_inode, &child_reuse_lockh);
2091         if (rc != ELDLM_OK)
2092                 GOTO(cleanup, rc);
2093         cleanup_phase = 3; /* child inum lock */
2094
2095         OBD_FAIL_WRITE(OBD_FAIL_MDS_REINT_UNLINK_WRITE, dparent->d_inode->i_sb);
2096
2097         /* ldlm_reply in buf[0] if called via intent */
2098         if (offset == 3)
2099                 offset = 1;
2100         else
2101                 offset = 0;
2102
2103         body = lustre_msg_buf(req->rq_repmsg, offset, sizeof (*body));
2104         LASSERT(body != NULL);
2105
2106         /* child i_alloc_sem protects orphan_dec_test && is_orphan race */
2107         DOWN_READ_I_ALLOC_SEM(child_inode);
2108         cleanup_phase = 4; /* up(&child_inode->i_sem) when finished */
2109
2110         /* If this is potentially the last reference to this inode, get the
2111          * OBD EA data first so the client can destroy OST objects.  We
2112          * only do the object removal later if no open files/links remain. */
2113         if ((S_ISDIR(child_inode->i_mode) && child_inode->i_nlink == 2) ||
2114             child_inode->i_nlink == 1) {
2115                 if (mds_orphan_open_count(child_inode) > 0) {
2116                         /* need to lock pending_dir before transaction */
2117                         down(&mds->mds_pending_dir->d_inode->i_sem);
2118                         cleanup_phase = 5; /* up(&pending_dir->i_sem) */
2119                 } else if (S_ISREG(child_inode->i_mode)) {
2120                         mds_pack_inode2body(obd, body, child_inode, 0);
2121                         mds_pack_md(obd, req->rq_repmsg, offset + 1,
2122                                     body, child_inode, MDS_PACK_MD_LOCK, 0);
2123                 }
2124         }
2125
2126         /* Step 4: Do the unlink: we already verified ur_mode above (bug 72) */
2127         switch (child_inode->i_mode & S_IFMT) {
2128         case S_IFDIR:
2129                 /* Drop any lingering child directories before we start our
2130                  * transaction, to avoid doing multiple inode dirty/delete
2131                  * in our compound transaction (bug 1321). */
2132                 shrink_dcache_parent(dchild);
2133                 handle = fsfilt_start(obd, dparent->d_inode, FSFILT_OP_RMDIR,
2134                                       NULL);
2135                 if (IS_ERR(handle))
2136                         GOTO(cleanup, rc = PTR_ERR(handle));
2137                 rc = vfs_rmdir(dparent->d_inode, dchild);
2138                 break;
2139         case S_IFREG: {
2140 #warning "optimization is possible here: we could drop nlink w/o removing local dentry in FIDS/"
2141                 struct lov_mds_md *lmm = lustre_msg_buf(req->rq_repmsg,
2142                                                         offset + 1, 0);
2143                 handle = fsfilt_start_log(obd, dparent->d_inode,
2144                                           FSFILT_OP_UNLINK, NULL,
2145                                           le32_to_cpu(lmm->lmm_stripe_count));
2146                 if (IS_ERR(handle))
2147                         GOTO(cleanup, rc = PTR_ERR(handle));
2148                 rc = vfs_unlink(dparent->d_inode, dchild);
2149                 break;
2150         }
2151         case S_IFLNK:
2152         case S_IFCHR:
2153         case S_IFBLK:
2154         case S_IFIFO:
2155         case S_IFSOCK:
2156                 handle = fsfilt_start(obd, dparent->d_inode, FSFILT_OP_UNLINK,
2157                                       NULL);
2158                 if (IS_ERR(handle))
2159                         GOTO(cleanup, rc = PTR_ERR(handle));
2160                 rc = vfs_unlink(dparent->d_inode, dchild);
2161                 break;
2162         default:
2163                 CERROR("bad file type %o unlinking %s\n", rec->ur_mode,
2164                        rec->ur_name);
2165                 LBUG();
2166                 GOTO(cleanup, rc = -EINVAL);
2167         }
2168
2169         if (rc == 0 && child_inode->i_nlink == 0) {
2170                 if (mds_orphan_open_count(child_inode) > 0)
2171                         rc = mds_orphan_add_link(rec, obd, dchild);
2172
2173                 if (rc == 1)
2174                         GOTO(cleanup, rc = 0);
2175
2176                 if (!S_ISREG(child_inode->i_mode))
2177                         GOTO(cleanup, rc);
2178
2179                 if (!(body->valid & OBD_MD_FLEASIZE)) {
2180                         body->valid |= (OBD_MD_FLSIZE | OBD_MD_FLBLOCKS |
2181                                         OBD_MD_FLATIME | OBD_MD_FLMTIME);
2182                 } else if (mds_log_op_unlink(obd, child_inode,
2183                                 lustre_msg_buf(req->rq_repmsg, offset + 1, 0),
2184                                         req->rq_repmsg->buflens[offset + 1],
2185                                 lustre_msg_buf(req->rq_repmsg, offset + 2, 0),
2186                                         req->rq_repmsg->buflens[offset+2], 
2187                                 &lcl) > 0){
2188                         body->valid |= OBD_MD_FLCOOKIE;
2189                 }
2190         }
2191
2192         GOTO(cleanup, rc);
2193
2194 cleanup:
2195         if (rc == 0) {
2196                 struct iattr iattr;
2197                 int err;
2198
2199                 iattr.ia_valid = ATTR_MTIME | ATTR_CTIME;
2200                 LTIME_S(iattr.ia_mtime) = rec->ur_time;
2201                 LTIME_S(iattr.ia_ctime) = rec->ur_time;
2202
2203                 err = fsfilt_setattr(obd, dparent, handle, &iattr, 0);
2204                 if (err)
2205                         CERROR("error on parent setattr: rc = %d\n", err);
2206         }
2207         rc = mds_finish_transno(mds, dparent ? dparent->d_inode : NULL,
2208                                 handle, req, rc, 0);
2209         if (!rc)
2210                 (void)obd_set_info(mds->mds_dt_exp, strlen("unlinked"),
2211                                    "unlinked", 0, NULL);
2212         switch(cleanup_phase) {
2213         case 5: /* pending_dir semaphore */
2214                 up(&mds->mds_pending_dir->d_inode->i_sem);
2215         case 4: /* child inode semaphore */
2216                 UP_READ_I_ALLOC_SEM(child_inode);
2217                  /* handle splitted dir */
2218                 if (rc == 0) {
2219                         /* master directory can be non-empty or something else ... */
2220                         mds_unlink_slave_objs(obd, dchild);
2221                 }
2222                 if (lcl != NULL)
2223                         ptlrpc_save_llog_lock(req, lcl);
2224         case 3: /* child ino-reuse lock */
2225                 if (rc && body != NULL) {
2226                         // Don't unlink the OST objects if the MDS unlink failed
2227                         body->valid = 0;
2228                 }
2229                 if (rc)
2230                         ldlm_lock_decref(&child_reuse_lockh, LCK_EX);
2231                 else
2232                         ptlrpc_save_lock(req, &child_reuse_lockh, LCK_EX);
2233         case 2: /* child lock */
2234                 mds_unlock_slave_objs(obd, dchild, slave_lockh);
2235                 if (child_lockh.cookie)
2236                         ldlm_lock_decref(&child_lockh, LCK_EX);
2237         case 1: /* child and parent dentry, parent lock */
2238 #ifdef S_PDIROPS
2239                 if (parent_lockh[1].cookie != 0)
2240                         ldlm_lock_decref(parent_lockh + 1, update_mode);
2241 #endif
2242                 if (rc)
2243                         ldlm_lock_decref(parent_lockh, LCK_PW);
2244                 else
2245                         ptlrpc_save_lock(req, parent_lockh, LCK_PW);
2246                 l_dput(dchild);
2247                 l_dput(dchild);
2248                 l_dput(dparent);
2249         case 0:
2250                 break;
2251         default:
2252                 CERROR("invalid cleanup_phase %d\n", cleanup_phase);
2253                 LBUG();
2254         }
2255         req->rq_status = rc;
2256         return 0;
2257 }
2258
2259 /*
2260  * to service requests from remote MDS to increment i_nlink
2261  */
2262 static int mds_reint_link_acquire(struct mds_update_record *rec,
2263                                   int offset, struct ptlrpc_request *req,
2264                                   struct lustre_handle *lh)
2265 {
2266         struct obd_device *obd = req->rq_export->exp_obd;
2267         struct ldlm_res_id src_res_id = { .name = {0} };
2268         struct lustre_handle *handle = NULL, src_lockh = {0};
2269         struct mds_obd *mds = mds_req2mds(req);
2270         int rc = 0, cleanup_phase = 0;
2271         struct dentry *de_src = NULL;
2272         ldlm_policy_data_t policy;
2273         int flags = 0;
2274         ENTRY;
2275
2276         DEBUG_REQ(D_INODE, req, "%s: request to acquire i_nlinks "DLID4"\n",
2277                   obd->obd_name, OLID4(rec->ur_id1));
2278
2279         /* Step 1: Lookup the source inode and target directory by ID */
2280         de_src = mds_id2dentry(obd, rec->ur_id1, NULL);
2281         if (IS_ERR(de_src))
2282                 GOTO(cleanup, rc = PTR_ERR(de_src));
2283         cleanup_phase = 1; /* source dentry */
2284
2285         src_res_id.name[0] = id_fid(rec->ur_id1);
2286         src_res_id.name[1] = id_group(rec->ur_id1);
2287         policy.l_inodebits.bits = MDS_INODELOCK_UPDATE;
2288
2289         rc = ldlm_cli_enqueue(NULL, NULL, obd->obd_namespace,
2290                               src_res_id, LDLM_IBITS, &policy,
2291                               LCK_EX, &flags, mds_blocking_ast,
2292                               ldlm_completion_ast, NULL, NULL,
2293                               NULL, 0, NULL, &src_lockh);
2294         if (rc != ELDLM_OK)
2295                 GOTO(cleanup, rc = -ENOLCK);
2296         cleanup_phase = 2; /* lock */
2297
2298         OBD_FAIL_WRITE(OBD_FAIL_MDS_REINT_LINK_WRITE, de_src->d_inode->i_sb);
2299
2300         handle = fsfilt_start(obd, de_src->d_inode, FSFILT_OP_LINK, NULL);
2301         if (IS_ERR(handle)) {
2302                 rc = PTR_ERR(handle);
2303                 GOTO(cleanup, rc);
2304         }
2305         de_src->d_inode->i_nlink++;
2306         mark_inode_dirty(de_src->d_inode);
2307
2308         EXIT;
2309 cleanup:
2310         rc = mds_finish_transno(mds, de_src ? de_src->d_inode : NULL,
2311                                 handle, req, rc, 0);
2312         switch (cleanup_phase) {
2313                 case 2:
2314                         if (rc)
2315                                 ldlm_lock_decref(&src_lockh, LCK_EX);
2316                         else
2317                                 ptlrpc_save_lock(req, &src_lockh, LCK_EX);
2318                 case 1:
2319                         l_dput(de_src);
2320                 case 0:
2321                         break;
2322                 default:
2323                         CERROR("invalid cleanup_phase %d\n", cleanup_phase);
2324                         LBUG();
2325         }
2326         req->rq_status = rc;
2327         return 0;
2328 }
2329
2330 /*
2331  * request to link to foreign inode:
2332  *  - acquire i_nlinks on this inode
2333  *  - add dentry
2334  */
2335 static int mds_reint_link_to_remote(struct mds_update_record *rec,
2336                                     int offset, struct ptlrpc_request *req,
2337                                     struct lustre_handle *lh)
2338 {
2339         struct lustre_handle *handle = NULL, tgt_dir_lockh[2] = {{0}, {0}};
2340         struct obd_device *obd = req->rq_export->exp_obd;
2341         struct dentry *de_tgt_dir = NULL;
2342         struct mds_obd *mds = mds_req2mds(req);
2343         int rc = 0, cleanup_phase = 0;
2344         struct mdc_op_data *op_data;
2345         struct ptlrpc_request *request = NULL;
2346         int update_mode;
2347         ENTRY;
2348
2349         DEBUG_REQ(D_INODE, req, "%s: request to link "DLID4
2350                   ":%*s to foreign inode "DLID4"\n", obd->obd_name,
2351                   OLID4(rec->ur_id2), rec->ur_namelen - 1, rec->ur_name,
2352                   OLID4(rec->ur_id1));
2353
2354         de_tgt_dir = mds_id2locked_dentry(obd, rec->ur_id2, NULL, LCK_EX,
2355                                           tgt_dir_lockh, &update_mode,
2356                                           rec->ur_name, rec->ur_namelen - 1,
2357                                           MDS_INODELOCK_UPDATE);
2358         if (IS_ERR(de_tgt_dir))
2359                 GOTO(cleanup, rc = PTR_ERR(de_tgt_dir));
2360         cleanup_phase = 1;
2361
2362         OBD_ALLOC(op_data, sizeof(*op_data));
2363         if (op_data == NULL)
2364                 GOTO(cleanup, rc = -ENOMEM);
2365
2366         memset(op_data, 0, sizeof(*op_data));
2367         op_data->id1 = *(rec->ur_id1);
2368         rc = md_link(mds->mds_md_exp, op_data, &request);
2369         OBD_FREE(op_data, sizeof(*op_data));
2370
2371         if (request)
2372                 ptlrpc_req_finished(request);
2373         if (rc)
2374                 GOTO(cleanup, rc);
2375
2376         cleanup_phase = 2;
2377
2378         OBD_FAIL_WRITE(OBD_FAIL_MDS_REINT_LINK_WRITE, de_tgt_dir->d_inode->i_sb);
2379
2380         handle = fsfilt_start(obd, de_tgt_dir->d_inode, FSFILT_OP_LINK, NULL);
2381         if (IS_ERR(handle)) {
2382                 rc = PTR_ERR(handle);
2383                 GOTO(cleanup, rc);
2384         }
2385         
2386         cleanup_phase = 3;
2387
2388         rc = fsfilt_add_dir_entry(obd, de_tgt_dir, rec->ur_name,
2389                                   rec->ur_namelen - 1, id_ino(rec->ur_id1),
2390                                   id_gen(rec->ur_id1), id_group(rec->ur_id1),
2391                                   id_fid(rec->ur_id1));
2392         EXIT;
2393 cleanup:
2394         rc = mds_finish_transno(mds, de_tgt_dir ? de_tgt_dir->d_inode : NULL,
2395                                 handle, req, rc, 0);
2396
2397         switch (cleanup_phase) {
2398                 case 3:
2399                         if (rc) {
2400                                 OBD_ALLOC(op_data, sizeof(*op_data));
2401                                 if (op_data != NULL) {
2402                                         request = NULL;
2403                                         memset(op_data, 0, sizeof(*op_data));
2404
2405                                         op_data->id1 = *(rec->ur_id1);
2406                                         op_data->create_mode = rec->ur_mode;
2407                                         
2408                                         rc = md_unlink(mds->mds_md_exp, op_data, &request);
2409                                         OBD_FREE(op_data, sizeof(*op_data));
2410                                         if (request)
2411                                                 ptlrpc_req_finished(request);
2412                                         if (rc) {
2413                                                 CERROR("error %d while dropping i_nlink on "
2414                                                        "remote inode\n", rc);
2415                                         }
2416                                 } else {
2417                                         CERROR("rc %d prevented dropping i_nlink on "
2418                                                "remote inode\n", -ENOMEM);
2419                                 }
2420                         }
2421                 case 2:
2422                 case 1:
2423                         if (rc) {
2424                                 ldlm_lock_decref(tgt_dir_lockh, LCK_EX);
2425 #ifdef S_PDIROPS
2426                                 ldlm_lock_decref(tgt_dir_lockh + 1, update_mode);
2427 #endif
2428                         } else {
2429                                 ptlrpc_save_lock(req, tgt_dir_lockh, LCK_EX);
2430 #ifdef S_PDIROPS
2431                                 ptlrpc_save_lock(req, tgt_dir_lockh + 1, update_mode);
2432 #endif
2433                         }
2434                         l_dput(de_tgt_dir);
2435                         break;
2436                 default:
2437                         CERROR("invalid cleanup_phase %d\n", cleanup_phase);
2438                         LBUG();
2439         }
2440         req->rq_status = rc;
2441         return 0;
2442 }
2443
2444 static int mds_reint_link(struct mds_update_record *rec, int offset,
2445                           struct ptlrpc_request *req,
2446                           struct lustre_handle *lh)
2447 {
2448         struct obd_device *obd = req->rq_export->exp_obd;
2449         struct dentry *de_src = NULL;
2450         struct dentry *de_tgt_dir = NULL;
2451         struct dentry *dchild = NULL;
2452         struct mds_obd *mds = mds_req2mds(req);
2453         struct lustre_handle *handle = NULL;
2454         struct lustre_handle tgt_dir_lockh[2] = {{0}, {0}}, src_lockh = {0};
2455         struct ldlm_res_id src_res_id = { .name = {0} };
2456         struct ldlm_res_id tgt_dir_res_id = { .name = {0} };
2457         ldlm_policy_data_t src_policy ={.l_inodebits = {MDS_INODELOCK_UPDATE}};
2458         ldlm_policy_data_t tgt_dir_policy =
2459                                        {.l_inodebits = {MDS_INODELOCK_UPDATE}};
2460         int rc = 0, cleanup_phase = 0;
2461 #ifdef S_PDIROPS
2462         int update_mode = 0;
2463 #endif
2464         ENTRY;
2465
2466         LASSERT(offset == 1);
2467
2468         DEBUG_REQ(D_INODE, req, "original "LPU64"/%u to "LPU64"/%u %s",
2469                   id_ino(rec->ur_id1), id_gen(rec->ur_id1),
2470                   id_ino(rec->ur_id2), id_gen(rec->ur_id2),
2471                   rec->ur_name);
2472
2473         MDS_CHECK_RESENT(req, mds_reconstruct_generic(req));
2474         MD_COUNTER_INCREMENT(obd, link);
2475         
2476         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_REINT_LINK))
2477                 GOTO(cleanup, rc = -ENOENT);
2478
2479         if (id_group(rec->ur_id1) != mds->mds_num) {
2480                 rc = mds_reint_link_to_remote(rec, offset, req, lh);
2481                 RETURN(rc);
2482         }
2483         
2484         if (rec->ur_namelen == 1) {
2485                 rc = mds_reint_link_acquire(rec, offset, req, lh);
2486                 RETURN(rc);
2487         }
2488
2489         /* Step 1: Lookup the source inode and target directory by ID */
2490         de_src = mds_id2dentry(obd, rec->ur_id1, NULL);
2491         if (IS_ERR(de_src))
2492                 GOTO(cleanup, rc = PTR_ERR(de_src));
2493
2494         cleanup_phase = 1; /* source dentry */
2495
2496         de_tgt_dir = mds_id2dentry(obd, rec->ur_id2, NULL);
2497         if (IS_ERR(de_tgt_dir)) {
2498                 rc = PTR_ERR(de_tgt_dir);
2499                 de_tgt_dir = NULL;
2500                 GOTO(cleanup, rc);
2501         }
2502
2503         cleanup_phase = 2; /* target directory dentry */
2504
2505         CDEBUG(D_INODE, "linking %*s/%s to inode %lu\n",
2506                de_tgt_dir->d_name.len, de_tgt_dir->d_name.name,
2507                rec->ur_name, de_src->d_inode->i_ino);
2508
2509         /* Step 2: Take the two locks */
2510         src_res_id.name[0] = id_fid(rec->ur_id1);
2511         src_res_id.name[1] = id_group(rec->ur_id1);
2512         tgt_dir_res_id.name[0] = id_fid(rec->ur_id2);
2513         tgt_dir_res_id.name[1] = id_group(rec->ur_id2);
2514         
2515 #ifdef S_PDIROPS
2516         if (IS_PDIROPS(de_tgt_dir->d_inode)) {
2517                 int flags = 0;
2518                 update_mode = mds_lock_mode_for_dir(obd, de_tgt_dir, LCK_EX);
2519                 if (update_mode) {
2520                         rc = ldlm_cli_enqueue(NULL, NULL, obd->obd_namespace,
2521                                               tgt_dir_res_id, LDLM_IBITS,
2522                                               &src_policy, update_mode, &flags,
2523                                               mds_blocking_ast,
2524                                               ldlm_completion_ast, NULL, NULL,
2525                                               NULL, 0, NULL, tgt_dir_lockh + 1);
2526                         if (rc != ELDLM_OK)
2527                                 GOTO(cleanup, rc = -ENOLCK);
2528                 }
2529
2530                 tgt_dir_res_id.name[2] = full_name_hash(rec->ur_name,
2531                                                         rec->ur_namelen - 1);
2532                 CDEBUG(D_INFO, "take lock on %lu:%lu:"LPX64"\n",
2533                        (unsigned long)id_fid(rec->ur_id2),
2534                        (unsigned long)id_group(rec->ur_id2),
2535                        tgt_dir_res_id.name[2]);
2536         }
2537 #endif
2538         rc = enqueue_ordered_locks(obd, &src_res_id, &src_lockh, LCK_EX,
2539                                    &src_policy, &tgt_dir_res_id, tgt_dir_lockh,
2540                                    LCK_EX, &tgt_dir_policy);
2541         if (rc)
2542                 GOTO(cleanup, rc);
2543
2544         cleanup_phase = 3; /* locks */
2545
2546         /* Step 3: Lookup the child */
2547         dchild = ll_lookup_one_len(rec->ur_name, de_tgt_dir, 
2548                                    rec->ur_namelen - 1);
2549         if (IS_ERR(dchild)) {
2550                 rc = PTR_ERR(dchild);
2551                 if (rc != -EPERM && rc != -EACCES)
2552                         CERROR("child lookup error %d\n", rc);
2553                 GOTO(cleanup, rc);
2554         }
2555
2556         cleanup_phase = 4; /* child dentry */
2557
2558         if (dchild->d_inode) {
2559                 CDEBUG(D_INODE, "child exists (dir %lu, name %s)\n",
2560                        de_tgt_dir->d_inode->i_ino, rec->ur_name);
2561                 rc = -EEXIST;
2562                 GOTO(cleanup, rc);
2563         }
2564
2565         /* Step 4: Do it. */
2566         OBD_FAIL_WRITE(OBD_FAIL_MDS_REINT_LINK_WRITE, de_src->d_inode->i_sb);
2567
2568         handle = fsfilt_start(obd, de_tgt_dir->d_inode, FSFILT_OP_LINK, NULL);
2569         if (IS_ERR(handle)) {
2570                 rc = PTR_ERR(handle);
2571                 GOTO(cleanup, rc);
2572         }
2573
2574         rc = vfs_link(de_src, de_tgt_dir->d_inode, dchild);
2575         if (rc && rc != -EPERM && rc != -EACCES)
2576                 CERROR("vfs_link error %d\n", rc);
2577 cleanup:
2578         rc = mds_finish_transno(mds, de_tgt_dir ? de_tgt_dir->d_inode : NULL,
2579                                 handle, req, rc, 0);
2580         EXIT;
2581
2582         switch (cleanup_phase) {
2583         case 4: /* child dentry */
2584                 l_dput(dchild);
2585         case 3: /* locks */
2586                 if (rc) {
2587                         ldlm_lock_decref(&src_lockh, LCK_EX);
2588                         ldlm_lock_decref(tgt_dir_lockh, LCK_EX);
2589                 } else {
2590                         ptlrpc_save_lock(req, &src_lockh, LCK_EX);
2591                         ptlrpc_save_lock(req, tgt_dir_lockh, LCK_EX);
2592                 }
2593         case 2: /* target dentry */
2594 #ifdef S_PDIROPS
2595                 if (tgt_dir_lockh[1].cookie && update_mode)
2596                         ldlm_lock_decref(tgt_dir_lockh + 1, update_mode);
2597 #endif
2598                 if (de_tgt_dir)
2599                         l_dput(de_tgt_dir);
2600         case 1: /* source dentry */
2601                 l_dput(de_src);
2602         case 0:
2603                 break;
2604         default:
2605                 CERROR("invalid cleanup_phase %d\n", cleanup_phase);
2606                 LBUG();
2607         }
2608         req->rq_status = rc;
2609         return 0;
2610 }
2611
2612 /* The idea here is that we need to get four locks in the end:
2613  * one on each parent directory, one on each child.  We need to take
2614  * these locks in some kind of order (to avoid deadlocks), and the order
2615  * I selected is "increasing resource number" order.  We need to look up
2616  * the children, however, before we know what the resource number(s) are.
2617  * Thus the following plan:
2618  *
2619  * 1,2. Look up the parents
2620  * 3,4. Look up the children
2621  * 5. Take locks on the parents and children, in order
2622  * 6. Verify that the children haven't changed since they were looked up
2623  *
2624  * If there was a race and the children changed since they were first looked
2625  * up, it is possible that mds_verify_child() will be able to just grab the
2626  * lock on the new child resource (if it has a higher resource than any other)
2627  * but we need to compare against not only its parent, but also against the
2628  * parent and child of the "other half" of the rename, hence maxres_{src,tgt}.
2629  *
2630  * We need the fancy igrab() on the child inodes because we aren't holding a
2631  * lock on the parent after the lookup is done, so dentry->d_inode may change
2632  * at any time, and igrab() itself doesn't like getting passed a NULL argument.
2633  */
2634 static int mds_get_parents_children_locked(struct obd_device *obd,
2635                                            struct mds_obd *mds,
2636                                            struct lustre_id *p1_id,
2637                                            struct dentry **de_srcdirp,
2638                                            struct lustre_id *p2_id,
2639                                            struct dentry **de_tgtdirp,
2640                                            int parent_mode,
2641                                            const char *old_name, int old_len,
2642                                            struct dentry **de_oldp,
2643                                            const char *new_name, int new_len,
2644                                            struct dentry **de_newp,
2645                                            struct lustre_handle *dlm_handles,
2646                                            int child_mode)
2647 {
2648         struct ldlm_res_id p1_res_id = { .name = {0} };
2649         struct ldlm_res_id p2_res_id = { .name = {0} };
2650         struct ldlm_res_id c1_res_id = { .name = {0} };
2651         struct ldlm_res_id c2_res_id = { .name = {0} };
2652         ldlm_policy_data_t p_policy = {.l_inodebits = {MDS_INODELOCK_UPDATE}};
2653         /* Only dentry should disappear, but the inode itself would be
2654            intact otherwise. */
2655         ldlm_policy_data_t c1_policy = {.l_inodebits = {MDS_INODELOCK_LOOKUP}};
2656         /* If something is going to be replaced, both dentry and inode locks are
2657            needed */
2658         ldlm_policy_data_t c2_policy = {.l_inodebits = {MDS_INODELOCK_FULL}};
2659         struct ldlm_res_id *maxres_src, *maxres_tgt;
2660         struct inode *inode;
2661         int rc = 0, cleanup_phase = 0;
2662         __u32 child_gen1 = 0;
2663         __u32 child_gen2 = 0;
2664         unsigned long child_ino1 = 0;
2665         unsigned long child_ino2 = 0;
2666         ENTRY;
2667
2668         /* Step 1: Lookup the source directory */
2669         *de_srcdirp = mds_id2dentry(obd, p1_id, NULL);
2670         if (IS_ERR(*de_srcdirp))
2671                 GOTO(cleanup, rc = PTR_ERR(*de_srcdirp));
2672
2673         cleanup_phase = 1; /* source directory dentry */
2674
2675         p1_res_id.name[0] = id_fid(p1_id);
2676         p1_res_id.name[1] = id_group(p1_id);
2677
2678         /* Step 2: Lookup the target directory */
2679         if (id_equal_stc(p1_id, p2_id)) {
2680                 *de_tgtdirp = dget(*de_srcdirp);
2681         } else {
2682                 *de_tgtdirp = mds_id2dentry(obd, p2_id, NULL);
2683                 if (IS_ERR(*de_tgtdirp)) {
2684                         rc = PTR_ERR(*de_tgtdirp);
2685                         *de_tgtdirp = NULL;
2686                         GOTO(cleanup, rc);
2687                 }
2688         }
2689
2690         cleanup_phase = 2; /* target directory dentry */
2691
2692         p2_res_id.name[0] = id_fid(p2_id);
2693         p2_res_id.name[1] = id_group(p2_id);
2694
2695 #ifdef S_PDIROPS
2696         dlm_handles[5].cookie = 0;
2697         dlm_handles[6].cookie = 0;
2698         
2699         if (IS_PDIROPS((*de_srcdirp)->d_inode)) {
2700                 /*
2701                  * get a temp lock on just fid, group to flush client cache and
2702                  * to protect dirs from concurrent splitting.
2703                  */
2704                 rc = enqueue_ordered_locks(obd, &p1_res_id, &dlm_handles[5],
2705                                            LCK_PW, &p_policy, &p2_res_id,
2706                                            &dlm_handles[6], LCK_PW, &p_policy);
2707                 if (rc != ELDLM_OK)
2708                         GOTO(cleanup, rc);
2709                 
2710                 p1_res_id.name[2] = full_name_hash(old_name, old_len - 1);
2711                 p2_res_id.name[2] = full_name_hash(new_name, new_len - 1);
2712
2713                 CDEBUG(D_INFO, "take locks on "
2714                        LPX64":"LPX64":"LPX64", "LPX64":"LPX64":"LPX64"\n",
2715                        p1_res_id.name[0], p1_res_id.name[1], p1_res_id.name[2],
2716                        p2_res_id.name[0], p2_res_id.name[1], p2_res_id.name[2]);
2717         }
2718         cleanup_phase = 3;
2719 #endif
2720
2721         /* Step 3: Lookup the source child entry */
2722         *de_oldp = ll_lookup_one_len(old_name, *de_srcdirp, 
2723                                      old_len - 1);
2724         if (IS_ERR(*de_oldp)) {
2725                 rc = PTR_ERR(*de_oldp);
2726                 CERROR("old child lookup error (%.*s): %d\n",
2727                        old_len - 1, old_name, rc);
2728                 GOTO(cleanup, rc);
2729         }
2730
2731         cleanup_phase = 4; /* original name dentry */
2732
2733         inode = (*de_oldp)->d_inode;
2734         if (inode != NULL) {
2735                 struct lustre_id sid;
2736                 
2737                 inode = igrab(inode);
2738                 if (inode == NULL)
2739                         GOTO(cleanup, rc = -ENOENT);
2740
2741                 down(&inode->i_sem);
2742                 rc = mds_read_inode_sid(obd, inode, &sid);
2743                 up(&inode->i_sem);
2744                 if (rc) {
2745                         CERROR("Can't read inode self id, inode %lu, "
2746                                "rc %d\n", inode->i_ino, rc);
2747                         iput(inode);
2748                         GOTO(cleanup, rc);
2749                 }
2750
2751                 child_ino1 = inode->i_ino;
2752                 child_gen1 = inode->i_generation;
2753                 c1_res_id.name[0] = id_fid(&sid);
2754                 c1_res_id.name[1] = id_group(&sid);
2755                 iput(inode);
2756         } else if ((*de_oldp)->d_flags & DCACHE_CROSS_REF) {
2757                 child_ino1 = (*de_oldp)->d_inum;
2758                 child_gen1 = (*de_oldp)->d_generation;
2759                 c1_res_id.name[0] = (*de_oldp)->d_fid;
2760                 c1_res_id.name[1] = (*de_oldp)->d_mdsnum;
2761         } else {
2762                 GOTO(cleanup, rc = -ENOENT);
2763         }
2764
2765         /* Step 4: Lookup the target child entry */
2766         *de_newp = ll_lookup_one_len(new_name, *de_tgtdirp, 
2767                                      new_len - 1);
2768         if (IS_ERR(*de_newp)) {
2769                 rc = PTR_ERR(*de_newp);
2770                 CERROR("new child lookup error (%.*s): %d\n",
2771                        old_len - 1, old_name, rc);
2772                 GOTO(cleanup, rc);
2773         }
2774
2775         cleanup_phase = 5; /* target dentry */
2776
2777         inode = (*de_newp)->d_inode;
2778         if (inode != NULL) {
2779                 struct lustre_id sid;
2780
2781                 inode = igrab(inode);
2782                 if (inode == NULL)
2783                         goto retry_locks;
2784
2785                 down(&inode->i_sem);
2786                 rc = mds_read_inode_sid(obd, inode, &sid);
2787                 up(&inode->i_sem);
2788                 if (rc) {
2789                         CERROR("Can't read inode self id, inode %lu, "
2790                                "rc %d\n", inode->i_ino, rc);
2791                         GOTO(cleanup, rc);
2792                 }
2793
2794                 child_ino2 = inode->i_ino;
2795                 child_gen2 = inode->i_generation;
2796                 c2_res_id.name[0] = id_fid(&sid);
2797                 c2_res_id.name[1] = id_group(&sid);
2798                 iput(inode);
2799         } else if ((*de_newp)->d_flags & DCACHE_CROSS_REF) {
2800                 child_ino2 = (*de_newp)->d_inum;
2801                 child_gen2 = (*de_newp)->d_generation;
2802                 c2_res_id.name[0] = (*de_newp)->d_fid;
2803                 c2_res_id.name[1] = (*de_newp)->d_mdsnum;
2804         }
2805
2806 retry_locks:
2807         /* Step 5: Take locks on the parents and child(ren) */
2808         maxres_src = &p1_res_id;
2809         maxres_tgt = &p2_res_id;
2810         cleanup_phase = 5; /* target dentry */
2811
2812         if (c1_res_id.name[0] != 0 && res_gt(&c1_res_id, &p1_res_id, NULL, NULL))
2813                 maxres_src = &c1_res_id;
2814         if (c2_res_id.name[0] != 0 && res_gt(&c2_res_id, &p2_res_id, NULL, NULL))
2815                 maxres_tgt = &c2_res_id;
2816
2817         rc = enqueue_4ordered_locks(obd, &p1_res_id, &dlm_handles[0], parent_mode,
2818                                     &p_policy,
2819                                     &p2_res_id, &dlm_handles[1], parent_mode,
2820                                     &p_policy,
2821                                     &c1_res_id, &dlm_handles[2], child_mode,
2822                                     &c1_policy,
2823                                     &c2_res_id, &dlm_handles[3], child_mode,
2824                                     &c2_policy);
2825         if (rc)
2826                 GOTO(cleanup, rc);
2827
2828         cleanup_phase = 6; /* parent and child(ren) locks */
2829
2830         /* Step 6a: Re-lookup source child to verify it hasn't changed */
2831         rc = mds_verify_child(obd, &p1_res_id, &dlm_handles[0], *de_srcdirp,
2832                               parent_mode, &c1_res_id, &dlm_handles[2],
2833                               de_oldp, child_mode, &c1_policy, old_name, old_len,
2834                               maxres_tgt, child_ino1, child_gen1);
2835         if (rc) {
2836                 if (c2_res_id.name[0] != 0)
2837                         ldlm_lock_decref(&dlm_handles[3], child_mode);
2838                 ldlm_lock_decref(&dlm_handles[1], parent_mode);
2839                 cleanup_phase = 5;
2840                 if (rc > 0)
2841                         goto retry_locks;
2842                 GOTO(cleanup, rc);
2843         }
2844
2845         if (!DENTRY_VALID(*de_oldp))
2846                 GOTO(cleanup, rc = -ENOENT);
2847
2848         /* Step 6b: Re-lookup target child to verify it hasn't changed */
2849         rc = mds_verify_child(obd, &p2_res_id, &dlm_handles[1], *de_tgtdirp,
2850                               parent_mode, &c2_res_id, &dlm_handles[3],
2851                               de_newp, child_mode, &c2_policy, new_name,
2852                               new_len, maxres_src, child_ino2, child_gen2);
2853         if (rc) {
2854                 ldlm_lock_decref(&dlm_handles[2], child_mode);
2855                 ldlm_lock_decref(&dlm_handles[0], parent_mode);
2856                 cleanup_phase = 5;
2857                 if (rc > 0)
2858                         goto retry_locks;
2859                 GOTO(cleanup, rc);
2860         }
2861
2862         EXIT;
2863 cleanup:
2864         if (rc) {
2865                 switch (cleanup_phase) {
2866                 case 6: /* child lock(s) */
2867                         if (c2_res_id.name[0] != 0)
2868                                 ldlm_lock_decref(&dlm_handles[3], child_mode);
2869                         if (c1_res_id.name[0] != 0)
2870                                 ldlm_lock_decref(&dlm_handles[2], child_mode);
2871                         if (dlm_handles[1].cookie != 0)
2872                                 ldlm_lock_decref(&dlm_handles[1], parent_mode);
2873                         if (dlm_handles[0].cookie != 0)
2874                                 ldlm_lock_decref(&dlm_handles[0], parent_mode);
2875                 case 5: /* target dentry */
2876                         l_dput(*de_newp);
2877                 case 4: /* source dentry */
2878                         l_dput(*de_oldp);
2879                 case 3:
2880 #ifdef S_PDIROPS
2881                         if (dlm_handles[5].cookie != 0)
2882                                 ldlm_lock_decref(&(dlm_handles[5]), LCK_PW);
2883                         if (dlm_handles[6].cookie != 0)
2884                                 ldlm_lock_decref(&(dlm_handles[6]), LCK_PW);
2885 #endif
2886                 case 2: /* target directory dentry */
2887                         l_dput(*de_tgtdirp);
2888                 case 1: /* source directry dentry */
2889                         l_dput(*de_srcdirp);
2890                 }
2891         }
2892
2893         return rc;
2894 }
2895
2896 /*
2897  * checks if dentry can be removed. This function also handles cross-ref
2898  * dentries.
2899  */
2900 static int mds_check_for_rename(struct obd_device *obd,
2901                                 struct dentry *dentry)
2902 {
2903         struct mds_obd *mds = &obd->u.mds;
2904         struct lustre_handle *rlockh;
2905         struct ptlrpc_request *req;
2906         struct mdc_op_data *op_data;
2907         struct lookup_intent it;
2908         int handle_size, rc = 0;
2909         ENTRY;
2910
2911         LASSERT(dentry != NULL);
2912
2913         if (dentry->d_inode) {
2914                 if (S_ISDIR(dentry->d_inode->i_mode) &&
2915                     !mds_is_dir_empty(obd, dentry))
2916                         rc = -ENOTEMPTY;
2917         } else {
2918                 LASSERT((dentry->d_flags & DCACHE_CROSS_REF));
2919                 handle_size = sizeof(struct lustre_handle);
2920         
2921                 OBD_ALLOC(rlockh, handle_size);
2922                 if (rlockh == NULL)
2923                         RETURN(-ENOMEM);
2924
2925                 memset(rlockh, 0, handle_size);
2926                 OBD_ALLOC(op_data, sizeof(*op_data));
2927                 if (op_data == NULL) {
2928                         OBD_FREE(rlockh, handle_size);
2929                         RETURN(-ENOMEM);
2930                 }
2931                 memset(op_data, 0, sizeof(*op_data));
2932                 mds_pack_dentry2id(obd, &op_data->id1, dentry, 1);
2933
2934                 it.it_op = IT_UNLINK;
2935                 OBD_ALLOC(it.d.fs_data, sizeof(struct lustre_intent_data));
2936                 if (!it.d.fs_data)
2937                         RETURN(-ENOMEM);
2938                 rc = md_enqueue(mds->mds_md_exp, LDLM_IBITS, &it, LCK_EX,
2939                                 op_data, rlockh, NULL, 0, ldlm_completion_ast,
2940                                 mds_blocking_ast, NULL);
2941                 OBD_FREE(op_data, sizeof(*op_data));
2942
2943
2944                 if (rc) {
2945                         OBD_FREE(it.d.fs_data,
2946                                  sizeof(struct lustre_intent_data));
2947                         RETURN(rc);
2948                 }
2949                 if (rlockh->cookie != 0)
2950                         ldlm_lock_decref(rlockh, LCK_EX);
2951                 
2952                 if (LUSTRE_IT(&it)->it_data) {
2953                         req = (struct ptlrpc_request *)LUSTRE_IT(&it)->it_data;
2954                         ptlrpc_req_finished(req);
2955                 }
2956
2957                 if (LUSTRE_IT(&it)->it_status)
2958                         rc = LUSTRE_IT(&it)->it_status;
2959                 OBD_FREE(it.d.fs_data, sizeof(struct lustre_intent_data));
2960                 OBD_FREE(rlockh, handle_size);
2961         }
2962         RETURN(rc);
2963 }
2964
2965 static int mds_add_local_dentry(struct mds_update_record *rec, int offset,
2966                                 struct ptlrpc_request *req, struct lustre_id *id,
2967                                 struct dentry *de_dir, struct dentry *de)
2968 {
2969         struct obd_device *obd = req->rq_export->exp_obd;
2970         struct mds_obd *mds = mds_req2mds(req);
2971         void *handle = NULL;
2972         int rc = 0;
2973         ENTRY;
2974
2975         if (de->d_inode) {
2976                 /*
2977                  * name exists and points to local inode try to unlink this name
2978                  * and create new one.
2979                  */
2980                 CDEBUG(D_OTHER, "%s: %s points to local inode %lu/%lu\n",
2981                        obd->obd_name, rec->ur_tgt, (unsigned long)de->d_inode->i_ino,
2982                        (unsigned long)de->d_inode->i_generation);
2983
2984                 /* checking if we can remove local dentry. */
2985                 rc = mds_check_for_rename(obd, de);
2986                 if (rc)
2987                         GOTO(cleanup, rc);
2988
2989                 handle = fsfilt_start(obd, de_dir->d_inode,
2990                                       FSFILT_OP_RENAME, NULL);
2991                 if (IS_ERR(handle))
2992                         GOTO(cleanup, rc = PTR_ERR(handle));
2993                 rc = fsfilt_del_dir_entry(req->rq_export->exp_obd, de);
2994                 if (rc)
2995                         GOTO(cleanup, rc);
2996         } else if (de->d_flags & DCACHE_CROSS_REF) {
2997                 CDEBUG(D_OTHER, "%s: %s points to remote inode %lu/%lu\n",
2998                        obd->obd_name, rec->ur_tgt, (unsigned long)de->d_mdsnum,
2999                         (unsigned long)de->d_fid);
3000
3001                 /* checking if we can remove local dentry. */
3002                 rc = mds_check_for_rename(obd, de);
3003                 if (rc)
3004                         GOTO(cleanup, rc);
3005
3006                 /*
3007                  * to be fully POSIX compatible, we should add one more check:
3008                  *
3009                  * if de_new is subdir of dir rec->ur_id1. If so - return
3010                  * -EINVAL.
3011                  *
3012                  * I do not know how to implement it right now, because
3013                  * inodes/dentries for new and old names lie on different MDS,
3014                  * so add this notice here just to make it visible for the rest
3015                  * of developers and do not forget about. And when this check
3016                  * will be added, del_cross_ref should gone, that is local
3017                  * dentry is able to be removed if all checks passed. --umka
3018                  */
3019
3020                 handle = fsfilt_start(obd, de_dir->d_inode,
3021                                       FSFILT_OP_RENAME, NULL);
3022                 if (IS_ERR(handle))
3023                         GOTO(cleanup, rc = PTR_ERR(handle));
3024                 rc = fsfilt_del_dir_entry(req->rq_export->exp_obd, de);
3025                 if (rc)
3026                         GOTO(cleanup, rc);
3027         } else {
3028                 /* name doesn't exist. the simplest case. */
3029                 handle = fsfilt_start(obd, de_dir->d_inode,
3030                                       FSFILT_OP_LINK, NULL);
3031                 if (IS_ERR(handle))
3032                         GOTO(cleanup, rc = PTR_ERR(handle));
3033         }
3034
3035         rc = fsfilt_add_dir_entry(obd, de_dir, rec->ur_tgt,
3036                                   rec->ur_tgtlen - 1, id_ino(id),
3037                                   id_gen(id), id_group(id), id_fid(id));
3038         if (rc) {
3039                 CERROR("add_dir_entry() returned error %d\n", rc);
3040                 GOTO(cleanup, rc);
3041         }
3042
3043         EXIT;
3044 cleanup:
3045         rc = mds_finish_transno(mds, de_dir ? de_dir->d_inode : NULL,
3046                                 handle, req, rc, 0);
3047
3048         return rc;
3049 }
3050
3051 static int mds_del_local_dentry(struct mds_update_record *rec, int offset,
3052                                 struct ptlrpc_request *req, struct dentry *de_dir,
3053                                 struct dentry *de)
3054 {
3055         struct obd_device *obd = req->rq_export->exp_obd;
3056         struct mds_obd *mds = mds_req2mds(req);
3057         void *handle = NULL;
3058         int rc = 0;
3059         ENTRY;
3060
3061         handle = fsfilt_start(obd, de_dir->d_inode, FSFILT_OP_UNLINK, NULL);
3062         if (IS_ERR(handle))
3063                 GOTO(cleanup, rc = PTR_ERR(handle));
3064         rc = fsfilt_del_dir_entry(obd, de);
3065         d_drop(de);
3066
3067         EXIT;
3068 cleanup:
3069         rc = mds_finish_transno(mds, de_dir ? de_dir->d_inode : NULL,
3070                                 handle, req, rc, 0);
3071         return rc;
3072 }
3073
3074 static int mds_reint_rename_create_name(struct mds_update_record *rec,
3075                                         int offset, struct ptlrpc_request *req)
3076 {
3077         struct lustre_handle parent_lockh[2] = {{0}, {0}};
3078         struct obd_device *obd = req->rq_export->exp_obd;
3079         struct mds_obd *mds = mds_req2mds(req);
3080         struct lustre_handle child_lockh = {0};
3081         struct dentry *de_tgtdir = NULL;
3082         struct dentry *de_new = NULL;
3083         int cleanup_phase = 0;
3084         int update_mode, rc = 0;
3085         ENTRY;
3086
3087         /*
3088          * another MDS executing rename operation has asked us to create target
3089          * name. such a creation should destroy existing target name.
3090          */
3091         CDEBUG(D_OTHER, "%s: request to create name %s for "DLID4"\n",
3092                obd->obd_name, rec->ur_tgt, OLID4(rec->ur_id1));
3093
3094         /* first, lookup the target */
3095         rc = mds_get_parent_child_locked(obd, mds, rec->ur_id2, parent_lockh,
3096                                          &de_tgtdir, LCK_PW, MDS_INODELOCK_UPDATE,
3097                                          &update_mode, rec->ur_tgt, rec->ur_tgtlen,
3098                                          &child_lockh, &de_new, LCK_EX,
3099                                          MDS_INODELOCK_LOOKUP);
3100         if (rc)
3101                 GOTO(cleanup, rc);
3102
3103         cleanup_phase = 1;
3104
3105         LASSERT(de_tgtdir);
3106         LASSERT(de_tgtdir->d_inode);
3107         LASSERT(de_new);
3108
3109         rc = mds_add_local_dentry(rec, offset, req, rec->ur_id1,
3110                                   de_tgtdir, de_new);
3111
3112         EXIT;
3113 cleanup:
3114         
3115         if (cleanup_phase == 1) {
3116 #ifdef S_PDIROPS
3117                 if (parent_lockh[1].cookie != 0)
3118                         ldlm_lock_decref(parent_lockh + 1, update_mode);
3119 #endif
3120                 ldlm_lock_decref(parent_lockh, LCK_PW);
3121                 if (child_lockh.cookie != 0)
3122                         ldlm_lock_decref(&child_lockh, LCK_EX);
3123                 l_dput(de_new);
3124                 l_dput(de_tgtdir);
3125         }
3126
3127         req->rq_status = rc;
3128         return 0;
3129 }
3130
3131 static int mds_reint_rename_to_remote(struct mds_update_record *rec, int offset,
3132                                       struct ptlrpc_request *req)
3133 {
3134         struct obd_device *obd = req->rq_export->exp_obd;
3135         struct ptlrpc_request *req2 = NULL;
3136         struct dentry *de_srcdir = NULL;
3137         struct dentry *de_old = NULL;
3138         struct mds_obd *mds = mds_req2mds(req);
3139         struct lustre_handle parent_lockh[2] = {{0}, {0}};
3140         struct lustre_handle child_lockh = {0};
3141         struct mdc_op_data *op_data;
3142         int update_mode, rc = 0;
3143         ENTRY;
3144
3145         CDEBUG(D_OTHER, "%s: move name %s onto another mds #%lu\n",
3146                obd->obd_name, rec->ur_name, (unsigned long)id_group(rec->ur_id2));
3147         
3148         OBD_ALLOC(op_data, sizeof(*op_data));
3149         if (op_data == NULL)
3150                 RETURN(-ENOMEM);
3151         memset(op_data, 0, sizeof(*op_data));
3152
3153         rc = mds_get_parent_child_locked(obd, mds, rec->ur_id1, parent_lockh,
3154                                          &de_srcdir, LCK_PW, MDS_INODELOCK_UPDATE,
3155                                          &update_mode, rec->ur_name, 
3156                                          rec->ur_namelen, &child_lockh, &de_old,
3157                                          LCK_EX, MDS_INODELOCK_LOOKUP);
3158         if (rc) {
3159                 OBD_FREE(op_data, sizeof(*op_data));
3160                 RETURN(rc);
3161         }
3162
3163         LASSERT(de_srcdir);
3164         LASSERT(de_srcdir->d_inode);
3165         LASSERT(de_old);
3166        
3167         /*
3168          * we already know the target should be created on another MDS so, we
3169          * have to request that MDS to do it.
3170          */
3171
3172         /* prepare source id */
3173         if (de_old->d_flags & DCACHE_CROSS_REF) {
3174                 LASSERT(de_old->d_inode == NULL);
3175                 CDEBUG(D_OTHER, "request to move remote name\n");
3176                 mds_pack_dentry2id(obd, &op_data->id1, de_old, 1);
3177         } else if (de_old->d_inode == NULL) {
3178                 /* oh, source doesn't exist */
3179                 OBD_FREE(op_data, sizeof(*op_data));
3180                 GOTO(cleanup, rc = -ENOENT);
3181         } else {
3182                 struct lustre_id sid;
3183                 struct inode *inode = de_old->d_inode;
3184                 
3185                 LASSERT(inode != NULL);
3186                 CDEBUG(D_OTHER, "request to move local name\n");
3187                 id_ino(&op_data->id1) = inode->i_ino;
3188                 id_group(&op_data->id1) = mds->mds_num;
3189                 id_gen(&op_data->id1) = inode->i_generation;
3190
3191                 down(&inode->i_sem);
3192                 rc = mds_read_inode_sid(obd, inode, &sid);
3193                 up(&inode->i_sem);
3194                 if (rc) {
3195                         CERROR("Can't read inode self id, "
3196                                "inode %lu, rc = %d\n",
3197                                inode->i_ino, rc);
3198                         GOTO(cleanup, rc);
3199                 }
3200
3201                 id_fid(&op_data->id1) = id_fid(&sid);
3202         }
3203
3204         op_data->id2 = *rec->ur_id2;
3205         rc = md_rename(mds->mds_md_exp, op_data, NULL, 0,
3206                        rec->ur_tgt, rec->ur_tgtlen - 1, &req2);
3207         OBD_FREE(op_data, sizeof(*op_data));
3208        
3209         if (rc)
3210                 GOTO(cleanup, rc);
3211         
3212         rc = mds_del_local_dentry(rec, offset, req, de_srcdir,
3213                                   de_old);
3214
3215         EXIT;
3216 cleanup:
3217         if (req2)
3218                 ptlrpc_req_finished(req2);
3219
3220 #ifdef S_PDIROPS
3221         if (parent_lockh[1].cookie != 0)
3222                 ldlm_lock_decref(parent_lockh + 1, update_mode);
3223 #endif
3224         ldlm_lock_decref(parent_lockh, LCK_PW);
3225         if (child_lockh.cookie != 0)
3226                 ldlm_lock_decref(&child_lockh, LCK_EX);
3227
3228         l_dput(de_old);
3229         l_dput(de_srcdir);
3230
3231         req->rq_status = rc;
3232         return 0;
3233 }
3234
3235 static int mds_reint_rename(struct mds_update_record *rec, int offset,
3236                             struct ptlrpc_request *req, struct lustre_handle *lockh)
3237 {
3238         struct obd_device *obd = req->rq_export->exp_obd;
3239         struct dentry *de_srcdir = NULL;
3240         struct dentry *de_tgtdir = NULL;
3241         struct dentry *de_old = NULL;
3242         struct dentry *de_new = NULL;
3243         struct inode *old_inode = NULL, *new_inode = NULL;
3244         struct mds_obd *mds = mds_req2mds(req);
3245         struct lustre_handle dlm_handles[7] = {{0},{0},{0},{0},{0},{0},{0}};
3246         struct mds_body *body = NULL;
3247         struct llog_create_locks *lcl = NULL;
3248         struct lov_mds_md *lmm = NULL;
3249         int rc = 0, cleanup_phase = 0;
3250         void *handle = NULL;
3251         ENTRY;
3252
3253         LASSERT(offset == 1);
3254
3255         DEBUG_REQ(D_INODE, req, "parent "DLID4" %s to "DLID4" %s",
3256                   OLID4(rec->ur_id1), rec->ur_name, OLID4(rec->ur_id2),
3257                   rec->ur_tgt);
3258
3259         MDS_CHECK_RESENT(req, mds_reconstruct_generic(req));
3260
3261         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY) {
3262                 DEBUG_REQ(D_HA, req, "rename replay\n");
3263                 memcpy(lustre_msg_buf(req->rq_repmsg, 2, 0),
3264                        lustre_msg_buf(req->rq_reqmsg, offset + 3, 0),
3265                        req->rq_repmsg->buflens[2]);
3266         }
3267
3268         MD_COUNTER_INCREMENT(obd, rename);
3269
3270         if (rec->ur_namelen == 1) {
3271                 rc = mds_reint_rename_create_name(rec, offset, req);
3272                 RETURN(rc);
3273         }
3274
3275         /* check if new name should be located on remote target. */
3276         if (id_group(rec->ur_id2) != mds->mds_num) {
3277                 rc = mds_reint_rename_to_remote(rec, offset, req);
3278                 RETURN(rc);
3279         }
3280         
3281         rc = mds_get_parents_children_locked(obd, mds, rec->ur_id1, &de_srcdir,
3282                                              rec->ur_id2, &de_tgtdir, LCK_PW,
3283                                              rec->ur_name, rec->ur_namelen,
3284                                              &de_old, rec->ur_tgt,
3285                                              rec->ur_tgtlen, &de_new,
3286                                              dlm_handles, LCK_EX);
3287         if (rc)
3288                 GOTO(cleanup, rc);
3289
3290         cleanup_phase = 1; /* parent(s), children, locks */
3291         old_inode = de_old->d_inode;
3292         new_inode = de_new->d_inode;
3293
3294         /* sanity check for src inode */
3295         if (de_old->d_flags & DCACHE_CROSS_REF) {
3296                 LASSERT(de_old->d_inode == NULL);
3297
3298                 /*
3299                  * in the case of cross-ref dir, we can perform this check only
3300                  * if child and parent lie on the same mds. This is because
3301                  * otherwise they can have the same inode numbers.
3302                  */
3303                 if (de_old->d_mdsnum == mds->mds_num) {
3304                         if (de_old->d_inum == de_srcdir->d_inode->i_ino ||
3305                             de_old->d_inum == de_tgtdir->d_inode->i_ino)
3306                                 GOTO(cleanup, rc = -EINVAL);
3307                 }
3308         } else {
3309                 LASSERT(de_old->d_inode != NULL);
3310                 if (de_old->d_inode->i_ino == de_srcdir->d_inode->i_ino ||
3311                     de_old->d_inode->i_ino == de_tgtdir->d_inode->i_ino)
3312                         GOTO(cleanup, rc = -EINVAL);
3313         }
3314
3315         /* sanity check for dest inode */
3316         if (de_new->d_flags & DCACHE_CROSS_REF) {
3317                 LASSERT(new_inode == NULL);
3318
3319                 /* the same check about target dentry. */
3320                 if (de_new->d_mdsnum == mds->mds_num) {
3321                         if (de_new->d_inum == de_srcdir->d_inode->i_ino ||
3322                             de_new->d_inum == de_tgtdir->d_inode->i_ino)
3323                                 GOTO(cleanup, rc = -EINVAL);
3324                 }
3325                 
3326                 /*
3327                  * regular files usualy do not have ->rename() implemented. But
3328                  * we handle only this case when @de_new is cross-ref entry,
3329                  * because in other cases it will be handled by vfs_rename().
3330                  */
3331                 if (de_old->d_inode && (!de_old->d_inode->i_op || 
3332                     !de_old->d_inode->i_op->rename))
3333                         GOTO(cleanup, rc = -EPERM);
3334         } else {
3335                 if (new_inode &&
3336                     (new_inode->i_ino == de_srcdir->d_inode->i_ino ||
3337                      new_inode->i_ino == de_tgtdir->d_inode->i_ino))
3338                         GOTO(cleanup, rc = -EINVAL);
3339
3340         }
3341         
3342         /*
3343          * check if inodes point to each other. This should be checked before
3344          * is_subdir() check, as for the same entries it will think that they
3345          * are subdirs.
3346          */
3347         if (!(de_old->d_flags & DCACHE_CROSS_REF) &&
3348             !(de_new->d_flags & DCACHE_CROSS_REF) &&
3349             old_inode == new_inode)
3350                 GOTO(cleanup, rc = 0);
3351
3352 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
3353         /*
3354          * check if we are moving old entry into its child. 2.6 does not check
3355          * for this in vfs_rename() anymore.
3356          */
3357         if (is_subdir(de_new, de_old))
3358                 GOTO(cleanup, rc = -EINVAL);
3359 #endif
3360         
3361         /*
3362          * if we are about to remove the target at first, pass the EA of that
3363          * inode to client to perform and cleanup on OST.
3364          */
3365         body = lustre_msg_buf(req->rq_repmsg, 0, sizeof (*body));
3366         LASSERT(body != NULL);
3367
3368         /* child i_alloc_sem protects orphan_dec_test && is_orphan race */
3369         if (new_inode) 
3370                 DOWN_READ_I_ALLOC_SEM(new_inode);
3371         
3372         cleanup_phase = 2; /* up(&new_inode->i_sem) when finished */
3373
3374         if (new_inode && ((S_ISDIR(new_inode->i_mode) && 
3375             new_inode->i_nlink == 2) ||
3376             new_inode->i_nlink == 1)) {
3377                 if (mds_orphan_open_count(new_inode) > 0) {
3378                         /* need to lock pending_dir before transaction */
3379                         down(&mds->mds_pending_dir->d_inode->i_sem);
3380                         cleanup_phase = 3; /* up(&pending_dir->i_sem) */
3381                 } else if (S_ISREG(new_inode->i_mode)) {
3382                         mds_pack_inode2body(obd, body, new_inode, 0);
3383                         mds_pack_md(obd, req->rq_repmsg, 1, body, 
3384                                     new_inode, MDS_PACK_MD_LOCK, 0);
3385                  }
3386         }
3387
3388         OBD_FAIL_WRITE(OBD_FAIL_MDS_REINT_RENAME_WRITE,
3389                        de_srcdir->d_inode->i_sb);
3390
3391         if (de_old->d_flags & DCACHE_CROSS_REF) {
3392                 struct lustre_id old_id;
3393
3394                 mds_pack_dentry2id(obd, &old_id, de_old, 1);
3395
3396                 rc = mds_add_local_dentry(rec, offset, req, &old_id,
3397                                           de_tgtdir, de_new);
3398                 if (rc)
3399                         GOTO(cleanup, rc);
3400
3401                 rc = mds_del_local_dentry(rec, offset, req, de_srcdir,
3402                                           de_old);
3403                 GOTO(cleanup, rc);
3404         }
3405
3406         lmm = lustre_msg_buf(req->rq_repmsg, 1, 0);
3407         handle = fsfilt_start_log(obd, de_tgtdir->d_inode, FSFILT_OP_RENAME,
3408                                   NULL, le32_to_cpu(lmm->lmm_stripe_count));
3409
3410         if (IS_ERR(handle))
3411                 GOTO(cleanup, rc = PTR_ERR(handle));
3412
3413         lock_kernel();
3414         de_old->d_fsdata = req;
3415         de_new->d_fsdata = req;
3416         rc = vfs_rename(de_srcdir->d_inode, de_old, de_tgtdir->d_inode, de_new);
3417         unlock_kernel();
3418
3419         if (rc == 0 && new_inode != NULL && new_inode->i_nlink == 0) {
3420                 if (mds_orphan_open_count(new_inode) > 0)
3421                         rc = mds_orphan_add_link(rec, obd, de_new);
3422
3423                 if (rc == 1)
3424                         GOTO(cleanup, rc = 0);
3425
3426                 if (!S_ISREG(new_inode->i_mode))
3427                         GOTO(cleanup, rc);
3428
3429                 if (!(body->valid & OBD_MD_FLEASIZE)) {
3430                         body->valid |= (OBD_MD_FLSIZE | OBD_MD_FLBLOCKS |
3431                                         OBD_MD_FLATIME | OBD_MD_FLMTIME);
3432                 } else if (mds_log_op_unlink(obd, new_inode,
3433                                              lustre_msg_buf(req->rq_repmsg,1,0),
3434                                              req->rq_repmsg->buflens[1],
3435                                              lustre_msg_buf(req->rq_repmsg,2,0),
3436                                              req->rq_repmsg->buflens[2], 
3437                                              &lcl) > 0) {
3438                         body->valid |= OBD_MD_FLCOOKIE;
3439                 }
3440         }
3441
3442         EXIT;
3443 cleanup:
3444         rc = mds_finish_transno(mds, (de_tgtdir ? de_tgtdir->d_inode : NULL),
3445                                 handle, req, rc, 0);
3446
3447         switch (cleanup_phase) {
3448         case 3:
3449                 up(&mds->mds_pending_dir->d_inode->i_sem);
3450         case 2:
3451                 if (new_inode)
3452                         UP_READ_I_ALLOC_SEM(new_inode);
3453         case 1:
3454 #ifdef S_PDIROPS
3455                 if (dlm_handles[5].cookie != 0)
3456                         ldlm_lock_decref(&(dlm_handles[5]), LCK_PW);
3457                 if (dlm_handles[6].cookie != 0)
3458                         ldlm_lock_decref(&(dlm_handles[6]), LCK_PW);
3459 #endif
3460                 if (lcl != NULL)
3461                         ptlrpc_save_llog_lock(req, lcl);
3462
3463                 if (rc) {
3464                         if (dlm_handles[3].cookie != 0)
3465                                 ldlm_lock_decref(&(dlm_handles[3]), LCK_EX);
3466                         ldlm_lock_decref(&(dlm_handles[2]), LCK_EX);
3467                         ldlm_lock_decref(&(dlm_handles[1]), LCK_PW);
3468                         ldlm_lock_decref(&(dlm_handles[0]), LCK_PW);
3469                 } else {
3470                         if (dlm_handles[3].cookie != 0)
3471                                 ptlrpc_save_lock(req,&(dlm_handles[3]), LCK_EX);
3472                         ptlrpc_save_lock(req, &(dlm_handles[2]), LCK_EX);
3473                         ptlrpc_save_lock(req, &(dlm_handles[1]), LCK_PW);
3474                         ptlrpc_save_lock(req, &(dlm_handles[0]), LCK_PW);
3475                 }
3476                 l_dput(de_new);
3477                 l_dput(de_old);
3478                 l_dput(de_tgtdir);
3479                 l_dput(de_srcdir);
3480         case 0:
3481                 break;
3482         default:
3483                 CERROR("invalid cleanup_phase %d\n", cleanup_phase);
3484                 LBUG();
3485         }
3486         req->rq_status = rc;
3487         return 0;
3488 }
3489
3490 typedef int (*mds_reinter)(struct mds_update_record *, int offset,
3491                            struct ptlrpc_request *, struct lustre_handle *);
3492
3493 static mds_reinter reinters[REINT_MAX + 1] = {
3494         [REINT_SETATTR] mds_reint_setattr,
3495         [REINT_CREATE] mds_reint_create,
3496         [REINT_LINK] mds_reint_link,
3497         [REINT_UNLINK] mds_reint_unlink,
3498         [REINT_RENAME] mds_reint_rename,
3499         [REINT_OPEN] mds_open
3500 };
3501
3502 int mds_reint_rec(struct mds_update_record *rec, int offset,
3503                   struct ptlrpc_request *req, struct lustre_handle *lockh)
3504 {
3505         struct obd_device *obd = req->rq_export->exp_obd;
3506         struct lvfs_run_ctxt saved;
3507         int rc;
3508
3509         /* checked by unpacker */
3510         LASSERT(rec->ur_opcode <= REINT_MAX &&
3511                 reinters[rec->ur_opcode] != NULL);
3512
3513         push_ctxt(&saved, &obd->obd_lvfs_ctxt, &rec->ur_uc);
3514         rc = reinters[rec->ur_opcode] (rec, offset, req, lockh);
3515         pop_ctxt(&saved, &obd->obd_lvfs_ctxt, &rec->ur_uc);
3516
3517         return rc;
3518 }