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