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