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