Whamcloud - gitweb
626615f271d97ef516305f5f0592791571e61e68
[fs/lustre-release.git] / lustre / llite / file.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.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, 2017, 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 <lustre_dlm.h>
41 #include <linux/pagemap.h>
42 #include <linux/file.h>
43 #include <linux/sched.h>
44 #include <linux/user_namespace.h>
45 #ifdef HAVE_UIDGID_HEADER
46 # include <linux/uidgid.h>
47 #endif
48
49 #include <uapi/linux/lustre/lustre_ioctl.h>
50 #include <lustre_swab.h>
51
52 #include "cl_object.h"
53 #include "llite_internal.h"
54 #include "vvp_internal.h"
55
56 static int
57 ll_put_grouplock(struct inode *inode, struct file *file, unsigned long arg);
58
59 static int ll_lease_close(struct obd_client_handle *och, struct inode *inode,
60                           bool *lease_broken);
61
62 static struct ll_file_data *ll_file_data_get(void)
63 {
64         struct ll_file_data *fd;
65
66         OBD_SLAB_ALLOC_PTR_GFP(fd, ll_file_data_slab, GFP_NOFS);
67         if (fd == NULL)
68                 return NULL;
69
70         fd->fd_write_failed = false;
71
72         return fd;
73 }
74
75 static void ll_file_data_put(struct ll_file_data *fd)
76 {
77         if (fd != NULL)
78                 OBD_SLAB_FREE_PTR(fd, ll_file_data_slab);
79 }
80
81 /**
82  * Packs all the attributes into @op_data for the CLOSE rpc.
83  */
84 static void ll_prepare_close(struct inode *inode, struct md_op_data *op_data,
85                              struct obd_client_handle *och)
86 {
87         ENTRY;
88
89         ll_prep_md_op_data(op_data, inode, NULL, NULL,
90                            0, 0, LUSTRE_OPC_ANY, NULL);
91
92         op_data->op_attr.ia_mode = inode->i_mode;
93         op_data->op_attr.ia_atime = inode->i_atime;
94         op_data->op_attr.ia_mtime = inode->i_mtime;
95         op_data->op_attr.ia_ctime = inode->i_ctime;
96         op_data->op_attr.ia_size = i_size_read(inode);
97         op_data->op_attr.ia_valid |= ATTR_MODE | ATTR_ATIME | ATTR_ATIME_SET |
98                                      ATTR_MTIME | ATTR_MTIME_SET |
99                                      ATTR_CTIME | ATTR_CTIME_SET;
100         op_data->op_attr_blocks = inode->i_blocks;
101         op_data->op_attr_flags = ll_inode_to_ext_flags(inode->i_flags);
102         op_data->op_handle = och->och_fh;
103
104         if (och->och_flags & FMODE_WRITE &&
105             ll_file_test_and_clear_flag(ll_i2info(inode), LLIF_DATA_MODIFIED))
106                 /* For HSM: if inode data has been modified, pack it so that
107                  * MDT can set data dirty flag in the archive. */
108                 op_data->op_bias |= MDS_DATA_MODIFIED;
109
110         EXIT;
111 }
112
113 /**
114  * Perform a close, possibly with a bias.
115  * The meaning of "data" depends on the value of "bias".
116  *
117  * If \a bias is MDS_HSM_RELEASE then \a data is a pointer to the data version.
118  * If \a bias is MDS_CLOSE_LAYOUT_SWAP then \a data is a pointer to the inode to
119  * swap layouts with.
120  */
121 static int ll_close_inode_openhandle(struct inode *inode,
122                                      struct obd_client_handle *och,
123                                      enum mds_op_bias bias, void *data)
124 {
125         struct obd_export *md_exp = ll_i2mdexp(inode);
126         const struct ll_inode_info *lli = ll_i2info(inode);
127         struct md_op_data *op_data;
128         struct ptlrpc_request *req = NULL;
129         int rc;
130         ENTRY;
131
132         if (class_exp2obd(md_exp) == NULL) {
133                 CERROR("%s: invalid MDC connection handle closing "DFID"\n",
134                        ll_get_fsname(inode->i_sb, NULL, 0),
135                        PFID(&lli->lli_fid));
136                 GOTO(out, rc = 0);
137         }
138
139         OBD_ALLOC_PTR(op_data);
140         /* We leak openhandle and request here on error, but not much to be
141          * done in OOM case since app won't retry close on error either. */
142         if (op_data == NULL)
143                 GOTO(out, rc = -ENOMEM);
144
145         ll_prepare_close(inode, op_data, och);
146         switch (bias) {
147         case MDS_CLOSE_LAYOUT_MERGE:
148                 /* merge blocks from the victim inode */
149                 op_data->op_attr_blocks += ((struct inode *)data)->i_blocks;
150                 op_data->op_attr.ia_valid |= ATTR_SIZE | ATTR_BLOCKS;
151         case MDS_CLOSE_LAYOUT_SWAP:
152                 LASSERT(data != NULL);
153                 op_data->op_bias |= bias;
154                 op_data->op_data_version = 0;
155                 op_data->op_lease_handle = och->och_lease_handle;
156                 op_data->op_fid2 = *ll_inode2fid(data);
157                 break;
158
159         case MDS_CLOSE_RESYNC_DONE: {
160                 struct ll_ioc_lease *ioc = data;
161
162                 LASSERT(data != NULL);
163                 op_data->op_attr_blocks +=
164                         ioc->lil_count * op_data->op_attr_blocks;
165                 op_data->op_attr.ia_valid |= ATTR_SIZE | ATTR_BLOCKS;
166                 op_data->op_bias |= MDS_CLOSE_RESYNC_DONE;
167
168                 op_data->op_lease_handle = och->och_lease_handle;
169                 op_data->op_data = &ioc->lil_ids[0];
170                 op_data->op_data_size =
171                         ioc->lil_count * sizeof(ioc->lil_ids[0]);
172                 break;
173         }
174
175         case MDS_HSM_RELEASE:
176                 LASSERT(data != NULL);
177                 op_data->op_bias |= MDS_HSM_RELEASE;
178                 op_data->op_data_version = *(__u64 *)data;
179                 op_data->op_lease_handle = och->och_lease_handle;
180                 op_data->op_attr.ia_valid |= ATTR_SIZE | ATTR_BLOCKS;
181                 break;
182
183         default:
184                 LASSERT(data == NULL);
185                 break;
186         }
187
188         rc = md_close(md_exp, op_data, och->och_mod, &req);
189         if (rc != 0 && rc != -EINTR)
190                 CERROR("%s: inode "DFID" mdc close failed: rc = %d\n",
191                        md_exp->exp_obd->obd_name, PFID(&lli->lli_fid), rc);
192
193         if (rc == 0 && op_data->op_bias & bias) {
194                 struct mdt_body *body;
195
196                 body = req_capsule_server_get(&req->rq_pill, &RMF_MDT_BODY);
197                 if (!(body->mbo_valid & OBD_MD_CLOSE_INTENT_EXECED))
198                         rc = -EBUSY;
199         }
200
201         ll_finish_md_op_data(op_data);
202         EXIT;
203 out:
204
205         md_clear_open_replay_data(md_exp, och);
206         och->och_fh.cookie = DEAD_HANDLE_MAGIC;
207         OBD_FREE_PTR(och);
208
209         ptlrpc_req_finished(req);       /* This is close request */
210         return rc;
211 }
212
213 int ll_md_real_close(struct inode *inode, fmode_t fmode)
214 {
215         struct ll_inode_info *lli = ll_i2info(inode);
216         struct obd_client_handle **och_p;
217         struct obd_client_handle *och;
218         __u64 *och_usecount;
219         int rc = 0;
220         ENTRY;
221
222         if (fmode & FMODE_WRITE) {
223                 och_p = &lli->lli_mds_write_och;
224                 och_usecount = &lli->lli_open_fd_write_count;
225         } else if (fmode & FMODE_EXEC) {
226                 och_p = &lli->lli_mds_exec_och;
227                 och_usecount = &lli->lli_open_fd_exec_count;
228         } else {
229                 LASSERT(fmode & FMODE_READ);
230                 och_p = &lli->lli_mds_read_och;
231                 och_usecount = &lli->lli_open_fd_read_count;
232         }
233
234         mutex_lock(&lli->lli_och_mutex);
235         if (*och_usecount > 0) {
236                 /* There are still users of this handle, so skip
237                  * freeing it. */
238                 mutex_unlock(&lli->lli_och_mutex);
239                 RETURN(0);
240         }
241
242         och = *och_p;
243         *och_p = NULL;
244         mutex_unlock(&lli->lli_och_mutex);
245
246         if (och != NULL) {
247                 /* There might be a race and this handle may already
248                  * be closed. */
249                 rc = ll_close_inode_openhandle(inode, och, 0, NULL);
250         }
251
252         RETURN(rc);
253 }
254
255 static int ll_md_close(struct inode *inode, struct file *file)
256 {
257         union ldlm_policy_data policy = {
258                 .l_inodebits    = { MDS_INODELOCK_OPEN },
259         };
260         __u64 flags = LDLM_FL_BLOCK_GRANTED | LDLM_FL_TEST_LOCK;
261         struct ll_file_data *fd = LUSTRE_FPRIVATE(file);
262         struct ll_inode_info *lli = ll_i2info(inode);
263         struct lustre_handle lockh;
264         enum ldlm_mode lockmode;
265         int rc = 0;
266         ENTRY;
267
268         /* clear group lock, if present */
269         if (unlikely(fd->fd_flags & LL_FILE_GROUP_LOCKED))
270                 ll_put_grouplock(inode, file, fd->fd_grouplock.lg_gid);
271
272         if (fd->fd_lease_och != NULL) {
273                 bool lease_broken;
274
275                 /* Usually the lease is not released when the
276                  * application crashed, we need to release here. */
277                 rc = ll_lease_close(fd->fd_lease_och, inode, &lease_broken);
278                 CDEBUG(rc ? D_ERROR : D_INODE, "Clean up lease "DFID" %d/%d\n",
279                         PFID(&lli->lli_fid), rc, lease_broken);
280
281                 fd->fd_lease_och = NULL;
282         }
283
284         if (fd->fd_och != NULL) {
285                 rc = ll_close_inode_openhandle(inode, fd->fd_och, 0, NULL);
286                 fd->fd_och = NULL;
287                 GOTO(out, rc);
288         }
289
290         /* Let's see if we have good enough OPEN lock on the file and if
291            we can skip talking to MDS */
292         mutex_lock(&lli->lli_och_mutex);
293         if (fd->fd_omode & FMODE_WRITE) {
294                 lockmode = LCK_CW;
295                 LASSERT(lli->lli_open_fd_write_count);
296                 lli->lli_open_fd_write_count--;
297         } else if (fd->fd_omode & FMODE_EXEC) {
298                 lockmode = LCK_PR;
299                 LASSERT(lli->lli_open_fd_exec_count);
300                 lli->lli_open_fd_exec_count--;
301         } else {
302                 lockmode = LCK_CR;
303                 LASSERT(lli->lli_open_fd_read_count);
304                 lli->lli_open_fd_read_count--;
305         }
306         mutex_unlock(&lli->lli_och_mutex);
307
308         if (!md_lock_match(ll_i2mdexp(inode), flags, ll_inode2fid(inode),
309                            LDLM_IBITS, &policy, lockmode, &lockh))
310                 rc = ll_md_real_close(inode, fd->fd_omode);
311
312 out:
313         LUSTRE_FPRIVATE(file) = NULL;
314         ll_file_data_put(fd);
315
316         RETURN(rc);
317 }
318
319 /* While this returns an error code, fput() the caller does not, so we need
320  * to make every effort to clean up all of our state here.  Also, applications
321  * rarely check close errors and even if an error is returned they will not
322  * re-try the close call.
323  */
324 int ll_file_release(struct inode *inode, struct file *file)
325 {
326         struct ll_file_data *fd;
327         struct ll_sb_info *sbi = ll_i2sbi(inode);
328         struct ll_inode_info *lli = ll_i2info(inode);
329         int rc;
330         ENTRY;
331
332         CDEBUG(D_VFSTRACE, "VFS Op:inode="DFID"(%p)\n",
333                PFID(ll_inode2fid(inode)), inode);
334
335         if (inode->i_sb->s_root != file_dentry(file))
336                 ll_stats_ops_tally(sbi, LPROC_LL_RELEASE, 1);
337         fd = LUSTRE_FPRIVATE(file);
338         LASSERT(fd != NULL);
339
340         /* The last ref on @file, maybe not the the owner pid of statahead,
341          * because parent and child process can share the same file handle. */
342         if (S_ISDIR(inode->i_mode) && lli->lli_opendir_key == fd)
343                 ll_deauthorize_statahead(inode, fd);
344
345         if (inode->i_sb->s_root == file_dentry(file)) {
346                 LUSTRE_FPRIVATE(file) = NULL;
347                 ll_file_data_put(fd);
348                 RETURN(0);
349         }
350
351         if (!S_ISDIR(inode->i_mode)) {
352                 if (lli->lli_clob != NULL)
353                         lov_read_and_clear_async_rc(lli->lli_clob);
354                 lli->lli_async_rc = 0;
355         }
356
357         rc = ll_md_close(inode, file);
358
359         if (CFS_FAIL_TIMEOUT_MS(OBD_FAIL_PTLRPC_DUMP_LOG, cfs_fail_val))
360                 libcfs_debug_dumplog();
361
362         RETURN(rc);
363 }
364
365 static int ll_intent_file_open(struct dentry *de, void *lmm, int lmmsize,
366                                 struct lookup_intent *itp)
367 {
368         struct ll_sb_info *sbi = ll_i2sbi(de->d_inode);
369         struct dentry *parent = de->d_parent;
370         const char *name = NULL;
371         int len = 0;
372         struct md_op_data *op_data;
373         struct ptlrpc_request *req = NULL;
374         int rc;
375         ENTRY;
376
377         LASSERT(parent != NULL);
378         LASSERT(itp->it_flags & MDS_OPEN_BY_FID);
379
380         /* if server supports open-by-fid, or file name is invalid, don't pack
381          * name in open request */
382         if (!(exp_connect_flags(sbi->ll_md_exp) & OBD_CONNECT_OPEN_BY_FID) &&
383             lu_name_is_valid_2(de->d_name.name, de->d_name.len)) {
384                 name = de->d_name.name;
385                 len = de->d_name.len;
386         }
387
388         op_data = ll_prep_md_op_data(NULL, parent->d_inode, de->d_inode,
389                                      name, len, 0, LUSTRE_OPC_ANY, NULL);
390         if (IS_ERR(op_data))
391                 RETURN(PTR_ERR(op_data));
392         op_data->op_data = lmm;
393         op_data->op_data_size = lmmsize;
394
395         rc = md_intent_lock(sbi->ll_md_exp, op_data, itp, &req,
396                             &ll_md_blocking_ast, 0);
397         ll_finish_md_op_data(op_data);
398         if (rc == -ESTALE) {
399                 /* reason for keep own exit path - don`t flood log
400                  * with messages with -ESTALE errors.
401                  */
402                 if (!it_disposition(itp, DISP_OPEN_OPEN) ||
403                      it_open_error(DISP_OPEN_OPEN, itp))
404                         GOTO(out, rc);
405                 ll_release_openhandle(de, itp);
406                 GOTO(out, rc);
407         }
408
409         if (it_disposition(itp, DISP_LOOKUP_NEG))
410                 GOTO(out, rc = -ENOENT);
411
412         if (rc != 0 || it_open_error(DISP_OPEN_OPEN, itp)) {
413                 rc = rc ? rc : it_open_error(DISP_OPEN_OPEN, itp);
414                 CDEBUG(D_VFSTRACE, "lock enqueue: err: %d\n", rc);
415                 GOTO(out, rc);
416         }
417
418         rc = ll_prep_inode(&de->d_inode, req, NULL, itp);
419         if (!rc && itp->it_lock_mode)
420                 ll_set_lock_data(sbi->ll_md_exp, de->d_inode, itp, NULL);
421
422 out:
423         ptlrpc_req_finished(req);
424         ll_intent_drop_lock(itp);
425
426         /* We did open by fid, but by the time we got to the server,
427          * the object disappeared. If this is a create, we cannot really
428          * tell the userspace that the file it was trying to create
429          * does not exist. Instead let's return -ESTALE, and the VFS will
430          * retry the create with LOOKUP_REVAL that we are going to catch
431          * in ll_revalidate_dentry() and use lookup then.
432          */
433         if (rc == -ENOENT && itp->it_op & IT_CREAT)
434                 rc = -ESTALE;
435
436         RETURN(rc);
437 }
438
439 static int ll_och_fill(struct obd_export *md_exp, struct lookup_intent *it,
440                        struct obd_client_handle *och)
441 {
442         struct mdt_body *body;
443
444         body = req_capsule_server_get(&it->it_request->rq_pill, &RMF_MDT_BODY);
445         och->och_fh = body->mbo_handle;
446         och->och_fid = body->mbo_fid1;
447         och->och_lease_handle.cookie = it->it_lock_handle;
448         och->och_magic = OBD_CLIENT_HANDLE_MAGIC;
449         och->och_flags = it->it_flags;
450
451         return md_set_open_replay_data(md_exp, och, it);
452 }
453
454 static int ll_local_open(struct file *file, struct lookup_intent *it,
455                          struct ll_file_data *fd, struct obd_client_handle *och)
456 {
457         struct inode *inode = file_inode(file);
458         ENTRY;
459
460         LASSERT(!LUSTRE_FPRIVATE(file));
461
462         LASSERT(fd != NULL);
463
464         if (och) {
465                 int rc;
466
467                 rc = ll_och_fill(ll_i2sbi(inode)->ll_md_exp, it, och);
468                 if (rc != 0)
469                         RETURN(rc);
470         }
471
472         LUSTRE_FPRIVATE(file) = fd;
473         ll_readahead_init(inode, &fd->fd_ras);
474         fd->fd_omode = it->it_flags & (FMODE_READ | FMODE_WRITE | FMODE_EXEC);
475
476         /* ll_cl_context initialize */
477         rwlock_init(&fd->fd_lock);
478         INIT_LIST_HEAD(&fd->fd_lccs);
479
480         RETURN(0);
481 }
482
483 /* Open a file, and (for the very first open) create objects on the OSTs at
484  * this time.  If opened with O_LOV_DELAY_CREATE, then we don't do the object
485  * creation or open until ll_lov_setstripe() ioctl is called.
486  *
487  * If we already have the stripe MD locally then we don't request it in
488  * md_open(), by passing a lmm_size = 0.
489  *
490  * It is up to the application to ensure no other processes open this file
491  * in the O_LOV_DELAY_CREATE case, or the default striping pattern will be
492  * used.  We might be able to avoid races of that sort by getting lli_open_sem
493  * before returning in the O_LOV_DELAY_CREATE case and dropping it here
494  * or in ll_file_release(), but I'm not sure that is desirable/necessary.
495  */
496 int ll_file_open(struct inode *inode, struct file *file)
497 {
498         struct ll_inode_info *lli = ll_i2info(inode);
499         struct lookup_intent *it, oit = { .it_op = IT_OPEN,
500                                           .it_flags = file->f_flags };
501         struct obd_client_handle **och_p = NULL;
502         __u64 *och_usecount = NULL;
503         struct ll_file_data *fd;
504         int rc = 0;
505         ENTRY;
506
507         CDEBUG(D_VFSTRACE, "VFS Op:inode="DFID"(%p), flags %o\n",
508                PFID(ll_inode2fid(inode)), inode, file->f_flags);
509
510         it = file->private_data; /* XXX: compat macro */
511         file->private_data = NULL; /* prevent ll_local_open assertion */
512
513         fd = ll_file_data_get();
514         if (fd == NULL)
515                 GOTO(out_openerr, rc = -ENOMEM);
516
517         fd->fd_file = file;
518         if (S_ISDIR(inode->i_mode))
519                 ll_authorize_statahead(inode, fd);
520
521         if (inode->i_sb->s_root == file_dentry(file)) {
522                 LUSTRE_FPRIVATE(file) = fd;
523                 RETURN(0);
524         }
525
526         if (!it || !it->it_disposition) {
527                 /* Convert f_flags into access mode. We cannot use file->f_mode,
528                  * because everything but O_ACCMODE mask was stripped from
529                  * there */
530                 if ((oit.it_flags + 1) & O_ACCMODE)
531                         oit.it_flags++;
532                 if (file->f_flags & O_TRUNC)
533                         oit.it_flags |= FMODE_WRITE;
534
535                 /* kernel only call f_op->open in dentry_open.  filp_open calls
536                  * dentry_open after call to open_namei that checks permissions.
537                  * Only nfsd_open call dentry_open directly without checking
538                  * permissions and because of that this code below is safe. */
539                 if (oit.it_flags & (FMODE_WRITE | FMODE_READ))
540                         oit.it_flags |= MDS_OPEN_OWNEROVERRIDE;
541
542                 /* We do not want O_EXCL here, presumably we opened the file
543                  * already? XXX - NFS implications? */
544                 oit.it_flags &= ~O_EXCL;
545
546                 /* bug20584, if "it_flags" contains O_CREAT, the file will be
547                  * created if necessary, then "IT_CREAT" should be set to keep
548                  * consistent with it */
549                 if (oit.it_flags & O_CREAT)
550                         oit.it_op |= IT_CREAT;
551
552                 it = &oit;
553         }
554
555 restart:
556         /* Let's see if we have file open on MDS already. */
557         if (it->it_flags & FMODE_WRITE) {
558                 och_p = &lli->lli_mds_write_och;
559                 och_usecount = &lli->lli_open_fd_write_count;
560         } else if (it->it_flags & FMODE_EXEC) {
561                 och_p = &lli->lli_mds_exec_och;
562                 och_usecount = &lli->lli_open_fd_exec_count;
563          } else {
564                 och_p = &lli->lli_mds_read_och;
565                 och_usecount = &lli->lli_open_fd_read_count;
566         }
567
568         mutex_lock(&lli->lli_och_mutex);
569         if (*och_p) { /* Open handle is present */
570                 if (it_disposition(it, DISP_OPEN_OPEN)) {
571                         /* Well, there's extra open request that we do not need,
572                            let's close it somehow. This will decref request. */
573                         rc = it_open_error(DISP_OPEN_OPEN, it);
574                         if (rc) {
575                                 mutex_unlock(&lli->lli_och_mutex);
576                                 GOTO(out_openerr, rc);
577                         }
578
579                         ll_release_openhandle(file_dentry(file), it);
580                 }
581                 (*och_usecount)++;
582
583                 rc = ll_local_open(file, it, fd, NULL);
584                 if (rc) {
585                         (*och_usecount)--;
586                         mutex_unlock(&lli->lli_och_mutex);
587                         GOTO(out_openerr, rc);
588                 }
589         } else {
590                 LASSERT(*och_usecount == 0);
591                 if (!it->it_disposition) {
592                         struct ll_dentry_data *ldd = ll_d2d(file->f_path.dentry);
593                         /* We cannot just request lock handle now, new ELC code
594                            means that one of other OPEN locks for this file
595                            could be cancelled, and since blocking ast handler
596                            would attempt to grab och_mutex as well, that would
597                            result in a deadlock */
598                         mutex_unlock(&lli->lli_och_mutex);
599                         /*
600                          * Normally called under two situations:
601                          * 1. NFS export.
602                          * 2. A race/condition on MDS resulting in no open
603                          *    handle to be returned from LOOKUP|OPEN request,
604                          *    for example if the target entry was a symlink.
605                          *
606                          *  Only fetch MDS_OPEN_LOCK if this is in NFS path,
607                          *  marked by a bit set in ll_iget_for_nfs. Clear the
608                          *  bit so that it's not confusing later callers.
609                          *
610                          *  NB; when ldd is NULL, it must have come via normal
611                          *  lookup path only, since ll_iget_for_nfs always calls
612                          *  ll_d_init().
613                          */
614                         if (ldd && ldd->lld_nfs_dentry) {
615                                 ldd->lld_nfs_dentry = 0;
616                                 it->it_flags |= MDS_OPEN_LOCK;
617                         }
618
619                          /*
620                          * Always specify MDS_OPEN_BY_FID because we don't want
621                          * to get file with different fid.
622                          */
623                         it->it_flags |= MDS_OPEN_BY_FID;
624                         rc = ll_intent_file_open(file_dentry(file), NULL, 0,
625                                                  it);
626                         if (rc)
627                                 GOTO(out_openerr, rc);
628
629                         goto restart;
630                 }
631                 OBD_ALLOC(*och_p, sizeof (struct obd_client_handle));
632                 if (!*och_p)
633                         GOTO(out_och_free, rc = -ENOMEM);
634
635                 (*och_usecount)++;
636
637                 /* md_intent_lock() didn't get a request ref if there was an
638                  * open error, so don't do cleanup on the request here
639                  * (bug 3430) */
640                 /* XXX (green): Should not we bail out on any error here, not
641                  * just open error? */
642                 rc = it_open_error(DISP_OPEN_OPEN, it);
643                 if (rc != 0)
644                         GOTO(out_och_free, rc);
645
646                 LASSERTF(it_disposition(it, DISP_ENQ_OPEN_REF),
647                          "inode %p: disposition %x, status %d\n", inode,
648                          it_disposition(it, ~0), it->it_status);
649
650                 rc = ll_local_open(file, it, fd, *och_p);
651                 if (rc)
652                         GOTO(out_och_free, rc);
653         }
654         mutex_unlock(&lli->lli_och_mutex);
655         fd = NULL;
656
657         /* Must do this outside lli_och_mutex lock to prevent deadlock where
658            different kind of OPEN lock for this same inode gets cancelled
659            by ldlm_cancel_lru */
660         if (!S_ISREG(inode->i_mode))
661                 GOTO(out_och_free, rc);
662
663         cl_lov_delay_create_clear(&file->f_flags);
664         GOTO(out_och_free, rc);
665
666 out_och_free:
667         if (rc) {
668                 if (och_p && *och_p) {
669                         OBD_FREE(*och_p, sizeof (struct obd_client_handle));
670                         *och_p = NULL; /* OBD_FREE writes some magic there */
671                         (*och_usecount)--;
672                 }
673                 mutex_unlock(&lli->lli_och_mutex);
674
675 out_openerr:
676                 if (lli->lli_opendir_key == fd)
677                         ll_deauthorize_statahead(inode, fd);
678                 if (fd != NULL)
679                         ll_file_data_put(fd);
680         } else {
681                 ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_OPEN, 1);
682         }
683
684         if (it && it_disposition(it, DISP_ENQ_OPEN_REF)) {
685                 ptlrpc_req_finished(it->it_request);
686                 it_clear_disposition(it, DISP_ENQ_OPEN_REF);
687         }
688
689         return rc;
690 }
691
692 static int ll_md_blocking_lease_ast(struct ldlm_lock *lock,
693                         struct ldlm_lock_desc *desc, void *data, int flag)
694 {
695         int rc;
696         struct lustre_handle lockh;
697         ENTRY;
698
699         switch (flag) {
700         case LDLM_CB_BLOCKING:
701                 ldlm_lock2handle(lock, &lockh);
702                 rc = ldlm_cli_cancel(&lockh, LCF_ASYNC);
703                 if (rc < 0) {
704                         CDEBUG(D_INODE, "ldlm_cli_cancel: %d\n", rc);
705                         RETURN(rc);
706                 }
707                 break;
708         case LDLM_CB_CANCELING:
709                 /* do nothing */
710                 break;
711         }
712         RETURN(0);
713 }
714
715 /**
716  * When setting a lease on a file, we take ownership of the lli_mds_*_och
717  * and save it as fd->fd_och so as to force client to reopen the file even
718  * if it has an open lock in cache already.
719  */
720 static int ll_lease_och_acquire(struct inode *inode, struct file *file,
721                                 struct lustre_handle *old_handle)
722 {
723         struct ll_inode_info *lli = ll_i2info(inode);
724         struct ll_file_data *fd = LUSTRE_FPRIVATE(file);
725         struct obd_client_handle **och_p;
726         __u64 *och_usecount;
727         int rc = 0;
728         ENTRY;
729
730         /* Get the openhandle of the file */
731         mutex_lock(&lli->lli_och_mutex);
732         if (fd->fd_lease_och != NULL)
733                 GOTO(out_unlock, rc = -EBUSY);
734
735         if (fd->fd_och == NULL) {
736                 if (file->f_mode & FMODE_WRITE) {
737                         LASSERT(lli->lli_mds_write_och != NULL);
738                         och_p = &lli->lli_mds_write_och;
739                         och_usecount = &lli->lli_open_fd_write_count;
740                 } else {
741                         LASSERT(lli->lli_mds_read_och != NULL);
742                         och_p = &lli->lli_mds_read_och;
743                         och_usecount = &lli->lli_open_fd_read_count;
744                 }
745
746                 if (*och_usecount > 1)
747                         GOTO(out_unlock, rc = -EBUSY);
748
749                 fd->fd_och = *och_p;
750                 *och_usecount = 0;
751                 *och_p = NULL;
752         }
753
754         *old_handle = fd->fd_och->och_fh;
755
756         EXIT;
757 out_unlock:
758         mutex_unlock(&lli->lli_och_mutex);
759         return rc;
760 }
761
762 /**
763  * Release ownership on lli_mds_*_och when putting back a file lease.
764  */
765 static int ll_lease_och_release(struct inode *inode, struct file *file)
766 {
767         struct ll_inode_info *lli = ll_i2info(inode);
768         struct ll_file_data *fd = LUSTRE_FPRIVATE(file);
769         struct obd_client_handle **och_p;
770         struct obd_client_handle *old_och = NULL;
771         __u64 *och_usecount;
772         int rc = 0;
773         ENTRY;
774
775         mutex_lock(&lli->lli_och_mutex);
776         if (file->f_mode & FMODE_WRITE) {
777                 och_p = &lli->lli_mds_write_och;
778                 och_usecount = &lli->lli_open_fd_write_count;
779         } else {
780                 och_p = &lli->lli_mds_read_och;
781                 och_usecount = &lli->lli_open_fd_read_count;
782         }
783
784         /* The file may have been open by another process (broken lease) so
785          * *och_p is not NULL. In this case we should simply increase usecount
786          * and close fd_och.
787          */
788         if (*och_p != NULL) {
789                 old_och = fd->fd_och;
790                 (*och_usecount)++;
791         } else {
792                 *och_p = fd->fd_och;
793                 *och_usecount = 1;
794         }
795         fd->fd_och = NULL;
796         mutex_unlock(&lli->lli_och_mutex);
797
798         if (old_och != NULL)
799                 rc = ll_close_inode_openhandle(inode, old_och, 0, NULL);
800
801         RETURN(rc);
802 }
803
804 /**
805  * Acquire a lease and open the file.
806  */
807 static struct obd_client_handle *
808 ll_lease_open(struct inode *inode, struct file *file, fmode_t fmode,
809               __u64 open_flags)
810 {
811         struct lookup_intent it = { .it_op = IT_OPEN };
812         struct ll_sb_info *sbi = ll_i2sbi(inode);
813         struct md_op_data *op_data;
814         struct ptlrpc_request *req = NULL;
815         struct lustre_handle old_handle = { 0 };
816         struct obd_client_handle *och = NULL;
817         int rc;
818         int rc2;
819         ENTRY;
820
821         if (fmode != FMODE_WRITE && fmode != FMODE_READ)
822                 RETURN(ERR_PTR(-EINVAL));
823
824         if (file != NULL) {
825                 if (!(fmode & file->f_mode) || (file->f_mode & FMODE_EXEC))
826                         RETURN(ERR_PTR(-EPERM));
827
828                 rc = ll_lease_och_acquire(inode, file, &old_handle);
829                 if (rc)
830                         RETURN(ERR_PTR(rc));
831         }
832
833         OBD_ALLOC_PTR(och);
834         if (och == NULL)
835                 RETURN(ERR_PTR(-ENOMEM));
836
837         op_data = ll_prep_md_op_data(NULL, inode, inode, NULL, 0, 0,
838                                         LUSTRE_OPC_ANY, NULL);
839         if (IS_ERR(op_data))
840                 GOTO(out, rc = PTR_ERR(op_data));
841
842         /* To tell the MDT this openhandle is from the same owner */
843         op_data->op_handle = old_handle;
844
845         it.it_flags = fmode | open_flags;
846         it.it_flags |= MDS_OPEN_LOCK | MDS_OPEN_BY_FID | MDS_OPEN_LEASE;
847         rc = md_intent_lock(sbi->ll_md_exp, op_data, &it, &req,
848                             &ll_md_blocking_lease_ast,
849         /* LDLM_FL_NO_LRU: To not put the lease lock into LRU list, otherwise
850          * it can be cancelled which may mislead applications that the lease is
851          * broken;
852          * LDLM_FL_EXCL: Set this flag so that it won't be matched by normal
853          * open in ll_md_blocking_ast(). Otherwise as ll_md_blocking_lease_ast
854          * doesn't deal with openhandle, so normal openhandle will be leaked. */
855                             LDLM_FL_NO_LRU | LDLM_FL_EXCL);
856         ll_finish_md_op_data(op_data);
857         ptlrpc_req_finished(req);
858         if (rc < 0)
859                 GOTO(out_release_it, rc);
860
861         if (it_disposition(&it, DISP_LOOKUP_NEG))
862                 GOTO(out_release_it, rc = -ENOENT);
863
864         rc = it_open_error(DISP_OPEN_OPEN, &it);
865         if (rc)
866                 GOTO(out_release_it, rc);
867
868         LASSERT(it_disposition(&it, DISP_ENQ_OPEN_REF));
869         ll_och_fill(sbi->ll_md_exp, &it, och);
870
871         if (!it_disposition(&it, DISP_OPEN_LEASE)) /* old server? */
872                 GOTO(out_close, rc = -EOPNOTSUPP);
873
874         /* already get lease, handle lease lock */
875         ll_set_lock_data(sbi->ll_md_exp, inode, &it, NULL);
876         if (it.it_lock_mode == 0 ||
877             it.it_lock_bits != MDS_INODELOCK_OPEN) {
878                 /* open lock must return for lease */
879                 CERROR(DFID "lease granted but no open lock, %d/%llu.\n",
880                         PFID(ll_inode2fid(inode)), it.it_lock_mode,
881                         it.it_lock_bits);
882                 GOTO(out_close, rc = -EPROTO);
883         }
884
885         ll_intent_release(&it);
886         RETURN(och);
887
888 out_close:
889         /* Cancel open lock */
890         if (it.it_lock_mode != 0) {
891                 ldlm_lock_decref_and_cancel(&och->och_lease_handle,
892                                             it.it_lock_mode);
893                 it.it_lock_mode = 0;
894                 och->och_lease_handle.cookie = 0ULL;
895         }
896         rc2 = ll_close_inode_openhandle(inode, och, 0, NULL);
897         if (rc2 < 0)
898                 CERROR("%s: error closing file "DFID": %d\n",
899                        ll_get_fsname(inode->i_sb, NULL, 0),
900                        PFID(&ll_i2info(inode)->lli_fid), rc2);
901         och = NULL; /* och has been freed in ll_close_inode_openhandle() */
902 out_release_it:
903         ll_intent_release(&it);
904 out:
905         if (och != NULL)
906                 OBD_FREE_PTR(och);
907         RETURN(ERR_PTR(rc));
908 }
909
910 /**
911  * Check whether a layout swap can be done between two inodes.
912  *
913  * \param[in] inode1  First inode to check
914  * \param[in] inode2  Second inode to check
915  *
916  * \retval 0 on success, layout swap can be performed between both inodes
917  * \retval negative error code if requirements are not met
918  */
919 static int ll_check_swap_layouts_validity(struct inode *inode1,
920                                           struct inode *inode2)
921 {
922         if (!S_ISREG(inode1->i_mode) || !S_ISREG(inode2->i_mode))
923                 return -EINVAL;
924
925         if (inode_permission(inode1, MAY_WRITE) ||
926             inode_permission(inode2, MAY_WRITE))
927                 return -EPERM;
928
929         if (inode1->i_sb != inode2->i_sb)
930                 return -EXDEV;
931
932         return 0;
933 }
934
935 static int ll_swap_layouts_close(struct obd_client_handle *och,
936                                  struct inode *inode, struct inode *inode2)
937 {
938         const struct lu_fid     *fid1 = ll_inode2fid(inode);
939         const struct lu_fid     *fid2;
940         int                      rc;
941         ENTRY;
942
943         CDEBUG(D_INODE, "%s: biased close of file "DFID"\n",
944                ll_get_fsname(inode->i_sb, NULL, 0), PFID(fid1));
945
946         rc = ll_check_swap_layouts_validity(inode, inode2);
947         if (rc < 0)
948                 GOTO(out_free_och, rc);
949
950         /* We now know that inode2 is a lustre inode */
951         fid2 = ll_inode2fid(inode2);
952
953         rc = lu_fid_cmp(fid1, fid2);
954         if (rc == 0)
955                 GOTO(out_free_och, rc = -EINVAL);
956
957         /* Close the file and {swap,merge} layouts between inode & inode2.
958          * NB: lease lock handle is released in mdc_close_layout_swap_pack()
959          * because we still need it to pack l_remote_handle to MDT. */
960         rc = ll_close_inode_openhandle(inode, och, MDS_CLOSE_LAYOUT_SWAP,
961                                        inode2);
962
963         och = NULL; /* freed in ll_close_inode_openhandle() */
964
965 out_free_och:
966         if (och != NULL)
967                 OBD_FREE_PTR(och);
968
969         RETURN(rc);
970 }
971
972 /**
973  * Release lease and close the file.
974  * It will check if the lease has ever broken.
975  */
976 static int ll_lease_close_intent(struct obd_client_handle *och,
977                                  struct inode *inode,
978                                  bool *lease_broken, enum mds_op_bias bias,
979                                  void *data)
980 {
981         struct ldlm_lock *lock;
982         bool cancelled = true;
983         int rc;
984         ENTRY;
985
986         lock = ldlm_handle2lock(&och->och_lease_handle);
987         if (lock != NULL) {
988                 lock_res_and_lock(lock);
989                 cancelled = ldlm_is_cancel(lock);
990                 unlock_res_and_lock(lock);
991                 LDLM_LOCK_PUT(lock);
992         }
993
994         CDEBUG(D_INODE, "lease for "DFID" broken? %d, bias: %x\n",
995                PFID(&ll_i2info(inode)->lli_fid), cancelled, bias);
996
997         if (lease_broken != NULL)
998                 *lease_broken = cancelled;
999
1000         if (!cancelled && !bias)
1001                 ldlm_cli_cancel(&och->och_lease_handle, 0);
1002
1003         if (cancelled) { /* no need to excute intent */
1004                 bias = 0;
1005                 data = NULL;
1006         }
1007
1008         rc = ll_close_inode_openhandle(inode, och, bias, data);
1009         RETURN(rc);
1010 }
1011
1012 static int ll_lease_close(struct obd_client_handle *och, struct inode *inode,
1013                           bool *lease_broken)
1014 {
1015         return ll_lease_close_intent(och, inode, lease_broken, 0, NULL);
1016 }
1017
1018 /**
1019  * After lease is taken, send the RPC MDS_REINT_RESYNC to the MDT
1020  */
1021 static int ll_lease_file_resync(struct obd_client_handle *och,
1022                                 struct inode *inode)
1023 {
1024         struct ll_sb_info *sbi = ll_i2sbi(inode);
1025         struct md_op_data *op_data;
1026         __u64 data_version_unused;
1027         int rc;
1028         ENTRY;
1029
1030         op_data = ll_prep_md_op_data(NULL, inode, NULL, NULL, 0, 0,
1031                                      LUSTRE_OPC_ANY, NULL);
1032         if (IS_ERR(op_data))
1033                 RETURN(PTR_ERR(op_data));
1034
1035         /* before starting file resync, it's necessary to clean up page cache
1036          * in client memory, otherwise once the layout version is increased,
1037          * writing back cached data will be denied the OSTs. */
1038         rc = ll_data_version(inode, &data_version_unused, LL_DV_WR_FLUSH);
1039         if (rc)
1040                 GOTO(out, rc);
1041
1042         op_data->op_handle = och->och_lease_handle;
1043         rc = md_file_resync(sbi->ll_md_exp, op_data);
1044         if (rc)
1045                 GOTO(out, rc);
1046
1047         EXIT;
1048 out:
1049         ll_finish_md_op_data(op_data);
1050         return rc;
1051 }
1052
1053 int ll_merge_attr(const struct lu_env *env, struct inode *inode)
1054 {
1055         struct ll_inode_info *lli = ll_i2info(inode);
1056         struct cl_object *obj = lli->lli_clob;
1057         struct cl_attr *attr = vvp_env_thread_attr(env);
1058         s64 atime;
1059         s64 mtime;
1060         s64 ctime;
1061         int rc = 0;
1062
1063         ENTRY;
1064
1065         ll_inode_size_lock(inode);
1066
1067         /* Merge timestamps the most recently obtained from MDS with
1068          * timestamps obtained from OSTs.
1069          *
1070          * Do not overwrite atime of inode because it may be refreshed
1071          * by file_accessed() function. If the read was served by cache
1072          * data, there is no RPC to be sent so that atime may not be
1073          * transferred to OSTs at all. MDT only updates atime at close time
1074          * if it's at least 'mdd.*.atime_diff' older.
1075          * All in all, the atime in Lustre does not strictly comply with
1076          * POSIX. Solving this problem needs to send an RPC to MDT for each
1077          * read, this will hurt performance. */
1078         if (LTIME_S(inode->i_atime) < lli->lli_atime || lli->lli_update_atime) {
1079                 LTIME_S(inode->i_atime) = lli->lli_atime;
1080                 lli->lli_update_atime = 0;
1081         }
1082         LTIME_S(inode->i_mtime) = lli->lli_mtime;
1083         LTIME_S(inode->i_ctime) = lli->lli_ctime;
1084
1085         atime = LTIME_S(inode->i_atime);
1086         mtime = LTIME_S(inode->i_mtime);
1087         ctime = LTIME_S(inode->i_ctime);
1088
1089         cl_object_attr_lock(obj);
1090         if (OBD_FAIL_CHECK(OBD_FAIL_MDC_MERGE))
1091                 rc = -EINVAL;
1092         else
1093                 rc = cl_object_attr_get(env, obj, attr);
1094         cl_object_attr_unlock(obj);
1095
1096         if (rc != 0)
1097                 GOTO(out_size_unlock, rc = (rc == -ENODATA ? 0 : rc));
1098
1099         if (atime < attr->cat_atime)
1100                 atime = attr->cat_atime;
1101
1102         if (ctime < attr->cat_ctime)
1103                 ctime = attr->cat_ctime;
1104
1105         if (mtime < attr->cat_mtime)
1106                 mtime = attr->cat_mtime;
1107
1108         CDEBUG(D_VFSTRACE, DFID" updating i_size %llu\n",
1109                PFID(&lli->lli_fid), attr->cat_size);
1110
1111         i_size_write(inode, attr->cat_size);
1112         inode->i_blocks = attr->cat_blocks;
1113
1114         LTIME_S(inode->i_atime) = atime;
1115         LTIME_S(inode->i_mtime) = mtime;
1116         LTIME_S(inode->i_ctime) = ctime;
1117
1118 out_size_unlock:
1119         ll_inode_size_unlock(inode);
1120
1121         RETURN(rc);
1122 }
1123
1124 /**
1125  * Set designated mirror for I/O.
1126  *
1127  * So far only read, write, and truncated can support to issue I/O to
1128  * designated mirror.
1129  */
1130 void ll_io_set_mirror(struct cl_io *io, const struct file *file)
1131 {
1132         struct ll_file_data *fd = LUSTRE_FPRIVATE(file);
1133
1134         /* clear layout version for generic(non-resync) I/O in case it carries
1135          * stale layout version due to I/O restart */
1136         io->ci_layout_version = 0;
1137
1138         /* FLR: disable non-delay for designated mirror I/O because obviously
1139          * only one mirror is available */
1140         if (fd->fd_designated_mirror > 0) {
1141                 io->ci_ndelay = 0;
1142                 io->ci_designated_mirror = fd->fd_designated_mirror;
1143                 io->ci_layout_version = fd->fd_layout_version;
1144                 io->ci_pio = 0; /* doesn't have a mechanism to pass mirror
1145                                  * io to ptasks */
1146         }
1147
1148         CDEBUG(D_VFSTRACE, "%s: desiginated mirror: %d\n",
1149                file->f_path.dentry->d_name.name, io->ci_designated_mirror);
1150 }
1151
1152 static bool file_is_noatime(const struct file *file)
1153 {
1154         const struct vfsmount *mnt = file->f_path.mnt;
1155         const struct inode *inode = file_inode((struct file *)file);
1156
1157         /* Adapted from file_accessed() and touch_atime().*/
1158         if (file->f_flags & O_NOATIME)
1159                 return true;
1160
1161         if (inode->i_flags & S_NOATIME)
1162                 return true;
1163
1164         if (IS_NOATIME(inode))
1165                 return true;
1166
1167         if (mnt->mnt_flags & (MNT_NOATIME | MNT_READONLY))
1168                 return true;
1169
1170         if ((mnt->mnt_flags & MNT_NODIRATIME) && S_ISDIR(inode->i_mode))
1171                 return true;
1172
1173         if ((inode->i_sb->s_flags & MS_NODIRATIME) && S_ISDIR(inode->i_mode))
1174                 return true;
1175
1176         return false;
1177 }
1178
1179 static int ll_file_io_ptask(struct cfs_ptask *ptask);
1180
1181 static void ll_io_init(struct cl_io *io, struct file *file, enum cl_io_type iot)
1182 {
1183         struct inode *inode = file_inode(file);
1184         struct ll_file_data *fd  = LUSTRE_FPRIVATE(file);
1185
1186         memset(&io->u.ci_rw.rw_iter, 0, sizeof(io->u.ci_rw.rw_iter));
1187         init_sync_kiocb(&io->u.ci_rw.rw_iocb, file);
1188         io->u.ci_rw.rw_file = file;
1189         io->u.ci_rw.rw_ptask = ll_file_io_ptask;
1190         io->u.ci_rw.rw_nonblock = !!(file->f_flags & O_NONBLOCK);
1191         io->ci_lock_no_expand = fd->ll_lock_no_expand;
1192
1193         if (iot == CIT_WRITE) {
1194                 io->u.ci_rw.rw_append = !!(file->f_flags & O_APPEND);
1195                 io->u.ci_rw.rw_sync   = !!(file->f_flags & O_SYNC ||
1196                                            file->f_flags & O_DIRECT ||
1197                                            IS_SYNC(inode));
1198         }
1199         io->ci_obj = ll_i2info(inode)->lli_clob;
1200         io->ci_lockreq = CILR_MAYBE;
1201         if (ll_file_nolock(file)) {
1202                 io->ci_lockreq = CILR_NEVER;
1203                 io->ci_no_srvlock = 1;
1204         } else if (file->f_flags & O_APPEND) {
1205                 io->ci_lockreq = CILR_MANDATORY;
1206         }
1207         io->ci_noatime = file_is_noatime(file);
1208         if (ll_i2sbi(inode)->ll_flags & LL_SBI_PIO)
1209                 io->ci_pio = !io->u.ci_rw.rw_append;
1210         else
1211                 io->ci_pio = 0;
1212
1213         /* FLR: only use non-delay I/O for read as there is only one
1214          * avaliable mirror for write. */
1215         io->ci_ndelay = !(iot == CIT_WRITE);
1216
1217         ll_io_set_mirror(io, file);
1218 }
1219
1220 static int ll_file_io_ptask(struct cfs_ptask *ptask)
1221 {
1222         struct cl_io_pt *pt = ptask->pt_cbdata;
1223         struct file *file = pt->cip_file;
1224         struct lu_env *env;
1225         struct cl_io *io;
1226         loff_t pos = pt->cip_pos;
1227         int rc;
1228         __u16 refcheck;
1229         ENTRY;
1230
1231         CDEBUG(D_VFSTRACE, "%s: %s range: [%llu, %llu)\n",
1232                 file_dentry(file)->d_name.name,
1233                 pt->cip_iot == CIT_READ ? "read" : "write",
1234                 pos, pos + pt->cip_count);
1235
1236         env = cl_env_get(&refcheck);
1237         if (IS_ERR(env))
1238                 RETURN(PTR_ERR(env));
1239
1240         io = vvp_env_thread_io(env);
1241         ll_io_init(io, file, pt->cip_iot);
1242         io->u.ci_rw.rw_iter = pt->cip_iter;
1243         io->u.ci_rw.rw_iocb = pt->cip_iocb;
1244         io->ci_pio = 0; /* It's already in parallel task */
1245
1246         rc = cl_io_rw_init(env, io, pt->cip_iot, pos,
1247                            pt->cip_count - pt->cip_result);
1248         if (!rc) {
1249                 struct vvp_io *vio = vvp_env_io(env);
1250
1251                 vio->vui_io_subtype = IO_NORMAL;
1252                 vio->vui_fd = LUSTRE_FPRIVATE(file);
1253
1254                 ll_cl_add(file, env, io, LCC_RW);
1255                 rc = cl_io_loop(env, io);
1256                 ll_cl_remove(file, env);
1257         } else {
1258                 /* cl_io_rw_init() handled IO */
1259                 rc = io->ci_result;
1260         }
1261
1262         if (OBD_FAIL_CHECK_RESET(OBD_FAIL_LLITE_PTASK_IO_FAIL, 0)) {
1263                 if (io->ci_nob > 0)
1264                         io->ci_nob /= 2;
1265                 rc = -EIO;
1266         }
1267
1268         if (io->ci_nob > 0) {
1269                 pt->cip_result += io->ci_nob;
1270                 iov_iter_advance(&pt->cip_iter, io->ci_nob);
1271                 pos += io->ci_nob;
1272                 pt->cip_iocb.ki_pos = pos;
1273 #ifdef HAVE_KIOCB_KI_LEFT
1274                 pt->cip_iocb.ki_left = pt->cip_count - pt->cip_result;
1275 #elif defined(HAVE_KI_NBYTES)
1276                 pt->cip_iocb.ki_nbytes = pt->cip_count - pt->cip_result;
1277 #endif
1278         }
1279
1280         cl_io_fini(env, io);
1281         cl_env_put(env, &refcheck);
1282
1283         pt->cip_need_restart = io->ci_need_restart;
1284
1285         CDEBUG(D_VFSTRACE, "%s: %s ret: %zd, rc: %d\n",
1286                 file_dentry(file)->d_name.name,
1287                 pt->cip_iot == CIT_READ ? "read" : "write",
1288                 pt->cip_result, rc);
1289
1290         RETURN(pt->cip_result > 0 ? 0 : rc);
1291 }
1292
1293 static ssize_t
1294 ll_file_io_generic(const struct lu_env *env, struct vvp_io_args *args,
1295                    struct file *file, enum cl_io_type iot,
1296                    loff_t *ppos, size_t count)
1297 {
1298         struct range_lock       range;
1299         struct vvp_io           *vio = vvp_env_io(env);
1300         struct inode            *inode = file_inode(file);
1301         struct ll_inode_info    *lli = ll_i2info(inode);
1302         struct ll_file_data     *fd  = LUSTRE_FPRIVATE(file);
1303         struct cl_io            *io;
1304         loff_t                  pos = *ppos;
1305         ssize_t                 result = 0;
1306         int                     rc = 0;
1307         unsigned                retried = 0;
1308         bool                    restarted = false;
1309
1310         ENTRY;
1311
1312         CDEBUG(D_VFSTRACE, "%s: %s range: [%llu, %llu)\n",
1313                 file_dentry(file)->d_name.name,
1314                 iot == CIT_READ ? "read" : "write", pos, pos + count);
1315
1316 restart:
1317         io = vvp_env_thread_io(env);
1318         ll_io_init(io, file, iot);
1319         if (args->via_io_subtype == IO_NORMAL) {
1320                 io->u.ci_rw.rw_iter = *args->u.normal.via_iter;
1321                 io->u.ci_rw.rw_iocb = *args->u.normal.via_iocb;
1322         }
1323         if (args->via_io_subtype != IO_NORMAL || restarted)
1324                 io->ci_pio = 0;
1325         io->ci_ndelay_tried = retried;
1326
1327         if (cl_io_rw_init(env, io, iot, pos, count) == 0) {
1328                 bool range_locked = false;
1329
1330                 if (file->f_flags & O_APPEND)
1331                         range_lock_init(&range, 0, LUSTRE_EOF);
1332                 else
1333                         range_lock_init(&range, pos, pos + count - 1);
1334
1335                 vio->vui_fd  = LUSTRE_FPRIVATE(file);
1336                 vio->vui_io_subtype = args->via_io_subtype;
1337
1338                 switch (vio->vui_io_subtype) {
1339                 case IO_NORMAL:
1340                         /* Direct IO reads must also take range lock,
1341                          * or multiple reads will try to work on the same pages
1342                          * See LU-6227 for details. */
1343                         if (((iot == CIT_WRITE) ||
1344                             (iot == CIT_READ && (file->f_flags & O_DIRECT))) &&
1345                             !(vio->vui_fd->fd_flags & LL_FILE_GROUP_LOCKED)) {
1346                                 CDEBUG(D_VFSTRACE, "Range lock "RL_FMT"\n",
1347                                        RL_PARA(&range));
1348                                 rc = range_lock(&lli->lli_write_tree, &range);
1349                                 if (rc < 0)
1350                                         GOTO(out, rc);
1351
1352                                 range_locked = true;
1353                         }
1354                         break;
1355                 case IO_SPLICE:
1356                         vio->u.splice.vui_pipe = args->u.splice.via_pipe;
1357                         vio->u.splice.vui_flags = args->u.splice.via_flags;
1358                         break;
1359                 default:
1360                         CERROR("unknown IO subtype %u\n", vio->vui_io_subtype);
1361                         LBUG();
1362                 }
1363
1364                 ll_cl_add(file, env, io, LCC_RW);
1365                 if (io->ci_pio && iot == CIT_WRITE && !IS_NOSEC(inode) &&
1366                     !lli->lli_inode_locked) {
1367                         inode_lock(inode);
1368                         lli->lli_inode_locked = 1;
1369                 }
1370                 rc = cl_io_loop(env, io);
1371                 if (lli->lli_inode_locked) {
1372                         lli->lli_inode_locked = 0;
1373                         inode_unlock(inode);
1374                 }
1375                 ll_cl_remove(file, env);
1376
1377                 if (range_locked) {
1378                         CDEBUG(D_VFSTRACE, "Range unlock "RL_FMT"\n",
1379                                RL_PARA(&range));
1380                         range_unlock(&lli->lli_write_tree, &range);
1381                 }
1382         } else {
1383                 /* cl_io_rw_init() handled IO */
1384                 rc = io->ci_result;
1385         }
1386
1387         if (io->ci_nob > 0) {
1388                 result += io->ci_nob;
1389                 count  -= io->ci_nob;
1390
1391                 if (args->via_io_subtype == IO_NORMAL) {
1392                         iov_iter_advance(args->u.normal.via_iter, io->ci_nob);
1393                         pos += io->ci_nob;
1394                         args->u.normal.via_iocb->ki_pos = pos;
1395 #ifdef HAVE_KIOCB_KI_LEFT
1396                         args->u.normal.via_iocb->ki_left = count;
1397 #elif defined(HAVE_KI_NBYTES)
1398                         args->u.normal.via_iocb->ki_nbytes = count;
1399 #endif
1400                 } else {
1401                         /* for splice */
1402                         pos = io->u.ci_rw.rw_range.cir_pos;
1403                 }
1404         }
1405 out:
1406         cl_io_fini(env, io);
1407
1408         CDEBUG(D_VFSTRACE,
1409                "%s: %d io complete with rc: %d, result: %zd, restart: %d\n",
1410                file->f_path.dentry->d_name.name,
1411                iot, rc, result, io->ci_need_restart);
1412
1413         if ((rc == 0 || rc == -ENODATA) && count > 0 && io->ci_need_restart) {
1414                 CDEBUG(D_VFSTRACE,
1415                         "%s: restart %s range: [%llu, %llu) ret: %zd, rc: %d\n",
1416                         file_dentry(file)->d_name.name,
1417                         iot == CIT_READ ? "read" : "write",
1418                         pos, pos + count, result, rc);
1419                 /* preserve the tried count for FLR */
1420                 retried = io->ci_ndelay_tried;
1421                 restarted = true;
1422                 goto restart;
1423         }
1424
1425         if (iot == CIT_READ) {
1426                 if (result > 0)
1427                         ll_stats_ops_tally(ll_i2sbi(inode),
1428                                            LPROC_LL_READ_BYTES, result);
1429         } else if (iot == CIT_WRITE) {
1430                 if (result > 0) {
1431                         ll_stats_ops_tally(ll_i2sbi(inode),
1432                                            LPROC_LL_WRITE_BYTES, result);
1433                         fd->fd_write_failed = false;
1434                 } else if (result == 0 && rc == 0) {
1435                         rc = io->ci_result;
1436                         if (rc < 0)
1437                                 fd->fd_write_failed = true;
1438                         else
1439                                 fd->fd_write_failed = false;
1440                 } else if (rc != -ERESTARTSYS) {
1441                         fd->fd_write_failed = true;
1442                 }
1443         }
1444
1445         CDEBUG(D_VFSTRACE, "%s: %s *ppos: %llu, pos: %llu, ret: %zd, rc: %d\n",
1446                 file_dentry(file)->d_name.name,
1447                 iot == CIT_READ ? "read" : "write", *ppos, pos, result, rc);
1448
1449         *ppos = pos;
1450
1451         RETURN(result > 0 ? result : rc);
1452 }
1453
1454 /**
1455  * The purpose of fast read is to overcome per I/O overhead and improve IOPS
1456  * especially for small I/O.
1457  *
1458  * To serve a read request, CLIO has to create and initialize a cl_io and
1459  * then request DLM lock. This has turned out to have siginificant overhead
1460  * and affects the performance of small I/O dramatically.
1461  *
1462  * It's not necessary to create a cl_io for each I/O. Under the help of read
1463  * ahead, most of the pages being read are already in memory cache and we can
1464  * read those pages directly because if the pages exist, the corresponding DLM
1465  * lock must exist so that page content must be valid.
1466  *
1467  * In fast read implementation, the llite speculatively finds and reads pages
1468  * in memory cache. There are three scenarios for fast read:
1469  *   - If the page exists and is uptodate, kernel VM will provide the data and
1470  *     CLIO won't be intervened;
1471  *   - If the page was brought into memory by read ahead, it will be exported
1472  *     and read ahead parameters will be updated;
1473  *   - Otherwise the page is not in memory, we can't do fast read. Therefore,
1474  *     it will go back and invoke normal read, i.e., a cl_io will be created
1475  *     and DLM lock will be requested.
1476  *
1477  * POSIX compliance: posix standard states that read is intended to be atomic.
1478  * Lustre read implementation is in line with Linux kernel read implementation
1479  * and neither of them complies with POSIX standard in this matter. Fast read
1480  * doesn't make the situation worse on single node but it may interleave write
1481  * results from multiple nodes due to short read handling in ll_file_aio_read().
1482  *
1483  * \param env - lu_env
1484  * \param iocb - kiocb from kernel
1485  * \param iter - user space buffers where the data will be copied
1486  *
1487  * \retval - number of bytes have been read, or error code if error occurred.
1488  */
1489 static ssize_t
1490 ll_do_fast_read(struct kiocb *iocb, struct iov_iter *iter)
1491 {
1492         ssize_t result;
1493
1494         if (!ll_sbi_has_fast_read(ll_i2sbi(file_inode(iocb->ki_filp))))
1495                 return 0;
1496
1497         /* NB: we can't do direct IO for fast read because it will need a lock
1498          * to make IO engine happy. */
1499         if (iocb->ki_filp->f_flags & O_DIRECT)
1500                 return 0;
1501
1502         result = generic_file_read_iter(iocb, iter);
1503
1504         /* If the first page is not in cache, generic_file_aio_read() will be
1505          * returned with -ENODATA.
1506          * See corresponding code in ll_readpage(). */
1507         if (result == -ENODATA)
1508                 result = 0;
1509
1510         if (result > 0)
1511                 ll_stats_ops_tally(ll_i2sbi(file_inode(iocb->ki_filp)),
1512                                 LPROC_LL_READ_BYTES, result);
1513
1514         return result;
1515 }
1516
1517 /*
1518  * Read from a file (through the page cache).
1519  */
1520 static ssize_t ll_file_read_iter(struct kiocb *iocb, struct iov_iter *to)
1521 {
1522         struct lu_env *env;
1523         struct vvp_io_args *args;
1524         ssize_t result;
1525         ssize_t rc2;
1526         __u16 refcheck;
1527
1528         result = ll_do_fast_read(iocb, to);
1529         if (result < 0 || iov_iter_count(to) == 0)
1530                 GOTO(out, result);
1531
1532         env = cl_env_get(&refcheck);
1533         if (IS_ERR(env))
1534                 return PTR_ERR(env);
1535
1536         args = ll_env_args(env, IO_NORMAL);
1537         args->u.normal.via_iter = to;
1538         args->u.normal.via_iocb = iocb;
1539
1540         rc2 = ll_file_io_generic(env, args, iocb->ki_filp, CIT_READ,
1541                                  &iocb->ki_pos, iov_iter_count(to));
1542         if (rc2 > 0)
1543                 result += rc2;
1544         else if (result == 0)
1545                 result = rc2;
1546
1547         cl_env_put(env, &refcheck);
1548 out:
1549         return result;
1550 }
1551
1552 /*
1553  * Write to a file (through the page cache).
1554  */
1555 static ssize_t ll_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
1556 {
1557         struct vvp_io_args *args;
1558         struct lu_env *env;
1559         ssize_t result;
1560         __u16 refcheck;
1561
1562         env = cl_env_get(&refcheck);
1563         if (IS_ERR(env))
1564                 return PTR_ERR(env);
1565
1566         args = ll_env_args(env, IO_NORMAL);
1567         args->u.normal.via_iter = from;
1568         args->u.normal.via_iocb = iocb;
1569
1570         result = ll_file_io_generic(env, args, iocb->ki_filp, CIT_WRITE,
1571                                     &iocb->ki_pos, iov_iter_count(from));
1572         cl_env_put(env, &refcheck);
1573         return result;
1574 }
1575
1576 #ifndef HAVE_FILE_OPERATIONS_READ_WRITE_ITER
1577 /*
1578  * XXX: exact copy from kernel code (__generic_file_aio_write_nolock)
1579  */
1580 static int ll_file_get_iov_count(const struct iovec *iov,
1581                                  unsigned long *nr_segs, size_t *count)
1582 {
1583         size_t cnt = 0;
1584         unsigned long seg;
1585
1586         for (seg = 0; seg < *nr_segs; seg++) {
1587                 const struct iovec *iv = &iov[seg];
1588
1589                 /*
1590                  * If any segment has a negative length, or the cumulative
1591                  * length ever wraps negative then return -EINVAL.
1592                  */
1593                 cnt += iv->iov_len;
1594                 if (unlikely((ssize_t)(cnt|iv->iov_len) < 0))
1595                         return -EINVAL;
1596                 if (access_ok(VERIFY_READ, iv->iov_base, iv->iov_len))
1597                         continue;
1598                 if (seg == 0)
1599                         return -EFAULT;
1600                 *nr_segs = seg;
1601                 cnt -= iv->iov_len;     /* This segment is no good */
1602                 break;
1603         }
1604         *count = cnt;
1605         return 0;
1606 }
1607
1608 static ssize_t ll_file_aio_read(struct kiocb *iocb, const struct iovec *iov,
1609                                 unsigned long nr_segs, loff_t pos)
1610 {
1611         struct iov_iter to;
1612         size_t iov_count;
1613         ssize_t result;
1614         ENTRY;
1615
1616         result = ll_file_get_iov_count(iov, &nr_segs, &iov_count);
1617         if (result)
1618                 RETURN(result);
1619
1620 # ifdef HAVE_IOV_ITER_INIT_DIRECTION
1621         iov_iter_init(&to, READ, iov, nr_segs, iov_count);
1622 # else /* !HAVE_IOV_ITER_INIT_DIRECTION */
1623         iov_iter_init(&to, iov, nr_segs, iov_count, 0);
1624 # endif /* HAVE_IOV_ITER_INIT_DIRECTION */
1625
1626         result = ll_file_read_iter(iocb, &to);
1627
1628         RETURN(result);
1629 }
1630
1631 static ssize_t ll_file_read(struct file *file, char __user *buf, size_t count,
1632                             loff_t *ppos)
1633 {
1634         struct iovec   iov = { .iov_base = buf, .iov_len = count };
1635         struct kiocb   kiocb;
1636         ssize_t        result;
1637         ENTRY;
1638
1639         init_sync_kiocb(&kiocb, file);
1640         kiocb.ki_pos = *ppos;
1641 #ifdef HAVE_KIOCB_KI_LEFT
1642         kiocb.ki_left = count;
1643 #elif defined(HAVE_KI_NBYTES)
1644         kiocb.i_nbytes = count;
1645 #endif
1646
1647         result = ll_file_aio_read(&kiocb, &iov, 1, kiocb.ki_pos);
1648         *ppos = kiocb.ki_pos;
1649
1650         RETURN(result);
1651 }
1652
1653 /*
1654  * Write to a file (through the page cache).
1655  * AIO stuff
1656  */
1657 static ssize_t ll_file_aio_write(struct kiocb *iocb, const struct iovec *iov,
1658                                  unsigned long nr_segs, loff_t pos)
1659 {
1660         struct iov_iter from;
1661         size_t iov_count;
1662         ssize_t result;
1663         ENTRY;
1664
1665         result = ll_file_get_iov_count(iov, &nr_segs, &iov_count);
1666         if (result)
1667                 RETURN(result);
1668
1669 # ifdef HAVE_IOV_ITER_INIT_DIRECTION
1670         iov_iter_init(&from, WRITE, iov, nr_segs, iov_count);
1671 # else /* !HAVE_IOV_ITER_INIT_DIRECTION */
1672         iov_iter_init(&from, iov, nr_segs, iov_count, 0);
1673 # endif /* HAVE_IOV_ITER_INIT_DIRECTION */
1674
1675         result = ll_file_write_iter(iocb, &from);
1676
1677         RETURN(result);
1678 }
1679
1680 static ssize_t ll_file_write(struct file *file, const char __user *buf,
1681                              size_t count, loff_t *ppos)
1682 {
1683         struct lu_env *env;
1684         struct iovec   iov = { .iov_base = (void __user *)buf,
1685                                .iov_len = count };
1686         struct kiocb  *kiocb;
1687         ssize_t        result;
1688         __u16          refcheck;
1689         ENTRY;
1690
1691         env = cl_env_get(&refcheck);
1692         if (IS_ERR(env))
1693                 RETURN(PTR_ERR(env));
1694
1695         kiocb = &ll_env_info(env)->lti_kiocb;
1696         init_sync_kiocb(kiocb, file);
1697         kiocb->ki_pos = *ppos;
1698 #ifdef HAVE_KIOCB_KI_LEFT
1699         kiocb->ki_left = count;
1700 #elif defined(HAVE_KI_NBYTES)
1701         kiocb->ki_nbytes = count;
1702 #endif
1703
1704         result = ll_file_aio_write(kiocb, &iov, 1, kiocb->ki_pos);
1705         *ppos = kiocb->ki_pos;
1706
1707         cl_env_put(env, &refcheck);
1708         RETURN(result);
1709 }
1710 #endif /* !HAVE_FILE_OPERATIONS_READ_WRITE_ITER */
1711
1712 /*
1713  * Send file content (through pagecache) somewhere with helper
1714  */
1715 static ssize_t ll_file_splice_read(struct file *in_file, loff_t *ppos,
1716                                    struct pipe_inode_info *pipe, size_t count,
1717                                    unsigned int flags)
1718 {
1719         struct lu_env      *env;
1720         struct vvp_io_args *args;
1721         ssize_t             result;
1722         __u16               refcheck;
1723         ENTRY;
1724
1725         env = cl_env_get(&refcheck);
1726         if (IS_ERR(env))
1727                 RETURN(PTR_ERR(env));
1728
1729         args = ll_env_args(env, IO_SPLICE);
1730         args->u.splice.via_pipe = pipe;
1731         args->u.splice.via_flags = flags;
1732
1733         result = ll_file_io_generic(env, args, in_file, CIT_READ, ppos, count);
1734         cl_env_put(env, &refcheck);
1735         RETURN(result);
1736 }
1737
1738 int ll_lov_setstripe_ea_info(struct inode *inode, struct dentry *dentry,
1739                              __u64 flags, struct lov_user_md *lum, int lum_size)
1740 {
1741         struct lookup_intent oit = {
1742                 .it_op = IT_OPEN,
1743                 .it_flags = flags | MDS_OPEN_BY_FID,
1744         };
1745         int rc;
1746         ENTRY;
1747
1748         ll_inode_size_lock(inode);
1749         rc = ll_intent_file_open(dentry, lum, lum_size, &oit);
1750         if (rc < 0)
1751                 GOTO(out_unlock, rc);
1752
1753         ll_release_openhandle(dentry, &oit);
1754
1755 out_unlock:
1756         ll_inode_size_unlock(inode);
1757         ll_intent_release(&oit);
1758
1759         RETURN(rc);
1760 }
1761
1762 int ll_lov_getstripe_ea_info(struct inode *inode, const char *filename,
1763                              struct lov_mds_md **lmmp, int *lmm_size,
1764                              struct ptlrpc_request **request)
1765 {
1766         struct ll_sb_info *sbi = ll_i2sbi(inode);
1767         struct mdt_body  *body;
1768         struct lov_mds_md *lmm = NULL;
1769         struct ptlrpc_request *req = NULL;
1770         struct md_op_data *op_data;
1771         int rc, lmmsize;
1772
1773         rc = ll_get_default_mdsize(sbi, &lmmsize);
1774         if (rc)
1775                 RETURN(rc);
1776
1777         op_data = ll_prep_md_op_data(NULL, inode, NULL, filename,
1778                                      strlen(filename), lmmsize,
1779                                      LUSTRE_OPC_ANY, NULL);
1780         if (IS_ERR(op_data))
1781                 RETURN(PTR_ERR(op_data));
1782
1783         op_data->op_valid = OBD_MD_FLEASIZE | OBD_MD_FLDIREA;
1784         rc = md_getattr_name(sbi->ll_md_exp, op_data, &req);
1785         ll_finish_md_op_data(op_data);
1786         if (rc < 0) {
1787                 CDEBUG(D_INFO, "md_getattr_name failed "
1788                        "on %s: rc %d\n", filename, rc);
1789                 GOTO(out, rc);
1790         }
1791
1792         body = req_capsule_server_get(&req->rq_pill, &RMF_MDT_BODY);
1793         LASSERT(body != NULL); /* checked by mdc_getattr_name */
1794
1795         lmmsize = body->mbo_eadatasize;
1796
1797         if (!(body->mbo_valid & (OBD_MD_FLEASIZE | OBD_MD_FLDIREA)) ||
1798                         lmmsize == 0) {
1799                 GOTO(out, rc = -ENODATA);
1800         }
1801
1802         lmm = req_capsule_server_sized_get(&req->rq_pill, &RMF_MDT_MD, lmmsize);
1803         LASSERT(lmm != NULL);
1804
1805         if (lmm->lmm_magic != cpu_to_le32(LOV_MAGIC_V1) &&
1806             lmm->lmm_magic != cpu_to_le32(LOV_MAGIC_V3) &&
1807             lmm->lmm_magic != cpu_to_le32(LOV_MAGIC_COMP_V1))
1808                 GOTO(out, rc = -EPROTO);
1809
1810         /*
1811          * This is coming from the MDS, so is probably in
1812          * little endian.  We convert it to host endian before
1813          * passing it to userspace.
1814          */
1815         if (LOV_MAGIC != cpu_to_le32(LOV_MAGIC)) {
1816                 int stripe_count;
1817
1818                 if (lmm->lmm_magic == cpu_to_le32(LOV_MAGIC_V1) ||
1819                     lmm->lmm_magic == cpu_to_le32(LOV_MAGIC_V3)) {
1820                         stripe_count = le16_to_cpu(lmm->lmm_stripe_count);
1821                         if (le32_to_cpu(lmm->lmm_pattern) &
1822                             LOV_PATTERN_F_RELEASED)
1823                                 stripe_count = 0;
1824                 }
1825
1826                 /* if function called for directory - we should
1827                  * avoid swab not existent lsm objects */
1828                 if (lmm->lmm_magic == cpu_to_le32(LOV_MAGIC_V1)) {
1829                         lustre_swab_lov_user_md_v1(
1830                                         (struct lov_user_md_v1 *)lmm);
1831                         if (S_ISREG(body->mbo_mode))
1832                                 lustre_swab_lov_user_md_objects(
1833                                     ((struct lov_user_md_v1 *)lmm)->lmm_objects,
1834                                     stripe_count);
1835                 } else if (lmm->lmm_magic == cpu_to_le32(LOV_MAGIC_V3)) {
1836                         lustre_swab_lov_user_md_v3(
1837                                         (struct lov_user_md_v3 *)lmm);
1838                         if (S_ISREG(body->mbo_mode))
1839                                 lustre_swab_lov_user_md_objects(
1840                                     ((struct lov_user_md_v3 *)lmm)->lmm_objects,
1841                                     stripe_count);
1842                 } else if (lmm->lmm_magic ==
1843                            cpu_to_le32(LOV_MAGIC_COMP_V1)) {
1844                         lustre_swab_lov_comp_md_v1(
1845                                         (struct lov_comp_md_v1 *)lmm);
1846                 }
1847         }
1848
1849 out:
1850         *lmmp = lmm;
1851         *lmm_size = lmmsize;
1852         *request = req;
1853         return rc;
1854 }
1855
1856 static int ll_lov_setea(struct inode *inode, struct file *file,
1857                         void __user *arg)
1858 {
1859         __u64                    flags = MDS_OPEN_HAS_OBJS | FMODE_WRITE;
1860         struct lov_user_md      *lump;
1861         int                      lum_size = sizeof(struct lov_user_md) +
1862                                             sizeof(struct lov_user_ost_data);
1863         int                      rc;
1864         ENTRY;
1865
1866         if (!cfs_capable(CFS_CAP_SYS_ADMIN))
1867                 RETURN(-EPERM);
1868
1869         OBD_ALLOC_LARGE(lump, lum_size);
1870         if (lump == NULL)
1871                 RETURN(-ENOMEM);
1872
1873         if (copy_from_user(lump, arg, lum_size))
1874                 GOTO(out_lump, rc = -EFAULT);
1875
1876         rc = ll_lov_setstripe_ea_info(inode, file_dentry(file), flags, lump,
1877                                       lum_size);
1878         cl_lov_delay_create_clear(&file->f_flags);
1879
1880 out_lump:
1881         OBD_FREE_LARGE(lump, lum_size);
1882         RETURN(rc);
1883 }
1884
1885 static int ll_file_getstripe(struct inode *inode, void __user *lum, size_t size)
1886 {
1887         struct lu_env   *env;
1888         __u16           refcheck;
1889         int             rc;
1890         ENTRY;
1891
1892         env = cl_env_get(&refcheck);
1893         if (IS_ERR(env))
1894                 RETURN(PTR_ERR(env));
1895
1896         rc = cl_object_getstripe(env, ll_i2info(inode)->lli_clob, lum, size);
1897         cl_env_put(env, &refcheck);
1898         RETURN(rc);
1899 }
1900
1901 static int ll_lov_setstripe(struct inode *inode, struct file *file,
1902                             void __user *arg)
1903 {
1904         struct lov_user_md __user *lum = (struct lov_user_md __user *)arg;
1905         struct lov_user_md        *klum;
1906         int                        lum_size, rc;
1907         __u64                      flags = FMODE_WRITE;
1908         ENTRY;
1909
1910         rc = ll_copy_user_md(lum, &klum);
1911         if (rc < 0)
1912                 RETURN(rc);
1913
1914         lum_size = rc;
1915         rc = ll_lov_setstripe_ea_info(inode, file_dentry(file), flags, klum,
1916                                       lum_size);
1917         if (!rc) {
1918                 __u32 gen;
1919
1920                 rc = put_user(0, &lum->lmm_stripe_count);
1921                 if (rc)
1922                         GOTO(out, rc);
1923
1924                 rc = ll_layout_refresh(inode, &gen);
1925                 if (rc)
1926                         GOTO(out, rc);
1927
1928                 rc = ll_file_getstripe(inode, arg, lum_size);
1929         }
1930         cl_lov_delay_create_clear(&file->f_flags);
1931
1932 out:
1933         OBD_FREE(klum, lum_size);
1934         RETURN(rc);
1935 }
1936
1937 static int
1938 ll_get_grouplock(struct inode *inode, struct file *file, unsigned long arg)
1939 {
1940         struct ll_inode_info *lli = ll_i2info(inode);
1941         struct cl_object *obj = lli->lli_clob;
1942         struct ll_file_data *fd = LUSTRE_FPRIVATE(file);
1943         struct ll_grouplock grouplock;
1944         int rc;
1945         ENTRY;
1946
1947         if (arg == 0) {
1948                 CWARN("group id for group lock must not be 0\n");
1949                 RETURN(-EINVAL);
1950         }
1951
1952         if (ll_file_nolock(file))
1953                 RETURN(-EOPNOTSUPP);
1954
1955         spin_lock(&lli->lli_lock);
1956         if (fd->fd_flags & LL_FILE_GROUP_LOCKED) {
1957                 CWARN("group lock already existed with gid %lu\n",
1958                       fd->fd_grouplock.lg_gid);
1959                 spin_unlock(&lli->lli_lock);
1960                 RETURN(-EINVAL);
1961         }
1962         LASSERT(fd->fd_grouplock.lg_lock == NULL);
1963         spin_unlock(&lli->lli_lock);
1964
1965         /**
1966          * XXX: group lock needs to protect all OST objects while PFL
1967          * can add new OST objects during the IO, so we'd instantiate
1968          * all OST objects before getting its group lock.
1969          */
1970         if (obj) {
1971                 struct lu_env *env;
1972                 __u16 refcheck;
1973                 struct cl_layout cl = {
1974                         .cl_is_composite = false,
1975                 };
1976                 struct lu_extent ext = {
1977                         .e_start = 0,
1978                         .e_end = OBD_OBJECT_EOF,
1979                 };
1980
1981                 env = cl_env_get(&refcheck);
1982                 if (IS_ERR(env))
1983                         RETURN(PTR_ERR(env));
1984
1985                 rc = cl_object_layout_get(env, obj, &cl);
1986                 if (!rc && cl.cl_is_composite)
1987                         rc = ll_layout_write_intent(inode, LAYOUT_INTENT_WRITE,
1988                                                     &ext);
1989
1990                 cl_env_put(env, &refcheck);
1991                 if (rc)
1992                         RETURN(rc);
1993         }
1994
1995         rc = cl_get_grouplock(ll_i2info(inode)->lli_clob,
1996                               arg, (file->f_flags & O_NONBLOCK), &grouplock);
1997         if (rc)
1998                 RETURN(rc);
1999
2000         spin_lock(&lli->lli_lock);
2001         if (fd->fd_flags & LL_FILE_GROUP_LOCKED) {
2002                 spin_unlock(&lli->lli_lock);
2003                 CERROR("another thread just won the race\n");
2004                 cl_put_grouplock(&grouplock);
2005                 RETURN(-EINVAL);
2006         }
2007
2008         fd->fd_flags |= LL_FILE_GROUP_LOCKED;
2009         fd->fd_grouplock = grouplock;
2010         spin_unlock(&lli->lli_lock);
2011
2012         CDEBUG(D_INFO, "group lock %lu obtained\n", arg);
2013         RETURN(0);
2014 }
2015
2016 static int ll_put_grouplock(struct inode *inode, struct file *file,
2017                             unsigned long arg)
2018 {
2019         struct ll_inode_info   *lli = ll_i2info(inode);
2020         struct ll_file_data    *fd = LUSTRE_FPRIVATE(file);
2021         struct ll_grouplock     grouplock;
2022         ENTRY;
2023
2024         spin_lock(&lli->lli_lock);
2025         if (!(fd->fd_flags & LL_FILE_GROUP_LOCKED)) {
2026                 spin_unlock(&lli->lli_lock);
2027                 CWARN("no group lock held\n");
2028                 RETURN(-EINVAL);
2029         }
2030
2031         LASSERT(fd->fd_grouplock.lg_lock != NULL);
2032
2033         if (fd->fd_grouplock.lg_gid != arg) {
2034                 CWARN("group lock %lu doesn't match current id %lu\n",
2035                       arg, fd->fd_grouplock.lg_gid);
2036                 spin_unlock(&lli->lli_lock);
2037                 RETURN(-EINVAL);
2038         }
2039
2040         grouplock = fd->fd_grouplock;
2041         memset(&fd->fd_grouplock, 0, sizeof(fd->fd_grouplock));
2042         fd->fd_flags &= ~LL_FILE_GROUP_LOCKED;
2043         spin_unlock(&lli->lli_lock);
2044
2045         cl_put_grouplock(&grouplock);
2046         CDEBUG(D_INFO, "group lock %lu released\n", arg);
2047         RETURN(0);
2048 }
2049
2050 /**
2051  * Close inode open handle
2052  *
2053  * \param dentry [in]     dentry which contains the inode
2054  * \param it     [in,out] intent which contains open info and result
2055  *
2056  * \retval 0     success
2057  * \retval <0    failure
2058  */
2059 int ll_release_openhandle(struct dentry *dentry, struct lookup_intent *it)
2060 {
2061         struct inode *inode = dentry->d_inode;
2062         struct obd_client_handle *och;
2063         int rc;
2064         ENTRY;
2065
2066         LASSERT(inode);
2067
2068         /* Root ? Do nothing. */
2069         if (dentry->d_inode->i_sb->s_root == dentry)
2070                 RETURN(0);
2071
2072         /* No open handle to close? Move away */
2073         if (!it_disposition(it, DISP_OPEN_OPEN))
2074                 RETURN(0);
2075
2076         LASSERT(it_open_error(DISP_OPEN_OPEN, it) == 0);
2077
2078         OBD_ALLOC(och, sizeof(*och));
2079         if (!och)
2080                 GOTO(out, rc = -ENOMEM);
2081
2082         ll_och_fill(ll_i2sbi(inode)->ll_md_exp, it, och);
2083
2084         rc = ll_close_inode_openhandle(inode, och, 0, NULL);
2085 out:
2086         /* this one is in place of ll_file_open */
2087         if (it_disposition(it, DISP_ENQ_OPEN_REF)) {
2088                 ptlrpc_req_finished(it->it_request);
2089                 it_clear_disposition(it, DISP_ENQ_OPEN_REF);
2090         }
2091         RETURN(rc);
2092 }
2093
2094 /**
2095  * Get size for inode for which FIEMAP mapping is requested.
2096  * Make the FIEMAP get_info call and returns the result.
2097  * \param fiemap        kernel buffer to hold extens
2098  * \param num_bytes     kernel buffer size
2099  */
2100 static int ll_do_fiemap(struct inode *inode, struct fiemap *fiemap,
2101                         size_t num_bytes)
2102 {
2103         struct lu_env                   *env;
2104         __u16                           refcheck;
2105         int                             rc = 0;
2106         struct ll_fiemap_info_key       fmkey = { .lfik_name = KEY_FIEMAP, };
2107         ENTRY;
2108
2109         /* Checks for fiemap flags */
2110         if (fiemap->fm_flags & ~LUSTRE_FIEMAP_FLAGS_COMPAT) {
2111                 fiemap->fm_flags &= ~LUSTRE_FIEMAP_FLAGS_COMPAT;
2112                 return -EBADR;
2113         }
2114
2115         /* Check for FIEMAP_FLAG_SYNC */
2116         if (fiemap->fm_flags & FIEMAP_FLAG_SYNC) {
2117                 rc = filemap_fdatawrite(inode->i_mapping);
2118                 if (rc)
2119                         return rc;
2120         }
2121
2122         env = cl_env_get(&refcheck);
2123         if (IS_ERR(env))
2124                 RETURN(PTR_ERR(env));
2125
2126         if (i_size_read(inode) == 0) {
2127                 rc = ll_glimpse_size(inode);
2128                 if (rc)
2129                         GOTO(out, rc);
2130         }
2131
2132         fmkey.lfik_oa.o_valid = OBD_MD_FLID | OBD_MD_FLGROUP;
2133         obdo_from_inode(&fmkey.lfik_oa, inode, OBD_MD_FLSIZE);
2134         obdo_set_parent_fid(&fmkey.lfik_oa, &ll_i2info(inode)->lli_fid);
2135
2136         /* If filesize is 0, then there would be no objects for mapping */
2137         if (fmkey.lfik_oa.o_size == 0) {
2138                 fiemap->fm_mapped_extents = 0;
2139                 GOTO(out, rc = 0);
2140         }
2141
2142         fmkey.lfik_fiemap = *fiemap;
2143
2144         rc = cl_object_fiemap(env, ll_i2info(inode)->lli_clob,
2145                               &fmkey, fiemap, &num_bytes);
2146 out:
2147         cl_env_put(env, &refcheck);
2148         RETURN(rc);
2149 }
2150
2151 int ll_fid2path(struct inode *inode, void __user *arg)
2152 {
2153         struct obd_export       *exp = ll_i2mdexp(inode);
2154         const struct getinfo_fid2path __user *gfin = arg;
2155         __u32                    pathlen;
2156         struct getinfo_fid2path *gfout;
2157         size_t                   outsize;
2158         int                      rc;
2159
2160         ENTRY;
2161
2162         if (!cfs_capable(CFS_CAP_DAC_READ_SEARCH) &&
2163             !(ll_i2sbi(inode)->ll_flags & LL_SBI_USER_FID2PATH))
2164                 RETURN(-EPERM);
2165
2166         /* Only need to get the buflen */
2167         if (get_user(pathlen, &gfin->gf_pathlen))
2168                 RETURN(-EFAULT);
2169
2170         if (pathlen > PATH_MAX)
2171                 RETURN(-EINVAL);
2172
2173         outsize = sizeof(*gfout) + pathlen;
2174         OBD_ALLOC(gfout, outsize);
2175         if (gfout == NULL)
2176                 RETURN(-ENOMEM);
2177
2178         if (copy_from_user(gfout, arg, sizeof(*gfout)))
2179                 GOTO(gf_free, rc = -EFAULT);
2180         /* append root FID after gfout to let MDT know the root FID so that it
2181          * can lookup the correct path, this is mainly for fileset.
2182          * old server without fileset mount support will ignore this. */
2183         *gfout->gf_u.gf_root_fid = *ll_inode2fid(inode);
2184
2185         /* Call mdc_iocontrol */
2186         rc = obd_iocontrol(OBD_IOC_FID2PATH, exp, outsize, gfout, NULL);
2187         if (rc != 0)
2188                 GOTO(gf_free, rc);
2189
2190         if (copy_to_user(arg, gfout, outsize))
2191                 rc = -EFAULT;
2192
2193 gf_free:
2194         OBD_FREE(gfout, outsize);
2195         RETURN(rc);
2196 }
2197
2198 static int
2199 ll_ioc_data_version(struct inode *inode, struct ioc_data_version *ioc)
2200 {
2201         struct cl_object *obj = ll_i2info(inode)->lli_clob;
2202         struct lu_env *env;
2203         struct cl_io *io;
2204         __u16  refcheck;
2205         int result;
2206
2207         ENTRY;
2208
2209         ioc->idv_version = 0;
2210         ioc->idv_layout_version = UINT_MAX;
2211
2212         /* If no file object initialized, we consider its version is 0. */
2213         if (obj == NULL)
2214                 RETURN(0);
2215
2216         env = cl_env_get(&refcheck);
2217         if (IS_ERR(env))
2218                 RETURN(PTR_ERR(env));
2219
2220         io = vvp_env_thread_io(env);
2221         io->ci_obj = obj;
2222         io->u.ci_data_version.dv_data_version = 0;
2223         io->u.ci_data_version.dv_layout_version = UINT_MAX;
2224         io->u.ci_data_version.dv_flags = ioc->idv_flags;
2225
2226 restart:
2227         if (cl_io_init(env, io, CIT_DATA_VERSION, io->ci_obj) == 0)
2228                 result = cl_io_loop(env, io);
2229         else
2230                 result = io->ci_result;
2231
2232         ioc->idv_version = io->u.ci_data_version.dv_data_version;
2233         ioc->idv_layout_version = io->u.ci_data_version.dv_layout_version;
2234
2235         cl_io_fini(env, io);
2236
2237         if (unlikely(io->ci_need_restart))
2238                 goto restart;
2239
2240         cl_env_put(env, &refcheck);
2241
2242         RETURN(result);
2243 }
2244
2245 /*
2246  * Read the data_version for inode.
2247  *
2248  * This value is computed using stripe object version on OST.
2249  * Version is computed using server side locking.
2250  *
2251  * @param flags if do sync on the OST side;
2252  *              0: no sync
2253  *              LL_DV_RD_FLUSH: flush dirty pages, LCK_PR on OSTs
2254  *              LL_DV_WR_FLUSH: drop all caching pages, LCK_PW on OSTs
2255  */
2256 int ll_data_version(struct inode *inode, __u64 *data_version, int flags)
2257 {
2258         struct ioc_data_version ioc = { .idv_flags = flags };
2259         int rc;
2260
2261         rc = ll_ioc_data_version(inode, &ioc);
2262         if (!rc)
2263                 *data_version = ioc.idv_version;
2264
2265         return rc;
2266 }
2267
2268 /*
2269  * Trigger a HSM release request for the provided inode.
2270  */
2271 int ll_hsm_release(struct inode *inode)
2272 {
2273         struct lu_env *env;
2274         struct obd_client_handle *och = NULL;
2275         __u64 data_version = 0;
2276         int rc;
2277         __u16 refcheck;
2278         ENTRY;
2279
2280         CDEBUG(D_INODE, "%s: Releasing file "DFID".\n",
2281                ll_get_fsname(inode->i_sb, NULL, 0),
2282                PFID(&ll_i2info(inode)->lli_fid));
2283
2284         och = ll_lease_open(inode, NULL, FMODE_WRITE, MDS_OPEN_RELEASE);
2285         if (IS_ERR(och))
2286                 GOTO(out, rc = PTR_ERR(och));
2287
2288         /* Grab latest data_version and [am]time values */
2289         rc = ll_data_version(inode, &data_version, LL_DV_WR_FLUSH);
2290         if (rc != 0)
2291                 GOTO(out, rc);
2292
2293         env = cl_env_get(&refcheck);
2294         if (IS_ERR(env))
2295                 GOTO(out, rc = PTR_ERR(env));
2296
2297         rc = ll_merge_attr(env, inode);
2298         cl_env_put(env, &refcheck);
2299
2300         /* If error happen, we have the wrong size for a file.
2301          * Don't release it.
2302          */
2303         if (rc != 0)
2304                 GOTO(out, rc);
2305
2306         /* Release the file.
2307          * NB: lease lock handle is released in mdc_hsm_release_pack() because
2308          * we still need it to pack l_remote_handle to MDT. */
2309         rc = ll_close_inode_openhandle(inode, och, MDS_HSM_RELEASE,
2310                                        &data_version);
2311         och = NULL;
2312
2313         EXIT;
2314 out:
2315         if (och != NULL && !IS_ERR(och)) /* close the file */
2316                 ll_lease_close(och, inode, NULL);
2317
2318         return rc;
2319 }
2320
2321 struct ll_swap_stack {
2322         __u64                    dv1;
2323         __u64                    dv2;
2324         struct inode            *inode1;
2325         struct inode            *inode2;
2326         bool                     check_dv1;
2327         bool                     check_dv2;
2328 };
2329
2330 static int ll_swap_layouts(struct file *file1, struct file *file2,
2331                            struct lustre_swap_layouts *lsl)
2332 {
2333         struct mdc_swap_layouts  msl;
2334         struct md_op_data       *op_data;
2335         __u32                    gid;
2336         __u64                    dv;
2337         struct ll_swap_stack    *llss = NULL;
2338         int                      rc;
2339
2340         OBD_ALLOC_PTR(llss);
2341         if (llss == NULL)
2342                 RETURN(-ENOMEM);
2343
2344         llss->inode1 = file_inode(file1);
2345         llss->inode2 = file_inode(file2);
2346
2347         rc = ll_check_swap_layouts_validity(llss->inode1, llss->inode2);
2348         if (rc < 0)
2349                 GOTO(free, rc);
2350
2351         /* we use 2 bool because it is easier to swap than 2 bits */
2352         if (lsl->sl_flags & SWAP_LAYOUTS_CHECK_DV1)
2353                 llss->check_dv1 = true;
2354
2355         if (lsl->sl_flags & SWAP_LAYOUTS_CHECK_DV2)
2356                 llss->check_dv2 = true;
2357
2358         /* we cannot use lsl->sl_dvX directly because we may swap them */
2359         llss->dv1 = lsl->sl_dv1;
2360         llss->dv2 = lsl->sl_dv2;
2361
2362         rc = lu_fid_cmp(ll_inode2fid(llss->inode1), ll_inode2fid(llss->inode2));
2363         if (rc == 0) /* same file, done! */
2364                 GOTO(free, rc);
2365
2366         if (rc < 0) { /* sequentialize it */
2367                 swap(llss->inode1, llss->inode2);
2368                 swap(file1, file2);
2369                 swap(llss->dv1, llss->dv2);
2370                 swap(llss->check_dv1, llss->check_dv2);
2371         }
2372
2373         gid = lsl->sl_gid;
2374         if (gid != 0) { /* application asks to flush dirty cache */
2375                 rc = ll_get_grouplock(llss->inode1, file1, gid);
2376                 if (rc < 0)
2377                         GOTO(free, rc);
2378
2379                 rc = ll_get_grouplock(llss->inode2, file2, gid);
2380                 if (rc < 0) {
2381                         ll_put_grouplock(llss->inode1, file1, gid);
2382                         GOTO(free, rc);
2383                 }
2384         }
2385
2386         /* ultimate check, before swaping the layouts we check if
2387          * dataversion has changed (if requested) */
2388         if (llss->check_dv1) {
2389                 rc = ll_data_version(llss->inode1, &dv, 0);
2390                 if (rc)
2391                         GOTO(putgl, rc);
2392                 if (dv != llss->dv1)
2393                         GOTO(putgl, rc = -EAGAIN);
2394         }
2395
2396         if (llss->check_dv2) {
2397                 rc = ll_data_version(llss->inode2, &dv, 0);
2398                 if (rc)
2399                         GOTO(putgl, rc);
2400                 if (dv != llss->dv2)
2401                         GOTO(putgl, rc = -EAGAIN);
2402         }
2403
2404         /* struct md_op_data is used to send the swap args to the mdt
2405          * only flags is missing, so we use struct mdc_swap_layouts
2406          * through the md_op_data->op_data */
2407         /* flags from user space have to be converted before they are send to
2408          * server, no flag is sent today, they are only used on the client */
2409         msl.msl_flags = 0;
2410         rc = -ENOMEM;
2411         op_data = ll_prep_md_op_data(NULL, llss->inode1, llss->inode2, NULL, 0,
2412                                      0, LUSTRE_OPC_ANY, &msl);
2413         if (IS_ERR(op_data))
2414                 GOTO(free, rc = PTR_ERR(op_data));
2415
2416         rc = obd_iocontrol(LL_IOC_LOV_SWAP_LAYOUTS, ll_i2mdexp(llss->inode1),
2417                            sizeof(*op_data), op_data, NULL);
2418         ll_finish_md_op_data(op_data);
2419
2420         if (rc < 0)
2421                 GOTO(putgl, rc);
2422
2423 putgl:
2424         if (gid != 0) {
2425                 ll_put_grouplock(llss->inode2, file2, gid);
2426                 ll_put_grouplock(llss->inode1, file1, gid);
2427         }
2428
2429 free:
2430         if (llss != NULL)
2431                 OBD_FREE_PTR(llss);
2432
2433         RETURN(rc);
2434 }
2435
2436 int ll_hsm_state_set(struct inode *inode, struct hsm_state_set *hss)
2437 {
2438         struct md_op_data       *op_data;
2439         int                      rc;
2440         ENTRY;
2441
2442         /* Detect out-of range masks */
2443         if ((hss->hss_setmask | hss->hss_clearmask) & ~HSM_FLAGS_MASK)
2444                 RETURN(-EINVAL);
2445
2446         /* Non-root users are forbidden to set or clear flags which are
2447          * NOT defined in HSM_USER_MASK. */
2448         if (((hss->hss_setmask | hss->hss_clearmask) & ~HSM_USER_MASK) &&
2449             !cfs_capable(CFS_CAP_SYS_ADMIN))
2450                 RETURN(-EPERM);
2451
2452         /* Detect out-of range archive id */
2453         if ((hss->hss_valid & HSS_ARCHIVE_ID) &&
2454             (hss->hss_archive_id > LL_HSM_MAX_ARCHIVE))
2455                 RETURN(-EINVAL);
2456
2457         op_data = ll_prep_md_op_data(NULL, inode, NULL, NULL, 0, 0,
2458                                      LUSTRE_OPC_ANY, hss);
2459         if (IS_ERR(op_data))
2460                 RETURN(PTR_ERR(op_data));
2461
2462         rc = obd_iocontrol(LL_IOC_HSM_STATE_SET, ll_i2mdexp(inode),
2463                            sizeof(*op_data), op_data, NULL);
2464
2465         ll_finish_md_op_data(op_data);
2466
2467         RETURN(rc);
2468 }
2469
2470 static int ll_hsm_import(struct inode *inode, struct file *file,
2471                          struct hsm_user_import *hui)
2472 {
2473         struct hsm_state_set    *hss = NULL;
2474         struct iattr            *attr = NULL;
2475         int                      rc;
2476         ENTRY;
2477
2478         if (!S_ISREG(inode->i_mode))
2479                 RETURN(-EINVAL);
2480
2481         /* set HSM flags */
2482         OBD_ALLOC_PTR(hss);
2483         if (hss == NULL)
2484                 GOTO(out, rc = -ENOMEM);
2485
2486         hss->hss_valid = HSS_SETMASK | HSS_ARCHIVE_ID;
2487         hss->hss_archive_id = hui->hui_archive_id;
2488         hss->hss_setmask = HS_ARCHIVED | HS_EXISTS | HS_RELEASED;
2489         rc = ll_hsm_state_set(inode, hss);
2490         if (rc != 0)
2491                 GOTO(out, rc);
2492
2493         OBD_ALLOC_PTR(attr);
2494         if (attr == NULL)
2495                 GOTO(out, rc = -ENOMEM);
2496
2497         attr->ia_mode = hui->hui_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
2498         attr->ia_mode |= S_IFREG;
2499         attr->ia_uid = make_kuid(&init_user_ns, hui->hui_uid);
2500         attr->ia_gid = make_kgid(&init_user_ns, hui->hui_gid);
2501         attr->ia_size = hui->hui_size;
2502         attr->ia_mtime.tv_sec = hui->hui_mtime;
2503         attr->ia_mtime.tv_nsec = hui->hui_mtime_ns;
2504         attr->ia_atime.tv_sec = hui->hui_atime;
2505         attr->ia_atime.tv_nsec = hui->hui_atime_ns;
2506
2507         attr->ia_valid = ATTR_SIZE | ATTR_MODE | ATTR_FORCE |
2508                          ATTR_UID | ATTR_GID |
2509                          ATTR_MTIME | ATTR_MTIME_SET |
2510                          ATTR_ATIME | ATTR_ATIME_SET;
2511
2512         inode_lock(inode);
2513
2514         rc = ll_setattr_raw(file_dentry(file), attr, true);
2515         if (rc == -ENODATA)
2516                 rc = 0;
2517
2518         inode_unlock(inode);
2519
2520 out:
2521         if (hss != NULL)
2522                 OBD_FREE_PTR(hss);
2523
2524         if (attr != NULL)
2525                 OBD_FREE_PTR(attr);
2526
2527         RETURN(rc);
2528 }
2529
2530 static inline long ll_lease_type_from_fmode(fmode_t fmode)
2531 {
2532         return ((fmode & FMODE_READ) ? LL_LEASE_RDLCK : 0) |
2533                ((fmode & FMODE_WRITE) ? LL_LEASE_WRLCK : 0);
2534 }
2535
2536 static int ll_file_futimes_3(struct file *file, const struct ll_futimes_3 *lfu)
2537 {
2538         struct inode *inode = file_inode(file);
2539         struct iattr ia = {
2540                 .ia_valid = ATTR_ATIME | ATTR_ATIME_SET |
2541                             ATTR_MTIME | ATTR_MTIME_SET |
2542                             ATTR_CTIME | ATTR_CTIME_SET,
2543                 .ia_atime = {
2544                         .tv_sec = lfu->lfu_atime_sec,
2545                         .tv_nsec = lfu->lfu_atime_nsec,
2546                 },
2547                 .ia_mtime = {
2548                         .tv_sec = lfu->lfu_mtime_sec,
2549                         .tv_nsec = lfu->lfu_mtime_nsec,
2550                 },
2551                 .ia_ctime = {
2552                         .tv_sec = lfu->lfu_ctime_sec,
2553                         .tv_nsec = lfu->lfu_ctime_nsec,
2554                 },
2555         };
2556         int rc;
2557         ENTRY;
2558
2559         if (!capable(CAP_SYS_ADMIN))
2560                 RETURN(-EPERM);
2561
2562         if (!S_ISREG(inode->i_mode))
2563                 RETURN(-EINVAL);
2564
2565         inode_lock(inode);
2566         rc = ll_setattr_raw(file_dentry(file), &ia, false);
2567         inode_unlock(inode);
2568
2569         RETURN(rc);
2570 }
2571
2572 static enum cl_lock_mode cl_mode_user_to_kernel(enum lock_mode_user mode)
2573 {
2574         switch (mode) {
2575         case MODE_READ_USER:
2576                 return CLM_READ;
2577         case MODE_WRITE_USER:
2578                 return CLM_WRITE;
2579         default:
2580                 return -EINVAL;
2581         }
2582 }
2583
2584 static const char *const user_lockname[] = LOCK_MODE_NAMES;
2585
2586 /* Used to allow the upper layers of the client to request an LDLM lock
2587  * without doing an actual read or write.
2588  *
2589  * Used for ladvise lockahead to manually request specific locks.
2590  *
2591  * \param[in] file      file this ladvise lock request is on
2592  * \param[in] ladvise   ladvise struct describing this lock request
2593  *
2594  * \retval 0            success, no detailed result available (sync requests
2595  *                      and requests sent to the server [not handled locally]
2596  *                      cannot return detailed results)
2597  * \retval LLA_RESULT_{SAME,DIFFERENT} - detailed result of the lock request,
2598  *                                       see definitions for details.
2599  * \retval negative     negative errno on error
2600  */
2601 int ll_file_lock_ahead(struct file *file, struct llapi_lu_ladvise *ladvise)
2602 {
2603         struct lu_env *env = NULL;
2604         struct cl_io *io  = NULL;
2605         struct cl_lock *lock = NULL;
2606         struct cl_lock_descr *descr = NULL;
2607         struct dentry *dentry = file->f_path.dentry;
2608         struct inode *inode = dentry->d_inode;
2609         enum cl_lock_mode cl_mode;
2610         off_t start = ladvise->lla_start;
2611         off_t end = ladvise->lla_end;
2612         int result;
2613         __u16 refcheck;
2614
2615         ENTRY;
2616
2617         CDEBUG(D_VFSTRACE, "Lock request: file=%.*s, inode=%p, mode=%s "
2618                "start=%llu, end=%llu\n", dentry->d_name.len,
2619                dentry->d_name.name, dentry->d_inode,
2620                user_lockname[ladvise->lla_lockahead_mode], (__u64) start,
2621                (__u64) end);
2622
2623         cl_mode = cl_mode_user_to_kernel(ladvise->lla_lockahead_mode);
2624         if (cl_mode < 0)
2625                 GOTO(out, result = cl_mode);
2626
2627         /* Get IO environment */
2628         result = cl_io_get(inode, &env, &io, &refcheck);
2629         if (result <= 0)
2630                 GOTO(out, result);
2631
2632         result = cl_io_init(env, io, CIT_MISC, io->ci_obj);
2633         if (result > 0) {
2634                 /*
2635                  * nothing to do for this io. This currently happens when
2636                  * stripe sub-object's are not yet created.
2637                  */
2638                 result = io->ci_result;
2639         } else if (result == 0) {
2640                 lock = vvp_env_lock(env);
2641                 descr = &lock->cll_descr;
2642
2643                 descr->cld_obj   = io->ci_obj;
2644                 /* Convert byte offsets to pages */
2645                 descr->cld_start = cl_index(io->ci_obj, start);
2646                 descr->cld_end   = cl_index(io->ci_obj, end);
2647                 descr->cld_mode  = cl_mode;
2648                 /* CEF_MUST is used because we do not want to convert a
2649                  * lockahead request to a lockless lock */
2650                 descr->cld_enq_flags = CEF_MUST | CEF_LOCK_NO_EXPAND |
2651                                        CEF_NONBLOCK;
2652
2653                 if (ladvise->lla_peradvice_flags & LF_ASYNC)
2654                         descr->cld_enq_flags |= CEF_SPECULATIVE;
2655
2656                 result = cl_lock_request(env, io, lock);
2657
2658                 /* On success, we need to release the lock */
2659                 if (result >= 0)
2660                         cl_lock_release(env, lock);
2661         }
2662         cl_io_fini(env, io);
2663         cl_env_put(env, &refcheck);
2664
2665         /* -ECANCELED indicates a matching lock with a different extent
2666          * was already present, and -EEXIST indicates a matching lock
2667          * on exactly the same extent was already present.
2668          * We convert them to positive values for userspace to make
2669          * recognizing true errors easier.
2670          * Note we can only return these detailed results on async requests,
2671          * as sync requests look the same as i/o requests for locking. */
2672         if (result == -ECANCELED)
2673                 result = LLA_RESULT_DIFFERENT;
2674         else if (result == -EEXIST)
2675                 result = LLA_RESULT_SAME;
2676
2677 out:
2678         RETURN(result);
2679 }
2680 static const char *const ladvise_names[] = LU_LADVISE_NAMES;
2681
2682 static int ll_ladvise_sanity(struct inode *inode,
2683                              struct llapi_lu_ladvise *ladvise)
2684 {
2685         enum lu_ladvise_type advice = ladvise->lla_advice;
2686         /* Note the peradvice flags is a 32 bit field, so per advice flags must
2687          * be in the first 32 bits of enum ladvise_flags */
2688         __u32 flags = ladvise->lla_peradvice_flags;
2689         /* 3 lines at 80 characters per line, should be plenty */
2690         int rc = 0;
2691
2692         if (advice > LU_LADVISE_MAX || advice == LU_LADVISE_INVALID) {
2693                 rc = -EINVAL;
2694                 CDEBUG(D_VFSTRACE, "%s: advice with value '%d' not recognized,"
2695                        "last supported advice is %s (value '%d'): rc = %d\n",
2696                        ll_get_fsname(inode->i_sb, NULL, 0), advice,
2697                        ladvise_names[LU_LADVISE_MAX-1], LU_LADVISE_MAX-1, rc);
2698                 GOTO(out, rc);
2699         }
2700
2701         /* Per-advice checks */
2702         switch (advice) {
2703         case LU_LADVISE_LOCKNOEXPAND:
2704                 if (flags & ~LF_LOCKNOEXPAND_MASK) {
2705                         rc = -EINVAL;
2706                         CDEBUG(D_VFSTRACE, "%s: Invalid flags (%x) for %s: "
2707                                "rc = %d\n",
2708                                ll_get_fsname(inode->i_sb, NULL, 0), flags,
2709                                ladvise_names[advice], rc);
2710                         GOTO(out, rc);
2711                 }
2712                 break;
2713         case LU_LADVISE_LOCKAHEAD:
2714                 /* Currently only READ and WRITE modes can be requested */
2715                 if (ladvise->lla_lockahead_mode >= MODE_MAX_USER ||
2716                     ladvise->lla_lockahead_mode == 0) {
2717                         rc = -EINVAL;
2718                         CDEBUG(D_VFSTRACE, "%s: Invalid mode (%d) for %s: "
2719                                "rc = %d\n",
2720                                ll_get_fsname(inode->i_sb, NULL, 0),
2721                                ladvise->lla_lockahead_mode,
2722                                ladvise_names[advice], rc);
2723                         GOTO(out, rc);
2724                 }
2725         case LU_LADVISE_WILLREAD:
2726         case LU_LADVISE_DONTNEED:
2727         default:
2728                 /* Note fall through above - These checks apply to all advices
2729                  * except LOCKNOEXPAND */
2730                 if (flags & ~LF_DEFAULT_MASK) {
2731                         rc = -EINVAL;
2732                         CDEBUG(D_VFSTRACE, "%s: Invalid flags (%x) for %s: "
2733                                "rc = %d\n",
2734                                ll_get_fsname(inode->i_sb, NULL, 0), flags,
2735                                ladvise_names[advice], rc);
2736                         GOTO(out, rc);
2737                 }
2738                 if (ladvise->lla_start >= ladvise->lla_end) {
2739                         rc = -EINVAL;
2740                         CDEBUG(D_VFSTRACE, "%s: Invalid range (%llu to %llu) "
2741                                "for %s: rc = %d\n",
2742                                ll_get_fsname(inode->i_sb, NULL, 0),
2743                                ladvise->lla_start, ladvise->lla_end,
2744                                ladvise_names[advice], rc);
2745                         GOTO(out, rc);
2746                 }
2747                 break;
2748         }
2749
2750 out:
2751         return rc;
2752 }
2753 #undef ERRSIZE
2754
2755 /*
2756  * Give file access advices
2757  *
2758  * The ladvise interface is similar to Linux fadvise() system call, except it
2759  * forwards the advices directly from Lustre client to server. The server side
2760  * codes will apply appropriate read-ahead and caching techniques for the
2761  * corresponding files.
2762  *
2763  * A typical workload for ladvise is e.g. a bunch of different clients are
2764  * doing small random reads of a file, so prefetching pages into OSS cache
2765  * with big linear reads before the random IO is a net benefit. Fetching
2766  * all that data into each client cache with fadvise() may not be, due to
2767  * much more data being sent to the client.
2768  */
2769 static int ll_ladvise(struct inode *inode, struct file *file, __u64 flags,
2770                       struct llapi_lu_ladvise *ladvise)
2771 {
2772         struct lu_env *env;
2773         struct cl_io *io;
2774         struct cl_ladvise_io *lio;
2775         int rc;
2776         __u16 refcheck;
2777         ENTRY;
2778
2779         env = cl_env_get(&refcheck);
2780         if (IS_ERR(env))
2781                 RETURN(PTR_ERR(env));
2782
2783         io = vvp_env_thread_io(env);
2784         io->ci_obj = ll_i2info(inode)->lli_clob;
2785
2786         /* initialize parameters for ladvise */
2787         lio = &io->u.ci_ladvise;
2788         lio->li_start = ladvise->lla_start;
2789         lio->li_end = ladvise->lla_end;
2790         lio->li_fid = ll_inode2fid(inode);
2791         lio->li_advice = ladvise->lla_advice;
2792         lio->li_flags = flags;
2793
2794         if (cl_io_init(env, io, CIT_LADVISE, io->ci_obj) == 0)
2795                 rc = cl_io_loop(env, io);
2796         else
2797                 rc = io->ci_result;
2798
2799         cl_io_fini(env, io);
2800         cl_env_put(env, &refcheck);
2801         RETURN(rc);
2802 }
2803
2804 static int ll_lock_noexpand(struct file *file, int flags)
2805 {
2806         struct ll_file_data *fd = LUSTRE_FPRIVATE(file);
2807
2808         fd->ll_lock_no_expand = !(flags & LF_UNSET);
2809
2810         return 0;
2811 }
2812
2813 int ll_ioctl_fsgetxattr(struct inode *inode, unsigned int cmd,
2814                         unsigned long arg)
2815 {
2816         struct fsxattr fsxattr;
2817
2818         if (copy_from_user(&fsxattr,
2819                            (const struct fsxattr __user *)arg,
2820                            sizeof(fsxattr)))
2821                 RETURN(-EFAULT);
2822
2823         fsxattr.fsx_xflags = ll_inode_to_ext_flags(inode->i_flags);
2824         fsxattr.fsx_projid = ll_i2info(inode)->lli_projid;
2825         if (copy_to_user((struct fsxattr __user *)arg,
2826                          &fsxattr, sizeof(fsxattr)))
2827                 RETURN(-EFAULT);
2828
2829         RETURN(0);
2830 }
2831
2832 int ll_ioctl_fssetxattr(struct inode *inode, unsigned int cmd,
2833                         unsigned long arg)
2834 {
2835
2836         struct md_op_data *op_data;
2837         struct ptlrpc_request *req = NULL;
2838         int rc = 0;
2839         struct fsxattr fsxattr;
2840         struct cl_object *obj;
2841
2842         /* only root could change project ID */
2843         if (!cfs_capable(CFS_CAP_SYS_ADMIN))
2844                 RETURN(-EPERM);
2845
2846         op_data = ll_prep_md_op_data(NULL, inode, NULL, NULL, 0, 0,
2847                                      LUSTRE_OPC_ANY, NULL);
2848         if (IS_ERR(op_data))
2849                 RETURN(PTR_ERR(op_data));
2850
2851         if (copy_from_user(&fsxattr,
2852                            (const struct fsxattr __user *)arg,
2853                            sizeof(fsxattr)))
2854                 GOTO(out_fsxattr1, rc = -EFAULT);
2855
2856         op_data->op_attr_flags = fsxattr.fsx_xflags;
2857         op_data->op_projid = fsxattr.fsx_projid;
2858         op_data->op_attr.ia_valid |= (MDS_ATTR_PROJID | ATTR_ATTR_FLAG);
2859         rc = md_setattr(ll_i2sbi(inode)->ll_md_exp, op_data, NULL,
2860                         0, &req);
2861         ptlrpc_req_finished(req);
2862
2863         obj = ll_i2info(inode)->lli_clob;
2864         if (obj) {
2865                 struct iattr *attr;
2866
2867                 inode->i_flags = ll_ext_to_inode_flags(fsxattr.fsx_xflags);
2868                 OBD_ALLOC_PTR(attr);
2869                 if (attr == NULL)
2870                         GOTO(out_fsxattr1, rc = -ENOMEM);
2871                 attr->ia_valid = ATTR_ATTR_FLAG;
2872                 rc = cl_setattr_ost(obj, attr, fsxattr.fsx_xflags);
2873
2874                 OBD_FREE_PTR(attr);
2875         }
2876 out_fsxattr1:
2877         ll_finish_md_op_data(op_data);
2878         RETURN(rc);
2879 }
2880
2881 static long ll_file_unlock_lease(struct file *file, struct ll_ioc_lease *ioc,
2882                                  unsigned long arg)
2883 {
2884         struct inode            *inode = file_inode(file);
2885         struct ll_file_data     *fd = LUSTRE_FPRIVATE(file);
2886         struct ll_inode_info    *lli = ll_i2info(inode);
2887         struct obd_client_handle *och = NULL;
2888         bool lease_broken;
2889         fmode_t fmode = 0;
2890         enum mds_op_bias bias = 0;
2891         struct file *layout_file = NULL;
2892         void *data = NULL;
2893         size_t data_size = 0;
2894         long rc;
2895         ENTRY;
2896
2897         mutex_lock(&lli->lli_och_mutex);
2898         if (fd->fd_lease_och != NULL) {
2899                 och = fd->fd_lease_och;
2900                 fd->fd_lease_och = NULL;
2901         }
2902         mutex_unlock(&lli->lli_och_mutex);
2903
2904         if (och == NULL)
2905                 GOTO(out, rc = -ENOLCK);
2906
2907         fmode = och->och_flags;
2908
2909         switch (ioc->lil_flags) {
2910         case LL_LEASE_RESYNC_DONE:
2911                 if (ioc->lil_count > IOC_IDS_MAX)
2912                         GOTO(out, rc = -EINVAL);
2913
2914                 data_size = offsetof(typeof(*ioc), lil_ids[ioc->lil_count]);
2915                 OBD_ALLOC(data, data_size);
2916                 if (!data)
2917                         GOTO(out, rc = -ENOMEM);
2918
2919                 if (copy_from_user(data, (void __user *)arg, data_size))
2920                         GOTO(out, rc = -EFAULT);
2921
2922                 bias = MDS_CLOSE_RESYNC_DONE;
2923                 break;
2924         case LL_LEASE_LAYOUT_MERGE: {
2925                 int fd;
2926
2927                 if (ioc->lil_count != 1)
2928                         GOTO(out, rc = -EINVAL);
2929
2930                 arg += sizeof(*ioc);
2931                 if (copy_from_user(&fd, (void __user *)arg, sizeof(__u32)))
2932                         GOTO(out, rc = -EFAULT);
2933
2934                 layout_file = fget(fd);
2935                 if (!layout_file)
2936                         GOTO(out, rc = -EBADF);
2937
2938                 if ((file->f_flags & O_ACCMODE) == O_RDONLY ||
2939                                 (layout_file->f_flags & O_ACCMODE) == O_RDONLY)
2940                         GOTO(out, rc = -EPERM);
2941
2942                 data = file_inode(layout_file);
2943                 bias = MDS_CLOSE_LAYOUT_MERGE;
2944                 break;
2945         }
2946         default:
2947                 /* without close intent */
2948                 break;
2949         }
2950
2951         rc = ll_lease_close_intent(och, inode, &lease_broken, bias, data);
2952         if (rc < 0)
2953                 GOTO(out, rc);
2954
2955         rc = ll_lease_och_release(inode, file);
2956         if (rc < 0)
2957                 GOTO(out, rc);
2958
2959         if (lease_broken)
2960                 fmode = 0;
2961         EXIT;
2962
2963 out:
2964         switch (ioc->lil_flags) {
2965         case LL_LEASE_RESYNC_DONE:
2966                 if (data)
2967                         OBD_FREE(data, data_size);
2968                 break;
2969         case LL_LEASE_LAYOUT_MERGE:
2970                 if (layout_file)
2971                         fput(layout_file);
2972                 break;
2973         }
2974
2975         if (!rc)
2976                 rc = ll_lease_type_from_fmode(fmode);
2977         RETURN(rc);
2978 }
2979
2980 static long ll_file_set_lease(struct file *file, struct ll_ioc_lease *ioc,
2981                               unsigned long arg)
2982 {
2983         struct inode *inode = file_inode(file);
2984         struct ll_inode_info *lli = ll_i2info(inode);
2985         struct ll_file_data *fd = LUSTRE_FPRIVATE(file);
2986         struct obd_client_handle *och = NULL;
2987         __u64 open_flags = 0;
2988         bool lease_broken;
2989         fmode_t fmode;
2990         long rc;
2991         ENTRY;
2992
2993         switch (ioc->lil_mode) {
2994         case LL_LEASE_WRLCK:
2995                 if (!(file->f_mode & FMODE_WRITE))
2996                         RETURN(-EPERM);
2997                 fmode = FMODE_WRITE;
2998                 break;
2999         case LL_LEASE_RDLCK:
3000                 if (!(file->f_mode & FMODE_READ))
3001                         RETURN(-EPERM);
3002                 fmode = FMODE_READ;
3003                 break;
3004         case LL_LEASE_UNLCK:
3005                 RETURN(ll_file_unlock_lease(file, ioc, arg));
3006         default:
3007                 RETURN(-EINVAL);
3008         }
3009
3010         CDEBUG(D_INODE, "Set lease with mode %u\n", fmode);
3011
3012         /* apply for lease */
3013         if (ioc->lil_flags & LL_LEASE_RESYNC)
3014                 open_flags = MDS_OPEN_RESYNC;
3015         och = ll_lease_open(inode, file, fmode, open_flags);
3016         if (IS_ERR(och))
3017                 RETURN(PTR_ERR(och));
3018
3019         if (ioc->lil_flags & LL_LEASE_RESYNC) {
3020                 rc = ll_lease_file_resync(och, inode);
3021                 if (rc) {
3022                         ll_lease_close(och, inode, NULL);
3023                         RETURN(rc);
3024                 }
3025                 rc = ll_layout_refresh(inode, &fd->fd_layout_version);
3026                 if (rc) {
3027                         ll_lease_close(och, inode, NULL);
3028                         RETURN(rc);
3029                 }
3030         }
3031
3032         rc = 0;
3033         mutex_lock(&lli->lli_och_mutex);
3034         if (fd->fd_lease_och == NULL) {
3035                 fd->fd_lease_och = och;
3036                 och = NULL;
3037         }
3038         mutex_unlock(&lli->lli_och_mutex);
3039         if (och != NULL) {
3040                 /* impossible now that only excl is supported for now */
3041                 ll_lease_close(och, inode, &lease_broken);
3042                 rc = -EBUSY;
3043         }
3044         RETURN(rc);
3045 }
3046
3047 static long
3048 ll_file_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
3049 {
3050         struct inode            *inode = file_inode(file);
3051         struct ll_file_data     *fd = LUSTRE_FPRIVATE(file);
3052         int                      flags, rc;
3053         ENTRY;
3054
3055         CDEBUG(D_VFSTRACE, "VFS Op:inode="DFID"(%p), cmd=%x\n",
3056                PFID(ll_inode2fid(inode)), inode, cmd);
3057         ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_IOCTL, 1);
3058
3059         /* asm-ppc{,64} declares TCGETS, et. al. as type 't' not 'T' */
3060         if (_IOC_TYPE(cmd) == 'T' || _IOC_TYPE(cmd) == 't') /* tty ioctls */
3061                 RETURN(-ENOTTY);
3062
3063         switch(cmd) {
3064         case LL_IOC_GETFLAGS:
3065                 /* Get the current value of the file flags */
3066                 return put_user(fd->fd_flags, (int __user *)arg);
3067         case LL_IOC_SETFLAGS:
3068         case LL_IOC_CLRFLAGS:
3069                 /* Set or clear specific file flags */
3070                 /* XXX This probably needs checks to ensure the flags are
3071                  *     not abused, and to handle any flag side effects.
3072                  */
3073                 if (get_user(flags, (int __user *) arg))
3074                         RETURN(-EFAULT);
3075
3076                 if (cmd == LL_IOC_SETFLAGS) {
3077                         if ((flags & LL_FILE_IGNORE_LOCK) &&
3078                             !(file->f_flags & O_DIRECT)) {
3079                                 CERROR("%s: unable to disable locking on "
3080                                        "non-O_DIRECT file\n", current->comm);
3081                                 RETURN(-EINVAL);
3082                         }
3083
3084                         fd->fd_flags |= flags;
3085                 } else {
3086                         fd->fd_flags &= ~flags;
3087                 }
3088                 RETURN(0);
3089         case LL_IOC_LOV_SETSTRIPE:
3090         case LL_IOC_LOV_SETSTRIPE_NEW:
3091                 RETURN(ll_lov_setstripe(inode, file, (void __user *)arg));
3092         case LL_IOC_LOV_SETEA:
3093                 RETURN(ll_lov_setea(inode, file, (void __user *)arg));
3094         case LL_IOC_LOV_SWAP_LAYOUTS: {
3095                 struct file *file2;
3096                 struct lustre_swap_layouts lsl;
3097
3098                 if (copy_from_user(&lsl, (char __user *)arg,
3099                                    sizeof(struct lustre_swap_layouts)))
3100                         RETURN(-EFAULT);
3101
3102                 if ((file->f_flags & O_ACCMODE) == O_RDONLY)
3103                         RETURN(-EPERM);
3104
3105                 file2 = fget(lsl.sl_fd);
3106                 if (file2 == NULL)
3107                         RETURN(-EBADF);
3108
3109                 /* O_WRONLY or O_RDWR */
3110                 if ((file2->f_flags & O_ACCMODE) == O_RDONLY)
3111                         GOTO(out, rc = -EPERM);
3112
3113                 if (lsl.sl_flags & SWAP_LAYOUTS_CLOSE) {
3114                         struct inode                    *inode2;
3115                         struct ll_inode_info            *lli;
3116                         struct obd_client_handle        *och = NULL;
3117
3118                         lli = ll_i2info(inode);
3119                         mutex_lock(&lli->lli_och_mutex);
3120                         if (fd->fd_lease_och != NULL) {
3121                                 och = fd->fd_lease_och;
3122                                 fd->fd_lease_och = NULL;
3123                         }
3124                         mutex_unlock(&lli->lli_och_mutex);
3125                         if (och == NULL)
3126                                 GOTO(out, rc = -ENOLCK);
3127                         inode2 = file_inode(file2);
3128                         rc = ll_swap_layouts_close(och, inode, inode2);
3129                 } else {
3130                         rc = ll_swap_layouts(file, file2, &lsl);
3131                 }
3132 out:
3133                 fput(file2);
3134                 RETURN(rc);
3135         }
3136         case LL_IOC_LOV_GETSTRIPE:
3137         case LL_IOC_LOV_GETSTRIPE_NEW:
3138                 RETURN(ll_file_getstripe(inode, (void __user *)arg, 0));
3139         case FSFILT_IOC_GETFLAGS:
3140         case FSFILT_IOC_SETFLAGS:
3141                 RETURN(ll_iocontrol(inode, file, cmd, arg));
3142         case FSFILT_IOC_GETVERSION_OLD:
3143         case FSFILT_IOC_GETVERSION:
3144                 RETURN(put_user(inode->i_generation, (int __user *)arg));
3145         case LL_IOC_GROUP_LOCK:
3146                 RETURN(ll_get_grouplock(inode, file, arg));
3147         case LL_IOC_GROUP_UNLOCK:
3148                 RETURN(ll_put_grouplock(inode, file, arg));
3149         case IOC_OBD_STATFS:
3150                 RETURN(ll_obd_statfs(inode, (void __user *)arg));
3151
3152         /* We need to special case any other ioctls we want to handle,
3153          * to send them to the MDS/OST as appropriate and to properly
3154          * network encode the arg field.
3155         case FSFILT_IOC_SETVERSION_OLD:
3156         case FSFILT_IOC_SETVERSION:
3157         */
3158         case LL_IOC_FLUSHCTX:
3159                 RETURN(ll_flush_ctx(inode));
3160         case LL_IOC_PATH2FID: {
3161                 if (copy_to_user((void __user *)arg, ll_inode2fid(inode),
3162                                  sizeof(struct lu_fid)))
3163                         RETURN(-EFAULT);
3164
3165                 RETURN(0);
3166         }
3167         case LL_IOC_GETPARENT:
3168                 RETURN(ll_getparent(file, (struct getparent __user *)arg));
3169
3170         case OBD_IOC_FID2PATH:
3171                 RETURN(ll_fid2path(inode, (void __user *)arg));
3172         case LL_IOC_DATA_VERSION: {
3173                 struct ioc_data_version idv;
3174                 int rc;
3175
3176                 if (copy_from_user(&idv, (char __user *)arg, sizeof(idv)))
3177                         RETURN(-EFAULT);
3178
3179                 idv.idv_flags &= LL_DV_RD_FLUSH | LL_DV_WR_FLUSH;
3180                 rc = ll_ioc_data_version(inode, &idv);
3181
3182                 if (rc == 0 &&
3183                     copy_to_user((char __user *)arg, &idv, sizeof(idv)))
3184                         RETURN(-EFAULT);
3185
3186                 RETURN(rc);
3187         }
3188
3189         case LL_IOC_GET_MDTIDX: {
3190                 int mdtidx;
3191
3192                 mdtidx = ll_get_mdt_idx(inode);
3193                 if (mdtidx < 0)
3194                         RETURN(mdtidx);
3195
3196                 if (put_user((int)mdtidx, (int __user *)arg))
3197                         RETURN(-EFAULT);
3198
3199                 RETURN(0);
3200         }
3201         case OBD_IOC_GETDTNAME:
3202         case OBD_IOC_GETMDNAME:
3203                 RETURN(ll_get_obd_name(inode, cmd, arg));
3204         case LL_IOC_HSM_STATE_GET: {
3205                 struct md_op_data       *op_data;
3206                 struct hsm_user_state   *hus;
3207                 int                      rc;
3208
3209                 OBD_ALLOC_PTR(hus);
3210                 if (hus == NULL)
3211                         RETURN(-ENOMEM);
3212
3213                 op_data = ll_prep_md_op_data(NULL, inode, NULL, NULL, 0, 0,
3214                                              LUSTRE_OPC_ANY, hus);
3215                 if (IS_ERR(op_data)) {
3216                         OBD_FREE_PTR(hus);
3217                         RETURN(PTR_ERR(op_data));
3218                 }
3219
3220                 rc = obd_iocontrol(cmd, ll_i2mdexp(inode), sizeof(*op_data),
3221                                    op_data, NULL);
3222
3223                 if (copy_to_user((void __user *)arg, hus, sizeof(*hus)))
3224                         rc = -EFAULT;
3225
3226                 ll_finish_md_op_data(op_data);
3227                 OBD_FREE_PTR(hus);
3228                 RETURN(rc);
3229         }
3230         case LL_IOC_HSM_STATE_SET: {
3231                 struct hsm_state_set    *hss;
3232                 int                      rc;
3233
3234                 OBD_ALLOC_PTR(hss);
3235                 if (hss == NULL)
3236                         RETURN(-ENOMEM);
3237
3238                 if (copy_from_user(hss, (char __user *)arg, sizeof(*hss))) {
3239                         OBD_FREE_PTR(hss);
3240                         RETURN(-EFAULT);
3241                 }
3242
3243                 rc = ll_hsm_state_set(inode, hss);
3244
3245                 OBD_FREE_PTR(hss);
3246                 RETURN(rc);
3247         }
3248         case LL_IOC_HSM_ACTION: {
3249                 struct md_op_data               *op_data;
3250                 struct hsm_current_action       *hca;
3251                 int                              rc;
3252
3253                 OBD_ALLOC_PTR(hca);
3254                 if (hca == NULL)
3255                         RETURN(-ENOMEM);
3256
3257                 op_data = ll_prep_md_op_data(NULL, inode, NULL, NULL, 0, 0,
3258                                              LUSTRE_OPC_ANY, hca);
3259                 if (IS_ERR(op_data)) {
3260                         OBD_FREE_PTR(hca);
3261                         RETURN(PTR_ERR(op_data));
3262                 }
3263
3264                 rc = obd_iocontrol(cmd, ll_i2mdexp(inode), sizeof(*op_data),
3265                                    op_data, NULL);
3266
3267                 if (copy_to_user((char __user *)arg, hca, sizeof(*hca)))
3268                         rc = -EFAULT;
3269
3270                 ll_finish_md_op_data(op_data);
3271                 OBD_FREE_PTR(hca);
3272                 RETURN(rc);
3273         }
3274         case LL_IOC_SET_LEASE_OLD: {
3275                 struct ll_ioc_lease ioc = { .lil_mode = (__u32)arg };
3276
3277                 RETURN(ll_file_set_lease(file, &ioc, 0));
3278         }
3279         case LL_IOC_SET_LEASE: {
3280                 struct ll_ioc_lease ioc;
3281
3282                 if (copy_from_user(&ioc, (void __user *)arg, sizeof(ioc)))
3283                         RETURN(-EFAULT);
3284
3285                 RETURN(ll_file_set_lease(file, &ioc, arg));
3286         }
3287         case LL_IOC_GET_LEASE: {
3288                 struct ll_inode_info *lli = ll_i2info(inode);
3289                 struct ldlm_lock *lock = NULL;
3290                 fmode_t fmode = 0;
3291
3292                 mutex_lock(&lli->lli_och_mutex);
3293                 if (fd->fd_lease_och != NULL) {
3294                         struct obd_client_handle *och = fd->fd_lease_och;
3295
3296                         lock = ldlm_handle2lock(&och->och_lease_handle);
3297                         if (lock != NULL) {
3298                                 lock_res_and_lock(lock);
3299                                 if (!ldlm_is_cancel(lock))
3300                                         fmode = och->och_flags;
3301
3302                                 unlock_res_and_lock(lock);
3303                                 LDLM_LOCK_PUT(lock);
3304                         }
3305                 }
3306                 mutex_unlock(&lli->lli_och_mutex);
3307
3308                 RETURN(ll_lease_type_from_fmode(fmode));
3309         }
3310         case LL_IOC_HSM_IMPORT: {
3311                 struct hsm_user_import *hui;
3312
3313                 OBD_ALLOC_PTR(hui);
3314                 if (hui == NULL)
3315                         RETURN(-ENOMEM);
3316
3317                 if (copy_from_user(hui, (void __user *)arg, sizeof(*hui))) {
3318                         OBD_FREE_PTR(hui);
3319                         RETURN(-EFAULT);
3320                 }
3321
3322                 rc = ll_hsm_import(inode, file, hui);
3323
3324                 OBD_FREE_PTR(hui);
3325                 RETURN(rc);
3326         }
3327         case LL_IOC_FUTIMES_3: {
3328                 struct ll_futimes_3 lfu;
3329
3330                 if (copy_from_user(&lfu,
3331                                    (const struct ll_futimes_3 __user *)arg,
3332                                    sizeof(lfu)))
3333                         RETURN(-EFAULT);
3334
3335                 RETURN(ll_file_futimes_3(file, &lfu));
3336         }
3337         case LL_IOC_LADVISE: {
3338                 struct llapi_ladvise_hdr *k_ladvise_hdr;
3339                 struct llapi_ladvise_hdr __user *u_ladvise_hdr;
3340                 int i;
3341                 int num_advise;
3342                 int alloc_size = sizeof(*k_ladvise_hdr);
3343
3344                 rc = 0;
3345                 u_ladvise_hdr = (void __user *)arg;
3346                 OBD_ALLOC_PTR(k_ladvise_hdr);
3347                 if (k_ladvise_hdr == NULL)
3348                         RETURN(-ENOMEM);
3349
3350                 if (copy_from_user(k_ladvise_hdr, u_ladvise_hdr, alloc_size))
3351                         GOTO(out_ladvise, rc = -EFAULT);
3352
3353                 if (k_ladvise_hdr->lah_magic != LADVISE_MAGIC ||
3354                     k_ladvise_hdr->lah_count < 1)
3355                         GOTO(out_ladvise, rc = -EINVAL);
3356
3357                 num_advise = k_ladvise_hdr->lah_count;
3358                 if (num_advise >= LAH_COUNT_MAX)
3359                         GOTO(out_ladvise, rc = -EFBIG);
3360
3361                 OBD_FREE_PTR(k_ladvise_hdr);
3362                 alloc_size = offsetof(typeof(*k_ladvise_hdr),
3363                                       lah_advise[num_advise]);
3364                 OBD_ALLOC(k_ladvise_hdr, alloc_size);
3365                 if (k_ladvise_hdr == NULL)
3366                         RETURN(-ENOMEM);
3367
3368                 /*
3369                  * TODO: submit multiple advices to one server in a single RPC
3370                  */
3371                 if (copy_from_user(k_ladvise_hdr, u_ladvise_hdr, alloc_size))
3372                         GOTO(out_ladvise, rc = -EFAULT);
3373
3374                 for (i = 0; i < num_advise; i++) {
3375                         struct llapi_lu_ladvise *k_ladvise =
3376                                         &k_ladvise_hdr->lah_advise[i];
3377                         struct llapi_lu_ladvise __user *u_ladvise =
3378                                         &u_ladvise_hdr->lah_advise[i];
3379
3380                         rc = ll_ladvise_sanity(inode, k_ladvise);
3381                         if (rc)
3382                                 GOTO(out_ladvise, rc);
3383
3384                         switch (k_ladvise->lla_advice) {
3385                         case LU_LADVISE_LOCKNOEXPAND:
3386                                 rc = ll_lock_noexpand(file,
3387                                                k_ladvise->lla_peradvice_flags);
3388                                 GOTO(out_ladvise, rc);
3389                         case LU_LADVISE_LOCKAHEAD:
3390
3391                                 rc = ll_file_lock_ahead(file, k_ladvise);
3392
3393                                 if (rc < 0)
3394                                         GOTO(out_ladvise, rc);
3395
3396                                 if (put_user(rc,
3397                                              &u_ladvise->lla_lockahead_result))
3398                                         GOTO(out_ladvise, rc = -EFAULT);
3399                                 break;
3400                         default:
3401                                 rc = ll_ladvise(inode, file,
3402                                                 k_ladvise_hdr->lah_flags,
3403                                                 k_ladvise);
3404                                 if (rc)
3405                                         GOTO(out_ladvise, rc);
3406                                 break;
3407                         }
3408
3409                 }
3410
3411 out_ladvise:
3412                 OBD_FREE(k_ladvise_hdr, alloc_size);
3413                 RETURN(rc);
3414         }
3415         case LL_IOC_FLR_SET_MIRROR: {
3416                 /* mirror I/O must be direct to avoid polluting page cache
3417                  * by stale data. */
3418                 if (!(file->f_flags & O_DIRECT))
3419                         RETURN(-EINVAL);
3420
3421                 fd->fd_designated_mirror = (__u32)arg;
3422                 RETURN(0);
3423         }
3424         case LL_IOC_FSGETXATTR:
3425                 RETURN(ll_ioctl_fsgetxattr(inode, cmd, arg));
3426         case LL_IOC_FSSETXATTR:
3427                 RETURN(ll_ioctl_fssetxattr(inode, cmd, arg));
3428         case BLKSSZGET:
3429                 RETURN(put_user(PAGE_SIZE, (int __user *)arg));
3430         default:
3431                 RETURN(obd_iocontrol(cmd, ll_i2dtexp(inode), 0, NULL,
3432                                      (void __user *)arg));
3433         }
3434 }
3435
3436 #ifndef HAVE_FILE_LLSEEK_SIZE
3437 static inline loff_t
3438 llseek_execute(struct file *file, loff_t offset, loff_t maxsize)
3439 {
3440         if (offset < 0 && !(file->f_mode & FMODE_UNSIGNED_OFFSET))
3441                 return -EINVAL;
3442         if (offset > maxsize)
3443                 return -EINVAL;
3444
3445         if (offset != file->f_pos) {
3446                 file->f_pos = offset;
3447                 file->f_version = 0;
3448         }
3449         return offset;
3450 }
3451
3452 static loff_t
3453 generic_file_llseek_size(struct file *file, loff_t offset, int origin,
3454                 loff_t maxsize, loff_t eof)
3455 {
3456         struct inode *inode = file_inode(file);
3457
3458         switch (origin) {
3459         case SEEK_END:
3460                 offset += eof;
3461                 break;
3462         case SEEK_CUR:
3463                 /*
3464                  * Here we special-case the lseek(fd, 0, SEEK_CUR)
3465                  * position-querying operation.  Avoid rewriting the "same"
3466                  * f_pos value back to the file because a concurrent read(),
3467                  * write() or lseek() might have altered it
3468                  */
3469                 if (offset == 0)
3470                         return file->f_pos;
3471                 /*
3472                  * f_lock protects against read/modify/write race with other
3473                  * SEEK_CURs. Note that parallel writes and reads behave
3474                  * like SEEK_SET.
3475                  */
3476                 inode_lock(inode);
3477                 offset = llseek_execute(file, file->f_pos + offset, maxsize);
3478                 inode_unlock(inode);
3479                 return offset;
3480         case SEEK_DATA:
3481                 /*
3482                  * In the generic case the entire file is data, so as long as
3483                  * offset isn't at the end of the file then the offset is data.
3484                  */
3485                 if (offset >= eof)
3486                         return -ENXIO;
3487                 break;
3488         case SEEK_HOLE:
3489                 /*
3490                  * There is a virtual hole at the end of the file, so as long as
3491                  * offset isn't i_size or larger, return i_size.
3492                  */
3493                 if (offset >= eof)
3494                         return -ENXIO;
3495                 offset = eof;
3496                 break;
3497         }
3498
3499         return llseek_execute(file, offset, maxsize);
3500 }
3501 #endif
3502
3503 static loff_t ll_file_seek(struct file *file, loff_t offset, int origin)
3504 {
3505         struct inode *inode = file_inode(file);
3506         loff_t retval, eof = 0;
3507
3508         ENTRY;
3509         retval = offset + ((origin == SEEK_END) ? i_size_read(inode) :
3510                            (origin == SEEK_CUR) ? file->f_pos : 0);
3511         CDEBUG(D_VFSTRACE, "VFS Op:inode="DFID"(%p), to=%llu=%#llx(%d)\n",
3512                PFID(ll_inode2fid(inode)), inode, retval, retval,
3513                origin);
3514         ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_LLSEEK, 1);
3515
3516         if (origin == SEEK_END || origin == SEEK_HOLE || origin == SEEK_DATA) {
3517                 retval = ll_glimpse_size(inode);
3518                 if (retval != 0)
3519                         RETURN(retval);
3520                 eof = i_size_read(inode);
3521         }
3522
3523         retval = ll_generic_file_llseek_size(file, offset, origin,
3524                                           ll_file_maxbytes(inode), eof);
3525         RETURN(retval);
3526 }
3527
3528 static int ll_flush(struct file *file, fl_owner_t id)
3529 {
3530         struct inode *inode = file_inode(file);
3531         struct ll_inode_info *lli = ll_i2info(inode);
3532         struct ll_file_data *fd = LUSTRE_FPRIVATE(file);
3533         int rc, err;
3534
3535         LASSERT(!S_ISDIR(inode->i_mode));
3536
3537         /* catch async errors that were recorded back when async writeback
3538          * failed for pages in this mapping. */
3539         rc = lli->lli_async_rc;
3540         lli->lli_async_rc = 0;
3541         if (lli->lli_clob != NULL) {
3542                 err = lov_read_and_clear_async_rc(lli->lli_clob);
3543                 if (rc == 0)
3544                         rc = err;
3545         }
3546
3547         /* The application has been told write failure already.
3548          * Do not report failure again. */
3549         if (fd->fd_write_failed)
3550                 return 0;
3551         return rc ? -EIO : 0;
3552 }
3553
3554 /**
3555  * Called to make sure a portion of file has been written out.
3556  * if @mode is not CL_FSYNC_LOCAL, it will send OST_SYNC RPCs to OST.
3557  *
3558  * Return how many pages have been written.
3559  */
3560 int cl_sync_file_range(struct inode *inode, loff_t start, loff_t end,
3561                        enum cl_fsync_mode mode, int ignore_layout)
3562 {
3563         struct lu_env *env;
3564         struct cl_io *io;
3565         struct cl_fsync_io *fio;
3566         int result;
3567         __u16 refcheck;
3568         ENTRY;
3569
3570         if (mode != CL_FSYNC_NONE && mode != CL_FSYNC_LOCAL &&
3571             mode != CL_FSYNC_DISCARD && mode != CL_FSYNC_ALL)
3572                 RETURN(-EINVAL);
3573
3574         env = cl_env_get(&refcheck);
3575         if (IS_ERR(env))
3576                 RETURN(PTR_ERR(env));
3577
3578         io = vvp_env_thread_io(env);
3579         io->ci_obj = ll_i2info(inode)->lli_clob;
3580         io->ci_ignore_layout = ignore_layout;
3581
3582         /* initialize parameters for sync */
3583         fio = &io->u.ci_fsync;
3584         fio->fi_start = start;
3585         fio->fi_end = end;
3586         fio->fi_fid = ll_inode2fid(inode);
3587         fio->fi_mode = mode;
3588         fio->fi_nr_written = 0;
3589
3590         if (cl_io_init(env, io, CIT_FSYNC, io->ci_obj) == 0)
3591                 result = cl_io_loop(env, io);
3592         else
3593                 result = io->ci_result;
3594         if (result == 0)
3595                 result = fio->fi_nr_written;
3596         cl_io_fini(env, io);
3597         cl_env_put(env, &refcheck);
3598
3599         RETURN(result);
3600 }
3601
3602 /*
3603  * When dentry is provided (the 'else' case), file_dentry() may be
3604  * null and dentry must be used directly rather than pulled from
3605  * file_dentry() as is done otherwise.
3606  */
3607
3608 #ifdef HAVE_FILE_FSYNC_4ARGS
3609 int ll_fsync(struct file *file, loff_t start, loff_t end, int datasync)
3610 {
3611         struct dentry *dentry = file_dentry(file);
3612         bool lock_inode;
3613 #elif defined(HAVE_FILE_FSYNC_2ARGS)
3614 int ll_fsync(struct file *file, int datasync)
3615 {
3616         struct dentry *dentry = file_dentry(file);
3617         loff_t start = 0;
3618         loff_t end = LLONG_MAX;
3619 #else
3620 int ll_fsync(struct file *file, struct dentry *dentry, int datasync)
3621 {
3622         loff_t start = 0;
3623         loff_t end = LLONG_MAX;
3624 #endif
3625         struct inode *inode = dentry->d_inode;
3626         struct ll_inode_info *lli = ll_i2info(inode);
3627         struct ptlrpc_request *req;
3628         int rc, err;
3629         ENTRY;
3630
3631         CDEBUG(D_VFSTRACE, "VFS Op:inode="DFID"(%p)\n",
3632                PFID(ll_inode2fid(inode)), inode);
3633         ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_FSYNC, 1);
3634
3635 #ifdef HAVE_FILE_FSYNC_4ARGS
3636         rc = filemap_write_and_wait_range(inode->i_mapping, start, end);
3637         lock_inode = !lli->lli_inode_locked;
3638         if (lock_inode)
3639                 inode_lock(inode);
3640 #else
3641         /* fsync's caller has already called _fdata{sync,write}, we want
3642          * that IO to finish before calling the osc and mdc sync methods */
3643         rc = filemap_fdatawait(inode->i_mapping);
3644 #endif
3645
3646         /* catch async errors that were recorded back when async writeback
3647          * failed for pages in this mapping. */
3648         if (!S_ISDIR(inode->i_mode)) {
3649                 err = lli->lli_async_rc;
3650                 lli->lli_async_rc = 0;
3651                 if (rc == 0)
3652                         rc = err;
3653                 if (lli->lli_clob != NULL) {
3654                         err = lov_read_and_clear_async_rc(lli->lli_clob);
3655                         if (rc == 0)
3656                                 rc = err;
3657                 }
3658         }
3659
3660         err = md_fsync(ll_i2sbi(inode)->ll_md_exp, ll_inode2fid(inode), &req);
3661         if (!rc)
3662                 rc = err;
3663         if (!err)
3664                 ptlrpc_req_finished(req);
3665
3666         if (S_ISREG(inode->i_mode)) {
3667                 struct ll_file_data *fd = LUSTRE_FPRIVATE(file);
3668
3669                 err = cl_sync_file_range(inode, start, end, CL_FSYNC_ALL, 0);
3670                 if (rc == 0 && err < 0)
3671                         rc = err;
3672                 if (rc < 0)
3673                         fd->fd_write_failed = true;
3674                 else
3675                         fd->fd_write_failed = false;
3676         }
3677
3678 #ifdef HAVE_FILE_FSYNC_4ARGS
3679         if (lock_inode)
3680                 inode_unlock(inode);
3681 #endif
3682         RETURN(rc);
3683 }
3684
3685 static int
3686 ll_file_flock(struct file *file, int cmd, struct file_lock *file_lock)
3687 {
3688         struct inode *inode = file_inode(file);
3689         struct ll_sb_info *sbi = ll_i2sbi(inode);
3690         struct ldlm_enqueue_info einfo = {
3691                 .ei_type        = LDLM_FLOCK,
3692                 .ei_cb_cp       = ldlm_flock_completion_ast,
3693                 .ei_cbdata      = file_lock,
3694         };
3695         struct md_op_data *op_data;
3696         struct lustre_handle lockh = { 0 };
3697         union ldlm_policy_data flock = { { 0 } };
3698         int fl_type = file_lock->fl_type;
3699         __u64 flags = 0;
3700         int rc;
3701         int rc2 = 0;
3702         ENTRY;
3703
3704         CDEBUG(D_VFSTRACE, "VFS Op:inode="DFID" file_lock=%p\n",
3705                PFID(ll_inode2fid(inode)), file_lock);
3706
3707         ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_FLOCK, 1);
3708
3709         if (file_lock->fl_flags & FL_FLOCK) {
3710                 LASSERT((cmd == F_SETLKW) || (cmd == F_SETLK));
3711                 /* flocks are whole-file locks */
3712                 flock.l_flock.end = OFFSET_MAX;
3713                 /* For flocks owner is determined by the local file desctiptor*/
3714                 flock.l_flock.owner = (unsigned long)file_lock->fl_file;
3715         } else if (file_lock->fl_flags & FL_POSIX) {
3716                 flock.l_flock.owner = (unsigned long)file_lock->fl_owner;
3717                 flock.l_flock.start = file_lock->fl_start;
3718                 flock.l_flock.end = file_lock->fl_end;
3719         } else {
3720                 RETURN(-EINVAL);
3721         }
3722         flock.l_flock.pid = file_lock->fl_pid;
3723
3724         /* Somewhat ugly workaround for svc lockd.
3725          * lockd installs custom fl_lmops->lm_compare_owner that checks
3726          * for the fl_owner to be the same (which it always is on local node
3727          * I guess between lockd processes) and then compares pid.
3728          * As such we assign pid to the owner field to make it all work,
3729          * conflict with normal locks is unlikely since pid space and
3730          * pointer space for current->files are not intersecting */
3731         if (file_lock->fl_lmops && file_lock->fl_lmops->lm_compare_owner)
3732                 flock.l_flock.owner = (unsigned long)file_lock->fl_pid;
3733
3734         switch (fl_type) {
3735         case F_RDLCK:
3736                 einfo.ei_mode = LCK_PR;
3737                 break;
3738         case F_UNLCK:
3739                 /* An unlock request may or may not have any relation to
3740                  * existing locks so we may not be able to pass a lock handle
3741                  * via a normal ldlm_lock_cancel() request. The request may even
3742                  * unlock a byte range in the middle of an existing lock. In
3743                  * order to process an unlock request we need all of the same
3744                  * information that is given with a normal read or write record
3745                  * lock request. To avoid creating another ldlm unlock (cancel)
3746                  * message we'll treat a LCK_NL flock request as an unlock. */
3747                 einfo.ei_mode = LCK_NL;
3748                 break;
3749         case F_WRLCK:
3750                 einfo.ei_mode = LCK_PW;
3751                 break;
3752         default:
3753                 CDEBUG(D_INFO, "Unknown fcntl lock type: %d\n", fl_type);
3754                 RETURN (-ENOTSUPP);
3755         }
3756
3757         switch (cmd) {
3758         case F_SETLKW:
3759 #ifdef F_SETLKW64
3760         case F_SETLKW64:
3761 #endif
3762                 flags = 0;
3763                 break;
3764         case F_SETLK:
3765 #ifdef F_SETLK64
3766         case F_SETLK64:
3767 #endif
3768                 flags = LDLM_FL_BLOCK_NOWAIT;
3769                 break;
3770         case F_GETLK:
3771 #ifdef F_GETLK64
3772         case F_GETLK64:
3773 #endif
3774                 flags = LDLM_FL_TEST_LOCK;
3775                 break;
3776         default:
3777                 CERROR("unknown fcntl lock command: %d\n", cmd);
3778                 RETURN (-EINVAL);
3779         }
3780
3781         /* Save the old mode so that if the mode in the lock changes we
3782          * can decrement the appropriate reader or writer refcount. */
3783         file_lock->fl_type = einfo.ei_mode;
3784
3785         op_data = ll_prep_md_op_data(NULL, inode, NULL, NULL, 0, 0,
3786                                      LUSTRE_OPC_ANY, NULL);
3787         if (IS_ERR(op_data))
3788                 RETURN(PTR_ERR(op_data));
3789
3790         CDEBUG(D_DLMTRACE, "inode="DFID", pid=%u, flags=%#llx, mode=%u, "
3791                "start=%llu, end=%llu\n", PFID(ll_inode2fid(inode)),
3792                flock.l_flock.pid, flags, einfo.ei_mode,
3793                flock.l_flock.start, flock.l_flock.end);
3794
3795         rc = md_enqueue(sbi->ll_md_exp, &einfo, &flock, op_data, &lockh,
3796                         flags);
3797
3798         /* Restore the file lock type if not TEST lock. */
3799         if (!(flags & LDLM_FL_TEST_LOCK))
3800                 file_lock->fl_type = fl_type;
3801
3802 #ifdef HAVE_LOCKS_LOCK_FILE_WAIT
3803         if ((rc == 0 || file_lock->fl_type == F_UNLCK) &&
3804             !(flags & LDLM_FL_TEST_LOCK))
3805                 rc2  = locks_lock_file_wait(file, file_lock);
3806 #else
3807         if ((file_lock->fl_flags & FL_FLOCK) &&
3808             (rc == 0 || file_lock->fl_type == F_UNLCK))
3809                 rc2  = flock_lock_file_wait(file, file_lock);
3810         if ((file_lock->fl_flags & FL_POSIX) &&
3811             (rc == 0 || file_lock->fl_type == F_UNLCK) &&
3812             !(flags & LDLM_FL_TEST_LOCK))
3813                 rc2  = posix_lock_file_wait(file, file_lock);
3814 #endif /* HAVE_LOCKS_LOCK_FILE_WAIT */
3815
3816         if (rc2 && file_lock->fl_type != F_UNLCK) {
3817                 einfo.ei_mode = LCK_NL;
3818                 md_enqueue(sbi->ll_md_exp, &einfo, &flock, op_data,
3819                            &lockh, flags);
3820                 rc = rc2;
3821         }
3822
3823         ll_finish_md_op_data(op_data);
3824
3825         RETURN(rc);
3826 }
3827
3828 int ll_get_fid_by_name(struct inode *parent, const char *name,
3829                        int namelen, struct lu_fid *fid,
3830                        struct inode **inode)
3831 {
3832         struct md_op_data       *op_data = NULL;
3833         struct mdt_body         *body;
3834         struct ptlrpc_request   *req;
3835         int                     rc;
3836         ENTRY;
3837
3838         op_data = ll_prep_md_op_data(NULL, parent, NULL, name, namelen, 0,
3839                                      LUSTRE_OPC_ANY, NULL);
3840         if (IS_ERR(op_data))
3841                 RETURN(PTR_ERR(op_data));
3842
3843         op_data->op_valid = OBD_MD_FLID | OBD_MD_FLTYPE;
3844         rc = md_getattr_name(ll_i2sbi(parent)->ll_md_exp, op_data, &req);
3845         ll_finish_md_op_data(op_data);
3846         if (rc < 0)
3847                 RETURN(rc);
3848
3849         body = req_capsule_server_get(&req->rq_pill, &RMF_MDT_BODY);
3850         if (body == NULL)
3851                 GOTO(out_req, rc = -EFAULT);
3852         if (fid != NULL)
3853                 *fid = body->mbo_fid1;
3854
3855         if (inode != NULL)
3856                 rc = ll_prep_inode(inode, req, parent->i_sb, NULL);
3857 out_req:
3858         ptlrpc_req_finished(req);
3859         RETURN(rc);
3860 }
3861
3862 int ll_migrate(struct inode *parent, struct file *file, int mdtidx,
3863                const char *name, int namelen)
3864 {
3865         struct dentry         *dchild = NULL;
3866         struct inode          *child_inode = NULL;
3867         struct md_op_data     *op_data;
3868         struct ptlrpc_request *request = NULL;
3869         struct obd_client_handle *och = NULL;
3870         struct qstr           qstr;
3871         struct mdt_body         *body;
3872         int                    rc;
3873         __u64                   data_version = 0;
3874         ENTRY;
3875
3876         CDEBUG(D_VFSTRACE, "migrate %s under "DFID" to MDT%04x\n",
3877                name, PFID(ll_inode2fid(parent)), mdtidx);
3878
3879         op_data = ll_prep_md_op_data(NULL, parent, NULL, name, namelen,
3880                                      0, LUSTRE_OPC_ANY, NULL);
3881         if (IS_ERR(op_data))
3882                 RETURN(PTR_ERR(op_data));
3883
3884         /* Get child FID first */
3885         qstr.hash = ll_full_name_hash(file_dentry(file), name, namelen);
3886         qstr.name = name;
3887         qstr.len = namelen;
3888         dchild = d_lookup(file_dentry(file), &qstr);
3889         if (dchild != NULL) {
3890                 if (dchild->d_inode != NULL)
3891                         child_inode = igrab(dchild->d_inode);
3892                 dput(dchild);
3893         }
3894
3895         if (child_inode == NULL) {
3896                 rc = ll_get_fid_by_name(parent, name, namelen,
3897                                         &op_data->op_fid3, &child_inode);
3898                 if (rc != 0)
3899                         GOTO(out_free, rc);
3900         }
3901
3902         if (child_inode == NULL)
3903                 GOTO(out_free, rc = -EINVAL);
3904
3905         /*
3906          * lfs migrate command needs to be blocked on the client
3907          * by checking the migrate FID against the FID of the
3908          * filesystem root.
3909          */
3910         if (child_inode == parent->i_sb->s_root->d_inode)
3911                 GOTO(out_iput, rc = -EINVAL);
3912
3913         inode_lock(child_inode);
3914         op_data->op_fid3 = *ll_inode2fid(child_inode);
3915         if (!fid_is_sane(&op_data->op_fid3)) {
3916                 CERROR("%s: migrate %s, but FID "DFID" is insane\n",
3917                        ll_get_fsname(parent->i_sb, NULL, 0), name,
3918                        PFID(&op_data->op_fid3));
3919                 GOTO(out_unlock, rc = -EINVAL);
3920         }
3921
3922         rc = ll_get_mdt_idx_by_fid(ll_i2sbi(parent), &op_data->op_fid3);
3923         if (rc < 0)
3924                 GOTO(out_unlock, rc);
3925
3926         if (rc == mdtidx) {
3927                 CDEBUG(D_INFO, "%s: "DFID" is already on MDT%04x\n", name,
3928                        PFID(&op_data->op_fid3), mdtidx);
3929                 GOTO(out_unlock, rc = 0);
3930         }
3931 again:
3932         if (S_ISREG(child_inode->i_mode)) {
3933                 och = ll_lease_open(child_inode, NULL, FMODE_WRITE, 0);
3934                 if (IS_ERR(och)) {
3935                         rc = PTR_ERR(och);
3936                         och = NULL;
3937                         GOTO(out_unlock, rc);
3938                 }
3939
3940                 rc = ll_data_version(child_inode, &data_version,
3941                                      LL_DV_WR_FLUSH);
3942                 if (rc != 0)
3943                         GOTO(out_close, rc);
3944
3945                 op_data->op_handle = och->och_fh;
3946                 op_data->op_data = och->och_mod;
3947                 op_data->op_data_version = data_version;
3948                 op_data->op_lease_handle = och->och_lease_handle;
3949                 op_data->op_bias |= MDS_RENAME_MIGRATE;
3950         }
3951
3952         op_data->op_mds = mdtidx;
3953         op_data->op_cli_flags = CLI_MIGRATE;
3954         rc = md_rename(ll_i2sbi(parent)->ll_md_exp, op_data, name,
3955                        namelen, name, namelen, &request);
3956         if (rc == 0) {
3957                 LASSERT(request != NULL);
3958                 ll_update_times(request, parent);
3959
3960                 body = req_capsule_server_get(&request->rq_pill, &RMF_MDT_BODY);
3961                 LASSERT(body != NULL);
3962
3963                 /* If the server does release layout lock, then we cleanup
3964                  * the client och here, otherwise release it in out_close: */
3965                 if (och != NULL &&
3966                     body->mbo_valid & OBD_MD_CLOSE_INTENT_EXECED) {
3967                         obd_mod_put(och->och_mod);
3968                         md_clear_open_replay_data(ll_i2sbi(parent)->ll_md_exp,
3969                                                   och);
3970                         och->och_fh.cookie = DEAD_HANDLE_MAGIC;
3971                         OBD_FREE_PTR(och);
3972                         och = NULL;
3973                 }
3974         }
3975
3976         if (request != NULL) {
3977                 ptlrpc_req_finished(request);
3978                 request = NULL;
3979         }
3980
3981         /* Try again if the file layout has changed. */
3982         if (rc == -EAGAIN && S_ISREG(child_inode->i_mode))
3983                 goto again;
3984
3985 out_close:
3986         if (och != NULL) /* close the file */
3987                 ll_lease_close(och, child_inode, NULL);
3988         if (rc == 0)
3989                 clear_nlink(child_inode);
3990 out_unlock:
3991         inode_unlock(child_inode);
3992 out_iput:
3993         iput(child_inode);
3994 out_free:
3995         ll_finish_md_op_data(op_data);
3996         RETURN(rc);
3997 }
3998
3999 static int
4000 ll_file_noflock(struct file *file, int cmd, struct file_lock *file_lock)
4001 {
4002         ENTRY;
4003
4004         RETURN(-ENOSYS);
4005 }
4006
4007 /**
4008  * test if some locks matching bits and l_req_mode are acquired
4009  * - bits can be in different locks
4010  * - if found clear the common lock bits in *bits
4011  * - the bits not found, are kept in *bits
4012  * \param inode [IN]
4013  * \param bits [IN] searched lock bits [IN]
4014  * \param l_req_mode [IN] searched lock mode
4015  * \retval boolean, true iff all bits are found
4016  */
4017 int ll_have_md_lock(struct inode *inode, __u64 *bits, enum ldlm_mode l_req_mode)
4018 {
4019         struct lustre_handle lockh;
4020         union ldlm_policy_data policy;
4021         enum ldlm_mode mode = (l_req_mode == LCK_MINMODE) ?
4022                               (LCK_CR | LCK_CW | LCK_PR | LCK_PW) : l_req_mode;
4023         struct lu_fid *fid;
4024         __u64 flags;
4025         int i;
4026         ENTRY;
4027
4028         if (!inode)
4029                RETURN(0);
4030
4031         fid = &ll_i2info(inode)->lli_fid;
4032         CDEBUG(D_INFO, "trying to match res "DFID" mode %s\n", PFID(fid),
4033                ldlm_lockname[mode]);
4034
4035         flags = LDLM_FL_BLOCK_GRANTED | LDLM_FL_CBPENDING | LDLM_FL_TEST_LOCK;
4036         for (i = 0; i <= MDS_INODELOCK_MAXSHIFT && *bits != 0; i++) {
4037                 policy.l_inodebits.bits = *bits & (1 << i);
4038                 if (policy.l_inodebits.bits == 0)
4039                         continue;
4040
4041                 if (md_lock_match(ll_i2mdexp(inode), flags, fid, LDLM_IBITS,
4042                                   &policy, mode, &lockh)) {
4043                         struct ldlm_lock *lock;
4044
4045                         lock = ldlm_handle2lock(&lockh);
4046                         if (lock) {
4047                                 *bits &=
4048                                       ~(lock->l_policy_data.l_inodebits.bits);
4049                                 LDLM_LOCK_PUT(lock);
4050                         } else {
4051                                 *bits &= ~policy.l_inodebits.bits;
4052                         }
4053                 }
4054         }
4055         RETURN(*bits == 0);
4056 }
4057
4058 enum ldlm_mode ll_take_md_lock(struct inode *inode, __u64 bits,
4059                                struct lustre_handle *lockh, __u64 flags,
4060                                enum ldlm_mode mode)
4061 {
4062         union ldlm_policy_data policy = { .l_inodebits = { bits } };
4063         struct lu_fid *fid;
4064         enum ldlm_mode rc;
4065         ENTRY;
4066
4067         fid = &ll_i2info(inode)->lli_fid;
4068         CDEBUG(D_INFO, "trying to match res "DFID"\n", PFID(fid));
4069
4070         rc = md_lock_match(ll_i2mdexp(inode), LDLM_FL_BLOCK_GRANTED|flags,
4071                            fid, LDLM_IBITS, &policy, mode, lockh);
4072
4073         RETURN(rc);
4074 }
4075
4076 static int ll_inode_revalidate_fini(struct inode *inode, int rc)
4077 {
4078         /* Already unlinked. Just update nlink and return success */
4079         if (rc == -ENOENT) {
4080                 clear_nlink(inode);
4081                 /* If it is striped directory, and there is bad stripe
4082                  * Let's revalidate the dentry again, instead of returning
4083                  * error */
4084                 if (S_ISDIR(inode->i_mode) &&
4085                     ll_i2info(inode)->lli_lsm_md != NULL)
4086                         return 0;
4087
4088                 /* This path cannot be hit for regular files unless in
4089                  * case of obscure races, so no need to to validate
4090                  * size. */
4091                 if (!S_ISREG(inode->i_mode) && !S_ISDIR(inode->i_mode))
4092                         return 0;
4093         } else if (rc != 0) {
4094                 CDEBUG_LIMIT((rc == -EACCES || rc == -EIDRM) ? D_INFO : D_ERROR,
4095                              "%s: revalidate FID "DFID" error: rc = %d\n",
4096                              ll_get_fsname(inode->i_sb, NULL, 0),
4097                              PFID(ll_inode2fid(inode)), rc);
4098         }
4099
4100         return rc;
4101 }
4102
4103 static int ll_inode_revalidate(struct dentry *dentry, enum ldlm_intent_flags op)
4104 {
4105         struct inode *inode = dentry->d_inode;
4106         struct obd_export *exp = ll_i2mdexp(inode);
4107         struct lookup_intent oit = {
4108                 .it_op = op,
4109         };
4110         struct ptlrpc_request *req = NULL;
4111         struct md_op_data *op_data;
4112         int rc = 0;
4113         ENTRY;
4114
4115         CDEBUG(D_VFSTRACE, "VFS Op:inode="DFID"(%p),name=%s\n",
4116                PFID(ll_inode2fid(inode)), inode, dentry->d_name.name);
4117
4118         /* Call getattr by fid, so do not provide name at all. */
4119         op_data = ll_prep_md_op_data(NULL, inode, inode, NULL, 0, 0,
4120                                      LUSTRE_OPC_ANY, NULL);
4121         if (IS_ERR(op_data))
4122                 RETURN(PTR_ERR(op_data));
4123
4124         rc = md_intent_lock(exp, op_data, &oit, &req, &ll_md_blocking_ast, 0);
4125         ll_finish_md_op_data(op_data);
4126         if (rc < 0) {
4127                 rc = ll_inode_revalidate_fini(inode, rc);
4128                 GOTO(out, rc);
4129         }
4130
4131         rc = ll_revalidate_it_finish(req, &oit, dentry);
4132         if (rc != 0) {
4133                 ll_intent_release(&oit);
4134                 GOTO(out, rc);
4135         }
4136
4137         /* Unlinked? Unhash dentry, so it is not picked up later by
4138          * do_lookup() -> ll_revalidate_it(). We cannot use d_drop
4139          * here to preserve get_cwd functionality on 2.6.
4140          * Bug 10503 */
4141         if (!dentry->d_inode->i_nlink) {
4142                 ll_lock_dcache(inode);
4143                 d_lustre_invalidate(dentry, 0);
4144                 ll_unlock_dcache(inode);
4145         }
4146
4147         ll_lookup_finish_locks(&oit, dentry);
4148 out:
4149         ptlrpc_req_finished(req);
4150
4151         return rc;
4152 }
4153
4154 static int ll_merge_md_attr(struct inode *inode)
4155 {
4156         struct cl_attr attr = { 0 };
4157         int rc;
4158
4159         LASSERT(ll_i2info(inode)->lli_lsm_md != NULL);
4160         rc = md_merge_attr(ll_i2mdexp(inode), ll_i2info(inode)->lli_lsm_md,
4161                            &attr, ll_md_blocking_ast);
4162         if (rc != 0)
4163                 RETURN(rc);
4164
4165         set_nlink(inode, attr.cat_nlink);
4166         inode->i_blocks = attr.cat_blocks;
4167         i_size_write(inode, attr.cat_size);
4168
4169         ll_i2info(inode)->lli_atime = attr.cat_atime;
4170         ll_i2info(inode)->lli_mtime = attr.cat_mtime;
4171         ll_i2info(inode)->lli_ctime = attr.cat_ctime;
4172
4173         RETURN(0);
4174 }
4175
4176 static inline dev_t ll_compat_encode_dev(dev_t dev)
4177 {
4178         /* The compat_sys_*stat*() syscalls will fail unless the
4179          * device majors and minors are both less than 256. Note that
4180          * the value returned here will be passed through
4181          * old_encode_dev() in cp_compat_stat(). And so we are not
4182          * trying to return a valid compat (u16) device number, just
4183          * one that will pass the old_valid_dev() check. */
4184
4185         return MKDEV(MAJOR(dev) & 0xff, MINOR(dev) & 0xff);
4186 }
4187
4188 #ifdef HAVE_INODEOPS_ENHANCED_GETATTR
4189 int ll_getattr(const struct path *path, struct kstat *stat,
4190                u32 request_mask, unsigned int flags)
4191 {
4192         struct dentry *de = path->dentry;
4193 #else
4194 int ll_getattr(struct vfsmount *mnt, struct dentry *de, struct kstat *stat)
4195 {
4196 #endif
4197         struct inode *inode = de->d_inode;
4198         struct ll_sb_info *sbi = ll_i2sbi(inode);
4199         struct ll_inode_info *lli = ll_i2info(inode);
4200         int rc;
4201
4202         ll_stats_ops_tally(sbi, LPROC_LL_GETATTR, 1);
4203
4204         rc = ll_inode_revalidate(de, IT_GETATTR);
4205         if (rc < 0)
4206                 RETURN(rc);
4207
4208         if (S_ISREG(inode->i_mode)) {
4209                 /* In case of restore, the MDT has the right size and has
4210                  * already send it back without granting the layout lock,
4211                  * inode is up-to-date so glimpse is useless.
4212                  * Also to glimpse we need the layout, in case of a running
4213                  * restore the MDT holds the layout lock so the glimpse will
4214                  * block up to the end of restore (getattr will block)
4215                  */
4216                 if (!ll_file_test_flag(lli, LLIF_FILE_RESTORING)) {
4217                         rc = ll_glimpse_size(inode);
4218                         if (rc < 0)
4219                                 RETURN(rc);
4220                 }
4221         } else {
4222                 /* If object isn't regular a file then don't validate size. */
4223                 if (S_ISDIR(inode->i_mode) &&
4224                     lli->lli_lsm_md != NULL) {
4225                         rc = ll_merge_md_attr(inode);
4226                         if (rc < 0)
4227                                 RETURN(rc);
4228                 }
4229
4230                 LTIME_S(inode->i_atime) = lli->lli_atime;
4231                 LTIME_S(inode->i_mtime) = lli->lli_mtime;
4232                 LTIME_S(inode->i_ctime) = lli->lli_ctime;
4233         }
4234
4235         OBD_FAIL_TIMEOUT(OBD_FAIL_GETATTR_DELAY, 30);
4236
4237         if (ll_need_32bit_api(sbi)) {
4238                 stat->ino = cl_fid_build_ino(&lli->lli_fid, 1);
4239                 stat->dev = ll_compat_encode_dev(inode->i_sb->s_dev);
4240                 stat->rdev = ll_compat_encode_dev(inode->i_rdev);
4241         } else {
4242                 stat->ino = inode->i_ino;
4243                 stat->dev = inode->i_sb->s_dev;
4244                 stat->rdev = inode->i_rdev;
4245         }
4246
4247         stat->mode = inode->i_mode;
4248         stat->uid = inode->i_uid;
4249         stat->gid = inode->i_gid;
4250         stat->atime = inode->i_atime;
4251         stat->mtime = inode->i_mtime;
4252         stat->ctime = inode->i_ctime;
4253         stat->blksize = sbi->ll_stat_blksize ?: 1 << inode->i_blkbits;
4254
4255         stat->nlink = inode->i_nlink;
4256         stat->size = i_size_read(inode);
4257         stat->blocks = inode->i_blocks;
4258
4259         return 0;
4260 }
4261
4262 static int ll_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
4263                      __u64 start, __u64 len)
4264 {
4265         int             rc;
4266         size_t          num_bytes;
4267         struct fiemap   *fiemap;
4268         unsigned int    extent_count = fieinfo->fi_extents_max;
4269
4270         num_bytes = sizeof(*fiemap) + (extent_count *
4271                                        sizeof(struct fiemap_extent));
4272         OBD_ALLOC_LARGE(fiemap, num_bytes);
4273
4274         if (fiemap == NULL)
4275                 RETURN(-ENOMEM);
4276
4277         fiemap->fm_flags = fieinfo->fi_flags;
4278         fiemap->fm_extent_count = fieinfo->fi_extents_max;
4279         fiemap->fm_start = start;
4280         fiemap->fm_length = len;
4281         if (extent_count > 0 &&
4282             copy_from_user(&fiemap->fm_extents[0], fieinfo->fi_extents_start,
4283                            sizeof(struct fiemap_extent)) != 0)
4284                 GOTO(out, rc = -EFAULT);
4285
4286         rc = ll_do_fiemap(inode, fiemap, num_bytes);
4287
4288         fieinfo->fi_flags = fiemap->fm_flags;
4289         fieinfo->fi_extents_mapped = fiemap->fm_mapped_extents;
4290         if (extent_count > 0 &&
4291             copy_to_user(fieinfo->fi_extents_start, &fiemap->fm_extents[0],
4292                          fiemap->fm_mapped_extents *
4293                          sizeof(struct fiemap_extent)) != 0)
4294                 GOTO(out, rc = -EFAULT);
4295 out:
4296         OBD_FREE_LARGE(fiemap, num_bytes);
4297         return rc;
4298 }
4299
4300 struct posix_acl *ll_get_acl(struct inode *inode, int type)
4301 {
4302         struct ll_inode_info *lli = ll_i2info(inode);
4303         struct posix_acl *acl = NULL;
4304         ENTRY;
4305
4306         spin_lock(&lli->lli_lock);
4307         /* VFS' acl_permission_check->check_acl will release the refcount */
4308         acl = posix_acl_dup(lli->lli_posix_acl);
4309         spin_unlock(&lli->lli_lock);
4310
4311         RETURN(acl);
4312 }
4313
4314 #ifdef HAVE_IOP_SET_ACL
4315 #ifdef CONFIG_FS_POSIX_ACL
4316 int ll_set_acl(struct inode *inode, struct posix_acl *acl, int type)
4317 {
4318         const char *name = NULL;
4319         char *value = NULL;
4320         size_t size = 0;
4321         int rc = 0;
4322         ENTRY;
4323
4324         switch (type) {
4325         case ACL_TYPE_ACCESS:
4326                 if (acl) {
4327                         rc = posix_acl_update_mode(inode, &inode->i_mode, &acl);
4328                         if (rc)
4329                                 GOTO(out, rc);
4330                 }
4331                 name = XATTR_NAME_POSIX_ACL_ACCESS;
4332                 break;
4333         case ACL_TYPE_DEFAULT:
4334                 if (!S_ISDIR(inode->i_mode))
4335                         GOTO(out, rc = acl ? -EACCES : 0);
4336                 name = XATTR_NAME_POSIX_ACL_DEFAULT;
4337                 break;
4338         default:
4339                 GOTO(out, rc = -EINVAL);
4340         }
4341
4342         if (acl) {
4343                 size = posix_acl_xattr_size(acl->a_count);
4344                 value = kmalloc(size, GFP_NOFS);
4345                 if (value == NULL)
4346                         GOTO(out, rc = -ENOMEM);
4347
4348                 rc = posix_acl_to_xattr(&init_user_ns, acl, value, size);
4349                 if (rc < 0)
4350                         GOTO(out_free, rc);
4351         }
4352
4353         /* dentry is only used for *.lov attributes so it's safe to be NULL */
4354         rc = __vfs_setxattr(NULL, inode, name, value, size, XATTR_CREATE);
4355 out_free:
4356         kfree(value);
4357 out:
4358         if (!rc)
4359                 set_cached_acl(inode, type, acl);
4360         else
4361                 forget_cached_acl(inode, type);
4362         RETURN(rc);
4363 }
4364 #endif /* CONFIG_FS_POSIX_ACL */
4365 #endif /* HAVE_IOP_SET_ACL */
4366
4367 #ifndef HAVE_GENERIC_PERMISSION_2ARGS
4368 static int
4369 # ifdef HAVE_GENERIC_PERMISSION_4ARGS
4370 ll_check_acl(struct inode *inode, int mask, unsigned int flags)
4371 # else
4372 ll_check_acl(struct inode *inode, int mask)
4373 # endif
4374 {
4375 # ifdef CONFIG_FS_POSIX_ACL
4376         struct posix_acl *acl;
4377         int rc;
4378         ENTRY;
4379
4380 #  ifdef HAVE_GENERIC_PERMISSION_4ARGS
4381         if (flags & IPERM_FLAG_RCU)
4382                 return -ECHILD;
4383 #  endif
4384         acl = ll_get_acl(inode, ACL_TYPE_ACCESS);
4385
4386         if (!acl)
4387                 RETURN(-EAGAIN);
4388
4389         rc = posix_acl_permission(inode, acl, mask);
4390         posix_acl_release(acl);
4391
4392         RETURN(rc);
4393 # else /* !CONFIG_FS_POSIX_ACL */
4394         return -EAGAIN;
4395 # endif /* CONFIG_FS_POSIX_ACL */
4396 }
4397 #endif /* HAVE_GENERIC_PERMISSION_2ARGS */
4398
4399 #ifdef HAVE_GENERIC_PERMISSION_4ARGS
4400 int ll_inode_permission(struct inode *inode, int mask, unsigned int flags)
4401 #else
4402 # ifdef HAVE_INODE_PERMISION_2ARGS
4403 int ll_inode_permission(struct inode *inode, int mask)
4404 # else
4405 int ll_inode_permission(struct inode *inode, int mask, struct nameidata *nd)
4406 # endif
4407 #endif
4408 {
4409         int rc = 0;
4410         struct ll_sb_info *sbi;
4411         struct root_squash_info *squash;
4412         struct cred *cred = NULL;
4413         const struct cred *old_cred = NULL;
4414         cfs_cap_t cap;
4415         bool squash_id = false;
4416         ENTRY;
4417
4418 #ifdef MAY_NOT_BLOCK
4419         if (mask & MAY_NOT_BLOCK)
4420                 return -ECHILD;
4421 #elif defined(HAVE_GENERIC_PERMISSION_4ARGS)
4422         if (flags & IPERM_FLAG_RCU)
4423                 return -ECHILD;
4424 #endif
4425
4426        /* as root inode are NOT getting validated in lookup operation,
4427         * need to do it before permission check. */
4428
4429         if (inode == inode->i_sb->s_root->d_inode) {
4430                 rc = ll_inode_revalidate(inode->i_sb->s_root, IT_LOOKUP);
4431                 if (rc)
4432                         RETURN(rc);
4433         }
4434
4435         CDEBUG(D_VFSTRACE, "VFS Op:inode="DFID"(%p), inode mode %x mask %o\n",
4436                PFID(ll_inode2fid(inode)), inode, inode->i_mode, mask);
4437
4438         /* squash fsuid/fsgid if needed */
4439         sbi = ll_i2sbi(inode);
4440         squash = &sbi->ll_squash;
4441         if (unlikely(squash->rsi_uid != 0 &&
4442                      uid_eq(current_fsuid(), GLOBAL_ROOT_UID) &&
4443                      !(sbi->ll_flags & LL_SBI_NOROOTSQUASH))) {
4444                         squash_id = true;
4445         }
4446         if (squash_id) {
4447                 CDEBUG(D_OTHER, "squash creds (%d:%d)=>(%d:%d)\n",
4448                        __kuid_val(current_fsuid()), __kgid_val(current_fsgid()),
4449                        squash->rsi_uid, squash->rsi_gid);
4450
4451                 /* update current process's credentials
4452                  * and FS capability */
4453                 cred = prepare_creds();
4454                 if (cred == NULL)
4455                         RETURN(-ENOMEM);
4456
4457                 cred->fsuid = make_kuid(&init_user_ns, squash->rsi_uid);
4458                 cred->fsgid = make_kgid(&init_user_ns, squash->rsi_gid);
4459                 for (cap = 0; cap < sizeof(cfs_cap_t) * 8; cap++) {
4460                         if ((1 << cap) & CFS_CAP_FS_MASK)
4461                                 cap_lower(cred->cap_effective, cap);
4462                 }
4463                 old_cred = override_creds(cred);
4464         }
4465
4466         ll_stats_ops_tally(sbi, LPROC_LL_INODE_PERM, 1);
4467         rc = ll_generic_permission(inode, mask, flags, ll_check_acl);
4468         /* restore current process's credentials and FS capability */
4469         if (squash_id) {
4470                 revert_creds(old_cred);
4471                 put_cred(cred);
4472         }
4473
4474         RETURN(rc);
4475 }
4476
4477 /* -o localflock - only provides locally consistent flock locks */
4478 struct file_operations ll_file_operations = {
4479 #ifdef HAVE_FILE_OPERATIONS_READ_WRITE_ITER
4480 # ifdef HAVE_SYNC_READ_WRITE
4481         .read           = new_sync_read,
4482         .write          = new_sync_write,
4483 # endif
4484         .read_iter      = ll_file_read_iter,
4485         .write_iter     = ll_file_write_iter,
4486 #else /* !HAVE_FILE_OPERATIONS_READ_WRITE_ITER */
4487         .read           = ll_file_read,
4488         .aio_read       = ll_file_aio_read,
4489         .write          = ll_file_write,
4490         .aio_write      = ll_file_aio_write,
4491 #endif /* HAVE_FILE_OPERATIONS_READ_WRITE_ITER */
4492         .unlocked_ioctl = ll_file_ioctl,
4493         .open           = ll_file_open,
4494         .release        = ll_file_release,
4495         .mmap           = ll_file_mmap,
4496         .llseek         = ll_file_seek,
4497         .splice_read    = ll_file_splice_read,
4498         .fsync          = ll_fsync,
4499         .flush          = ll_flush
4500 };
4501
4502 struct file_operations ll_file_operations_flock = {
4503 #ifdef HAVE_FILE_OPERATIONS_READ_WRITE_ITER
4504 # ifdef HAVE_SYNC_READ_WRITE
4505         .read           = new_sync_read,
4506         .write          = new_sync_write,
4507 # endif /* HAVE_SYNC_READ_WRITE */
4508         .read_iter      = ll_file_read_iter,
4509         .write_iter     = ll_file_write_iter,
4510 #else /* !HAVE_FILE_OPERATIONS_READ_WRITE_ITER */
4511         .read           = ll_file_read,
4512         .aio_read       = ll_file_aio_read,
4513         .write          = ll_file_write,
4514         .aio_write      = ll_file_aio_write,
4515 #endif /* HAVE_FILE_OPERATIONS_READ_WRITE_ITER */
4516         .unlocked_ioctl = ll_file_ioctl,
4517         .open           = ll_file_open,
4518         .release        = ll_file_release,
4519         .mmap           = ll_file_mmap,
4520         .llseek         = ll_file_seek,
4521         .splice_read    = ll_file_splice_read,
4522         .fsync          = ll_fsync,
4523         .flush          = ll_flush,
4524         .flock          = ll_file_flock,
4525         .lock           = ll_file_flock
4526 };
4527
4528 /* These are for -o noflock - to return ENOSYS on flock calls */
4529 struct file_operations ll_file_operations_noflock = {
4530 #ifdef HAVE_FILE_OPERATIONS_READ_WRITE_ITER
4531 # ifdef HAVE_SYNC_READ_WRITE
4532         .read           = new_sync_read,
4533         .write          = new_sync_write,
4534 # endif /* HAVE_SYNC_READ_WRITE */
4535         .read_iter      = ll_file_read_iter,
4536         .write_iter     = ll_file_write_iter,
4537 #else /* !HAVE_FILE_OPERATIONS_READ_WRITE_ITER */
4538         .read           = ll_file_read,
4539         .aio_read       = ll_file_aio_read,
4540         .write          = ll_file_write,
4541         .aio_write      = ll_file_aio_write,
4542 #endif /* HAVE_FILE_OPERATIONS_READ_WRITE_ITER */
4543         .unlocked_ioctl = ll_file_ioctl,
4544         .open           = ll_file_open,
4545         .release        = ll_file_release,
4546         .mmap           = ll_file_mmap,
4547         .llseek         = ll_file_seek,
4548         .splice_read    = ll_file_splice_read,
4549         .fsync          = ll_fsync,
4550         .flush          = ll_flush,
4551         .flock          = ll_file_noflock,
4552         .lock           = ll_file_noflock
4553 };
4554
4555 struct inode_operations ll_file_inode_operations = {
4556         .setattr        = ll_setattr,
4557         .getattr        = ll_getattr,
4558         .permission     = ll_inode_permission,
4559 #ifdef HAVE_IOP_XATTR
4560         .setxattr       = ll_setxattr,
4561         .getxattr       = ll_getxattr,
4562         .removexattr    = ll_removexattr,
4563 #endif
4564         .listxattr      = ll_listxattr,
4565         .fiemap         = ll_fiemap,
4566 #ifdef HAVE_IOP_GET_ACL
4567         .get_acl        = ll_get_acl,
4568 #endif
4569 #ifdef HAVE_IOP_SET_ACL
4570         .set_acl        = ll_set_acl,
4571 #endif
4572 };
4573
4574 int ll_layout_conf(struct inode *inode, const struct cl_object_conf *conf)
4575 {
4576         struct ll_inode_info *lli = ll_i2info(inode);
4577         struct cl_object *obj = lli->lli_clob;
4578         struct lu_env *env;
4579         int rc;
4580         __u16 refcheck;
4581         ENTRY;
4582
4583         if (obj == NULL)
4584                 RETURN(0);
4585
4586         env = cl_env_get(&refcheck);
4587         if (IS_ERR(env))
4588                 RETURN(PTR_ERR(env));
4589
4590         rc = cl_conf_set(env, lli->lli_clob, conf);
4591         if (rc < 0)
4592                 GOTO(out, rc);
4593
4594         if (conf->coc_opc == OBJECT_CONF_SET) {
4595                 struct ldlm_lock *lock = conf->coc_lock;
4596                 struct cl_layout cl = {
4597                         .cl_layout_gen = 0,
4598                 };
4599
4600                 LASSERT(lock != NULL);
4601                 LASSERT(ldlm_has_layout(lock));
4602
4603                 /* it can only be allowed to match after layout is
4604                  * applied to inode otherwise false layout would be
4605                  * seen. Applying layout shoud happen before dropping
4606                  * the intent lock. */
4607                 ldlm_lock_allow_match(lock);
4608
4609                 rc = cl_object_layout_get(env, obj, &cl);
4610                 if (rc < 0)
4611                         GOTO(out, rc);
4612
4613                 CDEBUG(D_VFSTRACE,
4614                        DFID": layout version change: %u -> %u\n",
4615                        PFID(&lli->lli_fid), ll_layout_version_get(lli),
4616                        cl.cl_layout_gen);
4617                 ll_layout_version_set(lli, cl.cl_layout_gen);
4618         }
4619
4620 out:
4621         cl_env_put(env, &refcheck);
4622
4623         RETURN(rc);
4624 }
4625
4626 /* Fetch layout from MDT with getxattr request, if it's not ready yet */
4627 static int ll_layout_fetch(struct inode *inode, struct ldlm_lock *lock)
4628
4629 {
4630         struct ll_sb_info *sbi = ll_i2sbi(inode);
4631         struct ptlrpc_request *req;
4632         struct mdt_body *body;
4633         void *lvbdata;
4634         void *lmm;
4635         int lmmsize;
4636         int rc;
4637         ENTRY;
4638
4639         CDEBUG(D_INODE, DFID" LVB_READY=%d l_lvb_data=%p l_lvb_len=%d\n",
4640                PFID(ll_inode2fid(inode)), ldlm_is_lvb_ready(lock),
4641                lock->l_lvb_data, lock->l_lvb_len);
4642
4643         if (lock->l_lvb_data != NULL)
4644                 RETURN(0);
4645
4646         /* if layout lock was granted right away, the layout is returned
4647          * within DLM_LVB of dlm reply; otherwise if the lock was ever
4648          * blocked and then granted via completion ast, we have to fetch
4649          * layout here. Please note that we can't use the LVB buffer in
4650          * completion AST because it doesn't have a large enough buffer */
4651         rc = ll_get_default_mdsize(sbi, &lmmsize);
4652         if (rc == 0)
4653                 rc = md_getxattr(sbi->ll_md_exp, ll_inode2fid(inode),
4654                                 OBD_MD_FLXATTR, XATTR_NAME_LOV, NULL, 0,
4655                                 lmmsize, 0, &req);
4656         if (rc < 0)
4657                 RETURN(rc);
4658
4659         body = req_capsule_server_get(&req->rq_pill, &RMF_MDT_BODY);
4660         if (body == NULL)
4661                 GOTO(out, rc = -EPROTO);
4662
4663         lmmsize = body->mbo_eadatasize;
4664         if (lmmsize == 0) /* empty layout */
4665                 GOTO(out, rc = 0);
4666
4667         lmm = req_capsule_server_sized_get(&req->rq_pill, &RMF_EADATA, lmmsize);
4668         if (lmm == NULL)
4669                 GOTO(out, rc = -EFAULT);
4670
4671         OBD_ALLOC_LARGE(lvbdata, lmmsize);
4672         if (lvbdata == NULL)
4673                 GOTO(out, rc = -ENOMEM);
4674
4675         memcpy(lvbdata, lmm, lmmsize);
4676         lock_res_and_lock(lock);
4677         if (unlikely(lock->l_lvb_data == NULL)) {
4678                 lock->l_lvb_type = LVB_T_LAYOUT;
4679                 lock->l_lvb_data = lvbdata;
4680                 lock->l_lvb_len = lmmsize;
4681                 lvbdata = NULL;
4682         }
4683         unlock_res_and_lock(lock);
4684
4685         if (lvbdata)
4686                 OBD_FREE_LARGE(lvbdata, lmmsize);
4687
4688         EXIT;
4689
4690 out:
4691         ptlrpc_req_finished(req);
4692         return rc;
4693 }
4694
4695 /**
4696  * Apply the layout to the inode. Layout lock is held and will be released
4697  * in this function.
4698  */
4699 static int ll_layout_lock_set(struct lustre_handle *lockh, enum ldlm_mode mode,
4700                               struct inode *inode)
4701 {
4702         struct ll_inode_info *lli = ll_i2info(inode);
4703         struct ll_sb_info    *sbi = ll_i2sbi(inode);
4704         struct ldlm_lock *lock;
4705         struct cl_object_conf conf;
4706         int rc = 0;
4707         bool lvb_ready;
4708         bool wait_layout = false;
4709         ENTRY;
4710
4711         LASSERT(lustre_handle_is_used(lockh));
4712
4713         lock = ldlm_handle2lock(lockh);
4714         LASSERT(lock != NULL);
4715         LASSERT(ldlm_has_layout(lock));
4716
4717         LDLM_DEBUG(lock, "file "DFID"(%p) being reconfigured",
4718                    PFID(&lli->lli_fid), inode);
4719
4720         /* in case this is a caching lock and reinstate with new inode */
4721         md_set_lock_data(sbi->ll_md_exp, lockh, inode, NULL);
4722
4723         lock_res_and_lock(lock);
4724         lvb_ready = ldlm_is_lvb_ready(lock);
4725         unlock_res_and_lock(lock);
4726
4727         /* checking lvb_ready is racy but this is okay. The worst case is
4728          * that multi processes may configure the file on the same time. */
4729         if (lvb_ready)
4730                 GOTO(out, rc = 0);
4731
4732         rc = ll_layout_fetch(inode, lock);
4733         if (rc < 0)
4734                 GOTO(out, rc);
4735
4736         /* for layout lock, lmm is stored in lock's lvb.
4737          * lvb_data is immutable if the lock is held so it's safe to access it
4738          * without res lock.
4739          *
4740          * set layout to file. Unlikely this will fail as old layout was
4741          * surely eliminated */
4742         memset(&conf, 0, sizeof conf);
4743         conf.coc_opc = OBJECT_CONF_SET;
4744         conf.coc_inode = inode;
4745         conf.coc_lock = lock;
4746         conf.u.coc_layout.lb_buf = lock->l_lvb_data;
4747         conf.u.coc_layout.lb_len = lock->l_lvb_len;
4748         rc = ll_layout_conf(inode, &conf);
4749
4750         /* refresh layout failed, need to wait */
4751         wait_layout = rc == -EBUSY;
4752         EXIT;
4753 out:
4754         LDLM_LOCK_PUT(lock);
4755         ldlm_lock_decref(lockh, mode);
4756
4757         /* wait for IO to complete if it's still being used. */
4758         if (wait_layout) {
4759                 CDEBUG(D_INODE, "%s: "DFID"(%p) wait for layout reconf\n",
4760                        ll_get_fsname(inode->i_sb, NULL, 0),
4761                        PFID(&lli->lli_fid), inode);
4762
4763                 memset(&conf, 0, sizeof conf);
4764                 conf.coc_opc = OBJECT_CONF_WAIT;
4765                 conf.coc_inode = inode;
4766                 rc = ll_layout_conf(inode, &conf);
4767                 if (rc == 0)
4768                         rc = -EAGAIN;
4769
4770                 CDEBUG(D_INODE, "%s file="DFID" waiting layout return: %d\n",
4771                        ll_get_fsname(inode->i_sb, NULL, 0),
4772                        PFID(&lli->lli_fid), rc);
4773         }
4774         RETURN(rc);
4775 }
4776
4777 /**
4778  * Issue layout intent RPC to MDS.
4779  * \param inode [in]    file inode
4780  * \param intent [in]   layout intent
4781  *
4782  * \retval 0    on success
4783  * \retval < 0  error code
4784  */
4785 static int ll_layout_intent(struct inode *inode, struct layout_intent *intent)
4786 {
4787         struct ll_inode_info  *lli = ll_i2info(inode);
4788         struct ll_sb_info     *sbi = ll_i2sbi(inode);
4789         struct md_op_data     *op_data;
4790         struct lookup_intent it;
4791         struct ptlrpc_request *req;
4792         int rc;
4793         ENTRY;
4794
4795         op_data = ll_prep_md_op_data(NULL, inode, inode, NULL,
4796                                      0, 0, LUSTRE_OPC_ANY, NULL);
4797         if (IS_ERR(op_data))
4798                 RETURN(PTR_ERR(op_data));
4799
4800         op_data->op_data = intent;
4801         op_data->op_data_size = sizeof(*intent);
4802
4803         memset(&it, 0, sizeof(it));
4804         it.it_op = IT_LAYOUT;
4805         if (intent->li_opc == LAYOUT_INTENT_WRITE ||
4806             intent->li_opc == LAYOUT_INTENT_TRUNC)
4807                 it.it_flags = FMODE_WRITE;
4808
4809         LDLM_DEBUG_NOLOCK("%s: requeue layout lock for file "DFID"(%p)",
4810                           ll_get_fsname(inode->i_sb, NULL, 0),
4811                           PFID(&lli->lli_fid), inode);
4812
4813         rc = md_intent_lock(sbi->ll_md_exp, op_data, &it, &req,
4814                             &ll_md_blocking_ast, 0);
4815         if (it.it_request != NULL)
4816                 ptlrpc_req_finished(it.it_request);
4817         it.it_request = NULL;
4818
4819         ll_finish_md_op_data(op_data);
4820
4821         /* set lock data in case this is a new lock */
4822         if (!rc)
4823                 ll_set_lock_data(sbi->ll_md_exp, inode, &it, NULL);
4824
4825         ll_intent_drop_lock(&it);
4826
4827         RETURN(rc);
4828 }
4829
4830 /**
4831  * This function checks if there exists a LAYOUT lock on the client side,
4832  * or enqueues it if it doesn't have one in cache.
4833  *
4834  * This function will not hold layout lock so it may be revoked any time after
4835  * this function returns. Any operations depend on layout should be redone
4836  * in that case.
4837  *
4838  * This function should be called before lov_io_init() to get an uptodate
4839  * layout version, the caller should save the version number and after IO
4840  * is finished, this function should be called again to verify that layout
4841  * is not changed during IO time.
4842  */
4843 int ll_layout_refresh(struct inode *inode, __u32 *gen)
4844 {
4845         struct ll_inode_info    *lli = ll_i2info(inode);
4846         struct ll_sb_info       *sbi = ll_i2sbi(inode);
4847         struct lustre_handle lockh;
4848         struct layout_intent intent = {
4849                 .li_opc = LAYOUT_INTENT_ACCESS,
4850         };
4851         enum ldlm_mode mode;
4852         int rc;
4853         ENTRY;
4854
4855         *gen = ll_layout_version_get(lli);
4856         if (!(sbi->ll_flags & LL_SBI_LAYOUT_LOCK) || *gen != CL_LAYOUT_GEN_NONE)
4857                 RETURN(0);
4858
4859         /* sanity checks */
4860         LASSERT(fid_is_sane(ll_inode2fid(inode)));
4861         LASSERT(S_ISREG(inode->i_mode));
4862
4863         /* take layout lock mutex to enqueue layout lock exclusively. */
4864         mutex_lock(&lli->lli_layout_mutex);
4865
4866         while (1) {
4867                 /* mostly layout lock is caching on the local side, so try to
4868                  * match it before grabbing layout lock mutex. */
4869                 mode = ll_take_md_lock(inode, MDS_INODELOCK_LAYOUT, &lockh, 0,
4870                                        LCK_CR | LCK_CW | LCK_PR | LCK_PW);
4871                 if (mode != 0) { /* hit cached lock */
4872                         rc = ll_layout_lock_set(&lockh, mode, inode);
4873                         if (rc == -EAGAIN)
4874                                 continue;
4875                         break;
4876                 }
4877
4878                 rc = ll_layout_intent(inode, &intent);
4879                 if (rc != 0)
4880                         break;
4881         }
4882
4883         if (rc == 0)
4884                 *gen = ll_layout_version_get(lli);
4885         mutex_unlock(&lli->lli_layout_mutex);
4886
4887         RETURN(rc);
4888 }
4889
4890 /**
4891  * Issue layout intent RPC indicating where in a file an IO is about to write.
4892  *
4893  * \param[in] inode     file inode.
4894  * \param[in] ext       write range with start offset of fille in bytes where
4895  *                      an IO is about to write, and exclusive end offset in
4896  *                      bytes.
4897  *
4898  * \retval 0    on success
4899  * \retval < 0  error code
4900  */
4901 int ll_layout_write_intent(struct inode *inode, enum layout_intent_opc opc,
4902                            struct lu_extent *ext)
4903 {
4904         struct layout_intent intent = {
4905                 .li_opc = opc,
4906                 .li_extent.e_start = ext->e_start,
4907                 .li_extent.e_end = ext->e_end,
4908         };
4909         int rc;
4910         ENTRY;
4911
4912         rc = ll_layout_intent(inode, &intent);
4913
4914         RETURN(rc);
4915 }
4916
4917 /**
4918  *  This function send a restore request to the MDT
4919  */
4920 int ll_layout_restore(struct inode *inode, loff_t offset, __u64 length)
4921 {
4922         struct hsm_user_request *hur;
4923         int                      len, rc;
4924         ENTRY;
4925
4926         len = sizeof(struct hsm_user_request) +
4927               sizeof(struct hsm_user_item);
4928         OBD_ALLOC(hur, len);
4929         if (hur == NULL)
4930                 RETURN(-ENOMEM);
4931
4932         hur->hur_request.hr_action = HUA_RESTORE;
4933         hur->hur_request.hr_archive_id = 0;
4934         hur->hur_request.hr_flags = 0;
4935         memcpy(&hur->hur_user_item[0].hui_fid, &ll_i2info(inode)->lli_fid,
4936                sizeof(hur->hur_user_item[0].hui_fid));
4937         hur->hur_user_item[0].hui_extent.offset = offset;
4938         hur->hur_user_item[0].hui_extent.length = length;
4939         hur->hur_request.hr_itemcount = 1;
4940         rc = obd_iocontrol(LL_IOC_HSM_REQUEST, ll_i2sbi(inode)->ll_md_exp,
4941                            len, hur, NULL);
4942         OBD_FREE(hur, len);
4943         RETURN(rc);
4944 }