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