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