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