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