Whamcloud - gitweb
96ba59decf634abf9c009ce602ef7d2c9987f915
[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-2005 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 the Lustre file system, http://www.lustre.org
13  *   Lustre is a trademark of Cluster File Systems, Inc.
14  *
15  *   You may have signed or agreed to another license before downloading
16  *   this software.  If so, you are bound by the terms and conditions
17  *   of that agreement, and the following does not apply to you.  See the
18  *   LICENSE file included with this distribution for more information.
19  *
20  *   If you did not agree to a different license, then this copy of Lustre
21  *   is open source software; you can redistribute it and/or modify it
22  *   under the terms of version 2 of the GNU General Public License as
23  *   published by the Free Software Foundation.
24  *
25  *   In either case, Lustre is distributed in the hope that it will be
26  *   useful, but WITHOUT ANY WARRANTY; without even the implied warranty
27  *   of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
28  *   license text for more details.
29  */
30
31 #ifndef EXPORT_SYMTAB
32 # define EXPORT_SYMTAB
33 #endif
34 #define DEBUG_SUBSYSTEM S_MDS
35
36 #include <linux/fs.h>
37 #include <obd_support.h>
38 #include <obd_class.h>
39 #include <obd.h>
40 #include <lustre_lib.h>
41 #include <lustre/lustre_idl.h>
42 #include <lustre_mds.h>
43 #include <lustre_dlm.h>
44 #include <lustre_fsfilt.h>
45 #include <lustre_ucache.h>
46
47 #include "mds_internal.h"
48
49 void mds_commit_cb(struct obd_device *obd, __u64 transno, void *data,
50                    int error)
51 {
52         obd_transno_commit_cb(obd, transno, error);
53 }
54
55 struct mds_logcancel_data {
56         struct lov_mds_md      *mlcd_lmm;
57         int                     mlcd_size;
58         int                     mlcd_cookielen;
59         int                     mlcd_eadatalen;
60         struct llog_cookie      mlcd_cookies[0];
61 };
62
63
64 static void mds_cancel_cookies_cb(struct obd_device *obd, __u64 transno,
65                                   void *cb_data, int error)
66 {
67         struct mds_logcancel_data *mlcd = cb_data;
68         struct lov_stripe_md *lsm = NULL;
69         struct llog_ctxt *ctxt;
70         int rc;
71
72         obd_transno_commit_cb(obd, transno, error);
73
74         CDEBUG(D_HA, "cancelling %d cookies\n",
75                (int)(mlcd->mlcd_cookielen / sizeof(*mlcd->mlcd_cookies)));
76
77         rc = obd_unpackmd(obd->u.mds.mds_osc_exp, &lsm, mlcd->mlcd_lmm, 
78                           mlcd->mlcd_eadatalen);
79         if (rc < 0) {
80                 CERROR("bad LSM cancelling %d log cookies: rc %d\n",
81                        (int)(mlcd->mlcd_cookielen/sizeof(*mlcd->mlcd_cookies)),
82                        rc);
83         } else {
84                 ///* XXX 0 normally, SENDNOW for debug */);
85                 rc = obd_checkmd(obd->u.mds.mds_osc_exp, obd->obd_self_export,
86                                  lsm);
87                 if (rc)
88                         CERROR("Can not revalidate lsm %p \n", lsm);
89
90                 ctxt = llog_get_context(obd,mlcd->mlcd_cookies[0].lgc_subsys+1);
91                 rc = llog_cancel(ctxt, lsm, mlcd->mlcd_cookielen /
92                                                 sizeof(*mlcd->mlcd_cookies),
93                                  mlcd->mlcd_cookies, OBD_LLOG_FL_SENDNOW);
94                 if (rc)
95                         CERROR("error cancelling %d log cookies: rc %d\n",
96                                (int)(mlcd->mlcd_cookielen /
97                                      sizeof(*mlcd->mlcd_cookies)), rc);
98         }
99
100         OBD_FREE(mlcd, mlcd->mlcd_size);
101 }
102
103 /* Assumes caller has already pushed us into the kernel context. */
104 int mds_finish_transno(struct mds_obd *mds, struct inode *inode, void *handle,
105                        struct ptlrpc_request *req, int rc, __u32 op_data)
106 {
107         struct mds_export_data *med = &req->rq_export->exp_mds_data;
108         struct mds_client_data *mcd = med->med_mcd;
109         struct obd_device *obd = req->rq_export->exp_obd;
110         __u64 transno, prev_transno;
111         int err;
112         loff_t off;
113         int log_pri = D_HA;
114         ENTRY;
115
116         if (IS_ERR(handle)) {
117                 LASSERT(rc != 0);
118                 RETURN(rc);
119         }
120
121         /* if the export has already been failed, we have no last_rcvd slot */
122         if (req->rq_export->exp_failed) {
123                 CWARN("commit transaction for disconnected client %s: rc %d\n",
124                       req->rq_export->exp_client_uuid.uuid, rc);
125                 if (rc == 0)
126                         rc = -ENOTCONN;
127                 if (handle)
128                         GOTO(commit, rc);
129                 RETURN(rc);
130         }
131
132         if (handle == NULL) {
133                 /* if we're starting our own xaction, use our own inode */
134                 inode = mds->mds_rcvd_filp->f_dentry->d_inode;
135                 handle = fsfilt_start(obd, inode, FSFILT_OP_SETATTR, NULL);
136                 if (IS_ERR(handle)) {
137                         CERROR("fsfilt_start: %ld\n", PTR_ERR(handle));
138                         RETURN(PTR_ERR(handle));
139                 }
140         }
141
142         off = med->med_lr_off;
143
144         transno = lustre_msg_get_transno(req->rq_reqmsg);
145         if (rc != 0) {
146                 if (transno != 0) {
147                         CERROR("%s: replay %s transno "LPU64" failed: rc %d\n",
148                                obd->obd_name,
149                                libcfs_nid2str(req->rq_export->exp_connection->c_peer.nid),
150                                transno, rc);
151                         transno = 0;
152                 }
153         } else if (transno == 0) {
154                 spin_lock(&mds->mds_transno_lock);
155                 transno = ++mds->mds_last_transno;
156                 spin_unlock(&mds->mds_transno_lock);
157         } else {
158                 spin_lock(&mds->mds_transno_lock);
159                 if (transno > mds->mds_last_transno)
160                         mds->mds_last_transno = transno;
161                 spin_unlock(&mds->mds_transno_lock);
162         }
163
164         req->rq_transno = transno;
165         lustre_msg_set_transno(req->rq_repmsg, transno);
166         if (lustre_msg_get_opc(req->rq_reqmsg) == MDS_CLOSE) {
167                 prev_transno = le64_to_cpu(mcd->mcd_last_close_transno);
168                 mcd->mcd_last_close_transno = cpu_to_le64(transno);
169                 mcd->mcd_last_close_xid = cpu_to_le64(req->rq_xid);
170                 mcd->mcd_last_close_result = cpu_to_le32(rc);
171                 mcd->mcd_last_close_data = cpu_to_le32(op_data);
172         } else {
173                 prev_transno = le64_to_cpu(mcd->mcd_last_transno);
174                 mcd->mcd_last_transno = cpu_to_le64(transno);
175                 mcd->mcd_last_xid = cpu_to_le64(req->rq_xid);
176                 mcd->mcd_last_result = cpu_to_le32(rc);
177                 mcd->mcd_last_data = cpu_to_le32(op_data);
178         }
179         /* update the server data to not lose the greatest transno. Bug 11125 */
180         if ((transno == 0) && (prev_transno == mds->mds_last_transno))
181                 mds_update_server_data(obd, 0);
182
183         if (off <= 0) {
184                 CERROR("client idx %d has offset %lld\n", med->med_lr_idx, off);
185                 err = -EINVAL;
186         } else {
187                 fsfilt_add_journal_cb(req->rq_export->exp_obd, transno, handle,
188                                       mds_commit_cb, NULL);
189                 err = fsfilt_write_record(obd, mds->mds_rcvd_filp, mcd,
190                                           sizeof(*mcd), &off,
191                                           req->rq_export->exp_need_sync);
192         }
193
194         if (err) {
195                 log_pri = D_ERROR;
196                 if (rc == 0)
197                         rc = err;
198         }
199
200         DEBUG_REQ(log_pri, req,
201                   "wrote trans #"LPU64" rc %d client %s at idx %u: err = %d",
202                   transno, rc, mcd->mcd_uuid, med->med_lr_idx, err);
203
204         err = mds_lov_write_objids(obd);
205         if (err) {
206                 log_pri = D_ERROR;
207                 if (rc == 0)
208                         rc = err;
209         }
210         CDEBUG(log_pri, "wrote objids: err = %d\n", err);
211
212 commit:
213         err = fsfilt_commit(obd, inode, handle, 0);
214         if (err) {
215                 CERROR("error committing transaction: %d\n", err);
216                 if (!rc)
217                         rc = err;
218         }
219
220         RETURN(rc);
221 }
222
223 /* this gives the same functionality as the code between
224  * sys_chmod and inode_setattr
225  * chown_common and inode_setattr
226  * utimes and inode_setattr
227  */
228 int mds_fix_attr(struct inode *inode, struct mds_update_record *rec)
229 {
230         time_t now = CURRENT_SECONDS;
231         struct iattr *attr = &rec->ur_iattr;
232         unsigned int ia_valid = attr->ia_valid;
233         int error;
234         ENTRY;
235
236         if (ia_valid & ATTR_RAW)
237                 attr->ia_valid &= ~ATTR_RAW;
238
239         if (!(ia_valid & ATTR_CTIME_SET))
240                 LTIME_S(attr->ia_ctime) = now;
241         else
242                 attr->ia_valid &= ~ATTR_CTIME_SET;
243         if (!(ia_valid & ATTR_ATIME_SET))
244                 LTIME_S(attr->ia_atime) = now;
245         if (!(ia_valid & ATTR_MTIME_SET))
246                 LTIME_S(attr->ia_mtime) = now;
247
248         if (IS_IMMUTABLE(inode) || IS_APPEND(inode))
249                 RETURN((attr->ia_valid & ~ATTR_ATTR_FLAG) ? -EPERM : 0);
250
251         /* times */
252         if ((ia_valid & (ATTR_MTIME|ATTR_ATIME)) == (ATTR_MTIME|ATTR_ATIME)) {
253                 if (current->fsuid != inode->i_uid &&
254                     (error = ll_permission(inode, MAY_WRITE, NULL)) != 0)
255                         RETURN(error);
256         }
257
258         if (ia_valid & ATTR_SIZE &&
259             /* NFSD hack for open(O_CREAT|O_TRUNC)=mknod+truncate (bug 5781) */
260             !(rec->ur_uc.luc_fsuid == inode->i_uid &&
261               ia_valid & MDS_OPEN_OWNEROVERRIDE)) {
262                 if ((error = ll_permission(inode, MAY_WRITE, NULL)) != 0)
263                         RETURN(error);
264         }
265
266         if (ia_valid & (ATTR_UID | ATTR_GID)) {
267                 /* chown */
268                 error = -EPERM;
269                 if (IS_IMMUTABLE(inode) || IS_APPEND(inode))
270                         RETURN(-EPERM);
271                 if (attr->ia_uid == (uid_t) -1)
272                         attr->ia_uid = inode->i_uid;
273                 if (attr->ia_gid == (gid_t) -1)
274                         attr->ia_gid = inode->i_gid;
275                 if (!(ia_valid & ATTR_MODE))
276                         attr->ia_mode = inode->i_mode;
277                 /*
278                  * If the user or group of a non-directory has been
279                  * changed by a non-root user, remove the setuid bit.
280                  * 19981026 David C Niemi <niemi@tux.org>
281                  *
282                  * Changed this to apply to all users, including root,
283                  * to avoid some races. This is the behavior we had in
284                  * 2.0. The check for non-root was definitely wrong
285                  * for 2.2 anyway, as it should have been using
286                  * CAP_FSETID rather than fsuid -- 19990830 SD.
287                  */
288                 if ((inode->i_mode & S_ISUID) == S_ISUID &&
289                     !S_ISDIR(inode->i_mode)) {
290                         attr->ia_mode &= ~S_ISUID;
291                         attr->ia_valid |= ATTR_MODE;
292                 }
293                 /*
294                  * Likewise, if the user or group of a non-directory
295                  * has been changed by a non-root user, remove the
296                  * setgid bit UNLESS there is no group execute bit
297                  * (this would be a file marked for mandatory
298                  * locking).  19981026 David C Niemi <niemi@tux.org>
299                  *
300                  * Removed the fsuid check (see the comment above) --
301                  * 19990830 SD.
302                  */
303                 if (((inode->i_mode & (S_ISGID | S_IXGRP)) ==
304                      (S_ISGID | S_IXGRP)) && !S_ISDIR(inode->i_mode)) {
305                         attr->ia_mode &= ~S_ISGID;
306                         attr->ia_valid |= ATTR_MODE;
307                 }
308         } else if (ia_valid & ATTR_MODE) {
309                 int mode = attr->ia_mode;
310                 /* chmod */
311                 if (attr->ia_mode == (umode_t)-1)
312                         mode = inode->i_mode;
313                 attr->ia_mode =
314                         (mode & S_IALLUGO) | (inode->i_mode & ~S_IALLUGO);
315         }
316         RETURN(0);
317 }
318
319 void mds_steal_ack_locks(struct ptlrpc_request *req)
320 {
321         struct obd_export         *exp = req->rq_export;
322         struct list_head          *tmp;
323         struct ptlrpc_reply_state *oldrep;
324         struct ptlrpc_service     *svc;
325         int                        i;
326
327         /* CAVEAT EMPTOR: spinlock order */
328         spin_lock(&exp->exp_lock);
329         list_for_each (tmp, &exp->exp_outstanding_replies) {
330                 oldrep = list_entry(tmp, struct ptlrpc_reply_state,rs_exp_list);
331
332                 if (oldrep->rs_xid != req->rq_xid)
333                         continue;
334
335                 if (lustre_msg_get_opc(oldrep->rs_msg) !=
336                     lustre_msg_get_opc(req->rq_reqmsg))
337                         CERROR ("Resent req xid "LPX64" has mismatched opc: "
338                                 "new %d old %d\n", req->rq_xid,
339                                 lustre_msg_get_opc(req->rq_reqmsg),
340                                 lustre_msg_get_opc(oldrep->rs_msg));
341
342                 svc = oldrep->rs_service;
343                 spin_lock (&svc->srv_lock);
344
345                 list_del_init (&oldrep->rs_exp_list);
346
347                 CWARN("Stealing %d locks from rs %p x"LPD64".t"LPD64
348                       " o%d NID %s\n",
349                       oldrep->rs_nlocks, oldrep,
350                       oldrep->rs_xid, oldrep->rs_transno,
351                       lustre_msg_get_opc(oldrep->rs_msg),
352                       libcfs_nid2str(exp->exp_connection->c_peer.nid));
353
354                 for (i = 0; i < oldrep->rs_nlocks; i++)
355                         ptlrpc_save_lock(req,
356                                          &oldrep->rs_locks[i],
357                                          oldrep->rs_modes[i]);
358                 oldrep->rs_nlocks = 0;
359
360                 DEBUG_REQ(D_HA, req, "stole locks for");
361                 ptlrpc_schedule_difficult_reply (oldrep);
362
363                 spin_unlock (&svc->srv_lock);
364                 break;
365         }
366         spin_unlock(&exp->exp_lock);
367 }
368
369 void mds_req_from_mcd(struct ptlrpc_request *req, struct mds_client_data *mcd)
370 {
371         if (lustre_msg_get_opc(req->rq_reqmsg) == MDS_CLOSE) {
372                 req->rq_transno = le64_to_cpu(mcd->mcd_last_close_transno);
373                 lustre_msg_set_transno(req->rq_repmsg, req->rq_transno);
374                 req->rq_status = le32_to_cpu(mcd->mcd_last_close_result);
375                 lustre_msg_set_status(req->rq_repmsg, req->rq_status);
376         } else {
377                 req->rq_transno = le64_to_cpu(mcd->mcd_last_transno);
378                 lustre_msg_set_transno(req->rq_repmsg, req->rq_transno);
379                 req->rq_status = le32_to_cpu(mcd->mcd_last_result);
380                 lustre_msg_set_status(req->rq_repmsg, req->rq_status);
381         }
382         DEBUG_REQ(D_HA, req, "restoring transno "LPD64"/status %d",
383                   req->rq_transno, req->rq_status);
384
385         mds_steal_ack_locks(req);
386 }
387
388 static void reconstruct_reint_setattr(struct mds_update_record *rec,
389                                       int offset, struct ptlrpc_request *req)
390 {
391         struct mds_export_data *med = &req->rq_export->exp_mds_data;
392         struct mds_obd *obd = &req->rq_export->exp_obd->u.mds;
393         struct dentry *de;
394         struct mds_body *body;
395
396         mds_req_from_mcd(req, med->med_mcd);
397
398         de = mds_fid2dentry(obd, rec->ur_fid1, NULL);
399         if (IS_ERR(de)) {
400                 LASSERT(PTR_ERR(de) == req->rq_status);
401                 return;
402         }
403
404         body = lustre_msg_buf(req->rq_repmsg, offset, sizeof(*body));
405         mds_pack_inode2fid(&body->fid1, de->d_inode);
406         mds_pack_inode2body(body, de->d_inode);
407
408         /* Don't return OST-specific attributes if we didn't just set them */
409         if (rec->ur_iattr.ia_valid & ATTR_SIZE)
410                 body->valid |= OBD_MD_FLSIZE | OBD_MD_FLBLOCKS;
411         if (rec->ur_iattr.ia_valid & (ATTR_MTIME | ATTR_MTIME_SET))
412                 body->valid |= OBD_MD_FLMTIME;
413         if (rec->ur_iattr.ia_valid & (ATTR_ATIME | ATTR_ATIME_SET))
414                 body->valid |= OBD_MD_FLATIME;
415
416         l_dput(de);
417 }
418
419 int mds_osc_setattr_async(struct obd_device *obd, struct inode *inode,
420                           struct lov_mds_md *lmm, int lmm_size,
421                           struct llog_cookie *logcookies, struct ll_fid *fid)
422 {
423         struct mds_obd *mds = &obd->u.mds;
424         struct obd_trans_info oti = { 0 };
425         struct obd_info oinfo = { { { 0 } } };
426         int rc;
427         ENTRY;
428
429         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_OST_SETATTR))
430                 RETURN(0);
431
432         /* first get memory EA */
433         oinfo.oi_oa = obdo_alloc();
434         if (!oinfo.oi_oa)
435                 RETURN(-ENOMEM);
436
437         LASSERT(lmm);
438
439         rc = obd_unpackmd(mds->mds_osc_exp, &oinfo.oi_md, lmm, lmm_size);
440         if (rc < 0) {
441                 CERROR("Error unpack md %p for inode %lu\n", lmm, inode->i_ino);
442                 GOTO(out, rc);
443         }
444
445         rc = obd_checkmd(mds->mds_osc_exp, obd->obd_self_export, oinfo.oi_md);
446         if (rc) {
447                 CERROR("Error revalidate lsm %p \n", oinfo.oi_md);
448                 GOTO(out, rc);
449         }
450
451         /* then fill oa */
452         obdo_from_inode(oinfo.oi_oa, inode, OBD_MD_FLUID | OBD_MD_FLGID);
453         oinfo.oi_oa->o_valid |= OBD_MD_FLID;
454         oinfo.oi_oa->o_id = oinfo.oi_md->lsm_object_id;
455         if (logcookies) {
456                 oinfo.oi_oa->o_valid |= OBD_MD_FLCOOKIE;
457                 oti.oti_logcookies = logcookies;
458         }
459
460         LASSERT(fid != NULL);
461         oinfo.oi_oa->o_fid = fid->id;
462         oinfo.oi_oa->o_generation = fid->generation;
463         oinfo.oi_oa->o_valid |= OBD_MD_FLFID | OBD_MD_FLGENER;
464
465         /* do async setattr from mds to ost not waiting for responses. */
466         rc = obd_setattr_async(mds->mds_osc_exp, &oinfo, &oti, NULL);
467         if (rc)
468                 CDEBUG(D_INODE, "mds to ost setattr objid 0x"LPX64
469                        " on ost error %d\n", oinfo.oi_md->lsm_object_id, rc);
470 out:
471         if (oinfo.oi_md)
472                 obd_free_memmd(mds->mds_osc_exp, &oinfo.oi_md);
473         obdo_free(oinfo.oi_oa);
474         RETURN(rc);
475 }
476
477 /* In the raw-setattr case, we lock the child inode.
478  * In the write-back case or if being called from open, the client holds a lock
479  * already.
480  *
481  * We use the ATTR_FROM_OPEN flag to tell these cases apart. */
482 static int mds_reint_setattr(struct mds_update_record *rec, int offset,
483                              struct ptlrpc_request *req,
484                              struct lustre_handle *lh)
485 {
486         unsigned int ia_valid = rec->ur_iattr.ia_valid;
487         struct mds_obd *mds = mds_req2mds(req);
488         struct obd_device *obd = req->rq_export->exp_obd;
489         struct mds_body *body;
490         struct dentry *de;
491         struct inode *inode = NULL;
492         struct lustre_handle lockh;
493         void *handle = NULL;
494         struct mds_logcancel_data *mlcd = NULL;
495         struct lov_mds_md *lmm = NULL;
496         struct llog_cookie *logcookies = NULL;
497         int lmm_size = 0, need_lock = 1, cookie_size = 0;
498         int rc = 0, cleanup_phase = 0, err, locked = 0;
499         unsigned int qcids[MAXQUOTAS] = { 0, 0 };
500         unsigned int qpids[MAXQUOTAS] = { rec->ur_iattr.ia_uid, 
501                                           rec->ur_iattr.ia_gid };
502         ENTRY;
503
504         LASSERT(offset == REQ_REC_OFF);
505         offset = REPLY_REC_OFF;
506
507         DEBUG_REQ(D_INODE, req, "setattr "LPU64"/%u %x", rec->ur_fid1->id,
508                   rec->ur_fid1->generation, rec->ur_iattr.ia_valid);
509         OBD_COUNTER_INCREMENT(obd, setattr);
510
511         MDS_CHECK_RESENT(req, reconstruct_reint_setattr(rec, offset, req));
512
513         if (rec->ur_iattr.ia_valid & ATTR_FROM_OPEN ||
514             (req->rq_export->exp_connect_flags & OBD_CONNECT_RDONLY)) {
515                 de = mds_fid2dentry(mds, rec->ur_fid1, NULL);
516                 if (IS_ERR(de))
517                         GOTO(cleanup, rc = PTR_ERR(de));
518                 if (req->rq_export->exp_connect_flags & OBD_CONNECT_RDONLY)
519                         GOTO(cleanup, rc = -EROFS);
520         } else {
521                 __u64 lockpart = MDS_INODELOCK_UPDATE;
522                 if (rec->ur_iattr.ia_valid & (ATTR_MODE|ATTR_UID|ATTR_GID))
523                         lockpart |= MDS_INODELOCK_LOOKUP;
524
525                 de = mds_fid2locked_dentry(obd, rec->ur_fid1, NULL, LCK_EX,
526                                            &lockh, NULL, 0, lockpart);
527                 if (IS_ERR(de))
528                         GOTO(cleanup, rc = PTR_ERR(de));
529                 locked = 1;
530         }
531
532         cleanup_phase = 1;
533         inode = de->d_inode;
534         LASSERT(inode);
535
536         if ((rec->ur_iattr.ia_valid & ATTR_FROM_OPEN) ||
537             (rec->ur_iattr.ia_valid & ATTR_SIZE)) {
538                 /* Check write access for the O_TRUNC case */
539                 if (mds_query_write_access(inode) < 0)
540                         GOTO(cleanup, rc = -ETXTBSY);
541         }
542
543         /* save uid/gid for quota acq/rel */
544         qcids[USRQUOTA] = inode->i_uid;
545         qcids[GRPQUOTA] = inode->i_gid;
546
547         if ((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode)) &&
548             rec->ur_eadata != NULL) {
549                 LOCK_INODE_MUTEX(inode);
550                 need_lock = 0;
551         }
552
553         OBD_FAIL_WRITE(obd, OBD_FAIL_MDS_REINT_SETATTR_WRITE, inode->i_sb);
554
555         /* start a log jounal handle if needed */
556         if (S_ISREG(inode->i_mode) &&
557             rec->ur_iattr.ia_valid & (ATTR_UID | ATTR_GID)) {
558                 lmm_size = mds->mds_max_mdsize;
559                 OBD_ALLOC(lmm, lmm_size);
560                 if (lmm == NULL)
561                         GOTO(cleanup, rc = -ENOMEM);
562
563                 cleanup_phase = 2;
564                 rc = mds_get_md(obd, inode, lmm, &lmm_size, need_lock);
565                 if (rc < 0)
566                         GOTO(cleanup, rc);
567                 rc = 0;
568
569                 handle = fsfilt_start_log(obd, inode, FSFILT_OP_SETATTR, NULL,
570                                           le32_to_cpu(lmm->lmm_stripe_count));
571         } else {
572                 handle = fsfilt_start(obd, inode, FSFILT_OP_SETATTR, NULL);
573         }
574         if (IS_ERR(handle))
575                 GOTO(cleanup, rc = PTR_ERR(handle));
576
577         if (rec->ur_iattr.ia_valid & (ATTR_MTIME | ATTR_CTIME))
578                 CDEBUG(D_INODE, "setting mtime %lu, ctime %lu\n",
579                        LTIME_S(rec->ur_iattr.ia_mtime),
580                        LTIME_S(rec->ur_iattr.ia_ctime));
581         rc = mds_fix_attr(inode, rec);
582         if (rc)
583                 GOTO(cleanup, rc);
584
585         if (rec->ur_iattr.ia_valid & ATTR_ATTR_FLAG) {  /* ioctl */
586                 rc = fsfilt_iocontrol(obd, inode, NULL, EXT3_IOC_SETFLAGS,
587                                       (long)&rec->ur_flags);
588         } else if (rec->ur_iattr.ia_valid) {            /* setattr */
589                 rc = fsfilt_setattr(obd, de, handle, &rec->ur_iattr, 0);
590                 /* journal chown/chgrp in llog, just like unlink */
591                 if (rc == 0 && lmm_size){
592                         cookie_size = mds_get_cookie_size(obd, lmm);
593                         OBD_ALLOC(logcookies, cookie_size);
594                         if (logcookies == NULL)
595                                 GOTO(cleanup, rc = -ENOMEM);
596
597                         if (mds_log_op_setattr(obd, inode, lmm, lmm_size,
598                                                logcookies, cookie_size) <= 0) {
599                                 OBD_FREE(logcookies, cookie_size);
600                                 logcookies = NULL;
601                         }
602                 }
603         }
604
605         if (rc == 0 && (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode)) &&
606             rec->ur_eadata != NULL) {
607                 struct lov_stripe_md *lsm = NULL;
608                 struct lov_user_md *lum = NULL;
609
610                 rc = ll_permission(inode, MAY_WRITE, NULL);
611                 if (rc < 0)
612                         GOTO(cleanup, rc);
613
614                 lum = rec->ur_eadata;
615                 /* if { size, offset, count } = { 0, -1, 0 } (i.e. all default
616                  * values specified) then delete default striping from dir. */
617                 if (S_ISDIR(inode->i_mode) &&
618                     ((lum->lmm_stripe_size == 0 &&
619                       lum->lmm_stripe_offset ==
620                       (typeof(lum->lmm_stripe_offset))(-1) &&
621                       lum->lmm_stripe_count == 0) ||
622                     /* lmm_stripe_size == -1 is deprecated in 1.4.6 */
623                     lum->lmm_stripe_size ==
624                     (typeof(lum->lmm_stripe_size))(-1))){
625                         rc = fsfilt_set_md(obd, inode, handle, NULL, 0, "lov");
626                         if (rc)
627                                 GOTO(cleanup, rc);
628                 } else {
629                         rc = obd_iocontrol(OBD_IOC_LOV_SETSTRIPE,
630                                            mds->mds_osc_exp, 0,
631                                            &lsm, rec->ur_eadata);
632                         if (rc)
633                                 GOTO(cleanup, rc);
634
635                         obd_free_memmd(mds->mds_osc_exp, &lsm);
636
637                         rc = fsfilt_set_md(obd, inode, handle, rec->ur_eadata,
638                                            rec->ur_eadatalen, "lov");
639                         if (rc)
640                                 GOTO(cleanup, rc);
641                 }
642         }
643
644         body = lustre_msg_buf(req->rq_repmsg, offset, sizeof(*body));
645         mds_pack_inode2fid(&body->fid1, inode);
646         mds_pack_inode2body(body, inode);
647
648         /* don't return OST-specific attributes if we didn't just set them. */
649         if (ia_valid & ATTR_SIZE)
650                 body->valid |= OBD_MD_FLSIZE | OBD_MD_FLBLOCKS;
651         if (ia_valid & (ATTR_MTIME | ATTR_MTIME_SET))
652                 body->valid |= OBD_MD_FLMTIME;
653         if (ia_valid & (ATTR_ATIME | ATTR_ATIME_SET))
654                 body->valid |= OBD_MD_FLATIME;
655
656         if (rc == 0 && rec->ur_cookielen && !IS_ERR(mds->mds_osc_obd)) {
657                 OBD_ALLOC(mlcd, sizeof(*mlcd) + rec->ur_cookielen +
658                           rec->ur_eadatalen);
659                 if (mlcd) {
660                         mlcd->mlcd_size = sizeof(*mlcd) + rec->ur_cookielen +
661                                 rec->ur_eadatalen;
662                         mlcd->mlcd_eadatalen = rec->ur_eadatalen;
663                         mlcd->mlcd_cookielen = rec->ur_cookielen;
664                         mlcd->mlcd_lmm = (void *)&mlcd->mlcd_cookies +
665                                 mlcd->mlcd_cookielen;
666                         memcpy(&mlcd->mlcd_cookies, rec->ur_logcookies,
667                                mlcd->mlcd_cookielen);
668                         memcpy(mlcd->mlcd_lmm, rec->ur_eadata,
669                                mlcd->mlcd_eadatalen);
670                 } else {
671                         CERROR("unable to allocate log cancel data\n");
672                 }
673         }
674         EXIT;
675  cleanup:
676         if (mlcd != NULL)
677                 fsfilt_add_journal_cb(req->rq_export->exp_obd, 0, handle,
678                                       mds_cancel_cookies_cb, mlcd);
679         err = mds_finish_transno(mds, inode, handle, req, rc, 0);
680         /* do mds to ost setattr if needed */
681         if (!rc && !err && lmm_size)
682                 mds_osc_setattr_async(obd, inode, lmm, lmm_size,
683                                       logcookies, rec->ur_fid1);
684
685         switch (cleanup_phase) {
686         case 2:
687                 OBD_FREE(lmm, mds->mds_max_mdsize);
688                 if (logcookies)
689                         OBD_FREE(logcookies, cookie_size);
690         case 1:
691                 if ((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode)) &&
692                     rec->ur_eadata != NULL)
693                         UNLOCK_INODE_MUTEX(inode);
694                 l_dput(de);
695                 if (locked) {
696                         if (rc) {
697                                 ldlm_lock_decref(&lockh, LCK_EX);
698                         } else {
699                                 ptlrpc_save_lock (req, &lockh, LCK_EX);
700                         }
701                 }
702         case 0:
703                 break;
704         default:
705                 LBUG();
706         }
707         if (err && !rc)
708                 rc = err;
709
710         req->rq_status = rc;
711
712         /* trigger dqrel/dqacq for original owner and new owner */
713         if (ia_valid & (ATTR_UID | ATTR_GID))
714                 lquota_adjust(mds_quota_interface_ref, obd, qcids, qpids, rc,
715                               FSFILT_OP_SETATTR);
716
717         return 0;
718 }
719
720 static void reconstruct_reint_create(struct mds_update_record *rec, int offset,
721                                      struct ptlrpc_request *req)
722 {
723         struct mds_export_data *med = &req->rq_export->exp_mds_data;
724         struct mds_obd *obd = &req->rq_export->exp_obd->u.mds;
725         struct dentry *parent, *child;
726         struct mds_body *body;
727
728         mds_req_from_mcd(req, med->med_mcd);
729
730         if (req->rq_status)
731                 return;
732
733         parent = mds_fid2dentry(obd, rec->ur_fid1, NULL);
734         LASSERT(!IS_ERR(parent));
735         child = ll_lookup_one_len(rec->ur_name, parent, rec->ur_namelen - 1);
736         LASSERT(!IS_ERR(child));
737
738         body = lustre_msg_buf(req->rq_repmsg, offset, sizeof(*body));
739         mds_pack_inode2fid(&body->fid1, child->d_inode);
740         mds_pack_inode2body(body, child->d_inode);
741
742         l_dput(parent);
743         l_dput(child);
744 }
745
746 static int mds_reint_create(struct mds_update_record *rec, int offset,
747                             struct ptlrpc_request *req,
748                             struct lustre_handle *lh)
749 {
750         struct dentry *dparent = NULL;
751         struct mds_obd *mds = mds_req2mds(req);
752         struct obd_device *obd = req->rq_export->exp_obd;
753         struct dentry *dchild = NULL;
754         struct inode *dir = NULL;
755         void *handle = NULL;
756         struct lustre_handle lockh;
757         int rc = 0, err, type = rec->ur_mode & S_IFMT, cleanup_phase = 0;
758         int created = 0;
759         unsigned int qcids[MAXQUOTAS] = { current->fsuid, current->fsgid };
760         unsigned int qpids[MAXQUOTAS] = { 0, 0 };
761         struct dentry_params dp;
762         ENTRY;
763
764         LASSERT(offset == REQ_REC_OFF);
765         offset = REPLY_REC_OFF;
766
767         LASSERT(!strcmp(req->rq_export->exp_obd->obd_type->typ_name,
768                         LUSTRE_MDS_NAME));
769
770         DEBUG_REQ(D_INODE, req, "parent "LPU64"/%u name %s mode %o",
771                   rec->ur_fid1->id, rec->ur_fid1->generation,
772                   rec->ur_name, rec->ur_mode);
773
774         MDS_CHECK_RESENT(req, reconstruct_reint_create(rec, offset, req));
775
776         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_REINT_CREATE))
777                 GOTO(cleanup, rc = -ESTALE);
778
779         dparent = mds_fid2locked_dentry(obd, rec->ur_fid1, NULL, LCK_EX, &lockh,
780                                         rec->ur_name, rec->ur_namelen - 1,
781                                         MDS_INODELOCK_UPDATE);
782         if (IS_ERR(dparent)) {
783                 rc = PTR_ERR(dparent);
784                 if (rc != -ENOENT)
785                         CERROR("parent "LPU64"/%u lookup error %d\n",
786                                rec->ur_fid1->id, rec->ur_fid1->generation, rc);
787                 GOTO(cleanup, rc);
788         }
789         cleanup_phase = 1; /* locked parent dentry */
790         dir = dparent->d_inode;
791         LASSERT(dir);
792
793         ldlm_lock_dump_handle(D_OTHER, &lockh);
794
795         dchild = ll_lookup_one_len(rec->ur_name, dparent, rec->ur_namelen - 1);
796         if (IS_ERR(dchild)) {
797                 rc = PTR_ERR(dchild);
798                 if (rc != -ENAMETOOLONG)
799                 CERROR("child lookup error %d\n", rc);
800                 GOTO(cleanup, rc);
801         }
802
803         cleanup_phase = 2; /* child dentry */
804
805         OBD_FAIL_WRITE(obd, OBD_FAIL_MDS_REINT_CREATE_WRITE, dir->i_sb);
806
807         if (req->rq_export->exp_connect_flags & OBD_CONNECT_RDONLY) {
808                 if (dchild->d_inode)
809                         GOTO(cleanup, rc = -EEXIST);
810                 GOTO(cleanup, rc = -EROFS);
811         }
812
813         if (dir->i_mode & S_ISGID && S_ISDIR(rec->ur_mode))
814                 rec->ur_mode |= S_ISGID;
815
816         dchild->d_fsdata = (void *)&dp;
817         dp.p_inum = (unsigned long)rec->ur_fid2->id;
818         dp.p_ptr = req;
819
820         switch (type) {
821         case S_IFREG:{
822                 handle = fsfilt_start(obd, dir, FSFILT_OP_CREATE, NULL);
823                 if (IS_ERR(handle))
824                         GOTO(cleanup, rc = PTR_ERR(handle));
825                 rc = ll_vfs_create(dir, dchild, rec->ur_mode, NULL);
826                 mds_counter_incr(req->rq_export, LPROC_MDS_MKNOD);
827                 EXIT;
828                 break;
829         }
830         case S_IFDIR:{
831                 handle = fsfilt_start(obd, dir, FSFILT_OP_MKDIR, NULL);
832                 if (IS_ERR(handle))
833                         GOTO(cleanup, rc = PTR_ERR(handle));
834                 rc = vfs_mkdir(dir, dchild, rec->ur_mode);
835                 mds_counter_incr(req->rq_export, LPROC_MDS_MKDIR);
836                 EXIT;
837                 break;
838         }
839         case S_IFLNK:{
840                 handle = fsfilt_start(obd, dir, FSFILT_OP_SYMLINK, NULL);
841                 if (IS_ERR(handle))
842                         GOTO(cleanup, rc = PTR_ERR(handle));
843                 if (rec->ur_tgt == NULL)        /* no target supplied */
844                         rc = -EINVAL;           /* -EPROTO? */
845                 else
846                         rc = ll_vfs_symlink(dir, dchild, rec->ur_tgt, S_IALLUGO);
847                 mds_counter_incr(req->rq_export, LPROC_MDS_MKNOD);
848                 EXIT;
849                 break;
850         }
851         case S_IFCHR:
852         case S_IFBLK:
853         case S_IFIFO:
854         case S_IFSOCK:{
855                 int rdev = rec->ur_rdev;
856                 handle = fsfilt_start(obd, dir, FSFILT_OP_MKNOD, NULL);
857                 if (IS_ERR(handle))
858                         GOTO(cleanup, rc = PTR_ERR(handle));
859                 rc = vfs_mknod(dir, dchild, rec->ur_mode, rdev);
860                 mds_counter_incr(req->rq_export, LPROC_MDS_MKNOD);
861                 EXIT;
862                 break;
863         }
864         default:
865                 CERROR("bad file type %o creating %s\n", type, rec->ur_name);
866                 dchild->d_fsdata = NULL;
867                 GOTO(cleanup, rc = -EINVAL);
868         }
869
870         /* In case we stored the desired inum in here, we want to clean up. */
871         if (dchild->d_fsdata == (void *)(unsigned long)rec->ur_fid2->id)
872                 dchild->d_fsdata = NULL;
873
874         if (rc) {
875                 CDEBUG(D_INODE, "error during create: %d\n", rc);
876                 GOTO(cleanup, rc);
877         } else {
878                 struct iattr iattr;
879                 struct inode *inode = dchild->d_inode;
880                 struct mds_body *body;
881
882                 created = 1;
883                 LTIME_S(iattr.ia_atime) = rec->ur_time;
884                 LTIME_S(iattr.ia_ctime) = rec->ur_time;
885                 LTIME_S(iattr.ia_mtime) = rec->ur_time;
886                 iattr.ia_uid = current->fsuid;  /* set by push_ctxt already */
887                 if (dir->i_mode & S_ISGID)
888                         iattr.ia_gid = dir->i_gid;
889                 else
890                         iattr.ia_gid = current->fsgid;
891                 iattr.ia_valid = ATTR_UID | ATTR_GID | ATTR_ATIME |
892                         ATTR_MTIME | ATTR_CTIME;
893
894                 if (rec->ur_fid2->id) {
895                         LASSERT(rec->ur_fid2->id == inode->i_ino);
896                         inode->i_generation = rec->ur_fid2->generation;
897                         /* Dirtied and committed by the upcoming setattr. */
898                         CDEBUG(D_INODE, "recreated ino %lu with gen %u\n",
899                                inode->i_ino, inode->i_generation);
900                 } else {
901                         CDEBUG(D_INODE, "created ino %lu with gen %x\n",
902                                inode->i_ino, inode->i_generation);
903                 }
904
905                 rc = fsfilt_setattr(obd, dchild, handle, &iattr, 0);
906                 if (rc)
907                         CERROR("error on child setattr: rc = %d\n", rc);
908
909                 iattr.ia_valid = ATTR_MTIME | ATTR_CTIME;
910                 rc = fsfilt_setattr(obd, dparent, handle, &iattr, 0);
911                 if (rc)
912                         CERROR("error on parent setattr: rc = %d\n", rc);
913
914                 if (S_ISDIR(inode->i_mode)) {
915                         struct lov_mds_md lmm;
916                         int lmm_size = sizeof(lmm);
917                         rc = mds_get_md(obd, dir, &lmm, &lmm_size, 1);
918                         if (rc > 0) {
919                                 LOCK_INODE_MUTEX(inode);
920                                 rc = fsfilt_set_md(obd, inode, handle,
921                                                    &lmm, lmm_size, "lov");
922                                 UNLOCK_INODE_MUTEX(inode);
923                         }
924                         if (rc)
925                                 CERROR("error on copy stripe info: rc = %d\n",
926                                         rc);
927                 }
928
929                 body = lustre_msg_buf(req->rq_repmsg, offset, sizeof(*body));
930                 mds_pack_inode2fid(&body->fid1, inode);
931                 mds_pack_inode2body(body, inode);
932         }
933         EXIT;
934
935 cleanup:
936         err = mds_finish_transno(mds, dir, handle, req, rc, 0);
937
938         if (rc && created) {
939                 /* Destroy the file we just created.  This should not need
940                  * extra journal credits, as we have already modified all of
941                  * the blocks needed in order to create the file in the first
942                  * place.
943                  */
944                 switch (type) {
945                 case S_IFDIR:
946                         err = vfs_rmdir(dir, dchild);
947                         if (err)
948                                 CERROR("rmdir in error path: %d\n", err);
949                         break;
950                 default:
951                         err = vfs_unlink(dir, dchild);
952                         if (err)
953                                 CERROR("unlink in error path: %d\n", err);
954                         break;
955                 }
956         } else if (created) {
957                 /* The inode we were allocated may have just been freed
958                  * by an unlink operation.  We take this lock to
959                  * synchronize against the matching reply-ack-lock taken
960                  * in unlink, to avoid replay problems if this reply
961                  * makes it out to the client but the unlink's does not.
962                  * See bug 2029 for more detail.*/
963                 mds_lock_new_child(obd, dchild->d_inode, NULL);
964                 /* save uid/gid of create inode and parent */
965                 qpids[USRQUOTA] = dir->i_uid;
966                 qpids[GRPQUOTA] = dir->i_gid;
967         } else {
968                 rc = err;
969         }
970
971         switch (cleanup_phase) {
972         case 2: /* child dentry */
973                 l_dput(dchild);
974         case 1: /* locked parent dentry */
975                 if (rc) {
976                         ldlm_lock_decref(&lockh, LCK_EX);
977                 } else {
978                         ptlrpc_save_lock (req, &lockh, LCK_EX);
979                 }
980                 l_dput(dparent);
981         case 0:
982                 break;
983         default:
984                 CERROR("invalid cleanup_phase %d\n", cleanup_phase);
985                 LBUG();
986         }
987         req->rq_status = rc;
988
989         /* trigger dqacq on the owner of child and parent */
990         lquota_adjust(mds_quota_interface_ref, obd, qcids, qpids, rc,
991                       FSFILT_OP_CREATE);
992         return 0;
993 }
994
995 int res_gt(struct ldlm_res_id *res1, struct ldlm_res_id *res2,
996            ldlm_policy_data_t *p1, ldlm_policy_data_t *p2)
997 {
998         int i;
999
1000         for (i = 0; i < RES_NAME_SIZE; i++) {
1001                 /* return 1 here, because enqueue_ordered will skip resources
1002                  * of all zeroes if they're sorted to the end of the list. */
1003                 if (res1->name[i] == 0 && res2->name[i] != 0)
1004                         return 1;
1005                 if (res2->name[i] == 0 && res1->name[i] != 0)
1006                         return 0;
1007
1008                 if (res1->name[i] > res2->name[i])
1009                         return 1;
1010                 if (res1->name[i] < res2->name[i])
1011                         return 0;
1012         }
1013         if (!p1 || !p2)
1014                 return 0;
1015         if (memcmp(p1, p2, sizeof(*p1)) < 0)
1016                 return 1;
1017         return 0;
1018 }
1019
1020 /* This function doesn't use ldlm_match_or_enqueue because we're always called
1021  * with EX or PW locks, and the MDS is no longer allowed to match write locks,
1022  * because they take the place of local semaphores.
1023  *
1024  * One or two locks are taken in numerical order.  A res_id->name[0] of 0 means
1025  * no lock is taken for that res_id.  Must be at least one non-zero res_id. */
1026 int enqueue_ordered_locks(struct obd_device *obd, struct ldlm_res_id *p1_res_id,
1027                           struct lustre_handle *p1_lockh, int p1_lock_mode,
1028                           ldlm_policy_data_t *p1_policy,
1029                           struct ldlm_res_id *p2_res_id,
1030                           struct lustre_handle *p2_lockh, int p2_lock_mode,
1031                           ldlm_policy_data_t *p2_policy)
1032 {
1033         struct ldlm_res_id *res_id[2] = { p1_res_id, p2_res_id };
1034         struct lustre_handle *handles[2] = { p1_lockh, p2_lockh };
1035         int lock_modes[2] = { p1_lock_mode, p2_lock_mode };
1036         ldlm_policy_data_t *policies[2] = {p1_policy, p2_policy};
1037         int rc, flags;
1038         ENTRY;
1039
1040         LASSERT(p1_res_id != NULL && p2_res_id != NULL);
1041
1042         CDEBUG(D_INFO, "locks before: "LPU64"/"LPU64"\n",
1043                res_id[0]->name[0], res_id[1]->name[0]);
1044
1045         if (res_gt(p1_res_id, p2_res_id, p1_policy, p2_policy)) {
1046                 handles[1] = p1_lockh;
1047                 handles[0] = p2_lockh;
1048                 res_id[1] = p1_res_id;
1049                 res_id[0] = p2_res_id;
1050                 lock_modes[1] = p1_lock_mode;
1051                 lock_modes[0] = p2_lock_mode;
1052                 policies[1] = p1_policy;
1053                 policies[0] = p2_policy;
1054         }
1055
1056         CDEBUG(D_DLMTRACE, "lock order: "LPU64"/"LPU64"\n",
1057                res_id[0]->name[0], res_id[1]->name[0]);
1058
1059         flags = LDLM_FL_LOCAL_ONLY | LDLM_FL_ATOMIC_CB;
1060         rc = ldlm_cli_enqueue_local(obd->obd_namespace, *res_id[0],
1061                                     LDLM_IBITS, policies[0], lock_modes[0],
1062                                     &flags, ldlm_blocking_ast, 
1063                                     ldlm_completion_ast, NULL, NULL, 0, 
1064                                     NULL, handles[0]);
1065         if (rc != ELDLM_OK)
1066                 RETURN(-EIO);
1067         ldlm_lock_dump_handle(D_OTHER, handles[0]);
1068
1069         if (memcmp(res_id[0], res_id[1], sizeof(*res_id[0])) == 0 &&
1070             (policies[0]->l_inodebits.bits & policies[1]->l_inodebits.bits)) {
1071                 memcpy(handles[1], handles[0], sizeof(*(handles[1])));
1072                 ldlm_lock_addref(handles[1], lock_modes[1]);
1073         } else if (res_id[1]->name[0] != 0) {
1074                 flags = LDLM_FL_LOCAL_ONLY | LDLM_FL_ATOMIC_CB;
1075                 rc = ldlm_cli_enqueue_local(obd->obd_namespace, *res_id[1],
1076                                             LDLM_IBITS, policies[1],
1077                                             lock_modes[1], &flags, 
1078                                             ldlm_blocking_ast,
1079                                             ldlm_completion_ast, NULL, NULL,
1080                                             0, NULL, handles[1]);
1081                 if (rc != ELDLM_OK) {
1082                         ldlm_lock_decref(handles[0], lock_modes[0]);
1083                         RETURN(-EIO);
1084                 }
1085                 ldlm_lock_dump_handle(D_OTHER, handles[1]);
1086         }
1087
1088         RETURN(0);
1089 }
1090
1091 static inline int res_eq(struct ldlm_res_id *res1, struct ldlm_res_id *res2)
1092 {
1093         return !memcmp(res1, res2, sizeof(*res1));
1094 }
1095
1096 static inline void
1097 try_to_aggregate_locks(struct ldlm_res_id *res1, ldlm_policy_data_t *p1,
1098                         struct ldlm_res_id *res2, ldlm_policy_data_t *p2)
1099 {
1100         if (!res_eq(res1, res2))
1101                 return;
1102         /* XXX: any additional inodebits (to current LOOKUP and UPDATE)
1103          * should be taken with great care here */
1104         p1->l_inodebits.bits |= p2->l_inodebits.bits;
1105 }
1106
1107 int enqueue_4ordered_locks(struct obd_device *obd,struct ldlm_res_id *p1_res_id,
1108                            struct lustre_handle *p1_lockh, int p1_lock_mode,
1109                            ldlm_policy_data_t *p1_policy, 
1110                            struct ldlm_res_id *p2_res_id,
1111                            struct lustre_handle *p2_lockh, int p2_lock_mode,
1112                            ldlm_policy_data_t *p2_policy, 
1113                            struct ldlm_res_id *c1_res_id,
1114                            struct lustre_handle *c1_lockh, int c1_lock_mode,
1115                            ldlm_policy_data_t *c1_policy, 
1116                            struct ldlm_res_id *c2_res_id,
1117                            struct lustre_handle *c2_lockh, int c2_lock_mode,
1118                            ldlm_policy_data_t *c2_policy)
1119 {
1120         struct ldlm_res_id *res_id[5] = { p1_res_id, p2_res_id,
1121                                           c1_res_id, c2_res_id };
1122         struct lustre_handle *dlm_handles[5] = { p1_lockh, p2_lockh,
1123                                                  c1_lockh, c2_lockh };
1124         int lock_modes[5] = { p1_lock_mode, p2_lock_mode,
1125                               c1_lock_mode, c2_lock_mode };
1126         ldlm_policy_data_t *policies[5] = {p1_policy, p2_policy,
1127                                            c1_policy, c2_policy};
1128         int rc, i, j, sorted, flags;
1129         ENTRY;
1130
1131         CDEBUG(D_DLMTRACE, "locks before: "LPU64"/"LPU64"/"LPU64"/"LPU64"\n",
1132                res_id[0]->name[0], res_id[1]->name[0], res_id[2]->name[0],
1133                res_id[3]->name[0]);
1134
1135         /* simple insertion sort - we have at most 4 elements */
1136         for (i = 1; i < 4; i++) {
1137                 j = i - 1;
1138                 dlm_handles[4] = dlm_handles[i];
1139                 res_id[4] = res_id[i];
1140                 lock_modes[4] = lock_modes[i];
1141                 policies[4] = policies[i];
1142
1143                 sorted = 0;
1144                 do {
1145                         if (res_gt(res_id[j], res_id[4], policies[j],
1146                                    policies[4])) {
1147                                 dlm_handles[j + 1] = dlm_handles[j];
1148                                 res_id[j + 1] = res_id[j];
1149                                 lock_modes[j + 1] = lock_modes[j];
1150                                 policies[j + 1] = policies[j];
1151                                 j--;
1152                         } else {
1153                                 sorted = 1;
1154                         }
1155                 } while (j >= 0 && !sorted);
1156
1157                 dlm_handles[j + 1] = dlm_handles[4];
1158                 res_id[j + 1] = res_id[4];
1159                 lock_modes[j + 1] = lock_modes[4];
1160                 policies[j + 1] = policies[4];
1161         }
1162
1163         CDEBUG(D_DLMTRACE, "lock order: "LPU64"/"LPU64"/"LPU64"/"LPU64"\n",
1164                res_id[0]->name[0], res_id[1]->name[0], res_id[2]->name[0],
1165                res_id[3]->name[0]);
1166
1167         /* XXX we could send ASTs on all these locks first before blocking? */
1168         for (i = 0; i < 4; i++) {
1169                 flags = LDLM_FL_ATOMIC_CB;
1170                 if (res_id[i]->name[0] == 0)
1171                         break;
1172                 if (i && res_eq(res_id[i], res_id[i-1])) {
1173                         memcpy(dlm_handles[i], dlm_handles[i-1],
1174                                sizeof(*(dlm_handles[i])));
1175                         ldlm_lock_addref(dlm_handles[i], lock_modes[i]);
1176                 } else {
1177                         /* we need to enqueue locks with different inodebits
1178                          * at once, because otherwise concurrent thread can
1179                          * hit the windown between these two locks and we'll
1180                          * get to deadlock. see bug 10360. note also, that it
1181                          * is impossible to have >2 equal res. */
1182                         if (i < 3)
1183                                 try_to_aggregate_locks(res_id[i], policies[i],
1184                                                        res_id[i+1], policies[i+1]);
1185                         rc = ldlm_cli_enqueue_local(obd->obd_namespace,
1186                                                     *res_id[i], LDLM_IBITS,
1187                                                     policies[i], lock_modes[i],
1188                                                     &flags, ldlm_blocking_ast,
1189                                                     ldlm_completion_ast, NULL, 
1190                                                     NULL, 0, NULL, 
1191                                                     dlm_handles[i]);
1192                         if (rc != ELDLM_OK)
1193                                 GOTO(out_err, rc = -EIO);
1194                         ldlm_lock_dump_handle(D_OTHER, dlm_handles[i]);
1195                 }
1196         }
1197
1198         RETURN(0);
1199 out_err:
1200         while (i-- > 0)
1201                 ldlm_lock_decref(dlm_handles[i], lock_modes[i]);
1202
1203         return rc;
1204 }
1205
1206 /* In the unlikely case that the child changed while we were waiting
1207  * on the lock, we need to drop the lock on the old child and either:
1208  * - if the child has a lower resource name, then we have to also
1209  *   drop the parent lock and regain the locks in the right order
1210  * - in the rename case, if the child has a lower resource name than one of
1211  *   the other parent/child resources (maxres) we also need to reget the locks
1212  * - if the child has a higher resource name (this is the common case)
1213  *   we can just get the lock on the new child (still in lock order)
1214  *
1215  * Returns 0 if the child did not change or if it changed but could be locked.
1216  * Returns 1 if the child changed and we need to re-lock (no locks held).
1217  * Returns -ve error with a valid dchild (no locks held). */
1218 static int mds_verify_child(struct obd_device *obd,
1219                             struct ldlm_res_id *parent_res_id,
1220                             struct lustre_handle *parent_lockh,
1221                             struct dentry *dparent, int parent_mode,
1222                             struct ldlm_res_id *child_res_id,
1223                             struct lustre_handle *child_lockh,
1224                             struct dentry **dchildp, int child_mode,
1225                             ldlm_policy_data_t *child_policy,
1226                             const char *name, int namelen,
1227                             struct ldlm_res_id *maxres)
1228 {
1229         struct dentry *vchild, *dchild = *dchildp;
1230         int rc = 0, cleanup_phase = 2; /* parent, child locks */
1231         ENTRY;
1232
1233         vchild = ll_lookup_one_len(name, dparent, namelen - 1);
1234         if (IS_ERR(vchild))
1235                 GOTO(cleanup, rc = PTR_ERR(vchild));
1236
1237         if (likely((vchild->d_inode == NULL && child_res_id->name[0] == 0) ||
1238                    (vchild->d_inode != NULL &&
1239                     child_res_id->name[0] == vchild->d_inode->i_ino &&
1240                     child_res_id->name[1] == vchild->d_inode->i_generation))) {
1241                 if (dchild != NULL)
1242                         l_dput(dchild);
1243                 *dchildp = vchild;
1244
1245                 RETURN(0);
1246         }
1247
1248         CDEBUG(D_DLMTRACE, "child inode changed: %p != %p (%lu != "LPU64")\n",
1249                vchild->d_inode, dchild ? dchild->d_inode : 0,
1250                vchild->d_inode ? vchild->d_inode->i_ino : 0,
1251                child_res_id->name[0]);
1252         if (child_res_id->name[0] != 0)
1253                 ldlm_lock_decref(child_lockh, child_mode);
1254         if (dchild)
1255                 l_dput(dchild);
1256
1257         cleanup_phase = 1; /* parent lock only */
1258         *dchildp = dchild = vchild;
1259
1260         if (dchild->d_inode) {
1261                 int flags = LDLM_FL_ATOMIC_CB;
1262                 child_res_id->name[0] = dchild->d_inode->i_ino;
1263                 child_res_id->name[1] = dchild->d_inode->i_generation;
1264
1265                 /* Make sure that we don't try to re-enqueue a lock on the
1266                  * same resource if it happens that the source is renamed to
1267                  * the target by another thread (bug 9974, thanks racer :-) */
1268                 if (!res_gt(child_res_id, parent_res_id, NULL, NULL) ||
1269                     !res_gt(child_res_id, maxres, NULL, NULL)) {
1270                         CDEBUG(D_DLMTRACE, "relock "LPU64"<("LPU64"|"LPU64")\n",
1271                                child_res_id->name[0], parent_res_id->name[0],
1272                                maxres->name[0]);
1273                         GOTO(cleanup, rc = 1);
1274                 }
1275
1276                 rc = ldlm_cli_enqueue_local(obd->obd_namespace, *child_res_id, 
1277                                             LDLM_IBITS, child_policy, 
1278                                             child_mode, &flags, 
1279                                             ldlm_blocking_ast, 
1280                                             ldlm_completion_ast, NULL, 
1281                                             NULL, 0, NULL, child_lockh);
1282                 if (rc != ELDLM_OK)
1283                         GOTO(cleanup, rc = -EIO);
1284         } else {
1285                 memset(child_res_id, 0, sizeof(*child_res_id));
1286         }
1287
1288         EXIT;
1289 cleanup:
1290         if (rc) {
1291                 switch(cleanup_phase) {
1292                 case 2:
1293                         if (child_res_id->name[0] != 0)
1294                                 ldlm_lock_decref(child_lockh, child_mode);
1295                 case 1:
1296                         ldlm_lock_decref(parent_lockh, parent_mode);
1297                 }
1298         }
1299         return rc;
1300 }
1301
1302 #define INODE_CTIME_AGE (10)
1303 #define INODE_CTIME_OLD(inode) (LTIME_S(inode->i_ctime) +               \
1304                                 INODE_CTIME_AGE < CURRENT_SECONDS)
1305
1306 int mds_get_parent_child_locked(struct obd_device *obd, struct mds_obd *mds,
1307                                 struct ll_fid *fid,
1308                                 struct lustre_handle *parent_lockh,
1309                                 struct dentry **dparentp, int parent_mode,
1310                                 __u64 parent_lockpart,
1311                                 char *name, int namelen,
1312                                 struct lustre_handle *child_lockh,
1313                                 struct dentry **dchildp, int child_mode,
1314                                 __u64 child_lockpart)
1315 {
1316         struct ldlm_res_id child_res_id = { .name = {0} };
1317         struct ldlm_res_id parent_res_id = { .name = {0} };
1318         ldlm_policy_data_t parent_policy = {.l_inodebits = { parent_lockpart }};
1319         ldlm_policy_data_t child_policy = {.l_inodebits = { child_lockpart }};
1320         struct inode *inode;
1321         int rc = 0, cleanup_phase = 0;
1322         ENTRY;
1323
1324         /* Step 1: Lookup parent */
1325         *dparentp = mds_fid2dentry(mds, fid, NULL);
1326         if (IS_ERR(*dparentp)) {
1327                 rc = PTR_ERR(*dparentp);
1328                 *dparentp = NULL;
1329                 RETURN(rc);
1330         }
1331
1332         CDEBUG(D_INODE, "parent ino %lu, name %s\n",
1333                (*dparentp)->d_inode->i_ino, name);
1334
1335         parent_res_id.name[0] = (*dparentp)->d_inode->i_ino;
1336         parent_res_id.name[1] = (*dparentp)->d_inode->i_generation;
1337
1338         cleanup_phase = 1; /* parent dentry */
1339
1340         /* Step 2: Lookup child (without DLM lock, to get resource name) */
1341         *dchildp = ll_lookup_one_len(name, *dparentp, namelen - 1);
1342         if (IS_ERR(*dchildp)) {
1343                 rc = PTR_ERR(*dchildp);
1344                 CDEBUG(D_INODE, "child lookup error %d\n", rc);
1345                 GOTO(cleanup, rc);
1346         }
1347
1348         cleanup_phase = 2; /* child dentry */
1349         inode = (*dchildp)->d_inode;
1350         if (inode != NULL) {
1351                 if (is_bad_inode(inode)) {
1352                         CERROR("bad inode returned %lu/%u\n",
1353                                inode->i_ino, inode->i_generation);
1354                         GOTO(cleanup, rc = -ENOENT);
1355                 }
1356                 inode = igrab(inode);
1357         }
1358         if (inode == NULL)
1359                 goto retry_locks;
1360
1361         child_res_id.name[0] = inode->i_ino;
1362         child_res_id.name[1] = inode->i_generation;
1363
1364         /* If we want a LCK_CR for a directory, and this directory has not been
1365            changed for some time, we return not only a LOOKUP lock, but also an 
1366            UPDATE lock to have negative dentry starts working for this dir.
1367            Also we apply same logic to non-directories. If the file is rarely
1368            changed - we return both locks and this might save us RPC on
1369            later STAT. */
1370         if ((child_mode & (LCK_CR|LCK_PR|LCK_CW)) && INODE_CTIME_OLD(inode))
1371                 child_policy.l_inodebits.bits |= MDS_INODELOCK_UPDATE;
1372
1373         iput(inode);
1374
1375 retry_locks:
1376         cleanup_phase = 2; /* child dentry */
1377
1378         /* Step 3: Lock parent and child in resource order.  If child doesn't
1379          *         exist, we still have to lock the parent and re-lookup. */
1380         rc = enqueue_ordered_locks(obd,&parent_res_id,parent_lockh,parent_mode,
1381                                    &parent_policy,
1382                                    &child_res_id, child_lockh, child_mode,
1383                                    &child_policy);
1384         if (rc)
1385                 GOTO(cleanup, rc);
1386
1387         if (!(*dchildp)->d_inode)
1388                 cleanup_phase = 3; /* parent lock */
1389         else
1390                 cleanup_phase = 4; /* child lock */
1391
1392         /* Step 4: Re-lookup child to verify it hasn't changed since locking */
1393         rc = mds_verify_child(obd, &parent_res_id, parent_lockh, *dparentp,
1394                               parent_mode, &child_res_id, child_lockh, dchildp,
1395                               child_mode,&child_policy, name, namelen, &parent_res_id);
1396         if (rc > 0)
1397                 goto retry_locks;
1398         if (rc < 0) {
1399                 cleanup_phase = 2;
1400                 GOTO(cleanup, rc);
1401         }
1402
1403 cleanup:
1404         if (rc) {
1405                 switch (cleanup_phase) {
1406                 case 4:
1407                         ldlm_lock_decref(child_lockh, child_mode);
1408                 case 3:
1409                         ldlm_lock_decref(parent_lockh, parent_mode);
1410                 case 2:
1411                         l_dput(*dchildp);
1412                 case 1:
1413                         l_dput(*dparentp);
1414                 default: ;
1415                 }
1416         }
1417         return rc;
1418 }
1419
1420 void mds_reconstruct_generic(struct ptlrpc_request *req)
1421 {
1422         struct mds_export_data *med = &req->rq_export->exp_mds_data;
1423
1424         mds_req_from_mcd(req, med->med_mcd);
1425 }
1426
1427 /* If we are unlinking an open file/dir (i.e. creating an orphan) then
1428  * we instead link the inode into the PENDING directory until it is
1429  * finally released.  We can't simply call mds_reint_rename() or some
1430  * part thereof, because we don't have the inode to check for link
1431  * count/open status until after it is locked.
1432  *
1433  * For lock ordering, caller must get child->i_mutex first, then
1434  * pending->i_mutex before starting journal transaction.
1435  *
1436  * returns 1 on success
1437  * returns 0 if we lost a race and didn't make a new link
1438  * returns negative on error
1439  */
1440 static int mds_orphan_add_link(struct mds_update_record *rec,
1441                                struct obd_device *obd, struct dentry *dentry)
1442 {
1443         struct mds_obd *mds = &obd->u.mds;
1444         struct inode *pending_dir = mds->mds_pending_dir->d_inode;
1445         struct inode *inode = dentry->d_inode;
1446         struct dentry *pending_child;
1447         char fidname[LL_FID_NAMELEN];
1448         int fidlen = 0, rc, mode;
1449         ENTRY;
1450
1451         LASSERT(inode != NULL);
1452         LASSERT(!mds_inode_is_orphan(inode));
1453 #ifndef HAVE_I_ALLOC_SEM
1454         LASSERT(TRYLOCK_INODE_MUTEX(inode) == 0);
1455 #endif
1456         LASSERT(TRYLOCK_INODE_MUTEX(pending_dir) == 0);
1457
1458         fidlen = ll_fid2str(fidname, inode->i_ino, inode->i_generation);
1459
1460         CDEBUG(D_INODE, "pending destroy of %dx open %d linked %s %s = %s\n",
1461                mds_orphan_open_count(inode), inode->i_nlink,
1462                S_ISDIR(inode->i_mode) ? "dir" :
1463                 S_ISREG(inode->i_mode) ? "file" : "other",rec->ur_name,fidname);
1464
1465         if (mds_orphan_open_count(inode) == 0 || inode->i_nlink != 0)
1466                 RETURN(0);
1467
1468         pending_child = lookup_one_len(fidname, mds->mds_pending_dir, fidlen);
1469         if (IS_ERR(pending_child))
1470                 RETURN(PTR_ERR(pending_child));
1471
1472         if (pending_child->d_inode != NULL) {
1473                 CERROR("re-destroying orphan file %s?\n", rec->ur_name);
1474                 LASSERT(pending_child->d_inode == inode);
1475                 GOTO(out_dput, rc = 0);
1476         }
1477
1478         /* link() is semanticaly-wrong for S_IFDIR, so we set S_IFREG
1479          * for linking and return real mode back then -bzzz */
1480         mode = inode->i_mode;
1481         inode->i_mode = S_IFREG;
1482         rc = vfs_link(dentry, pending_dir, pending_child);
1483         if (rc)
1484                 CERROR("error linking orphan %s to PENDING: rc = %d\n",
1485                        rec->ur_name, rc);
1486         else
1487                 mds_inode_set_orphan(inode);
1488
1489         /* return mode and correct i_nlink if inode is directory */
1490         inode->i_mode = mode;
1491         LASSERTF(inode->i_nlink == 1, "%s nlink == %d\n",
1492                  S_ISDIR(mode) ? "dir" : S_ISREG(mode) ? "file" : "other",
1493                  inode->i_nlink);
1494         if (S_ISDIR(mode)) {
1495                 inode->i_nlink++;
1496                 pending_dir->i_nlink++;
1497                 mark_inode_dirty(inode);
1498                 mark_inode_dirty(pending_dir);
1499         }
1500
1501         GOTO(out_dput, rc = 1);
1502 out_dput:
1503         l_dput(pending_child);
1504         RETURN(rc);
1505 }
1506
1507 int mds_get_cookie_size(struct obd_device *obd, struct lov_mds_md *lmm)
1508 {
1509         int count = le32_to_cpu(lmm->lmm_stripe_count);
1510         int real_csize = count * sizeof(struct llog_cookie); 
1511         return real_csize;
1512 }
1513
1514 void mds_shrink_reply(struct obd_device *obd, struct ptlrpc_request *req,
1515                       struct mds_body *body, int md_off)
1516 {
1517         int cookie_size = 0, md_size = 0;
1518
1519         if (body && body->valid & OBD_MD_FLEASIZE) {
1520                 md_size = body->eadatasize;
1521         }
1522         if (body && body->valid & OBD_MD_FLCOOKIE) {
1523                 LASSERT(body->valid & OBD_MD_FLEASIZE);
1524                 cookie_size = mds_get_cookie_size(obd, lustre_msg_buf(
1525                                                   req->rq_repmsg, md_off, 0));
1526         }
1527
1528         CDEBUG(D_INFO, "Shrink to md_size %d cookie_size %d \n", md_size,
1529                cookie_size);
1530  
1531         lustre_shrink_reply(req, md_off, md_size, 1);
1532         
1533         lustre_shrink_reply(req, md_off + (md_size > 0), cookie_size, 0); 
1534 }
1535
1536 static int mds_reint_unlink(struct mds_update_record *rec, int offset,
1537                             struct ptlrpc_request *req,
1538                             struct lustre_handle *lh)
1539 {
1540         struct dentry *dparent = NULL, *dchild;
1541         struct mds_obd *mds = mds_req2mds(req);
1542         struct obd_device *obd = req->rq_export->exp_obd;
1543         struct mds_body *body = NULL;
1544         struct inode *child_inode = NULL;
1545         struct lustre_handle parent_lockh, child_lockh, child_reuse_lockh;
1546         void *handle = NULL;
1547         int rc = 0, cleanup_phase = 0;
1548         unsigned int qcids[MAXQUOTAS] = { 0, 0 };
1549         unsigned int qpids[MAXQUOTAS] = { 0, 0 };
1550         ENTRY;
1551
1552         LASSERT(offset == REQ_REC_OFF); /*  || offset == DLM_INTENT_REC_OFF); */
1553         offset = REPLY_REC_OFF;
1554
1555         DEBUG_REQ(D_INODE, req, "parent ino "LPU64"/%u, child %s",
1556                   rec->ur_fid1->id, rec->ur_fid1->generation, rec->ur_name);
1557
1558         MDS_CHECK_RESENT(req, mds_reconstruct_generic(req));
1559
1560         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_REINT_UNLINK))
1561                 GOTO(cleanup, rc = -ENOENT);
1562
1563         rc = mds_get_parent_child_locked(obd, mds, rec->ur_fid1,
1564                                          &parent_lockh, &dparent, LCK_EX,
1565                                          MDS_INODELOCK_UPDATE, 
1566                                          rec->ur_name, rec->ur_namelen,
1567                                          &child_lockh, &dchild, LCK_EX, 
1568                                          MDS_INODELOCK_FULL);
1569         if (rc)
1570                 GOTO(cleanup, rc);
1571
1572         cleanup_phase = 1; /* dchild, dparent, locks */
1573
1574         dget(dchild);
1575         child_inode = dchild->d_inode;
1576         if (child_inode == NULL) {
1577                 CDEBUG(D_INODE, "child doesn't exist (dir %lu, name %s)\n",
1578                        dparent->d_inode->i_ino, rec->ur_name);
1579                 GOTO(cleanup, rc = -ENOENT);
1580         }
1581
1582         /* save uid/gid for quota acquire/release */
1583         qcids[USRQUOTA] = child_inode->i_uid;
1584         qcids[GRPQUOTA] = child_inode->i_gid;
1585         qpids[USRQUOTA] = dparent->d_inode->i_uid;
1586         qpids[GRPQUOTA] = dparent->d_inode->i_gid;
1587
1588         cleanup_phase = 2; /* dchild has a lock */
1589
1590         /* We have to do these checks ourselves, in case we are making an
1591          * orphan.  The client tells us whether rmdir() or unlink() was called,
1592          * so we need to return appropriate errors (bug 72). */
1593         if ((rec->ur_mode & S_IFMT) == S_IFDIR) {
1594                 if (!S_ISDIR(child_inode->i_mode))
1595                         GOTO(cleanup, rc = -ENOTDIR);
1596         } else {
1597                 if (S_ISDIR(child_inode->i_mode))
1598                         GOTO(cleanup, rc = -EISDIR);
1599         }
1600
1601         /* Check for EROFS after we check ENODENT, ENOTDIR, and EISDIR */
1602         if (req->rq_export->exp_connect_flags & OBD_CONNECT_RDONLY)
1603                 GOTO(cleanup, rc = -EROFS);
1604
1605         /* Step 3: Get a lock on the ino to sync with creation WRT inode
1606          * reuse (see bug 2029). */
1607         rc = mds_lock_new_child(obd, child_inode, &child_reuse_lockh);
1608         if (rc != ELDLM_OK)
1609                 GOTO(cleanup, rc);
1610
1611         cleanup_phase = 3; /* child inum lock */
1612
1613         OBD_FAIL_WRITE(obd, OBD_FAIL_MDS_REINT_UNLINK_WRITE, dparent->d_inode->i_sb);
1614
1615         /* ldlm_reply in buf[0] if called via intent */
1616         if (offset == DLM_INTENT_REC_OFF)
1617                 offset = DLM_REPLY_REC_OFF;
1618
1619         body = lustre_msg_buf(req->rq_repmsg, offset, sizeof(*body));
1620         LASSERT(body != NULL);
1621
1622         /* child orphan sem protects orphan_dec_test && is_orphan race */
1623         MDS_DOWN_READ_ORPHAN_SEM(child_inode);
1624         cleanup_phase = 4; /* MDS_UP_READ_ORPHAN_SEM(new_inode) when finished */
1625
1626         /* If this is potentially the last reference to this inode, get the
1627          * OBD EA data first so the client can destroy OST objects.  We
1628          * only do the object removal later if no open files/links remain. */
1629         if ((S_ISDIR(child_inode->i_mode) && child_inode->i_nlink == 2) ||
1630             child_inode->i_nlink == 1) {
1631                 if (mds_orphan_open_count(child_inode) > 0) {
1632                         /* need to lock pending_dir before transaction */
1633                         LOCK_INODE_MUTEX(mds->mds_pending_dir->d_inode);
1634                         cleanup_phase = 5; /* UNLOCK_INODE_MUTEX(mds->mds_pending_dir->d_inode); */
1635                 } else if (S_ISREG(child_inode->i_mode)) {
1636                         mds_pack_inode2fid(&body->fid1, child_inode);
1637                         mds_pack_inode2body(body, child_inode);
1638                         mds_pack_md(obd, req->rq_repmsg, offset + 1, body,
1639                                     child_inode, MDS_PACK_MD_LOCK);
1640                 }
1641         }
1642
1643         /* Step 4: Do the unlink: we already verified ur_mode above (bug 72) */
1644         switch (child_inode->i_mode & S_IFMT) {
1645         case S_IFDIR:
1646                 /* Drop any lingering child directories before we start our
1647                  * transaction, to avoid doing multiple inode dirty/delete
1648                  * in our compound transaction (bug 1321). */
1649                 shrink_dcache_parent(dchild);
1650                 handle = fsfilt_start(obd, dparent->d_inode, FSFILT_OP_RMDIR,
1651                                       NULL);
1652                 if (IS_ERR(handle))
1653                         GOTO(cleanup, rc = PTR_ERR(handle));
1654                 rc = vfs_rmdir(dparent->d_inode, dchild);
1655                 mds_counter_incr(req->rq_export, LPROC_MDS_RMDIR);
1656                 break;
1657         case S_IFREG: {
1658                 struct lov_mds_md *lmm = lustre_msg_buf(req->rq_repmsg,
1659                                                         offset + 1, 0);
1660                 handle = fsfilt_start_log(obd, dparent->d_inode,
1661                                           FSFILT_OP_UNLINK, NULL,
1662                                           le32_to_cpu(lmm->lmm_stripe_count));
1663                 if (IS_ERR(handle))
1664                         GOTO(cleanup, rc = PTR_ERR(handle));
1665                 rc = vfs_unlink(dparent->d_inode, dchild);
1666                 mds_counter_incr(req->rq_export, LPROC_MDS_UNLINK);
1667                 break;
1668         }
1669         case S_IFLNK:
1670         case S_IFCHR:
1671         case S_IFBLK:
1672         case S_IFIFO:
1673         case S_IFSOCK:
1674                 handle = fsfilt_start(obd, dparent->d_inode, FSFILT_OP_UNLINK,
1675                                       NULL);
1676                 if (IS_ERR(handle))
1677                         GOTO(cleanup, rc = PTR_ERR(handle));
1678                 rc = vfs_unlink(dparent->d_inode, dchild);
1679                 mds_counter_incr(req->rq_export, LPROC_MDS_UNLINK);
1680                 break;
1681         default:
1682                 CERROR("bad file type %o unlinking %s\n", rec->ur_mode,
1683                        rec->ur_name);
1684                 LBUG();
1685                 GOTO(cleanup, rc = -EINVAL);
1686         }
1687
1688         if (rc == 0 && child_inode->i_nlink == 0) {
1689                 if (mds_orphan_open_count(child_inode) > 0)
1690                         rc = mds_orphan_add_link(rec, obd, dchild);
1691
1692                 if (rc == 1)
1693                         GOTO(cleanup, rc = 0);
1694
1695                 if (!S_ISREG(child_inode->i_mode))
1696                         GOTO(cleanup, rc);
1697
1698                 if (!(body->valid & OBD_MD_FLEASIZE)) {
1699                         body->valid |=(OBD_MD_FLSIZE | OBD_MD_FLBLOCKS |
1700                                        OBD_MD_FLATIME | OBD_MD_FLMTIME);
1701                 } else if (mds_log_op_unlink(obd,
1702                                 lustre_msg_buf(req->rq_repmsg, offset + 1, 0),
1703                                 lustre_msg_buflen(req->rq_repmsg, offset + 1),
1704                                 lustre_msg_buf(req->rq_repmsg, offset + 2, 0),
1705                                 lustre_msg_buflen(req->rq_repmsg, offset+2)) >
1706                            0) {
1707                         body->valid |= OBD_MD_FLCOOKIE;
1708                 }
1709         }
1710
1711         GOTO(cleanup, rc);
1712 cleanup:
1713         if (rc == 0) {
1714                 struct iattr iattr;
1715                 int err;
1716
1717                 iattr.ia_valid = ATTR_MTIME | ATTR_CTIME;
1718                 LTIME_S(iattr.ia_mtime) = rec->ur_time;
1719                 LTIME_S(iattr.ia_ctime) = rec->ur_time;
1720
1721                 err = fsfilt_setattr(obd, dparent, handle, &iattr, 0);
1722                 if (err)
1723                         CERROR("error on parent setattr: rc = %d\n", err);
1724         }
1725
1726         rc = mds_finish_transno(mds, dparent ? dparent->d_inode : NULL,
1727                                 handle, req, rc, 0);
1728         if (!rc)
1729                 (void)obd_set_info_async(mds->mds_osc_exp, strlen("unlinked"),
1730                                          "unlinked", 0, NULL, NULL);
1731         switch(cleanup_phase) {
1732         case 5: /* pending_dir semaphore */
1733                 UNLOCK_INODE_MUTEX(mds->mds_pending_dir->d_inode);
1734         case 4: /* child inode semaphore */
1735                 MDS_UP_READ_ORPHAN_SEM(child_inode);
1736         case 3: /* child ino-reuse lock */
1737                 if (rc && body != NULL) {
1738                         // Don't unlink the OST objects if the MDS unlink failed
1739                         body->valid = 0;
1740                 }
1741                 if (rc)
1742                         ldlm_lock_decref(&child_reuse_lockh, LCK_EX);
1743                 else
1744                         ptlrpc_save_lock(req, &child_reuse_lockh, LCK_EX);
1745         case 2: /* child lock */
1746                 ldlm_lock_decref(&child_lockh, LCK_EX);
1747         case 1: /* child and parent dentry, parent lock */
1748                 if (rc)
1749                         ldlm_lock_decref(&parent_lockh, LCK_EX);
1750                 else
1751                         ptlrpc_save_lock(req, &parent_lockh, LCK_EX);
1752                 l_dput(dchild);
1753                 l_dput(dchild);
1754                 l_dput(dparent);
1755         case 0:
1756                 break;
1757         default:
1758                 CERROR("invalid cleanup_phase %d\n", cleanup_phase);
1759                 LBUG();
1760         }
1761         req->rq_status = rc;
1762
1763         mds_shrink_reply(obd, req, body, REPLY_REC_OFF + 1);
1764
1765         /* trigger dqrel on the owner of child and parent */
1766         lquota_adjust(mds_quota_interface_ref, obd, qcids, qpids, rc,
1767                       FSFILT_OP_UNLINK);
1768         return 0;
1769 }
1770
1771 static int mds_reint_link(struct mds_update_record *rec, int offset,
1772                           struct ptlrpc_request *req,
1773                           struct lustre_handle *lh)
1774 {
1775         struct obd_device *obd = req->rq_export->exp_obd;
1776         struct dentry *de_src = NULL;
1777         struct dentry *de_tgt_dir = NULL;
1778         struct dentry *dchild = NULL;
1779         struct mds_obd *mds = mds_req2mds(req);
1780         struct lustre_handle *handle = NULL, tgt_dir_lockh, src_lockh;
1781         struct ldlm_res_id src_res_id = { .name = {0} };
1782         struct ldlm_res_id tgt_dir_res_id = { .name = {0} };
1783         ldlm_policy_data_t src_policy ={.l_inodebits = {MDS_INODELOCK_UPDATE}};
1784         ldlm_policy_data_t tgt_dir_policy =
1785                                        {.l_inodebits = {MDS_INODELOCK_UPDATE}};
1786         int rc = 0, cleanup_phase = 0;
1787         ENTRY;
1788
1789         LASSERT(offset == REQ_REC_OFF);
1790
1791         DEBUG_REQ(D_INODE, req, "original "LPU64"/%u to "LPU64"/%u %s",
1792                   rec->ur_fid1->id, rec->ur_fid1->generation,
1793                   rec->ur_fid2->id, rec->ur_fid2->generation, rec->ur_name);
1794
1795         mds_counter_incr(req->rq_export, LPROC_MDS_LINK);
1796
1797         MDS_CHECK_RESENT(req, mds_reconstruct_generic(req));
1798
1799         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_REINT_LINK))
1800                 GOTO(cleanup, rc = -ENOENT);
1801
1802         /* Step 1: Lookup the source inode and target directory by FID */
1803         de_src = mds_fid2dentry(mds, rec->ur_fid1, NULL);
1804         if (IS_ERR(de_src))
1805                 GOTO(cleanup, rc = PTR_ERR(de_src));
1806
1807         cleanup_phase = 1; /* source dentry */
1808
1809         de_tgt_dir = mds_fid2dentry(mds, rec->ur_fid2, NULL);
1810         if (IS_ERR(de_tgt_dir)) {
1811                 rc = PTR_ERR(de_tgt_dir);
1812                 de_tgt_dir = NULL;
1813                 GOTO(cleanup, rc);
1814         }
1815
1816         cleanup_phase = 2; /* target directory dentry */
1817
1818         CDEBUG(D_INODE, "linking %.*s/%s to inode %lu\n",
1819                de_tgt_dir->d_name.len, de_tgt_dir->d_name.name, rec->ur_name,
1820                de_src->d_inode->i_ino);
1821
1822         /* Step 2: Take the two locks */
1823         src_res_id.name[0] = de_src->d_inode->i_ino;
1824         src_res_id.name[1] = de_src->d_inode->i_generation;
1825         tgt_dir_res_id.name[0] = de_tgt_dir->d_inode->i_ino;
1826         tgt_dir_res_id.name[1] = de_tgt_dir->d_inode->i_generation;
1827
1828         rc = enqueue_ordered_locks(obd, &src_res_id, &src_lockh, LCK_EX,
1829                                    &src_policy,
1830                                    &tgt_dir_res_id, &tgt_dir_lockh, LCK_EX,
1831                                    &tgt_dir_policy);
1832         if (rc)
1833                 GOTO(cleanup, rc);
1834
1835         cleanup_phase = 3; /* locks */
1836
1837         if (mds_inode_is_orphan(de_src->d_inode)) {
1838                 CDEBUG(D_INODE, "an attempt to link an orphan inode %lu/%u\n",
1839                        de_src->d_inode->i_ino,
1840                        de_src->d_inode->i_generation);
1841                 GOTO(cleanup, rc = -ENOENT);
1842         }
1843
1844         /* Step 3: Lookup the child */
1845         dchild = ll_lookup_one_len(rec->ur_name, de_tgt_dir, rec->ur_namelen-1);
1846         if (IS_ERR(dchild)) {
1847                 rc = PTR_ERR(dchild);
1848                 if (rc != -EPERM && rc != -EACCES && rc != -ENAMETOOLONG)
1849                         CERROR("child lookup error %d\n", rc);
1850                 GOTO(cleanup, rc);
1851         }
1852
1853         cleanup_phase = 4; /* child dentry */
1854
1855         if (dchild->d_inode) {
1856                 CDEBUG(D_INODE, "child exists (dir %lu, name %s)\n",
1857                        de_tgt_dir->d_inode->i_ino, rec->ur_name);
1858                 rc = -EEXIST;
1859                 GOTO(cleanup, rc);
1860         }
1861
1862         /* Step 4: Do it. */
1863         OBD_FAIL_WRITE(obd, OBD_FAIL_MDS_REINT_LINK_WRITE, de_src->d_inode->i_sb);
1864
1865         if (req->rq_export->exp_connect_flags & OBD_CONNECT_RDONLY)
1866                 GOTO(cleanup, rc = -EROFS);
1867
1868         handle = fsfilt_start(obd, de_tgt_dir->d_inode, FSFILT_OP_LINK, NULL);
1869         if (IS_ERR(handle))
1870                 GOTO(cleanup, rc = PTR_ERR(handle));
1871
1872         rc = vfs_link(de_src, de_tgt_dir->d_inode, dchild);
1873         if (rc && rc != -EPERM && rc != -EACCES)
1874                 CERROR("vfs_link error %d\n", rc);
1875 cleanup:
1876         rc = mds_finish_transno(mds, de_tgt_dir ? de_tgt_dir->d_inode : NULL,
1877                                 handle, req, rc, 0);
1878         EXIT;
1879
1880         switch (cleanup_phase) {
1881         case 4: /* child dentry */
1882                 l_dput(dchild);
1883         case 3: /* locks */
1884                 if (rc) {
1885                         ldlm_lock_decref(&src_lockh, LCK_EX);
1886                         ldlm_lock_decref(&tgt_dir_lockh, LCK_EX);
1887                 } else {
1888                         ptlrpc_save_lock(req, &src_lockh, LCK_EX);
1889                         ptlrpc_save_lock(req, &tgt_dir_lockh, LCK_EX);
1890                 }
1891         case 2: /* target dentry */
1892                 l_dput(de_tgt_dir);
1893         case 1: /* source dentry */
1894                 l_dput(de_src);
1895         case 0:
1896                 break;
1897         default:
1898                 CERROR("invalid cleanup_phase %d\n", cleanup_phase);
1899                 LBUG();
1900         }
1901         req->rq_status = rc;
1902         return 0;
1903 }
1904
1905 /* The idea here is that we need to get four locks in the end:
1906  * one on each parent directory, one on each child.  We need to take
1907  * these locks in some kind of order (to avoid deadlocks), and the order
1908  * I selected is "increasing resource number" order.  We need to look up
1909  * the children, however, before we know what the resource number(s) are.
1910  * Thus the following plan:
1911  *
1912  * 1,2. Look up the parents
1913  * 3,4. Look up the children
1914  * 5. Take locks on the parents and children, in order
1915  * 6. Verify that the children haven't changed since they were looked up
1916  *
1917  * If there was a race and the children changed since they were first looked
1918  * up, it is possible that mds_verify_child() will be able to just grab the
1919  * lock on the new child resource (if it has a higher resource than any other)
1920  * but we need to compare against not only its parent, but also against the
1921  * parent and child of the "other half" of the rename, hence maxres_{src,tgt}.
1922  *
1923  * We need the fancy igrab() on the child inodes because we aren't holding a
1924  * lock on the parent after the lookup is done, so dentry->d_inode may change
1925  * at any time, and igrab() itself doesn't like getting passed a NULL argument.
1926  */
1927 int mds_get_parents_children_locked(struct obd_device *obd,
1928                                     struct mds_obd *mds,
1929                                     struct ll_fid *p1_fid,
1930                                     struct dentry **de_srcdirp,
1931                                     struct ll_fid *p2_fid,
1932                                     struct dentry **de_tgtdirp,
1933                                     int parent_mode,
1934                                     const char *old_name, int old_len,
1935                                     struct dentry **de_oldp,
1936                                     const char *new_name, int new_len,
1937                                     struct dentry **de_newp,
1938                                     struct lustre_handle *dlm_handles,
1939                                     int child_mode)
1940 {
1941         struct ldlm_res_id p1_res_id = { .name = {0} };
1942         struct ldlm_res_id p2_res_id = { .name = {0} };
1943         struct ldlm_res_id c1_res_id = { .name = {0} };
1944         struct ldlm_res_id c2_res_id = { .name = {0} };
1945         ldlm_policy_data_t p_policy = {.l_inodebits = {MDS_INODELOCK_UPDATE}};
1946         /* Only dentry should disappear, but the inode itself would be
1947            intact otherwise. */
1948         ldlm_policy_data_t c1_policy = {.l_inodebits = {MDS_INODELOCK_LOOKUP}};
1949         /* If something is going to be replaced, both dentry and inode locks are           needed */
1950         ldlm_policy_data_t c2_policy = {.l_inodebits = {MDS_INODELOCK_FULL}};
1951         struct ldlm_res_id *maxres_src, *maxres_tgt;
1952         struct inode *inode;
1953         int rc = 0, cleanup_phase = 0;
1954         ENTRY;
1955
1956         /* Step 1: Lookup the source directory */
1957         *de_srcdirp = mds_fid2dentry(mds, p1_fid, NULL);
1958         if (IS_ERR(*de_srcdirp))
1959                 GOTO(cleanup, rc = PTR_ERR(*de_srcdirp));
1960
1961         cleanup_phase = 1; /* source directory dentry */
1962
1963         p1_res_id.name[0] = (*de_srcdirp)->d_inode->i_ino;
1964         p1_res_id.name[1] = (*de_srcdirp)->d_inode->i_generation;
1965
1966         /* Step 2: Lookup the target directory */
1967         if (memcmp(p1_fid, p2_fid, sizeof(*p1_fid)) == 0) {
1968                 *de_tgtdirp = dget(*de_srcdirp);
1969         } else {
1970                 *de_tgtdirp = mds_fid2dentry(mds, p2_fid, NULL);
1971                 if (IS_ERR(*de_tgtdirp)) {
1972                         rc = PTR_ERR(*de_tgtdirp);
1973                         *de_tgtdirp = NULL;
1974                         GOTO(cleanup, rc);
1975                 }
1976         }
1977
1978         cleanup_phase = 2; /* target directory dentry */
1979
1980         p2_res_id.name[0] = (*de_tgtdirp)->d_inode->i_ino;
1981         p2_res_id.name[1] = (*de_tgtdirp)->d_inode->i_generation;
1982
1983         /* Step 3: Lookup the source child entry */
1984         *de_oldp = ll_lookup_one_len(old_name, *de_srcdirp, old_len - 1);
1985         if (IS_ERR(*de_oldp)) {
1986                 rc = PTR_ERR(*de_oldp);
1987                 CERROR("old child lookup error (%.*s): %d\n",
1988                        old_len - 1, old_name, rc);
1989                 GOTO(cleanup, rc);
1990         }
1991
1992         cleanup_phase = 3; /* original name dentry */
1993
1994         inode = (*de_oldp)->d_inode;
1995         if (inode != NULL)
1996                 inode = igrab(inode);
1997         if (inode == NULL)
1998                 GOTO(cleanup, rc = -ENOENT);
1999
2000         c1_res_id.name[0] = inode->i_ino;
2001         c1_res_id.name[1] = inode->i_generation;
2002
2003         iput(inode);
2004
2005         /* Step 4: Lookup the target child entry */
2006         if (!new_name)
2007                 GOTO(retry_locks, rc);
2008         *de_newp = ll_lookup_one_len(new_name, *de_tgtdirp, new_len - 1);
2009         if (IS_ERR(*de_newp)) {
2010                 rc = PTR_ERR(*de_newp);
2011                 if (rc != -ENAMETOOLONG)
2012                 CERROR("new child lookup error (%.*s): %d\n",
2013                        old_len - 1, old_name, rc);
2014                 GOTO(cleanup, rc);
2015         }
2016
2017         cleanup_phase = 4; /* target dentry */
2018
2019         inode = (*de_newp)->d_inode;
2020         if (inode != NULL)
2021                 inode = igrab(inode);
2022         if (inode == NULL)
2023                 goto retry_locks;
2024
2025         c2_res_id.name[0] = inode->i_ino;
2026         c2_res_id.name[1] = inode->i_generation;
2027         iput(inode);
2028
2029 retry_locks:
2030         /* Step 5: Take locks on the parents and child(ren) */
2031         maxres_src = &p1_res_id;
2032         maxres_tgt = &p2_res_id;
2033         cleanup_phase = 4; /* target dentry */
2034
2035         if (c1_res_id.name[0] != 0 && res_gt(&c1_res_id, &p1_res_id,NULL,NULL))
2036                 maxres_src = &c1_res_id;
2037         if (c2_res_id.name[0] != 0 && res_gt(&c2_res_id, &p2_res_id,NULL,NULL))
2038                 maxres_tgt = &c2_res_id;
2039
2040         rc = enqueue_4ordered_locks(obd, &p1_res_id,&dlm_handles[0],parent_mode,
2041                                     &p_policy,
2042                                     &p2_res_id, &dlm_handles[1], parent_mode,
2043                                     &p_policy,
2044                                     &c1_res_id, &dlm_handles[2], child_mode,
2045                                     &c1_policy,
2046                                     &c2_res_id, &dlm_handles[3], child_mode,
2047                                     &c2_policy);
2048         if (rc)
2049                 GOTO(cleanup, rc);
2050
2051         cleanup_phase = 6; /* parent and child(ren) locks */
2052
2053         /* Step 6a: Re-lookup source child to verify it hasn't changed */
2054         rc = mds_verify_child(obd, &p1_res_id, &dlm_handles[0], *de_srcdirp,
2055                               parent_mode, &c1_res_id, &dlm_handles[2], de_oldp,
2056                               child_mode, &c1_policy, old_name, old_len,
2057                               maxres_tgt);
2058         if (rc) {
2059                 if (c2_res_id.name[0] != 0)
2060                         ldlm_lock_decref(&dlm_handles[3], child_mode);
2061                 ldlm_lock_decref(&dlm_handles[1], parent_mode);
2062                 cleanup_phase = 4;
2063                 if (rc > 0)
2064                         goto retry_locks;
2065                 GOTO(cleanup, rc);
2066         }
2067
2068         if ((*de_oldp)->d_inode == NULL)
2069                 GOTO(cleanup, rc = -ENOENT);
2070
2071         if (!new_name)
2072                 GOTO(cleanup, rc);
2073         /* Step 6b: Re-lookup target child to verify it hasn't changed */
2074         rc = mds_verify_child(obd, &p2_res_id, &dlm_handles[1], *de_tgtdirp,
2075                               parent_mode, &c2_res_id, &dlm_handles[3], de_newp,
2076                               child_mode, &c2_policy, new_name, new_len,
2077                               maxres_src);
2078         if (rc) {
2079                 ldlm_lock_decref(&dlm_handles[2], child_mode);
2080                 ldlm_lock_decref(&dlm_handles[0], parent_mode);
2081                 cleanup_phase = 4;
2082                 if (rc > 0)
2083                         goto retry_locks;
2084                 GOTO(cleanup, rc);
2085         }
2086
2087         EXIT;
2088 cleanup:
2089         if (rc) {
2090                 switch (cleanup_phase) {
2091                 case 6: /* child lock(s) */
2092                         if (c2_res_id.name[0] != 0)
2093                                 ldlm_lock_decref(&dlm_handles[3], child_mode);
2094                         if (c1_res_id.name[0] != 0)
2095                                 ldlm_lock_decref(&dlm_handles[2], child_mode);
2096                 case 5: /* parent locks */
2097                         ldlm_lock_decref(&dlm_handles[1], parent_mode);
2098                         ldlm_lock_decref(&dlm_handles[0], parent_mode);
2099                 case 4: /* target dentry */
2100                         l_dput(*de_newp);
2101                 case 3: /* source dentry */
2102                         l_dput(*de_oldp);
2103                 case 2: /* target directory dentry */
2104                         l_dput(*de_tgtdirp);
2105                 case 1: /* source directry dentry */
2106                         l_dput(*de_srcdirp);
2107                 }
2108         }
2109
2110         return rc;
2111 }
2112
2113 static int mds_reint_rename(struct mds_update_record *rec, int offset,
2114                             struct ptlrpc_request *req,
2115                             struct lustre_handle *lockh)
2116 {
2117         struct obd_device *obd = req->rq_export->exp_obd;
2118         struct dentry *de_srcdir = NULL;
2119         struct dentry *de_tgtdir = NULL;
2120         struct dentry *de_old = NULL;
2121         struct dentry *de_new = NULL;
2122         struct inode *old_inode = NULL, *new_inode = NULL;
2123         struct mds_obd *mds = mds_req2mds(req);
2124         struct lustre_handle dlm_handles[4];
2125         struct mds_body *body = NULL;
2126         struct lov_mds_md *lmm = NULL;
2127         int rc = 0, lock_count = 3, cleanup_phase = 0;
2128         void *handle = NULL;
2129         unsigned int qcids[MAXQUOTAS] = { 0, 0 };
2130         unsigned int qpids[4] = { 0, 0, 0, 0 };
2131         ENTRY;
2132
2133         LASSERT(offset == REQ_REC_OFF);
2134         offset = REPLY_REC_OFF;
2135
2136         DEBUG_REQ(D_INODE, req, "parent "LPU64"/%u %s to "LPU64"/%u %s",
2137                   rec->ur_fid1->id, rec->ur_fid1->generation, rec->ur_name,
2138                   rec->ur_fid2->id, rec->ur_fid2->generation, rec->ur_tgt);
2139
2140         mds_counter_incr(req->rq_export, LPROC_MDS_RENAME);
2141         
2142         MDS_CHECK_RESENT(req, mds_reconstruct_generic(req));
2143
2144         rc = mds_get_parents_children_locked(obd, mds, rec->ur_fid1, &de_srcdir,
2145                                              rec->ur_fid2, &de_tgtdir, LCK_EX,
2146                                              rec->ur_name, rec->ur_namelen,
2147                                              &de_old, rec->ur_tgt,
2148                                              rec->ur_tgtlen, &de_new,
2149                                              dlm_handles, LCK_EX);
2150         if (rc)
2151                 GOTO(cleanup, rc);
2152
2153         cleanup_phase = 1; /* parent(s), children, locks */
2154
2155         old_inode = de_old->d_inode;
2156         new_inode = de_new->d_inode;
2157
2158         if (new_inode != NULL)
2159                 lock_count = 4;
2160
2161         /* sanity check for src inode */
2162         if (old_inode->i_ino == de_srcdir->d_inode->i_ino ||
2163             old_inode->i_ino == de_tgtdir->d_inode->i_ino)
2164                 GOTO(cleanup, rc = -EINVAL);
2165
2166         if (req->rq_export->exp_connect_flags & OBD_CONNECT_RDONLY)
2167                 GOTO(cleanup, rc = -EROFS);
2168
2169         if (new_inode == NULL)
2170                 goto no_unlink;
2171
2172         igrab(new_inode);
2173         cleanup_phase = 2; /* iput(new_inode) when finished */
2174
2175         /* sanity check for dest inode */
2176         if (new_inode->i_ino == de_srcdir->d_inode->i_ino ||
2177             new_inode->i_ino == de_tgtdir->d_inode->i_ino)
2178                 GOTO(cleanup, rc = -EINVAL);
2179
2180         if (old_inode == new_inode)
2181                 GOTO(cleanup, rc = 0);
2182
2183         /* save uids/gids for qunit acquire/release */
2184         qcids[USRQUOTA] = old_inode->i_uid;
2185         qcids[GRPQUOTA] = old_inode->i_gid;
2186         qpids[USRQUOTA] = de_tgtdir->d_inode->i_uid;
2187         qpids[GRPQUOTA] = de_tgtdir->d_inode->i_gid;
2188         qpids[2] = de_srcdir->d_inode->i_uid;
2189         qpids[3] = de_srcdir->d_inode->i_gid;
2190
2191         /* if we are about to remove the target at first, pass the EA of
2192          * that inode to client to perform and cleanup on OST */
2193         body = lustre_msg_buf(req->rq_repmsg, offset, sizeof(*body));
2194         LASSERT(body != NULL);
2195
2196         /* child orphan sem protects orphan_dec_test && is_orphan race */
2197         MDS_DOWN_READ_ORPHAN_SEM(new_inode);
2198         cleanup_phase = 3; /* MDS_UP_READ_ORPHAN_SEM(new_inode) when finished */
2199
2200         if ((S_ISDIR(new_inode->i_mode) && new_inode->i_nlink == 2) ||
2201             new_inode->i_nlink == 1) {
2202                 if (mds_orphan_open_count(new_inode) > 0) {
2203                         /* need to lock pending_dir before transaction */
2204                         LOCK_INODE_MUTEX(mds->mds_pending_dir->d_inode);
2205                         cleanup_phase = 4; /* UNLOCK_INODE_MUTEX(mds->mds_pending_dir->d_inode); */
2206                 } else if (S_ISREG(new_inode->i_mode)) {
2207                         mds_pack_inode2fid(&body->fid1, new_inode);
2208                         mds_pack_inode2body(body, new_inode);
2209                         mds_pack_md(obd, req->rq_repmsg, offset + 1, body,
2210                                     new_inode, MDS_PACK_MD_LOCK);
2211                 }
2212         }
2213
2214 no_unlink:
2215         OBD_FAIL_WRITE(obd, OBD_FAIL_MDS_REINT_RENAME_WRITE,
2216                        de_srcdir->d_inode->i_sb);
2217
2218 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
2219         /* Check if we are moving old entry into its child. 2.6 does not
2220            check for this in vfs_rename() anymore */
2221         if (is_subdir(de_new, de_old))
2222                 GOTO(cleanup, rc = -EINVAL);
2223 #endif
2224
2225         lmm = lustre_msg_buf(req->rq_repmsg, offset + 1, 0);
2226         handle = fsfilt_start_log(obd, de_tgtdir->d_inode, FSFILT_OP_RENAME,
2227                                   NULL, le32_to_cpu(lmm->lmm_stripe_count));
2228
2229         if (IS_ERR(handle))
2230                 GOTO(cleanup, rc = PTR_ERR(handle));
2231
2232         lock_kernel();
2233         de_old->d_fsdata = req;
2234         de_new->d_fsdata = req;
2235
2236         rc = vfs_rename(de_srcdir->d_inode, de_old, de_tgtdir->d_inode, de_new);
2237         unlock_kernel();
2238
2239         if (rc == 0 && new_inode != NULL && new_inode->i_nlink == 0) {
2240                 if (mds_orphan_open_count(new_inode) > 0)
2241                         rc = mds_orphan_add_link(rec, obd, de_new);
2242
2243                 if (rc == 1)
2244                         GOTO(cleanup, rc = 0);
2245
2246                 if (!S_ISREG(new_inode->i_mode))
2247                         GOTO(cleanup, rc);
2248
2249                 if (!(body->valid & OBD_MD_FLEASIZE)) {
2250                         body->valid |= (OBD_MD_FLSIZE | OBD_MD_FLBLOCKS |
2251                                         OBD_MD_FLATIME | OBD_MD_FLMTIME);
2252                 } else if (mds_log_op_unlink(obd,
2253                                              lustre_msg_buf(req->rq_repmsg,
2254                                                             offset + 1, 0),
2255                                              lustre_msg_buflen(req->rq_repmsg,
2256                                                                offset + 1),
2257                                              lustre_msg_buf(req->rq_repmsg,
2258                                                             offset + 2, 0),
2259                                              lustre_msg_buflen(req->rq_repmsg,
2260                                                                offset + 2))
2261                            > 0) {
2262                         body->valid |= OBD_MD_FLCOOKIE;
2263                 }
2264         }
2265
2266         GOTO(cleanup, rc);
2267 cleanup:
2268         rc = mds_finish_transno(mds, de_tgtdir ? de_tgtdir->d_inode : NULL,
2269                                 handle, req, rc, 0);
2270
2271         switch (cleanup_phase) {
2272         case 4:
2273                 UNLOCK_INODE_MUTEX(mds->mds_pending_dir->d_inode);
2274         case 3:
2275                 MDS_UP_READ_ORPHAN_SEM(new_inode);
2276         case 2:
2277                 iput(new_inode);
2278         case 1:
2279                 if (rc) {
2280                         if (lock_count == 4)
2281                                 ldlm_lock_decref(&(dlm_handles[3]), LCK_EX);
2282                         ldlm_lock_decref(&(dlm_handles[2]), LCK_EX);
2283                         ldlm_lock_decref(&(dlm_handles[1]), LCK_EX);
2284                         ldlm_lock_decref(&(dlm_handles[0]), LCK_EX);
2285                 } else {
2286                         if (lock_count == 4)
2287                                 ptlrpc_save_lock(req,&(dlm_handles[3]), LCK_EX);
2288                         ptlrpc_save_lock(req, &(dlm_handles[2]), LCK_EX);
2289                         ptlrpc_save_lock(req, &(dlm_handles[1]), LCK_EX);
2290                         ptlrpc_save_lock(req, &(dlm_handles[0]), LCK_EX);
2291                 }
2292                 l_dput(de_new);
2293                 l_dput(de_old);
2294                 l_dput(de_tgtdir);
2295                 l_dput(de_srcdir);
2296         case 0:
2297                 break;
2298         default:
2299                 CERROR("invalid cleanup_phase %d\n", cleanup_phase);
2300                 LBUG();
2301         }
2302         req->rq_status = rc;
2303
2304         /* acquire/release qunit */
2305         lquota_adjust(mds_quota_interface_ref, obd, qcids, qpids, rc,
2306                       FSFILT_OP_RENAME);
2307         return 0;
2308 }
2309
2310 typedef int (*mds_reinter)(struct mds_update_record *, int offset,
2311                            struct ptlrpc_request *, struct lustre_handle *);
2312
2313 static mds_reinter reinters[REINT_MAX] = {
2314         [REINT_SETATTR] mds_reint_setattr,
2315         [REINT_CREATE] mds_reint_create,
2316         [REINT_LINK] mds_reint_link,
2317         [REINT_UNLINK] mds_reint_unlink,
2318         [REINT_RENAME] mds_reint_rename,
2319         [REINT_OPEN] mds_open
2320 };
2321
2322 int mds_reint_rec(struct mds_update_record *rec, int offset,
2323                   struct ptlrpc_request *req, struct lustre_handle *lockh)
2324 {
2325         struct obd_device *obd = req->rq_export->exp_obd;
2326         struct mds_obd *mds = &obd->u.mds;
2327         struct lvfs_run_ctxt saved;
2328         int rc;
2329         ENTRY;
2330
2331 #ifdef CRAY_XT3
2332         if (req->rq_uid != LNET_UID_ANY) {
2333                 /* non-root local cluster client
2334                  * NB root's creds are believed... */
2335                 LASSERT (req->rq_uid != 0);
2336                 rec->ur_uc.luc_fsuid = req->rq_uid;
2337                 rec->ur_uc.luc_cap = 0;
2338         }
2339 #endif
2340
2341         /* get group info of this user */
2342         rec->ur_uc.luc_uce = upcall_cache_get_entry(mds->mds_group_hash,
2343                                                     rec->ur_uc.luc_fsuid,
2344                                                     rec->ur_uc.luc_fsgid, 2,
2345                                                     &rec->ur_uc.luc_suppgid1);
2346
2347         if (IS_ERR(rec->ur_uc.luc_uce)) {
2348                 rc = PTR_ERR(rec->ur_uc.luc_uce);
2349                 rec->ur_uc.luc_uce = NULL;
2350                 RETURN(rc);
2351         }
2352
2353         /* checked by unpacker */
2354         LASSERT(rec->ur_opcode < REINT_MAX && reinters[rec->ur_opcode] != NULL);
2355
2356 #ifdef CRAY_XT3
2357         if (rec->ur_uc.luc_uce)
2358                 rec->ur_uc.luc_fsgid = rec->ur_uc.luc_uce->ue_primary;
2359 #endif
2360
2361         push_ctxt(&saved, &obd->obd_lvfs_ctxt, &rec->ur_uc);
2362         rc = reinters[rec->ur_opcode] (rec, offset, req, lockh);
2363         pop_ctxt(&saved, &obd->obd_lvfs_ctxt, &rec->ur_uc);
2364
2365         upcall_cache_put_entry(mds->mds_group_hash, rec->ur_uc.luc_uce);
2366         RETURN(rc);
2367 }