Whamcloud - gitweb
- fixes and cleanups in GNS:
[fs/lustre-release.git] / lustre / mds / mds_open.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  *  Copyright (c) 2003 Cluster File Systems, Inc.
5  *   Author: Peter Braam <braam@clusterfs.com>
6  *   Author: Andreas Dilger <adilger@clusterfs.com>
7  *   Author: Phil Schwan <phil@clusterfs.com>
8  *   Author: Mike Shaver <shaver@clusterfs.com>
9  *
10  *   This file is part of Lustre, http://www.lustre.org.
11  *
12  *   Lustre is free software; you can redistribute it and/or
13  *   modify it under the terms of version 2 of the GNU General Public
14  *   License as published by the Free Software Foundation.
15  *
16  *   Lustre is distributed in the hope that it will be useful,
17  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
18  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  *   GNU General Public License for more details.
20  *
21  *   You should have received a copy of the GNU General Public License
22  *   along with Lustre; if not, write to the Free Software
23  *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24  */
25
26 #ifndef EXPORT_SYMTAB
27 # define EXPORT_SYMTAB
28 #endif
29 #define DEBUG_SUBSYSTEM S_MDS
30
31 #include <linux/version.h>
32 #include <linux/module.h>
33 #include <linux/init.h>
34 #include <linux/version.h>
35 #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0))
36 # include <linux/buffer_head.h>
37 # include <linux/workqueue.h>
38 #else
39 # include <linux/locks.h>
40 #endif
41
42 #include <linux/obd_class.h>
43 #include <linux/obd_lov.h>
44 #include <linux/lustre_fsfilt.h>
45 #include <linux/lprocfs_status.h>
46
47 #include "mds_internal.h"
48
49 /* Exported function from this file are:
50  *
51  * mds_open - called by the intent handler
52  * mds_close - an rpc handling function
53  * mds_pin - an rpc handling function - which will go away
54  * mds_mfd_close - for force closing files when a client dies
55  */
56
57 /*
58  * MDS file data handling: file data holds a handle for a file opened
59  * by a client.
60  */
61
62 static void mds_mfd_addref(void *mfdp)
63 {
64         struct mds_file_data *mfd = mfdp;
65
66         atomic_inc(&mfd->mfd_refcount);
67         CDEBUG(D_INFO, "GETting mfd %p : new refcount %d\n", mfd,
68                atomic_read(&mfd->mfd_refcount));
69 }
70
71 struct mds_file_data *mds_mfd_new(void)
72 {
73         struct mds_file_data *mfd;
74
75         OBD_ALLOC(mfd, sizeof *mfd);
76         if (mfd == NULL) {
77                 CERROR("mds: out of memory\n");
78                 return NULL;
79         }
80
81         atomic_set(&mfd->mfd_refcount, 2);
82
83         INIT_LIST_HEAD(&mfd->mfd_handle.h_link);
84         class_handle_hash(&mfd->mfd_handle, mds_mfd_addref);
85
86         return mfd;
87 }
88
89 static struct mds_file_data *mds_handle2mfd(struct lustre_handle *handle)
90 {
91         ENTRY;
92         LASSERT(handle != NULL);
93         RETURN(class_handle2object(handle->cookie));
94 }
95
96 static void mds_mfd_put(struct mds_file_data *mfd)
97 {
98         CDEBUG(D_INFO, "PUTting mfd %p : new refcount %d\n", mfd,
99                atomic_read(&mfd->mfd_refcount) - 1);
100         LASSERT(atomic_read(&mfd->mfd_refcount) > 0 &&
101                 atomic_read(&mfd->mfd_refcount) < 0x5a5a);
102         if (atomic_dec_and_test(&mfd->mfd_refcount)) {
103                 LASSERT(list_empty(&mfd->mfd_handle.h_link));
104                 OBD_FREE(mfd, sizeof *mfd);
105         }
106 }
107
108 static void mds_mfd_destroy(struct mds_file_data *mfd)
109 {
110         class_handle_unhash(&mfd->mfd_handle);
111         mds_mfd_put(mfd);
112 }
113
114 #ifdef IFILTERDATA_ACTUALLY_USED
115 /* Caller must hold mds->mds_epoch_sem */
116 static int mds_alloc_filterdata(struct inode *inode)
117 {
118         LASSERT(inode->i_filterdata == NULL);
119         OBD_ALLOC(inode->i_filterdata, sizeof(struct mds_filter_data));
120         if (inode->i_filterdata == NULL)
121                 return -ENOMEM;
122         LASSERT(igrab(inode) == inode);
123         return 0;
124 }
125
126 /* Caller must hold mds->mds_epoch_sem */
127 static void mds_free_filterdata(struct inode *inode)
128 {
129         LASSERT(inode->i_filterdata != NULL);
130         OBD_FREE(inode->i_filterdata, sizeof(struct mds_filter_data));
131         inode->i_filterdata = NULL;
132         iput(inode);
133 }
134 #endif /*IFILTERDATA_ACTUALLY_USED*/
135
136 /* Write access to a file: executors cause a negative count,
137  * writers a positive count.  The semaphore is needed to perform
138  * a check for the sign and then increment or decrement atomically.
139  *
140  * This code is closely tied to the allocation of the d_fsdata and the
141  * MDS epoch, so we use the same semaphore for the whole lot.
142  *
143  * We could use a different semaphore for each file, if it ever shows
144  * up in a profile, which it won't.
145  *
146  * epoch argument is nonzero during recovery */
147 static int mds_get_write_access(struct mds_obd *mds, struct inode *inode,
148                                 __u64 epoch)
149 {
150         int rc = 0;
151
152         down(&mds->mds_epoch_sem);
153
154         if (atomic_read(&inode->i_writecount) < 0) {
155                 up(&mds->mds_epoch_sem);
156                 RETURN(-ETXTBSY);
157         }
158
159 #ifdef IFILTERDATA_ACTUALLY_USED
160         if (MDS_FILTERDATA(inode) && MDS_FILTERDATA(inode)->io_epoch != 0) {
161                 CDEBUG(D_INODE, "continuing MDS epoch "LPU64" for ino %lu/%u\n",
162                        MDS_FILTERDATA(inode)->io_epoch, inode->i_ino,
163                        inode->i_generation);
164                 goto out;
165         }
166
167         if (inode->i_filterdata == NULL)
168                 mds_alloc_filterdata(inode);
169         if (inode->i_filterdata == NULL) {
170                 rc = -ENOMEM;
171                 goto out;
172         }
173 #endif /*IFILTERDATA_ACTUALLY_USED*/
174         if (epoch > mds->mds_io_epoch)
175                 mds->mds_io_epoch = epoch;
176         else
177                 mds->mds_io_epoch++;
178 #ifdef IFILTERDATA_ACTUALLY_USED
179         MDS_FILTERDATA(inode)->io_epoch = mds->mds_io_epoch;
180         CDEBUG(D_INODE, "starting MDS epoch "LPU64" for ino %lu/%u\n",
181                mds->mds_io_epoch, inode->i_ino, inode->i_generation);
182  out:
183 #endif /*IFILTERDATA_ACTUALLY_USED*/
184         if (rc == 0)
185                 atomic_inc(&inode->i_writecount);
186         up(&mds->mds_epoch_sem);
187         return rc;
188 }
189
190 /* Returns EAGAIN if the client needs to get size and/or cookies and close
191  * again -- which is never true if the file is about to be unlinked.  Otherwise
192  * returns the number of remaining writers. */
193 static int mds_put_write_access(struct mds_obd *mds, struct inode *inode,
194                                 struct mds_body *body, int unlinking)
195 {
196         int rc = 0;
197         ENTRY;
198
199         down(&mds->mds_epoch_sem);
200         atomic_dec(&inode->i_writecount);
201         rc = atomic_read(&inode->i_writecount);
202         if (rc > 0)
203                 GOTO(out, rc);
204 #if 0
205         if (!unlinking && !(body->valid & OBD_MD_FLSIZE))
206                 GOTO(out, rc = EAGAIN);
207 #endif
208 #ifdef IFILTERDATA_ACTUALLY_USED
209         mds_free_filterdata(inode);
210 #endif
211  out:
212         up(&mds->mds_epoch_sem);
213         return rc;
214 }
215
216 static int mds_deny_write_access(struct mds_obd *mds, struct inode *inode)
217 {
218         ENTRY;
219         down(&mds->mds_epoch_sem);
220         if (atomic_read(&inode->i_writecount) > 0) {
221                 up(&mds->mds_epoch_sem);
222                 RETURN(-ETXTBSY);
223         }
224         atomic_dec(&inode->i_writecount);
225         up(&mds->mds_epoch_sem);
226         RETURN(0);
227 }
228
229 static void mds_allow_write_access(struct inode *inode)
230 {
231         ENTRY;
232         atomic_inc(&inode->i_writecount);
233 }
234
235 int mds_query_write_access(struct inode *inode)
236 {
237         ENTRY;
238         RETURN(atomic_read(&inode->i_writecount));
239 }
240
241 /* This replaces the VFS dentry_open, it manages mfd and writecount */
242 static struct mds_file_data *mds_dentry_open(struct dentry *dentry,
243                                              struct vfsmount *mnt, int flags,
244                                              struct ptlrpc_request *req)
245 {
246         struct mds_export_data *med = &req->rq_export->exp_mds_data;
247         struct mds_obd *mds = mds_req2mds(req);
248         struct mds_file_data *mfd;
249         struct mds_body *body;
250         int error;
251         ENTRY;
252
253         mfd = mds_mfd_new();
254         if (mfd == NULL) {
255                 CERROR("mds: out of memory\n");
256                 GOTO(cleanup_dentry, error = -ENOMEM);
257         }
258
259         body = lustre_msg_buf(req->rq_repmsg, 1, sizeof (*body));
260
261         if (flags & FMODE_WRITE) {
262                 /* FIXME: in recovery, need to pass old epoch here */
263                 error = mds_get_write_access(mds, dentry->d_inode, 0);
264                 if (error)
265                         GOTO(cleanup_mfd, error);
266 #ifdef IFILTERDATA_ACTUALLY_USED
267                 body->io_epoch = MDS_FILTERDATA(dentry->d_inode)->io_epoch;
268 #endif /*IFILTERDATA_ACTUALLY_USED*/
269         } else if (flags & FMODE_EXEC) {
270                 error = mds_deny_write_access(mds, dentry->d_inode);
271                 if (error)
272                         GOTO(cleanup_mfd, error);
273         }
274
275         dget(dentry);
276
277         /* Mark the file as open to handle open-unlink. */
278
279         DOWN_WRITE_I_ALLOC_SEM(dentry->d_inode);
280         mds_orphan_open_inc(dentry->d_inode);
281         UP_WRITE_I_ALLOC_SEM(dentry->d_inode);
282
283         mfd->mfd_mode = flags;
284         mfd->mfd_dentry = dentry;
285         mfd->mfd_xid = req->rq_xid;
286
287         spin_lock(&med->med_open_lock);
288         list_add(&mfd->mfd_list, &med->med_open_head);
289         spin_unlock(&med->med_open_lock);
290         mds_mfd_put(mfd);
291
292         body->handle.cookie = mfd->mfd_handle.h_cookie;
293
294         RETURN(mfd);
295
296 cleanup_mfd:
297         mds_mfd_put(mfd);
298         mds_mfd_destroy(mfd);
299 cleanup_dentry:
300         return ERR_PTR(error);
301 }
302
303 static void mds_objids_from_lmm(obd_id *ids, struct lov_mds_md *lmm,
304                                 struct lov_desc *desc)
305 {
306         int i;
307         for (i = 0; i < le32_to_cpu(lmm->lmm_stripe_count); i++) {
308                 ids[le32_to_cpu(lmm->lmm_objects[i].l_ost_idx)] =
309                         le64_to_cpu(lmm->lmm_objects[i].l_object_id);
310         }
311 }
312
313 /* Must be called with i_sem held */
314 static int mds_create_objects(struct ptlrpc_request *req, int offset,
315                               struct mds_update_record *rec,
316                               struct mds_obd *mds, struct obd_device *obd,
317                               struct dentry *dchild, void **handle, 
318                               obd_id **ids)
319 {
320         struct obdo *oa = NULL;
321         struct obd_trans_info oti = { 0 };
322         struct mds_body *body;
323         struct lov_stripe_md *lsm = NULL;
324         struct lov_mds_md *lmm = NULL;
325         struct inode *inode = dchild->d_inode;
326         void *lmm_buf;
327         int rc, lmm_bufsize, lmm_size;
328         ENTRY;
329
330         if (rec->ur_flags & MDS_OPEN_DELAY_CREATE ||
331             !(rec->ur_flags & FMODE_WRITE))
332                 RETURN(0);
333
334         body = lustre_msg_buf(req->rq_repmsg, 1, sizeof(*body));
335
336         if (!S_ISREG(inode->i_mode))
337                 RETURN(0);
338         if (body->valid & OBD_MD_FLEASIZE)
339                 RETURN(0);
340
341         OBD_ALLOC(*ids, mds->mds_dt_desc.ld_tgt_count * sizeof(**ids));
342         if (*ids == NULL)
343                 RETURN(-ENOMEM);
344         oti.oti_objid = *ids;
345
346         /* replay case */
347         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY) {
348                 LASSERT(id_ino(rec->ur_id2));
349                 body->valid |= OBD_MD_FLBLKSZ | OBD_MD_FLEASIZE;
350                 lmm_size = rec->ur_eadatalen;
351                 lmm = rec->ur_eadata;
352                 LASSERT(lmm);
353
354                 if (*handle == NULL)
355                         *handle = fsfilt_start(obd,inode,FSFILT_OP_CREATE,NULL);
356                 if (IS_ERR(*handle)) {
357                         rc = PTR_ERR(*handle);
358                         *handle = NULL;
359                         GOTO(out_oa, rc);
360                 }
361
362                 mds_objids_from_lmm(*ids, lmm, &mds->mds_dt_desc);
363
364                 lmm_buf = lustre_msg_buf(req->rq_repmsg, offset, 0);
365                 lmm_bufsize = req->rq_repmsg->buflens[offset];
366                 LASSERT(lmm_buf);
367                 LASSERT(lmm_bufsize >= lmm_size);
368                 memcpy(lmm_buf, lmm, lmm_size);
369                 rc = fsfilt_set_md(obd, inode, *handle, lmm,
370                                    lmm_size, EA_LOV);
371                 if (rc)
372                         CERROR("open replay failed to set md:%d\n", rc);
373                 RETURN(0);
374         }
375
376         if (OBD_FAIL_CHECK_ONCE(OBD_FAIL_MDS_ALLOC_OBDO))
377                 GOTO(out_ids, rc = -ENOMEM);
378
379         oa = obdo_alloc();
380         if (oa == NULL)
381                 GOTO(out_ids, rc = -ENOMEM);
382         oa->o_mode = S_IFREG | 0600;
383         oa->o_id = inode->i_ino;
384         oa->o_gr = FILTER_GROUP_FIRST_MDS + mds->mds_num;
385         oa->o_generation = inode->i_generation;
386         oa->o_uid = 0; /* must have 0 uid / gid on OST */
387         oa->o_gid = 0;
388         oa->o_valid = OBD_MD_FLID | OBD_MD_FLGENER | OBD_MD_FLTYPE |
389                 OBD_MD_FLMODE | OBD_MD_FLUID | OBD_MD_FLGID | OBD_MD_FLGROUP;
390         oa->o_size = 0;
391
392         obdo_from_inode(oa, inode, OBD_MD_FLTYPE|OBD_MD_FLATIME|OBD_MD_FLMTIME|
393                         OBD_MD_FLCTIME);
394
395         if (!(rec->ur_flags & MDS_OPEN_HAS_OBJS)) {
396                 /* check if things like lfs setstripe are sending us the ea */
397                 if (rec->ur_flags & MDS_OPEN_HAS_EA) {
398                         rc = obd_iocontrol(OBD_IOC_LOV_SETSTRIPE,
399                                            mds->mds_dt_exp,
400                                            0, &lsm, rec->ur_eadata);
401                         if (rc)
402                                 GOTO(out_oa, rc);
403                 } else {
404                         OBD_ALLOC(lmm, mds->mds_max_mdsize);
405                         if (lmm == NULL)
406                                 GOTO(out_oa, rc = -ENOMEM);
407
408                         lmm_size = mds->mds_max_mdsize;
409                         rc = mds_get_md(obd, dchild->d_parent->d_inode,
410                                         lmm, &lmm_size, 1, 0);
411                         if (rc > 0)
412                                 rc = obd_iocontrol(OBD_IOC_LOV_SETSTRIPE,
413                                                    mds->mds_dt_exp,
414                                                    0, &lsm, lmm);
415                         OBD_FREE(lmm, mds->mds_max_mdsize);
416                         if (rc)
417                                 GOTO(out_oa, rc);
418                 } 
419                 LASSERT(oa->o_gr >= FILTER_GROUP_FIRST_MDS);
420                 rc = obd_create(mds->mds_dt_exp, oa, &lsm, &oti);
421                 if (rc) {
422                         int level = D_ERROR;
423                         if (rc == -ENOSPC)
424                                 level = D_INODE;
425                         CDEBUG(level, "error creating objects for "
426                                       "inode %lu: rc = %d\n",
427                                inode->i_ino, rc);
428                         if (rc > 0) {
429                                 CERROR("obd_create returned invalid "
430                                        "rc %d\n", rc);
431                                 rc = -EIO;
432                         }
433                         GOTO(out_oa, rc);
434                 }
435         } else {
436                 rc = obd_iocontrol(OBD_IOC_LOV_SETEA, mds->mds_dt_exp,
437                                    0, &lsm, rec->ur_eadata);
438                 if (rc) {
439                         GOTO(out_oa, rc);
440                 }
441                 lsm->lsm_object_id = oa->o_id;
442                 lsm->lsm_object_gr = oa->o_gr;
443         }
444         if (inode->i_size) {
445                 oa->o_size = inode->i_size;
446                 obdo_from_inode(oa, inode, OBD_MD_FLTYPE|OBD_MD_FLATIME|
447                                 OBD_MD_FLMTIME| OBD_MD_FLCTIME| OBD_MD_FLSIZE);
448                 rc = obd_setattr(mds->mds_dt_exp, oa, lsm, &oti);
449                 if (rc) {
450                         CERROR("error setting attrs for inode %lu: rc %d\n",
451                                inode->i_ino, rc);
452                         if (rc > 0) {
453                                 CERROR("obd_setattr returned bad rc %d\n", rc);
454                                 rc = -EIO;
455                         }
456                         GOTO(out_oa, rc);
457                 }
458         }
459
460         body->valid |= OBD_MD_FLBLKSZ | OBD_MD_FLEASIZE;
461         obdo_refresh_inode(inode, oa, OBD_MD_FLBLKSZ);
462
463         LASSERT(lsm && lsm->lsm_object_id);
464         lmm = NULL;
465         rc = obd_packmd(mds->mds_dt_exp, &lmm, lsm);
466         if (!id_ino(rec->ur_id2))
467                 obd_free_memmd(mds->mds_dt_exp, &lsm);
468         LASSERT(rc >= 0);
469         lmm_size = rc;
470         body->eadatasize = rc;
471
472         if (*handle == NULL)
473                 *handle = fsfilt_start(obd, inode, FSFILT_OP_CREATE, NULL);
474         if (IS_ERR(*handle)) {
475                 rc = PTR_ERR(*handle);
476                 *handle = NULL;
477                 GOTO(out_ids, rc);
478         }
479
480         rc = fsfilt_set_md(obd, inode, *handle, lmm,
481                            lmm_size, EA_LOV);
482         
483         lmm_buf = lustre_msg_buf(req->rq_repmsg, offset, 0);
484         lmm_bufsize = req->rq_repmsg->buflens[offset];
485         LASSERT(lmm_buf);
486         LASSERT(lmm_bufsize >= lmm_size);
487
488         memcpy(lmm_buf, lmm, lmm_size);
489         obd_free_diskmd(mds->mds_dt_exp, &lmm);
490  out_oa:
491         oti_free_cookies(&oti);
492         obdo_free(oa);
493  out_ids:
494         if (rc) {
495                 OBD_FREE(*ids, mds->mds_dt_desc.ld_tgt_count * sizeof(**ids));
496                 *ids = NULL;
497         }
498         if(lsm)
499                 obd_free_memmd(mds->mds_dt_exp, &lsm);
500         RETURN(rc);
501 }
502
503 static void reconstruct_open(struct mds_update_record *rec, int offset,
504                              struct ptlrpc_request *req,
505                              struct lustre_handle *child_lockh)
506 {
507         struct mds_export_data *med = &req->rq_export->exp_mds_data;
508         struct mds_client_data *mcd = med->med_mcd;
509         struct mds_obd *mds = mds_req2mds(req);
510         struct mds_file_data *mfd;
511         struct obd_device *obd = req->rq_export->exp_obd;
512         struct dentry *parent, *dchild;
513         struct ldlm_reply *rep;
514         struct mds_body *body;
515         struct list_head *t;
516         int put_child = 1;
517         int rc;
518         ENTRY;
519
520         LASSERT(offset == 3); /* only called via intent */
521         rep = lustre_msg_buf(req->rq_repmsg, 0, sizeof (*rep));
522         body = lustre_msg_buf(req->rq_repmsg, 1, sizeof (*body));
523
524         /* copy rc, transno and disp; steal locks */
525         mds_req_from_mcd(req, mcd);
526         intent_set_disposition(rep, mcd->mcd_last_data);
527
528         /* Only replay if create or open actually happened. */
529         if (!intent_disposition(rep, DISP_OPEN_CREATE | DISP_OPEN_OPEN) ) {
530                 EXIT;
531                 return; /* error looking up parent or child */
532         }
533
534         parent = mds_id2dentry(obd, rec->ur_id1, NULL);
535         LASSERTF(!IS_ERR(parent), "lid "DLID4" rc %ld\n", 
536                  OLID4(rec->ur_id1), PTR_ERR(parent));
537
538         dchild = ll_lookup_one_len(rec->ur_name, parent, 
539                                    rec->ur_namelen - 1);
540         LASSERTF(!IS_ERR(dchild), "parent "DLID4" child %s rc %ld\n",
541                  OLID4(rec->ur_id1), rec->ur_name, PTR_ERR(dchild));
542
543         if (!dchild->d_inode)
544                 GOTO(out_dput, 0); /* child not present to open */
545
546         /* At this point, we know we have a child. We'll send
547          * it back _unless_ it not created and open failed.  */
548         if (intent_disposition(rep, DISP_OPEN_OPEN) &&
549             !intent_disposition(rep, DISP_OPEN_CREATE) &&
550             req->rq_status)
551                 GOTO(out_dput, 0);
552
553         /* get lock (write for O_CREAT, read otherwise) */
554         mds_pack_inode2body(obd, body, dchild->d_inode, 1);
555         if (S_ISREG(dchild->d_inode->i_mode)) {
556                 rc = mds_pack_md(obd, req->rq_repmsg, 2, body,
557                                  dchild->d_inode, 1, 0);
558
559                 if (rc)
560                         LASSERT(rc == req->rq_status);
561
562                 /* If we have LOV EA data, the OST holds size, mtime */
563                 if (!(body->valid & OBD_MD_FLEASIZE))
564                         body->valid |= (OBD_MD_FLSIZE | OBD_MD_FLBLOCKS |
565                                         OBD_MD_FLATIME | OBD_MD_FLMTIME);
566         }
567         
568         /* If we have -EEXIST as the status, and we were asked to create
569          * exclusively, we can tell we failed because the file already existed.
570          */
571         if (req->rq_status == -EEXIST &&
572             ((rec->ur_flags & (MDS_OPEN_CREAT | MDS_OPEN_EXCL)) ==
573              (MDS_OPEN_CREAT | MDS_OPEN_EXCL))) {
574                 GOTO(out_dput, 0);
575         }
576
577         /* If we didn't get as far as trying to open, then some locking thing
578          * probably went wrong, and we'll just bail here.
579          */
580         if (!intent_disposition(rep, DISP_OPEN_OPEN))
581                 GOTO(out_dput, 0);
582
583         /* If we failed, then we must have failed opening, so don't look for
584          * file descriptor or anything, just give the client the bad news.
585          */
586         if (req->rq_status)
587                 GOTO(out_dput, 0);
588
589         mfd = NULL;
590         list_for_each(t, &med->med_open_head) {
591                 mfd = list_entry(t, struct mds_file_data, mfd_list);
592                 if (mfd->mfd_xid == req->rq_xid)
593                         break;
594                 mfd = NULL;
595         }
596
597         /* #warning "XXX fixme" bug 2991 */
598         /* Here it used to LASSERT(mfd) if exp_outstanding_reply != NULL.
599          * Now that exp_outstanding_reply is a list, it's just using mfd != NULL
600          * to detect a re-open */
601         if (mfd == NULL) {
602                 mntget(mds->mds_vfsmnt);
603                 CERROR("Re-opened file \n");
604                 mfd = mds_dentry_open(dchild, mds->mds_vfsmnt,
605                                       rec->ur_flags & ~MDS_OPEN_TRUNC, req);
606                 if (!mfd) {
607                         CERROR("mds: out of memory\n");
608                         GOTO(out_dput, req->rq_status = -ENOMEM);
609                 }
610                 put_child = 0;
611         } else {
612                 body->handle.cookie = mfd->mfd_handle.h_cookie;
613                 CDEBUG(D_INODE, "resend mfd %p, cookie "LPX64"\n", mfd,
614                        mfd->mfd_handle.h_cookie);
615         }
616
617  out_dput:
618         if (put_child)
619                 l_dput(dchild);
620         l_dput(parent);
621         EXIT;
622 }
623
624 /* do NOT or the MAY_*'s, you'll get the weakest */
625 static int accmode(int flags)
626 {
627         int res = 0;
628
629         if (flags & FMODE_READ)
630                 res = MAY_READ;
631         if (flags & (FMODE_WRITE|MDS_OPEN_TRUNC))
632                 res |= MAY_WRITE;
633         if (flags & FMODE_EXEC)
634                 res = MAY_EXEC;
635         return res;
636 }
637
638 /* Handles object creation, actual opening, and I/O epoch */
639 static int mds_finish_open(struct ptlrpc_request *req, struct dentry *dchild,
640                            struct mds_body *body, int flags, void **handle,
641                            struct mds_update_record *rec, struct ldlm_reply *rep)
642 {
643         struct mds_obd *mds = mds_req2mds(req);
644         struct obd_device *obd = req->rq_export->exp_obd;
645         struct mds_file_data *mfd = NULL;
646         obd_id *ids = NULL; /* object IDs created */
647         unsigned mode;
648         int rc = 0;
649         ENTRY;
650
651         /* atomically create objects if necessary */
652         down(&dchild->d_inode->i_sem);
653         mode = dchild->d_inode->i_mode;
654         if ((S_ISREG(mode) && !(body->valid & OBD_MD_FLEASIZE)) || 
655             (S_ISDIR(mode) && !(body->valid & OBD_MD_FLDIREA))) {
656                 rc = mds_pack_md(obd, req->rq_repmsg, 2, body,
657                                  dchild->d_inode, 0, 0);
658                 if (rc) {
659                         up(&dchild->d_inode->i_sem);
660                         RETURN(rc);
661                 }
662         }
663         if (rec != NULL) {
664                 /* no EA: create objects */
665                 if ((body->valid & OBD_MD_FLEASIZE) &&
666                     (rec->ur_flags & MDS_OPEN_HAS_EA)) {
667                         up(&dchild->d_inode->i_sem);
668                         RETURN(-EEXIST);
669                 }
670                 if (!(body->valid & OBD_MD_FLEASIZE)) {
671                         /* no EA: create objects */
672                         rc = mds_create_objects(req, 2, rec, mds, obd,
673                                                 dchild, handle, &ids);
674                         if (rc) {
675                                 CERROR("mds_create_objects: rc = %d\n", rc);
676                                 up(&dchild->d_inode->i_sem);
677                                 RETURN(rc);
678                         }
679                 }
680                 if (S_ISREG(dchild->d_inode->i_mode) &&
681                     (body->valid & OBD_MD_FLEASIZE)) {
682                         rc = mds_revalidate_lov_ea(obd, dchild->d_inode,
683                                                    req->rq_repmsg, 2);
684                         if (!rc)
685                                 rc = mds_pack_md(obd, req->rq_repmsg, 2, body,
686                                                  dchild->d_inode, 0, 0);
687                         if (rc) {
688                                 up(&dchild->d_inode->i_sem);
689                                 RETURN(rc);
690                         }
691                 }
692         }
693         rc = mds_pack_acl(obd, req->rq_repmsg, 3, body, dchild->d_inode);
694         if (rc < 0) {
695                 CERROR("mds_pack_acl: rc = %d\n", rc);
696                 up(&dchild->d_inode->i_sem);
697                 RETURN(rc);
698         }
699
700         /* If the inode has no EA data, then MDSs hold size, mtime */
701         if (S_ISREG(dchild->d_inode->i_mode) &&
702             !(body->valid & OBD_MD_FLEASIZE)) {
703                 body->valid |= (OBD_MD_FLSIZE | OBD_MD_FLBLOCKS |
704                                 OBD_MD_FLATIME | OBD_MD_FLMTIME);
705         }
706         up(&dchild->d_inode->i_sem);
707
708         intent_set_disposition(rep, DISP_OPEN_OPEN);
709         mfd = mds_dentry_open(dchild, mds->mds_vfsmnt, flags, req);
710         if (IS_ERR(mfd))
711                 RETURN(PTR_ERR(mfd));
712
713         CDEBUG(D_INODE, "mfd %p, cookie "LPX64"\n", mfd,
714                mfd->mfd_handle.h_cookie);
715         if (ids != NULL) {
716                 mds_dt_update_objids(obd, ids);
717                 OBD_FREE(ids, sizeof(*ids) * mds->mds_dt_desc.ld_tgt_count);
718         }
719         //if (rc)
720         //        mds_mfd_destroy(mfd);
721         RETURN(rc);
722 }
723
724 static int mds_open_by_id(struct ptlrpc_request *req,
725                           struct lustre_id *id,
726                           struct mds_body *body, int flags,
727                           struct mds_update_record *rec,
728                           struct ldlm_reply *rep)
729 {
730         struct mds_obd *mds = mds_req2mds(req);
731         struct inode *pending_dir = mds->mds_pending_dir->d_inode;
732         struct dentry *dchild;
733         char idname[LL_ID_NAMELEN];
734         int idlen = 0, rc;
735         void *handle = NULL;
736         ENTRY;
737
738         down(&pending_dir->i_sem);
739         idlen = ll_id2str(idname, id_ino(id), id_gen(id));
740         dchild = lookup_one_len(idname, mds->mds_pending_dir,
741                                 idlen);
742         if (IS_ERR(dchild)) {
743                 up(&pending_dir->i_sem);
744                 rc = PTR_ERR(dchild);
745                 CERROR("error looking up %s in PENDING: rc = %d\n", 
746                        idname, rc);
747                 RETURN(rc);
748         }
749
750         if (dchild->d_inode != NULL) {
751                 mds_inode_set_orphan(dchild->d_inode);
752                 mds_pack_inode2body(req2obd(req), body,
753                                     dchild->d_inode, 1);
754                 
755                 intent_set_disposition(rep, DISP_LOOKUP_EXECD);
756                 intent_set_disposition(rep, DISP_LOOKUP_POS);
757                 CWARN("Orphan %s found and opened in PENDING directory\n",
758                        idname);
759                 goto open;
760         }
761         l_dput(dchild);
762
763         /*
764          * we didn't find it in PENDING so it isn't an orphan.  See if it was a
765          * regular inode that was previously created.
766          */
767         dchild = mds_id2dentry(req2obd(req), id, NULL);
768         if (IS_ERR(dchild))
769                 RETURN(PTR_ERR(dchild));
770
771         mds_pack_inode2body(req2obd(req), body,
772                             dchild->d_inode, 1);
773         
774         intent_set_disposition(rep, DISP_LOOKUP_EXECD);
775         intent_set_disposition(rep, DISP_LOOKUP_POS);
776
777  open:
778         rc = mds_finish_open(req, dchild, body, flags, &handle, rec, rep);
779         rc = mds_finish_transno(mds, dchild ? dchild->d_inode : NULL, handle,
780                                 req, rc, rep ? rep->lock_policy_res1 : 0);
781         /* XXX what do we do here if mds_finish_transno itself failed? */
782         l_dput(dchild);
783         RETURN(rc);
784 }
785
786 int mds_pin(struct ptlrpc_request *req, int offset)
787 {
788         struct obd_device *obd = req->rq_export->exp_obd;
789         struct mds_body *request_body, *reply_body;
790         struct lvfs_run_ctxt saved;
791         int rc, size = sizeof(*reply_body);
792         ENTRY;
793
794         request_body = lustre_msg_buf(req->rq_reqmsg, offset,
795                                       sizeof(*request_body));
796
797         rc = lustre_pack_reply(req, 1, &size, NULL);
798         if (rc)
799                 RETURN(rc);
800         reply_body = lustre_msg_buf(req->rq_repmsg, 0, sizeof(*reply_body));
801
802         push_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
803         rc = mds_open_by_id(req, &request_body->id1, reply_body,
804                             request_body->flags, NULL, NULL);
805         pop_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
806
807         RETURN(rc);
808 }
809
810 /*
811  * get a lock on the ino to sync with creation WRT inode reuse (bug 2029). If
812  * child_lockh is NULL we just get the lock as a barrier to wait for other
813  * holders of this lock, and drop it right away again.
814  */
815 int mds_lock_new_child(struct obd_device *obd, struct inode *inode,
816                        struct lustre_handle *child_lockh)
817 {
818         struct ldlm_res_id child_res_id = { .name = { inode->i_ino, 0, 1, 0 } };
819         struct lustre_handle lockh;
820         int lock_flags = 0;
821         int rc;
822         ENTRY;
823
824         if (child_lockh == NULL)
825                 child_lockh = &lockh;
826
827         rc = ldlm_cli_enqueue(NULL, NULL, obd->obd_namespace, child_res_id,
828                               LDLM_PLAIN, NULL, LCK_EX, &lock_flags,
829                               mds_blocking_ast, ldlm_completion_ast, NULL,
830                               NULL, NULL, 0, NULL, child_lockh);
831         if (rc != ELDLM_OK)
832                 CERROR("ldlm_cli_enqueue: %d\n", rc);
833         else if (child_lockh == &lockh)
834                 ldlm_lock_decref(child_lockh, LCK_EX);
835
836         RETURN(rc);
837 }
838
839 int mds_open(struct mds_update_record *rec, int offset,
840              struct ptlrpc_request *req, struct lustre_handle *child_lockh)
841 {
842         /* XXX ALLOCATE _something_ - 464 bytes on stack here */
843         struct obd_device *obd = req->rq_export->exp_obd;
844         struct mds_obd *mds = mds_req2mds(req);
845         struct ldlm_reply *rep = NULL;
846         struct mds_body *body = NULL;
847         struct dentry *dchild = NULL, *dparent = NULL;
848         struct mds_export_data *med;
849         struct lustre_handle parent_lockh[2] = {{0}, {0}};
850         int rc = 0, cleanup_phase = 0, acc_mode, created = 0;
851         int parent_mode = LCK_PR;
852         void *handle = NULL;
853         struct dentry_params dp;
854         struct mea *mea = NULL;
855         int mea_size, update_mode;
856         int child_mode = LCK_PR;
857         /* Always returning LOOKUP lock if open succesful to guard
858            dentry on client. */
859         ldlm_policy_data_t policy = {.l_inodebits={MDS_INODELOCK_LOOKUP}};
860         struct ldlm_res_id child_res_id = { .name = {0}};
861         int lock_flags = 0;
862         ENTRY;
863
864         DEBUG_REQ(D_INODE, req, "parent "DLID4" name %*s mode %o",
865                   OLID4(rec->ur_id1), rec->ur_namelen - 1, rec->ur_name,
866                   rec->ur_mode);
867
868         OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_PAUSE_OPEN | OBD_FAIL_ONCE,
869                          (obd_timeout + 1) / 4);
870
871         if (offset == 3) { /* intent */
872                 rep = lustre_msg_buf(req->rq_repmsg, 0, sizeof (*rep));
873                 body = lustre_msg_buf(req->rq_repmsg, 1, sizeof (*body));
874         } else if (offset == 1) { /* non-intent reint */
875                 body = lustre_msg_buf(req->rq_repmsg, 0, sizeof (*body));
876         } else {
877                 body = NULL;
878                 LBUG();
879         }
880
881         MDS_CHECK_RESENT(req, reconstruct_open(rec, offset, req, child_lockh));
882
883         /*
884          * Step 0: If we are passed a id, then we assume the client already
885          * opened this file and is only replaying the RPC, so we open the inode
886          * by fid (at some large expense in security).
887          */
888         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY) {
889                 CDEBUG(D_HA, "open obj "DLID4" name %*s mode %o\n",
890                        OLID4(rec->ur_id2), rec->ur_namelen - 1, 
891                        rec->ur_name, rec->ur_mode);
892
893                 LASSERT(id_ino(rec->ur_id2));
894
895                 rc = mds_open_by_id(req, rec->ur_id2, body, rec->ur_flags,
896                                     rec, rep);
897                 if (rc != -ENOENT)
898                         RETURN(rc);
899
900                 /* We didn't find the correct inode on disk either, so we
901                  * need to re-create it via a regular replay. */
902                 LASSERT(rec->ur_flags & MDS_OPEN_CREAT);
903         } else {
904                 LASSERT(!id_ino(rec->ur_id2));
905         }
906
907         LASSERT(offset == 3); /* If we got here, we must be called via intent */
908
909         med = &req->rq_export->exp_mds_data;
910         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_OPEN_PACK)) {
911                 CERROR("test case OBD_FAIL_MDS_OPEN_PACK\n");
912                 RETURN(-ENOMEM);
913         }
914
915         acc_mode = accmode(rec->ur_flags);
916
917         /* Step 1: Find and lock the parent */
918         if (rec->ur_flags & MDS_OPEN_CREAT) {
919                 /* XXX Well, in fact we only need this lock mode change if
920                    in addition to O_CREAT, the file does not exist.
921                    But we do not know if it exists or not yet */
922                 parent_mode = LCK_PW;
923         }
924         
925         if (rec->ur_namelen == 1) {
926                 /* client (LMV) wants to open the file by id */
927                 CDEBUG(D_OTHER, "OPEN by id "DLID4"\n", OLID4(rec->ur_id1));
928                 dchild = mds_id2dentry(obd, rec->ur_id1, NULL);
929                 if (IS_ERR(dchild)) {
930                         rc = PTR_ERR(dparent);
931                         CERROR("child lookup by an id error %d\n", rc);
932                         GOTO(cleanup, rc);
933                 }
934                 goto got_child;
935         }
936         
937         dparent = mds_id2locked_dentry(obd, rec->ur_id1, NULL, parent_mode,
938                                        parent_lockh, &update_mode, rec->ur_name,
939                                        rec->ur_namelen - 1, MDS_INODELOCK_UPDATE);
940         if (IS_ERR(dparent)) {
941                 rc = PTR_ERR(dparent);
942                 if (rc != -ENOENT)
943                         CERROR("parent lookup for "DLID4" failed, error %d\n",
944                                OLID4(rec->ur_id1), rc);
945                 GOTO(cleanup, rc);
946         }
947         LASSERT(dparent->d_inode != NULL);
948
949         cleanup_phase = 1; /* parent dentry and lock */
950
951         /* try to retrieve MEA data for this dir */
952         rc = mds_md_get_attr(obd, dparent->d_inode, &mea, &mea_size);
953         if (rc)
954                 GOTO(cleanup, rc);
955        
956         if (mea != NULL) {
957                 /*
958                  * dir is already splitted, check is requested filename should *
959                  * live at this MDS or at another one.
960                  */
961                 int i;
962                 i = mea_name2idx(mea, rec->ur_name, rec->ur_namelen - 1);
963                 if (mea->mea_master != id_group(&mea->mea_ids[i])) {
964                         CDEBUG(D_OTHER,
965                                "%s: inapropriate MDS(%d) for %lu/%u:%s."
966                                " should be %lu(%d)\n", obd->obd_name,
967                                mea->mea_master, dparent->d_inode->i_ino,
968                                dparent->d_inode->i_generation, rec->ur_name,
969                                (unsigned long)id_group(&mea->mea_ids[i]), i);
970                         GOTO(cleanup, rc = -ERESTART);
971                 }
972         }
973
974         /* Step 2: Lookup the child */
975         dchild = ll_lookup_one_len(rec->ur_name, dparent, rec->ur_namelen - 1);
976         if (IS_ERR(dchild)) {
977                 rc = PTR_ERR(dchild);
978                 dchild = NULL; /* don't confuse mds_finish_transno() below */
979                 GOTO(cleanup, rc);
980         }
981
982 got_child:
983         cleanup_phase = 2; /* child dentry */
984
985         intent_set_disposition(rep, DISP_LOOKUP_EXECD);
986
987         if (dchild->d_flags & DCACHE_CROSS_REF) {
988                 struct ldlm_res_id res_id = { . name = {0} };
989                 ldlm_policy_data_t policy;
990                 int flags = 0;
991
992                 mds_pack_dentry2body(obd, body, dchild, 1);
993                 intent_set_disposition(rep, DISP_LOOKUP_POS);
994
995                 CDEBUG(D_OTHER, "cross reference: "DLID4"\n",
996                        OLID4(&body->id1));
997                 
998                 res_id.name[0] = dchild->d_fid;
999                 res_id.name[1] = dchild->d_mdsnum;
1000                 
1001                 policy.l_inodebits.bits = MDS_INODELOCK_LOOKUP;
1002                 rc = ldlm_cli_enqueue(NULL, NULL, obd->obd_namespace,
1003                                       res_id, LDLM_IBITS, &policy,
1004                                       LCK_PR, &flags, mds_blocking_ast,
1005                                       ldlm_completion_ast, NULL, NULL,
1006                                       NULL, 0, NULL, child_lockh);
1007 #ifdef S_PDIROPS
1008                 if (parent_lockh[1].cookie != 0)
1009                         ldlm_lock_decref(parent_lockh + 1, update_mode);
1010 #endif
1011                 ldlm_lock_decref(parent_lockh, parent_mode);
1012                 if (mea)
1013                         OBD_FREE(mea, mea_size);
1014                 l_dput(dchild);
1015                 l_dput(dparent);
1016                 RETURN(rc);
1017         }
1018         
1019         if (dchild->d_inode)
1020                 intent_set_disposition(rep, DISP_LOOKUP_POS);
1021         else
1022                 intent_set_disposition(rep, DISP_LOOKUP_NEG);
1023
1024         /* Step 3: If the child was negative, and we're supposed to, create it.*/
1025         if (dchild->d_inode == NULL) {
1026                 unsigned long ino;
1027                 struct iattr iattr;
1028                 struct inode *inode;
1029                 
1030                 ino = (unsigned long)id_ino(rec->ur_id2);
1031                 
1032                 rc = mds_try_to_split_dir(obd, dparent, &mea, 0,
1033                                           update_mode);
1034                 
1035                 CDEBUG(D_OTHER, "%s: splitted %lu/%u - %d\n",
1036                        obd->obd_name, dparent->d_inode->i_ino,
1037                        dparent->d_inode->i_generation, rc);
1038
1039                 if (rc > 0) {
1040                         /* dir got splitted */
1041                         GOTO(cleanup, rc = -ERESTART);
1042                 } else if (rc < 0) {
1043                         /* error happened during spitting */
1044                         GOTO(cleanup, rc);
1045                 }
1046
1047                 if (!(rec->ur_flags & MDS_OPEN_CREAT)) {
1048                         /*
1049                          * dentry is negative and we weren't supposed to create
1050                          * object, get out of here.
1051                          */
1052                         GOTO(cleanup, rc = -ENOENT);
1053                 }
1054
1055                 intent_set_disposition(rep, DISP_OPEN_CREATE);
1056                 handle = fsfilt_start(obd, dparent->d_inode, FSFILT_OP_CREATE,
1057                                       NULL);
1058                 if (IS_ERR(handle)) {
1059                         rc = PTR_ERR(handle);
1060                         handle = NULL;
1061                         GOTO(cleanup, rc);
1062                 }
1063                 dchild->d_fsdata = (void *) &dp;
1064                 dp.p_ptr = req;
1065                 dp.p_inum = ino;
1066
1067                 rc = ll_vfs_create(dparent->d_inode, dchild, rec->ur_mode, NULL);
1068                 if (dchild->d_fsdata == (void *)(unsigned long)ino)
1069                         dchild->d_fsdata = NULL;
1070
1071                 if (rc) {
1072                         CDEBUG(D_INODE, "error during create: %d\n", rc);
1073                         GOTO(cleanup, rc);
1074                 }
1075                 inode = dchild->d_inode;
1076                 if (ino) {
1077                         LASSERT(ino == inode->i_ino);
1078                         
1079                         /* written as part of setattr */
1080                         inode->i_generation = id_gen(rec->ur_id2);
1081                         CDEBUG(D_HA, "recreated ino %lu with gen %u\n",
1082                                inode->i_ino, inode->i_generation);
1083                 }
1084
1085                 created = 1;
1086                 LTIME_S(iattr.ia_atime) = rec->ur_time;
1087                 LTIME_S(iattr.ia_ctime) = rec->ur_time;
1088                 LTIME_S(iattr.ia_mtime) = rec->ur_time;
1089
1090                 iattr.ia_uid = rec->ur_fsuid;
1091                 if (dparent->d_inode->i_mode & S_ISGID)
1092                         iattr.ia_gid = dparent->d_inode->i_gid;
1093                 else
1094                         iattr.ia_gid = rec->ur_fsgid;
1095
1096                 iattr.ia_valid = ATTR_UID | ATTR_GID | ATTR_ATIME |
1097                         ATTR_MTIME | ATTR_CTIME;
1098
1099                 rc = fsfilt_setattr(obd, dchild, handle, &iattr, 0);
1100                 if (rc)
1101                         CERROR("error on child setattr: rc = %d\n", rc);
1102
1103                 iattr.ia_valid = ATTR_MTIME | ATTR_CTIME;
1104
1105                 rc = fsfilt_setattr(obd, dparent, handle, &iattr, 0);
1106                 if (rc)
1107                         CERROR("error on parent setattr: rc = %d\n", rc);
1108                 else {
1109                         MD_COUNTER_INCREMENT(obd, create);
1110                 }
1111
1112                 down(&dchild->d_inode->i_sem);
1113                 if (ino) {
1114                         rc = mds_update_inode_sid(obd, dchild->d_inode,
1115                                                   handle, rec->ur_id2);
1116                         if (rc) {
1117                                 CERROR("mds_update_inode_sid() failed, "
1118                                        "rc = %d\n", rc);
1119                         }
1120                         id_assign_fid(&body->id1, rec->ur_id2);
1121
1122                         /* 
1123                          * make sure, that fid is up-to-date.
1124                          */
1125                         mds_set_last_fid(obd, id_fid(rec->ur_id2));
1126                 } else {
1127                         rc = mds_alloc_inode_sid(obd, dchild->d_inode,
1128                                                  handle, &body->id1);
1129                         if (rc) {
1130                                 CERROR("mds_alloc_inode_sid() failed, "
1131                                        "rc = %d\n", rc);
1132                         }
1133                 }
1134                 up(&dchild->d_inode->i_sem);
1135                 
1136                 if (!(rec->ur_flags & O_EXCL)) { /* bug 3313 */
1137                         rc = fsfilt_commit(obd, dchild->d_inode->i_sb,
1138                                            dchild->d_inode, handle, 
1139                                            req->rq_export->exp_sync);
1140                         handle = NULL;
1141                 }
1142
1143                 acc_mode = 0;           /* Don't check for permissions */
1144         }
1145         mds_pack_inode2body(obd, body, dchild->d_inode, 1);
1146         
1147         LASSERTF(!mds_inode_is_orphan(dchild->d_inode),
1148                  "dchild %.*s (%p) inode %p\n", dchild->d_name.len,
1149                  dchild->d_name.name, dchild, dchild->d_inode);
1150
1151         if (S_ISREG(dchild->d_inode->i_mode)) {
1152                 /* Check permissions etc */
1153                 rc = ll_permission(dchild->d_inode, acc_mode, NULL);
1154                 if (rc != 0)
1155                         GOTO(cleanup, rc);
1156
1157                 /* Can't write to a read-only file */
1158                 if (IS_RDONLY(dchild->d_inode) && (acc_mode & MAY_WRITE) != 0)
1159                         GOTO(cleanup, rc = -EPERM);
1160
1161                 /* An append-only file must be opened in append mode for
1162                  * writing */
1163                 if (IS_APPEND(dchild->d_inode) && (acc_mode & MAY_WRITE) != 0 &&
1164                     ((rec->ur_flags & MDS_OPEN_APPEND) == 0 ||
1165                      (rec->ur_flags & MDS_OPEN_TRUNC) != 0))
1166                         GOTO(cleanup, rc = -EPERM);
1167         }
1168
1169         if (!created && (rec->ur_flags & MDS_OPEN_CREAT) &&
1170             (rec->ur_flags & MDS_OPEN_EXCL)) {
1171                 /* File already exists, we didn't just create it, and we
1172                  * were passed O_EXCL; err-or. */
1173                 GOTO(cleanup, rc = -EEXIST); // returns a lock to the client
1174         }
1175
1176         if (S_ISDIR(dchild->d_inode->i_mode)) {
1177                 if (rec->ur_flags & MDS_OPEN_CREAT ||
1178                     rec->ur_flags & FMODE_WRITE) {
1179                         /* we are trying to create or write a exist dir */
1180                         GOTO(cleanup, rc = -EISDIR);
1181                 }
1182                 if (ll_permission(dchild->d_inode, acc_mode, NULL))
1183                         GOTO(cleanup, rc = -EACCES);
1184
1185                 /* 
1186                  * here was checking for possible GNS mount points to skip their
1187                  * open. I removed it as its detection based only on SUID bit is
1188                  * not reliable. Opening such a dirs should not cause any
1189                  * problems, at least tests show that. --umka
1190                  */
1191         }
1192
1193         /* if we are following a symlink, don't open */
1194         if (S_ISLNK(dchild->d_inode->i_mode))
1195                 GOTO(cleanup_no_trans, rc = 0);
1196
1197         if ((rec->ur_flags & MDS_OPEN_DIRECTORY) &&
1198             !S_ISDIR(dchild->d_inode->i_mode))
1199                 GOTO(cleanup, rc = -ENOTDIR);
1200                 
1201         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_OPEN_CREATE)) {
1202                 obd_fail_loc = OBD_FAIL_LDLM_REPLY | OBD_FAIL_ONCE;
1203                 GOTO(cleanup, rc = -EAGAIN);
1204         }
1205  
1206         /* Obtain OPEN lock as well */
1207         policy.l_inodebits.bits |= MDS_INODELOCK_OPEN;
1208
1209         /* We cannot use acc_mode here, because it is zeroed in case of
1210            creating a file, so we get wrong lockmode */
1211         if (accmode(rec->ur_flags) & MAY_WRITE)
1212                 child_mode = LCK_CW;
1213         else if (accmode(rec->ur_flags) & MAY_EXEC)
1214                 child_mode = LCK_PR;
1215         else
1216                 child_mode = LCK_CR;
1217
1218         if (!(lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY)) {
1219                 struct lustre_id sid;
1220                 
1221                 down(&dchild->d_inode->i_sem);
1222                 rc = mds_read_inode_sid(obd, dchild->d_inode, &sid);
1223                 up(&dchild->d_inode->i_sem);
1224                 if (rc) {
1225                         CERROR("Can't read inode self id, "
1226                                "inode %lu, rc %d\n",
1227                                dchild->d_inode->i_ino, rc);
1228                         GOTO(cleanup, rc);
1229                 }
1230                 
1231                 /* In case of replay we do not get a lock assuming that the
1232                    caller has it already */
1233                 child_res_id.name[0] = id_fid(&sid);
1234                 child_res_id.name[1] = id_group(&sid);
1235
1236                 rc = ldlm_cli_enqueue(NULL, NULL, obd->obd_namespace,
1237                                       child_res_id, LDLM_IBITS, &policy,
1238                                       child_mode, &lock_flags,
1239                                       mds_blocking_ast, ldlm_completion_ast,
1240                                       NULL, NULL, NULL, 0, NULL, child_lockh);
1241                 if (rc != ELDLM_OK)
1242                         GOTO(cleanup, rc);
1243
1244                 cleanup_phase = 3;
1245         }
1246
1247         /* Step 5: mds_open it */
1248         rc = mds_finish_open(req, dchild, body, rec->ur_flags, &handle,
1249                              rec, rep);
1250
1251         EXIT;
1252 cleanup:
1253         rc = mds_finish_transno(mds, dchild ? dchild->d_inode : NULL, handle,
1254                                 req, rc, rep ? rep->lock_policy_res1 : 0);
1255
1256 cleanup_no_trans:
1257         switch (cleanup_phase) {
1258         case 3:
1259                 if (rc) {
1260                         ldlm_lock_decref(child_lockh, child_mode);
1261                         child_lockh->cookie = 0;
1262                 }
1263         case 2:
1264                 if (rc && created) {
1265                         int err = vfs_unlink(dparent->d_inode, dchild);
1266                         if (err) {
1267                                 CERROR("unlink(%.*s) in error path: %d\n",
1268                                        dchild->d_name.len, dchild->d_name.name,
1269                                        err);
1270                         }
1271                 } else if (created) {
1272                         mds_lock_new_child(obd, dchild->d_inode, NULL);
1273                 }
1274                 l_dput(dchild);
1275         case 1:
1276                 if (dparent == NULL)
1277                         break;
1278
1279                 l_dput(dparent);
1280 #ifdef S_PDIROPS
1281                 if (parent_lockh[1].cookie != 0)
1282                         ldlm_lock_decref(parent_lockh + 1, update_mode);
1283 #endif
1284                 if (rc)
1285                         ldlm_lock_decref(parent_lockh, parent_mode);
1286                 else
1287                         ptlrpc_save_lock (req, parent_lockh, parent_mode);
1288         }
1289         if (mea)
1290                 OBD_FREE(mea, mea_size);
1291         if (rc == 0)
1292                 atomic_inc(&mds->mds_open_count);
1293
1294         /*
1295          * If we have not taken the "open" lock, we may not return 0 here,
1296          * because caller expects 0 to mean "lock is taken", and it needs
1297          * nonzero return here for caller to return EDLM_LOCK_ABORTED to
1298          * client. Later caller should rewrite the return value back to zero
1299          * if it to be used any further.
1300          */
1301         if ((cleanup_phase != 3) && !rc)
1302                 rc = ENOLCK;
1303         RETURN(rc);
1304 }
1305
1306 /* Close a "file descriptor" and possibly unlink an orphan from the
1307  * PENDING directory.  Caller must hold child->i_sem, this drops it. 
1308  *
1309  * If we are being called from mds_disconnect() because the client has
1310  * disappeared, then req == NULL and we do not update last_rcvd because
1311  * there is nothing that could be recovered by the client at this stage
1312  * (it will not even _have_ an entry in last_rcvd anymore).
1313  *
1314  * Returns EAGAIN if the client needs to get more data and re-close. */
1315 int mds_mfd_close(struct ptlrpc_request *req, int offset,
1316                   struct obd_device *obd, struct mds_file_data *mfd,
1317                   int unlink_orphan)
1318 {
1319         struct inode *inode = mfd->mfd_dentry->d_inode;
1320         char idname[LL_ID_NAMELEN];
1321         int last_orphan, idlen, rc = 0, cleanup_phase = 0;
1322         struct dentry *pending_child = NULL;
1323         struct mds_obd *mds = &obd->u.mds;
1324         struct inode *pending_dir = mds->mds_pending_dir->d_inode;
1325         void *handle = NULL;
1326         struct mds_body *request_body = NULL, *reply_body = NULL;
1327         struct dentry_params dp;
1328         struct iattr iattr = { 0 };
1329         struct llog_create_locks *lcl = NULL;
1330         ENTRY;
1331
1332         if (req && req->rq_reqmsg != NULL)
1333                 request_body = lustre_msg_buf(req->rq_reqmsg, offset,
1334                                               sizeof(*request_body));
1335         if (req && req->rq_repmsg != NULL)
1336                 reply_body = lustre_msg_buf(req->rq_repmsg, 0,
1337                                             sizeof(*reply_body));
1338
1339         idlen = ll_id2str(idname, inode->i_ino, inode->i_generation);
1340         CDEBUG(D_INODE, "inode %p ino %s nlink %d orphan %d\n", inode, 
1341                idname, inode->i_nlink, mds_orphan_open_count(inode));
1342
1343         last_orphan = mds_orphan_open_dec_test(inode) &&
1344                 mds_inode_is_orphan(inode);
1345         UP_WRITE_I_ALLOC_SEM(inode);
1346
1347         /* this is half of the actual "close" */
1348         if (mfd->mfd_mode & FMODE_WRITE) {
1349                 rc = mds_put_write_access(mds, inode, request_body,
1350                                           last_orphan && unlink_orphan);
1351         } else if (mfd->mfd_mode & FMODE_EXEC) {
1352                 mds_allow_write_access(inode);
1353         }
1354
1355         if (last_orphan && unlink_orphan) {
1356                 struct lov_mds_md *lmm = NULL;
1357                 int stripe_count = 0;
1358                 LASSERT(rc == 0); /* mds_put_write_access must have succeeded */
1359
1360                 if (obd->obd_recovering) {
1361                         CDEBUG(D_HA, "not remove orphan %s until recovery"
1362                                " is over\n", idname);
1363                         GOTO(out, rc);
1364                 }
1365
1366                 CDEBUG(D_HA, "destroying orphan object %s\n", idname);
1367                 
1368                 if ((S_ISREG(inode->i_mode) && inode->i_nlink != 1) ||
1369                     (S_ISDIR(inode->i_mode) && inode->i_nlink != 2))
1370                         CERROR("found \"orphan\" %s %s with link count %d\n",
1371                                S_ISREG(inode->i_mode) ? "file" : "dir",
1372                                idname, inode->i_nlink);
1373                 /*
1374                  * sadly, there is no easy way to save pending_child from
1375                  * mds_reint_unlink() into mfd, so we need to re-lookup, but
1376                  * normally it will still be in the dcache.
1377                  */
1378                 down(&pending_dir->i_sem);
1379                 cleanup_phase = 1; /* up(i_sem) when finished */
1380                 pending_child = lookup_one_len(idname, mds->mds_pending_dir,
1381                                                idlen);
1382                 if (IS_ERR(pending_child))
1383                         GOTO(cleanup, rc = PTR_ERR(pending_child));
1384                 LASSERT(pending_child->d_inode != NULL);
1385
1386                 cleanup_phase = 2; /* dput(pending_child) when finished */
1387                 if (S_ISDIR(pending_child->d_inode->i_mode)) {
1388                         rc = vfs_rmdir(pending_dir, pending_child);
1389                         if (rc)
1390                                 CERROR("error unlinking orphan dir %s: rc %d\n",
1391                                        idname, rc);
1392                         goto out;
1393                 }
1394
1395                 if (req != NULL && req->rq_repmsg != NULL) {
1396                         lmm = lustre_msg_buf(req->rq_repmsg, 1, 0);
1397                         stripe_count = le32_to_cpu(lmm->lmm_stripe_count);
1398                 }
1399
1400                 handle = fsfilt_start_log(obd, pending_dir, FSFILT_OP_UNLINK,
1401                                           NULL, stripe_count);
1402                 if (IS_ERR(handle)) {
1403                         rc = PTR_ERR(handle);
1404                         handle = NULL;
1405                         GOTO(cleanup, rc);
1406                 }
1407
1408                 pending_child->d_fsdata = (void *) &dp;
1409                 dp.p_inum = 0;
1410                 dp.p_ptr = req;
1411                 rc = vfs_unlink(pending_dir, pending_child);
1412                 if (rc)
1413                         CERROR("error unlinking orphan %s: rc %d\n",
1414                                idname, rc);
1415
1416                 if (req != NULL && req->rq_repmsg != NULL &&
1417                     (reply_body->valid & OBD_MD_FLEASIZE) &&
1418                     mds_log_op_unlink(obd, pending_child->d_inode,
1419                                       lmm, req->rq_repmsg->buflens[1],
1420                                       lustre_msg_buf(req->rq_repmsg, 2, 0),
1421                                       req->rq_repmsg->buflens[2], &lcl) > 0) {
1422                         reply_body->valid |= OBD_MD_FLCOOKIE;
1423                 }
1424
1425                 goto out; /* Don't bother updating attrs on unlinked inode */
1426         }
1427
1428 #if 0
1429         if (request_body != NULL && mfd->mfd_mode & FMODE_WRITE && rc == 0) {
1430                 /* Update the on-disk attributes if this was the last write
1431                  * close, and all information was provided (i.e., rc == 0)
1432                  *
1433                  * XXX this should probably be abstracted with mds_reint_setattr
1434                  */
1435
1436                 if (request_body->valid & OBD_MD_FLMTIME &&
1437                     LTIME_S(request_body->mtime) > LTIME_S(inode->i_mtime)) {
1438                         LTIME_S(iattr.ia_mtime) = LTIME_S(request_body->mtime);
1439                         iattr.ia_valid |= ATTR_MTIME;
1440                 }
1441                 if (request_body->valid & OBD_MD_FLCTIME &&
1442                     LTIME_S(request_body->ctime) > LTIME_S(inode->i_ctime)) {
1443                         LTIME_S(iattr.ia_ctime) = LTIME_S(request_body->ctime);
1444                         iattr.ia_valid |= ATTR_CTIME;
1445                 }
1446
1447                 /* XXX can't set block count with fsfilt_setattr (!) */
1448                 if (request_body->valid & OBD_MD_FLSIZE) {
1449                         iattr.ia_valid |= ATTR_SIZE;
1450                         iattr.ia_size = request_body->size;
1451                 }
1452                 /* if (request_body->valid & OBD_MD_FLBLOCKS) {
1453                         iattr.ia_valid |= ATTR_BLOCKS;
1454                         iattr.ia_blocks = request_body->blocks
1455                 } */
1456
1457         }
1458 #endif
1459         if (request_body != NULL && request_body->valid & OBD_MD_FLATIME) {
1460                 /* Only start a transaction to write out only the atime if
1461                  * it is more out-of-date than the specified limit.  If we
1462                  * are already going to write out the atime then do it anyway.
1463                  * */
1464                 if ((request_body->atime >
1465                      LTIME_S(inode->i_atime) + MAX_ATIME_DIFF) ||
1466                     (iattr.ia_valid != 0 &&
1467                      request_body->atime > LTIME_S(inode->i_atime))) {
1468                         LTIME_S(iattr.ia_atime) = request_body->atime;
1469                         iattr.ia_valid |= ATTR_ATIME;
1470                 }
1471         }
1472
1473         if (iattr.ia_valid != 0) {
1474                 handle = fsfilt_start(obd, inode, FSFILT_OP_SETATTR, NULL);
1475                 if (IS_ERR(handle))
1476                         GOTO(cleanup, rc = PTR_ERR(handle));
1477                 rc = fsfilt_setattr(obd, mfd->mfd_dentry, handle, &iattr, 0);
1478                 if (rc)
1479                         CERROR("error in setattr(%s): rc %d\n", idname, rc);
1480         }
1481 out:
1482         /* If other clients have this file open for write, rc will be > 0 */
1483         if (rc > 0)
1484                 rc = 0;
1485         l_dput(mfd->mfd_dentry);
1486         mds_mfd_destroy(mfd);
1487
1488  cleanup:
1489         atomic_dec(&mds->mds_open_count);
1490         if (req != NULL && reply_body != NULL) {
1491                 rc = mds_finish_transno(mds, pending_dir, handle, req, rc, 0);
1492         } else if (handle) {
1493                 int err, force_sync = 0;
1494
1495                 if (req && req->rq_export)
1496                         force_sync = req->rq_export->exp_sync;
1497
1498                 err = fsfilt_commit(obd, mds->mds_sb, pending_dir, handle, 
1499                                     force_sync);
1500                 if (err) {
1501                         CERROR("error committing close: %d\n", err);
1502                         if (!rc)
1503                                 rc = err;
1504                 }
1505         }
1506
1507         switch (cleanup_phase) {
1508         case 2:
1509                 if (lcl != NULL)
1510                         ptlrpc_save_llog_lock(req, lcl);
1511                 dput(pending_child);
1512         case 1:
1513                 up(&pending_dir->i_sem);
1514         }
1515         RETURN(rc);
1516 }
1517
1518 int mds_close(struct ptlrpc_request *req, int offset)
1519 {
1520         struct mds_export_data *med = &req->rq_export->exp_mds_data;
1521         struct obd_device *obd = req->rq_export->exp_obd;
1522         struct mds_body *body;
1523         struct mds_file_data *mfd;
1524         struct lvfs_run_ctxt saved;
1525         struct inode *inode;
1526         int rc, repsize[3] = {sizeof(struct mds_body),
1527                               obd->u.mds.mds_max_mdsize,
1528                               obd->u.mds.mds_max_cookiesize};
1529         ENTRY;
1530         MD_COUNTER_INCREMENT(obd, close);
1531
1532         rc = lustre_pack_reply(req, 3, repsize, NULL);
1533         if (rc) {
1534                 CERROR("lustre_pack_reply: rc = %d\n", rc);
1535                 req->rq_status = rc;
1536         } else {
1537                 MDS_CHECK_RESENT(req, mds_reconstruct_generic(req));
1538         }
1539
1540         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY) {
1541                 DEBUG_REQ(D_HA, req, "close replay\n");
1542                 memcpy(lustre_msg_buf(req->rq_repmsg, 2, 0),
1543                        lustre_msg_buf(req->rq_reqmsg, offset + 1, 0),
1544                        req->rq_repmsg->buflens[2]);
1545         }
1546
1547         body = lustre_swab_reqbuf(req, offset, sizeof(*body),
1548                                   lustre_swab_mds_body);
1549         if (body == NULL) {
1550                 CERROR("Can't unpack body\n");
1551                 req->rq_status = -EFAULT;
1552                 RETURN(-EFAULT);
1553         }
1554
1555         if (body->flags & MDS_BFLAG_UNCOMMITTED_WRITES)
1556                 /* do some stuff */ ;
1557
1558         mfd = mds_handle2mfd(&body->handle);
1559         if (mfd == NULL) {
1560                 DEBUG_REQ(D_ERROR, req, "no handle for file close ino "LPD64
1561                           ": cookie "LPX64, id_ino(&body->id1), body->handle.cookie);
1562                 req->rq_status = -ESTALE;
1563                 RETURN(-ESTALE);
1564         }
1565
1566         inode = mfd->mfd_dentry->d_inode;
1567         /* child i_alloc_sem protects orphan_dec_test && is_orphan race */
1568         DOWN_WRITE_I_ALLOC_SEM(inode); /* mds_mfd_close drops this */
1569         if (mds_inode_is_orphan(inode) && mds_orphan_open_count(inode) == 1) {
1570                 struct mds_body *rep_body;
1571
1572                 rep_body = lustre_msg_buf(req->rq_repmsg, 0,
1573                                           sizeof (*rep_body));
1574                 LASSERT(rep_body != NULL);
1575
1576                 mds_pack_inode2body(obd, rep_body, inode,
1577                                     (body->valid & OBD_MD_FID) ? 1 : 0);
1578                 
1579                 mds_pack_md(obd, req->rq_repmsg, 1, rep_body, 
1580                             inode, MDS_PACK_MD_LOCK, 0);
1581         }
1582         spin_lock(&med->med_open_lock);
1583         list_del(&mfd->mfd_list);
1584         spin_unlock(&med->med_open_lock);
1585
1586         push_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
1587         req->rq_status = mds_mfd_close(req, offset, obd, mfd, 1);
1588         pop_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
1589
1590         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_CLOSE_PACK)) {
1591                 CERROR("test case OBD_FAIL_MDS_CLOSE_PACK\n");
1592                 req->rq_status = -ENOMEM;
1593                 mds_mfd_put(mfd);
1594                 RETURN(-ENOMEM);
1595         }
1596
1597         mds_mfd_put(mfd);
1598         RETURN(0);
1599 }
1600
1601 int mds_done_writing(struct ptlrpc_request *req, int offset)
1602 {
1603         struct mds_body *body;
1604         int rc, size = sizeof(struct mds_body);
1605         ENTRY;
1606
1607         MDS_CHECK_RESENT(req, mds_reconstruct_generic(req));
1608
1609         body = lustre_swab_reqbuf(req, offset, sizeof(*body),
1610                                   lustre_swab_mds_body);
1611         if (body == NULL) {
1612                 CERROR("Can't unpack body\n");
1613                 req->rq_status = -EFAULT;
1614                 RETURN(-EFAULT);
1615         }
1616
1617         rc = lustre_pack_reply(req, 1, &size, NULL);
1618         if (rc) {
1619                 CERROR("lustre_pack_reply: rc = %d\n", rc);
1620                 req->rq_status = rc;
1621         }
1622
1623         RETURN(0);
1624 }