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