Whamcloud - gitweb
LU-4429 llite: fix open lock matching in ll_md_blocking_ast()
[fs/lustre-release.git] / lustre / llite / file.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
19  *
20  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
21  * CA 95054 USA or visit www.sun.com if you need additional information or
22  * have any questions.
23  *
24  * GPL HEADER END
25  */
26 /*
27  * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2011, 2013, Intel Corporation.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * lustre/llite/file.c
37  *
38  * Author: Peter Braam <braam@clusterfs.com>
39  * Author: Phil Schwan <phil@clusterfs.com>
40  * Author: Andreas Dilger <adilger@clusterfs.com>
41  */
42
43 #define DEBUG_SUBSYSTEM S_LLITE
44 #include <lustre_dlm.h>
45 #include <lustre_lite.h>
46 #include <linux/pagemap.h>
47 #include <linux/file.h>
48 #include "llite_internal.h"
49 #include <lustre/ll_fiemap.h>
50
51 #include "cl_object.h"
52
53 struct ll_file_data *ll_file_data_get(void)
54 {
55         struct ll_file_data *fd;
56
57         OBD_SLAB_ALLOC_PTR_GFP(fd, ll_file_data_slab, __GFP_IO);
58         if (fd == NULL)
59                 return NULL;
60
61         fd->fd_write_failed = false;
62
63         return fd;
64 }
65
66 static void ll_file_data_put(struct ll_file_data *fd)
67 {
68         if (fd != NULL)
69                 OBD_SLAB_FREE_PTR(fd, ll_file_data_slab);
70 }
71
72 void ll_pack_inode2opdata(struct inode *inode, struct md_op_data *op_data,
73                           struct lustre_handle *fh)
74 {
75         op_data->op_fid1 = ll_i2info(inode)->lli_fid;
76         op_data->op_attr.ia_mode = inode->i_mode;
77         op_data->op_attr.ia_atime = inode->i_atime;
78         op_data->op_attr.ia_mtime = inode->i_mtime;
79         op_data->op_attr.ia_ctime = inode->i_ctime;
80         op_data->op_attr.ia_size = i_size_read(inode);
81         op_data->op_attr_blocks = inode->i_blocks;
82         ((struct ll_iattr *)&op_data->op_attr)->ia_attr_flags =
83                                         ll_inode_to_ext_flags(inode->i_flags);
84         op_data->op_ioepoch = ll_i2info(inode)->lli_ioepoch;
85         if (fh)
86                 op_data->op_handle = *fh;
87         op_data->op_capa1 = ll_mdscapa_get(inode);
88
89         if (LLIF_DATA_MODIFIED & ll_i2info(inode)->lli_flags)
90                 op_data->op_bias |= MDS_DATA_MODIFIED;
91 }
92
93 /**
94  * Closes the IO epoch and packs all the attributes into @op_data for
95  * the CLOSE rpc.
96  */
97 static void ll_prepare_close(struct inode *inode, struct md_op_data *op_data,
98                              struct obd_client_handle *och)
99 {
100         ENTRY;
101
102         op_data->op_attr.ia_valid = ATTR_MODE | ATTR_ATIME | ATTR_ATIME_SET |
103                                         ATTR_MTIME | ATTR_MTIME_SET |
104                                         ATTR_CTIME | ATTR_CTIME_SET;
105
106         if (!(och->och_flags & FMODE_WRITE))
107                 goto out;
108
109         if (!exp_connect_som(ll_i2mdexp(inode)) || !S_ISREG(inode->i_mode))
110                 op_data->op_attr.ia_valid |= ATTR_SIZE | ATTR_BLOCKS;
111         else
112                 ll_ioepoch_close(inode, op_data, &och, 0);
113
114 out:
115         ll_pack_inode2opdata(inode, op_data, &och->och_fh);
116         ll_prep_md_op_data(op_data, inode, NULL, NULL,
117                            0, 0, LUSTRE_OPC_ANY, NULL);
118         EXIT;
119 }
120
121 static int ll_close_inode_openhandle(struct obd_export *md_exp,
122                                      struct inode *inode,
123                                      struct obd_client_handle *och,
124                                      const __u64 *data_version)
125 {
126         struct obd_export *exp = ll_i2mdexp(inode);
127         struct md_op_data *op_data;
128         struct ptlrpc_request *req = NULL;
129         struct obd_device *obd = class_exp2obd(exp);
130         int epoch_close = 1;
131         int rc;
132         ENTRY;
133
134         if (obd == NULL) {
135                 /*
136                  * XXX: in case of LMV, is this correct to access
137                  * ->exp_handle?
138                  */
139                 CERROR("Invalid MDC connection handle "LPX64"\n",
140                        ll_i2mdexp(inode)->exp_handle.h_cookie);
141                 GOTO(out, rc = 0);
142         }
143
144         OBD_ALLOC_PTR(op_data);
145         if (op_data == NULL)
146                 GOTO(out, rc = -ENOMEM); // XXX We leak openhandle and request here.
147
148         ll_prepare_close(inode, op_data, och);
149         if (data_version != NULL) {
150                 /* Pass in data_version implies release. */
151                 op_data->op_bias |= MDS_HSM_RELEASE;
152                 op_data->op_data_version = *data_version;
153                 op_data->op_lease_handle = och->och_lease_handle;
154                 op_data->op_attr.ia_valid |= ATTR_SIZE | ATTR_BLOCKS;
155         }
156         epoch_close = (op_data->op_flags & MF_EPOCH_CLOSE);
157         rc = md_close(md_exp, op_data, och->och_mod, &req);
158         if (rc == -EAGAIN) {
159                 /* This close must have the epoch closed. */
160                 LASSERT(epoch_close);
161                 /* MDS has instructed us to obtain Size-on-MDS attribute from
162                  * OSTs and send setattr to back to MDS. */
163                 rc = ll_som_update(inode, op_data);
164                 if (rc) {
165                         CERROR("%s: inode "DFID" mdc Size-on-MDS update"
166                                " failed: rc = %d\n",
167                                ll_i2mdexp(inode)->exp_obd->obd_name,
168                                PFID(ll_inode2fid(inode)), rc);
169                         rc = 0;
170                 }
171         } else if (rc) {
172                 CERROR("%s: inode "DFID" mdc close failed: rc = %d\n",
173                        ll_i2mdexp(inode)->exp_obd->obd_name,
174                        PFID(ll_inode2fid(inode)), rc);
175         }
176
177         /* DATA_MODIFIED flag was successfully sent on close, cancel data
178          * modification flag. */
179         if (rc == 0 && (op_data->op_bias & MDS_DATA_MODIFIED)) {
180                 struct ll_inode_info *lli = ll_i2info(inode);
181
182                 spin_lock(&lli->lli_lock);
183                 lli->lli_flags &= ~LLIF_DATA_MODIFIED;
184                 spin_unlock(&lli->lli_lock);
185         }
186
187         if (rc == 0) {
188                 rc = ll_objects_destroy(req, inode);
189                 if (rc)
190                         CERROR("%s: inode "DFID
191                                " ll_objects destroy: rc = %d\n",
192                                ll_i2mdexp(inode)->exp_obd->obd_name,
193                                PFID(ll_inode2fid(inode)), rc);
194         }
195
196         if (rc == 0 && op_data->op_bias & MDS_HSM_RELEASE) {
197                 struct mdt_body *body;
198                 body = req_capsule_server_get(&req->rq_pill, &RMF_MDT_BODY);
199                 if (!(body->valid & OBD_MD_FLRELEASED))
200                         rc = -EBUSY;
201         }
202
203         ll_finish_md_op_data(op_data);
204         EXIT;
205 out:
206
207         if (exp_connect_som(exp) && !epoch_close &&
208             S_ISREG(inode->i_mode) && (och->och_flags & FMODE_WRITE)) {
209                 ll_queue_done_writing(inode, LLIF_DONE_WRITING);
210         } else {
211                 md_clear_open_replay_data(md_exp, och);
212                 /* Free @och if it is not waiting for DONE_WRITING. */
213                 och->och_fh.cookie = DEAD_HANDLE_MAGIC;
214                 OBD_FREE_PTR(och);
215         }
216         if (req) /* This is close request */
217                 ptlrpc_req_finished(req);
218         return rc;
219 }
220
221 int ll_md_real_close(struct inode *inode, fmode_t fmode)
222 {
223         struct ll_inode_info *lli = ll_i2info(inode);
224         struct obd_client_handle **och_p;
225         struct obd_client_handle *och;
226         __u64 *och_usecount;
227         int rc = 0;
228         ENTRY;
229
230         if (fmode & FMODE_WRITE) {
231                 och_p = &lli->lli_mds_write_och;
232                 och_usecount = &lli->lli_open_fd_write_count;
233         } else if (fmode & FMODE_EXEC) {
234                 och_p = &lli->lli_mds_exec_och;
235                 och_usecount = &lli->lli_open_fd_exec_count;
236         } else {
237                 LASSERT(fmode & FMODE_READ);
238                 och_p = &lli->lli_mds_read_och;
239                 och_usecount = &lli->lli_open_fd_read_count;
240         }
241
242         mutex_lock(&lli->lli_och_mutex);
243         if (*och_usecount > 0) {
244                 /* There are still users of this handle, so skip
245                  * freeing it. */
246                 mutex_unlock(&lli->lli_och_mutex);
247                 RETURN(0);
248         }
249
250         och = *och_p;
251         *och_p = NULL;
252         mutex_unlock(&lli->lli_och_mutex);
253
254         if (och != NULL) {
255                 /* There might be a race and this handle may already
256                  * be closed. */
257                 rc = ll_close_inode_openhandle(ll_i2sbi(inode)->ll_md_exp,
258                                                inode, och, NULL);
259         }
260
261         RETURN(rc);
262 }
263
264 int ll_md_close(struct obd_export *md_exp, struct inode *inode,
265                 struct file *file)
266 {
267         struct ll_file_data *fd = LUSTRE_FPRIVATE(file);
268         struct ll_inode_info *lli = ll_i2info(inode);
269         int rc = 0;
270         ENTRY;
271
272         /* clear group lock, if present */
273         if (unlikely(fd->fd_flags & LL_FILE_GROUP_LOCKED))
274                 ll_put_grouplock(inode, file, fd->fd_grouplock.cg_gid);
275
276         if (fd->fd_lease_och != NULL) {
277                 bool lease_broken;
278
279                 /* Usually the lease is not released when the
280                  * application crashed, we need to release here. */
281                 rc = ll_lease_close(fd->fd_lease_och, inode, &lease_broken);
282                 CDEBUG(rc ? D_ERROR : D_INODE, "Clean up lease "DFID" %d/%d\n",
283                         PFID(&lli->lli_fid), rc, lease_broken);
284
285                 fd->fd_lease_och = NULL;
286         }
287
288         if (fd->fd_och != NULL) {
289                 rc = ll_close_inode_openhandle(md_exp, inode, fd->fd_och, NULL);
290                 fd->fd_och = NULL;
291                 GOTO(out, rc);
292         }
293
294         /* Let's see if we have good enough OPEN lock on the file and if
295            we can skip talking to MDS */
296         if (file->f_dentry->d_inode) { /* Can this ever be false? */
297                 int lockmode;
298                 __u64 flags = LDLM_FL_BLOCK_GRANTED | LDLM_FL_TEST_LOCK;
299                 struct lustre_handle lockh;
300                 struct inode *inode = file->f_dentry->d_inode;
301                 ldlm_policy_data_t policy = {.l_inodebits={MDS_INODELOCK_OPEN}};
302
303                 mutex_lock(&lli->lli_och_mutex);
304                 if (fd->fd_omode & FMODE_WRITE) {
305                         lockmode = LCK_CW;
306                         LASSERT(lli->lli_open_fd_write_count);
307                         lli->lli_open_fd_write_count--;
308                 } else if (fd->fd_omode & FMODE_EXEC) {
309                         lockmode = LCK_PR;
310                         LASSERT(lli->lli_open_fd_exec_count);
311                         lli->lli_open_fd_exec_count--;
312                 } else {
313                         lockmode = LCK_CR;
314                         LASSERT(lli->lli_open_fd_read_count);
315                         lli->lli_open_fd_read_count--;
316                 }
317                 mutex_unlock(&lli->lli_och_mutex);
318
319                 if (!md_lock_match(md_exp, flags, ll_inode2fid(inode),
320                                    LDLM_IBITS, &policy, lockmode,
321                                    &lockh)) {
322                         rc = ll_md_real_close(file->f_dentry->d_inode,
323                                               fd->fd_omode);
324                 }
325         } else {
326                 CERROR("Releasing a file %p with negative dentry %p. Name %s",
327                        file, file->f_dentry, file->f_dentry->d_name.name);
328         }
329
330 out:
331         LUSTRE_FPRIVATE(file) = NULL;
332         ll_file_data_put(fd);
333         ll_capa_close(inode);
334
335         RETURN(rc);
336 }
337
338 /* While this returns an error code, fput() the caller does not, so we need
339  * to make every effort to clean up all of our state here.  Also, applications
340  * rarely check close errors and even if an error is returned they will not
341  * re-try the close call.
342  */
343 int ll_file_release(struct inode *inode, struct file *file)
344 {
345         struct ll_file_data *fd;
346         struct ll_sb_info *sbi = ll_i2sbi(inode);
347         struct ll_inode_info *lli = ll_i2info(inode);
348         int rc;
349         ENTRY;
350
351         CDEBUG(D_VFSTRACE, "VFS Op:inode="DFID"(%p)\n",
352                PFID(ll_inode2fid(inode)), inode);
353
354 #ifdef CONFIG_FS_POSIX_ACL
355         if (sbi->ll_flags & LL_SBI_RMT_CLIENT &&
356             inode == inode->i_sb->s_root->d_inode) {
357                 struct ll_file_data *fd = LUSTRE_FPRIVATE(file);
358
359                 LASSERT(fd != NULL);
360                 if (unlikely(fd->fd_flags & LL_FILE_RMTACL)) {
361                         fd->fd_flags &= ~LL_FILE_RMTACL;
362                         rct_del(&sbi->ll_rct, current_pid());
363                         et_search_free(&sbi->ll_et, current_pid());
364                 }
365         }
366 #endif
367
368         if (inode->i_sb->s_root != file->f_dentry)
369                 ll_stats_ops_tally(sbi, LPROC_LL_RELEASE, 1);
370         fd = LUSTRE_FPRIVATE(file);
371         LASSERT(fd != NULL);
372
373         /* The last ref on @file, maybe not the the owner pid of statahead.
374          * Different processes can open the same dir, "ll_opendir_key" means:
375          * it is me that should stop the statahead thread. */
376         if (S_ISDIR(inode->i_mode) && lli->lli_opendir_key == fd &&
377             lli->lli_opendir_pid != 0)
378                 ll_stop_statahead(inode, lli->lli_opendir_key);
379
380         if (inode->i_sb->s_root == file->f_dentry) {
381                 LUSTRE_FPRIVATE(file) = NULL;
382                 ll_file_data_put(fd);
383                 RETURN(0);
384         }
385
386         if (!S_ISDIR(inode->i_mode)) {
387                 lov_read_and_clear_async_rc(lli->lli_clob);
388                 lli->lli_async_rc = 0;
389         }
390
391         rc = ll_md_close(sbi->ll_md_exp, inode, file);
392
393         if (CFS_FAIL_TIMEOUT_MS(OBD_FAIL_PTLRPC_DUMP_LOG, cfs_fail_val))
394                 libcfs_debug_dumplog();
395
396         RETURN(rc);
397 }
398
399 static int ll_intent_file_open(struct file *file, void *lmm,
400                                int lmmsize, struct lookup_intent *itp)
401 {
402         struct ll_sb_info *sbi = ll_i2sbi(file->f_dentry->d_inode);
403         struct dentry *parent = file->f_dentry->d_parent;
404         const char *name = file->f_dentry->d_name.name;
405         const int len = file->f_dentry->d_name.len;
406         struct md_op_data *op_data;
407         struct ptlrpc_request *req;
408         __u32 opc = LUSTRE_OPC_ANY;
409         int rc;
410         ENTRY;
411
412         if (!parent)
413                 RETURN(-ENOENT);
414
415         /* Usually we come here only for NFSD, and we want open lock.
416            But we can also get here with pre 2.6.15 patchless kernels, and in
417            that case that lock is also ok */
418         /* We can also get here if there was cached open handle in revalidate_it
419          * but it disappeared while we were getting from there to ll_file_open.
420          * But this means this file was closed and immediatelly opened which
421          * makes a good candidate for using OPEN lock */
422         /* If lmmsize & lmm are not 0, we are just setting stripe info
423          * parameters. No need for the open lock */
424         if (lmm == NULL && lmmsize == 0) {
425                 itp->it_flags |= MDS_OPEN_LOCK;
426                 if (itp->it_flags & FMODE_WRITE)
427                         opc = LUSTRE_OPC_CREATE;
428         }
429
430         op_data  = ll_prep_md_op_data(NULL, parent->d_inode,
431                                       file->f_dentry->d_inode, name, len,
432                                       O_RDWR, opc, NULL);
433         if (IS_ERR(op_data))
434                 RETURN(PTR_ERR(op_data));
435
436         itp->it_flags |= MDS_OPEN_BY_FID;
437         rc = md_intent_lock(sbi->ll_md_exp, op_data, lmm, lmmsize, itp,
438                             0 /*unused */, &req, ll_md_blocking_ast, 0);
439         ll_finish_md_op_data(op_data);
440         if (rc == -ESTALE) {
441                 /* reason for keep own exit path - don`t flood log
442                 * with messages with -ESTALE errors.
443                 */
444                 if (!it_disposition(itp, DISP_OPEN_OPEN) ||
445                      it_open_error(DISP_OPEN_OPEN, itp))
446                         GOTO(out, rc);
447                 ll_release_openhandle(file->f_dentry, itp);
448                 GOTO(out, rc);
449         }
450
451         if (it_disposition(itp, DISP_LOOKUP_NEG))
452                 GOTO(out, rc = -ENOENT);
453
454         if (rc != 0 || it_open_error(DISP_OPEN_OPEN, itp)) {
455                 rc = rc ? rc : it_open_error(DISP_OPEN_OPEN, itp);
456                 CDEBUG(D_VFSTRACE, "lock enqueue: err: %d\n", rc);
457                 GOTO(out, rc);
458         }
459
460         rc = ll_prep_inode(&file->f_dentry->d_inode, req, NULL, itp);
461         if (!rc && itp->d.lustre.it_lock_mode)
462                 ll_set_lock_data(sbi->ll_md_exp, file->f_dentry->d_inode,
463                                  itp, NULL);
464
465 out:
466         ptlrpc_req_finished(req);
467         ll_intent_drop_lock(itp);
468
469         RETURN(rc);
470 }
471
472 /**
473  * Assign an obtained @ioepoch to client's inode. No lock is needed, MDS does
474  * not believe attributes if a few ioepoch holders exist. Attributes for
475  * previous ioepoch if new one is opened are also skipped by MDS.
476  */
477 void ll_ioepoch_open(struct ll_inode_info *lli, __u64 ioepoch)
478 {
479         if (ioepoch && lli->lli_ioepoch != ioepoch) {
480                 lli->lli_ioepoch = ioepoch;
481                 CDEBUG(D_INODE, "Epoch "LPU64" opened on "DFID"\n",
482                        ioepoch, PFID(&lli->lli_fid));
483         }
484 }
485
486 static int ll_och_fill(struct obd_export *md_exp, struct lookup_intent *it,
487                        struct obd_client_handle *och)
488 {
489         struct ptlrpc_request *req = it->d.lustre.it_data;
490         struct mdt_body *body;
491
492         body = req_capsule_server_get(&req->rq_pill, &RMF_MDT_BODY);
493         och->och_fh = body->handle;
494         och->och_fid = body->fid1;
495         och->och_lease_handle.cookie = it->d.lustre.it_lock_handle;
496         och->och_magic = OBD_CLIENT_HANDLE_MAGIC;
497         och->och_flags = it->it_flags;
498
499         return md_set_open_replay_data(md_exp, och, it);
500 }
501
502 int ll_local_open(struct file *file, struct lookup_intent *it,
503                   struct ll_file_data *fd, struct obd_client_handle *och)
504 {
505         struct inode *inode = file->f_dentry->d_inode;
506         struct ll_inode_info *lli = ll_i2info(inode);
507         ENTRY;
508
509         LASSERT(!LUSTRE_FPRIVATE(file));
510
511         LASSERT(fd != NULL);
512
513         if (och) {
514                 struct ptlrpc_request *req = it->d.lustre.it_data;
515                 struct mdt_body *body;
516                 int rc;
517
518                 rc = ll_och_fill(ll_i2sbi(inode)->ll_md_exp, it, och);
519                 if (rc != 0)
520                         RETURN(rc);
521
522                 body = req_capsule_server_get(&req->rq_pill, &RMF_MDT_BODY);
523                 ll_ioepoch_open(lli, body->ioepoch);
524         }
525
526         LUSTRE_FPRIVATE(file) = fd;
527         ll_readahead_init(inode, &fd->fd_ras);
528         fd->fd_omode = it->it_flags & (FMODE_READ | FMODE_WRITE | FMODE_EXEC);
529
530         RETURN(0);
531 }
532
533 /* Open a file, and (for the very first open) create objects on the OSTs at
534  * this time.  If opened with O_LOV_DELAY_CREATE, then we don't do the object
535  * creation or open until ll_lov_setstripe() ioctl is called.
536  *
537  * If we already have the stripe MD locally then we don't request it in
538  * md_open(), by passing a lmm_size = 0.
539  *
540  * It is up to the application to ensure no other processes open this file
541  * in the O_LOV_DELAY_CREATE case, or the default striping pattern will be
542  * used.  We might be able to avoid races of that sort by getting lli_open_sem
543  * before returning in the O_LOV_DELAY_CREATE case and dropping it here
544  * or in ll_file_release(), but I'm not sure that is desirable/necessary.
545  */
546 int ll_file_open(struct inode *inode, struct file *file)
547 {
548         struct ll_inode_info *lli = ll_i2info(inode);
549         struct lookup_intent *it, oit = { .it_op = IT_OPEN,
550                                           .it_flags = file->f_flags };
551         struct obd_client_handle **och_p = NULL;
552         __u64 *och_usecount = NULL;
553         struct ll_file_data *fd;
554         int rc = 0, opendir_set = 0;
555         ENTRY;
556
557         CDEBUG(D_VFSTRACE, "VFS Op:inode="DFID"(%p), flags %o\n",
558                PFID(ll_inode2fid(inode)), inode, file->f_flags);
559
560         it = file->private_data; /* XXX: compat macro */
561         file->private_data = NULL; /* prevent ll_local_open assertion */
562
563         fd = ll_file_data_get();
564         if (fd == NULL)
565                 GOTO(out_openerr, rc = -ENOMEM);
566
567         fd->fd_file = file;
568         if (S_ISDIR(inode->i_mode)) {
569                 spin_lock(&lli->lli_sa_lock);
570                 if (lli->lli_opendir_key == NULL && lli->lli_sai == NULL &&
571                     lli->lli_opendir_pid == 0) {
572                         lli->lli_opendir_key = fd;
573                         lli->lli_opendir_pid = current_pid();
574                         opendir_set = 1;
575                 }
576                 spin_unlock(&lli->lli_sa_lock);
577         }
578
579         if (inode->i_sb->s_root == file->f_dentry) {
580                 LUSTRE_FPRIVATE(file) = fd;
581                 RETURN(0);
582         }
583
584         if (!it || !it->d.lustre.it_disposition) {
585                 /* Convert f_flags into access mode. We cannot use file->f_mode,
586                  * because everything but O_ACCMODE mask was stripped from
587                  * there */
588                 if ((oit.it_flags + 1) & O_ACCMODE)
589                         oit.it_flags++;
590                 if (file->f_flags & O_TRUNC)
591                         oit.it_flags |= FMODE_WRITE;
592
593                 /* kernel only call f_op->open in dentry_open.  filp_open calls
594                  * dentry_open after call to open_namei that checks permissions.
595                  * Only nfsd_open call dentry_open directly without checking
596                  * permissions and because of that this code below is safe. */
597                 if (oit.it_flags & (FMODE_WRITE | FMODE_READ))
598                         oit.it_flags |= MDS_OPEN_OWNEROVERRIDE;
599
600                 /* We do not want O_EXCL here, presumably we opened the file
601                  * already? XXX - NFS implications? */
602                 oit.it_flags &= ~O_EXCL;
603
604                 /* bug20584, if "it_flags" contains O_CREAT, the file will be
605                  * created if necessary, then "IT_CREAT" should be set to keep
606                  * consistent with it */
607                 if (oit.it_flags & O_CREAT)
608                         oit.it_op |= IT_CREAT;
609
610                 it = &oit;
611         }
612
613 restart:
614         /* Let's see if we have file open on MDS already. */
615         if (it->it_flags & FMODE_WRITE) {
616                 och_p = &lli->lli_mds_write_och;
617                 och_usecount = &lli->lli_open_fd_write_count;
618         } else if (it->it_flags & FMODE_EXEC) {
619                 och_p = &lli->lli_mds_exec_och;
620                 och_usecount = &lli->lli_open_fd_exec_count;
621          } else {
622                 och_p = &lli->lli_mds_read_och;
623                 och_usecount = &lli->lli_open_fd_read_count;
624         }
625
626         mutex_lock(&lli->lli_och_mutex);
627         if (*och_p) { /* Open handle is present */
628                 if (it_disposition(it, DISP_OPEN_OPEN)) {
629                         /* Well, there's extra open request that we do not need,
630                            let's close it somehow. This will decref request. */
631                         rc = it_open_error(DISP_OPEN_OPEN, it);
632                         if (rc) {
633                                 mutex_unlock(&lli->lli_och_mutex);
634                                 GOTO(out_openerr, rc);
635                         }
636
637                         ll_release_openhandle(file->f_dentry, it);
638                 }
639                 (*och_usecount)++;
640
641                 rc = ll_local_open(file, it, fd, NULL);
642                 if (rc) {
643                         (*och_usecount)--;
644                         mutex_unlock(&lli->lli_och_mutex);
645                         GOTO(out_openerr, rc);
646                 }
647         } else {
648                 LASSERT(*och_usecount == 0);
649                 if (!it->d.lustre.it_disposition) {
650                         /* We cannot just request lock handle now, new ELC code
651                            means that one of other OPEN locks for this file
652                            could be cancelled, and since blocking ast handler
653                            would attempt to grab och_mutex as well, that would
654                            result in a deadlock */
655                         mutex_unlock(&lli->lli_och_mutex);
656                         it->it_create_mode |= M_CHECK_STALE;
657                         rc = ll_intent_file_open(file, NULL, 0, it);
658                         it->it_create_mode &= ~M_CHECK_STALE;
659                         if (rc)
660                                 GOTO(out_openerr, rc);
661
662                         goto restart;
663                 }
664                 OBD_ALLOC(*och_p, sizeof (struct obd_client_handle));
665                 if (!*och_p)
666                         GOTO(out_och_free, rc = -ENOMEM);
667
668                 (*och_usecount)++;
669
670                 /* md_intent_lock() didn't get a request ref if there was an
671                  * open error, so don't do cleanup on the request here
672                  * (bug 3430) */
673                 /* XXX (green): Should not we bail out on any error here, not
674                  * just open error? */
675                 rc = it_open_error(DISP_OPEN_OPEN, it);
676                 if (rc != 0)
677                         GOTO(out_och_free, rc);
678
679                 LASSERTF(it_disposition(it, DISP_ENQ_OPEN_REF),
680                          "inode %p: disposition %x, status %d\n", inode,
681                          it_disposition(it, ~0), it->d.lustre.it_status);
682
683                 rc = ll_local_open(file, it, fd, *och_p);
684                 if (rc)
685                         GOTO(out_och_free, rc);
686         }
687         mutex_unlock(&lli->lli_och_mutex);
688         fd = NULL;
689
690         /* Must do this outside lli_och_mutex lock to prevent deadlock where
691            different kind of OPEN lock for this same inode gets cancelled
692            by ldlm_cancel_lru */
693         if (!S_ISREG(inode->i_mode))
694                 GOTO(out_och_free, rc);
695
696         ll_capa_open(inode);
697
698         if (!lli->lli_has_smd) {
699                 if (file->f_flags & O_LOV_DELAY_CREATE ||
700                     !(file->f_mode & FMODE_WRITE)) {
701                         CDEBUG(D_INODE, "object creation was delayed\n");
702                         GOTO(out_och_free, rc);
703                 }
704         }
705         file->f_flags &= ~O_LOV_DELAY_CREATE;
706         GOTO(out_och_free, rc);
707
708 out_och_free:
709         if (rc) {
710                 if (och_p && *och_p) {
711                         OBD_FREE(*och_p, sizeof (struct obd_client_handle));
712                         *och_p = NULL; /* OBD_FREE writes some magic there */
713                         (*och_usecount)--;
714                 }
715                 mutex_unlock(&lli->lli_och_mutex);
716
717 out_openerr:
718                 if (opendir_set != 0)
719                         ll_stop_statahead(inode, lli->lli_opendir_key);
720                 if (fd != NULL)
721                         ll_file_data_put(fd);
722         } else {
723                 ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_OPEN, 1);
724         }
725
726         if (it && it_disposition(it, DISP_ENQ_OPEN_REF)) {
727                 ptlrpc_req_finished(it->d.lustre.it_data);
728                 it_clear_disposition(it, DISP_ENQ_OPEN_REF);
729         }
730
731         return rc;
732 }
733
734 static int ll_md_blocking_lease_ast(struct ldlm_lock *lock,
735                         struct ldlm_lock_desc *desc, void *data, int flag)
736 {
737         int rc;
738         struct lustre_handle lockh;
739         ENTRY;
740
741         switch (flag) {
742         case LDLM_CB_BLOCKING:
743                 ldlm_lock2handle(lock, &lockh);
744                 rc = ldlm_cli_cancel(&lockh, LCF_ASYNC);
745                 if (rc < 0) {
746                         CDEBUG(D_INODE, "ldlm_cli_cancel: %d\n", rc);
747                         RETURN(rc);
748                 }
749                 break;
750         case LDLM_CB_CANCELING:
751                 /* do nothing */
752                 break;
753         }
754         RETURN(0);
755 }
756
757 /**
758  * Acquire a lease and open the file.
759  */
760 struct obd_client_handle *ll_lease_open(struct inode *inode, struct file *file,
761                                         fmode_t fmode, __u64 open_flags)
762 {
763         struct lookup_intent it = { .it_op = IT_OPEN };
764         struct ll_sb_info *sbi = ll_i2sbi(inode);
765         struct md_op_data *op_data;
766         struct ptlrpc_request *req;
767         struct lustre_handle old_handle = { 0 };
768         struct obd_client_handle *och = NULL;
769         int rc;
770         int rc2;
771         ENTRY;
772
773         if (fmode != FMODE_WRITE && fmode != FMODE_READ)
774                 RETURN(ERR_PTR(-EINVAL));
775
776         if (file != NULL) {
777                 struct ll_inode_info *lli = ll_i2info(inode);
778                 struct ll_file_data *fd = LUSTRE_FPRIVATE(file);
779                 struct obd_client_handle **och_p;
780                 __u64 *och_usecount;
781
782                 if (!(fmode & file->f_mode) || (file->f_mode & FMODE_EXEC))
783                         RETURN(ERR_PTR(-EPERM));
784
785                 /* Get the openhandle of the file */
786                 rc = -EBUSY;
787                 mutex_lock(&lli->lli_och_mutex);
788                 if (fd->fd_lease_och != NULL) {
789                         mutex_unlock(&lli->lli_och_mutex);
790                         RETURN(ERR_PTR(rc));
791                 }
792
793                 if (fd->fd_och == NULL) {
794                         if (file->f_mode & FMODE_WRITE) {
795                                 LASSERT(lli->lli_mds_write_och != NULL);
796                                 och_p = &lli->lli_mds_write_och;
797                                 och_usecount = &lli->lli_open_fd_write_count;
798                         } else {
799                                 LASSERT(lli->lli_mds_read_och != NULL);
800                                 och_p = &lli->lli_mds_read_och;
801                                 och_usecount = &lli->lli_open_fd_read_count;
802                         }
803                         if (*och_usecount == 1) {
804                                 fd->fd_och = *och_p;
805                                 *och_p = NULL;
806                                 *och_usecount = 0;
807                                 rc = 0;
808                         }
809                 }
810                 mutex_unlock(&lli->lli_och_mutex);
811                 if (rc < 0) /* more than 1 opener */
812                         RETURN(ERR_PTR(rc));
813
814                 LASSERT(fd->fd_och != NULL);
815                 old_handle = fd->fd_och->och_fh;
816         }
817
818         OBD_ALLOC_PTR(och);
819         if (och == NULL)
820                 RETURN(ERR_PTR(-ENOMEM));
821
822         op_data = ll_prep_md_op_data(NULL, inode, inode, NULL, 0, 0,
823                                         LUSTRE_OPC_ANY, NULL);
824         if (IS_ERR(op_data))
825                 GOTO(out, rc = PTR_ERR(op_data));
826
827         /* To tell the MDT this openhandle is from the same owner */
828         op_data->op_handle = old_handle;
829
830         it.it_flags = fmode | open_flags;
831         it.it_flags |= MDS_OPEN_LOCK | MDS_OPEN_BY_FID | MDS_OPEN_LEASE;
832         rc = md_intent_lock(sbi->ll_md_exp, op_data, NULL, 0, &it, 0, &req,
833                                 ll_md_blocking_lease_ast,
834         /* LDLM_FL_NO_LRU: To not put the lease lock into LRU list, otherwise
835          * it can be cancelled which may mislead applications that the lease is
836          * broken;
837          * LDLM_FL_EXCL: Set this flag so that it won't be matched by normal
838          * open in ll_md_blocking_ast(). Otherwise as ll_md_blocking_lease_ast
839          * doesn't deal with openhandle, so normal openhandle will be leaked. */
840                                 LDLM_FL_NO_LRU | LDLM_FL_EXCL);
841         ll_finish_md_op_data(op_data);
842         ptlrpc_req_finished(req);
843         if (rc < 0)
844                 GOTO(out_release_it, rc);
845
846         if (it_disposition(&it, DISP_LOOKUP_NEG))
847                 GOTO(out_release_it, rc = -ENOENT);
848
849         rc = it_open_error(DISP_OPEN_OPEN, &it);
850         if (rc)
851                 GOTO(out_release_it, rc);
852
853         LASSERT(it_disposition(&it, DISP_ENQ_OPEN_REF));
854         ll_och_fill(sbi->ll_md_exp, &it, och);
855
856         if (!it_disposition(&it, DISP_OPEN_LEASE)) /* old server? */
857                 GOTO(out_close, rc = -EOPNOTSUPP);
858
859         /* already get lease, handle lease lock */
860         ll_set_lock_data(sbi->ll_md_exp, inode, &it, NULL);
861         if (it.d.lustre.it_lock_mode == 0 ||
862             it.d.lustre.it_lock_bits != MDS_INODELOCK_OPEN) {
863                 /* open lock must return for lease */
864                 CERROR(DFID "lease granted but no open lock, %d/%Lu.\n",
865                         PFID(ll_inode2fid(inode)), it.d.lustre.it_lock_mode,
866                         it.d.lustre.it_lock_bits);
867                 GOTO(out_close, rc = -EPROTO);
868         }
869
870         ll_intent_release(&it);
871         RETURN(och);
872
873 out_close:
874         /* Cancel open lock */
875         if (it.d.lustre.it_lock_mode != 0) {
876                 ldlm_lock_decref_and_cancel(&och->och_lease_handle,
877                                             it.d.lustre.it_lock_mode);
878                 it.d.lustre.it_lock_mode = 0;
879                 och->och_lease_handle.cookie = 0ULL;
880         }
881         rc2 = ll_close_inode_openhandle(sbi->ll_md_exp, inode, och, NULL);
882         if (rc2 < 0)
883                 CERROR("%s: error closing file "DFID": %d\n",
884                        ll_get_fsname(inode->i_sb, NULL, 0),
885                        PFID(&ll_i2info(inode)->lli_fid), rc2);
886         och = NULL; /* och has been freed in ll_close_inode_openhandle() */
887 out_release_it:
888         ll_intent_release(&it);
889 out:
890         if (och != NULL)
891                 OBD_FREE_PTR(och);
892         RETURN(ERR_PTR(rc));
893 }
894 EXPORT_SYMBOL(ll_lease_open);
895
896 /**
897  * Release lease and close the file.
898  * It will check if the lease has ever broken.
899  */
900 int ll_lease_close(struct obd_client_handle *och, struct inode *inode,
901                         bool *lease_broken)
902 {
903         struct ldlm_lock *lock;
904         bool cancelled = true;
905         int rc;
906         ENTRY;
907
908         lock = ldlm_handle2lock(&och->och_lease_handle);
909         if (lock != NULL) {
910                 lock_res_and_lock(lock);
911                 cancelled = ldlm_is_cancel(lock);
912                 unlock_res_and_lock(lock);
913                 LDLM_LOCK_PUT(lock);
914         }
915
916         CDEBUG(D_INODE, "lease for "DFID" broken? %d\n",
917                 PFID(&ll_i2info(inode)->lli_fid), cancelled);
918
919         if (!cancelled)
920                 ldlm_cli_cancel(&och->och_lease_handle, 0);
921         if (lease_broken != NULL)
922                 *lease_broken = cancelled;
923
924         rc = ll_close_inode_openhandle(ll_i2sbi(inode)->ll_md_exp, inode, och,
925                                        NULL);
926         RETURN(rc);
927 }
928 EXPORT_SYMBOL(ll_lease_close);
929
930 /* Fills the obdo with the attributes for the lsm */
931 static int ll_lsm_getattr(struct lov_stripe_md *lsm, struct obd_export *exp,
932                           struct obd_capa *capa, struct obdo *obdo,
933                           __u64 ioepoch, int dv_flags)
934 {
935         struct ptlrpc_request_set *set;
936         struct obd_info            oinfo = { { { 0 } } };
937         int                        rc;
938
939         ENTRY;
940
941         LASSERT(lsm != NULL);
942
943         oinfo.oi_md = lsm;
944         oinfo.oi_oa = obdo;
945         oinfo.oi_oa->o_oi = lsm->lsm_oi;
946         oinfo.oi_oa->o_mode = S_IFREG;
947         oinfo.oi_oa->o_ioepoch = ioepoch;
948         oinfo.oi_oa->o_valid = OBD_MD_FLID | OBD_MD_FLTYPE |
949                                OBD_MD_FLSIZE | OBD_MD_FLBLOCKS |
950                                OBD_MD_FLBLKSZ | OBD_MD_FLATIME |
951                                OBD_MD_FLMTIME | OBD_MD_FLCTIME |
952                                OBD_MD_FLGROUP | OBD_MD_FLEPOCH |
953                                OBD_MD_FLDATAVERSION;
954         oinfo.oi_capa = capa;
955         if (dv_flags & (LL_DV_WR_FLUSH | LL_DV_RD_FLUSH)) {
956                 oinfo.oi_oa->o_valid |= OBD_MD_FLFLAGS;
957                 oinfo.oi_oa->o_flags |= OBD_FL_SRVLOCK;
958                 if (dv_flags & LL_DV_WR_FLUSH)
959                         oinfo.oi_oa->o_flags |= OBD_FL_FLUSH;
960         }
961
962         set = ptlrpc_prep_set();
963         if (set == NULL) {
964                 CERROR("can't allocate ptlrpc set\n");
965                 rc = -ENOMEM;
966         } else {
967                 rc = obd_getattr_async(exp, &oinfo, set);
968                 if (rc == 0)
969                         rc = ptlrpc_set_wait(set);
970                 ptlrpc_set_destroy(set);
971         }
972         if (rc == 0) {
973                 oinfo.oi_oa->o_valid &= (OBD_MD_FLBLOCKS | OBD_MD_FLBLKSZ |
974                                          OBD_MD_FLATIME | OBD_MD_FLMTIME |
975                                          OBD_MD_FLCTIME | OBD_MD_FLSIZE |
976                                          OBD_MD_FLDATAVERSION | OBD_MD_FLFLAGS);
977                 if (dv_flags & LL_DV_WR_FLUSH &&
978                     !(oinfo.oi_oa->o_valid & OBD_MD_FLFLAGS &&
979                       oinfo.oi_oa->o_flags & OBD_FL_FLUSH))
980                         RETURN(-ENOTSUPP);
981         }
982         RETURN(rc);
983 }
984
985 /**
986   * Performs the getattr on the inode and updates its fields.
987   * If @sync != 0, perform the getattr under the server-side lock.
988   */
989 int ll_inode_getattr(struct inode *inode, struct obdo *obdo,
990                      __u64 ioepoch, int sync)
991 {
992         struct obd_capa      *capa = ll_mdscapa_get(inode);
993         struct lov_stripe_md *lsm;
994         int rc;
995         ENTRY;
996
997         lsm = ccc_inode_lsm_get(inode);
998         rc = ll_lsm_getattr(lsm, ll_i2dtexp(inode),
999                                 capa, obdo, ioepoch, sync ? LL_DV_RD_FLUSH : 0);
1000         capa_put(capa);
1001         if (rc == 0) {
1002                 struct ost_id *oi = lsm ? &lsm->lsm_oi : &obdo->o_oi;
1003
1004                 obdo_refresh_inode(inode, obdo, obdo->o_valid);
1005                 CDEBUG(D_INODE, "objid "DOSTID" size %llu, blocks %llu,"
1006                        " blksize %lu\n", POSTID(oi), i_size_read(inode),
1007                        (unsigned long long)inode->i_blocks,
1008                        (unsigned long)ll_inode_blksize(inode));
1009         }
1010         ccc_inode_lsm_put(inode, lsm);
1011         RETURN(rc);
1012 }
1013
1014 int ll_merge_lvb(const struct lu_env *env, struct inode *inode)
1015 {
1016         struct ll_inode_info *lli = ll_i2info(inode);
1017         struct cl_object *obj = lli->lli_clob;
1018         struct cl_attr *attr = ccc_env_thread_attr(env);
1019         struct ost_lvb lvb;
1020         int rc = 0;
1021
1022         ENTRY;
1023
1024         ll_inode_size_lock(inode);
1025         /* merge timestamps the most recently obtained from mds with
1026            timestamps obtained from osts */
1027         LTIME_S(inode->i_atime) = lli->lli_lvb.lvb_atime;
1028         LTIME_S(inode->i_mtime) = lli->lli_lvb.lvb_mtime;
1029         LTIME_S(inode->i_ctime) = lli->lli_lvb.lvb_ctime;
1030         inode_init_lvb(inode, &lvb);
1031
1032         cl_object_attr_lock(obj);
1033         rc = cl_object_attr_get(env, obj, attr);
1034         cl_object_attr_unlock(obj);
1035
1036         if (rc == 0) {
1037                 if (lvb.lvb_atime < attr->cat_atime)
1038                         lvb.lvb_atime = attr->cat_atime;
1039                 if (lvb.lvb_ctime < attr->cat_ctime)
1040                         lvb.lvb_ctime = attr->cat_ctime;
1041                 if (lvb.lvb_mtime < attr->cat_mtime)
1042                         lvb.lvb_mtime = attr->cat_mtime;
1043
1044                 CDEBUG(D_VFSTRACE, DFID" updating i_size "LPU64"\n",
1045                                 PFID(&lli->lli_fid), attr->cat_size);
1046                 cl_isize_write_nolock(inode, attr->cat_size);
1047
1048                 inode->i_blocks = attr->cat_blocks;
1049
1050                 LTIME_S(inode->i_mtime) = lvb.lvb_mtime;
1051                 LTIME_S(inode->i_atime) = lvb.lvb_atime;
1052                 LTIME_S(inode->i_ctime) = lvb.lvb_ctime;
1053         }
1054         ll_inode_size_unlock(inode);
1055
1056         RETURN(rc);
1057 }
1058
1059 int ll_glimpse_ioctl(struct ll_sb_info *sbi, struct lov_stripe_md *lsm,
1060                      lstat_t *st)
1061 {
1062         struct obdo obdo = { 0 };
1063         int rc;
1064
1065         rc = ll_lsm_getattr(lsm, sbi->ll_dt_exp, NULL, &obdo, 0, 0);
1066         if (rc == 0) {
1067                 st->st_size   = obdo.o_size;
1068                 st->st_blocks = obdo.o_blocks;
1069                 st->st_mtime  = obdo.o_mtime;
1070                 st->st_atime  = obdo.o_atime;
1071                 st->st_ctime  = obdo.o_ctime;
1072         }
1073         return rc;
1074 }
1075
1076 static bool file_is_noatime(const struct file *file)
1077 {
1078         const struct vfsmount *mnt = file->f_path.mnt;
1079         const struct inode *inode = file->f_path.dentry->d_inode;
1080
1081         /* Adapted from file_accessed() and touch_atime().*/
1082         if (file->f_flags & O_NOATIME)
1083                 return true;
1084
1085         if (inode->i_flags & S_NOATIME)
1086                 return true;
1087
1088         if (IS_NOATIME(inode))
1089                 return true;
1090
1091         if (mnt->mnt_flags & (MNT_NOATIME | MNT_READONLY))
1092                 return true;
1093
1094         if ((mnt->mnt_flags & MNT_NODIRATIME) && S_ISDIR(inode->i_mode))
1095                 return true;
1096
1097         if ((inode->i_sb->s_flags & MS_NODIRATIME) && S_ISDIR(inode->i_mode))
1098                 return true;
1099
1100         return false;
1101 }
1102
1103 void ll_io_init(struct cl_io *io, const struct file *file, int write)
1104 {
1105         struct inode *inode = file->f_dentry->d_inode;
1106
1107         io->u.ci_rw.crw_nonblock = file->f_flags & O_NONBLOCK;
1108         if (write) {
1109                 io->u.ci_wr.wr_append = !!(file->f_flags & O_APPEND);
1110                 io->u.ci_wr.wr_sync = file->f_flags & O_SYNC ||
1111                                       file->f_flags & O_DIRECT ||
1112                                       IS_SYNC(inode);
1113         }
1114         io->ci_obj     = ll_i2info(inode)->lli_clob;
1115         io->ci_lockreq = CILR_MAYBE;
1116         if (ll_file_nolock(file)) {
1117                 io->ci_lockreq = CILR_NEVER;
1118                 io->ci_no_srvlock = 1;
1119         } else if (file->f_flags & O_APPEND) {
1120                 io->ci_lockreq = CILR_MANDATORY;
1121         }
1122
1123         io->ci_noatime = file_is_noatime(file);
1124 }
1125
1126 static ssize_t
1127 ll_file_io_generic(const struct lu_env *env, struct vvp_io_args *args,
1128                    struct file *file, enum cl_io_type iot,
1129                    loff_t *ppos, size_t count)
1130 {
1131         struct ll_inode_info *lli = ll_i2info(file->f_dentry->d_inode);
1132         struct ll_file_data  *fd  = LUSTRE_FPRIVATE(file);
1133         struct cl_io         *io;
1134         ssize_t               result;
1135         ENTRY;
1136
1137         CDEBUG(D_VFSTRACE, "file: %s, type: %d ppos: "LPU64", count: %zd\n",
1138                 file->f_dentry->d_name.name, iot, *ppos, count);
1139
1140 restart:
1141         io = ccc_env_thread_io(env);
1142         ll_io_init(io, file, iot == CIT_WRITE);
1143
1144         if (cl_io_rw_init(env, io, iot, *ppos, count) == 0) {
1145                 struct vvp_io *vio = vvp_env_io(env);
1146                 struct ccc_io *cio = ccc_env_io(env);
1147                 int write_mutex_locked = 0;
1148
1149                 cio->cui_fd  = LUSTRE_FPRIVATE(file);
1150                 vio->cui_io_subtype = args->via_io_subtype;
1151
1152                 switch (vio->cui_io_subtype) {
1153                 case IO_NORMAL:
1154                         cio->cui_iov = args->u.normal.via_iov;
1155                         cio->cui_nrsegs = args->u.normal.via_nrsegs;
1156                         cio->cui_tot_nrsegs = cio->cui_nrsegs;
1157                         cio->cui_iocb = args->u.normal.via_iocb;
1158                         if ((iot == CIT_WRITE) &&
1159                             !(cio->cui_fd->fd_flags & LL_FILE_GROUP_LOCKED)) {
1160                                 if (mutex_lock_interruptible(&lli->
1161                                                         lli_write_mutex))
1162                                         GOTO(out, result = -ERESTARTSYS);
1163                                 write_mutex_locked = 1;
1164                         }
1165                         down_read(&lli->lli_trunc_sem);
1166                         break;
1167                 case IO_SENDFILE:
1168                         vio->u.sendfile.cui_actor = args->u.sendfile.via_actor;
1169                         vio->u.sendfile.cui_target = args->u.sendfile.via_target;
1170                         break;
1171                 case IO_SPLICE:
1172                         vio->u.splice.cui_pipe = args->u.splice.via_pipe;
1173                         vio->u.splice.cui_flags = args->u.splice.via_flags;
1174                         break;
1175                 default:
1176                         CERROR("Unknow IO type - %u\n", vio->cui_io_subtype);
1177                         LBUG();
1178                 }
1179                 result = cl_io_loop(env, io);
1180                 if (args->via_io_subtype == IO_NORMAL)
1181                         up_read(&lli->lli_trunc_sem);
1182                 if (write_mutex_locked)
1183                         mutex_unlock(&lli->lli_write_mutex);
1184         } else {
1185                 /* cl_io_rw_init() handled IO */
1186                 result = io->ci_result;
1187         }
1188
1189         if (io->ci_nob > 0) {
1190                 result = io->ci_nob;
1191                 *ppos = io->u.ci_wr.wr.crw_pos;
1192         }
1193         GOTO(out, result);
1194 out:
1195         cl_io_fini(env, io);
1196         /* If any bit been read/written (result != 0), we just return
1197          * short read/write instead of restart io. */
1198         if ((result == 0 || result == -ENODATA) && io->ci_need_restart) {
1199                 CDEBUG(D_VFSTRACE, "Restart %s on %s from %lld, count:%zd\n",
1200                        iot == CIT_READ ? "read" : "write",
1201                        file->f_dentry->d_name.name, *ppos, count);
1202                 LASSERTF(io->ci_nob == 0, "%zd", io->ci_nob);
1203                 goto restart;
1204         }
1205
1206         if (iot == CIT_READ) {
1207                 if (result >= 0)
1208                         ll_stats_ops_tally(ll_i2sbi(file->f_dentry->d_inode),
1209                                            LPROC_LL_READ_BYTES, result);
1210         } else if (iot == CIT_WRITE) {
1211                 if (result >= 0) {
1212                         ll_stats_ops_tally(ll_i2sbi(file->f_dentry->d_inode),
1213                                            LPROC_LL_WRITE_BYTES, result);
1214                         fd->fd_write_failed = false;
1215                 } else if (result != -ERESTARTSYS) {
1216                         fd->fd_write_failed = true;
1217                 }
1218         }
1219         CDEBUG(D_VFSTRACE, "iot: %d, result: %zd\n", iot, result);
1220
1221         return result;
1222 }
1223
1224
1225 /*
1226  * XXX: exact copy from kernel code (__generic_file_aio_write_nolock)
1227  */
1228 static int ll_file_get_iov_count(const struct iovec *iov,
1229                                  unsigned long *nr_segs, size_t *count)
1230 {
1231         size_t cnt = 0;
1232         unsigned long seg;
1233
1234         for (seg = 0; seg < *nr_segs; seg++) {
1235                 const struct iovec *iv = &iov[seg];
1236
1237                 /*
1238                  * If any segment has a negative length, or the cumulative
1239                  * length ever wraps negative then return -EINVAL.
1240                  */
1241                 cnt += iv->iov_len;
1242                 if (unlikely((ssize_t)(cnt|iv->iov_len) < 0))
1243                         return -EINVAL;
1244                 if (access_ok(VERIFY_READ, iv->iov_base, iv->iov_len))
1245                         continue;
1246                 if (seg == 0)
1247                         return -EFAULT;
1248                 *nr_segs = seg;
1249                 cnt -= iv->iov_len;   /* This segment is no good */
1250                 break;
1251         }
1252         *count = cnt;
1253         return 0;
1254 }
1255
1256 static ssize_t ll_file_aio_read(struct kiocb *iocb, const struct iovec *iov,
1257                                 unsigned long nr_segs, loff_t pos)
1258 {
1259         struct lu_env      *env;
1260         struct vvp_io_args *args;
1261         size_t              count;
1262         ssize_t             result;
1263         int                 refcheck;
1264         ENTRY;
1265
1266         result = ll_file_get_iov_count(iov, &nr_segs, &count);
1267         if (result)
1268                 RETURN(result);
1269
1270         env = cl_env_get(&refcheck);
1271         if (IS_ERR(env))
1272                 RETURN(PTR_ERR(env));
1273
1274         args = vvp_env_args(env, IO_NORMAL);
1275         args->u.normal.via_iov = (struct iovec *)iov;
1276         args->u.normal.via_nrsegs = nr_segs;
1277         args->u.normal.via_iocb = iocb;
1278
1279         result = ll_file_io_generic(env, args, iocb->ki_filp, CIT_READ,
1280                                     &iocb->ki_pos, count);
1281         cl_env_put(env, &refcheck);
1282         RETURN(result);
1283 }
1284
1285 static ssize_t ll_file_read(struct file *file, char *buf, size_t count,
1286                             loff_t *ppos)
1287 {
1288         struct lu_env *env;
1289         struct iovec  *local_iov;
1290         struct kiocb  *kiocb;
1291         ssize_t        result;
1292         int            refcheck;
1293         ENTRY;
1294
1295         env = cl_env_get(&refcheck);
1296         if (IS_ERR(env))
1297                 RETURN(PTR_ERR(env));
1298
1299         local_iov = &vvp_env_info(env)->vti_local_iov;
1300         kiocb = &vvp_env_info(env)->vti_kiocb;
1301         local_iov->iov_base = (void __user *)buf;
1302         local_iov->iov_len = count;
1303         init_sync_kiocb(kiocb, file);
1304         kiocb->ki_pos = *ppos;
1305         kiocb->ki_left = count;
1306
1307         result = ll_file_aio_read(kiocb, local_iov, 1, kiocb->ki_pos);
1308         *ppos = kiocb->ki_pos;
1309
1310         cl_env_put(env, &refcheck);
1311         RETURN(result);
1312 }
1313
1314 /*
1315  * Write to a file (through the page cache).
1316  * AIO stuff
1317  */
1318 static ssize_t ll_file_aio_write(struct kiocb *iocb, const struct iovec *iov,
1319                                  unsigned long nr_segs, loff_t pos)
1320 {
1321         struct lu_env      *env;
1322         struct vvp_io_args *args;
1323         size_t              count;
1324         ssize_t             result;
1325         int                 refcheck;
1326         ENTRY;
1327
1328         result = ll_file_get_iov_count(iov, &nr_segs, &count);
1329         if (result)
1330                 RETURN(result);
1331
1332         env = cl_env_get(&refcheck);
1333         if (IS_ERR(env))
1334                 RETURN(PTR_ERR(env));
1335
1336         args = vvp_env_args(env, IO_NORMAL);
1337         args->u.normal.via_iov = (struct iovec *)iov;
1338         args->u.normal.via_nrsegs = nr_segs;
1339         args->u.normal.via_iocb = iocb;
1340
1341         result = ll_file_io_generic(env, args, iocb->ki_filp, CIT_WRITE,
1342                                   &iocb->ki_pos, count);
1343         cl_env_put(env, &refcheck);
1344         RETURN(result);
1345 }
1346
1347 static ssize_t ll_file_write(struct file *file, const char *buf, size_t count,
1348                              loff_t *ppos)
1349 {
1350         struct lu_env *env;
1351         struct iovec  *local_iov;
1352         struct kiocb  *kiocb;
1353         ssize_t        result;
1354         int            refcheck;
1355         ENTRY;
1356
1357         env = cl_env_get(&refcheck);
1358         if (IS_ERR(env))
1359                 RETURN(PTR_ERR(env));
1360
1361         local_iov = &vvp_env_info(env)->vti_local_iov;
1362         kiocb = &vvp_env_info(env)->vti_kiocb;
1363         local_iov->iov_base = (void __user *)buf;
1364         local_iov->iov_len = count;
1365         init_sync_kiocb(kiocb, file);
1366         kiocb->ki_pos = *ppos;
1367         kiocb->ki_left = count;
1368
1369         result = ll_file_aio_write(kiocb, local_iov, 1, kiocb->ki_pos);
1370         *ppos = kiocb->ki_pos;
1371
1372         cl_env_put(env, &refcheck);
1373         RETURN(result);
1374 }
1375
1376 /*
1377  * Send file content (through pagecache) somewhere with helper
1378  */
1379 static ssize_t ll_file_splice_read(struct file *in_file, loff_t *ppos,
1380                                    struct pipe_inode_info *pipe, size_t count,
1381                                    unsigned int flags)
1382 {
1383         struct lu_env      *env;
1384         struct vvp_io_args *args;
1385         ssize_t             result;
1386         int                 refcheck;
1387         ENTRY;
1388
1389         env = cl_env_get(&refcheck);
1390         if (IS_ERR(env))
1391                 RETURN(PTR_ERR(env));
1392
1393         args = vvp_env_args(env, IO_SPLICE);
1394         args->u.splice.via_pipe = pipe;
1395         args->u.splice.via_flags = flags;
1396
1397         result = ll_file_io_generic(env, args, in_file, CIT_READ, ppos, count);
1398         cl_env_put(env, &refcheck);
1399         RETURN(result);
1400 }
1401
1402 static int ll_lov_recreate(struct inode *inode, struct ost_id *oi,
1403                            obd_count ost_idx)
1404 {
1405         struct obd_export *exp = ll_i2dtexp(inode);
1406         struct obd_trans_info oti = { 0 };
1407         struct obdo *oa = NULL;
1408         int lsm_size;
1409         int rc = 0;
1410         struct lov_stripe_md *lsm = NULL, *lsm2;
1411         ENTRY;
1412
1413         OBDO_ALLOC(oa);
1414         if (oa == NULL)
1415                 RETURN(-ENOMEM);
1416
1417         lsm = ccc_inode_lsm_get(inode);
1418         if (!lsm_has_objects(lsm))
1419                 GOTO(out, rc = -ENOENT);
1420
1421         lsm_size = sizeof(*lsm) + (sizeof(struct lov_oinfo) *
1422                    (lsm->lsm_stripe_count));
1423
1424         OBD_ALLOC_LARGE(lsm2, lsm_size);
1425         if (lsm2 == NULL)
1426                 GOTO(out, rc = -ENOMEM);
1427
1428         oa->o_oi = *oi;
1429         oa->o_nlink = ost_idx;
1430         oa->o_flags |= OBD_FL_RECREATE_OBJS;
1431         oa->o_valid = OBD_MD_FLID | OBD_MD_FLFLAGS | OBD_MD_FLGROUP;
1432         obdo_from_inode(oa, inode, OBD_MD_FLTYPE | OBD_MD_FLATIME |
1433                                    OBD_MD_FLMTIME | OBD_MD_FLCTIME);
1434         obdo_set_parent_fid(oa, &ll_i2info(inode)->lli_fid);
1435         memcpy(lsm2, lsm, lsm_size);
1436         ll_inode_size_lock(inode);
1437         rc = obd_create(NULL, exp, oa, &lsm2, &oti);
1438         ll_inode_size_unlock(inode);
1439
1440         OBD_FREE_LARGE(lsm2, lsm_size);
1441         GOTO(out, rc);
1442 out:
1443         ccc_inode_lsm_put(inode, lsm);
1444         OBDO_FREE(oa);
1445         return rc;
1446 }
1447
1448 static int ll_lov_recreate_obj(struct inode *inode, unsigned long arg)
1449 {
1450         struct ll_recreate_obj ucreat;
1451         struct ost_id           oi;
1452         ENTRY;
1453
1454         if (!cfs_capable(CFS_CAP_SYS_ADMIN))
1455                 RETURN(-EPERM);
1456
1457         if (copy_from_user(&ucreat, (struct ll_recreate_obj *)arg,
1458                            sizeof(ucreat)))
1459                 RETURN(-EFAULT);
1460
1461         ostid_set_seq_mdt0(&oi);
1462         ostid_set_id(&oi, ucreat.lrc_id);
1463         RETURN(ll_lov_recreate(inode, &oi, ucreat.lrc_ost_idx));
1464 }
1465
1466 static int ll_lov_recreate_fid(struct inode *inode, unsigned long arg)
1467 {
1468         struct lu_fid   fid;
1469         struct ost_id   oi;
1470         obd_count       ost_idx;
1471         ENTRY;
1472
1473         if (!cfs_capable(CFS_CAP_SYS_ADMIN))
1474                 RETURN(-EPERM);
1475
1476         if (copy_from_user(&fid, (struct lu_fid *)arg, sizeof(fid)))
1477                 RETURN(-EFAULT);
1478
1479         fid_to_ostid(&fid, &oi);
1480         ost_idx = (fid_seq(&fid) >> 16) & 0xffff;
1481         RETURN(ll_lov_recreate(inode, &oi, ost_idx));
1482 }
1483
1484 int ll_lov_setstripe_ea_info(struct inode *inode, struct file *file,
1485                              __u64  flags, struct lov_user_md *lum,
1486                              int lum_size)
1487 {
1488         struct lov_stripe_md *lsm = NULL;
1489         struct lookup_intent oit = {.it_op = IT_OPEN, .it_flags = flags};
1490         int rc = 0;
1491         ENTRY;
1492
1493         lsm = ccc_inode_lsm_get(inode);
1494         if (lsm != NULL) {
1495                 ccc_inode_lsm_put(inode, lsm);
1496                 CDEBUG(D_IOCTL, "stripe already exists for inode "DFID"\n",
1497                        PFID(ll_inode2fid(inode)));
1498                 RETURN(-EEXIST);
1499         }
1500
1501         ll_inode_size_lock(inode);
1502         rc = ll_intent_file_open(file, lum, lum_size, &oit);
1503         if (rc)
1504                 GOTO(out, rc);
1505         rc = oit.d.lustre.it_status;
1506         if (rc < 0)
1507                 GOTO(out_req_free, rc);
1508
1509         ll_release_openhandle(file->f_dentry, &oit);
1510
1511  out:
1512         ll_inode_size_unlock(inode);
1513         ll_intent_release(&oit);
1514         ccc_inode_lsm_put(inode, lsm);
1515         RETURN(rc);
1516 out_req_free:
1517         ptlrpc_req_finished((struct ptlrpc_request *) oit.d.lustre.it_data);
1518         goto out;
1519 }
1520
1521 int ll_lov_getstripe_ea_info(struct inode *inode, const char *filename,
1522                              struct lov_mds_md **lmmp, int *lmm_size,
1523                              struct ptlrpc_request **request)
1524 {
1525         struct ll_sb_info *sbi = ll_i2sbi(inode);
1526         struct mdt_body  *body;
1527         struct lov_mds_md *lmm = NULL;
1528         struct ptlrpc_request *req = NULL;
1529         struct md_op_data *op_data;
1530         int rc, lmmsize;
1531
1532         rc = ll_get_max_mdsize(sbi, &lmmsize);
1533         if (rc)
1534                 RETURN(rc);
1535
1536         op_data = ll_prep_md_op_data(NULL, inode, NULL, filename,
1537                                      strlen(filename), lmmsize,
1538                                      LUSTRE_OPC_ANY, NULL);
1539         if (IS_ERR(op_data))
1540                 RETURN(PTR_ERR(op_data));
1541
1542         op_data->op_valid = OBD_MD_FLEASIZE | OBD_MD_FLDIREA;
1543         rc = md_getattr_name(sbi->ll_md_exp, op_data, &req);
1544         ll_finish_md_op_data(op_data);
1545         if (rc < 0) {
1546                 CDEBUG(D_INFO, "md_getattr_name failed "
1547                        "on %s: rc %d\n", filename, rc);
1548                 GOTO(out, rc);
1549         }
1550
1551         body = req_capsule_server_get(&req->rq_pill, &RMF_MDT_BODY);
1552         LASSERT(body != NULL); /* checked by mdc_getattr_name */
1553
1554         lmmsize = body->eadatasize;
1555
1556         if (!(body->valid & (OBD_MD_FLEASIZE | OBD_MD_FLDIREA)) ||
1557                         lmmsize == 0) {
1558                 GOTO(out, rc = -ENODATA);
1559         }
1560
1561         lmm = req_capsule_server_sized_get(&req->rq_pill, &RMF_MDT_MD, lmmsize);
1562         LASSERT(lmm != NULL);
1563
1564         if ((lmm->lmm_magic != cpu_to_le32(LOV_MAGIC_V1)) &&
1565             (lmm->lmm_magic != cpu_to_le32(LOV_MAGIC_V3))) {
1566                 GOTO(out, rc = -EPROTO);
1567         }
1568
1569         /*
1570          * This is coming from the MDS, so is probably in
1571          * little endian.  We convert it to host endian before
1572          * passing it to userspace.
1573          */
1574         if (LOV_MAGIC != cpu_to_le32(LOV_MAGIC)) {
1575                 int stripe_count;
1576
1577                 stripe_count = le16_to_cpu(lmm->lmm_stripe_count);
1578                 if (le32_to_cpu(lmm->lmm_pattern) & LOV_PATTERN_F_RELEASED)
1579                         stripe_count = 0;
1580
1581                 /* if function called for directory - we should
1582                  * avoid swab not existent lsm objects */
1583                 if (lmm->lmm_magic == cpu_to_le32(LOV_MAGIC_V1)) {
1584                         lustre_swab_lov_user_md_v1((struct lov_user_md_v1 *)lmm);
1585                         if (S_ISREG(body->mode))
1586                                 lustre_swab_lov_user_md_objects(
1587                                  ((struct lov_user_md_v1 *)lmm)->lmm_objects,
1588                                  stripe_count);
1589                 } else if (lmm->lmm_magic == cpu_to_le32(LOV_MAGIC_V3)) {
1590                         lustre_swab_lov_user_md_v3((struct lov_user_md_v3 *)lmm);
1591                         if (S_ISREG(body->mode))
1592                                 lustre_swab_lov_user_md_objects(
1593                                  ((struct lov_user_md_v3 *)lmm)->lmm_objects,
1594                                  stripe_count);
1595                 }
1596         }
1597
1598 out:
1599         *lmmp = lmm;
1600         *lmm_size = lmmsize;
1601         *request = req;
1602         return rc;
1603 }
1604
1605 static int ll_lov_setea(struct inode *inode, struct file *file,
1606                             unsigned long arg)
1607 {
1608         __u64                    flags = MDS_OPEN_HAS_OBJS | FMODE_WRITE;
1609         struct lov_user_md      *lump;
1610         int                      lum_size = sizeof(struct lov_user_md) +
1611                                             sizeof(struct lov_user_ost_data);
1612         int                      rc;
1613         ENTRY;
1614
1615         if (!cfs_capable(CFS_CAP_SYS_ADMIN))
1616                 RETURN(-EPERM);
1617
1618         OBD_ALLOC_LARGE(lump, lum_size);
1619         if (lump == NULL)
1620                 RETURN(-ENOMEM);
1621
1622         if (copy_from_user(lump, (struct lov_user_md  *)arg, lum_size)) {
1623                 OBD_FREE_LARGE(lump, lum_size);
1624                 RETURN(-EFAULT);
1625         }
1626
1627         rc = ll_lov_setstripe_ea_info(inode, file, flags, lump, lum_size);
1628
1629         OBD_FREE_LARGE(lump, lum_size);
1630         RETURN(rc);
1631 }
1632
1633 static int ll_lov_setstripe(struct inode *inode, struct file *file,
1634                             unsigned long arg)
1635 {
1636         struct lov_user_md_v3    lumv3;
1637         struct lov_user_md_v1   *lumv1 = (struct lov_user_md_v1 *)&lumv3;
1638         struct lov_user_md_v1   *lumv1p = (struct lov_user_md_v1 *)arg;
1639         struct lov_user_md_v3   *lumv3p = (struct lov_user_md_v3 *)arg;
1640         int                      lum_size, rc;
1641         __u64                    flags = FMODE_WRITE;
1642         ENTRY;
1643
1644         /* first try with v1 which is smaller than v3 */
1645         lum_size = sizeof(struct lov_user_md_v1);
1646         if (copy_from_user(lumv1, lumv1p, lum_size))
1647                 RETURN(-EFAULT);
1648
1649         if (lumv1->lmm_magic == LOV_USER_MAGIC_V3) {
1650                 lum_size = sizeof(struct lov_user_md_v3);
1651                 if (copy_from_user(&lumv3, lumv3p, lum_size))
1652                         RETURN(-EFAULT);
1653         }
1654
1655         rc = ll_lov_setstripe_ea_info(inode, file, flags, lumv1, lum_size);
1656         if (rc == 0) {
1657                 struct lov_stripe_md *lsm;
1658                 __u32 gen;
1659
1660                 put_user(0, &lumv1p->lmm_stripe_count);
1661
1662                 ll_layout_refresh(inode, &gen);
1663                 lsm = ccc_inode_lsm_get(inode);
1664                 rc = obd_iocontrol(LL_IOC_LOV_GETSTRIPE, ll_i2dtexp(inode),
1665                                    0, lsm, (void *)arg);
1666                 ccc_inode_lsm_put(inode, lsm);
1667         }
1668         RETURN(rc);
1669 }
1670
1671 static int ll_lov_getstripe(struct inode *inode, unsigned long arg)
1672 {
1673         struct lov_stripe_md *lsm;
1674         int rc = -ENODATA;
1675         ENTRY;
1676
1677         lsm = ccc_inode_lsm_get(inode);
1678         if (lsm != NULL)
1679                 rc = obd_iocontrol(LL_IOC_LOV_GETSTRIPE, ll_i2dtexp(inode), 0,
1680                                    lsm, (void *)arg);
1681         ccc_inode_lsm_put(inode, lsm);
1682         RETURN(rc);
1683 }
1684
1685 int ll_get_grouplock(struct inode *inode, struct file *file, unsigned long arg)
1686 {
1687         struct ll_inode_info   *lli = ll_i2info(inode);
1688         struct ll_file_data    *fd = LUSTRE_FPRIVATE(file);
1689         struct ccc_grouplock    grouplock;
1690         int                     rc;
1691         ENTRY;
1692
1693         if (ll_file_nolock(file))
1694                 RETURN(-EOPNOTSUPP);
1695
1696         spin_lock(&lli->lli_lock);
1697         if (fd->fd_flags & LL_FILE_GROUP_LOCKED) {
1698                 CWARN("group lock already existed with gid %lu\n",
1699                       fd->fd_grouplock.cg_gid);
1700                 spin_unlock(&lli->lli_lock);
1701                 RETURN(-EINVAL);
1702         }
1703         LASSERT(fd->fd_grouplock.cg_lock == NULL);
1704         spin_unlock(&lli->lli_lock);
1705
1706         rc = cl_get_grouplock(cl_i2info(inode)->lli_clob,
1707                               arg, (file->f_flags & O_NONBLOCK), &grouplock);
1708         if (rc)
1709                 RETURN(rc);
1710
1711         spin_lock(&lli->lli_lock);
1712         if (fd->fd_flags & LL_FILE_GROUP_LOCKED) {
1713                 spin_unlock(&lli->lli_lock);
1714                 CERROR("another thread just won the race\n");
1715                 cl_put_grouplock(&grouplock);
1716                 RETURN(-EINVAL);
1717         }
1718
1719         fd->fd_flags |= LL_FILE_GROUP_LOCKED;
1720         fd->fd_grouplock = grouplock;
1721         spin_unlock(&lli->lli_lock);
1722
1723         CDEBUG(D_INFO, "group lock %lu obtained\n", arg);
1724         RETURN(0);
1725 }
1726
1727 int ll_put_grouplock(struct inode *inode, struct file *file, unsigned long arg)
1728 {
1729         struct ll_inode_info   *lli = ll_i2info(inode);
1730         struct ll_file_data    *fd = LUSTRE_FPRIVATE(file);
1731         struct ccc_grouplock    grouplock;
1732         ENTRY;
1733
1734         spin_lock(&lli->lli_lock);
1735         if (!(fd->fd_flags & LL_FILE_GROUP_LOCKED)) {
1736                 spin_unlock(&lli->lli_lock);
1737                 CWARN("no group lock held\n");
1738                 RETURN(-EINVAL);
1739         }
1740         LASSERT(fd->fd_grouplock.cg_lock != NULL);
1741
1742         if (fd->fd_grouplock.cg_gid != arg) {
1743                 CWARN("group lock %lu doesn't match current id %lu\n",
1744                        arg, fd->fd_grouplock.cg_gid);
1745                 spin_unlock(&lli->lli_lock);
1746                 RETURN(-EINVAL);
1747         }
1748
1749         grouplock = fd->fd_grouplock;
1750         memset(&fd->fd_grouplock, 0, sizeof(fd->fd_grouplock));
1751         fd->fd_flags &= ~LL_FILE_GROUP_LOCKED;
1752         spin_unlock(&lli->lli_lock);
1753
1754         cl_put_grouplock(&grouplock);
1755         CDEBUG(D_INFO, "group lock %lu released\n", arg);
1756         RETURN(0);
1757 }
1758
1759 /**
1760  * Close inode open handle
1761  *
1762  * \param dentry [in]     dentry which contains the inode
1763  * \param it     [in,out] intent which contains open info and result
1764  *
1765  * \retval 0     success
1766  * \retval <0    failure
1767  */
1768 int ll_release_openhandle(struct dentry *dentry, struct lookup_intent *it)
1769 {
1770         struct inode *inode = dentry->d_inode;
1771         struct obd_client_handle *och;
1772         int rc;
1773         ENTRY;
1774
1775         LASSERT(inode);
1776
1777         /* Root ? Do nothing. */
1778         if (dentry->d_inode->i_sb->s_root == dentry)
1779                 RETURN(0);
1780
1781         /* No open handle to close? Move away */
1782         if (!it_disposition(it, DISP_OPEN_OPEN))
1783                 RETURN(0);
1784
1785         LASSERT(it_open_error(DISP_OPEN_OPEN, it) == 0);
1786
1787         OBD_ALLOC(och, sizeof(*och));
1788         if (!och)
1789                 GOTO(out, rc = -ENOMEM);
1790
1791         ll_och_fill(ll_i2sbi(inode)->ll_md_exp, it, och);
1792
1793         rc = ll_close_inode_openhandle(ll_i2sbi(inode)->ll_md_exp,
1794                                        inode, och, NULL);
1795 out:
1796         /* this one is in place of ll_file_open */
1797         if (it_disposition(it, DISP_ENQ_OPEN_REF)) {
1798                 ptlrpc_req_finished(it->d.lustre.it_data);
1799                 it_clear_disposition(it, DISP_ENQ_OPEN_REF);
1800         }
1801         RETURN(rc);
1802 }
1803
1804 /**
1805  * Get size for inode for which FIEMAP mapping is requested.
1806  * Make the FIEMAP get_info call and returns the result.
1807  */
1808 int ll_do_fiemap(struct inode *inode, struct ll_user_fiemap *fiemap,
1809               int num_bytes)
1810 {
1811         struct obd_export *exp = ll_i2dtexp(inode);
1812         struct lov_stripe_md *lsm = NULL;
1813         struct ll_fiemap_info_key fm_key = { .name = KEY_FIEMAP, };
1814         int vallen = num_bytes;
1815         int rc;
1816         ENTRY;
1817
1818         /* Checks for fiemap flags */
1819         if (fiemap->fm_flags & ~LUSTRE_FIEMAP_FLAGS_COMPAT) {
1820                 fiemap->fm_flags &= ~LUSTRE_FIEMAP_FLAGS_COMPAT;
1821                 return -EBADR;
1822         }
1823
1824         /* Check for FIEMAP_FLAG_SYNC */
1825         if (fiemap->fm_flags & FIEMAP_FLAG_SYNC) {
1826                 rc = filemap_fdatawrite(inode->i_mapping);
1827                 if (rc)
1828                         return rc;
1829         }
1830
1831         lsm = ccc_inode_lsm_get(inode);
1832         if (lsm == NULL)
1833                 return -ENOENT;
1834
1835         /* If the stripe_count > 1 and the application does not understand
1836          * DEVICE_ORDER flag, then it cannot interpret the extents correctly.
1837          */
1838         if (lsm->lsm_stripe_count > 1 &&
1839             !(fiemap->fm_flags & FIEMAP_FLAG_DEVICE_ORDER))
1840                 GOTO(out, rc = -EOPNOTSUPP);
1841
1842         fm_key.oa.o_oi = lsm->lsm_oi;
1843         fm_key.oa.o_valid = OBD_MD_FLID | OBD_MD_FLGROUP;
1844
1845         obdo_from_inode(&fm_key.oa, inode, OBD_MD_FLSIZE);
1846         obdo_set_parent_fid(&fm_key.oa, &ll_i2info(inode)->lli_fid);
1847         /* If filesize is 0, then there would be no objects for mapping */
1848         if (fm_key.oa.o_size == 0) {
1849                 fiemap->fm_mapped_extents = 0;
1850                 GOTO(out, rc = 0);
1851         }
1852
1853         memcpy(&fm_key.fiemap, fiemap, sizeof(*fiemap));
1854
1855         rc = obd_get_info(NULL, exp, sizeof(fm_key), &fm_key, &vallen,
1856                           fiemap, lsm);
1857         if (rc)
1858                 CERROR("obd_get_info failed: rc = %d\n", rc);
1859
1860 out:
1861         ccc_inode_lsm_put(inode, lsm);
1862         RETURN(rc);
1863 }
1864
1865 int ll_fid2path(struct inode *inode, void *arg)
1866 {
1867         struct obd_export       *exp = ll_i2mdexp(inode);
1868         struct getinfo_fid2path *gfout, *gfin;
1869         int                      outsize, rc;
1870         ENTRY;
1871
1872         if (!cfs_capable(CFS_CAP_DAC_READ_SEARCH) &&
1873             !(ll_i2sbi(inode)->ll_flags & LL_SBI_USER_FID2PATH))
1874                 RETURN(-EPERM);
1875
1876         /* Need to get the buflen */
1877         OBD_ALLOC_PTR(gfin);
1878         if (gfin == NULL)
1879                 RETURN(-ENOMEM);
1880         if (copy_from_user(gfin, arg, sizeof(*gfin))) {
1881                 OBD_FREE_PTR(gfin);
1882                 RETURN(-EFAULT);
1883         }
1884
1885         outsize = sizeof(*gfout) + gfin->gf_pathlen;
1886         OBD_ALLOC(gfout, outsize);
1887         if (gfout == NULL) {
1888                 OBD_FREE_PTR(gfin);
1889                 RETURN(-ENOMEM);
1890         }
1891         memcpy(gfout, gfin, sizeof(*gfout));
1892         OBD_FREE_PTR(gfin);
1893
1894         /* Call mdc_iocontrol */
1895         rc = obd_iocontrol(OBD_IOC_FID2PATH, exp, outsize, gfout, NULL);
1896         if (rc)
1897                 GOTO(gf_free, rc);
1898
1899         if (copy_to_user(arg, gfout, outsize))
1900                 rc = -EFAULT;
1901
1902 gf_free:
1903         OBD_FREE(gfout, outsize);
1904         RETURN(rc);
1905 }
1906
1907 static int ll_ioctl_fiemap(struct inode *inode, unsigned long arg)
1908 {
1909         struct ll_user_fiemap *fiemap_s;
1910         size_t num_bytes, ret_bytes;
1911         unsigned int extent_count;
1912         int rc = 0;
1913
1914         /* Get the extent count so we can calculate the size of
1915          * required fiemap buffer */
1916         if (get_user(extent_count,
1917             &((struct ll_user_fiemap __user *)arg)->fm_extent_count))
1918                 RETURN(-EFAULT);
1919         num_bytes = sizeof(*fiemap_s) + (extent_count *
1920                                          sizeof(struct ll_fiemap_extent));
1921
1922         OBD_ALLOC_LARGE(fiemap_s, num_bytes);
1923         if (fiemap_s == NULL)
1924                 RETURN(-ENOMEM);
1925
1926         /* get the fiemap value */
1927         if (copy_from_user(fiemap_s, (struct ll_user_fiemap __user *)arg,
1928                            sizeof(*fiemap_s)))
1929                 GOTO(error, rc = -EFAULT);
1930
1931         /* If fm_extent_count is non-zero, read the first extent since
1932          * it is used to calculate end_offset and device from previous
1933          * fiemap call. */
1934         if (extent_count) {
1935                 if (copy_from_user(&fiemap_s->fm_extents[0],
1936                     (char __user *)arg + sizeof(*fiemap_s),
1937                     sizeof(struct ll_fiemap_extent)))
1938                         GOTO(error, rc = -EFAULT);
1939         }
1940
1941         rc = ll_do_fiemap(inode, fiemap_s, num_bytes);
1942         if (rc)
1943                 GOTO(error, rc);
1944
1945         ret_bytes = sizeof(struct ll_user_fiemap);
1946
1947         if (extent_count != 0)
1948                 ret_bytes += (fiemap_s->fm_mapped_extents *
1949                                  sizeof(struct ll_fiemap_extent));
1950
1951         if (copy_to_user((void *)arg, fiemap_s, ret_bytes))
1952                 rc = -EFAULT;
1953
1954 error:
1955         OBD_FREE_LARGE(fiemap_s, num_bytes);
1956         RETURN(rc);
1957 }
1958
1959 /*
1960  * Read the data_version for inode.
1961  *
1962  * This value is computed using stripe object version on OST.
1963  * Version is computed using server side locking.
1964  *
1965  * @param sync if do sync on the OST side;
1966  *              0: no sync
1967  *              LL_DV_RD_FLUSH: flush dirty pages, LCK_PR on OSTs
1968  *              LL_DV_WR_FLUSH: drop all caching pages, LCK_PW on OSTs
1969  */
1970 int ll_data_version(struct inode *inode, __u64 *data_version, int flags)
1971 {
1972         struct lov_stripe_md    *lsm = NULL;
1973         struct ll_sb_info       *sbi = ll_i2sbi(inode);
1974         struct obdo             *obdo = NULL;
1975         int                      rc;
1976         ENTRY;
1977
1978         /* If no stripe, we consider version is 0. */
1979         lsm = ccc_inode_lsm_get(inode);
1980         if (!lsm_has_objects(lsm)) {
1981                 *data_version = 0;
1982                 CDEBUG(D_INODE, "No object for inode\n");
1983                 GOTO(out, rc = 0);
1984         }
1985
1986         OBD_ALLOC_PTR(obdo);
1987         if (obdo == NULL)
1988                 GOTO(out, rc = -ENOMEM);
1989
1990         rc = ll_lsm_getattr(lsm, sbi->ll_dt_exp, NULL, obdo, 0, flags);
1991         if (rc == 0) {
1992                 if (!(obdo->o_valid & OBD_MD_FLDATAVERSION))
1993                         rc = -EOPNOTSUPP;
1994                 else
1995                         *data_version = obdo->o_data_version;
1996         }
1997
1998         OBD_FREE_PTR(obdo);
1999         EXIT;
2000 out:
2001         ccc_inode_lsm_put(inode, lsm);
2002         RETURN(rc);
2003 }
2004
2005 /*
2006  * Trigger a HSM release request for the provided inode.
2007  */
2008 int ll_hsm_release(struct inode *inode)
2009 {
2010         struct cl_env_nest nest;
2011         struct lu_env *env;
2012         struct obd_client_handle *och = NULL;
2013         __u64 data_version = 0;
2014         int rc;
2015         ENTRY;
2016
2017         CDEBUG(D_INODE, "%s: Releasing file "DFID".\n",
2018                ll_get_fsname(inode->i_sb, NULL, 0),
2019                PFID(&ll_i2info(inode)->lli_fid));
2020
2021         och = ll_lease_open(inode, NULL, FMODE_WRITE, MDS_OPEN_RELEASE);
2022         if (IS_ERR(och))
2023                 GOTO(out, rc = PTR_ERR(och));
2024
2025         /* Grab latest data_version and [am]time values */
2026         rc = ll_data_version(inode, &data_version, LL_DV_WR_FLUSH);
2027         if (rc != 0)
2028                 GOTO(out, rc);
2029
2030         env = cl_env_nested_get(&nest);
2031         if (IS_ERR(env))
2032                 GOTO(out, rc = PTR_ERR(env));
2033
2034         ll_merge_lvb(env, inode);
2035         cl_env_nested_put(&nest, env);
2036
2037         /* Release the file.
2038          * NB: lease lock handle is released in mdc_hsm_release_pack() because
2039          * we still need it to pack l_remote_handle to MDT. */
2040         rc = ll_close_inode_openhandle(ll_i2sbi(inode)->ll_md_exp, inode, och,
2041                                        &data_version);
2042         och = NULL;
2043
2044         EXIT;
2045 out:
2046         if (och != NULL && !IS_ERR(och)) /* close the file */
2047                 ll_lease_close(och, inode, NULL);
2048
2049         return rc;
2050 }
2051
2052 struct ll_swap_stack {
2053         struct iattr             ia1, ia2;
2054         __u64                    dv1, dv2;
2055         struct inode            *inode1, *inode2;
2056         bool                     check_dv1, check_dv2;
2057 };
2058
2059 static int ll_swap_layouts(struct file *file1, struct file *file2,
2060                            struct lustre_swap_layouts *lsl)
2061 {
2062         struct mdc_swap_layouts  msl;
2063         struct md_op_data       *op_data;
2064         __u32                    gid;
2065         __u64                    dv;
2066         struct ll_swap_stack    *llss = NULL;
2067         int                      rc;
2068
2069         OBD_ALLOC_PTR(llss);
2070         if (llss == NULL)
2071                 RETURN(-ENOMEM);
2072
2073         llss->inode1 = file1->f_dentry->d_inode;
2074         llss->inode2 = file2->f_dentry->d_inode;
2075
2076         if (!S_ISREG(llss->inode2->i_mode))
2077                 GOTO(free, rc = -EINVAL);
2078
2079         if (inode_permission(llss->inode1, MAY_WRITE) ||
2080             inode_permission(llss->inode2, MAY_WRITE))
2081                 GOTO(free, rc = -EPERM);
2082
2083         if (llss->inode2->i_sb != llss->inode1->i_sb)
2084                 GOTO(free, rc = -EXDEV);
2085
2086         /* we use 2 bool because it is easier to swap than 2 bits */
2087         if (lsl->sl_flags & SWAP_LAYOUTS_CHECK_DV1)
2088                 llss->check_dv1 = true;
2089
2090         if (lsl->sl_flags & SWAP_LAYOUTS_CHECK_DV2)
2091                 llss->check_dv2 = true;
2092
2093         /* we cannot use lsl->sl_dvX directly because we may swap them */
2094         llss->dv1 = lsl->sl_dv1;
2095         llss->dv2 = lsl->sl_dv2;
2096
2097         rc = lu_fid_cmp(ll_inode2fid(llss->inode1), ll_inode2fid(llss->inode2));
2098         if (rc == 0) /* same file, done! */
2099                 GOTO(free, rc = 0);
2100
2101         if (rc < 0) { /* sequentialize it */
2102                 swap(llss->inode1, llss->inode2);
2103                 swap(file1, file2);
2104                 swap(llss->dv1, llss->dv2);
2105                 swap(llss->check_dv1, llss->check_dv2);
2106         }
2107
2108         gid = lsl->sl_gid;
2109         if (gid != 0) { /* application asks to flush dirty cache */
2110                 rc = ll_get_grouplock(llss->inode1, file1, gid);
2111                 if (rc < 0)
2112                         GOTO(free, rc);
2113
2114                 rc = ll_get_grouplock(llss->inode2, file2, gid);
2115                 if (rc < 0) {
2116                         ll_put_grouplock(llss->inode1, file1, gid);
2117                         GOTO(free, rc);
2118                 }
2119         }
2120
2121         /* to be able to restore mtime and atime after swap
2122          * we need to first save them */
2123         if (lsl->sl_flags &
2124             (SWAP_LAYOUTS_KEEP_MTIME | SWAP_LAYOUTS_KEEP_ATIME)) {
2125                 llss->ia1.ia_mtime = llss->inode1->i_mtime;
2126                 llss->ia1.ia_atime = llss->inode1->i_atime;
2127                 llss->ia1.ia_valid = ATTR_MTIME | ATTR_ATIME;
2128                 llss->ia2.ia_mtime = llss->inode2->i_mtime;
2129                 llss->ia2.ia_atime = llss->inode2->i_atime;
2130                 llss->ia2.ia_valid = ATTR_MTIME | ATTR_ATIME;
2131         }
2132
2133         /* ultimate check, before swaping the layouts we check if
2134          * dataversion has changed (if requested) */
2135         if (llss->check_dv1) {
2136                 rc = ll_data_version(llss->inode1, &dv, 0);
2137                 if (rc)
2138                         GOTO(putgl, rc);
2139                 if (dv != llss->dv1)
2140                         GOTO(putgl, rc = -EAGAIN);
2141         }
2142
2143         if (llss->check_dv2) {
2144                 rc = ll_data_version(llss->inode2, &dv, 0);
2145                 if (rc)
2146                         GOTO(putgl, rc);
2147                 if (dv != llss->dv2)
2148                         GOTO(putgl, rc = -EAGAIN);
2149         }
2150
2151         /* struct md_op_data is used to send the swap args to the mdt
2152          * only flags is missing, so we use struct mdc_swap_layouts
2153          * through the md_op_data->op_data */
2154         /* flags from user space have to be converted before they are send to
2155          * server, no flag is sent today, they are only used on the client */
2156         msl.msl_flags = 0;
2157         rc = -ENOMEM;
2158         op_data = ll_prep_md_op_data(NULL, llss->inode1, llss->inode2, NULL, 0,
2159                                      0, LUSTRE_OPC_ANY, &msl);
2160         if (IS_ERR(op_data))
2161                 GOTO(free, rc = PTR_ERR(op_data));
2162
2163         rc = obd_iocontrol(LL_IOC_LOV_SWAP_LAYOUTS, ll_i2mdexp(llss->inode1),
2164                            sizeof(*op_data), op_data, NULL);
2165         ll_finish_md_op_data(op_data);
2166
2167 putgl:
2168         if (gid != 0) {
2169                 ll_put_grouplock(llss->inode2, file2, gid);
2170                 ll_put_grouplock(llss->inode1, file1, gid);
2171         }
2172
2173         /* rc can be set from obd_iocontrol() or from a GOTO(putgl, ...) */
2174         if (rc != 0)
2175                 GOTO(free, rc);
2176
2177         /* clear useless flags */
2178         if (!(lsl->sl_flags & SWAP_LAYOUTS_KEEP_MTIME)) {
2179                 llss->ia1.ia_valid &= ~ATTR_MTIME;
2180                 llss->ia2.ia_valid &= ~ATTR_MTIME;
2181         }
2182
2183         if (!(lsl->sl_flags & SWAP_LAYOUTS_KEEP_ATIME)) {
2184                 llss->ia1.ia_valid &= ~ATTR_ATIME;
2185                 llss->ia2.ia_valid &= ~ATTR_ATIME;
2186         }
2187
2188         /* update time if requested */
2189         rc = 0;
2190         if (llss->ia2.ia_valid != 0) {
2191                 mutex_lock(&llss->inode1->i_mutex);
2192                 rc = ll_setattr(file1->f_dentry, &llss->ia2);
2193                 mutex_unlock(&llss->inode1->i_mutex);
2194         }
2195
2196         if (llss->ia1.ia_valid != 0) {
2197                 int rc1;
2198
2199                 mutex_lock(&llss->inode2->i_mutex);
2200                 rc1 = ll_setattr(file2->f_dentry, &llss->ia1);
2201                 mutex_unlock(&llss->inode2->i_mutex);
2202                 if (rc == 0)
2203                         rc = rc1;
2204         }
2205
2206 free:
2207         if (llss != NULL)
2208                 OBD_FREE_PTR(llss);
2209
2210         RETURN(rc);
2211 }
2212
2213 static int ll_hsm_state_set(struct inode *inode, struct hsm_state_set *hss)
2214 {
2215         struct md_op_data       *op_data;
2216         int                      rc;
2217
2218         /* Non-root users are forbidden to set or clear flags which are
2219          * NOT defined in HSM_USER_MASK. */
2220         if (((hss->hss_setmask | hss->hss_clearmask) & ~HSM_USER_MASK) &&
2221             !cfs_capable(CFS_CAP_SYS_ADMIN))
2222                 RETURN(-EPERM);
2223
2224         op_data = ll_prep_md_op_data(NULL, inode, NULL, NULL, 0, 0,
2225                                      LUSTRE_OPC_ANY, hss);
2226         if (IS_ERR(op_data))
2227                 RETURN(PTR_ERR(op_data));
2228
2229         rc = obd_iocontrol(LL_IOC_HSM_STATE_SET, ll_i2mdexp(inode),
2230                            sizeof(*op_data), op_data, NULL);
2231
2232         ll_finish_md_op_data(op_data);
2233
2234         RETURN(rc);
2235 }
2236
2237 static int ll_hsm_import(struct inode *inode, struct file *file,
2238                          struct hsm_user_import *hui)
2239 {
2240         struct hsm_state_set    *hss = NULL;
2241         struct iattr            *attr = NULL;
2242         int                      rc;
2243         ENTRY;
2244
2245         if (!S_ISREG(inode->i_mode))
2246                 RETURN(-EINVAL);
2247
2248         /* set HSM flags */
2249         OBD_ALLOC_PTR(hss);
2250         if (hss == NULL)
2251                 GOTO(out, rc = -ENOMEM);
2252
2253         hss->hss_valid = HSS_SETMASK | HSS_ARCHIVE_ID;
2254         hss->hss_archive_id = hui->hui_archive_id;
2255         hss->hss_setmask = HS_ARCHIVED | HS_EXISTS | HS_RELEASED;
2256         rc = ll_hsm_state_set(inode, hss);
2257         if (rc != 0)
2258                 GOTO(out, rc);
2259
2260         OBD_ALLOC_PTR(attr);
2261         if (attr == NULL)
2262                 GOTO(out, rc = -ENOMEM);
2263
2264         attr->ia_mode = hui->hui_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
2265         attr->ia_mode |= S_IFREG;
2266         attr->ia_uid = hui->hui_uid;
2267         attr->ia_gid = hui->hui_gid;
2268         attr->ia_size = hui->hui_size;
2269         attr->ia_mtime.tv_sec = hui->hui_mtime;
2270         attr->ia_mtime.tv_nsec = hui->hui_mtime_ns;
2271         attr->ia_atime.tv_sec = hui->hui_atime;
2272         attr->ia_atime.tv_nsec = hui->hui_atime_ns;
2273
2274         attr->ia_valid = ATTR_SIZE | ATTR_MODE | ATTR_FORCE |
2275                          ATTR_UID | ATTR_GID |
2276                          ATTR_MTIME | ATTR_MTIME_SET |
2277                          ATTR_ATIME | ATTR_ATIME_SET;
2278
2279         rc = ll_setattr_raw(file->f_dentry, attr, true);
2280         if (rc == -ENODATA)
2281                 rc = 0;
2282
2283 out:
2284         if (hss != NULL)
2285                 OBD_FREE_PTR(hss);
2286
2287         if (attr != NULL)
2288                 OBD_FREE_PTR(attr);
2289
2290         RETURN(rc);
2291 }
2292
2293 long ll_file_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
2294 {
2295         struct inode            *inode = file->f_dentry->d_inode;
2296         struct ll_file_data     *fd = LUSTRE_FPRIVATE(file);
2297         int                      flags, rc;
2298         ENTRY;
2299
2300         CDEBUG(D_VFSTRACE, "VFS Op:inode="DFID"(%p), cmd=%x\n",
2301                PFID(ll_inode2fid(inode)), inode, cmd);
2302         ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_IOCTL, 1);
2303
2304         /* asm-ppc{,64} declares TCGETS, et. al. as type 't' not 'T' */
2305         if (_IOC_TYPE(cmd) == 'T' || _IOC_TYPE(cmd) == 't') /* tty ioctls */
2306                 RETURN(-ENOTTY);
2307
2308         switch(cmd) {
2309         case LL_IOC_GETFLAGS:
2310                 /* Get the current value of the file flags */
2311                 return put_user(fd->fd_flags, (int *)arg);
2312         case LL_IOC_SETFLAGS:
2313         case LL_IOC_CLRFLAGS:
2314                 /* Set or clear specific file flags */
2315                 /* XXX This probably needs checks to ensure the flags are
2316                  *     not abused, and to handle any flag side effects.
2317                  */
2318                 if (get_user(flags, (int *) arg))
2319                         RETURN(-EFAULT);
2320
2321                 if (cmd == LL_IOC_SETFLAGS) {
2322                         if ((flags & LL_FILE_IGNORE_LOCK) &&
2323                             !(file->f_flags & O_DIRECT)) {
2324                                 CERROR("%s: unable to disable locking on "
2325                                        "non-O_DIRECT file\n", current->comm);
2326                                 RETURN(-EINVAL);
2327                         }
2328
2329                         fd->fd_flags |= flags;
2330                 } else {
2331                         fd->fd_flags &= ~flags;
2332                 }
2333                 RETURN(0);
2334         case LL_IOC_LOV_SETSTRIPE:
2335                 RETURN(ll_lov_setstripe(inode, file, arg));
2336         case LL_IOC_LOV_SETEA:
2337                 RETURN(ll_lov_setea(inode, file, arg));
2338         case LL_IOC_LOV_SWAP_LAYOUTS: {
2339                 struct file *file2;
2340                 struct lustre_swap_layouts lsl;
2341
2342                 if (copy_from_user(&lsl, (char *)arg,
2343                                        sizeof(struct lustre_swap_layouts)))
2344                         RETURN(-EFAULT);
2345
2346                 if ((file->f_flags & O_ACCMODE) == 0) /* O_RDONLY */
2347                         RETURN(-EPERM);
2348
2349                 file2 = fget(lsl.sl_fd);
2350                 if (file2 == NULL)
2351                         RETURN(-EBADF);
2352
2353                 rc = -EPERM;
2354                 if ((file2->f_flags & O_ACCMODE) != 0) /* O_WRONLY or O_RDWR */
2355                         rc = ll_swap_layouts(file, file2, &lsl);
2356                 fput(file2);
2357                 RETURN(rc);
2358         }
2359         case LL_IOC_LOV_GETSTRIPE:
2360                 RETURN(ll_lov_getstripe(inode, arg));
2361         case LL_IOC_RECREATE_OBJ:
2362                 RETURN(ll_lov_recreate_obj(inode, arg));
2363         case LL_IOC_RECREATE_FID:
2364                 RETURN(ll_lov_recreate_fid(inode, arg));
2365         case FSFILT_IOC_FIEMAP:
2366                 RETURN(ll_ioctl_fiemap(inode, arg));
2367         case FSFILT_IOC_GETFLAGS:
2368         case FSFILT_IOC_SETFLAGS:
2369                 RETURN(ll_iocontrol(inode, file, cmd, arg));
2370         case FSFILT_IOC_GETVERSION_OLD:
2371         case FSFILT_IOC_GETVERSION:
2372                 RETURN(put_user(inode->i_generation, (int *)arg));
2373         case LL_IOC_GROUP_LOCK:
2374                 RETURN(ll_get_grouplock(inode, file, arg));
2375         case LL_IOC_GROUP_UNLOCK:
2376                 RETURN(ll_put_grouplock(inode, file, arg));
2377         case IOC_OBD_STATFS:
2378                 RETURN(ll_obd_statfs(inode, (void *)arg));
2379
2380         /* We need to special case any other ioctls we want to handle,
2381          * to send them to the MDS/OST as appropriate and to properly
2382          * network encode the arg field.
2383         case FSFILT_IOC_SETVERSION_OLD:
2384         case FSFILT_IOC_SETVERSION:
2385         */
2386         case LL_IOC_FLUSHCTX:
2387                 RETURN(ll_flush_ctx(inode));
2388         case LL_IOC_PATH2FID: {
2389                 if (copy_to_user((void *)arg, ll_inode2fid(inode),
2390                                  sizeof(struct lu_fid)))
2391                         RETURN(-EFAULT);
2392
2393                 RETURN(0);
2394         }
2395         case OBD_IOC_FID2PATH:
2396                 RETURN(ll_fid2path(inode, (void *)arg));
2397         case LL_IOC_DATA_VERSION: {
2398                 struct ioc_data_version idv;
2399                 int rc;
2400
2401                 if (copy_from_user(&idv, (char *)arg, sizeof(idv)))
2402                         RETURN(-EFAULT);
2403
2404                 idv.idv_flags &= LL_DV_RD_FLUSH | LL_DV_WR_FLUSH;
2405                 rc = ll_data_version(inode, &idv.idv_version, idv.idv_flags);
2406
2407                 if (rc == 0 && copy_to_user((char *) arg, &idv, sizeof(idv)))
2408                         RETURN(-EFAULT);
2409
2410                 RETURN(rc);
2411         }
2412
2413         case LL_IOC_GET_MDTIDX: {
2414                 int mdtidx;
2415
2416                 mdtidx = ll_get_mdt_idx(inode);
2417                 if (mdtidx < 0)
2418                         RETURN(mdtidx);
2419
2420                 if (put_user((int)mdtidx, (int*)arg))
2421                         RETURN(-EFAULT);
2422
2423                 RETURN(0);
2424         }
2425         case OBD_IOC_GETDTNAME:
2426         case OBD_IOC_GETMDNAME:
2427                 RETURN(ll_get_obd_name(inode, cmd, arg));
2428         case LL_IOC_HSM_STATE_GET: {
2429                 struct md_op_data       *op_data;
2430                 struct hsm_user_state   *hus;
2431                 int                      rc;
2432
2433                 OBD_ALLOC_PTR(hus);
2434                 if (hus == NULL)
2435                         RETURN(-ENOMEM);
2436
2437                 op_data = ll_prep_md_op_data(NULL, inode, NULL, NULL, 0, 0,
2438                                              LUSTRE_OPC_ANY, hus);
2439                 if (IS_ERR(op_data)) {
2440                         OBD_FREE_PTR(hus);
2441                         RETURN(PTR_ERR(op_data));
2442                 }
2443
2444                 rc = obd_iocontrol(cmd, ll_i2mdexp(inode), sizeof(*op_data),
2445                                    op_data, NULL);
2446
2447                 if (copy_to_user((void *)arg, hus, sizeof(*hus)))
2448                         rc = -EFAULT;
2449
2450                 ll_finish_md_op_data(op_data);
2451                 OBD_FREE_PTR(hus);
2452                 RETURN(rc);
2453         }
2454         case LL_IOC_HSM_STATE_SET: {
2455                 struct hsm_state_set    *hss;
2456                 int                      rc;
2457
2458                 OBD_ALLOC_PTR(hss);
2459                 if (hss == NULL)
2460                         RETURN(-ENOMEM);
2461
2462                 if (copy_from_user(hss, (char *)arg, sizeof(*hss))) {
2463                         OBD_FREE_PTR(hss);
2464                         RETURN(-EFAULT);
2465                 }
2466
2467                 rc = ll_hsm_state_set(inode, hss);
2468
2469                 OBD_FREE_PTR(hss);
2470                 RETURN(rc);
2471         }
2472         case LL_IOC_HSM_ACTION: {
2473                 struct md_op_data               *op_data;
2474                 struct hsm_current_action       *hca;
2475                 int                              rc;
2476
2477                 OBD_ALLOC_PTR(hca);
2478                 if (hca == NULL)
2479                         RETURN(-ENOMEM);
2480
2481                 op_data = ll_prep_md_op_data(NULL, inode, NULL, NULL, 0, 0,
2482                                              LUSTRE_OPC_ANY, hca);
2483                 if (IS_ERR(op_data)) {
2484                         OBD_FREE_PTR(hca);
2485                         RETURN(PTR_ERR(op_data));
2486                 }
2487
2488                 rc = obd_iocontrol(cmd, ll_i2mdexp(inode), sizeof(*op_data),
2489                                    op_data, NULL);
2490
2491                 if (copy_to_user((char *)arg, hca, sizeof(*hca)))
2492                         rc = -EFAULT;
2493
2494                 ll_finish_md_op_data(op_data);
2495                 OBD_FREE_PTR(hca);
2496                 RETURN(rc);
2497         }
2498         case LL_IOC_SET_LEASE: {
2499                 struct ll_inode_info *lli = ll_i2info(inode);
2500                 struct obd_client_handle *och = NULL;
2501                 bool lease_broken;
2502                 fmode_t mode = 0;
2503
2504                 switch (arg) {
2505                 case F_WRLCK:
2506                         if (!(file->f_mode & FMODE_WRITE))
2507                                 RETURN(-EPERM);
2508                         mode = FMODE_WRITE;
2509                         break;
2510                 case F_RDLCK:
2511                         if (!(file->f_mode & FMODE_READ))
2512                                 RETURN(-EPERM);
2513                         mode = FMODE_READ;
2514                         break;
2515                 case F_UNLCK:
2516                         mutex_lock(&lli->lli_och_mutex);
2517                         if (fd->fd_lease_och != NULL) {
2518                                 och = fd->fd_lease_och;
2519                                 fd->fd_lease_och = NULL;
2520                         }
2521                         mutex_unlock(&lli->lli_och_mutex);
2522
2523                         if (och != NULL) {
2524                                 mode = och->och_flags &(FMODE_READ|FMODE_WRITE);
2525                                 rc = ll_lease_close(och, inode, &lease_broken);
2526                                 if (rc == 0 && lease_broken)
2527                                         mode = 0;
2528                         } else {
2529                                 rc = -ENOLCK;
2530                         }
2531
2532                         /* return the type of lease or error */
2533                         RETURN(rc < 0 ? rc : (int)mode);
2534                 default:
2535                         RETURN(-EINVAL);
2536                 }
2537
2538                 CDEBUG(D_INODE, "Set lease with mode %d\n", mode);
2539
2540                 /* apply for lease */
2541                 och = ll_lease_open(inode, file, mode, 0);
2542                 if (IS_ERR(och))
2543                         RETURN(PTR_ERR(och));
2544
2545                 rc = 0;
2546                 mutex_lock(&lli->lli_och_mutex);
2547                 if (fd->fd_lease_och == NULL) {
2548                         fd->fd_lease_och = och;
2549                         och = NULL;
2550                 }
2551                 mutex_unlock(&lli->lli_och_mutex);
2552                 if (och != NULL) {
2553                         /* impossible now that only excl is supported for now */
2554                         ll_lease_close(och, inode, &lease_broken);
2555                         rc = -EBUSY;
2556                 }
2557                 RETURN(rc);
2558         }
2559         case LL_IOC_GET_LEASE: {
2560                 struct ll_inode_info *lli = ll_i2info(inode);
2561                 struct ldlm_lock *lock = NULL;
2562
2563                 rc = 0;
2564                 mutex_lock(&lli->lli_och_mutex);
2565                 if (fd->fd_lease_och != NULL) {
2566                         struct obd_client_handle *och = fd->fd_lease_och;
2567
2568                         lock = ldlm_handle2lock(&och->och_lease_handle);
2569                         if (lock != NULL) {
2570                                 lock_res_and_lock(lock);
2571                                 if (!ldlm_is_cancel(lock))
2572                                         rc = och->och_flags &
2573                                                 (FMODE_READ | FMODE_WRITE);
2574                                 unlock_res_and_lock(lock);
2575                                 LDLM_LOCK_PUT(lock);
2576                         }
2577                 }
2578                 mutex_unlock(&lli->lli_och_mutex);
2579                 RETURN(rc);
2580         }
2581         case LL_IOC_HSM_IMPORT: {
2582                 struct hsm_user_import *hui;
2583
2584                 OBD_ALLOC_PTR(hui);
2585                 if (hui == NULL)
2586                         RETURN(-ENOMEM);
2587
2588                 if (copy_from_user(hui, (void *)arg, sizeof(*hui))) {
2589                         OBD_FREE_PTR(hui);
2590                         RETURN(-EFAULT);
2591                 }
2592
2593                 rc = ll_hsm_import(inode, file, hui);
2594
2595                 OBD_FREE_PTR(hui);
2596                 RETURN(rc);
2597         }
2598         default: {
2599                 int err;
2600
2601                 if (LLIOC_STOP ==
2602                      ll_iocontrol_call(inode, file, cmd, arg, &err))
2603                         RETURN(err);
2604
2605                 RETURN(obd_iocontrol(cmd, ll_i2dtexp(inode), 0, NULL,
2606                                      (void *)arg));
2607         }
2608         }
2609 }
2610
2611 #ifndef HAVE_FILE_LLSEEK_SIZE
2612 static inline loff_t
2613 llseek_execute(struct file *file, loff_t offset, loff_t maxsize)
2614 {
2615         if (offset < 0 && !(file->f_mode & FMODE_UNSIGNED_OFFSET))
2616                 return -EINVAL;
2617         if (offset > maxsize)
2618                 return -EINVAL;
2619
2620         if (offset != file->f_pos) {
2621                 file->f_pos = offset;
2622                 file->f_version = 0;
2623         }
2624         return offset;
2625 }
2626
2627 static loff_t
2628 generic_file_llseek_size(struct file *file, loff_t offset, int origin,
2629                 loff_t maxsize, loff_t eof)
2630 {
2631         struct inode *inode = file->f_dentry->d_inode;
2632
2633         switch (origin) {
2634         case SEEK_END:
2635                 offset += eof;
2636                 break;
2637         case SEEK_CUR:
2638                 /*
2639                  * Here we special-case the lseek(fd, 0, SEEK_CUR)
2640                  * position-querying operation.  Avoid rewriting the "same"
2641                  * f_pos value back to the file because a concurrent read(),
2642                  * write() or lseek() might have altered it
2643                  */
2644                 if (offset == 0)
2645                         return file->f_pos;
2646                 /*
2647                  * f_lock protects against read/modify/write race with other
2648                  * SEEK_CURs. Note that parallel writes and reads behave
2649                  * like SEEK_SET.
2650                  */
2651                 mutex_lock(&inode->i_mutex);
2652                 offset = llseek_execute(file, file->f_pos + offset, maxsize);
2653                 mutex_unlock(&inode->i_mutex);
2654                 return offset;
2655         case SEEK_DATA:
2656                 /*
2657                  * In the generic case the entire file is data, so as long as
2658                  * offset isn't at the end of the file then the offset is data.
2659                  */
2660                 if (offset >= eof)
2661                         return -ENXIO;
2662                 break;
2663         case SEEK_HOLE:
2664                 /*
2665                  * There is a virtual hole at the end of the file, so as long as
2666                  * offset isn't i_size or larger, return i_size.
2667                  */
2668                 if (offset >= eof)
2669                         return -ENXIO;
2670                 offset = eof;
2671                 break;
2672         }
2673
2674         return llseek_execute(file, offset, maxsize);
2675 }
2676 #endif
2677
2678 loff_t ll_file_seek(struct file *file, loff_t offset, int origin)
2679 {
2680         struct inode *inode = file->f_dentry->d_inode;
2681         loff_t retval, eof = 0;
2682
2683         ENTRY;
2684         retval = offset + ((origin == SEEK_END) ? i_size_read(inode) :
2685                            (origin == SEEK_CUR) ? file->f_pos : 0);
2686         CDEBUG(D_VFSTRACE, "VFS Op:inode="DFID"(%p), to=%llu=%#llx(%d)\n",
2687                PFID(ll_inode2fid(inode)), inode, retval, retval,
2688                origin);
2689         ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_LLSEEK, 1);
2690
2691         if (origin == SEEK_END || origin == SEEK_HOLE || origin == SEEK_DATA) {
2692                 retval = ll_glimpse_size(inode);
2693                 if (retval != 0)
2694                         RETURN(retval);
2695                 eof = i_size_read(inode);
2696         }
2697
2698         retval = ll_generic_file_llseek_size(file, offset, origin,
2699                                           ll_file_maxbytes(inode), eof);
2700         RETURN(retval);
2701 }
2702
2703 int ll_flush(struct file *file, fl_owner_t id)
2704 {
2705         struct inode *inode = file->f_dentry->d_inode;
2706         struct ll_inode_info *lli = ll_i2info(inode);
2707         struct ll_file_data *fd = LUSTRE_FPRIVATE(file);
2708         int rc, err;
2709
2710         LASSERT(!S_ISDIR(inode->i_mode));
2711
2712         /* catch async errors that were recorded back when async writeback
2713          * failed for pages in this mapping. */
2714         rc = lli->lli_async_rc;
2715         lli->lli_async_rc = 0;
2716         err = lov_read_and_clear_async_rc(lli->lli_clob);
2717         if (rc == 0)
2718                 rc = err;
2719
2720         /* The application has been told write failure already.
2721          * Do not report failure again. */
2722         if (fd->fd_write_failed)
2723                 return 0;
2724         return rc ? -EIO : 0;
2725 }
2726
2727 /**
2728  * Called to make sure a portion of file has been written out.
2729  * if @local_only is not true, it will send OST_SYNC RPCs to ost.
2730  *
2731  * Return how many pages have been written.
2732  */
2733 int cl_sync_file_range(struct inode *inode, loff_t start, loff_t end,
2734                        enum cl_fsync_mode mode, int ignore_layout)
2735 {
2736         struct cl_env_nest nest;
2737         struct lu_env *env;
2738         struct cl_io *io;
2739         struct obd_capa *capa = NULL;
2740         struct cl_fsync_io *fio;
2741         int result;
2742         ENTRY;
2743
2744         if (mode != CL_FSYNC_NONE && mode != CL_FSYNC_LOCAL &&
2745             mode != CL_FSYNC_DISCARD && mode != CL_FSYNC_ALL)
2746                 RETURN(-EINVAL);
2747
2748         env = cl_env_nested_get(&nest);
2749         if (IS_ERR(env))
2750                 RETURN(PTR_ERR(env));
2751
2752         capa = ll_osscapa_get(inode, CAPA_OPC_OSS_WRITE);
2753
2754         io = ccc_env_thread_io(env);
2755         io->ci_obj = cl_i2info(inode)->lli_clob;
2756         io->ci_ignore_layout = ignore_layout;
2757
2758         /* initialize parameters for sync */
2759         fio = &io->u.ci_fsync;
2760         fio->fi_capa = capa;
2761         fio->fi_start = start;
2762         fio->fi_end = end;
2763         fio->fi_fid = ll_inode2fid(inode);
2764         fio->fi_mode = mode;
2765         fio->fi_nr_written = 0;
2766
2767         if (cl_io_init(env, io, CIT_FSYNC, io->ci_obj) == 0)
2768                 result = cl_io_loop(env, io);
2769         else
2770                 result = io->ci_result;
2771         if (result == 0)
2772                 result = fio->fi_nr_written;
2773         cl_io_fini(env, io);
2774         cl_env_nested_put(&nest, env);
2775
2776         capa_put(capa);
2777
2778         RETURN(result);
2779 }
2780
2781 /*
2782  * When dentry is provided (the 'else' case), *file->f_dentry may be
2783  * null and dentry must be used directly rather than pulled from
2784  * *file->f_dentry as is done otherwise.
2785  */
2786
2787 #ifdef HAVE_FILE_FSYNC_4ARGS
2788 int ll_fsync(struct file *file, loff_t start, loff_t end, int datasync)
2789 {
2790         struct dentry *dentry = file->f_dentry;
2791 #elif defined(HAVE_FILE_FSYNC_2ARGS)
2792 int ll_fsync(struct file *file, int datasync)
2793 {
2794         struct dentry *dentry = file->f_dentry;
2795 #else
2796 int ll_fsync(struct file *file, struct dentry *dentry, int datasync)
2797 {
2798 #endif
2799         struct inode *inode = dentry->d_inode;
2800         struct ll_inode_info *lli = ll_i2info(inode);
2801         struct ptlrpc_request *req;
2802         struct obd_capa *oc;
2803         int rc, err;
2804         ENTRY;
2805
2806         CDEBUG(D_VFSTRACE, "VFS Op:inode="DFID"(%p)\n",
2807                PFID(ll_inode2fid(inode)), inode);
2808         ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_FSYNC, 1);
2809
2810 #ifdef HAVE_FILE_FSYNC_4ARGS
2811         rc = filemap_write_and_wait_range(inode->i_mapping, start, end);
2812         mutex_lock(&inode->i_mutex);
2813 #else
2814         /* fsync's caller has already called _fdata{sync,write}, we want
2815          * that IO to finish before calling the osc and mdc sync methods */
2816         rc = filemap_fdatawait(inode->i_mapping);
2817 #endif
2818
2819         /* catch async errors that were recorded back when async writeback
2820          * failed for pages in this mapping. */
2821         if (!S_ISDIR(inode->i_mode)) {
2822                 err = lli->lli_async_rc;
2823                 lli->lli_async_rc = 0;
2824                 if (rc == 0)
2825                         rc = err;
2826                 err = lov_read_and_clear_async_rc(lli->lli_clob);
2827                 if (rc == 0)
2828                         rc = err;
2829         }
2830
2831         oc = ll_mdscapa_get(inode);
2832         err = md_fsync(ll_i2sbi(inode)->ll_md_exp, ll_inode2fid(inode), oc,
2833                        &req);
2834         capa_put(oc);
2835         if (!rc)
2836                 rc = err;
2837         if (!err)
2838                 ptlrpc_req_finished(req);
2839
2840         if (datasync && S_ISREG(inode->i_mode)) {
2841                 struct ll_file_data *fd = LUSTRE_FPRIVATE(file);
2842
2843                 err = cl_sync_file_range(inode, 0, OBD_OBJECT_EOF,
2844                                 CL_FSYNC_ALL, 0);
2845                 if (rc == 0 && err < 0)
2846                         rc = err;
2847                 if (rc < 0)
2848                         fd->fd_write_failed = true;
2849                 else
2850                         fd->fd_write_failed = false;
2851         }
2852
2853 #ifdef HAVE_FILE_FSYNC_4ARGS
2854         mutex_unlock(&inode->i_mutex);
2855 #endif
2856         RETURN(rc);
2857 }
2858
2859 int ll_file_flock(struct file *file, int cmd, struct file_lock *file_lock)
2860 {
2861         struct inode *inode = file->f_dentry->d_inode;
2862         struct ll_sb_info *sbi = ll_i2sbi(inode);
2863         struct ldlm_enqueue_info einfo = {
2864                 .ei_type        = LDLM_FLOCK,
2865                 .ei_cb_cp       = ldlm_flock_completion_ast,
2866                 .ei_cbdata      = file_lock,
2867         };
2868         struct md_op_data *op_data;
2869         struct lustre_handle lockh = {0};
2870         ldlm_policy_data_t flock = {{0}};
2871         __u64 flags = 0;
2872         int rc;
2873         int rc2 = 0;
2874         ENTRY;
2875
2876         CDEBUG(D_VFSTRACE, "VFS Op:inode="DFID" file_lock=%p\n",
2877                PFID(ll_inode2fid(inode)), file_lock);
2878
2879         ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_FLOCK, 1);
2880
2881         if (file_lock->fl_flags & FL_FLOCK) {
2882                 LASSERT((cmd == F_SETLKW) || (cmd == F_SETLK));
2883                 /* flocks are whole-file locks */
2884                 flock.l_flock.end = OFFSET_MAX;
2885                 /* For flocks owner is determined by the local file desctiptor*/
2886                 flock.l_flock.owner = (unsigned long)file_lock->fl_file;
2887         } else if (file_lock->fl_flags & FL_POSIX) {
2888                 flock.l_flock.owner = (unsigned long)file_lock->fl_owner;
2889                 flock.l_flock.start = file_lock->fl_start;
2890                 flock.l_flock.end = file_lock->fl_end;
2891         } else {
2892                 RETURN(-EINVAL);
2893         }
2894         flock.l_flock.pid = file_lock->fl_pid;
2895
2896         /* Somewhat ugly workaround for svc lockd.
2897          * lockd installs custom fl_lmops->lm_compare_owner that checks
2898          * for the fl_owner to be the same (which it always is on local node
2899          * I guess between lockd processes) and then compares pid.
2900          * As such we assign pid to the owner field to make it all work,
2901          * conflict with normal locks is unlikely since pid space and
2902          * pointer space for current->files are not intersecting */
2903         if (file_lock->fl_lmops && file_lock->fl_lmops->lm_compare_owner)
2904                 flock.l_flock.owner = (unsigned long)file_lock->fl_pid;
2905
2906         switch (file_lock->fl_type) {
2907         case F_RDLCK:
2908                 einfo.ei_mode = LCK_PR;
2909                 break;
2910         case F_UNLCK:
2911                 /* An unlock request may or may not have any relation to
2912                  * existing locks so we may not be able to pass a lock handle
2913                  * via a normal ldlm_lock_cancel() request. The request may even
2914                  * unlock a byte range in the middle of an existing lock. In
2915                  * order to process an unlock request we need all of the same
2916                  * information that is given with a normal read or write record
2917                  * lock request. To avoid creating another ldlm unlock (cancel)
2918                  * message we'll treat a LCK_NL flock request as an unlock. */
2919                 einfo.ei_mode = LCK_NL;
2920                 break;
2921         case F_WRLCK:
2922                 einfo.ei_mode = LCK_PW;
2923                 break;
2924         default:
2925                 CDEBUG(D_INFO, "Unknown fcntl lock type: %d\n",
2926                         file_lock->fl_type);
2927                 RETURN (-ENOTSUPP);
2928         }
2929
2930         switch (cmd) {
2931         case F_SETLKW:
2932 #ifdef F_SETLKW64
2933         case F_SETLKW64:
2934 #endif
2935                 flags = 0;
2936                 break;
2937         case F_SETLK:
2938 #ifdef F_SETLK64
2939         case F_SETLK64:
2940 #endif
2941                 flags = LDLM_FL_BLOCK_NOWAIT;
2942                 break;
2943         case F_GETLK:
2944 #ifdef F_GETLK64
2945         case F_GETLK64:
2946 #endif
2947                 flags = LDLM_FL_TEST_LOCK;
2948                 /* Save the old mode so that if the mode in the lock changes we
2949                  * can decrement the appropriate reader or writer refcount. */
2950                 file_lock->fl_type = einfo.ei_mode;
2951                 break;
2952         default:
2953                 CERROR("unknown fcntl lock command: %d\n", cmd);
2954                 RETURN (-EINVAL);
2955         }
2956
2957         op_data = ll_prep_md_op_data(NULL, inode, NULL, NULL, 0, 0,
2958                                      LUSTRE_OPC_ANY, NULL);
2959         if (IS_ERR(op_data))
2960                 RETURN(PTR_ERR(op_data));
2961
2962         CDEBUG(D_DLMTRACE, "inode="DFID", pid=%u, flags="LPX64", mode=%u, "
2963                "start="LPU64", end="LPU64"\n", PFID(ll_inode2fid(inode)),
2964                flock.l_flock.pid, flags, einfo.ei_mode,
2965                flock.l_flock.start, flock.l_flock.end);
2966
2967         rc = md_enqueue(sbi->ll_md_exp, &einfo, NULL,
2968                         op_data, &lockh, &flock, 0, NULL /* req */, flags);
2969
2970         if ((file_lock->fl_flags & FL_FLOCK) &&
2971             (rc == 0 || file_lock->fl_type == F_UNLCK))
2972                 rc2  = flock_lock_file_wait(file, file_lock);
2973         if ((file_lock->fl_flags & FL_POSIX) &&
2974             (rc == 0 || file_lock->fl_type == F_UNLCK) &&
2975             !(flags & LDLM_FL_TEST_LOCK))
2976                 rc2  = posix_lock_file_wait(file, file_lock);
2977
2978         if (rc2 && file_lock->fl_type != F_UNLCK) {
2979                 einfo.ei_mode = LCK_NL;
2980                 md_enqueue(sbi->ll_md_exp, &einfo, NULL,
2981                         op_data, &lockh, &flock, 0, NULL /* req */, flags);
2982                 rc = rc2;
2983         }
2984
2985         ll_finish_md_op_data(op_data);
2986
2987         RETURN(rc);
2988 }
2989
2990 int ll_file_noflock(struct file *file, int cmd, struct file_lock *file_lock)
2991 {
2992         ENTRY;
2993
2994         RETURN(-ENOSYS);
2995 }
2996
2997 /**
2998  * test if some locks matching bits and l_req_mode are acquired
2999  * - bits can be in different locks
3000  * - if found clear the common lock bits in *bits
3001  * - the bits not found, are kept in *bits
3002  * \param inode [IN]
3003  * \param bits [IN] searched lock bits [IN]
3004  * \param l_req_mode [IN] searched lock mode
3005  * \retval boolean, true iff all bits are found
3006  */
3007 int ll_have_md_lock(struct inode *inode, __u64 *bits,  ldlm_mode_t l_req_mode)
3008 {
3009         struct lustre_handle lockh;
3010         ldlm_policy_data_t policy;
3011         ldlm_mode_t mode = (l_req_mode == LCK_MINMODE) ?
3012                                 (LCK_CR|LCK_CW|LCK_PR|LCK_PW) : l_req_mode;
3013         struct lu_fid *fid;
3014         __u64 flags;
3015         int i;
3016         ENTRY;
3017
3018         if (!inode)
3019                RETURN(0);
3020
3021         fid = &ll_i2info(inode)->lli_fid;
3022         CDEBUG(D_INFO, "trying to match res "DFID" mode %s\n", PFID(fid),
3023                ldlm_lockname[mode]);
3024
3025         flags = LDLM_FL_BLOCK_GRANTED | LDLM_FL_CBPENDING | LDLM_FL_TEST_LOCK;
3026         for (i = 0; i <= MDS_INODELOCK_MAXSHIFT && *bits != 0; i++) {
3027                 policy.l_inodebits.bits = *bits & (1 << i);
3028                 if (policy.l_inodebits.bits == 0)
3029                         continue;
3030
3031                 if (md_lock_match(ll_i2mdexp(inode), flags, fid, LDLM_IBITS,
3032                                   &policy, mode, &lockh)) {
3033                         struct ldlm_lock *lock;
3034
3035                         lock = ldlm_handle2lock(&lockh);
3036                         if (lock) {
3037                                 *bits &=
3038                                       ~(lock->l_policy_data.l_inodebits.bits);
3039                                 LDLM_LOCK_PUT(lock);
3040                         } else {
3041                                 *bits &= ~policy.l_inodebits.bits;
3042                         }
3043                 }
3044         }
3045         RETURN(*bits == 0);
3046 }
3047
3048 ldlm_mode_t ll_take_md_lock(struct inode *inode, __u64 bits,
3049                             struct lustre_handle *lockh, __u64 flags,
3050                             ldlm_mode_t mode)
3051 {
3052         ldlm_policy_data_t policy = { .l_inodebits = {bits}};
3053         struct lu_fid *fid;
3054         ldlm_mode_t rc;
3055         ENTRY;
3056
3057         fid = &ll_i2info(inode)->lli_fid;
3058         CDEBUG(D_INFO, "trying to match res "DFID"\n", PFID(fid));
3059
3060         rc = md_lock_match(ll_i2mdexp(inode), LDLM_FL_BLOCK_GRANTED|flags,
3061                            fid, LDLM_IBITS, &policy, mode, lockh);
3062
3063         RETURN(rc);
3064 }
3065
3066 static int ll_inode_revalidate_fini(struct inode *inode, int rc)
3067 {
3068         /* Already unlinked. Just update nlink and return success */
3069         if (rc == -ENOENT) {
3070                 clear_nlink(inode);
3071                 /* This path cannot be hit for regular files unless in
3072                  * case of obscure races, so no need to to validate
3073                  * size. */
3074                 if (!S_ISREG(inode->i_mode) && !S_ISDIR(inode->i_mode))
3075                         return 0;
3076         } else if (rc != 0) {
3077                 CERROR("%s: revalidate FID "DFID" error: rc = %d\n",
3078                        ll_get_fsname(inode->i_sb, NULL, 0),
3079                        PFID(ll_inode2fid(inode)), rc);
3080         }
3081
3082         return rc;
3083 }
3084
3085 int __ll_inode_revalidate_it(struct dentry *dentry, struct lookup_intent *it,
3086                              __u64 ibits)
3087 {
3088         struct inode *inode = dentry->d_inode;
3089         struct ptlrpc_request *req = NULL;
3090         struct obd_export *exp;
3091         int rc = 0;
3092         ENTRY;
3093
3094         LASSERT(inode != NULL);
3095
3096         CDEBUG(D_VFSTRACE, "VFS Op:inode="DFID"(%p),name=%s\n",
3097                PFID(ll_inode2fid(inode)), inode, dentry->d_name.name);
3098
3099         exp = ll_i2mdexp(inode);
3100
3101         /* XXX: Enable OBD_CONNECT_ATTRFID to reduce unnecessary getattr RPC.
3102          *      But under CMD case, it caused some lock issues, should be fixed
3103          *      with new CMD ibits lock. See bug 12718 */
3104         if (exp_connect_flags(exp) & OBD_CONNECT_ATTRFID) {
3105                 struct lookup_intent oit = { .it_op = IT_GETATTR };
3106                 struct md_op_data *op_data;
3107
3108                 if (ibits == MDS_INODELOCK_LOOKUP)
3109                         oit.it_op = IT_LOOKUP;
3110
3111                 /* Call getattr by fid, so do not provide name at all. */
3112                 op_data = ll_prep_md_op_data(NULL, dentry->d_inode,
3113                                              dentry->d_inode, NULL, 0, 0,
3114                                              LUSTRE_OPC_ANY, NULL);
3115                 if (IS_ERR(op_data))
3116                         RETURN(PTR_ERR(op_data));
3117
3118                 oit.it_create_mode |= M_CHECK_STALE;
3119                 rc = md_intent_lock(exp, op_data, NULL, 0,
3120                                     /* we are not interested in name
3121                                        based lookup */
3122                                     &oit, 0, &req,
3123                                     ll_md_blocking_ast, 0);
3124                 ll_finish_md_op_data(op_data);
3125                 oit.it_create_mode &= ~M_CHECK_STALE;
3126                 if (rc < 0) {
3127                         rc = ll_inode_revalidate_fini(inode, rc);
3128                         GOTO (out, rc);
3129                 }
3130
3131                 rc = ll_revalidate_it_finish(req, &oit, dentry);
3132                 if (rc != 0) {
3133                         ll_intent_release(&oit);
3134                         GOTO(out, rc);
3135                 }
3136
3137                 /* Unlinked? Unhash dentry, so it is not picked up later by
3138                    do_lookup() -> ll_revalidate_it(). We cannot use d_drop
3139                    here to preserve get_cwd functionality on 2.6.
3140                    Bug 10503 */
3141                 if (!dentry->d_inode->i_nlink)
3142                         d_lustre_invalidate(dentry, 0);
3143
3144                 ll_lookup_finish_locks(&oit, dentry);
3145         } else if (!ll_have_md_lock(dentry->d_inode, &ibits, LCK_MINMODE)) {
3146                 struct ll_sb_info *sbi = ll_i2sbi(dentry->d_inode);
3147                 obd_valid valid = OBD_MD_FLGETATTR;
3148                 struct md_op_data *op_data;
3149                 int ealen = 0;
3150
3151                 if (S_ISREG(inode->i_mode)) {
3152                         rc = ll_get_max_mdsize(sbi, &ealen);
3153                         if (rc)
3154                                 RETURN(rc);
3155                         valid |= OBD_MD_FLEASIZE | OBD_MD_FLMODEASIZE;
3156                 }
3157
3158                 op_data = ll_prep_md_op_data(NULL, inode, NULL, NULL,
3159                                              0, ealen, LUSTRE_OPC_ANY,
3160                                              NULL);
3161                 if (IS_ERR(op_data))
3162                         RETURN(PTR_ERR(op_data));
3163
3164                 op_data->op_valid = valid;
3165                 /* Once OBD_CONNECT_ATTRFID is not supported, we can't find one
3166                  * capa for this inode. Because we only keep capas of dirs
3167                  * fresh. */
3168                 rc = md_getattr(sbi->ll_md_exp, op_data, &req);
3169                 ll_finish_md_op_data(op_data);
3170                 if (rc) {
3171                         rc = ll_inode_revalidate_fini(inode, rc);
3172                         RETURN(rc);
3173                 }
3174
3175                 rc = ll_prep_inode(&inode, req, NULL, NULL);
3176         }
3177 out:
3178         ptlrpc_req_finished(req);
3179         return rc;
3180 }
3181
3182 int ll_inode_revalidate_it(struct dentry *dentry, struct lookup_intent *it,
3183                            __u64 ibits)
3184 {
3185         struct inode    *inode = dentry->d_inode;
3186         int              rc;
3187         ENTRY;
3188
3189         rc = __ll_inode_revalidate_it(dentry, it, ibits);
3190         if (rc != 0)
3191                 RETURN(rc);
3192
3193         /* if object isn't regular file, don't validate size */
3194         if (!S_ISREG(inode->i_mode)) {
3195                 LTIME_S(inode->i_atime) = ll_i2info(inode)->lli_lvb.lvb_atime;
3196                 LTIME_S(inode->i_mtime) = ll_i2info(inode)->lli_lvb.lvb_mtime;
3197                 LTIME_S(inode->i_ctime) = ll_i2info(inode)->lli_lvb.lvb_ctime;
3198         } else {
3199                 /* In case of restore, the MDT has the right size and has
3200                  * already send it back without granting the layout lock,
3201                  * inode is up-to-date so glimpse is useless.
3202                  * Also to glimpse we need the layout, in case of a running
3203                  * restore the MDT holds the layout lock so the glimpse will
3204                  * block up to the end of restore (getattr will block)
3205                  */
3206                 if (!(ll_i2info(inode)->lli_flags & LLIF_FILE_RESTORING))
3207                         rc = ll_glimpse_size(inode);
3208         }
3209         RETURN(rc);
3210 }
3211
3212 int ll_getattr_it(struct vfsmount *mnt, struct dentry *de,
3213                   struct lookup_intent *it, struct kstat *stat)
3214 {
3215         struct inode *inode = de->d_inode;
3216         struct ll_sb_info *sbi = ll_i2sbi(inode);
3217         struct ll_inode_info *lli = ll_i2info(inode);
3218         int res = 0;
3219
3220         res = ll_inode_revalidate_it(de, it, MDS_INODELOCK_UPDATE |
3221                                              MDS_INODELOCK_LOOKUP);
3222         ll_stats_ops_tally(sbi, LPROC_LL_GETATTR, 1);
3223
3224         if (res)
3225                 return res;
3226
3227         stat->dev = inode->i_sb->s_dev;
3228         if (ll_need_32bit_api(sbi))
3229                 stat->ino = cl_fid_build_ino(&lli->lli_fid, 1);
3230         else
3231                 stat->ino = inode->i_ino;
3232         stat->mode = inode->i_mode;
3233         stat->nlink = inode->i_nlink;
3234         stat->uid = inode->i_uid;
3235         stat->gid = inode->i_gid;
3236         stat->rdev = inode->i_rdev;
3237         stat->atime = inode->i_atime;
3238         stat->mtime = inode->i_mtime;
3239         stat->ctime = inode->i_ctime;
3240         stat->blksize = 1 << inode->i_blkbits;
3241
3242         stat->size = i_size_read(inode);
3243         stat->blocks = inode->i_blocks;
3244
3245         return 0;
3246 }
3247 int ll_getattr(struct vfsmount *mnt, struct dentry *de, struct kstat *stat)
3248 {
3249         struct lookup_intent it = { .it_op = IT_GETATTR };
3250
3251         return ll_getattr_it(mnt, de, &it, stat);
3252 }
3253
3254 int ll_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
3255                 __u64 start, __u64 len)
3256 {
3257         int rc;
3258         size_t num_bytes;
3259         struct ll_user_fiemap *fiemap;
3260         unsigned int extent_count = fieinfo->fi_extents_max;
3261
3262         num_bytes = sizeof(*fiemap) + (extent_count *
3263                                        sizeof(struct ll_fiemap_extent));
3264         OBD_ALLOC_LARGE(fiemap, num_bytes);
3265
3266         if (fiemap == NULL)
3267                 RETURN(-ENOMEM);
3268
3269         fiemap->fm_flags = fieinfo->fi_flags;
3270         fiemap->fm_extent_count = fieinfo->fi_extents_max;
3271         fiemap->fm_start = start;
3272         fiemap->fm_length = len;
3273         memcpy(&fiemap->fm_extents[0], fieinfo->fi_extents_start,
3274                sizeof(struct ll_fiemap_extent));
3275
3276         rc = ll_do_fiemap(inode, fiemap, num_bytes);
3277
3278         fieinfo->fi_flags = fiemap->fm_flags;
3279         fieinfo->fi_extents_mapped = fiemap->fm_mapped_extents;
3280         memcpy(fieinfo->fi_extents_start, &fiemap->fm_extents[0],
3281                fiemap->fm_mapped_extents * sizeof(struct ll_fiemap_extent));
3282
3283         OBD_FREE_LARGE(fiemap, num_bytes);
3284         return rc;
3285 }
3286
3287 struct posix_acl * ll_get_acl(struct inode *inode, int type)
3288 {
3289         struct ll_inode_info *lli = ll_i2info(inode);
3290         struct posix_acl *acl = NULL;
3291         ENTRY;
3292
3293         spin_lock(&lli->lli_lock);
3294         /* VFS' acl_permission_check->check_acl will release the refcount */
3295         acl = posix_acl_dup(lli->lli_posix_acl);
3296         spin_unlock(&lli->lli_lock);
3297
3298         RETURN(acl);
3299 }
3300
3301 #ifndef HAVE_GENERIC_PERMISSION_2ARGS
3302 static int
3303 # ifdef HAVE_GENERIC_PERMISSION_4ARGS
3304 ll_check_acl(struct inode *inode, int mask, unsigned int flags)
3305 # else
3306 ll_check_acl(struct inode *inode, int mask)
3307 # endif
3308 {
3309 # ifdef CONFIG_FS_POSIX_ACL
3310         struct posix_acl *acl;
3311         int rc;
3312         ENTRY;
3313
3314 #  ifdef HAVE_GENERIC_PERMISSION_4ARGS
3315         if (flags & IPERM_FLAG_RCU)
3316                 return -ECHILD;
3317 #  endif
3318         acl = ll_get_acl(inode, ACL_TYPE_ACCESS);
3319
3320         if (!acl)
3321                 RETURN(-EAGAIN);
3322
3323         rc = posix_acl_permission(inode, acl, mask);
3324         posix_acl_release(acl);
3325
3326         RETURN(rc);
3327 # else /* !CONFIG_FS_POSIX_ACL */
3328         return -EAGAIN;
3329 # endif /* CONFIG_FS_POSIX_ACL */
3330 }
3331 #endif /* HAVE_GENERIC_PERMISSION_2ARGS */
3332
3333 #ifdef HAVE_GENERIC_PERMISSION_4ARGS
3334 int ll_inode_permission(struct inode *inode, int mask, unsigned int flags)
3335 #else
3336 # ifdef HAVE_INODE_PERMISION_2ARGS
3337 int ll_inode_permission(struct inode *inode, int mask)
3338 # else
3339 int ll_inode_permission(struct inode *inode, int mask, struct nameidata *nd)
3340 # endif
3341 #endif
3342 {
3343         int rc = 0;
3344         ENTRY;
3345
3346 #ifdef MAY_NOT_BLOCK
3347         if (mask & MAY_NOT_BLOCK)
3348                 return -ECHILD;
3349 #elif defined(HAVE_GENERIC_PERMISSION_4ARGS)
3350         if (flags & IPERM_FLAG_RCU)
3351                 return -ECHILD;
3352 #endif
3353
3354        /* as root inode are NOT getting validated in lookup operation,
3355         * need to do it before permission check. */
3356
3357         if (inode == inode->i_sb->s_root->d_inode) {
3358                 struct lookup_intent it = { .it_op = IT_LOOKUP };
3359
3360                 rc = __ll_inode_revalidate_it(inode->i_sb->s_root, &it,
3361                                               MDS_INODELOCK_LOOKUP);
3362                 if (rc)
3363                         RETURN(rc);
3364         }
3365
3366         CDEBUG(D_VFSTRACE, "VFS Op:inode="DFID"(%p), inode mode %x mask %o\n",
3367                PFID(ll_inode2fid(inode)), inode, inode->i_mode, mask);
3368
3369         if (ll_i2sbi(inode)->ll_flags & LL_SBI_RMT_CLIENT)
3370                 return lustre_check_remote_perm(inode, mask);
3371
3372         ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_INODE_PERM, 1);
3373         rc = ll_generic_permission(inode, mask, flags, ll_check_acl);
3374
3375         RETURN(rc);
3376 }
3377
3378 /* -o localflock - only provides locally consistent flock locks */
3379 struct file_operations ll_file_operations = {
3380         .read           = ll_file_read,
3381         .aio_read    = ll_file_aio_read,
3382         .write          = ll_file_write,
3383         .aio_write   = ll_file_aio_write,
3384         .unlocked_ioctl = ll_file_ioctl,
3385         .open           = ll_file_open,
3386         .release        = ll_file_release,
3387         .mmap           = ll_file_mmap,
3388         .llseek         = ll_file_seek,
3389         .splice_read    = ll_file_splice_read,
3390         .fsync          = ll_fsync,
3391         .flush          = ll_flush
3392 };
3393
3394 struct file_operations ll_file_operations_flock = {
3395         .read           = ll_file_read,
3396         .aio_read    = ll_file_aio_read,
3397         .write          = ll_file_write,
3398         .aio_write   = ll_file_aio_write,
3399         .unlocked_ioctl = ll_file_ioctl,
3400         .open           = ll_file_open,
3401         .release        = ll_file_release,
3402         .mmap           = ll_file_mmap,
3403         .llseek         = ll_file_seek,
3404         .splice_read    = ll_file_splice_read,
3405         .fsync          = ll_fsync,
3406         .flush          = ll_flush,
3407         .flock          = ll_file_flock,
3408         .lock           = ll_file_flock
3409 };
3410
3411 /* These are for -o noflock - to return ENOSYS on flock calls */
3412 struct file_operations ll_file_operations_noflock = {
3413         .read           = ll_file_read,
3414         .aio_read    = ll_file_aio_read,
3415         .write          = ll_file_write,
3416         .aio_write   = ll_file_aio_write,
3417         .unlocked_ioctl = ll_file_ioctl,
3418         .open           = ll_file_open,
3419         .release        = ll_file_release,
3420         .mmap           = ll_file_mmap,
3421         .llseek         = ll_file_seek,
3422         .splice_read    = ll_file_splice_read,
3423         .fsync          = ll_fsync,
3424         .flush          = ll_flush,
3425         .flock          = ll_file_noflock,
3426         .lock           = ll_file_noflock
3427 };
3428
3429 struct inode_operations ll_file_inode_operations = {
3430         .setattr        = ll_setattr,
3431         .getattr        = ll_getattr,
3432         .permission     = ll_inode_permission,
3433         .setxattr       = ll_setxattr,
3434         .getxattr       = ll_getxattr,
3435         .listxattr      = ll_listxattr,
3436         .removexattr    = ll_removexattr,
3437         .fiemap         = ll_fiemap,
3438 #ifdef HAVE_IOP_GET_ACL
3439         .get_acl        = ll_get_acl,
3440 #endif
3441 };
3442
3443 /* dynamic ioctl number support routins */
3444 static struct llioc_ctl_data {
3445         struct rw_semaphore     ioc_sem;
3446         cfs_list_t              ioc_head;
3447 } llioc = {
3448         __RWSEM_INITIALIZER(llioc.ioc_sem),
3449         CFS_LIST_HEAD_INIT(llioc.ioc_head)
3450 };
3451
3452
3453 struct llioc_data {
3454         cfs_list_t              iocd_list;
3455         unsigned int            iocd_size;
3456         llioc_callback_t        iocd_cb;
3457         unsigned int            iocd_count;
3458         unsigned int            iocd_cmd[0];
3459 };
3460
3461 void *ll_iocontrol_register(llioc_callback_t cb, int count, unsigned int *cmd)
3462 {
3463         unsigned int size;
3464         struct llioc_data *in_data = NULL;
3465         ENTRY;
3466
3467         if (cb == NULL || cmd == NULL ||
3468             count > LLIOC_MAX_CMD || count < 0)
3469                 RETURN(NULL);
3470
3471         size = sizeof(*in_data) + count * sizeof(unsigned int);
3472         OBD_ALLOC(in_data, size);
3473         if (in_data == NULL)
3474                 RETURN(NULL);
3475
3476         memset(in_data, 0, sizeof(*in_data));
3477         in_data->iocd_size = size;
3478         in_data->iocd_cb = cb;
3479         in_data->iocd_count = count;
3480         memcpy(in_data->iocd_cmd, cmd, sizeof(unsigned int) * count);
3481
3482         down_write(&llioc.ioc_sem);
3483         cfs_list_add_tail(&in_data->iocd_list, &llioc.ioc_head);
3484         up_write(&llioc.ioc_sem);
3485
3486         RETURN(in_data);
3487 }
3488
3489 void ll_iocontrol_unregister(void *magic)
3490 {
3491         struct llioc_data *tmp;
3492
3493         if (magic == NULL)
3494                 return;
3495
3496         down_write(&llioc.ioc_sem);
3497         cfs_list_for_each_entry(tmp, &llioc.ioc_head, iocd_list) {
3498                 if (tmp == magic) {
3499                         unsigned int size = tmp->iocd_size;
3500
3501                         cfs_list_del(&tmp->iocd_list);
3502                         up_write(&llioc.ioc_sem);
3503
3504                         OBD_FREE(tmp, size);
3505                         return;
3506                 }
3507         }
3508         up_write(&llioc.ioc_sem);
3509
3510         CWARN("didn't find iocontrol register block with magic: %p\n", magic);
3511 }
3512
3513 EXPORT_SYMBOL(ll_iocontrol_register);
3514 EXPORT_SYMBOL(ll_iocontrol_unregister);
3515
3516 enum llioc_iter ll_iocontrol_call(struct inode *inode, struct file *file,
3517                         unsigned int cmd, unsigned long arg, int *rcp)
3518 {
3519         enum llioc_iter ret = LLIOC_CONT;
3520         struct llioc_data *data;
3521         int rc = -EINVAL, i;
3522
3523         down_read(&llioc.ioc_sem);
3524         cfs_list_for_each_entry(data, &llioc.ioc_head, iocd_list) {
3525                 for (i = 0; i < data->iocd_count; i++) {
3526                         if (cmd != data->iocd_cmd[i])
3527                                 continue;
3528
3529                         ret = data->iocd_cb(inode, file, cmd, arg, data, &rc);
3530                         break;
3531                 }
3532
3533                 if (ret == LLIOC_STOP)
3534                         break;
3535         }
3536         up_read(&llioc.ioc_sem);
3537
3538         if (rcp)
3539                 *rcp = rc;
3540         return ret;
3541 }
3542
3543 int ll_layout_conf(struct inode *inode, const struct cl_object_conf *conf)
3544 {
3545         struct ll_inode_info *lli = ll_i2info(inode);
3546         struct cl_env_nest nest;
3547         struct lu_env *env;
3548         int result;
3549         ENTRY;
3550
3551         if (lli->lli_clob == NULL)
3552                 RETURN(0);
3553
3554         env = cl_env_nested_get(&nest);
3555         if (IS_ERR(env))
3556                 RETURN(PTR_ERR(env));
3557
3558         result = cl_conf_set(env, lli->lli_clob, conf);
3559         cl_env_nested_put(&nest, env);
3560
3561         if (conf->coc_opc == OBJECT_CONF_SET) {
3562                 struct ldlm_lock *lock = conf->coc_lock;
3563
3564                 LASSERT(lock != NULL);
3565                 LASSERT(ldlm_has_layout(lock));
3566                 if (result == 0) {
3567                         /* it can only be allowed to match after layout is
3568                          * applied to inode otherwise false layout would be
3569                          * seen. Applying layout shoud happen before dropping
3570                          * the intent lock. */
3571                         ldlm_lock_allow_match(lock);
3572                 }
3573         }
3574         RETURN(result);
3575 }
3576
3577 /* Fetch layout from MDT with getxattr request, if it's not ready yet */
3578 static int ll_layout_fetch(struct inode *inode, struct ldlm_lock *lock)
3579
3580 {
3581         struct ll_sb_info *sbi = ll_i2sbi(inode);
3582         struct obd_capa *oc;
3583         struct ptlrpc_request *req;
3584         struct mdt_body *body;
3585         void *lvbdata;
3586         void *lmm;
3587         int lmmsize;
3588         int rc;
3589         ENTRY;
3590
3591         CDEBUG(D_INODE, DFID" LVB_READY=%d l_lvb_data=%p l_lvb_len=%d\n",
3592                PFID(ll_inode2fid(inode)), ldlm_is_lvb_ready(lock),
3593                lock->l_lvb_data, lock->l_lvb_len);
3594
3595         if ((lock->l_lvb_data != NULL) && ldlm_is_lvb_ready(lock))
3596                 RETURN(0);
3597
3598         /* if layout lock was granted right away, the layout is returned
3599          * within DLM_LVB of dlm reply; otherwise if the lock was ever
3600          * blocked and then granted via completion ast, we have to fetch
3601          * layout here. Please note that we can't use the LVB buffer in
3602          * completion AST because it doesn't have a large enough buffer */
3603         oc = ll_mdscapa_get(inode);
3604         rc = ll_get_max_mdsize(sbi, &lmmsize);
3605         if (rc == 0)
3606                 rc = md_getxattr(sbi->ll_md_exp, ll_inode2fid(inode), oc,
3607                                 OBD_MD_FLXATTR, XATTR_NAME_LOV, NULL, 0,
3608                                 lmmsize, 0, &req);
3609         capa_put(oc);
3610         if (rc < 0)
3611                 RETURN(rc);
3612
3613         body = req_capsule_server_get(&req->rq_pill, &RMF_MDT_BODY);
3614         if (body == NULL || body->eadatasize > lmmsize)
3615                 GOTO(out, rc = -EPROTO);
3616
3617         lmmsize = body->eadatasize;
3618         if (lmmsize == 0) /* empty layout */
3619                 GOTO(out, rc = 0);
3620
3621         lmm = req_capsule_server_sized_get(&req->rq_pill, &RMF_EADATA, lmmsize);
3622         if (lmm == NULL)
3623                 GOTO(out, rc = -EFAULT);
3624
3625         OBD_ALLOC_LARGE(lvbdata, lmmsize);
3626         if (lvbdata == NULL)
3627                 GOTO(out, rc = -ENOMEM);
3628
3629         memcpy(lvbdata, lmm, lmmsize);
3630         lock_res_and_lock(lock);
3631         if (lock->l_lvb_data != NULL)
3632                 OBD_FREE_LARGE(lock->l_lvb_data, lock->l_lvb_len);
3633
3634         lock->l_lvb_data = lvbdata;
3635         lock->l_lvb_len = lmmsize;
3636         unlock_res_and_lock(lock);
3637
3638         EXIT;
3639
3640 out:
3641         ptlrpc_req_finished(req);
3642         return rc;
3643 }
3644
3645 /**
3646  * Apply the layout to the inode. Layout lock is held and will be released
3647  * in this function.
3648  */
3649 static int ll_layout_lock_set(struct lustre_handle *lockh, ldlm_mode_t mode,
3650                                 struct inode *inode, __u32 *gen, bool reconf)
3651 {
3652         struct ll_inode_info *lli = ll_i2info(inode);
3653         struct ll_sb_info    *sbi = ll_i2sbi(inode);
3654         struct ldlm_lock *lock;
3655         struct lustre_md md = { NULL };
3656         struct cl_object_conf conf;
3657         int rc = 0;
3658         bool lvb_ready;
3659         bool wait_layout = false;
3660         ENTRY;
3661
3662         LASSERT(lustre_handle_is_used(lockh));
3663
3664         lock = ldlm_handle2lock(lockh);
3665         LASSERT(lock != NULL);
3666         LASSERT(ldlm_has_layout(lock));
3667
3668         LDLM_DEBUG(lock, "file "DFID"(%p) being reconfigured: %d\n",
3669                    PFID(&lli->lli_fid), inode, reconf);
3670
3671         /* in case this is a caching lock and reinstate with new inode */
3672         md_set_lock_data(sbi->ll_md_exp, &lockh->cookie, inode, NULL);
3673
3674         lock_res_and_lock(lock);
3675         lvb_ready = ldlm_is_lvb_ready(lock);
3676         unlock_res_and_lock(lock);
3677         /* checking lvb_ready is racy but this is okay. The worst case is
3678          * that multi processes may configure the file on the same time. */
3679
3680         if (lvb_ready || !reconf) {
3681                 rc = -ENODATA;
3682                 if (lvb_ready) {
3683                         /* layout_gen must be valid if layout lock is not
3684                          * cancelled and stripe has already set */
3685                         *gen = lli->lli_layout_gen;
3686                         rc = 0;
3687                 }
3688                 GOTO(out, rc);
3689         }
3690
3691         rc = ll_layout_fetch(inode, lock);
3692         if (rc < 0)
3693                 GOTO(out, rc);
3694
3695         /* for layout lock, lmm is returned in lock's lvb.
3696          * lvb_data is immutable if the lock is held so it's safe to access it
3697          * without res lock. See the description in ldlm_lock_decref_internal()
3698          * for the condition to free lvb_data of layout lock */
3699         if (lock->l_lvb_data != NULL) {
3700                 rc = obd_unpackmd(sbi->ll_dt_exp, &md.lsm,
3701                                   lock->l_lvb_data, lock->l_lvb_len);
3702                 if (rc >= 0) {
3703                         *gen = LL_LAYOUT_GEN_EMPTY;
3704                         if (md.lsm != NULL)
3705                                 *gen = md.lsm->lsm_layout_gen;
3706                         rc = 0;
3707                 } else {
3708                         CERROR("%s: file "DFID" unpackmd error: %d\n",
3709                                 ll_get_fsname(inode->i_sb, NULL, 0),
3710                                 PFID(&lli->lli_fid), rc);
3711                 }
3712         }
3713         if (rc < 0)
3714                 GOTO(out, rc);
3715
3716         /* set layout to file. Unlikely this will fail as old layout was
3717          * surely eliminated */
3718         memset(&conf, 0, sizeof conf);
3719         conf.coc_opc = OBJECT_CONF_SET;
3720         conf.coc_inode = inode;
3721         conf.coc_lock = lock;
3722         conf.u.coc_md = &md;
3723         rc = ll_layout_conf(inode, &conf);
3724
3725         if (md.lsm != NULL)
3726                 obd_free_memmd(sbi->ll_dt_exp, &md.lsm);
3727
3728         /* refresh layout failed, need to wait */
3729         wait_layout = rc == -EBUSY;
3730         EXIT;
3731
3732 out:
3733         LDLM_LOCK_PUT(lock);
3734         ldlm_lock_decref(lockh, mode);
3735
3736         /* wait for IO to complete if it's still being used. */
3737         if (wait_layout) {
3738                 CDEBUG(D_INODE, "%s: "DFID"(%p) wait for layout reconf\n",
3739                        ll_get_fsname(inode->i_sb, NULL, 0),
3740                        PFID(&lli->lli_fid), inode);
3741
3742                 memset(&conf, 0, sizeof conf);
3743                 conf.coc_opc = OBJECT_CONF_WAIT;
3744                 conf.coc_inode = inode;
3745                 rc = ll_layout_conf(inode, &conf);
3746                 if (rc == 0)
3747                         rc = -EAGAIN;
3748
3749                 CDEBUG(D_INODE, "%s file="DFID" waiting layout return: %d\n",
3750                        ll_get_fsname(inode->i_sb, NULL, 0),
3751                        PFID(&lli->lli_fid), rc);
3752         }
3753         RETURN(rc);
3754 }
3755
3756 /**
3757  * This function checks if there exists a LAYOUT lock on the client side,
3758  * or enqueues it if it doesn't have one in cache.
3759  *
3760  * This function will not hold layout lock so it may be revoked any time after
3761  * this function returns. Any operations depend on layout should be redone
3762  * in that case.
3763  *
3764  * This function should be called before lov_io_init() to get an uptodate
3765  * layout version, the caller should save the version number and after IO
3766  * is finished, this function should be called again to verify that layout
3767  * is not changed during IO time.
3768  */
3769 int ll_layout_refresh(struct inode *inode, __u32 *gen)
3770 {
3771         struct ll_inode_info  *lli = ll_i2info(inode);
3772         struct ll_sb_info     *sbi = ll_i2sbi(inode);
3773         struct md_op_data     *op_data;
3774         struct lookup_intent   it;
3775         struct lustre_handle   lockh;
3776         ldlm_mode_t            mode;
3777         struct ldlm_enqueue_info einfo = {
3778                 .ei_type = LDLM_IBITS,
3779                 .ei_mode = LCK_CR,
3780                 .ei_cb_bl = ll_md_blocking_ast,
3781                 .ei_cb_cp = ldlm_completion_ast,
3782         };
3783         int rc;
3784         ENTRY;
3785
3786         *gen = lli->lli_layout_gen;
3787         if (!(sbi->ll_flags & LL_SBI_LAYOUT_LOCK))
3788                 RETURN(0);
3789
3790         /* sanity checks */
3791         LASSERT(fid_is_sane(ll_inode2fid(inode)));
3792         LASSERT(S_ISREG(inode->i_mode));
3793
3794         /* mostly layout lock is caching on the local side, so try to match
3795          * it before grabbing layout lock mutex. */
3796         mode = ll_take_md_lock(inode, MDS_INODELOCK_LAYOUT, &lockh, 0,
3797                                LCK_CR | LCK_CW | LCK_PR | LCK_PW);
3798         if (mode != 0) { /* hit cached lock */
3799                 rc = ll_layout_lock_set(&lockh, mode, inode, gen, false);
3800                 if (rc == 0)
3801                         RETURN(0);
3802
3803                 /* better hold lli_layout_mutex to try again otherwise
3804                  * it will have starvation problem. */
3805         }
3806
3807         /* take layout lock mutex to enqueue layout lock exclusively. */
3808         mutex_lock(&lli->lli_layout_mutex);
3809
3810 again:
3811         /* try again. Maybe somebody else has done this. */
3812         mode = ll_take_md_lock(inode, MDS_INODELOCK_LAYOUT, &lockh, 0,
3813                                LCK_CR | LCK_CW | LCK_PR | LCK_PW);
3814         if (mode != 0) { /* hit cached lock */
3815                 rc = ll_layout_lock_set(&lockh, mode, inode, gen, true);
3816                 if (rc == -EAGAIN)
3817                         goto again;
3818
3819                 mutex_unlock(&lli->lli_layout_mutex);
3820                 RETURN(rc);
3821         }
3822
3823         op_data = ll_prep_md_op_data(NULL, inode, inode, NULL,
3824                                      0, 0, LUSTRE_OPC_ANY, NULL);
3825         if (IS_ERR(op_data)) {
3826                 mutex_unlock(&lli->lli_layout_mutex);
3827                 RETURN(PTR_ERR(op_data));
3828         }
3829
3830         /* have to enqueue one */
3831         memset(&it, 0, sizeof(it));
3832         it.it_op = IT_LAYOUT;
3833         lockh.cookie = 0ULL;
3834
3835         LDLM_DEBUG_NOLOCK("%s: requeue layout lock for file "DFID"(%p)\n",
3836                           ll_get_fsname(inode->i_sb, NULL, 0),
3837                           PFID(&lli->lli_fid), inode);
3838
3839         rc = md_enqueue(sbi->ll_md_exp, &einfo, &it, op_data, &lockh,
3840                         NULL, 0, NULL, 0);
3841         if (it.d.lustre.it_data != NULL)
3842                 ptlrpc_req_finished(it.d.lustre.it_data);
3843         it.d.lustre.it_data = NULL;
3844
3845         ll_finish_md_op_data(op_data);
3846
3847         mode = it.d.lustre.it_lock_mode;
3848         it.d.lustre.it_lock_mode = 0;
3849         ll_intent_drop_lock(&it);
3850
3851         if (rc == 0) {
3852                 /* set lock data in case this is a new lock */
3853                 ll_set_lock_data(sbi->ll_md_exp, inode, &it, NULL);
3854                 rc = ll_layout_lock_set(&lockh, mode, inode, gen, true);
3855                 if (rc == -EAGAIN)
3856                         goto again;
3857         }
3858         mutex_unlock(&lli->lli_layout_mutex);
3859
3860         RETURN(rc);
3861 }
3862
3863 /**
3864  *  This function send a restore request to the MDT
3865  */
3866 int ll_layout_restore(struct inode *inode, loff_t offset, __u64 length)
3867 {
3868         struct hsm_user_request *hur;
3869         int                      len, rc;
3870         ENTRY;
3871
3872         len = sizeof(struct hsm_user_request) +
3873               sizeof(struct hsm_user_item);
3874         OBD_ALLOC(hur, len);
3875         if (hur == NULL)
3876                 RETURN(-ENOMEM);
3877
3878         hur->hur_request.hr_action = HUA_RESTORE;
3879         hur->hur_request.hr_archive_id = 0;
3880         hur->hur_request.hr_flags = 0;
3881         memcpy(&hur->hur_user_item[0].hui_fid, &ll_i2info(inode)->lli_fid,
3882                sizeof(hur->hur_user_item[0].hui_fid));
3883         hur->hur_user_item[0].hui_extent.offset = offset;
3884         hur->hur_user_item[0].hui_extent.length = length;
3885         hur->hur_request.hr_itemcount = 1;
3886         rc = obd_iocontrol(LL_IOC_HSM_REQUEST, cl_i2sbi(inode)->ll_md_exp,
3887                            len, hur, NULL);
3888         OBD_FREE(hur, len);
3889         RETURN(rc);
3890 }
3891