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