Whamcloud - gitweb
LU-13802 llite: add fail loc to force bio-dio switch
[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_get_atime(inode);
115         op_data->op_attr.ia_mtime = inode_get_mtime(inode);
116         op_data->op_attr.ia_ctime = inode_get_ctime(inode);
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_get_atime_sec(inode) < lli->lli_atime)
1499                 inode_set_atime(inode, lli->lli_atime, 0);
1500
1501         inode_set_mtime(inode, lli->lli_mtime, 0);
1502         inode_set_ctime(inode, lli->lli_ctime, 0);
1503
1504         mtime = inode_get_mtime_sec(inode);
1505         atime = inode_get_atime_sec(inode);
1506         ctime = inode_get_ctime_sec(inode);
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_set_mtime(inode, mtime, 0);
1544         inode_set_atime(inode, atime, 0);
1545         inode_set_ctime(inode, ctime, 0);
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         struct timespec64 ts;
1609         struct timespec64 atime;
1610
1611         if (!(mnt->mnt_flags & MNT_RELATIME))
1612                 return 1;
1613         /*
1614          * Is mtime younger than atime? If yes, update atime:
1615          */
1616         atime = inode_get_atime(inode);
1617         ts = inode_get_mtime(inode);
1618         if (timespec64_compare(&ts, &atime) >= 0)
1619                 return 1;
1620         /*
1621          * Is ctime younger than atime? If yes, update atime:
1622          */
1623         ts = inode_get_ctime(inode);
1624         if (timespec64_compare(&ts, &atime) >= 0)
1625                 return 1;
1626
1627         /*
1628          * Is the previous atime value older than a day? If yes,
1629          * update atime:
1630          */
1631         if ((long)(now.tv_sec - atime.tv_sec) >= 24*60*60)
1632                 return 1;
1633         /*
1634          * Good, we can skip the atime update:
1635          */
1636         return 0;
1637 }
1638
1639 /*
1640  * Very similar to kernel function: !__atime_needs_update()
1641  */
1642 static bool file_is_noatime(const struct file *file)
1643 {
1644         struct vfsmount *mnt = file->f_path.mnt;
1645         struct inode *inode = file_inode((struct file *)file);
1646         struct timespec64 now;
1647
1648         if (file->f_flags & O_NOATIME)
1649                 return true;
1650
1651         if (inode->i_flags & S_NOATIME)
1652                 return true;
1653
1654         if (IS_NOATIME(inode))
1655                 return true;
1656
1657         if (mnt->mnt_flags & (MNT_NOATIME | MNT_READONLY))
1658                 return true;
1659
1660         if ((mnt->mnt_flags & MNT_NODIRATIME) && S_ISDIR(inode->i_mode))
1661                 return true;
1662
1663         if ((inode->i_sb->s_flags & SB_NODIRATIME) && S_ISDIR(inode->i_mode))
1664                 return true;
1665
1666         now = current_time(inode);
1667
1668         if (!relatime_need_update(mnt, inode, now))
1669                 return true;
1670
1671         return false;
1672 }
1673
1674 void ll_io_init(struct cl_io *io, struct file *file, enum cl_io_type iot,
1675                 struct vvp_io_args *args)
1676 {
1677         struct inode *inode = file_inode(file);
1678         struct ll_file_data *fd  = file->private_data;
1679         int flags = vvp_io_args_flags(file, args);
1680
1681         io->u.ci_rw.crw_nonblock = file->f_flags & O_NONBLOCK;
1682         io->ci_lock_no_expand = fd->ll_lock_no_expand;
1683
1684         if (iot == CIT_WRITE) {
1685                 io->u.ci_wr.wr_append = iocb_ki_flags_check(flags, APPEND);
1686                 io->u.ci_wr.wr_sync   = !!(iocb_ki_flags_check(flags, SYNC) ||
1687                                            iocb_ki_flags_check(flags, DSYNC) ||
1688                                            IS_SYNC(inode));
1689         }
1690
1691 #ifdef IOCB_NOWAIT
1692         io->ci_iocb_nowait = iocb_ki_flags_check(flags, NOWAIT);
1693 #endif
1694
1695         io->ci_obj = ll_i2info(inode)->lli_clob;
1696         io->ci_lockreq = CILR_MAYBE;
1697         if (ll_file_nolock(file)) {
1698                 io->ci_lockreq = CILR_NEVER;
1699                 io->ci_no_srvlock = 1;
1700         } else if (iocb_ki_flags_check(flags, APPEND)) {
1701                 io->ci_lockreq = CILR_MANDATORY;
1702         }
1703         io->ci_noatime = file_is_noatime(file);
1704         io->ci_async_readahead = false;
1705
1706         /* FLR: only use non-delay I/O for read as there is only one
1707          * avaliable mirror for write. */
1708         io->ci_ndelay = !(iot == CIT_WRITE);
1709         /* unaligned DIO has compat issues with some older servers, but we find
1710          * out if there are such servers while setting up the IO, so it starts
1711          * out allowed
1712          */
1713         io->ci_allow_unaligned_dio = true;
1714         if (args)
1715                 io->ci_hybrid_switched = args->via_hybrid_switched;
1716
1717         ll_io_set_mirror(io, file);
1718 }
1719
1720 static void ll_heat_add(struct inode *inode, enum cl_io_type iot,
1721                         __u64 count)
1722 {
1723         struct ll_inode_info *lli = ll_i2info(inode);
1724         struct ll_sb_info *sbi = ll_i2sbi(inode);
1725         enum obd_heat_type sample_type;
1726         enum obd_heat_type iobyte_type;
1727         __u64 now = ktime_get_real_seconds();
1728
1729         if (!ll_sbi_has_file_heat(sbi) ||
1730             lli->lli_heat_flags & LU_HEAT_FLAG_OFF)
1731                 return;
1732
1733         if (iot == CIT_READ) {
1734                 sample_type = OBD_HEAT_READSAMPLE;
1735                 iobyte_type = OBD_HEAT_READBYTE;
1736         } else if (iot == CIT_WRITE) {
1737                 sample_type = OBD_HEAT_WRITESAMPLE;
1738                 iobyte_type = OBD_HEAT_WRITEBYTE;
1739         } else {
1740                 return;
1741         }
1742
1743         spin_lock(&lli->lli_heat_lock);
1744         obd_heat_add(&lli->lli_heat_instances[sample_type], now, 1,
1745                      sbi->ll_heat_decay_weight, sbi->ll_heat_period_second);
1746         obd_heat_add(&lli->lli_heat_instances[iobyte_type], now, count,
1747                      sbi->ll_heat_decay_weight, sbi->ll_heat_period_second);
1748         spin_unlock(&lli->lli_heat_lock);
1749 }
1750
1751 static bool
1752 ll_hybrid_bio_dio_switch_check(struct file *file, struct kiocb *iocb,
1753                                enum cl_io_type iot, size_t count)
1754 {
1755         /* we can only do this with IOCB_FLAGS, since we can't modify f_flags
1756          * because they're visible in userspace.  so we check for IOCB_DIRECT
1757          */
1758 #ifdef IOCB_DIRECT
1759         struct inode *inode = file_inode(file);
1760         struct ll_sb_info *sbi = ll_i2sbi(inode);
1761
1762         ENTRY;
1763
1764         /* it doesn't make sense to switch unless it's READ or WRITE */
1765         if (iot != CIT_WRITE && iot != CIT_READ)
1766                 RETURN(false);
1767
1768         if (!iocb)
1769                 RETURN(false);
1770
1771         /* Already using direct I/O, no need to switch. */
1772         if (iocb->ki_flags & IOCB_DIRECT)
1773                 RETURN(false);
1774
1775         if (!test_bit(LL_SBI_HYBRID_IO, sbi->ll_flags))
1776                 RETURN(false);
1777 #endif
1778         RETURN(false);
1779 }
1780
1781 static ssize_t
1782 ll_file_io_generic(const struct lu_env *env, struct vvp_io_args *args,
1783                    struct file *file, enum cl_io_type iot,
1784                    loff_t *ppos, size_t bytes)
1785 {
1786         struct inode *inode = file_inode(file);
1787         struct ll_file_data *fd  = file->private_data;
1788         struct ll_inode_info *lli = ll_i2info(inode);
1789         struct ll_sb_info *sbi = ll_i2sbi(inode);
1790         struct vvp_io *vio = vvp_env_io(env);
1791         struct cl_dio_aio *ci_dio_aio = NULL;
1792         struct range_lock range;
1793         struct cl_io *io;
1794         int flags = vvp_io_args_flags(file, args);
1795         bool is_parallel_dio = false;
1796         bool range_locked = false;
1797         unsigned int retried = 0;
1798         bool dio_lock = false;
1799         bool is_aio = false;
1800         size_t max_io_bytes;
1801         ssize_t result = 0;
1802         int retries = 1000;
1803         size_t per_bytes;
1804         bool partial_io;
1805         int rc2 = 0;
1806         int rc = 0;
1807
1808         ENTRY;
1809
1810         CDEBUG(D_VFSTRACE, "%s: %s ppos: %llu, bytes: %zu\n",
1811                 file_dentry(file)->d_name.name,
1812                 iot == CIT_READ ? "read" : "write", *ppos, bytes);
1813
1814         max_io_bytes = min_t(size_t, PTLRPC_MAX_BRW_PAGES * OBD_MAX_RIF_DEFAULT,
1815                              sbi->ll_cache->ccc_lru_max >> 2) << PAGE_SHIFT;
1816
1817         io = vvp_env_thread_io(env);
1818         if (iocb_ki_flags_check(flags, DIRECT)) {
1819                 if (iocb_ki_flags_check(flags, APPEND))
1820                         dio_lock = true;
1821                 if (!is_sync_kiocb(args->u.normal.via_iocb) &&
1822                 /* hybrid IO is also potentially async */
1823                     !args->via_hybrid_switched)
1824                         is_aio = true;
1825
1826                 /* the kernel does not support AIO on pipes, and parallel DIO
1827                  * uses part of the AIO path, so we must not do parallel dio
1828                  * to pipes
1829                  */
1830                 is_parallel_dio = !iov_iter_is_pipe(args->u.normal.via_iter) &&
1831                                   !is_aio;
1832
1833                 if (!ll_sbi_has_parallel_dio(sbi))
1834                         is_parallel_dio = false;
1835
1836                 ci_dio_aio = cl_dio_aio_alloc(args->u.normal.via_iocb,
1837                                           ll_i2info(inode)->lli_clob, is_aio);
1838                 if (!ci_dio_aio)
1839                         GOTO(out, rc = -ENOMEM);
1840         }
1841
1842 restart:
1843         /**
1844          * IO block size need be aware of cached page limit, otherwise
1845          * if we have small max_cached_mb but large block IO issued, io
1846          * could not be finished and blocked whole client.
1847          */
1848         if (iocb_ki_flags_check(flags, DIRECT) || bytes < max_io_bytes) {
1849                 per_bytes = bytes;
1850                 partial_io = false;
1851         } else {
1852                 per_bytes = max_io_bytes;
1853                 partial_io = true;
1854         }
1855         io = vvp_env_thread_io(env);
1856         ll_io_init(io, file, iot, args);
1857         io->ci_dio_aio = ci_dio_aio;
1858         io->ci_dio_lock = dio_lock;
1859         io->ci_ndelay_tried = retried;
1860         io->ci_parallel_dio = is_parallel_dio;
1861
1862         if (cl_io_rw_init(env, io, iot, *ppos, per_bytes) == 0) {
1863                 if (iocb_ki_flags_check(flags, APPEND))
1864                         range_lock_init(&range, 0, LUSTRE_EOF);
1865                 else
1866                         range_lock_init(&range, *ppos, *ppos + per_bytes - 1);
1867
1868                 vio->vui_fd  = file->private_data;
1869                 vio->vui_iter = args->u.normal.via_iter;
1870                 vio->vui_iocb = args->u.normal.via_iocb;
1871                 /* Direct IO reads must also take range lock,
1872                  * or multiple reads will try to work on the same pages
1873                  * See LU-6227 for details.
1874                  */
1875                 if (((iot == CIT_WRITE) ||
1876                     (iot == CIT_READ && iocb_ki_flags_check(flags, DIRECT))) &&
1877                     !(vio->vui_fd->fd_flags & LL_FILE_GROUP_LOCKED)) {
1878                         CDEBUG(D_VFSTRACE, "Range lock "RL_FMT"\n",
1879                                RL_PARA(&range));
1880                         rc = range_lock(&lli->lli_write_tree, &range);
1881                         if (rc < 0)
1882                                 GOTO(out, rc);
1883
1884                         range_locked = true;
1885                 }
1886
1887                 ll_cl_add(inode, env, io, LCC_RW);
1888                 rc = cl_io_loop(env, io);
1889                 ll_cl_remove(inode, env);
1890         } else {
1891                 /* cl_io_rw_init() handled IO */
1892                 rc = io->ci_result;
1893         }
1894
1895         if (io->ci_dio_aio && !is_aio) {
1896                 struct cl_sync_io *anchor = &io->ci_dio_aio->cda_sync;
1897
1898                 /* for dio, EIOCBQUEUED is an implementation detail,
1899                  * and we don't return it to userspace
1900                  */
1901                 if (rc == -EIOCBQUEUED)
1902                         rc = 0;
1903
1904                 /* N/B: parallel DIO may be disabled during i/o submission;
1905                  * if that occurs, I/O shifts to sync, so it's all resolved
1906                  * before we get here, and this wait call completes
1907                  * immediately.
1908                  */
1909                 rc2 = cl_sync_io_wait_recycle(env, anchor, 0, 0);
1910                 if (rc2 < 0)
1911                         rc = rc2;
1912         }
1913
1914         if (range_locked) {
1915                 CDEBUG(D_VFSTRACE, "Range unlock "RL_FMT"\n",
1916                        RL_PARA(&range));
1917                 range_unlock(&lli->lli_write_tree, &range);
1918                         range_locked = false;
1919         }
1920
1921         if (io->ci_bytes > 0) {
1922                 if (rc2 == 0) {
1923                         result += io->ci_bytes;
1924                         *ppos = io->u.ci_wr.wr.crw_pos; /* for splice */
1925                 } else if (rc2) {
1926                         result = 0;
1927                 }
1928                 bytes -= io->ci_bytes;
1929
1930                 /* prepare IO restart */
1931                 if (bytes > 0)
1932                         args->u.normal.via_iter = vio->vui_iter;
1933
1934                 if (partial_io) {
1935                         /**
1936                          * Reexpand iov count because it was zero
1937                          * after IO finish.
1938                          */
1939                         iov_iter_reexpand(vio->vui_iter, bytes);
1940                         if (per_bytes == io->ci_bytes)
1941                                 io->ci_need_restart = 1;
1942                 }
1943         }
1944 out:
1945         cl_io_fini(env, io);
1946
1947         CDEBUG(D_VFSTRACE,
1948                "%s: %d io complete with rc: %d, result: %zd, restart: %d\n",
1949                file->f_path.dentry->d_name.name,
1950                iot, rc, result, io->ci_need_restart);
1951
1952         if ((!rc || rc == -ENODATA || rc == -ENOLCK || rc == -EIOCBQUEUED) &&
1953             bytes > 0 && io->ci_need_restart && retries-- > 0) {
1954                 CDEBUG(D_VFSTRACE,
1955                        "%s: restart %s from ppos=%lld bytes=%zu retries=%u ret=%zd: rc = %d\n",
1956                        file_dentry(file)->d_name.name,
1957                        iot == CIT_READ ? "read" : "write",
1958                        *ppos, bytes, retries, result, rc);
1959                 /* preserve the tried count for FLR */
1960                 retried = io->ci_ndelay_tried;
1961                 dio_lock = io->ci_dio_lock;
1962                 goto restart;
1963         }
1964
1965         if (io->ci_dio_aio) {
1966                 /* set the number of bytes successfully moved in the aio */
1967                 if (result > 0)
1968                         io->ci_dio_aio->cda_bytes = result;
1969                 /*
1970                  * VFS will call aio_complete() if no -EIOCBQUEUED
1971                  * is returned for AIO, so we can not call aio_complete()
1972                  * in our end_io().  (cda_no_aio_complete is always set for
1973                  * normal DIO.)
1974                  *
1975                  * NB: Setting cda_no_aio_complete like this is safe because
1976                  * the atomic_dec_and_lock in cl_sync_io_note has implicit
1977                  * memory barriers, so this will be seen by whichever thread
1978                  * completes the DIO/AIO, even if it's not this one.
1979                  */
1980                 if (is_aio && rc != -EIOCBQUEUED)
1981                         io->ci_dio_aio->cda_no_aio_complete = 1;
1982                 /* if an aio enqueued successfully (-EIOCBQUEUED), then Lustre
1983                  * will call aio_complete rather than the vfs, so we return 0
1984                  * to tell the VFS we're handling it
1985                  */
1986                 else if (is_aio) /* rc == -EIOCBQUEUED */
1987                         result = 0;
1988                 /**
1989                  * Drop the reference held by the llite layer on this top level
1990                  * IO context.
1991                  *
1992                  * For DIO, this frees it here, since IO is complete, and for
1993                  * AIO, we will call aio_complete() (and then free this top
1994                  * level context) once all the outstanding chunks of this AIO
1995                  * have completed.
1996                  */
1997                 cl_sync_io_note(env, &io->ci_dio_aio->cda_sync,
1998                                 rc == -EIOCBQUEUED ? 0 : rc);
1999                 if (!is_aio) {
2000                         LASSERT(io->ci_dio_aio->cda_creator_free);
2001                         cl_dio_aio_free(env, io->ci_dio_aio);
2002                         io->ci_dio_aio = NULL;
2003                 }
2004         }
2005
2006         if (iot == CIT_READ) {
2007                 if (result > 0)
2008                         ll_stats_ops_tally(ll_i2sbi(inode),
2009                                            LPROC_LL_READ_BYTES, result);
2010         } else if (iot == CIT_WRITE) {
2011                 if (result > 0) {
2012                         ll_stats_ops_tally(ll_i2sbi(inode),
2013                                            LPROC_LL_WRITE_BYTES, result);
2014                         fd->fd_write_failed = false;
2015                 } else if (result == 0 && rc == 0) {
2016                         rc = io->ci_result;
2017                         if (rc < 0)
2018                                 fd->fd_write_failed = true;
2019                         else
2020                                 fd->fd_write_failed = false;
2021                 } else if (rc != -ERESTARTSYS) {
2022                         fd->fd_write_failed = true;
2023                 }
2024         }
2025
2026         CDEBUG(D_VFSTRACE, "iot: %d, result: %zd\n", iot, result);
2027         if (result > 0)
2028                 ll_heat_add(inode, iot, result);
2029
2030         RETURN(result > 0 ? result : rc);
2031 }
2032
2033 /**
2034  * The purpose of fast read is to overcome per I/O overhead and improve IOPS
2035  * especially for small I/O.
2036  *
2037  * To serve a read request, CLIO has to create and initialize a cl_io and
2038  * then request DLM lock. This has turned out to have siginificant overhead
2039  * and affects the performance of small I/O dramatically.
2040  *
2041  * It's not necessary to create a cl_io for each I/O. Under the help of read
2042  * ahead, most of the pages being read are already in memory cache and we can
2043  * read those pages directly because if the pages exist, the corresponding DLM
2044  * lock must exist so that page content must be valid.
2045  *
2046  * In fast read implementation, the llite speculatively finds and reads pages
2047  * in memory cache. There are three scenarios for fast read:
2048  *   - If the page exists and is uptodate, kernel VM will provide the data and
2049  *     CLIO won't be intervened;
2050  *   - If the page was brought into memory by read ahead, it will be exported
2051  *     and read ahead parameters will be updated;
2052  *   - Otherwise the page is not in memory, we can't do fast read. Therefore,
2053  *     it will go back and invoke normal read, i.e., a cl_io will be created
2054  *     and DLM lock will be requested.
2055  *
2056  * POSIX compliance: posix standard states that read is intended to be atomic.
2057  * Lustre read implementation is in line with Linux kernel read implementation
2058  * and neither of them complies with POSIX standard in this matter. Fast read
2059  * doesn't make the situation worse on single node but it may interleave write
2060  * results from multiple nodes due to short read handling in ll_file_aio_read().
2061  *
2062  * \param env - lu_env
2063  * \param iocb - kiocb from kernel
2064  * \param iter - user space buffers where the data will be copied
2065  *
2066  * \retval - number of bytes have been read, or error code if error occurred.
2067  */
2068 static ssize_t
2069 ll_do_fast_read(struct kiocb *iocb, struct iov_iter *iter)
2070 {
2071         struct ll_inode_info *lli = ll_i2info(file_inode(iocb->ki_filp));
2072         int flags = iocb_ki_flags_get(iocb->ki_filp, iocb);
2073         ssize_t result;
2074
2075         if (!ll_sbi_has_fast_read(ll_i2sbi(file_inode(iocb->ki_filp))))
2076                 return 0;
2077
2078         /* NB: we can't do direct IO for fast read because it will need a lock
2079          * to make IO engine happy. */
2080         if (iocb_ki_flags_check(flags, DIRECT))
2081                 return 0;
2082
2083         if (ll_layout_version_get(lli) == CL_LAYOUT_GEN_NONE)
2084                 return 0;
2085
2086         result = generic_file_read_iter(iocb, iter);
2087
2088         /* If the first page is not in cache, generic_file_aio_read() will be
2089          * returned with -ENODATA.  Fall back to full read path.
2090          * See corresponding code in ll_readpage().
2091          *
2092          * if we raced with page deletion, we might get EIO.  Rather than add
2093          * locking to the fast path for this rare case, fall back to the full
2094          * read path.  (See vvp_io_read_start() for rest of handling.
2095          */
2096         if (result == -ENODATA || result == -EIO)
2097                 result = 0;
2098
2099         if (result > 0) {
2100                 ll_heat_add(file_inode(iocb->ki_filp), CIT_READ, result);
2101                 ll_stats_ops_tally(ll_i2sbi(file_inode(iocb->ki_filp)),
2102                                    LPROC_LL_READ_BYTES, result);
2103         }
2104
2105         return result;
2106 }
2107
2108 /**
2109  * Confine read iter lest read beyond the EOF
2110  *
2111  * \param iocb [in]     kernel iocb
2112  * \param to [in]       reader iov_iter
2113  *
2114  * \retval <0   failure
2115  * \retval 0    success
2116  * \retval >0   @iocb->ki_pos has passed the EOF
2117  */
2118 static int file_read_confine_iter(struct lu_env *env, struct kiocb *iocb,
2119                                   struct iov_iter *to)
2120 {
2121         struct cl_io *io;
2122         struct cl_attr *attr = vvp_env_thread_attr(env);
2123         struct file *file = iocb->ki_filp;
2124         struct inode *inode = file_inode(file);
2125         struct ll_inode_info *lli = ll_i2info(inode);
2126         struct cl_object *obj = lli->lli_clob;
2127         loff_t read_end = iocb->ki_pos + iov_iter_count(to);
2128         loff_t kms;
2129         loff_t size;
2130         int rc = 0;
2131
2132         ENTRY;
2133
2134         if (!obj)
2135                 RETURN(rc);
2136
2137         io = vvp_env_thread_io(env);
2138         io->ci_obj = obj;
2139         rc = cl_io_init(env, io, CIT_MISC, obj);
2140         if (rc < 0)
2141                 GOTO(fini_io, rc);
2142
2143         cl_object_attr_lock(lli->lli_clob);
2144         rc = cl_object_attr_get(env, lli->lli_clob, attr);
2145         cl_object_attr_unlock(lli->lli_clob);
2146
2147 fini_io:
2148         cl_io_fini(env, io);
2149         if (rc < 0)
2150                 RETURN(rc);
2151
2152         kms = attr->cat_kms;
2153         /* if read beyond end-of-file, adjust read count */
2154         if (kms > 0 && (iocb->ki_pos >= kms || read_end > kms)) {
2155                 rc = ll_glimpse_size(inode);
2156                 if (rc != 0)
2157                         return rc;
2158
2159                 size = i_size_read(inode);
2160                 if (iocb->ki_pos >= size || read_end > size) {
2161                         CDEBUG(D_VFSTRACE,
2162                                "%s: read [%llu, %llu] over eof, kms %llu, file_size %llu.\n",
2163                                file_dentry(file)->d_name.name,
2164                                iocb->ki_pos, read_end, kms, size);
2165
2166                         if (iocb->ki_pos >= size)
2167                                 RETURN(1);
2168
2169                         if (read_end > size)
2170                                 iov_iter_truncate(to, size - iocb->ki_pos);
2171                 }
2172         }
2173
2174         RETURN(rc);
2175 }
2176
2177 /*
2178  * Read from a file (through the page cache).
2179  */
2180 static ssize_t ll_file_read_iter(struct kiocb *iocb, struct iov_iter *to)
2181 {
2182         struct lu_env *env;
2183         struct vvp_io_args *args;
2184         struct file *file = iocb->ki_filp;
2185         loff_t orig_ki_pos = iocb->ki_pos;
2186         ssize_t result;
2187         ssize_t rc2;
2188         __u16 refcheck;
2189         ktime_t kstart = ktime_get();
2190         bool cached;
2191         bool stale_data = false;
2192
2193         ENTRY;
2194
2195         CDEBUG(D_VFSTRACE|D_IOTRACE,
2196                "START file %s:"DFID", ppos: %lld, count: %zu\n",
2197                file_dentry(file)->d_name.name,
2198                PFID(ll_inode2fid(file_inode(file))), iocb->ki_pos,
2199                iov_iter_count(to));
2200
2201         if (!iov_iter_count(to))
2202                 RETURN(0);
2203
2204         env = cl_env_get(&refcheck);
2205         if (IS_ERR(env))
2206                 RETURN(PTR_ERR(env));
2207
2208         result = file_read_confine_iter(env, iocb, to);
2209         if (result < 0)
2210                 GOTO(out, result);
2211         else if (result > 0)
2212                 stale_data = true;
2213
2214         CFS_FAIL_TIMEOUT_ORSET(OBD_FAIL_LLITE_READ_PAUSE, CFS_FAIL_ONCE,
2215                                cfs_fail_val);
2216         /**
2217          * Currently when PCC read failed, we do not fall back to the
2218          * normal read path, just return the error.
2219          * The resaon is that: for RW-PCC, the file data may be modified
2220          * in the PCC and inconsistent with the data on OSTs (or file
2221          * data has been removed from the Lustre file system), at this
2222          * time, fallback to the normal read path may read the wrong
2223          * data.
2224          * TODO: for RO-PCC (readonly PCC), fall back to normal read
2225          * path: read data from data copy on OSTs.
2226          */
2227         result = pcc_file_read_iter(iocb, to, &cached);
2228         if (cached)
2229                 GOTO(out, result);
2230
2231         ll_ras_enter(file, iocb->ki_pos, iov_iter_count(to));
2232
2233         args = ll_env_args(env);
2234         args->u.normal.via_iter = to;
2235         args->u.normal.via_iocb = iocb;
2236
2237         if (ll_hybrid_bio_dio_switch_check(file, iocb, CIT_READ,
2238                                            iov_iter_count(to)) ||
2239             CFS_FAIL_CHECK(OBD_FAIL_LLITE_FORCE_BIO_AS_DIO)) {
2240 #ifdef IOCB_DIRECT
2241                 iocb->ki_flags |= IOCB_DIRECT;
2242                 CDEBUG(D_VFSTRACE, "switching to DIO\n");
2243                 args->via_hybrid_switched = 1;
2244 #endif
2245         }
2246
2247         result = ll_do_fast_read(iocb, to);
2248         if (result < 0 || iov_iter_count(to) == 0)
2249                 GOTO(out, result);
2250
2251         rc2 = ll_file_io_generic(env, args, file, CIT_READ,
2252                                  &iocb->ki_pos, iov_iter_count(to));
2253         if (rc2 > 0)
2254                 result += rc2;
2255         else if (result == 0)
2256                 result = rc2;
2257
2258 out:
2259         cl_env_put(env, &refcheck);
2260
2261         if (stale_data && result > 0) {
2262                 /**
2263                  * we've reached EOF before the read, the data read are cached
2264                  * stale data.
2265                  */
2266                 iocb->ki_pos = orig_ki_pos;
2267                 iov_iter_truncate(to, 0);
2268                 result = 0;
2269         }
2270
2271         if (result > 0) {
2272                 ll_rw_stats_tally(ll_i2sbi(file_inode(file)), current->pid,
2273                                   file->private_data, iocb->ki_pos, result,
2274                                   READ);
2275                 ll_stats_ops_tally(ll_i2sbi(file_inode(file)), LPROC_LL_READ,
2276                                    ktime_us_delta(ktime_get(), kstart));
2277         }
2278
2279         CDEBUG(D_IOTRACE,
2280                "COMPLETED: file %s:"DFID", ppos: %lld, count: %zu, rc = %zu\n",
2281                file_dentry(file)->d_name.name,
2282                PFID(ll_inode2fid(file_inode(file))), iocb->ki_pos,
2283                iov_iter_count(to), result);
2284
2285         RETURN(result);
2286 }
2287
2288 /**
2289  * Similar trick to ll_do_fast_read, this improves write speed for tiny writes.
2290  * If a page is already in the page cache and dirty (and some other things -
2291  * See ll_tiny_write_begin for the instantiation of these rules), then we can
2292  * write to it without doing a full I/O, because Lustre already knows about it
2293  * and will write it out.  This saves a lot of processing time.
2294  *
2295  * All writes here are within one page, so exclusion is handled by the page
2296  * lock on the vm page.  We do not do tiny writes for writes which touch
2297  * multiple pages because it's very unlikely multiple sequential pages are
2298  * are already dirty.
2299  *
2300  * We limit these to < PAGE_SIZE because PAGE_SIZE writes are relatively common
2301  * and are unlikely to be to already dirty pages.
2302  *
2303  * Attribute updates are important here, we do them in ll_tiny_write_end.
2304  */
2305 static ssize_t ll_do_tiny_write(struct kiocb *iocb, struct iov_iter *iter)
2306 {
2307         ssize_t count = iov_iter_count(iter);
2308         struct  file *file = iocb->ki_filp;
2309         struct  inode *inode = file_inode(file);
2310         bool    lock_inode = !IS_NOSEC(inode);
2311         ssize_t result = 0;
2312
2313         ENTRY;
2314
2315         /* Restrict writes to single page and < PAGE_SIZE.  See comment at top
2316          * of function for why.
2317          */
2318         if (count >= PAGE_SIZE ||
2319             (iocb->ki_pos & (PAGE_SIZE-1)) + count > PAGE_SIZE)
2320                 RETURN(0);
2321
2322         if (unlikely(lock_inode))
2323                 ll_inode_lock(inode);
2324         result = __generic_file_write_iter(iocb, iter);
2325
2326         if (unlikely(lock_inode))
2327                 ll_inode_unlock(inode);
2328
2329         /* If the page is not already dirty, ll_tiny_write_begin returns
2330          * -ENODATA.  We continue on to normal write.
2331          */
2332         if (result == -ENODATA)
2333                 result = 0;
2334
2335         if (result > 0) {
2336                 ll_heat_add(inode, CIT_WRITE, result);
2337                 set_bit(LLIF_DATA_MODIFIED, &ll_i2info(inode)->lli_flags);
2338         }
2339
2340         CDEBUG(D_VFSTRACE, "result: %zu, original count %zu\n", result, count);
2341
2342         RETURN(result);
2343 }
2344
2345 /*
2346  * Write to a file (through the page cache).
2347  */
2348 static ssize_t ll_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
2349 {
2350         struct file *file = iocb->ki_filp;
2351         struct vvp_io_args *args;
2352         struct lu_env *env;
2353         int flags = iocb_ki_flags_get(file, iocb);
2354         ktime_t kstart = ktime_get();
2355         bool hybrid_switched = false;
2356         ssize_t rc_tiny = 0;
2357         ssize_t rc_normal;
2358         __u16 refcheck;
2359         bool cached;
2360         int result;
2361
2362         ENTRY;
2363
2364         CDEBUG(D_VFSTRACE|D_IOTRACE,
2365                "START file %s:"DFID", ppos: %lld, count: %zu\n",
2366                file_dentry(file)->d_name.name,
2367                PFID(ll_inode2fid(file_inode(file))), iocb->ki_pos,
2368                iov_iter_count(from));
2369
2370         if (!iov_iter_count(from))
2371                 GOTO(out, rc_normal = 0);
2372
2373         /**
2374          * When PCC write failed, we usually do not fall back to the normal
2375          * write path, just return the error. But there is a special case when
2376          * returned error code is -ENOSPC due to running out of space on PCC HSM
2377          * bakcend. At this time, it will fall back to normal I/O path and
2378          * retry the I/O. As the file is in HSM released state, it will restore
2379          * the file data to OSTs first and redo the write again. And the
2380          * restore process will revoke the layout lock and detach the file
2381          * from PCC cache automatically.
2382          */
2383         result = pcc_file_write_iter(iocb, from, &cached);
2384         if (cached && result != -ENOSPC && result != -EDQUOT)
2385                 GOTO(out, rc_normal = result);
2386
2387         if (ll_hybrid_bio_dio_switch_check(file, iocb, CIT_WRITE,
2388                                            iov_iter_count(from)) ||
2389             CFS_FAIL_CHECK(OBD_FAIL_LLITE_FORCE_BIO_AS_DIO)) {
2390 #ifdef IOCB_DIRECT
2391                 iocb->ki_flags |= IOCB_DIRECT;
2392                 CDEBUG(D_VFSTRACE, "switching to DIO\n");
2393                 hybrid_switched = true;
2394 #endif
2395         }
2396
2397         /* NB: we can't do direct IO for tiny writes because they use the page
2398          * cache, we can't do sync writes because tiny writes can't flush
2399          * pages, and we can't do append writes because we can't guarantee the
2400          * required DLM locks are held to protect file size.
2401          */
2402         if (ll_sbi_has_tiny_write(ll_i2sbi(file_inode(file))) &&
2403             !(flags &
2404               (ki_flag(DIRECT) | ki_flag(DSYNC) | ki_flag(SYNC) | ki_flag(APPEND))))
2405                 rc_tiny = ll_do_tiny_write(iocb, from);
2406
2407         /* In case of error, go on and try normal write - Only stop if tiny
2408          * write completed I/O.
2409          */
2410         if (iov_iter_count(from) == 0)
2411                 GOTO(out, rc_normal = rc_tiny);
2412
2413         env = cl_env_get(&refcheck);
2414         if (IS_ERR(env))
2415                 RETURN(PTR_ERR(env));
2416
2417         args = ll_env_args(env);
2418         args->u.normal.via_iter = from;
2419         args->u.normal.via_iocb = iocb;
2420         args->via_hybrid_switched = hybrid_switched;
2421
2422         rc_normal = ll_file_io_generic(env, args, file, CIT_WRITE,
2423                                        &iocb->ki_pos, iov_iter_count(from));
2424
2425         /* On success, combine bytes written. */
2426         if (rc_tiny >= 0 && rc_normal > 0)
2427                 rc_normal += rc_tiny;
2428         /* On error, only return error from normal write if tiny write did not
2429          * write any bytes.  Otherwise return bytes written by tiny write.
2430          */
2431         else if (rc_tiny > 0)
2432                 rc_normal = rc_tiny;
2433
2434         cl_env_put(env, &refcheck);
2435 out:
2436         if (rc_normal > 0) {
2437                 ll_rw_stats_tally(ll_i2sbi(file_inode(file)), current->pid,
2438                                   file->private_data, iocb->ki_pos,
2439                                   rc_normal, WRITE);
2440                 ll_stats_ops_tally(ll_i2sbi(file_inode(file)), LPROC_LL_WRITE,
2441                                    ktime_us_delta(ktime_get(), kstart));
2442         }
2443
2444         CDEBUG(D_IOTRACE,
2445                "COMPLETED: file %s:"DFID", ppos: %lld, count: %zu, rc = %zu\n",
2446                file_dentry(file)->d_name.name,
2447                PFID(ll_inode2fid(file_inode(file))), iocb->ki_pos,
2448                iov_iter_count(from), rc_normal);
2449
2450         RETURN(rc_normal);
2451 }
2452
2453 #ifndef HAVE_FILE_OPERATIONS_READ_WRITE_ITER
2454 /*
2455  * XXX: exact copy from kernel code (__generic_file_aio_write_nolock)
2456  */
2457 static int ll_file_get_iov_count(const struct iovec *iov,
2458                                  unsigned long *nr_segs, size_t *count,
2459                                  int access_flags)
2460 {
2461         size_t cnt = 0;
2462         unsigned long seg;
2463
2464         for (seg = 0; seg < *nr_segs; seg++) {
2465                 const struct iovec *iv = &iov[seg];
2466
2467                 /*
2468                  * If any segment has a negative length, or the cumulative
2469                  * length ever wraps negative then return -EINVAL.
2470                  */
2471                 cnt += iv->iov_len;
2472                 if (unlikely((ssize_t)(cnt|iv->iov_len) < 0))
2473                         return -EINVAL;
2474                 if (access_ok(access_flags, iv->iov_base, iv->iov_len))
2475                         continue;
2476                 if (seg == 0)
2477                         return -EFAULT;
2478                 *nr_segs = seg;
2479                 cnt -= iv->iov_len;     /* This segment is no good */
2480                 break;
2481         }
2482         *count = cnt;
2483         return 0;
2484 }
2485
2486 static ssize_t ll_file_aio_read(struct kiocb *iocb, const struct iovec *iov,
2487                                 unsigned long nr_segs, loff_t pos)
2488 {
2489         struct iov_iter to;
2490         size_t iov_count;
2491         ssize_t result;
2492         ENTRY;
2493
2494         result = ll_file_get_iov_count(iov, &nr_segs, &iov_count, VERIFY_READ);
2495         if (result)
2496                 RETURN(result);
2497
2498         if (!iov_count)
2499                 RETURN(0);
2500
2501 # ifdef HAVE_IOV_ITER_INIT_DIRECTION
2502         iov_iter_init(&to, READ, iov, nr_segs, iov_count);
2503 # else /* !HAVE_IOV_ITER_INIT_DIRECTION */
2504         iov_iter_init(&to, iov, nr_segs, iov_count, 0);
2505 # endif /* HAVE_IOV_ITER_INIT_DIRECTION */
2506
2507         result = ll_file_read_iter(iocb, &to);
2508
2509         RETURN(result);
2510 }
2511
2512 static ssize_t ll_file_read(struct file *file, char __user *buf, size_t count,
2513                             loff_t *ppos)
2514 {
2515         struct iovec   iov = { .iov_base = buf, .iov_len = count };
2516         struct kiocb   kiocb;
2517         ssize_t        result;
2518
2519         ENTRY;
2520
2521         if (!count)
2522                 RETURN(0);
2523
2524         init_sync_kiocb(&kiocb, file);
2525         kiocb.ki_pos = *ppos;
2526 #ifdef HAVE_KIOCB_KI_LEFT
2527         kiocb.ki_left = count;
2528 #elif defined(HAVE_KI_NBYTES)
2529         kiocb.i_nbytes = count;
2530 #endif
2531
2532         result = ll_file_aio_read(&kiocb, &iov, 1, kiocb.ki_pos);
2533         *ppos = kiocb.ki_pos;
2534
2535         RETURN(result);
2536 }
2537
2538 /*
2539  * Write to a file (through the page cache).
2540  * AIO stuff
2541  */
2542 static ssize_t ll_file_aio_write(struct kiocb *iocb, const struct iovec *iov,
2543                                  unsigned long nr_segs, loff_t pos)
2544 {
2545         struct iov_iter from;
2546         size_t iov_count;
2547         ssize_t result;
2548         ENTRY;
2549
2550         result = ll_file_get_iov_count(iov, &nr_segs, &iov_count, VERIFY_WRITE);
2551         if (result)
2552                 RETURN(result);
2553
2554         if (!iov_count)
2555                 RETURN(0);
2556
2557 # ifdef HAVE_IOV_ITER_INIT_DIRECTION
2558         iov_iter_init(&from, WRITE, iov, nr_segs, iov_count);
2559 # else /* !HAVE_IOV_ITER_INIT_DIRECTION */
2560         iov_iter_init(&from, iov, nr_segs, iov_count, 0);
2561 # endif /* HAVE_IOV_ITER_INIT_DIRECTION */
2562
2563         result = ll_file_write_iter(iocb, &from);
2564
2565         RETURN(result);
2566 }
2567
2568 static ssize_t ll_file_write(struct file *file, const char __user *buf,
2569                              size_t count, loff_t *ppos)
2570 {
2571         struct iovec   iov = { .iov_base = (void __user *)buf,
2572                                .iov_len = count };
2573         struct kiocb   kiocb;
2574         ssize_t        result;
2575
2576         ENTRY;
2577
2578         if (!count)
2579                 RETURN(0);
2580
2581         init_sync_kiocb(&kiocb, file);
2582         kiocb.ki_pos = *ppos;
2583 #ifdef HAVE_KIOCB_KI_LEFT
2584         kiocb.ki_left = count;
2585 #elif defined(HAVE_KI_NBYTES)
2586         kiocb.ki_nbytes = count;
2587 #endif
2588
2589         result = ll_file_aio_write(&kiocb, &iov, 1, kiocb.ki_pos);
2590         *ppos = kiocb.ki_pos;
2591
2592         RETURN(result);
2593 }
2594 #endif /* !HAVE_FILE_OPERATIONS_READ_WRITE_ITER */
2595
2596 int ll_lov_setstripe_ea_info(struct inode *inode, struct dentry *dentry,
2597                              __u64 flags, struct lov_user_md *lum, int lum_size)
2598 {
2599         struct lookup_intent oit = {
2600                 .it_op = IT_OPEN,
2601                 .it_flags = flags | MDS_OPEN_BY_FID,
2602         };
2603         int rc;
2604         ENTRY;
2605
2606         if ((__swab32(lum->lmm_magic) & le32_to_cpu(LOV_MAGIC_MASK)) ==
2607             le32_to_cpu(LOV_MAGIC_MAGIC)) {
2608                 /* this code will only exist for big-endian systems */
2609                 lustre_swab_lov_user_md(lum, 0);
2610         }
2611
2612         ll_inode_size_lock(inode);
2613         rc = ll_intent_file_open(dentry, lum, lum_size, &oit);
2614         if (rc < 0)
2615                 GOTO(out_unlock, rc);
2616
2617         ll_release_openhandle(dentry, &oit);
2618
2619 out_unlock:
2620         ll_inode_size_unlock(inode);
2621         ll_intent_release(&oit);
2622
2623         RETURN(rc);
2624 }
2625
2626 int ll_lov_getstripe_ea_info(struct inode *inode, const char *filename,
2627                              struct lov_mds_md **lmmp, int *lmm_size,
2628                              struct ptlrpc_request **request)
2629 {
2630         struct ll_sb_info *sbi = ll_i2sbi(inode);
2631         struct mdt_body  *body;
2632         struct lov_mds_md *lmm = NULL;
2633         struct ptlrpc_request *req = NULL;
2634         struct md_op_data *op_data;
2635         int rc, lmmsize;
2636
2637         ENTRY;
2638
2639         rc = ll_get_default_mdsize(sbi, &lmmsize);
2640         if (rc)
2641                 RETURN(rc);
2642
2643         op_data = ll_prep_md_op_data(NULL, inode, NULL, filename,
2644                                      strlen(filename), lmmsize,
2645                                      LUSTRE_OPC_ANY, NULL);
2646         if (IS_ERR(op_data))
2647                 RETURN(PTR_ERR(op_data));
2648
2649         op_data->op_valid = OBD_MD_FLEASIZE | OBD_MD_FLDIREA;
2650         rc = md_getattr_name(sbi->ll_md_exp, op_data, &req);
2651         ll_finish_md_op_data(op_data);
2652         if (rc < 0) {
2653                 CDEBUG(D_INFO, "md_getattr_name failed on %s: rc %d\n",
2654                        filename, rc);
2655                 GOTO(out, rc);
2656         }
2657
2658         body = req_capsule_server_get(&req->rq_pill, &RMF_MDT_BODY);
2659         LASSERT(body != NULL); /* checked by mdc_getattr_name */
2660
2661         lmmsize = body->mbo_eadatasize;
2662
2663         if (!(body->mbo_valid & (OBD_MD_FLEASIZE | OBD_MD_FLDIREA)) ||
2664             lmmsize == 0)
2665                 GOTO(out, rc = -ENODATA);
2666
2667         lmm = req_capsule_server_sized_get(&req->rq_pill, &RMF_MDT_MD, lmmsize);
2668         LASSERT(lmm != NULL);
2669
2670         if (lmm->lmm_magic != cpu_to_le32(LOV_MAGIC_V1) &&
2671             lmm->lmm_magic != cpu_to_le32(LOV_MAGIC_V3) &&
2672             lmm->lmm_magic != cpu_to_le32(LOV_MAGIC_COMP_V1) &&
2673             lmm->lmm_magic != cpu_to_le32(LOV_MAGIC_FOREIGN))
2674                 GOTO(out, rc = -EPROTO);
2675
2676         /*
2677          * This is coming from the MDS, so is probably in
2678          * little endian. We convert it to host endian before
2679          * passing it to userspace.
2680          */
2681         if (cpu_to_le32(LOV_MAGIC) != LOV_MAGIC) {
2682                 int stripe_count = 0;
2683
2684                 if (lmm->lmm_magic == cpu_to_le32(LOV_MAGIC_V1) ||
2685                     lmm->lmm_magic == cpu_to_le32(LOV_MAGIC_V3)) {
2686                         stripe_count = le16_to_cpu(lmm->lmm_stripe_count);
2687                         if (le32_to_cpu(lmm->lmm_pattern) &
2688                             LOV_PATTERN_F_RELEASED)
2689                                 stripe_count = 0;
2690                         lustre_swab_lov_user_md((struct lov_user_md *)lmm, 0);
2691
2692                         /* if function called for directory - we should
2693                          * avoid swab not existent lsm objects
2694                          */
2695                         if (lmm->lmm_magic == LOV_MAGIC_V1 &&
2696                             S_ISREG(body->mbo_mode))
2697                                 lustre_swab_lov_user_md_objects(
2698                                 ((struct lov_user_md_v1 *)lmm)->lmm_objects,
2699                                 stripe_count);
2700                         else if (lmm->lmm_magic == LOV_MAGIC_V3 &&
2701                                  S_ISREG(body->mbo_mode))
2702                                 lustre_swab_lov_user_md_objects(
2703                                 ((struct lov_user_md_v3 *)lmm)->lmm_objects,
2704                                 stripe_count);
2705                 } else if (lmm->lmm_magic == cpu_to_le32(LOV_MAGIC_COMP_V1)) {
2706                         lustre_swab_lov_comp_md_v1(
2707                                 (struct lov_comp_md_v1 *)lmm);
2708                 }
2709         }
2710
2711         if (lmm->lmm_magic == LOV_MAGIC_COMP_V1) {
2712                 struct lov_comp_md_v1 *comp_v1 = NULL;
2713                 struct lov_comp_md_entry_v1 *ent;
2714                 struct lov_user_md_v1 *v1 = NULL;
2715                 __u32 off;
2716                 int i = 0;
2717
2718                 comp_v1 = (struct lov_comp_md_v1 *)lmm;
2719                 /* Dump the striping information */
2720                 for (; i < comp_v1->lcm_entry_count; i++) {
2721                         ent = &comp_v1->lcm_entries[i];
2722                         off = ent->lcme_offset;
2723                         v1 = (struct lov_user_md_v1 *)((char *)lmm + off);
2724                         CDEBUG(D_INFO,
2725                                "comp[%d]: stripe_count=%u, stripe_size=%u\n",
2726                                i, v1->lmm_stripe_count, v1->lmm_stripe_size);
2727
2728                         if (unlikely(CFS_FAIL_CHECK(OBD_FAIL_LOV_COMP_MAGIC) &&
2729                                      (cfs_fail_val == i + 1)))
2730                                 v1->lmm_magic = LOV_MAGIC_BAD;
2731
2732                         if (unlikely(CFS_FAIL_CHECK(OBD_FAIL_LOV_COMP_PATTERN) &&
2733                                      (cfs_fail_val == i + 1)))
2734                                 v1->lmm_pattern = LOV_PATTERN_BAD;
2735                 }
2736
2737                 if (v1 == NULL)
2738                         GOTO(out, rc = -EINVAL);
2739
2740                 lmm->lmm_stripe_count = v1->lmm_stripe_count;
2741                 lmm->lmm_stripe_size = v1->lmm_stripe_size;
2742                 /**
2743                  * Return valid stripe_count and stripe_size instead of 0 for
2744                  * DoM files to avoid divide-by-zero for older userspace that
2745                  * calls this ioctl, e.g. lustre ADIO driver.
2746                  */
2747                 if (lmm->lmm_stripe_count == 0)
2748                         lmm->lmm_stripe_count = 1;
2749                 if (lmm->lmm_stripe_size == 0) {
2750                         /* Since the first component of the file data is placed
2751                          * on the MDT for faster access, the stripe_size of the
2752                          * second one is always that applications which are
2753                          * doing large IOs.
2754                          */
2755                         if (lmm->lmm_pattern & LOV_PATTERN_MDT)
2756                                 i = comp_v1->lcm_entry_count > 1 ? 1 : 0;
2757                         else
2758                                 i = comp_v1->lcm_entry_count > 1 ?
2759                                     comp_v1->lcm_entry_count - 1 : 0;
2760                         ent = &comp_v1->lcm_entries[i];
2761                         off = ent->lcme_offset;
2762                         v1 = (struct lov_user_md_v1 *)((char *)lmm + off);
2763                         lmm->lmm_stripe_size = v1->lmm_stripe_size;
2764                 }
2765         }
2766 out:
2767         *lmmp = lmm;
2768         *lmm_size = lmmsize;
2769         *request = req;
2770         RETURN(rc);
2771 }
2772
2773 static int ll_lov_setea(struct inode *inode, struct file *file,
2774                         void __user *arg)
2775 {
2776         __u64 flags = MDS_OPEN_HAS_OBJS | FMODE_WRITE;
2777         struct lov_user_md *lump;
2778         int lum_size = sizeof(*lump) + sizeof(struct lov_user_ost_data);
2779         int rc;
2780         ENTRY;
2781
2782         if (!capable(CAP_SYS_ADMIN))
2783                 RETURN(-EPERM);
2784
2785         OBD_ALLOC_LARGE(lump, lum_size);
2786         if (lump == NULL)
2787                 RETURN(-ENOMEM);
2788
2789         if (copy_from_user(lump, arg, lum_size))
2790                 GOTO(out_lump, rc = -EFAULT);
2791
2792         rc = ll_lov_setstripe_ea_info(inode, file_dentry(file), flags, lump,
2793                                       lum_size);
2794         cl_lov_delay_create_clear(&file->f_flags);
2795
2796 out_lump:
2797         OBD_FREE_LARGE(lump, lum_size);
2798         RETURN(rc);
2799 }
2800
2801 static int ll_file_getstripe(struct inode *inode, void __user *lum, size_t size)
2802 {
2803         struct lu_env *env;
2804         __u16 refcheck;
2805         int rc;
2806         ENTRY;
2807
2808         /* exit before doing any work if pointer is bad */
2809         if (unlikely(!ll_access_ok(lum, sizeof(struct lov_user_md))))
2810                 RETURN(-EFAULT);
2811
2812         env = cl_env_get(&refcheck);
2813         if (IS_ERR(env))
2814                 RETURN(PTR_ERR(env));
2815
2816         rc = cl_object_getstripe(env, ll_i2info(inode)->lli_clob, lum, size);
2817         cl_env_put(env, &refcheck);
2818         RETURN(rc);
2819 }
2820
2821 static int ll_lov_setstripe(struct inode *inode, struct file *file,
2822                             void __user *arg)
2823 {
2824         struct lov_user_md __user *lum = arg;
2825         struct lov_user_md *klum;
2826         int lum_size, rc;
2827         __u64 flags = FMODE_WRITE;
2828         ENTRY;
2829
2830         rc = ll_copy_user_md(lum, &klum);
2831         if (rc < 0)
2832                 RETURN(rc);
2833
2834         lum_size = rc;
2835         rc = ll_lov_setstripe_ea_info(inode, file_dentry(file), flags, klum,
2836                                       lum_size);
2837         if (!rc) {
2838                 __u32 gen;
2839
2840                 rc = put_user(0, &lum->lmm_stripe_count);
2841                 if (rc)
2842                         GOTO(out, rc);
2843
2844                 rc = ll_layout_refresh(inode, &gen);
2845                 if (rc)
2846                         GOTO(out, rc);
2847
2848                 rc = ll_file_getstripe(inode, arg, lum_size);
2849                 if (S_ISREG(inode->i_mode) && IS_ENCRYPTED(inode) &&
2850                     ll_i2info(inode)->lli_clob) {
2851                         struct iattr attr = { 0 };
2852
2853                         rc = cl_setattr_ost(ll_i2info(inode)->lli_clob, &attr,
2854                                             OP_XVALID_FLAGS, LUSTRE_ENCRYPT_FL);
2855                 }
2856         }
2857         cl_lov_delay_create_clear(&file->f_flags);
2858
2859 out:
2860         OBD_FREE_LARGE(klum, lum_size);
2861         RETURN(rc);
2862 }
2863
2864
2865 static int
2866 ll_get_grouplock(struct inode *inode, struct file *file, unsigned long arg)
2867 {
2868         struct ll_inode_info *lli = ll_i2info(inode);
2869         struct cl_object *obj = lli->lli_clob;
2870         struct ll_file_data *fd = file->private_data;
2871         struct ll_grouplock grouplock;
2872         int rc;
2873         ENTRY;
2874
2875         if (arg == 0) {
2876                 CWARN("group id for group lock must not be 0\n");
2877                 RETURN(-EINVAL);
2878         }
2879
2880         if (ll_file_nolock(file))
2881                 RETURN(-EOPNOTSUPP);
2882 retry:
2883         if (file->f_flags & O_NONBLOCK) {
2884                 if (!mutex_trylock(&lli->lli_group_mutex))
2885                         RETURN(-EAGAIN);
2886         } else {
2887                 mutex_lock(&lli->lli_group_mutex);
2888         }
2889
2890         if (fd->fd_flags & LL_FILE_GROUP_LOCKED) {
2891                 CWARN("group lock already existed with gid %lu\n",
2892                       fd->fd_grouplock.lg_gid);
2893                 GOTO(out, rc = -EINVAL);
2894         }
2895         if (arg != lli->lli_group_gid && lli->lli_group_users != 0) {
2896                 if (file->f_flags & O_NONBLOCK)
2897                         GOTO(out, rc = -EAGAIN);
2898                 mutex_unlock(&lli->lli_group_mutex);
2899                 wait_var_event(&lli->lli_group_users, !lli->lli_group_users);
2900                 GOTO(retry, rc = 0);
2901         }
2902         LASSERT(fd->fd_grouplock.lg_lock == NULL);
2903
2904         /**
2905          * XXX: group lock needs to protect all OST objects while PFL
2906          * can add new OST objects during the IO, so we'd instantiate
2907          * all OST objects before getting its group lock.
2908          */
2909         if (obj) {
2910                 struct lu_env *env;
2911                 __u16 refcheck;
2912                 struct cl_layout cl = {
2913                         .cl_is_composite = false,
2914                 };
2915                 struct lu_extent ext = {
2916                         .e_start = 0,
2917                         .e_end = OBD_OBJECT_EOF,
2918                 };
2919
2920                 env = cl_env_get(&refcheck);
2921                 if (IS_ERR(env))
2922                         GOTO(out, rc = PTR_ERR(env));
2923
2924                 rc = cl_object_layout_get(env, obj, &cl);
2925                 if (rc >= 0 && cl.cl_is_composite)
2926                         rc = ll_layout_write_intent(inode, LAYOUT_INTENT_WRITE,
2927                                                     &ext);
2928
2929                 cl_env_put(env, &refcheck);
2930                 if (rc < 0)
2931                         GOTO(out, rc);
2932         }
2933
2934         rc = cl_get_grouplock(ll_i2info(inode)->lli_clob,
2935                               arg, (file->f_flags & O_NONBLOCK), &grouplock);
2936
2937         if (rc)
2938                 GOTO(out, rc);
2939
2940         fd->fd_flags |= LL_FILE_GROUP_LOCKED;
2941         fd->fd_grouplock = grouplock;
2942         if (lli->lli_group_users == 0)
2943                 lli->lli_group_gid = grouplock.lg_gid;
2944         lli->lli_group_users++;
2945
2946         CDEBUG(D_INFO, "group lock %lu obtained\n", arg);
2947 out:
2948         mutex_unlock(&lli->lli_group_mutex);
2949
2950         RETURN(rc);
2951 }
2952
2953 static int ll_put_grouplock(struct inode *inode, struct file *file,
2954                             unsigned long arg)
2955 {
2956         struct ll_inode_info   *lli = ll_i2info(inode);
2957         struct ll_file_data    *fd = file->private_data;
2958         struct ll_grouplock     grouplock;
2959         int                     rc;
2960         ENTRY;
2961
2962         mutex_lock(&lli->lli_group_mutex);
2963         if (!(fd->fd_flags & LL_FILE_GROUP_LOCKED)) {
2964                 CWARN("no group lock held\n");
2965                 GOTO(out, rc = -EINVAL);
2966         }
2967
2968         LASSERT(fd->fd_grouplock.lg_lock != NULL);
2969
2970         if (fd->fd_grouplock.lg_gid != arg) {
2971                 CWARN("group lock %lu doesn't match current id %lu\n",
2972                       arg, fd->fd_grouplock.lg_gid);
2973                 GOTO(out, rc = -EINVAL);
2974         }
2975
2976         grouplock = fd->fd_grouplock;
2977         memset(&fd->fd_grouplock, 0, sizeof(fd->fd_grouplock));
2978         fd->fd_flags &= ~LL_FILE_GROUP_LOCKED;
2979
2980         cl_put_grouplock(&grouplock);
2981
2982         lli->lli_group_users--;
2983         if (lli->lli_group_users == 0) {
2984                 lli->lli_group_gid = 0;
2985                 wake_up_var(&lli->lli_group_users);
2986         }
2987         CDEBUG(D_INFO, "group lock %lu released\n", arg);
2988         GOTO(out, rc = 0);
2989 out:
2990         mutex_unlock(&lli->lli_group_mutex);
2991
2992         RETURN(rc);
2993 }
2994
2995 /**
2996  * Close inode open handle
2997  *
2998  * \param dentry [in]     dentry which contains the inode
2999  * \param it     [in,out] intent which contains open info and result
3000  *
3001  * \retval 0     success
3002  * \retval <0    failure
3003  */
3004 int ll_release_openhandle(struct dentry *dentry, struct lookup_intent *it)
3005 {
3006         struct inode *inode = dentry->d_inode;
3007         struct obd_client_handle *och;
3008         int rc;
3009         ENTRY;
3010
3011         LASSERT(inode);
3012
3013         /* Root ? Do nothing. */
3014         if (is_root_inode(inode))
3015                 RETURN(0);
3016
3017         /* No open handle to close? Move away */
3018         if (!it_disposition(it, DISP_OPEN_OPEN))
3019                 RETURN(0);
3020
3021         LASSERT(it_open_error(DISP_OPEN_OPEN, it) == 0);
3022
3023         OBD_ALLOC(och, sizeof(*och));
3024         if (!och)
3025                 GOTO(out, rc = -ENOMEM);
3026
3027         rc = ll_och_fill(ll_i2sbi(inode)->ll_md_exp, it, och);
3028         if (rc)
3029                 GOTO(out, rc);
3030
3031         rc = ll_close_inode_openhandle(inode, och, 0, NULL);
3032 out:
3033         /* this one is in place of ll_file_open */
3034         if (it_disposition(it, DISP_ENQ_OPEN_REF)) {
3035                 ptlrpc_req_finished(it->it_request);
3036                 it_clear_disposition(it, DISP_ENQ_OPEN_REF);
3037         }
3038         RETURN(rc);
3039 }
3040
3041 /**
3042  * Get size for inode for which FIEMAP mapping is requested.
3043  * Make the FIEMAP get_info call and returns the result.
3044  * \param fiemap        kernel buffer to hold extens
3045  * \param num_bytes     kernel buffer size
3046  */
3047 static int ll_do_fiemap(struct inode *inode, struct fiemap *fiemap,
3048                         size_t num_bytes)
3049 {
3050         struct lu_env                   *env;
3051         __u16                           refcheck;
3052         int                             rc = 0;
3053         struct ll_fiemap_info_key       fmkey = { .lfik_name = KEY_FIEMAP, };
3054         ENTRY;
3055
3056         /* Checks for fiemap flags */
3057         if (fiemap->fm_flags & ~LUSTRE_FIEMAP_FLAGS_COMPAT) {
3058                 fiemap->fm_flags &= ~LUSTRE_FIEMAP_FLAGS_COMPAT;
3059                 return -EBADR;
3060         }
3061
3062         /* Check for FIEMAP_FLAG_SYNC */
3063         if (fiemap->fm_flags & FIEMAP_FLAG_SYNC) {
3064                 rc = filemap_write_and_wait(inode->i_mapping);
3065                 if (rc)
3066                         return rc;
3067         }
3068
3069         env = cl_env_get(&refcheck);
3070         if (IS_ERR(env))
3071                 RETURN(PTR_ERR(env));
3072
3073         if (i_size_read(inode) == 0) {
3074                 rc = ll_glimpse_size(inode);
3075                 if (rc)
3076                         GOTO(out, rc);
3077         }
3078
3079         fmkey.lfik_oa.o_valid = OBD_MD_FLID | OBD_MD_FLGROUP | OBD_MD_FLPROJID;
3080         obdo_from_inode(&fmkey.lfik_oa, inode, OBD_MD_FLSIZE);
3081         obdo_set_parent_fid(&fmkey.lfik_oa, &ll_i2info(inode)->lli_fid);
3082
3083         /* If filesize is 0, then there would be no objects for mapping */
3084         if (fmkey.lfik_oa.o_size == 0) {
3085                 fiemap->fm_mapped_extents = 0;
3086                 GOTO(out, rc = 0);
3087         }
3088
3089         fmkey.lfik_fiemap = *fiemap;
3090
3091         rc = cl_object_fiemap(env, ll_i2info(inode)->lli_clob,
3092                               &fmkey, fiemap, &num_bytes);
3093 out:
3094         cl_env_put(env, &refcheck);
3095         RETURN(rc);
3096 }
3097
3098 static int fid2path_for_enc_file(struct inode *parent, char *gfpath,
3099                                  __u32 gfpathlen)
3100 {
3101         struct dentry *de = NULL, *de_parent = d_find_any_alias(parent);
3102         struct llcrypt_str lltr = LLTR_INIT(NULL, 0);
3103         struct llcrypt_str de_name;
3104         char *p, *ptr = gfpath;
3105         size_t len = 0, len_orig = 0;
3106         int enckey = -1, nameenc = -1;
3107         int rc = 0;
3108
3109         gfpath++;
3110         while ((p = strsep(&gfpath, "/")) != NULL) {
3111                 struct lu_fid fid;
3112
3113                 de = NULL;
3114                 if (!*p) {
3115                         dput(de_parent);
3116                         break;
3117                 }
3118                 len_orig = strlen(p);
3119
3120                 rc = sscanf(p, "["SFID"]", RFID(&fid));
3121                 if (rc == 3)
3122                         p = strchr(p, ']') + 1;
3123                 else
3124                         fid_zero(&fid);
3125                 rc = 0;
3126                 len = strlen(p);
3127
3128                 if (!IS_ENCRYPTED(parent)) {
3129                         if (gfpathlen < len + 1) {
3130                                 dput(de_parent);
3131                                 rc = -EOVERFLOW;
3132                                 break;
3133                         }
3134                         memmove(ptr, p, len);
3135                         p = ptr;
3136                         ptr += len;
3137                         *(ptr++) = '/';
3138                         gfpathlen -= len + 1;
3139                         goto lookup;
3140                 }
3141
3142                 /* From here, we know parent is encrypted */
3143
3144                 if (enckey != 0) {
3145                         rc = llcrypt_prepare_readdir(parent);
3146                         if (rc && rc != -ENOKEY) {
3147                                 dput(de_parent);
3148                                 break;
3149                         }
3150                 }
3151
3152                 if (enckey == -1) {
3153                         if (llcrypt_has_encryption_key(parent))
3154                                 enckey = 1;
3155                         else
3156                                 enckey = 0;
3157                         if (enckey == 1)
3158                                 nameenc =
3159                                         llcrypt_policy_has_filename_enc(parent);
3160                 }
3161
3162                 /* Even if names are not encrypted, we still need to call
3163                  * ll_fname_disk_to_usr in order to decode names as they are
3164                  * coming from the wire.
3165                  */
3166                 rc = llcrypt_fname_alloc_buffer(parent, NAME_MAX + 1, &lltr);
3167                 if (rc < 0) {
3168                         dput(de_parent);
3169                         break;
3170                 }
3171
3172                 de_name.name = p;
3173                 de_name.len = len;
3174                 rc = ll_fname_disk_to_usr(parent, 0, 0, &de_name,
3175                                           &lltr, &fid);
3176                 if (rc) {
3177                         llcrypt_fname_free_buffer(&lltr);
3178                         dput(de_parent);
3179                         break;
3180                 }
3181                 lltr.name[lltr.len] = '\0';
3182
3183                 if (lltr.len <= len_orig && gfpathlen >= lltr.len + 1) {
3184                         memcpy(ptr, lltr.name, lltr.len);
3185                         p = ptr;
3186                         len = lltr.len;
3187                         ptr += lltr.len;
3188                         *(ptr++) = '/';
3189                         gfpathlen -= lltr.len + 1;
3190                 } else {
3191                         rc = -EOVERFLOW;
3192                 }
3193                 llcrypt_fname_free_buffer(&lltr);
3194
3195                 if (rc == -EOVERFLOW) {
3196                         dput(de_parent);
3197                         break;
3198                 }
3199
3200 lookup:
3201                 if (!gfpath) {
3202                         /* We reached the end of the string, which means
3203                          * we are dealing with the last component in the path.
3204                          * So save a useless lookup and exit.
3205                          */
3206                         dput(de_parent);
3207                         break;
3208                 }
3209
3210                 if (enckey == 0 || nameenc == 0)
3211                         continue;
3212
3213                 ll_inode_lock(parent);
3214                 de = lookup_one_len(p, de_parent, len);
3215                 ll_inode_unlock(parent);
3216                 if (IS_ERR_OR_NULL(de) || !de->d_inode) {
3217                         dput(de_parent);
3218                         rc = -ENODATA;
3219                         break;
3220                 }
3221
3222                 parent = de->d_inode;
3223                 dput(de_parent);
3224                 de_parent = de;
3225         }
3226
3227         if (len)
3228                 *(ptr - 1) = '\0';
3229         if (!IS_ERR_OR_NULL(de))
3230                 dput(de);
3231         return rc;
3232 }
3233
3234 int __ll_fid2path(struct inode *inode, struct getinfo_fid2path *gfout,
3235                   size_t outsize, __u32 pathlen_orig)
3236 {
3237         struct obd_export *exp = ll_i2mdexp(inode);
3238         int rc;
3239
3240         /* Append root FID after gfout to let MDT know the root FID so that
3241          * it can lookup the correct path, this is mainly for fileset.
3242          * old server without fileset mount support will ignore this.
3243          */
3244         *gfout->gf_u.gf_root_fid = *ll_inode2fid(inode);
3245
3246         /* Call mdc_iocontrol */
3247         rc = obd_iocontrol(OBD_IOC_FID2PATH, exp, outsize, gfout, NULL);
3248
3249         if (!rc && gfout->gf_pathlen && gfout->gf_u.gf_path[0] == '/') {
3250                 /* by convention, server side (mdt_path_current()) puts
3251                  * a leading '/' to tell client that we are dealing with
3252                  * an encrypted file
3253                  */
3254                 rc = fid2path_for_enc_file(inode, gfout->gf_u.gf_path,
3255                                            gfout->gf_pathlen);
3256                 if (!rc && strlen(gfout->gf_u.gf_path) > pathlen_orig)
3257                         rc = -EOVERFLOW;
3258         }
3259
3260         return rc;
3261 }
3262
3263 int ll_fid2path(struct inode *inode, void __user *arg)
3264 {
3265         const struct getinfo_fid2path __user *gfin = arg;
3266         __u32 pathlen, pathlen_orig;
3267         struct getinfo_fid2path *gfout;
3268         size_t outsize;
3269         int rc = 0;
3270
3271         ENTRY;
3272
3273         if (!capable(CAP_DAC_READ_SEARCH) &&
3274             !test_bit(LL_SBI_USER_FID2PATH, ll_i2sbi(inode)->ll_flags))
3275                 RETURN(-EPERM);
3276
3277         /* Only need to get the buflen */
3278         if (get_user(pathlen, &gfin->gf_pathlen))
3279                 RETURN(-EFAULT);
3280
3281         if (pathlen > PATH_MAX)
3282                 RETURN(-EINVAL);
3283         pathlen_orig = pathlen;
3284
3285 gf_alloc:
3286         outsize = sizeof(*gfout) + pathlen;
3287         OBD_ALLOC(gfout, outsize);
3288         if (gfout == NULL)
3289                 RETURN(-ENOMEM);
3290
3291         if (copy_from_user(gfout, arg, sizeof(*gfout)))
3292                 GOTO(gf_free, rc = -EFAULT);
3293
3294         gfout->gf_pathlen = pathlen;
3295         rc = __ll_fid2path(inode, gfout, outsize, pathlen_orig);
3296         if (rc)
3297                 GOTO(gf_free, rc);
3298
3299         if (copy_to_user(arg, gfout, sizeof(*gfout) + pathlen_orig))
3300                 rc = -EFAULT;
3301
3302 gf_free:
3303         OBD_FREE(gfout, outsize);
3304         if (rc == -ENAMETOOLONG) {
3305                 pathlen += PATH_MAX;
3306                 GOTO(gf_alloc, rc);
3307         }
3308         RETURN(rc);
3309 }
3310
3311 static int
3312 ll_ioc_data_version(struct inode *inode, struct ioc_data_version *ioc)
3313 {
3314         struct cl_object *obj = ll_i2info(inode)->lli_clob;
3315         struct lu_env *env;
3316         struct cl_io *io;
3317         __u16  refcheck;
3318         int result;
3319
3320         ENTRY;
3321
3322         ioc->idv_version = 0;
3323         ioc->idv_layout_version = UINT_MAX;
3324
3325         /* If no file object initialized, we consider its version is 0. */
3326         if (obj == NULL)
3327                 RETURN(0);
3328
3329         env = cl_env_get(&refcheck);
3330         if (IS_ERR(env))
3331                 RETURN(PTR_ERR(env));
3332
3333         io = vvp_env_thread_io(env);
3334         io->ci_obj = obj;
3335         io->u.ci_data_version.dv_data_version = 0;
3336         io->u.ci_data_version.dv_layout_version = UINT_MAX;
3337         io->u.ci_data_version.dv_flags = ioc->idv_flags;
3338
3339 restart:
3340         if (cl_io_init(env, io, CIT_DATA_VERSION, io->ci_obj) == 0)
3341                 result = cl_io_loop(env, io);
3342         else
3343                 result = io->ci_result;
3344
3345         ioc->idv_version = io->u.ci_data_version.dv_data_version;
3346         ioc->idv_layout_version = io->u.ci_data_version.dv_layout_version;
3347         cl_io_fini(env, io);
3348
3349         if (unlikely(io->ci_need_restart))
3350                 goto restart;
3351
3352         cl_env_put(env, &refcheck);
3353
3354         RETURN(result);
3355 }
3356
3357 /*
3358  * Read the data_version for inode.
3359  *
3360  * This value is computed using stripe object version on OST.
3361  * Version is computed using server side locking.
3362  *
3363  * @param flags if do sync on the OST side;
3364  *              0: no sync
3365  *              LL_DV_RD_FLUSH: flush dirty pages, LCK_PR on OSTs
3366  *              LL_DV_WR_FLUSH: drop all caching pages, LCK_PW on OSTs
3367  */
3368 int ll_data_version(struct inode *inode, __u64 *data_version, int flags)
3369 {
3370         struct ioc_data_version ioc = { .idv_flags = flags };
3371         int rc;
3372
3373         rc = ll_ioc_data_version(inode, &ioc);
3374         if (!rc)
3375                 *data_version = ioc.idv_version;
3376
3377         return rc;
3378 }
3379
3380 /*
3381  * Trigger a HSM release request for the provided inode.
3382  */
3383 int ll_hsm_release(struct inode *inode)
3384 {
3385         struct lu_env *env;
3386         struct obd_client_handle *och = NULL;
3387         __u64 data_version = 0;
3388         __u16 refcheck;
3389         int rc;
3390
3391         ENTRY;
3392
3393         CDEBUG(D_INODE, "%s: Releasing file "DFID".\n",
3394                ll_i2sbi(inode)->ll_fsname,
3395                PFID(&ll_i2info(inode)->lli_fid));
3396
3397         och = ll_lease_open(inode, NULL, FMODE_WRITE, MDS_OPEN_RELEASE);
3398         if (IS_ERR(och))
3399                 GOTO(out, rc = PTR_ERR(och));
3400
3401         /* Grab latest data_version and [am]time values */
3402         rc = ll_data_version(inode, &data_version,
3403                              LL_DV_WR_FLUSH | LL_DV_SZ_UPDATE);
3404         if (rc != 0)
3405                 GOTO(out, rc);
3406
3407         env = cl_env_get(&refcheck);
3408         if (IS_ERR(env))
3409                 GOTO(out, rc = PTR_ERR(env));
3410
3411         rc = ll_merge_attr(env, inode);
3412         cl_env_put(env, &refcheck);
3413
3414         /* If error happen, we have the wrong size for a file.
3415          * Don't release it.
3416          */
3417         if (rc != 0)
3418                 GOTO(out, rc);
3419
3420         /* Release the file.
3421          * NB: lease lock handle is released in mdc_hsm_release_pack() because
3422          * we still need it to pack l_remote_handle to MDT. */
3423         rc = ll_close_inode_openhandle(inode, och, MDS_HSM_RELEASE,
3424                                        &data_version);
3425         och = NULL;
3426
3427         EXIT;
3428 out:
3429         if (och != NULL && !IS_ERR(och)) /* close the file */
3430                 ll_lease_close(och, inode, NULL);
3431
3432         return rc;
3433 }
3434
3435 struct ll_swap_stack {
3436         __u64                    dv1;
3437         __u64                    dv2;
3438         struct inode            *inode1;
3439         struct inode            *inode2;
3440         bool                     check_dv1;
3441         bool                     check_dv2;
3442 };
3443
3444 static int ll_swap_layouts(struct file *file1, struct file *file2,
3445                            struct lustre_swap_layouts *lsl)
3446 {
3447         struct mdc_swap_layouts  msl;
3448         struct md_op_data       *op_data;
3449         __u32                    gid;
3450         __u64                    dv;
3451         struct ll_swap_stack    *llss = NULL;
3452         int                      rc;
3453
3454         OBD_ALLOC_PTR(llss);
3455         if (llss == NULL)
3456                 RETURN(-ENOMEM);
3457
3458         llss->inode1 = file_inode(file1);
3459         llss->inode2 = file_inode(file2);
3460
3461         rc = ll_check_swap_layouts_validity(llss->inode1, llss->inode2);
3462         if (rc < 0)
3463                 GOTO(free, rc);
3464
3465         /* we use 2 bool because it is easier to swap than 2 bits */
3466         if (lsl->sl_flags & SWAP_LAYOUTS_CHECK_DV1)
3467                 llss->check_dv1 = true;
3468
3469         if (lsl->sl_flags & SWAP_LAYOUTS_CHECK_DV2)
3470                 llss->check_dv2 = true;
3471
3472         /* we cannot use lsl->sl_dvX directly because we may swap them */
3473         llss->dv1 = lsl->sl_dv1;
3474         llss->dv2 = lsl->sl_dv2;
3475
3476         rc = lu_fid_cmp(ll_inode2fid(llss->inode1), ll_inode2fid(llss->inode2));
3477         if (rc == 0) /* same file, done! */
3478                 GOTO(free, rc);
3479
3480         if (rc < 0) { /* sequentialize it */
3481                 swap(llss->inode1, llss->inode2);
3482                 swap(file1, file2);
3483                 swap(llss->dv1, llss->dv2);
3484                 swap(llss->check_dv1, llss->check_dv2);
3485         }
3486
3487         gid = lsl->sl_gid;
3488         if (gid != 0) { /* application asks to flush dirty cache */
3489                 rc = ll_get_grouplock(llss->inode1, file1, gid);
3490                 if (rc < 0)
3491                         GOTO(free, rc);
3492
3493                 rc = ll_get_grouplock(llss->inode2, file2, gid);
3494                 if (rc < 0) {
3495                         ll_put_grouplock(llss->inode1, file1, gid);
3496                         GOTO(free, rc);
3497                 }
3498         }
3499
3500         /* ultimate check, before swaping the layouts we check if
3501          * dataversion has changed (if requested) */
3502         if (llss->check_dv1) {
3503                 rc = ll_data_version(llss->inode1, &dv, 0);
3504                 if (rc)
3505                         GOTO(putgl, rc);
3506                 if (dv != llss->dv1)
3507                         GOTO(putgl, rc = -EAGAIN);
3508         }
3509
3510         if (llss->check_dv2) {
3511                 rc = ll_data_version(llss->inode2, &dv, 0);
3512                 if (rc)
3513                         GOTO(putgl, rc);
3514                 if (dv != llss->dv2)
3515                         GOTO(putgl, rc = -EAGAIN);
3516         }
3517
3518         /* struct md_op_data is used to send the swap args to the mdt
3519          * only flags is missing, so we use struct mdc_swap_layouts
3520          * through the md_op_data->op_data */
3521         /* flags from user space have to be converted before they are send to
3522          * server, no flag is sent today, they are only used on the client */
3523         msl.msl_flags = 0;
3524         rc = -ENOMEM;
3525         op_data = ll_prep_md_op_data(NULL, llss->inode1, llss->inode2, NULL, 0,
3526                                      0, LUSTRE_OPC_ANY, &msl);
3527         if (IS_ERR(op_data))
3528                 GOTO(free, rc = PTR_ERR(op_data));
3529
3530         rc = obd_iocontrol(LL_IOC_LOV_SWAP_LAYOUTS, ll_i2mdexp(llss->inode1),
3531                            sizeof(*op_data), op_data, NULL);
3532         ll_finish_md_op_data(op_data);
3533
3534         if (rc < 0)
3535                 GOTO(putgl, rc);
3536
3537 putgl:
3538         if (gid != 0) {
3539                 ll_put_grouplock(llss->inode2, file2, gid);
3540                 ll_put_grouplock(llss->inode1, file1, gid);
3541         }
3542
3543 free:
3544         if (llss != NULL)
3545                 OBD_FREE_PTR(llss);
3546
3547         RETURN(rc);
3548 }
3549
3550 int ll_hsm_state_set(struct inode *inode, struct hsm_state_set *hss)
3551 {
3552         struct obd_export *exp = ll_i2mdexp(inode);
3553         struct md_op_data *op_data;
3554         int rc;
3555         ENTRY;
3556
3557         /* Detect out-of range masks */
3558         if ((hss->hss_setmask | hss->hss_clearmask) & ~HSM_FLAGS_MASK)
3559                 RETURN(-EINVAL);
3560
3561         /* Non-root users are forbidden to set or clear flags which are
3562          * NOT defined in HSM_USER_MASK. */
3563         if (((hss->hss_setmask | hss->hss_clearmask) & ~HSM_USER_MASK) &&
3564             !capable(CAP_SYS_ADMIN))
3565                 RETURN(-EPERM);
3566
3567         if (!exp_connect_archive_id_array(exp)) {
3568                 /* Detect out-of range archive id */
3569                 if ((hss->hss_valid & HSS_ARCHIVE_ID) &&
3570                     (hss->hss_archive_id > LL_HSM_ORIGIN_MAX_ARCHIVE))
3571                         RETURN(-EINVAL);
3572         }
3573
3574         op_data = ll_prep_md_op_data(NULL, inode, NULL, NULL, 0, 0,
3575                                      LUSTRE_OPC_ANY, hss);
3576         if (IS_ERR(op_data))
3577                 RETURN(PTR_ERR(op_data));
3578
3579         rc = obd_iocontrol(LL_IOC_HSM_STATE_SET, exp, sizeof(*op_data),
3580                            op_data, NULL);
3581
3582         ll_finish_md_op_data(op_data);
3583
3584         RETURN(rc);
3585 }
3586
3587 static int ll_hsm_import(struct inode *inode, struct file *file,
3588                          struct hsm_user_import *hui)
3589 {
3590         struct hsm_state_set    *hss = NULL;
3591         struct iattr            *attr = NULL;
3592         int                      rc;
3593         ENTRY;
3594
3595         if (!S_ISREG(inode->i_mode))
3596                 RETURN(-EINVAL);
3597
3598         /* set HSM flags */
3599         OBD_ALLOC_PTR(hss);
3600         if (hss == NULL)
3601                 GOTO(out, rc = -ENOMEM);
3602
3603         hss->hss_valid = HSS_SETMASK | HSS_ARCHIVE_ID;
3604         hss->hss_archive_id = hui->hui_archive_id;
3605         hss->hss_setmask = HS_ARCHIVED | HS_EXISTS | HS_RELEASED;
3606         rc = ll_hsm_state_set(inode, hss);
3607         if (rc != 0)
3608                 GOTO(out, rc);
3609
3610         OBD_ALLOC_PTR(attr);
3611         if (attr == NULL)
3612                 GOTO(out, rc = -ENOMEM);
3613
3614         attr->ia_mode = hui->hui_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
3615         attr->ia_mode |= S_IFREG;
3616         attr->ia_uid = make_kuid(&init_user_ns, hui->hui_uid);
3617         attr->ia_gid = make_kgid(&init_user_ns, hui->hui_gid);
3618         attr->ia_size = hui->hui_size;
3619         attr->ia_mtime.tv_sec = hui->hui_mtime;
3620         attr->ia_mtime.tv_nsec = hui->hui_mtime_ns;
3621         attr->ia_atime.tv_sec = hui->hui_atime;
3622         attr->ia_atime.tv_nsec = hui->hui_atime_ns;
3623
3624         attr->ia_valid = ATTR_SIZE | ATTR_MODE | ATTR_FORCE |
3625                          ATTR_UID | ATTR_GID |
3626                          ATTR_MTIME | ATTR_MTIME_SET |
3627                          ATTR_ATIME | ATTR_ATIME_SET;
3628
3629         inode_lock(inode);
3630         /* inode lock owner set in ll_setattr_raw()*/
3631         rc = ll_setattr_raw(file_dentry(file), attr, 0, true);
3632         if (rc == -ENODATA)
3633                 rc = 0;
3634         inode_unlock(inode);
3635
3636 out:
3637         if (hss != NULL)
3638                 OBD_FREE_PTR(hss);
3639
3640         if (attr != NULL)
3641                 OBD_FREE_PTR(attr);
3642
3643         RETURN(rc);
3644 }
3645
3646 static inline long ll_lease_type_from_fmode(fmode_t fmode)
3647 {
3648         return ((fmode & FMODE_READ) ? LL_LEASE_RDLCK : 0) |
3649                ((fmode & FMODE_WRITE) ? LL_LEASE_WRLCK : 0);
3650 }
3651
3652 static int ll_file_futimes_3(struct file *file, const struct ll_futimes_3 *lfu)
3653 {
3654         struct inode *inode = file_inode(file);
3655         struct iattr ia = {
3656                 .ia_valid = ATTR_ATIME | ATTR_ATIME_SET |
3657                             ATTR_MTIME | ATTR_MTIME_SET |
3658                             ATTR_CTIME,
3659                 .ia_atime = {
3660                         .tv_sec = lfu->lfu_atime_sec,
3661                         .tv_nsec = lfu->lfu_atime_nsec,
3662                 },
3663                 .ia_mtime = {
3664                         .tv_sec = lfu->lfu_mtime_sec,
3665                         .tv_nsec = lfu->lfu_mtime_nsec,
3666                 },
3667                 .ia_ctime = {
3668                         .tv_sec = lfu->lfu_ctime_sec,
3669                         .tv_nsec = lfu->lfu_ctime_nsec,
3670                 },
3671         };
3672         int rc;
3673         ENTRY;
3674
3675         if (!capable(CAP_SYS_ADMIN))
3676                 RETURN(-EPERM);
3677
3678         if (!S_ISREG(inode->i_mode))
3679                 RETURN(-EINVAL);
3680
3681         inode_lock(inode);
3682         /* inode lock owner set in ll_setattr_raw()*/
3683         rc = ll_setattr_raw(file_dentry(file), &ia, OP_XVALID_CTIME_SET,
3684                             false);
3685         inode_unlock(inode);
3686
3687         RETURN(rc);
3688 }
3689
3690 static enum cl_lock_mode cl_mode_user_to_kernel(enum lock_mode_user mode)
3691 {
3692         switch (mode) {
3693         case MODE_READ_USER:
3694                 return CLM_READ;
3695         case MODE_WRITE_USER:
3696                 return CLM_WRITE;
3697         default:
3698                 return -EINVAL;
3699         }
3700 }
3701
3702 static const char *const user_lockname[] = LOCK_MODE_NAMES;
3703
3704 /* Used to allow the upper layers of the client to request an LDLM lock
3705  * without doing an actual read or write.
3706  *
3707  * Used for ladvise lockahead to manually request specific locks.
3708  *
3709  * \param[in] file      file this ladvise lock request is on
3710  * \param[in] ladvise   ladvise struct describing this lock request
3711  *
3712  * \retval 0            success, no detailed result available (sync requests
3713  *                      and requests sent to the server [not handled locally]
3714  *                      cannot return detailed results)
3715  * \retval LLA_RESULT_{SAME,DIFFERENT} - detailed result of the lock request,
3716  *                                       see definitions for details.
3717  * \retval negative     negative errno on error
3718  */
3719 int ll_file_lock_ahead(struct file *file, struct llapi_lu_ladvise *ladvise)
3720 {
3721         struct lu_env *env = NULL;
3722         struct cl_io *io  = NULL;
3723         struct cl_lock *lock = NULL;
3724         struct cl_lock_descr *descr = NULL;
3725         struct dentry *dentry = file->f_path.dentry;
3726         struct inode *inode = dentry->d_inode;
3727         enum cl_lock_mode cl_mode;
3728         off_t start = ladvise->lla_start;
3729         off_t end = ladvise->lla_end;
3730         int result;
3731         __u16 refcheck;
3732
3733         ENTRY;
3734
3735         CDEBUG(D_VFSTRACE,
3736                "Lock request: file=%pd, inode=%p, mode=%s start=%llu, end=%llu\n",
3737                dentry, dentry->d_inode,
3738                user_lockname[ladvise->lla_lockahead_mode], (__u64) start,
3739                (__u64) end);
3740
3741         cl_mode = cl_mode_user_to_kernel(ladvise->lla_lockahead_mode);
3742         if (cl_mode < 0)
3743                 GOTO(out, result = cl_mode);
3744
3745         /* Get IO environment */
3746         result = cl_io_get(inode, &env, &io, &refcheck);
3747         if (result <= 0)
3748                 GOTO(out, result);
3749
3750         result = cl_io_init(env, io, CIT_MISC, io->ci_obj);
3751         if (result > 0) {
3752                 /*
3753                  * nothing to do for this io. This currently happens when
3754                  * stripe sub-object's are not yet created.
3755                  */
3756                 result = io->ci_result;
3757         } else if (result == 0) {
3758                 lock = vvp_env_lock(env);
3759                 descr = &lock->cll_descr;
3760
3761                 descr->cld_obj   = io->ci_obj;
3762                 /* Convert byte offsets to pages */
3763                 descr->cld_start = start >> PAGE_SHIFT;
3764                 descr->cld_end   = end >> PAGE_SHIFT;
3765                 descr->cld_mode  = cl_mode;
3766                 /* CEF_MUST is used because we do not want to convert a
3767                  * lockahead request to a lockless lock */
3768                 descr->cld_enq_flags = CEF_MUST | CEF_LOCK_NO_EXPAND;
3769
3770                 if (ladvise->lla_peradvice_flags & LF_ASYNC)
3771                         descr->cld_enq_flags |= CEF_SPECULATIVE;
3772
3773                 result = cl_lock_request(env, io, lock);
3774
3775                 /* On success, we need to release the lock */
3776                 if (result >= 0)
3777                         cl_lock_release(env, lock);
3778         }
3779         cl_io_fini(env, io);
3780         cl_env_put(env, &refcheck);
3781
3782         /* -ECANCELED indicates a matching lock with a different extent
3783          * was already present, and -EEXIST indicates a matching lock
3784          * on exactly the same extent was already present.
3785          * We convert them to positive values for userspace to make
3786          * recognizing true errors easier.
3787          * Note we can only return these detailed results on async requests,
3788          * as sync requests look the same as i/o requests for locking. */
3789         if (result == -ECANCELED)
3790                 result = LLA_RESULT_DIFFERENT;
3791         else if (result == -EEXIST)
3792                 result = LLA_RESULT_SAME;
3793
3794 out:
3795         RETURN(result);
3796 }
3797 static const char *const ladvise_names[] = LU_LADVISE_NAMES;
3798
3799 static int ll_ladvise_sanity(struct inode *inode,
3800                              struct llapi_lu_ladvise *ladvise)
3801 {
3802         struct ll_sb_info *sbi = ll_i2sbi(inode);
3803         enum lu_ladvise_type advice = ladvise->lla_advice;
3804         /* Note the peradvice flags is a 32 bit field, so per advice flags must
3805          * be in the first 32 bits of enum ladvise_flags */
3806         __u32 flags = ladvise->lla_peradvice_flags;
3807         /* 3 lines at 80 characters per line, should be plenty */
3808         int rc = 0;
3809
3810         if (advice > LU_LADVISE_MAX || advice == LU_LADVISE_INVALID) {
3811                 rc = -EINVAL;
3812                 CDEBUG(D_VFSTRACE,
3813                        "%s: advice with value '%d' not recognized, last supported advice is %s (value '%d'): rc = %d\n",
3814                        sbi->ll_fsname, advice,
3815                        ladvise_names[LU_LADVISE_MAX-1], LU_LADVISE_MAX-1, rc);
3816                 GOTO(out, rc);
3817         }
3818
3819         /* Per-advice checks */
3820         switch (advice) {
3821         case LU_LADVISE_LOCKNOEXPAND:
3822                 if (flags & ~LF_LOCKNOEXPAND_MASK) {
3823                         rc = -EINVAL;
3824                         CDEBUG(D_VFSTRACE, "%s: Invalid flags (%x) for %s: "
3825                                "rc = %d\n", sbi->ll_fsname, flags,
3826                                ladvise_names[advice], rc);
3827                         GOTO(out, rc);
3828                 }
3829                 break;
3830         case LU_LADVISE_LOCKAHEAD:
3831                 /* Currently only READ and WRITE modes can be requested */
3832                 if (ladvise->lla_lockahead_mode >= MODE_MAX_USER ||
3833                     ladvise->lla_lockahead_mode == 0) {
3834                         rc = -EINVAL;
3835                         CDEBUG(D_VFSTRACE, "%s: Invalid mode (%d) for %s: "
3836                                "rc = %d\n", sbi->ll_fsname,
3837                                ladvise->lla_lockahead_mode,
3838                                ladvise_names[advice], rc);
3839                         GOTO(out, rc);
3840                 }
3841                 fallthrough;
3842         case LU_LADVISE_WILLREAD:
3843         case LU_LADVISE_DONTNEED:
3844         default:
3845                 /* Note fall through above - These checks apply to all advices
3846                  * except LOCKNOEXPAND */
3847                 if (flags & ~LF_DEFAULT_MASK) {
3848                         rc = -EINVAL;
3849                         CDEBUG(D_VFSTRACE, "%s: Invalid flags (%x) for %s: "
3850                                "rc = %d\n", sbi->ll_fsname, flags,
3851                                ladvise_names[advice], rc);
3852                         GOTO(out, rc);
3853                 }
3854                 if (ladvise->lla_start >= ladvise->lla_end) {
3855                         rc = -EINVAL;
3856                         CDEBUG(D_VFSTRACE, "%s: Invalid range (%llu to %llu) "
3857                                "for %s: rc = %d\n", sbi->ll_fsname,
3858                                ladvise->lla_start, ladvise->lla_end,
3859                                ladvise_names[advice], rc);
3860                         GOTO(out, rc);
3861                 }
3862                 break;
3863         }
3864
3865 out:
3866         return rc;
3867 }
3868 #undef ERRSIZE
3869
3870 /*
3871  * Give file access advices
3872  *
3873  * The ladvise interface is similar to Linux fadvise() system call, except it
3874  * forwards the advices directly from Lustre client to server. The server side
3875  * codes will apply appropriate read-ahead and caching techniques for the
3876  * corresponding files.
3877  *
3878  * A typical workload for ladvise is e.g. a bunch of different clients are
3879  * doing small random reads of a file, so prefetching pages into OSS cache
3880  * with big linear reads before the random IO is a net benefit. Fetching
3881  * all that data into each client cache with fadvise() may not be, due to
3882  * much more data being sent to the client.
3883  */
3884 static int ll_ladvise(struct inode *inode, struct file *file, __u64 flags,
3885                       struct llapi_lu_ladvise *ladvise)
3886 {
3887         struct lu_env *env;
3888         struct cl_io *io;
3889         struct cl_ladvise_io *lio;
3890         int rc;
3891         __u16 refcheck;
3892         ENTRY;
3893
3894         env = cl_env_get(&refcheck);
3895         if (IS_ERR(env))
3896                 RETURN(PTR_ERR(env));
3897
3898         io = vvp_env_thread_io(env);
3899         io->ci_obj = ll_i2info(inode)->lli_clob;
3900
3901         /* initialize parameters for ladvise */
3902         lio = &io->u.ci_ladvise;
3903         lio->lio_start = ladvise->lla_start;
3904         lio->lio_end = ladvise->lla_end;
3905         lio->lio_fid = ll_inode2fid(inode);
3906         lio->lio_advice = ladvise->lla_advice;
3907         lio->lio_flags = flags;
3908
3909         if (cl_io_init(env, io, CIT_LADVISE, io->ci_obj) == 0)
3910                 rc = cl_io_loop(env, io);
3911         else
3912                 rc = io->ci_result;
3913
3914         cl_io_fini(env, io);
3915         cl_env_put(env, &refcheck);
3916         RETURN(rc);
3917 }
3918
3919 static int ll_lock_noexpand(struct file *file, int flags)
3920 {
3921         struct ll_file_data *fd = file->private_data;
3922
3923         fd->ll_lock_no_expand = !(flags & LF_UNSET);
3924
3925         return 0;
3926 }
3927
3928 #ifndef HAVE_FILEATTR_GET
3929 int ll_ioctl_fsgetxattr(struct inode *inode, unsigned int cmd,
3930                         void __user *uarg)
3931 {
3932         struct fsxattr fsxattr;
3933
3934         if (copy_from_user(&fsxattr, uarg, sizeof(fsxattr)))
3935                 RETURN(-EFAULT);
3936
3937         fsxattr.fsx_xflags = ll_inode_flags_to_xflags(inode->i_flags);
3938         if (test_bit(LLIF_PROJECT_INHERIT, &ll_i2info(inode)->lli_flags))
3939                 fsxattr.fsx_xflags |= FS_XFLAG_PROJINHERIT;
3940         fsxattr.fsx_projid = ll_i2info(inode)->lli_projid;
3941         if (copy_to_user(uarg, &fsxattr, sizeof(fsxattr)))
3942                 RETURN(-EFAULT);
3943
3944         RETURN(0);
3945 }
3946 #endif
3947
3948 int ll_ioctl_check_project(struct inode *inode, __u32 xflags,
3949                            __u32 projid)
3950 {
3951         /*
3952          * Project Quota ID state is only allowed to change from within the init
3953          * namespace. Enforce that restriction only if we are trying to change
3954          * the quota ID state. Everything else is allowed in user namespaces.
3955          */
3956         if (current_user_ns() == &init_user_ns) {
3957                 /*
3958                  * Caller is allowed to change the project ID. if it is being
3959                  * changed, make sure that the new value is valid.
3960                  */
3961                 if (ll_i2info(inode)->lli_projid != projid &&
3962                      !projid_valid(make_kprojid(&init_user_ns, projid)))
3963                         return -EINVAL;
3964
3965                 return 0;
3966         }
3967
3968         if (ll_i2info(inode)->lli_projid != projid)
3969                 return -EINVAL;
3970
3971         if (test_bit(LLIF_PROJECT_INHERIT, &ll_i2info(inode)->lli_flags)) {
3972                 if (!(xflags & FS_XFLAG_PROJINHERIT))
3973                         return -EINVAL;
3974         } else {
3975                 if (xflags & FS_XFLAG_PROJINHERIT)
3976                         return -EINVAL;
3977         }
3978
3979         return 0;
3980 }
3981
3982 int ll_set_project(struct inode *inode, __u32 xflags, __u32 projid)
3983 {
3984         struct ptlrpc_request *req = NULL;
3985         struct md_op_data *op_data;
3986         struct cl_object *obj;
3987         unsigned int inode_flags;
3988         int rc = 0;
3989
3990         CDEBUG(D_QUOTA, DFID" xflags=%x projid=%u\n",
3991                PFID(ll_inode2fid(inode)), xflags, projid);
3992         rc = ll_ioctl_check_project(inode, xflags, projid);
3993         if (rc)
3994                 RETURN(rc);
3995
3996         op_data = ll_prep_md_op_data(NULL, inode, NULL, NULL, 0, 0,
3997                                      LUSTRE_OPC_ANY, NULL);
3998         if (IS_ERR(op_data))
3999                 RETURN(PTR_ERR(op_data));
4000
4001         inode_flags = ll_xflags_to_inode_flags(xflags);
4002         op_data->op_attr_flags = ll_inode_to_ext_flags(inode_flags);
4003         if (xflags & FS_XFLAG_PROJINHERIT)
4004                 op_data->op_attr_flags |= LUSTRE_PROJINHERIT_FL;
4005
4006         /* pass projid to md_op_data */
4007         op_data->op_projid = projid;
4008
4009         op_data->op_xvalid |= OP_XVALID_PROJID | OP_XVALID_FLAGS;
4010         rc = md_setattr(ll_i2sbi(inode)->ll_md_exp, op_data, NULL, 0, &req);
4011         ptlrpc_req_finished(req);
4012         if (rc)
4013                 GOTO(out_fsxattr, rc);
4014         ll_update_inode_flags(inode, op_data->op_attr_flags);
4015
4016         /* Avoid OST RPC if this is only ioctl setting project inherit flag */
4017         if (xflags == 0 || xflags == FS_XFLAG_PROJINHERIT)
4018                 GOTO(out_fsxattr, rc);
4019
4020         obj = ll_i2info(inode)->lli_clob;
4021         if (obj) {
4022                 struct iattr attr = { 0 };
4023
4024                 rc = cl_setattr_ost(obj, &attr, OP_XVALID_FLAGS, xflags);
4025         }
4026
4027 out_fsxattr:
4028         ll_finish_md_op_data(op_data);
4029         RETURN(rc);
4030 }
4031
4032 #ifndef HAVE_FILEATTR_GET
4033 int ll_ioctl_fssetxattr(struct inode *inode, unsigned int cmd,
4034                         void __user *uarg)
4035 {
4036         struct fsxattr fsxattr;
4037
4038         ENTRY;
4039
4040         if (copy_from_user(&fsxattr, uarg, sizeof(fsxattr)))
4041                 RETURN(-EFAULT);
4042
4043         RETURN(ll_set_project(inode, fsxattr.fsx_xflags,
4044                               fsxattr.fsx_projid));
4045 }
4046 #endif
4047
4048 int ll_ioctl_project(struct file *file, unsigned int cmd, void __user *uarg)
4049 {
4050         struct lu_project lu_project;
4051         struct dentry *dentry = file_dentry(file);
4052         struct inode *inode = file_inode(file);
4053         struct dentry *child_dentry = NULL;
4054         int rc = 0, name_len;
4055
4056         if (copy_from_user(&lu_project, uarg, sizeof(lu_project)))
4057                 RETURN(-EFAULT);
4058
4059         /* apply child dentry if name is valid */
4060         name_len = strnlen(lu_project.project_name, NAME_MAX);
4061         if (name_len > 0 && name_len <= NAME_MAX) {
4062                 ll_inode_lock(inode);
4063                 child_dentry = lookup_one_len(lu_project.project_name,
4064                                               dentry, name_len);
4065                 ll_inode_unlock(inode);
4066                 if (IS_ERR(child_dentry)) {
4067                         rc = PTR_ERR(child_dentry);
4068                         goto out;
4069                 }
4070                 inode = child_dentry->d_inode;
4071                 if (!inode) {
4072                         rc = -ENOENT;
4073                         goto out;
4074                 }
4075         } else if (name_len > NAME_MAX) {
4076                 rc = -EINVAL;
4077                 goto out;
4078         }
4079
4080         switch (lu_project.project_type) {
4081         case LU_PROJECT_SET:
4082                 rc = ll_set_project(inode, lu_project.project_xflags,
4083                                     lu_project.project_id);
4084                 break;
4085         case LU_PROJECT_GET:
4086                 lu_project.project_xflags =
4087                                 ll_inode_flags_to_xflags(inode->i_flags);
4088                 if (test_bit(LLIF_PROJECT_INHERIT,
4089                              &ll_i2info(inode)->lli_flags))
4090                         lu_project.project_xflags |= FS_XFLAG_PROJINHERIT;
4091                 lu_project.project_id = ll_i2info(inode)->lli_projid;
4092                 if (copy_to_user(uarg, &lu_project, sizeof(lu_project))) {
4093                         rc = -EFAULT;
4094                         goto out;
4095                 }
4096                 break;
4097         default:
4098                 rc = -EINVAL;
4099                 break;
4100         }
4101 out:
4102         if (!IS_ERR_OR_NULL(child_dentry))
4103                 dput(child_dentry);
4104         RETURN(rc);
4105 }
4106
4107 static long ll_file_unlock_lease(struct file *file, struct ll_ioc_lease *ioc,
4108                                  void __user *uarg)
4109 {
4110         struct inode *inode = file_inode(file);
4111         struct ll_file_data *fd = file->private_data;
4112         struct ll_inode_info *lli = ll_i2info(inode);
4113         struct obd_client_handle *och = NULL;
4114         struct split_param sp;
4115         struct pcc_param param;
4116         bool lease_broken = false;
4117         fmode_t fmode = 0;
4118         enum mds_op_bias bias = 0;
4119         __u32 fdv;
4120         struct file *layout_file = NULL;
4121         void *data = NULL;
4122         size_t data_size = 0;
4123         bool attached = false;
4124         long rc, rc2 = 0;
4125
4126         ENTRY;
4127
4128         mutex_lock(&lli->lli_och_mutex);
4129         if (fd->fd_lease_och != NULL) {
4130                 och = fd->fd_lease_och;
4131                 fd->fd_lease_och = NULL;
4132         }
4133         mutex_unlock(&lli->lli_och_mutex);
4134
4135         if (och == NULL)
4136                 RETURN(-ENOLCK);
4137
4138         fmode = och->och_flags;
4139
4140         switch (ioc->lil_flags) {
4141         case LL_LEASE_RESYNC_DONE:
4142                 if (ioc->lil_count > IOC_IDS_MAX)
4143                         GOTO(out_lease_close, rc = -EINVAL);
4144
4145                 data_size = offsetof(typeof(*ioc), lil_ids[ioc->lil_count]);
4146                 OBD_ALLOC(data, data_size);
4147                 if (!data)
4148                         GOTO(out_lease_close, rc = -ENOMEM);
4149
4150                 if (copy_from_user(data, uarg, data_size))
4151                         GOTO(out_lease_close, rc = -EFAULT);
4152
4153                 bias = MDS_CLOSE_RESYNC_DONE;
4154                 break;
4155         case LL_LEASE_LAYOUT_MERGE:
4156                 if (ioc->lil_count != 1)
4157                         GOTO(out_lease_close, rc = -EINVAL);
4158
4159                 uarg += sizeof(*ioc);
4160                 if (copy_from_user(&fdv, uarg, sizeof(fdv)))
4161                         GOTO(out_lease_close, rc = -EFAULT);
4162
4163                 layout_file = fget(fdv);
4164                 if (!layout_file)
4165                         GOTO(out_lease_close, rc = -EBADF);
4166
4167                 if ((file->f_flags & O_ACCMODE) == O_RDONLY ||
4168                                 (layout_file->f_flags & O_ACCMODE) == O_RDONLY)
4169                         GOTO(out_lease_close, rc = -EPERM);
4170
4171                 data = file_inode(layout_file);
4172                 bias = MDS_CLOSE_LAYOUT_MERGE;
4173                 break;
4174         case LL_LEASE_LAYOUT_SPLIT: {
4175                 __u32 mirror_id;
4176
4177                 if (ioc->lil_count != 2)
4178                         GOTO(out_lease_close, rc = -EINVAL);
4179
4180                 uarg += sizeof(*ioc);
4181                 if (copy_from_user(&fdv, uarg, sizeof(fdv)))
4182                         GOTO(out_lease_close, rc = -EFAULT);
4183
4184                 uarg += sizeof(fdv);
4185                 if (copy_from_user(&mirror_id, uarg, sizeof(mirror_id)))
4186                         GOTO(out_lease_close, rc = -EFAULT);
4187                 if (mirror_id >= MIRROR_ID_NEG)
4188                         GOTO(out_lease_close, rc = -EINVAL);
4189
4190                 layout_file = fget(fdv);
4191                 if (!layout_file)
4192                         GOTO(out_lease_close, rc = -EBADF);
4193
4194                 /* if layout_file == file, it means to destroy the mirror */
4195                 sp.sp_inode = file_inode(layout_file);
4196                 sp.sp_mirror_id = (__u16)mirror_id;
4197                 data = &sp;
4198                 bias = MDS_CLOSE_LAYOUT_SPLIT;
4199                 break;
4200         }
4201         case LL_LEASE_PCC_ATTACH:
4202                 if (ioc->lil_count != 1)
4203                         RETURN(-EINVAL);
4204
4205                 if (IS_ENCRYPTED(inode))
4206                         RETURN(-EOPNOTSUPP);
4207
4208                 uarg += sizeof(*ioc);
4209                 if (copy_from_user(&param.pa_archive_id, uarg, sizeof(__u32)))
4210                         GOTO(out_lease_close, rc2 = -EFAULT);
4211
4212                 rc2 = pcc_readwrite_attach(file, inode, param.pa_archive_id);
4213                 if (rc2)
4214                         GOTO(out_lease_close, rc2);
4215
4216                 attached = true;
4217                 /* Grab latest data version */
4218                 rc2 = ll_data_version(inode, &param.pa_data_version,
4219                                      LL_DV_WR_FLUSH);
4220                 if (rc2)
4221                         GOTO(out_lease_close, rc2);
4222
4223                 data = &param;
4224                 bias = MDS_PCC_ATTACH;
4225                 break;
4226         default:
4227                 /* without close intent */
4228                 break;
4229         }
4230
4231 out_lease_close:
4232         rc = ll_lease_close_intent(och, inode, &lease_broken, bias, data);
4233         if (rc < 0)
4234                 GOTO(out, rc);
4235
4236         rc = ll_lease_och_release(inode, file);
4237         if (rc < 0)
4238                 GOTO(out, rc);
4239
4240         if (lease_broken)
4241                 fmode = 0;
4242         EXIT;
4243
4244 out:
4245         if (ioc->lil_flags == LL_LEASE_RESYNC_DONE && data)
4246                 OBD_FREE(data, data_size);
4247
4248         if (layout_file)
4249                 fput(layout_file);
4250
4251         if (ioc->lil_flags == LL_LEASE_PCC_ATTACH) {
4252                 if (!rc)
4253                         rc = rc2;
4254                 rc = pcc_readwrite_attach_fini(file, inode,
4255                                                param.pa_layout_gen,
4256                                                lease_broken, rc,
4257                                                attached);
4258         }
4259
4260         ll_layout_refresh(inode, &fd->fd_layout_version);
4261
4262         if (!rc)
4263                 rc = ll_lease_type_from_fmode(fmode);
4264         RETURN(rc);
4265 }
4266
4267 static long ll_file_set_lease(struct file *file, struct ll_ioc_lease *ioc,
4268                               void __user *uarg)
4269 {
4270         struct inode *inode = file_inode(file);
4271         struct ll_inode_info *lli = ll_i2info(inode);
4272         struct ll_file_data *fd = file->private_data;
4273         struct obd_client_handle *och = NULL;
4274         __u64 open_flags = 0;
4275         bool lease_broken;
4276         fmode_t fmode;
4277         long rc;
4278         ENTRY;
4279
4280         switch (ioc->lil_mode) {
4281         case LL_LEASE_WRLCK:
4282                 if (!(file->f_mode & FMODE_WRITE))
4283                         RETURN(-EPERM);
4284                 fmode = FMODE_WRITE;
4285                 break;
4286         case LL_LEASE_RDLCK:
4287                 if (!(file->f_mode & FMODE_READ))
4288                         RETURN(-EPERM);
4289                 fmode = FMODE_READ;
4290                 break;
4291         case LL_LEASE_UNLCK:
4292                 RETURN(ll_file_unlock_lease(file, ioc, uarg));
4293         default:
4294                 RETURN(-EINVAL);
4295         }
4296
4297         CDEBUG(D_INODE, "Set lease with mode %u\n", fmode);
4298
4299         /* apply for lease */
4300         if (ioc->lil_flags & LL_LEASE_RESYNC)
4301                 open_flags = MDS_OPEN_RESYNC;
4302         och = ll_lease_open(inode, file, fmode, open_flags);
4303         if (IS_ERR(och))
4304                 RETURN(PTR_ERR(och));
4305
4306         if (ioc->lil_flags & LL_LEASE_RESYNC) {
4307                 rc = ll_lease_file_resync(och, inode, uarg);
4308                 if (rc) {
4309                         ll_lease_close(och, inode, NULL);
4310                         RETURN(rc);
4311                 }
4312                 rc = ll_layout_refresh(inode, &fd->fd_layout_version);
4313                 if (rc) {
4314                         ll_lease_close(och, inode, NULL);
4315                         RETURN(rc);
4316                 }
4317         }
4318
4319         rc = 0;
4320         mutex_lock(&lli->lli_och_mutex);
4321         if (fd->fd_lease_och == NULL) {
4322                 fd->fd_lease_och = och;
4323                 och = NULL;
4324         }
4325         mutex_unlock(&lli->lli_och_mutex);
4326         if (och != NULL) {
4327                 /* impossible now that only excl is supported for now */
4328                 ll_lease_close(och, inode, &lease_broken);
4329                 rc = -EBUSY;
4330         }
4331         RETURN(rc);
4332 }
4333
4334 static void ll_heat_get(struct inode *inode, struct lu_heat *heat)
4335 {
4336         struct ll_inode_info *lli = ll_i2info(inode);
4337         struct ll_sb_info *sbi = ll_i2sbi(inode);
4338         __u64 now = ktime_get_real_seconds();
4339         int i;
4340
4341         spin_lock(&lli->lli_heat_lock);
4342         heat->lh_flags = lli->lli_heat_flags;
4343         for (i = 0; i < heat->lh_count; i++)
4344                 heat->lh_heat[i] = obd_heat_get(&lli->lli_heat_instances[i],
4345                                                 now, sbi->ll_heat_decay_weight,
4346                                                 sbi->ll_heat_period_second);
4347         spin_unlock(&lli->lli_heat_lock);
4348 }
4349
4350 static int ll_heat_set(struct inode *inode, enum lu_heat_flag flags)
4351 {
4352         struct ll_inode_info *lli = ll_i2info(inode);
4353         int rc = 0;
4354
4355         spin_lock(&lli->lli_heat_lock);
4356         if (flags & LU_HEAT_FLAG_CLEAR)
4357                 obd_heat_clear(lli->lli_heat_instances, OBD_HEAT_COUNT);
4358
4359         if (flags & LU_HEAT_FLAG_OFF)
4360                 lli->lli_heat_flags |= LU_HEAT_FLAG_OFF;
4361         else
4362                 lli->lli_heat_flags &= ~LU_HEAT_FLAG_OFF;
4363
4364         spin_unlock(&lli->lli_heat_lock);
4365
4366         RETURN(rc);
4367 }
4368
4369 static long
4370 ll_file_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
4371 {
4372         struct inode *inode = file_inode(file);
4373         struct ll_file_data *fd = file->private_data;
4374         void __user *uarg = (void __user *)arg;
4375         int flags, rc;
4376         ENTRY;
4377
4378         CDEBUG(D_VFSTRACE|D_IOCTL, "VFS Op:inode="DFID"(%pK) cmd=%x arg=%lx\n",
4379                PFID(ll_inode2fid(inode)), inode, cmd, arg);
4380         ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_IOCTL, 1);
4381
4382         /* asm-ppc{,64} declares TCGETS, et. al. as type 't' not 'T' */
4383         if (_IOC_TYPE(cmd) == 'T' || _IOC_TYPE(cmd) == 't') /* tty ioctls */
4384                 RETURN(-ENOTTY);
4385
4386         /* can't do a generic karg == NULL check here, since it is too noisy and
4387          * we need to return -ENOTTY for unsupported ioctls instead of -EINVAL.
4388          */
4389         switch (cmd) {
4390         case LL_IOC_GETFLAGS:
4391                 /* Get the current value of the file flags */
4392                 return put_user(fd->fd_flags, (int __user *)arg);
4393         case LL_IOC_SETFLAGS:
4394         case LL_IOC_CLRFLAGS:
4395                 /* Set or clear specific file flags */
4396                 /* XXX This probably needs checks to ensure the flags are
4397                  *     not abused, and to handle any flag side effects.
4398                  */
4399                 if (get_user(flags, (int __user *)arg))
4400                         RETURN(-EFAULT);
4401
4402                 /* LL_FILE_GROUP_LOCKED is managed via its own ioctls */
4403                 if (flags & LL_FILE_GROUP_LOCKED)
4404                         RETURN(-EINVAL);
4405
4406                 if (cmd == LL_IOC_SETFLAGS) {
4407                         if ((flags & LL_FILE_IGNORE_LOCK) &&
4408                             !(file->f_flags & O_DIRECT)) {
4409                                 rc = -EINVAL;
4410                                 CERROR("%s: unable to disable locking on non-O_DIRECT file "DFID": rc = %d\n",
4411                                        current->comm, PFID(ll_inode2fid(inode)),
4412                                        rc);
4413                                 RETURN(rc);
4414                         }
4415
4416                         fd->fd_flags |= flags;
4417                 } else {
4418                         fd->fd_flags &= ~flags;
4419                 }
4420                 RETURN(0);
4421         case LL_IOC_LOV_SETSTRIPE:
4422         case LL_IOC_LOV_SETSTRIPE_NEW:
4423                 RETURN(ll_lov_setstripe(inode, file, uarg));
4424         case LL_IOC_LOV_SETEA:
4425                 RETURN(ll_lov_setea(inode, file, uarg));
4426         case LL_IOC_LOV_SWAP_LAYOUTS: {
4427                 struct file *file2;
4428                 struct lustre_swap_layouts lsl;
4429
4430                 if (copy_from_user(&lsl, uarg, sizeof(lsl)))
4431                         RETURN(-EFAULT);
4432
4433                 if ((file->f_flags & O_ACCMODE) == O_RDONLY)
4434                         RETURN(-EPERM);
4435
4436                 file2 = fget(lsl.sl_fd);
4437                 if (file2 == NULL)
4438                         RETURN(-EBADF);
4439
4440                 /* O_WRONLY or O_RDWR */
4441                 if ((file2->f_flags & O_ACCMODE) == O_RDONLY)
4442                         GOTO(out, rc = -EPERM);
4443
4444                 if (lsl.sl_flags & SWAP_LAYOUTS_CLOSE) {
4445                         struct obd_client_handle *och = NULL;
4446                         struct ll_inode_info *lli;
4447                         struct inode *inode2;
4448
4449                         lli = ll_i2info(inode);
4450                         mutex_lock(&lli->lli_och_mutex);
4451                         if (fd->fd_lease_och != NULL) {
4452                                 och = fd->fd_lease_och;
4453                                 fd->fd_lease_och = NULL;
4454                         }
4455                         mutex_unlock(&lli->lli_och_mutex);
4456                         if (och == NULL)
4457                                 GOTO(out, rc = -ENOLCK);
4458                         inode2 = file_inode(file2);
4459                         rc = ll_swap_layouts_close(och, inode, inode2, &lsl);
4460                 } else {
4461                         rc = ll_swap_layouts(file, file2, &lsl);
4462                 }
4463 out:
4464                 fput(file2);
4465                 RETURN(rc);
4466         }
4467         case LL_IOC_LOV_GETSTRIPE:
4468         case LL_IOC_LOV_GETSTRIPE_NEW:
4469                 RETURN(ll_file_getstripe(inode, uarg, 0));
4470         case LL_IOC_GROUP_LOCK:
4471                 RETURN(ll_get_grouplock(inode, file, arg));
4472         case LL_IOC_GROUP_UNLOCK:
4473                 RETURN(ll_put_grouplock(inode, file, arg));
4474         case LL_IOC_DATA_VERSION: {
4475                 struct ioc_data_version idv;
4476                 int rc;
4477
4478                 if (copy_from_user(&idv, uarg, sizeof(idv)))
4479                         RETURN(-EFAULT);
4480
4481                 idv.idv_flags &= LL_DV_RD_FLUSH | LL_DV_WR_FLUSH;
4482                 rc = ll_ioc_data_version(inode, &idv);
4483
4484                 if (rc == 0 && copy_to_user(uarg, &idv, sizeof(idv)))
4485                         RETURN(-EFAULT);
4486
4487                 RETURN(rc);
4488         }
4489         case LL_IOC_HSM_STATE_GET: {
4490                 struct md_op_data *op_data;
4491                 struct hsm_user_state *hus;
4492                 int rc;
4493
4494                 if (!ll_access_ok(uarg, sizeof(*hus)))
4495                         RETURN(-EFAULT);
4496
4497                 OBD_ALLOC_PTR(hus);
4498                 if (hus == NULL)
4499                         RETURN(-ENOMEM);
4500
4501                 op_data = ll_prep_md_op_data(NULL, inode, NULL, NULL, 0, 0,
4502                                              LUSTRE_OPC_ANY, hus);
4503                 if (IS_ERR(op_data)) {
4504                         rc = PTR_ERR(op_data);
4505                 } else {
4506                         rc = obd_iocontrol(cmd, ll_i2mdexp(inode),
4507                                            sizeof(*op_data), op_data, NULL);
4508
4509                         if (copy_to_user(uarg, hus, sizeof(*hus)))
4510                                 rc = -EFAULT;
4511
4512                         ll_finish_md_op_data(op_data);
4513                 }
4514                 OBD_FREE_PTR(hus);
4515                 RETURN(rc);
4516         }
4517         case LL_IOC_HSM_STATE_SET: {
4518                 struct hsm_state_set *hss;
4519                 int rc;
4520
4521                 OBD_ALLOC_PTR(hss);
4522                 if (hss == NULL)
4523                         RETURN(-ENOMEM);
4524
4525                 if (copy_from_user(hss, uarg, sizeof(*hss)))
4526                         rc = -EFAULT;
4527                 else
4528                         rc = ll_hsm_state_set(inode, hss);
4529
4530                 OBD_FREE_PTR(hss);
4531                 RETURN(rc);
4532         }
4533         case LL_IOC_HSM_ACTION: {
4534                 struct md_op_data *op_data;
4535                 struct hsm_current_action *hca;
4536                 const char *action;
4537                 int rc;
4538
4539                 if (!ll_access_ok(uarg, sizeof(*hca)))
4540                         RETURN(-EFAULT);
4541
4542                 OBD_ALLOC_PTR(hca);
4543                 if (hca == NULL)
4544                         RETURN(-ENOMEM);
4545
4546                 op_data = ll_prep_md_op_data(NULL, inode, NULL, NULL, 0, 0,
4547                                              LUSTRE_OPC_ANY, hca);
4548                 if (IS_ERR(op_data)) {
4549                         OBD_FREE_PTR(hca);
4550                         RETURN(PTR_ERR(op_data));
4551                 }
4552
4553                 rc = obd_iocontrol(cmd, ll_i2mdexp(inode), sizeof(*op_data),
4554                                    op_data, NULL);
4555                 if (rc < 0)
4556                         GOTO(skip_copy, rc);
4557
4558                 /* The hsm_current_action retreived from the server could
4559                  * contain corrupt information. If it is incorrect data collect
4560                  * debug information. We still send the data even if incorrect
4561                  * to user land to handle.
4562                  */
4563                 action = hsm_user_action2name(hca->hca_action);
4564                 if (strcmp(action, "UNKNOWN") == 0 ||
4565                     hca->hca_state > HPS_DONE) {
4566                         CDEBUG(D_HSM,
4567                                "HSM current state %s action %s, offset = %llu, length %llu\n",
4568                                hsm_progress_state2name(hca->hca_state), action,
4569                                hca->hca_location.offset, hca->hca_location.length);
4570                 }
4571
4572                 if (copy_to_user(uarg, hca, sizeof(*hca)))
4573                         rc = -EFAULT;
4574 skip_copy:
4575                 ll_finish_md_op_data(op_data);
4576                 OBD_FREE_PTR(hca);
4577                 RETURN(rc);
4578         }
4579         case LL_IOC_SET_LEASE_OLD: {
4580                 struct ll_ioc_lease ioc = { .lil_mode = arg };
4581
4582                 RETURN(ll_file_set_lease(file, &ioc, 0));
4583         }
4584         case LL_IOC_SET_LEASE: {
4585                 struct ll_ioc_lease ioc;
4586
4587                 if (copy_from_user(&ioc, uarg, sizeof(ioc)))
4588                         RETURN(-EFAULT);
4589
4590                 RETURN(ll_file_set_lease(file, &ioc, uarg));
4591         }
4592         case LL_IOC_GET_LEASE: {
4593                 struct ll_inode_info *lli = ll_i2info(inode);
4594                 struct ldlm_lock *lock = NULL;
4595                 fmode_t fmode = 0;
4596
4597                 mutex_lock(&lli->lli_och_mutex);
4598                 if (fd->fd_lease_och != NULL) {
4599                         struct obd_client_handle *och = fd->fd_lease_och;
4600
4601                         lock = ldlm_handle2lock(&och->och_lease_handle);
4602                         if (lock != NULL) {
4603                                 lock_res_and_lock(lock);
4604                                 if (!ldlm_is_cancel(lock))
4605                                         fmode = och->och_flags;
4606
4607                                 unlock_res_and_lock(lock);
4608                                 LDLM_LOCK_PUT(lock);
4609                         }
4610                 }
4611                 mutex_unlock(&lli->lli_och_mutex);
4612
4613                 RETURN(ll_lease_type_from_fmode(fmode));
4614         }
4615         case LL_IOC_HSM_IMPORT: {
4616                 struct hsm_user_import *hui;
4617
4618                 OBD_ALLOC_PTR(hui);
4619                 if (hui == NULL)
4620                         RETURN(-ENOMEM);
4621
4622                 if (copy_from_user(hui, uarg, sizeof(*hui)))
4623                         rc = -EFAULT;
4624                 else
4625                         rc = ll_hsm_import(inode, file, hui);
4626
4627                 OBD_FREE_PTR(hui);
4628                 RETURN(rc);
4629         }
4630         case LL_IOC_FUTIMES_3: {
4631                 struct ll_futimes_3 lfu;
4632
4633                 if (copy_from_user(&lfu, uarg, sizeof(lfu)))
4634                         RETURN(-EFAULT);
4635
4636                 RETURN(ll_file_futimes_3(file, &lfu));
4637         }
4638         case LL_IOC_LADVISE: {
4639                 struct llapi_ladvise_hdr *k_ladvise_hdr;
4640                 struct llapi_ladvise_hdr __user *u_ladvise_hdr;
4641                 int i;
4642                 int num_advise;
4643                 int alloc_size = sizeof(*k_ladvise_hdr);
4644
4645                 rc = 0;
4646                 u_ladvise_hdr = uarg;
4647                 OBD_ALLOC_PTR(k_ladvise_hdr);
4648                 if (k_ladvise_hdr == NULL)
4649                         RETURN(-ENOMEM);
4650
4651                 if (copy_from_user(k_ladvise_hdr, u_ladvise_hdr, alloc_size))
4652                         GOTO(out_ladvise, rc = -EFAULT);
4653
4654                 if (k_ladvise_hdr->lah_magic != LADVISE_MAGIC ||
4655                     k_ladvise_hdr->lah_count < 1)
4656                         GOTO(out_ladvise, rc = -EINVAL);
4657
4658                 num_advise = k_ladvise_hdr->lah_count;
4659                 if (num_advise >= LAH_COUNT_MAX)
4660                         GOTO(out_ladvise, rc = -EFBIG);
4661
4662                 OBD_FREE_PTR(k_ladvise_hdr);
4663                 alloc_size = offsetof(typeof(*k_ladvise_hdr),
4664                                       lah_advise[num_advise]);
4665                 OBD_ALLOC(k_ladvise_hdr, alloc_size);
4666                 if (k_ladvise_hdr == NULL)
4667                         RETURN(-ENOMEM);
4668
4669                 /*
4670                  * TODO: submit multiple advices to one server in a single RPC
4671                  */
4672                 if (copy_from_user(k_ladvise_hdr, u_ladvise_hdr, alloc_size))
4673                         GOTO(out_ladvise, rc = -EFAULT);
4674
4675                 for (i = 0; i < num_advise; i++) {
4676                         struct llapi_lu_ladvise *k_ladvise =
4677                                         &k_ladvise_hdr->lah_advise[i];
4678                         struct llapi_lu_ladvise __user *u_ladvise =
4679                                         &u_ladvise_hdr->lah_advise[i];
4680
4681                         rc = ll_ladvise_sanity(inode, k_ladvise);
4682                         if (rc)
4683                                 GOTO(out_ladvise, rc);
4684
4685                         switch (k_ladvise->lla_advice) {
4686                         case LU_LADVISE_LOCKNOEXPAND:
4687                                 rc = ll_lock_noexpand(file,
4688                                                k_ladvise->lla_peradvice_flags);
4689                                 GOTO(out_ladvise, rc);
4690                         case LU_LADVISE_LOCKAHEAD:
4691
4692                                 rc = ll_file_lock_ahead(file, k_ladvise);
4693
4694                                 if (rc < 0)
4695                                         GOTO(out_ladvise, rc);
4696
4697                                 if (put_user(rc,
4698                                              &u_ladvise->lla_lockahead_result))
4699                                         GOTO(out_ladvise, rc = -EFAULT);
4700                                 break;
4701                         default:
4702                                 rc = ll_ladvise(inode, file,
4703                                                 k_ladvise_hdr->lah_flags,
4704                                                 k_ladvise);
4705                                 if (rc)
4706                                         GOTO(out_ladvise, rc);
4707                                 break;
4708                         }
4709
4710                 }
4711
4712 out_ladvise:
4713                 OBD_FREE(k_ladvise_hdr, alloc_size);
4714                 RETURN(rc);
4715         }
4716         case LL_IOC_FLR_SET_MIRROR: {
4717                 /* mirror I/O must be direct to avoid polluting page cache
4718                  * by stale data. */
4719                 if (!(file->f_flags & O_DIRECT))
4720                         RETURN(-EINVAL);
4721
4722                 fd->fd_designated_mirror = arg;
4723                 RETURN(0);
4724         }
4725         case LL_IOC_HEAT_GET: {
4726                 struct lu_heat uheat;
4727                 struct lu_heat *heat;
4728                 int size;
4729
4730                 if (copy_from_user(&uheat, uarg, sizeof(uheat)))
4731                         RETURN(-EFAULT);
4732
4733                 if (uheat.lh_count > OBD_HEAT_COUNT)
4734                         uheat.lh_count = OBD_HEAT_COUNT;
4735
4736                 size = offsetof(typeof(uheat), lh_heat[uheat.lh_count]);
4737                 OBD_ALLOC(heat, size);
4738                 if (heat == NULL)
4739                         RETURN(-ENOMEM);
4740
4741                 heat->lh_count = uheat.lh_count;
4742                 ll_heat_get(inode, heat);
4743                 rc = copy_to_user(uarg, heat, size);
4744                 OBD_FREE(heat, size);
4745                 RETURN(rc ? -EFAULT : 0);
4746         }
4747         case LL_IOC_HEAT_SET: {
4748                 __u64 flags;
4749
4750                 if (copy_from_user(&flags, uarg, sizeof(flags)))
4751                         RETURN(-EFAULT);
4752
4753                 rc = ll_heat_set(inode, flags);
4754                 RETURN(rc);
4755         }
4756         case LL_IOC_PCC_ATTACH: {
4757                 struct lu_pcc_attach *attach;
4758
4759                 if (!S_ISREG(inode->i_mode))
4760                         RETURN(-EINVAL);
4761
4762                 if (!inode_owner_or_capable(&nop_mnt_idmap, inode))
4763                         RETURN(-EPERM);
4764
4765                 OBD_ALLOC_PTR(attach);
4766                 if (attach == NULL)
4767                         RETURN(-ENOMEM);
4768
4769                 if (copy_from_user(attach,
4770                                    (const struct lu_pcc_attach __user *)arg,
4771                                    sizeof(*attach)))
4772                         GOTO(out_pcc, rc = -EFAULT);
4773
4774                 rc = pcc_ioctl_attach(file, inode, attach);
4775 out_pcc:
4776                 OBD_FREE_PTR(attach);
4777                 RETURN(rc);
4778         }
4779         case LL_IOC_PCC_DETACH: {
4780                 struct lu_pcc_detach *detach;
4781
4782                 OBD_ALLOC_PTR(detach);
4783                 if (detach == NULL)
4784                         RETURN(-ENOMEM);
4785
4786                 if (copy_from_user(detach, uarg, sizeof(*detach)))
4787                         GOTO(out_detach_free, rc = -EFAULT);
4788
4789                 if (!S_ISREG(inode->i_mode))
4790                         GOTO(out_detach_free, rc = -EINVAL);
4791
4792                 if (!inode_owner_or_capable(&nop_mnt_idmap, inode))
4793                         GOTO(out_detach_free, rc = -EPERM);
4794
4795                 rc = pcc_ioctl_detach(inode, detach->pccd_opt);
4796 out_detach_free:
4797                 OBD_FREE_PTR(detach);
4798                 RETURN(rc);
4799         }
4800         case LL_IOC_PCC_STATE: {
4801                 struct lu_pcc_state __user *ustate = uarg;
4802                 struct lu_pcc_state *state;
4803
4804                 OBD_ALLOC_PTR(state);
4805                 if (state == NULL)
4806                         RETURN(-ENOMEM);
4807
4808                 if (copy_from_user(state, ustate, sizeof(*state)))
4809                         GOTO(out_state, rc = -EFAULT);
4810
4811                 rc = pcc_ioctl_state(file, inode, state);
4812                 if (rc)
4813                         GOTO(out_state, rc);
4814
4815                 if (copy_to_user(ustate, state, sizeof(*state)))
4816                         GOTO(out_state, rc = -EFAULT);
4817
4818 out_state:
4819                 OBD_FREE_PTR(state);
4820                 RETURN(rc);
4821         }
4822         default:
4823                 rc = ll_iocontrol(inode, file, cmd, uarg);
4824                 if (rc != -ENOTTY)
4825                         RETURN(rc);
4826                 RETURN(obd_iocontrol(cmd, ll_i2dtexp(inode), 0, NULL, uarg));
4827         }
4828 }
4829
4830 static loff_t ll_lseek(struct file *file, loff_t offset, int whence)
4831 {
4832         struct inode *inode = file_inode(file);
4833         struct lu_env *env;
4834         struct cl_io *io;
4835         struct cl_lseek_io *lsio;
4836         __u16 refcheck;
4837         int rc;
4838         loff_t retval;
4839
4840         ENTRY;
4841
4842         env = cl_env_get(&refcheck);
4843         if (IS_ERR(env))
4844                 RETURN(PTR_ERR(env));
4845
4846         io = vvp_env_thread_io(env);
4847         io->ci_obj = ll_i2info(inode)->lli_clob;
4848         ll_io_set_mirror(io, file);
4849
4850         lsio = &io->u.ci_lseek;
4851         lsio->ls_start = offset;
4852         lsio->ls_whence = whence;
4853         lsio->ls_result = -ENXIO;
4854
4855         do {
4856                 rc = cl_io_init(env, io, CIT_LSEEK, io->ci_obj);
4857                 if (!rc) {
4858                         struct vvp_io *vio = vvp_env_io(env);
4859
4860                         vio->vui_fd = file->private_data;
4861                         rc = cl_io_loop(env, io);
4862                 } else {
4863                         rc = io->ci_result;
4864                 }
4865                 retval = rc ? : lsio->ls_result;
4866                 cl_io_fini(env, io);
4867         } while (unlikely(io->ci_need_restart));
4868
4869         cl_env_put(env, &refcheck);
4870
4871         /* Without the key, SEEK_HOLE return value has to be
4872          * rounded up to next LUSTRE_ENCRYPTION_UNIT_SIZE.
4873          */
4874         if (llcrypt_require_key(inode) == -ENOKEY && whence == SEEK_HOLE)
4875                 retval = round_up(retval, LUSTRE_ENCRYPTION_UNIT_SIZE);
4876
4877         RETURN(retval);
4878 }
4879
4880 #define LU_SEEK_NAMES {                                 \
4881         [SEEK_SET]      = "SEEK_SET",                   \
4882         [SEEK_CUR]      = "SEEK_CUR",                   \
4883         [SEEK_DATA]     = "SEEK_DATA",                  \
4884         [SEEK_HOLE]     = "SEEK_HOLE",                  \
4885 }
4886
4887 static const char *const ll_seek_names[] = LU_SEEK_NAMES;
4888
4889 static loff_t ll_file_seek(struct file *file, loff_t offset, int origin)
4890 {
4891         struct inode *inode = file_inode(file);
4892         loff_t retval = offset, eof = 0;
4893         ktime_t kstart = ktime_get();
4894
4895         ENTRY;
4896
4897         CDEBUG(D_VFSTRACE|D_IOTRACE,
4898                "START file %s:"DFID", offset: %lld, type: %s\n",
4899                file_dentry(file)->d_name.name,
4900                PFID(ll_inode2fid(file_inode(file))), offset,
4901                ll_seek_names[origin]);
4902
4903         if (origin == SEEK_END) {
4904                 retval = ll_glimpse_size(inode);
4905                 if (retval != 0)
4906                         RETURN(retval);
4907                 eof = i_size_read(inode);
4908         }
4909
4910         if (origin == SEEK_HOLE || origin == SEEK_DATA) {
4911                 if (offset < 0)
4912                         return -ENXIO;
4913
4914                 /* flush local cache first if any */
4915                 cl_sync_file_range(inode, offset, OBD_OBJECT_EOF,
4916                                    CL_FSYNC_LOCAL, 0);
4917
4918                 retval = ll_lseek(file, offset, origin);
4919                 if (retval < 0)
4920                         return retval;
4921                 retval = vfs_setpos(file, retval, ll_file_maxbytes(inode));
4922         } else {
4923                 retval = generic_file_llseek_size(file, offset, origin,
4924                                                   ll_file_maxbytes(inode), eof);
4925         }
4926         if (retval >= 0)
4927                 ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_LLSEEK,
4928                                    ktime_us_delta(ktime_get(), kstart));
4929         CDEBUG(D_VFSTRACE|D_IOTRACE,
4930                "COMPLETED file %s:"DFID", offset: %lld, type: %s, rc = %lld\n",
4931                file_dentry(file)->d_name.name,
4932                PFID(ll_inode2fid(file_inode(file))), offset,
4933                ll_seek_names[origin], retval);
4934
4935         RETURN(retval);
4936 }
4937
4938 static int ll_flush(struct file *file, fl_owner_t id)
4939 {
4940         struct inode *inode = file_inode(file);
4941         struct ll_inode_info *lli = ll_i2info(inode);
4942         struct ll_file_data *fd = file->private_data;
4943         int rc, err;
4944
4945         LASSERT(!S_ISDIR(inode->i_mode));
4946
4947         /* catch async errors that were recorded back when async writeback
4948          * failed for pages in this mapping. */
4949         rc = lli->lli_async_rc;
4950         lli->lli_async_rc = 0;
4951         if (lli->lli_clob != NULL) {
4952                 err = lov_read_and_clear_async_rc(lli->lli_clob);
4953                 if (rc == 0)
4954                         rc = err;
4955         }
4956
4957         /* The application has been told write failure already.
4958          * Do not report failure again. */
4959         if (fd->fd_write_failed)
4960                 return 0;
4961         return rc ? -EIO : 0;
4962 }
4963
4964 /**
4965  * Called to make sure a portion of file has been written out.
4966  * if @mode is not CL_FSYNC_LOCAL, it will send OST_SYNC RPCs to OST.
4967  *
4968  * Return how many pages have been written.
4969  */
4970 int cl_sync_file_range(struct inode *inode, loff_t start, loff_t end,
4971                        enum cl_fsync_mode mode, int ignore_layout)
4972 {
4973         struct lu_env *env;
4974         struct cl_io *io;
4975         struct cl_fsync_io *fio;
4976         int result;
4977         __u16 refcheck;
4978         ENTRY;
4979
4980         if (mode != CL_FSYNC_NONE && mode != CL_FSYNC_LOCAL &&
4981             mode != CL_FSYNC_DISCARD && mode != CL_FSYNC_ALL &&
4982             mode != CL_FSYNC_RECLAIM)
4983                 RETURN(-EINVAL);
4984
4985         env = cl_env_get(&refcheck);
4986         if (IS_ERR(env))
4987                 RETURN(PTR_ERR(env));
4988
4989         io = vvp_env_thread_io(env);
4990         io->ci_obj = ll_i2info(inode)->lli_clob;
4991         cl_object_get(io->ci_obj);
4992         io->ci_ignore_layout = ignore_layout;
4993
4994         /* initialize parameters for sync */
4995         fio = &io->u.ci_fsync;
4996         fio->fi_start = start;
4997         fio->fi_end = end;
4998         fio->fi_fid = ll_inode2fid(inode);
4999         fio->fi_mode = mode;
5000         fio->fi_nr_written = 0;
5001
5002         if (cl_io_init(env, io, CIT_FSYNC, io->ci_obj) == 0)
5003                 result = cl_io_loop(env, io);
5004         else
5005                 result = io->ci_result;
5006         if (result == 0)
5007                 result = fio->fi_nr_written;
5008         cl_io_fini(env, io);
5009         cl_object_put(env, io->ci_obj);
5010         cl_env_put(env, &refcheck);
5011
5012         RETURN(result);
5013 }
5014
5015 /*
5016  * When dentry is provided (the 'else' case), file_dentry() may be
5017  * null and dentry must be used directly rather than pulled from
5018  * file_dentry() as is done otherwise.
5019  */
5020
5021 int ll_fsync(struct file *file, loff_t start, loff_t end, int datasync)
5022 {
5023         struct dentry *dentry = file_dentry(file);
5024         struct inode *inode = dentry->d_inode;
5025         struct ll_inode_info *lli = ll_i2info(inode);
5026         struct ptlrpc_request *req;
5027         ktime_t kstart = ktime_get();
5028         int rc, err;
5029
5030         ENTRY;
5031
5032         CDEBUG(D_VFSTRACE,
5033                "VFS Op:inode="DFID"(%p), start %lld, end %lld, datasync %d\n",
5034                PFID(ll_inode2fid(inode)), inode, start, end, datasync);
5035
5036         /* fsync's caller has already called _fdata{sync,write}, we want
5037          * that IO to finish before calling the osc and mdc sync methods */
5038         rc = filemap_write_and_wait_range(inode->i_mapping, start, end);
5039
5040         /* catch async errors that were recorded back when async writeback
5041          * failed for pages in this mapping. */
5042         if (!S_ISDIR(inode->i_mode)) {
5043                 err = lli->lli_async_rc;
5044                 lli->lli_async_rc = 0;
5045                 if (rc == 0)
5046                         rc = err;
5047                 if (lli->lli_clob != NULL) {
5048                         err = lov_read_and_clear_async_rc(lli->lli_clob);
5049                         if (rc == 0)
5050                                 rc = err;
5051                 }
5052         }
5053
5054         if (S_ISREG(inode->i_mode) && !lli->lli_synced_to_mds) {
5055                 /*
5056                  * only the first sync on MDS makes sense,
5057                  * everything else is stored on OSTs
5058                  */
5059                 err = md_fsync(ll_i2sbi(inode)->ll_md_exp,
5060                                ll_inode2fid(inode), &req);
5061                 if (!rc)
5062                         rc = err;
5063                 if (!err) {
5064                         lli->lli_synced_to_mds = true;
5065                         ptlrpc_req_finished(req);
5066                 }
5067         }
5068
5069         if (S_ISREG(inode->i_mode)) {
5070                 struct ll_file_data *fd = file->private_data;
5071                 bool cached;
5072
5073                 /* Sync metadata on MDT first, and then sync the cached data
5074                  * on PCC.
5075                  */
5076                 err = pcc_fsync(file, start, end, datasync, &cached);
5077                 if (!cached)
5078                         err = cl_sync_file_range(inode, start, end,
5079                                                  CL_FSYNC_ALL, 0);
5080                 if (rc == 0 && err < 0)
5081                         rc = err;
5082                 if (rc < 0)
5083                         fd->fd_write_failed = true;
5084                 else
5085                         fd->fd_write_failed = false;
5086         }
5087
5088         if (!rc)
5089                 ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_FSYNC,
5090                                    ktime_us_delta(ktime_get(), kstart));
5091         RETURN(rc);
5092 }
5093
5094 static int
5095 ll_file_flock(struct file *file, int cmd, struct file_lock *file_lock)
5096 {
5097         struct inode *inode = file_inode(file);
5098         struct ll_sb_info *sbi = ll_i2sbi(inode);
5099         struct ldlm_enqueue_info einfo = {
5100                 .ei_type        = LDLM_FLOCK,
5101                 .ei_cb_cp       = ldlm_flock_completion_ast,
5102                 .ei_cbdata      = file_lock,
5103         };
5104         struct md_op_data *op_data;
5105         struct lustre_handle lockh = { 0 };
5106         union ldlm_policy_data flock = { { 0 } };
5107         int fl_type = file_lock->fl_type;
5108         ktime_t kstart = ktime_get();
5109         __u64 flags = 0;
5110         int rc;
5111         int rc2 = 0;
5112         ENTRY;
5113
5114         CDEBUG(D_VFSTRACE, "VFS Op:inode="DFID" file_lock=%p\n",
5115                PFID(ll_inode2fid(inode)), file_lock);
5116
5117         if (file_lock->fl_flags & FL_FLOCK) {
5118                 LASSERT((cmd == F_SETLKW) || (cmd == F_SETLK));
5119                 /* flocks are whole-file locks */
5120                 flock.l_flock.end = OFFSET_MAX;
5121                 /* For flocks owner is determined by the local file desctiptor*/
5122                 flock.l_flock.owner = (unsigned long)file_lock->fl_file;
5123         } else if (file_lock->fl_flags & FL_POSIX) {
5124                 flock.l_flock.owner = (unsigned long)file_lock->fl_owner;
5125                 flock.l_flock.start = file_lock->fl_start;
5126                 flock.l_flock.end = file_lock->fl_end;
5127         } else {
5128                 RETURN(-EINVAL);
5129         }
5130         flock.l_flock.pid = file_lock->fl_pid;
5131
5132 #if defined(HAVE_LM_COMPARE_OWNER) || defined(lm_compare_owner)
5133         /* Somewhat ugly workaround for svc lockd.
5134          * lockd installs custom fl_lmops->lm_compare_owner that checks
5135          * for the fl_owner to be the same (which it always is on local node
5136          * I guess between lockd processes) and then compares pid.
5137          * As such we assign pid to the owner field to make it all work,
5138          * conflict with normal locks is unlikely since pid space and
5139          * pointer space for current->files are not intersecting */
5140         if (file_lock->fl_lmops && file_lock->fl_lmops->lm_compare_owner)
5141                 flock.l_flock.owner = (unsigned long)file_lock->fl_pid;
5142 #endif
5143
5144         switch (fl_type) {
5145         case F_RDLCK:
5146                 einfo.ei_mode = LCK_PR;
5147                 break;
5148         case F_UNLCK:
5149                 /* An unlock request may or may not have any relation to
5150                  * existing locks so we may not be able to pass a lock handle
5151                  * via a normal ldlm_lock_cancel() request. The request may even
5152                  * unlock a byte range in the middle of an existing lock. In
5153                  * order to process an unlock request we need all of the same
5154                  * information that is given with a normal read or write record
5155                  * lock request. To avoid creating another ldlm unlock (cancel)
5156                  * message we'll treat a LCK_NL flock request as an unlock. */
5157                 einfo.ei_mode = LCK_NL;
5158                 break;
5159         case F_WRLCK:
5160                 einfo.ei_mode = LCK_PW;
5161                 break;
5162         default:
5163                 rc = -EINVAL;
5164                 CERROR("%s: fcntl from '%s' unknown lock type=%d: rc = %d\n",
5165                        sbi->ll_fsname, current->comm, fl_type, rc);
5166                 RETURN(rc);
5167         }
5168
5169         switch (cmd) {
5170         case F_SETLKW:
5171 #ifdef F_SETLKW64
5172         case F_SETLKW64:
5173 #endif
5174                 flags = 0;
5175                 break;
5176         case F_SETLK:
5177 #ifdef F_SETLK64
5178         case F_SETLK64:
5179 #endif
5180                 flags = LDLM_FL_BLOCK_NOWAIT;
5181                 break;
5182         case F_GETLK:
5183 #ifdef F_GETLK64
5184         case F_GETLK64:
5185 #endif
5186                 flags = LDLM_FL_TEST_LOCK;
5187                 break;
5188         default:
5189                 rc = -EINVAL;
5190                 CERROR("%s: fcntl from '%s' unknown lock command=%d: rc = %d\n",
5191                        sbi->ll_fsname, current->comm, cmd, rc);
5192                 RETURN(rc);
5193         }
5194
5195         /* Save the old mode so that if the mode in the lock changes we
5196          * can decrement the appropriate reader or writer refcount. */
5197         file_lock->fl_type = einfo.ei_mode;
5198
5199         op_data = ll_prep_md_op_data(NULL, inode, NULL, NULL, 0, 0,
5200                                      LUSTRE_OPC_ANY, NULL);
5201         if (IS_ERR(op_data))
5202                 RETURN(PTR_ERR(op_data));
5203
5204         CDEBUG(D_DLMTRACE, "inode="DFID", pid=%u, flags=%#llx, mode=%u, "
5205                "start=%llu, end=%llu\n", PFID(ll_inode2fid(inode)),
5206                flock.l_flock.pid, flags, einfo.ei_mode,
5207                flock.l_flock.start, flock.l_flock.end);
5208
5209         rc = md_enqueue(sbi->ll_md_exp, &einfo, &flock, op_data, &lockh,
5210                         flags);
5211
5212         /* Restore the file lock type if not TEST lock. */
5213         if (!(flags & LDLM_FL_TEST_LOCK))
5214                 file_lock->fl_type = fl_type;
5215
5216 #ifdef HAVE_LOCKS_LOCK_FILE_WAIT
5217         if ((rc == 0 || file_lock->fl_type == F_UNLCK) &&
5218             !(flags & LDLM_FL_TEST_LOCK))
5219                 rc2  = locks_lock_file_wait(file, file_lock);
5220 #else
5221         if ((file_lock->fl_flags & FL_FLOCK) &&
5222             (rc == 0 || file_lock->fl_type == F_UNLCK))
5223                 rc2  = flock_lock_file_wait(file, file_lock);
5224         if ((file_lock->fl_flags & FL_POSIX) &&
5225             (rc == 0 || file_lock->fl_type == F_UNLCK) &&
5226             !(flags & LDLM_FL_TEST_LOCK))
5227                 rc2  = posix_lock_file_wait(file, file_lock);
5228 #endif /* HAVE_LOCKS_LOCK_FILE_WAIT */
5229
5230         if (rc2 && file_lock->fl_type != F_UNLCK) {
5231                 einfo.ei_mode = LCK_NL;
5232                 md_enqueue(sbi->ll_md_exp, &einfo, &flock, op_data,
5233                            &lockh, flags);
5234                 rc = rc2;
5235         }
5236
5237         ll_finish_md_op_data(op_data);
5238
5239         if (!rc)
5240                 ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_FLOCK,
5241                                    ktime_us_delta(ktime_get(), kstart));
5242         RETURN(rc);
5243 }
5244
5245 int ll_get_fid_by_name(struct inode *parent, const char *name,
5246                        int namelen, struct lu_fid *fid,
5247                        struct inode **inode)
5248 {
5249         struct md_op_data *op_data = NULL;
5250         struct mdt_body *body;
5251         struct ptlrpc_request *req;
5252         int rc;
5253         ENTRY;
5254
5255         op_data = ll_prep_md_op_data(NULL, parent, NULL, name, namelen, 0,
5256                                      LUSTRE_OPC_ANY, NULL);
5257         if (IS_ERR(op_data))
5258                 RETURN(PTR_ERR(op_data));
5259
5260         op_data->op_valid = OBD_MD_FLID | OBD_MD_FLTYPE;
5261         rc = md_getattr_name(ll_i2sbi(parent)->ll_md_exp, op_data, &req);
5262         ll_finish_md_op_data(op_data);
5263         if (rc < 0)
5264                 RETURN(rc);
5265
5266         body = req_capsule_server_get(&req->rq_pill, &RMF_MDT_BODY);
5267         if (body == NULL)
5268                 GOTO(out_req, rc = -EFAULT);
5269         if (fid != NULL)
5270                 *fid = body->mbo_fid1;
5271
5272         if (inode != NULL)
5273                 rc = ll_prep_inode(inode, &req->rq_pill, parent->i_sb, NULL);
5274 out_req:
5275         ptlrpc_req_finished(req);
5276         RETURN(rc);
5277 }
5278
5279 int ll_migrate(struct inode *parent, struct file *file, struct lmv_user_md *lum,
5280                const char *name, __u32 flags)
5281 {
5282         struct dentry *dchild = NULL;
5283         struct inode *child_inode = NULL;
5284         struct md_op_data *op_data;
5285         struct ptlrpc_request *request = NULL;
5286         struct obd_client_handle *och = NULL;
5287         struct qstr qstr;
5288         struct mdt_body *body;
5289         __u64 data_version = 0;
5290         size_t namelen = strlen(name);
5291         int lumlen = lmv_user_md_size(lum->lum_stripe_count, lum->lum_magic);
5292         bool locked = false;
5293         int rc;
5294         ENTRY;
5295
5296         CDEBUG(D_VFSTRACE, "migrate "DFID"/%s to MDT%04x stripe count %d\n",
5297                PFID(ll_inode2fid(parent)), name,
5298                lum->lum_stripe_offset, lum->lum_stripe_count);
5299
5300         if (lum->lum_magic != cpu_to_le32(LMV_USER_MAGIC) &&
5301             lum->lum_magic != cpu_to_le32(LMV_USER_MAGIC_SPECIFIC))
5302                 lustre_swab_lmv_user_md(lum);
5303
5304         /* Get child FID first */
5305         qstr.hash = ll_full_name_hash(file_dentry(file), name, namelen);
5306         qstr.name = name;
5307         qstr.len = namelen;
5308         dchild = d_lookup(file_dentry(file), &qstr);
5309         if (dchild) {
5310                 if (dchild->d_inode)
5311                         child_inode = igrab(dchild->d_inode);
5312                 dput(dchild);
5313         }
5314
5315         if (!child_inode) {
5316                 rc = ll_get_fid_by_name(parent, name, namelen, NULL,
5317                                         &child_inode);
5318                 if (rc)
5319                         RETURN(rc);
5320         }
5321
5322         if (!child_inode)
5323                 RETURN(-ENOENT);
5324
5325         if (!(exp_connect_flags2(ll_i2sbi(parent)->ll_md_exp) &
5326               OBD_CONNECT2_DIR_MIGRATE)) {
5327                 if (le32_to_cpu(lum->lum_stripe_count) > 1 ||
5328                     ll_dir_striped(child_inode)) {
5329                         CERROR("%s: MDT doesn't support stripe directory "
5330                                "migration!\n", ll_i2sbi(parent)->ll_fsname);
5331                         GOTO(out_iput, rc = -EOPNOTSUPP);
5332                 }
5333         }
5334
5335         /*
5336          * lfs migrate command needs to be blocked on the client
5337          * by checking the migrate FID against the FID of the
5338          * filesystem root.
5339          */
5340         if (is_root_inode(child_inode))
5341                 GOTO(out_iput, rc = -EINVAL);
5342
5343         op_data = ll_prep_md_op_data(NULL, parent, NULL, name, namelen,
5344                                      child_inode->i_mode, LUSTRE_OPC_ANY, NULL);
5345         if (IS_ERR(op_data))
5346                 GOTO(out_iput, rc = PTR_ERR(op_data));
5347
5348         op_data->op_fid3 = *ll_inode2fid(child_inode);
5349         if (!fid_is_sane(&op_data->op_fid3)) {
5350                 CERROR("%s: migrate %s, but FID "DFID" is insane\n",
5351                        ll_i2sbi(parent)->ll_fsname, name,
5352                        PFID(&op_data->op_fid3));
5353                 GOTO(out_data, rc = -EINVAL);
5354         }
5355
5356         op_data->op_cli_flags |= CLI_MIGRATE | CLI_SET_MEA;
5357         op_data->op_data = lum;
5358         op_data->op_data_size = lumlen;
5359
5360         /* migrate dirent only for subdirs if MDS_MIGRATE_NSONLY set */
5361         if (S_ISDIR(child_inode->i_mode) && (flags & MDS_MIGRATE_NSONLY) &&
5362             lmv_dir_layout_changing(op_data->op_lso1))
5363                 op_data->op_bias |= MDS_MIGRATE_NSONLY;
5364
5365 again:
5366         if (S_ISREG(child_inode->i_mode)) {
5367                 och = ll_lease_open(child_inode, NULL, FMODE_WRITE, 0);
5368                 if (IS_ERR(och)) {
5369                         rc = PTR_ERR(och);
5370                         och = NULL;
5371                         GOTO(out_data, rc);
5372                 }
5373
5374                 rc = ll_data_version(child_inode, &data_version,
5375                                      LL_DV_WR_FLUSH);
5376                 if (rc != 0)
5377                         GOTO(out_close, rc);
5378
5379                 op_data->op_open_handle = och->och_open_handle;
5380                 op_data->op_data_version = data_version;
5381                 op_data->op_lease_handle = och->och_lease_handle;
5382                 op_data->op_bias |= MDS_CLOSE_MIGRATE;
5383
5384                 spin_lock(&och->och_mod->mod_open_req->rq_lock);
5385                 och->och_mod->mod_open_req->rq_replay = 0;
5386                 spin_unlock(&och->och_mod->mod_open_req->rq_lock);
5387         }
5388         LASSERT(locked == false);
5389         ll_inode_lock(child_inode);
5390         locked = true;
5391
5392         rc = md_rename(ll_i2sbi(parent)->ll_md_exp, op_data,
5393                        op_data->op_name, op_data->op_namelen,
5394                        op_data->op_name, op_data->op_namelen, &request);
5395         if (rc == 0) {
5396                 LASSERT(request != NULL);
5397                 ll_update_times(request, parent);
5398         }
5399
5400         if (rc == 0 || rc == -EAGAIN) {
5401                 body = req_capsule_server_get(&request->rq_pill, &RMF_MDT_BODY);
5402                 LASSERT(body != NULL);
5403
5404                 /* If the server does release layout lock, then we cleanup
5405                  * the client och here, otherwise release it in out_close: */
5406                 if (och && body->mbo_valid & OBD_MD_CLOSE_INTENT_EXECED) {
5407                         obd_mod_put(och->och_mod);
5408                         md_clear_open_replay_data(ll_i2sbi(parent)->ll_md_exp,
5409                                                   och);
5410                         och->och_open_handle.cookie = DEAD_HANDLE_MAGIC;
5411                         OBD_FREE_PTR(och);
5412                         och = NULL;
5413                 }
5414         }
5415
5416         if (request != NULL) {
5417                 ptlrpc_req_finished(request);
5418                 request = NULL;
5419         }
5420
5421         /* Try again if the lease has cancelled. */
5422         if (rc == -EAGAIN && S_ISREG(child_inode->i_mode)) {
5423                 LASSERT(locked == true);
5424                 ll_inode_unlock(child_inode);
5425                 locked = false;
5426                 goto again;
5427         }
5428
5429 out_close:
5430         if (och)
5431                 ll_lease_close(och, child_inode, NULL);
5432         if (!rc)
5433                 clear_nlink(child_inode);
5434 out_data:
5435         ll_finish_md_op_data(op_data);
5436 out_iput:
5437         if (locked)
5438                 ll_inode_unlock(child_inode);
5439         iput(child_inode);
5440         RETURN(rc);
5441 }
5442
5443 static int
5444 ll_file_noflock(struct file *file, int cmd, struct file_lock *file_lock)
5445 {
5446         struct ll_file_data *fd = file->private_data;
5447         ENTRY;
5448
5449         /*
5450          * In order to avoid flood of warning messages, only print one message
5451          * for one file. And the entire message rate on the client is limited
5452          * by CDEBUG_LIMIT too.
5453          */
5454         if (!(fd->fd_flags & LL_FILE_FLOCK_WARNING)) {
5455                 fd->fd_flags |= LL_FILE_FLOCK_WARNING;
5456                 CDEBUG_LIMIT(D_CONSOLE,
5457                              "flock disabled, mount with '-o [local]flock' to enable\r\n");
5458         }
5459         RETURN(-ENOSYS);
5460 }
5461
5462 /**
5463  * test if some locks matching bits and l_req_mode are acquired
5464  * - bits can be in different locks
5465  * - if found clear the common lock bits in *bits
5466  * - the bits not found, are kept in *bits
5467  * \param inode [IN]
5468  * \param bits [IN] searched lock bits [IN]
5469  * \param l_req_mode [IN] searched lock mode
5470  * \retval boolean, true iff all bits are found
5471  */
5472 int ll_have_md_lock(struct obd_export *exp, struct inode *inode, __u64 *bits,
5473                     enum ldlm_mode l_req_mode)
5474 {
5475         struct lustre_handle lockh;
5476         union ldlm_policy_data policy;
5477         enum ldlm_mode mode = (l_req_mode == LCK_MINMODE) ?
5478                               (LCK_CR | LCK_CW | LCK_PR | LCK_PW) : l_req_mode;
5479         struct lu_fid *fid;
5480         __u64 flags;
5481         int i;
5482         ENTRY;
5483
5484         if (!inode)
5485                RETURN(0);
5486
5487         fid = &ll_i2info(inode)->lli_fid;
5488         CDEBUG(D_INFO, "trying to match res "DFID" mode %s\n", PFID(fid),
5489                ldlm_lockname[mode]);
5490
5491         flags = LDLM_FL_BLOCK_GRANTED | LDLM_FL_CBPENDING | LDLM_FL_TEST_LOCK;
5492         for (i = 0; i < MDS_INODELOCK_NUMBITS && *bits != 0; i++) {
5493                 policy.l_inodebits.bits = *bits & BIT(i);
5494                 if (policy.l_inodebits.bits == 0)
5495                         continue;
5496
5497                 if (md_lock_match(exp, flags, fid, LDLM_IBITS, &policy, mode,
5498                                   &lockh)) {
5499                         struct ldlm_lock *lock;
5500
5501                         lock = ldlm_handle2lock(&lockh);
5502                         if (lock) {
5503                                 *bits &=
5504                                         ~(lock->l_policy_data.l_inodebits.bits);
5505                                 LDLM_LOCK_PUT(lock);
5506                         } else {
5507                                 *bits &= ~policy.l_inodebits.bits;
5508                         }
5509                 }
5510         }
5511         RETURN(*bits == 0);
5512 }
5513
5514 enum ldlm_mode ll_take_md_lock(struct inode *inode, __u64 bits,
5515                                struct lustre_handle *lockh, __u64 flags,
5516                                enum ldlm_mode mode)
5517 {
5518         union ldlm_policy_data policy = { .l_inodebits = { bits } };
5519         struct lu_fid *fid;
5520         enum ldlm_mode rc;
5521         ENTRY;
5522
5523         fid = &ll_i2info(inode)->lli_fid;
5524         CDEBUG(D_INFO, "trying to match res "DFID"\n", PFID(fid));
5525
5526         rc = md_lock_match(ll_i2mdexp(inode), LDLM_FL_BLOCK_GRANTED|flags,
5527                            fid, LDLM_IBITS, &policy, mode, lockh);
5528
5529         RETURN(rc);
5530 }
5531
5532 static int ll_inode_revalidate_fini(struct inode *inode, int rc)
5533 {
5534         /* Already unlinked. Just update nlink and return success */
5535         if (rc == -ENOENT) {
5536                 clear_nlink(inode);
5537                 /* If it is striped directory, and there is bad stripe
5538                  * Let's revalidate the dentry again, instead of returning
5539                  * error */
5540                 if (ll_dir_striped(inode))
5541                         return 0;
5542
5543                 /* This path cannot be hit for regular files unless in
5544                  * case of obscure races, so no need to to validate
5545                  * size. */
5546                 if (!S_ISREG(inode->i_mode) && !S_ISDIR(inode->i_mode))
5547                         return 0;
5548         } else if (rc != 0) {
5549                 CDEBUG_LIMIT((rc == -EACCES || rc == -EIDRM) ? D_INFO : D_ERROR,
5550                              "%s: revalidate FID "DFID" error: rc = %d\n",
5551                              ll_i2sbi(inode)->ll_fsname,
5552                              PFID(ll_inode2fid(inode)), rc);
5553         }
5554
5555         return rc;
5556 }
5557
5558 static int ll_inode_revalidate(struct dentry *dentry, enum ldlm_intent_flags op)
5559 {
5560         struct dentry *parent = NULL;
5561         struct inode *dir;
5562         struct inode *inode = dentry->d_inode;
5563         struct obd_export *exp = ll_i2mdexp(inode);
5564         struct lookup_intent oit = {
5565                 .it_op = op,
5566         };
5567         struct ptlrpc_request *req = NULL;
5568         struct md_op_data *op_data;
5569         const char *name = NULL;
5570         size_t namelen = 0;
5571         int rc = 0;
5572         ENTRY;
5573
5574         CDEBUG(D_VFSTRACE, "VFS Op:inode="DFID"(%p),name=%s\n",
5575                PFID(ll_inode2fid(inode)), inode, dentry->d_name.name);
5576
5577         if (exp_connect_flags2(exp) & OBD_CONNECT2_GETATTR_PFID) {
5578                 parent = dget_parent(dentry);
5579                 dir = d_inode(parent);
5580                 name = dentry->d_name.name;
5581                 namelen = dentry->d_name.len;
5582         } else {
5583                 dir = inode;
5584         }
5585
5586         op_data = ll_prep_md_op_data(NULL, dir, inode, name, namelen, 0,
5587                                      LUSTRE_OPC_ANY, NULL);
5588         if (parent)
5589                 dput(parent);
5590         if (IS_ERR(op_data))
5591                 RETURN(PTR_ERR(op_data));
5592
5593         /* Call getattr by fid */
5594         if (exp_connect_flags2(exp) & OBD_CONNECT2_GETATTR_PFID)
5595                 op_data->op_flags = MF_GETATTR_BY_FID;
5596         rc = md_intent_lock(exp, op_data, &oit, &req, &ll_md_blocking_ast, 0);
5597         ll_finish_md_op_data(op_data);
5598         if (rc < 0) {
5599                 rc = ll_inode_revalidate_fini(inode, rc);
5600                 GOTO(out, rc);
5601         }
5602
5603         rc = ll_revalidate_it_finish(req, &oit, dentry);
5604         if (rc != 0) {
5605                 ll_intent_release(&oit);
5606                 GOTO(out, rc);
5607         }
5608
5609         /* Unlinked? Unhash dentry, so it is not picked up later by
5610          * do_lookup() -> ll_revalidate_it(). We cannot use d_drop
5611          * here to preserve get_cwd functionality on 2.6.
5612          * Bug 10503 */
5613         if (!dentry->d_inode->i_nlink)
5614                 d_lustre_invalidate(dentry);
5615
5616         ll_lookup_finish_locks(&oit, dentry);
5617 out:
5618         ptlrpc_req_finished(req);
5619
5620         return rc;
5621 }
5622
5623 static int ll_merge_md_attr(struct inode *inode)
5624 {
5625         struct ll_inode_info *lli = ll_i2info(inode);
5626         struct lmv_stripe_object *lsm_obj;
5627         struct cl_attr attr = { 0 };
5628         int rc;
5629
5630         if (!ll_dir_striped(inode))
5631                 RETURN(0);
5632
5633         down_read(&lli->lli_lsm_sem);
5634         if (!ll_dir_striped_locked(inode)) {
5635                 up_read(&lli->lli_lsm_sem);
5636                 RETURN(0);
5637         }
5638         LASSERT(lli->lli_lsm_obj != NULL);
5639
5640         lsm_obj = lmv_stripe_object_get(lli->lli_lsm_obj);
5641         up_read(&lli->lli_lsm_sem);
5642
5643         rc = md_merge_attr(ll_i2mdexp(inode), lsm_obj,
5644                            &attr, ll_md_blocking_ast);
5645         lmv_stripe_object_put(&lsm_obj);
5646         if (rc != 0)
5647                 RETURN(rc);
5648
5649         spin_lock(&inode->i_lock);
5650         set_nlink(inode, attr.cat_nlink);
5651         spin_unlock(&inode->i_lock);
5652
5653         inode->i_blocks = attr.cat_blocks;
5654         i_size_write(inode, attr.cat_size);
5655
5656         ll_i2info(inode)->lli_atime = attr.cat_atime;
5657         ll_i2info(inode)->lli_mtime = attr.cat_mtime;
5658         ll_i2info(inode)->lli_ctime = attr.cat_ctime;
5659
5660         RETURN(0);
5661 }
5662
5663 int ll_getattr_dentry(struct dentry *de, struct kstat *stat, u32 request_mask,
5664                       unsigned int flags, bool foreign)
5665 {
5666         struct inode *inode = de->d_inode;
5667         struct ll_sb_info *sbi = ll_i2sbi(inode);
5668         struct ll_inode_info *lli = ll_i2info(inode);
5669         struct dentry *parent;
5670         struct inode *dir;
5671         bool need_glimpse = true;
5672         ktime_t kstart = ktime_get();
5673         int rc;
5674
5675         CDEBUG(D_VFSTRACE|D_IOTRACE,
5676                "START file %s:"DFID"(%p), request_mask %d, flags %u, foreign %d\n",
5677                de->d_name.name, PFID(ll_inode2fid(inode)), inode,
5678                request_mask, flags, foreign);
5679
5680         /* The OST object(s) determine the file size, blocks and mtime. */
5681         if (!(request_mask & STATX_SIZE || request_mask & STATX_BLOCKS ||
5682               request_mask & STATX_MTIME))
5683                 need_glimpse = false;
5684
5685         parent = dget_parent(de);
5686         dir = d_inode(parent);
5687         ll_statahead_enter(dir, de);
5688         if (dentry_may_statahead(dir, de))
5689                 ll_start_statahead(dir, de, need_glimpse &&
5690                                    !(flags & AT_STATX_DONT_SYNC));
5691         dput(parent);
5692
5693         if (flags & AT_STATX_DONT_SYNC)
5694                 GOTO(fill_attr, rc = 0);
5695
5696         rc = ll_inode_revalidate(de, IT_GETATTR);
5697         if (rc < 0)
5698                 RETURN(rc);
5699
5700         /* foreign file/dir are always of zero length, so don't
5701          * need to validate size.
5702          */
5703         if (S_ISREG(inode->i_mode) && !foreign) {
5704                 bool cached;
5705
5706                 if (!need_glimpse)
5707                         GOTO(fill_attr, rc);
5708
5709                 rc = pcc_inode_getattr(inode, request_mask, flags, &cached);
5710                 if (cached && rc < 0)
5711                         RETURN(rc);
5712
5713                 if (cached)
5714                         GOTO(fill_attr, rc);
5715
5716                 /*
5717                  * If the returned attr is masked with OBD_MD_FLSIZE &
5718                  * OBD_MD_FLBLOCKS & OBD_MD_FLMTIME, it means that the file size
5719                  * or blocks obtained from MDT is strictly correct, and the file
5720                  * is usually not being modified by clients, and the [a|m|c]time
5721                  * got from MDT is also strictly correct.
5722                  * Under this circumstance, it does not need to send glimpse
5723                  * RPCs to OSTs for file attributes such as the size and blocks.
5724                  */
5725                 if (lli->lli_attr_valid & OBD_MD_FLSIZE &&
5726                     lli->lli_attr_valid & OBD_MD_FLBLOCKS &&
5727                     lli->lli_attr_valid & OBD_MD_FLMTIME) {
5728                         inode_set_mtime(inode, lli->lli_mtime, 0);
5729                         if (lli->lli_attr_valid & OBD_MD_FLATIME)
5730                                 inode_set_atime(inode, lli->lli_atime, 0);
5731                         if (lli->lli_attr_valid & OBD_MD_FLCTIME)
5732                                 inode_set_ctime(inode, lli->lli_ctime, 0);
5733                         GOTO(fill_attr, rc);
5734                 }
5735
5736                 /* In case of restore, the MDT has the right size and has
5737                  * already send it back without granting the layout lock,
5738                  * inode is up-to-date so glimpse is useless.
5739                  * Also to glimpse we need the layout, in case of a running
5740                  * restore the MDT holds the layout lock so the glimpse will
5741                  * block up to the end of restore (getattr will block)
5742                  */
5743                 if (!test_bit(LLIF_FILE_RESTORING, &lli->lli_flags)) {
5744                         rc = ll_glimpse_size(inode);
5745                         if (rc < 0)
5746                                 RETURN(rc);
5747                 }
5748         } else {
5749                 /* If object isn't regular a file then don't validate size. */
5750                 /* foreign dir is not striped dir */
5751                 if (!foreign) {
5752                         rc = ll_merge_md_attr(inode);
5753                         if (rc < 0)
5754                                 RETURN(rc);
5755                 }
5756
5757                 if (lli->lli_attr_valid & OBD_MD_FLATIME)
5758                         inode_set_atime(inode, lli->lli_atime, 0);
5759                 if (lli->lli_attr_valid & OBD_MD_FLMTIME)
5760                         inode_set_mtime(inode, lli->lli_mtime, 0);
5761                 if (lli->lli_attr_valid & OBD_MD_FLCTIME)
5762                         inode_set_ctime(inode, lli->lli_ctime, 0);
5763         }
5764
5765 fill_attr:
5766         CFS_FAIL_TIMEOUT(OBD_FAIL_GETATTR_DELAY, 30);
5767
5768         if (ll_need_32bit_api(sbi)) {
5769                 stat->ino = cl_fid_build_ino(&lli->lli_fid, 1);
5770                 stat->dev = ll_compat_encode_dev(inode->i_sb->s_dev);
5771                 stat->rdev = ll_compat_encode_dev(inode->i_rdev);
5772         } else {
5773                 stat->ino = inode->i_ino;
5774                 stat->dev = inode->i_sb->s_dev;
5775                 stat->rdev = inode->i_rdev;
5776         }
5777
5778         /* foreign symlink to be exposed as a real symlink */
5779         if (!foreign)
5780                 stat->mode = inode->i_mode;
5781         else
5782                 stat->mode = (inode->i_mode & ~S_IFMT) | S_IFLNK;
5783
5784         stat->uid = inode->i_uid;
5785         stat->gid = inode->i_gid;
5786         stat->atime = inode_get_atime(inode);
5787         stat->mtime = inode_get_mtime(inode);
5788         stat->ctime = inode_get_ctime(inode);
5789         /* stat->blksize is used to tell about preferred IO size */
5790         if (sbi->ll_stat_blksize)
5791                 stat->blksize = sbi->ll_stat_blksize;
5792         else if (S_ISREG(inode->i_mode))
5793                 stat->blksize = min(PTLRPC_MAX_BRW_SIZE,
5794                                     1U << LL_MAX_BLKSIZE_BITS);
5795         else if (S_ISDIR(inode->i_mode))
5796                 stat->blksize = min(MD_MAX_BRW_SIZE,
5797                                     1U << LL_MAX_BLKSIZE_BITS);
5798         else
5799                 stat->blksize = 1 << inode->i_sb->s_blocksize_bits;
5800
5801         stat->nlink = inode->i_nlink;
5802         stat->size = i_size_read(inode);
5803         stat->blocks = inode->i_blocks;
5804
5805 #if defined(HAVE_USER_NAMESPACE_ARG) || defined(HAVE_INODEOPS_ENHANCED_GETATTR)
5806         if (flags & AT_STATX_DONT_SYNC) {
5807                 if (stat->size == 0 &&
5808                     lli->lli_attr_valid & OBD_MD_FLLAZYSIZE)
5809                         stat->size = lli->lli_lazysize;
5810                 if (stat->blocks == 0 &&
5811                     lli->lli_attr_valid & OBD_MD_FLLAZYBLOCKS)
5812                         stat->blocks = lli->lli_lazyblocks;
5813         }
5814
5815         if (lli->lli_attr_valid & OBD_MD_FLBTIME) {
5816                 stat->result_mask |= STATX_BTIME;
5817                 stat->btime.tv_sec = lli->lli_btime;
5818         }
5819
5820         stat->attributes_mask = STATX_ATTR_IMMUTABLE | STATX_ATTR_APPEND;
5821 #ifdef HAVE_LUSTRE_CRYPTO
5822         stat->attributes_mask |= STATX_ATTR_ENCRYPTED;
5823 #endif
5824         stat->attributes |= ll_inode_to_ext_flags(inode->i_flags);
5825         /* if Lustre specific LUSTRE_ENCRYPT_FL flag is set, also set
5826          * ext4 equivalent to please statx
5827          */
5828         if (stat->attributes & LUSTRE_ENCRYPT_FL)
5829                 stat->attributes |= STATX_ATTR_ENCRYPTED;
5830         stat->result_mask &= request_mask;
5831 #endif
5832
5833         ll_stats_ops_tally(sbi, LPROC_LL_GETATTR,
5834                            ktime_us_delta(ktime_get(), kstart));
5835
5836         CDEBUG(D_IOTRACE,
5837                "COMPLETED file %s:"DFID"(%p), request_mask %d, flags %u, foreign %d\n",
5838                de->d_name.name, PFID(ll_inode2fid(inode)), inode,
5839                request_mask, flags, foreign);
5840
5841         return 0;
5842 }
5843
5844 #if defined(HAVE_USER_NAMESPACE_ARG) || defined(HAVE_INODEOPS_ENHANCED_GETATTR)
5845 int ll_getattr(struct mnt_idmap *map, const struct path *path,
5846                struct kstat *stat, u32 request_mask, unsigned int flags)
5847 {
5848         return ll_getattr_dentry(path->dentry, stat, request_mask, flags,
5849                                  false);
5850 }
5851 #else
5852 int ll_getattr(struct vfsmount *mnt, struct dentry *de, struct kstat *stat)
5853 {
5854         return ll_getattr_dentry(de, stat, STATX_BASIC_STATS,
5855                                  AT_STATX_SYNC_AS_STAT, false);
5856 }
5857 #endif
5858
5859 static int cl_falloc(struct file *file, struct inode *inode, int mode,
5860                      loff_t offset, loff_t len)
5861 {
5862         loff_t size = i_size_read(inode);
5863         struct lu_env *env;
5864         struct cl_io *io;
5865         __u16 refcheck;
5866         int rc;
5867
5868         ENTRY;
5869
5870         env = cl_env_get(&refcheck);
5871         if (IS_ERR(env))
5872                 RETURN(PTR_ERR(env));
5873
5874         io = vvp_env_thread_io(env);
5875         io->ci_obj = ll_i2info(inode)->lli_clob;
5876         ll_io_set_mirror(io, file);
5877
5878         io->ci_verify_layout = 1;
5879         io->u.ci_setattr.sa_parent_fid = lu_object_fid(&io->ci_obj->co_lu);
5880         io->u.ci_setattr.sa_falloc_mode = mode;
5881         io->u.ci_setattr.sa_falloc_offset = offset;
5882         io->u.ci_setattr.sa_falloc_end = offset + len;
5883         io->u.ci_setattr.sa_subtype = CL_SETATTR_FALLOCATE;
5884
5885         CDEBUG(D_INODE, "UID %u GID %u PRJID %u\n",
5886                from_kuid(&init_user_ns, inode->i_uid),
5887                from_kgid(&init_user_ns, inode->i_gid),
5888                ll_i2info(inode)->lli_projid);
5889
5890         io->u.ci_setattr.sa_falloc_uid = from_kuid(&init_user_ns, inode->i_uid);
5891         io->u.ci_setattr.sa_falloc_gid = from_kgid(&init_user_ns, inode->i_gid);
5892         io->u.ci_setattr.sa_falloc_projid = ll_i2info(inode)->lli_projid;
5893
5894         if (io->u.ci_setattr.sa_falloc_end > size) {
5895                 loff_t newsize = io->u.ci_setattr.sa_falloc_end;
5896
5897                 /* Check new size against VFS/VM file size limit and rlimit */
5898                 rc = inode_newsize_ok(inode, newsize);
5899                 if (rc)
5900                         goto out;
5901                 if (newsize > ll_file_maxbytes(inode)) {
5902                         CDEBUG(D_INODE, "file size too large %llu > %llu\n",
5903                                (unsigned long long)newsize,
5904                                ll_file_maxbytes(inode));
5905                         rc = -EFBIG;
5906                         goto out;
5907                 }
5908         }
5909
5910         do {
5911                 rc = cl_io_init(env, io, CIT_SETATTR, io->ci_obj);
5912                 if (!rc)
5913                         rc = cl_io_loop(env, io);
5914                 else
5915                         rc = io->ci_result;
5916                 cl_io_fini(env, io);
5917         } while (unlikely(io->ci_need_restart));
5918
5919 out:
5920         cl_env_put(env, &refcheck);
5921         RETURN(rc);
5922 }
5923
5924 static long ll_fallocate(struct file *filp, int mode, loff_t offset, loff_t len)
5925 {
5926         struct inode *inode = file_inode(filp);
5927         int rc;
5928
5929         if (offset < 0 || len <= 0)
5930                 RETURN(-EINVAL);
5931         /*
5932          * Encrypted inodes can't handle collapse range or zero range or insert
5933          * range since we would need to re-encrypt blocks with a different IV or
5934          * XTS tweak (which are based on the logical block number).
5935          * Similar to what ext4 does.
5936          */
5937         if (IS_ENCRYPTED(inode) &&
5938             (mode & (FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_INSERT_RANGE |
5939                      FALLOC_FL_ZERO_RANGE)))
5940                 RETURN(-EOPNOTSUPP);
5941
5942         /*
5943          * mode == 0 (which is standard prealloc) and PUNCH is supported
5944          * Rest of mode options are not supported yet.
5945          */
5946         if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE))
5947                 RETURN(-EOPNOTSUPP);
5948
5949         ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_FALLOCATE, 1);
5950
5951         rc = cl_falloc(filp, inode, mode, offset, len);
5952         /*
5953          * ENOTSUPP (524) is an NFSv3 specific error code erroneously
5954          * used by Lustre in several places. Retuning it here would
5955          * confuse applications that explicity test for EOPNOTSUPP
5956          * (95) and fall back to ftruncate().
5957          */
5958         if (rc == -ENOTSUPP)
5959                 rc = -EOPNOTSUPP;
5960
5961         RETURN(rc);
5962 }
5963
5964 static int ll_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
5965                      __u64 start, __u64 len)
5966 {
5967         int             rc;
5968         size_t          num_bytes;
5969         struct fiemap   *fiemap;
5970         unsigned int    extent_count = fieinfo->fi_extents_max;
5971
5972         num_bytes = sizeof(*fiemap) + (extent_count *
5973                                        sizeof(struct fiemap_extent));
5974         OBD_ALLOC_LARGE(fiemap, num_bytes);
5975
5976         if (fiemap == NULL)
5977                 RETURN(-ENOMEM);
5978
5979         fiemap->fm_flags = fieinfo->fi_flags;
5980         fiemap->fm_extent_count = fieinfo->fi_extents_max;
5981         fiemap->fm_start = start;
5982         fiemap->fm_length = len;
5983         if (extent_count > 0 &&
5984             copy_from_user(&fiemap->fm_extents[0], fieinfo->fi_extents_start,
5985                            sizeof(struct fiemap_extent)) != 0)
5986                 GOTO(out, rc = -EFAULT);
5987
5988         rc = ll_do_fiemap(inode, fiemap, num_bytes);
5989
5990         if (IS_ENCRYPTED(inode) && extent_count > 0) {
5991                 int i;
5992
5993                 for (i = 0; i < fiemap->fm_mapped_extents; i++)
5994                         fiemap->fm_extents[i].fe_flags |=
5995                                 FIEMAP_EXTENT_DATA_ENCRYPTED |
5996                                 FIEMAP_EXTENT_ENCODED;
5997         }
5998
5999         fieinfo->fi_flags = fiemap->fm_flags;
6000         fieinfo->fi_extents_mapped = fiemap->fm_mapped_extents;
6001         if (extent_count > 0 &&
6002             copy_to_user(fieinfo->fi_extents_start, &fiemap->fm_extents[0],
6003                          fiemap->fm_mapped_extents *
6004                          sizeof(struct fiemap_extent)) != 0)
6005                 GOTO(out, rc = -EFAULT);
6006 out:
6007         OBD_FREE_LARGE(fiemap, num_bytes);
6008         return rc;
6009 }
6010
6011 int ll_inode_permission(struct mnt_idmap *idmap, struct inode *inode, int mask)
6012 {
6013         int rc = 0;
6014         struct ll_sb_info *sbi;
6015         struct root_squash_info *squash;
6016         struct cred *cred = NULL;
6017         const struct cred *old_cred = NULL;
6018         bool squash_id = false;
6019         ktime_t kstart = ktime_get();
6020
6021         ENTRY;
6022
6023         if (mask & MAY_NOT_BLOCK)
6024                 return -ECHILD;
6025
6026         /*
6027          * as root inode are NOT getting validated in lookup operation,
6028          * need to revalidate PERM before permission check.
6029          */
6030         if (is_root_inode(inode)) {
6031                 rc = ll_inode_revalidate(inode->i_sb->s_root, IT_GETATTR);
6032                 if (rc)
6033                         RETURN(rc);
6034         }
6035
6036         CDEBUG(D_VFSTRACE, "VFS Op:inode="DFID"(%p), inode mode %x mask %o\n",
6037                PFID(ll_inode2fid(inode)), inode, inode->i_mode, mask);
6038
6039         /* squash fsuid/fsgid if needed */
6040         sbi = ll_i2sbi(inode);
6041         squash = &sbi->ll_squash;
6042         if (unlikely(squash->rsi_uid != 0 &&
6043                      uid_eq(current_fsuid(), GLOBAL_ROOT_UID) &&
6044                      !test_bit(LL_SBI_NOROOTSQUASH, sbi->ll_flags))) {
6045                         squash_id = true;
6046         }
6047         if (squash_id) {
6048                 CDEBUG(D_OTHER, "squash creds (%d:%d)=>(%d:%d)\n",
6049                        __kuid_val(current_fsuid()), __kgid_val(current_fsgid()),
6050                        squash->rsi_uid, squash->rsi_gid);
6051
6052                 /* update current process's credentials
6053                  * and FS capability */
6054                 cred = prepare_creds();
6055                 if (cred == NULL)
6056                         RETURN(-ENOMEM);
6057
6058                 cred->fsuid = make_kuid(&init_user_ns, squash->rsi_uid);
6059                 cred->fsgid = make_kgid(&init_user_ns, squash->rsi_gid);
6060                 cred->cap_effective = cap_drop_nfsd_set(cred->cap_effective);
6061                 cred->cap_effective = cap_drop_fs_set(cred->cap_effective);
6062
6063                 old_cred = override_creds(cred);
6064         }
6065
6066         rc = generic_permission(idmap, inode, mask);
6067         /* restore current process's credentials and FS capability */
6068         if (squash_id) {
6069                 revert_creds(old_cred);
6070                 put_cred(cred);
6071         }
6072
6073         if (!rc)
6074                 ll_stats_ops_tally(sbi, LPROC_LL_INODE_PERM,
6075                                    ktime_us_delta(ktime_get(), kstart));
6076
6077         RETURN(rc);
6078 }
6079
6080 #if defined(HAVE_FILEMAP_SPLICE_READ)
6081 # define ll_splice_read         filemap_splice_read
6082 #elif !defined(HAVE_DEFAULT_FILE_SPLICE_READ_EXPORT)
6083 # define ll_splice_read         generic_file_splice_read
6084 #else
6085 # define ll_splice_read         pcc_file_splice_read
6086 #endif
6087
6088 /* -o localflock - only provides locally consistent flock locks */
6089 static const struct file_operations ll_file_operations = {
6090 #ifdef HAVE_FILE_OPERATIONS_READ_WRITE_ITER
6091 # ifdef HAVE_SYNC_READ_WRITE
6092         .read           = new_sync_read,
6093         .write          = new_sync_write,
6094 # endif
6095         .read_iter      = ll_file_read_iter,
6096         .write_iter     = ll_file_write_iter,
6097 #else /* !HAVE_FILE_OPERATIONS_READ_WRITE_ITER */
6098         .read           = ll_file_read,
6099         .aio_read       = ll_file_aio_read,
6100         .write          = ll_file_write,
6101         .aio_write      = ll_file_aio_write,
6102 #endif /* HAVE_FILE_OPERATIONS_READ_WRITE_ITER */
6103         .unlocked_ioctl = ll_file_ioctl,
6104         .open           = ll_file_open,
6105         .release        = ll_file_release,
6106         .mmap           = ll_file_mmap,
6107         .llseek         = ll_file_seek,
6108         .splice_read    = ll_splice_read,
6109 #ifdef HAVE_ITER_FILE_SPLICE_WRITE
6110         .splice_write   = iter_file_splice_write,
6111 #endif
6112         .fsync          = ll_fsync,
6113         .flush          = ll_flush,
6114         .fallocate      = ll_fallocate,
6115 };
6116
6117 static const struct file_operations ll_file_operations_flock = {
6118 #ifdef HAVE_FILE_OPERATIONS_READ_WRITE_ITER
6119 # ifdef HAVE_SYNC_READ_WRITE
6120         .read           = new_sync_read,
6121         .write          = new_sync_write,
6122 # endif /* HAVE_SYNC_READ_WRITE */
6123         .read_iter      = ll_file_read_iter,
6124         .write_iter     = ll_file_write_iter,
6125 #else /* !HAVE_FILE_OPERATIONS_READ_WRITE_ITER */
6126         .read           = ll_file_read,
6127         .aio_read       = ll_file_aio_read,
6128         .write          = ll_file_write,
6129         .aio_write      = ll_file_aio_write,
6130 #endif /* HAVE_FILE_OPERATIONS_READ_WRITE_ITER */
6131         .unlocked_ioctl = ll_file_ioctl,
6132         .open           = ll_file_open,
6133         .release        = ll_file_release,
6134         .mmap           = ll_file_mmap,
6135         .llseek         = ll_file_seek,
6136         .splice_read    = ll_splice_read,
6137 #ifdef HAVE_ITER_FILE_SPLICE_WRITE
6138         .splice_write   = iter_file_splice_write,
6139 #endif
6140         .fsync          = ll_fsync,
6141         .flush          = ll_flush,
6142         .flock          = ll_file_flock,
6143         .lock           = ll_file_flock,
6144         .fallocate      = ll_fallocate,
6145 };
6146
6147 /* These are for -o noflock - to return ENOSYS on flock calls */
6148 static const struct file_operations ll_file_operations_noflock = {
6149 #ifdef HAVE_FILE_OPERATIONS_READ_WRITE_ITER
6150 # ifdef HAVE_SYNC_READ_WRITE
6151         .read           = new_sync_read,
6152         .write          = new_sync_write,
6153 # endif /* HAVE_SYNC_READ_WRITE */
6154         .read_iter      = ll_file_read_iter,
6155         .write_iter     = ll_file_write_iter,
6156 #else /* !HAVE_FILE_OPERATIONS_READ_WRITE_ITER */
6157         .read           = ll_file_read,
6158         .aio_read       = ll_file_aio_read,
6159         .write          = ll_file_write,
6160         .aio_write      = ll_file_aio_write,
6161 #endif /* HAVE_FILE_OPERATIONS_READ_WRITE_ITER */
6162         .unlocked_ioctl = ll_file_ioctl,
6163         .open           = ll_file_open,
6164         .release        = ll_file_release,
6165         .mmap           = ll_file_mmap,
6166         .llseek         = ll_file_seek,
6167         .splice_read    = ll_splice_read,
6168 #ifdef HAVE_ITER_FILE_SPLICE_WRITE
6169         .splice_write   = iter_file_splice_write,
6170 #endif
6171         .fsync          = ll_fsync,
6172         .flush          = ll_flush,
6173         .flock          = ll_file_noflock,
6174         .lock           = ll_file_noflock,
6175         .fallocate      = ll_fallocate,
6176 };
6177
6178 const struct inode_operations ll_file_inode_operations = {
6179         .setattr        = ll_setattr,
6180         .getattr        = ll_getattr,
6181         .permission     = ll_inode_permission,
6182 #ifdef HAVE_IOP_XATTR
6183         .setxattr       = ll_setxattr,
6184         .getxattr       = ll_getxattr,
6185         .removexattr    = ll_removexattr,
6186 #endif
6187         .listxattr      = ll_listxattr,
6188         .fiemap         = ll_fiemap,
6189         .get_acl        = ll_get_acl,
6190 #ifdef HAVE_IOP_SET_ACL
6191         .set_acl        = ll_set_acl,
6192 #endif
6193 #ifdef HAVE_FILEATTR_GET
6194         .fileattr_get   = ll_fileattr_get,
6195         .fileattr_set   = ll_fileattr_set,
6196 #endif
6197 };
6198
6199 const struct file_operations *ll_select_file_operations(struct ll_sb_info *sbi)
6200 {
6201         const struct file_operations *fops = &ll_file_operations_noflock;
6202
6203         if (test_bit(LL_SBI_FLOCK, sbi->ll_flags))
6204                 fops = &ll_file_operations_flock;
6205         else if (test_bit(LL_SBI_LOCALFLOCK, sbi->ll_flags))
6206                 fops = &ll_file_operations;
6207
6208         return fops;
6209 }
6210
6211 int ll_layout_conf(struct inode *inode, const struct cl_object_conf *conf)
6212 {
6213         struct ll_inode_info *lli = ll_i2info(inode);
6214         struct cl_object *obj = lli->lli_clob;
6215         struct lu_env *env;
6216         int rc;
6217         __u16 refcheck;
6218         ENTRY;
6219
6220         if (obj == NULL)
6221                 RETURN(0);
6222
6223         env = cl_env_get(&refcheck);
6224         if (IS_ERR(env))
6225                 RETURN(PTR_ERR(env));
6226
6227         rc = cl_conf_set(env, lli->lli_clob, conf);
6228         if (rc < 0)
6229                 GOTO(out, rc);
6230
6231         if (conf->coc_opc == OBJECT_CONF_SET) {
6232                 struct ldlm_lock *lock = conf->coc_lock;
6233                 struct cl_layout cl = {
6234                         .cl_layout_gen = 0,
6235                 };
6236
6237                 LASSERT(lock != NULL);
6238                 LASSERT(ldlm_has_layout(lock));
6239
6240                 /* it can only be allowed to match after layout is
6241                  * applied to inode otherwise false layout would be
6242                  * seen. Applying layout shoud happen before dropping
6243                  * the intent lock. */
6244                 ldlm_lock_allow_match(lock);
6245
6246                 rc = cl_object_layout_get(env, obj, &cl);
6247                 if (rc < 0)
6248                         GOTO(out, rc);
6249
6250                 CDEBUG(D_VFSTRACE,
6251                        DFID": layout version change: %u -> %u\n",
6252                        PFID(&lli->lli_fid), ll_layout_version_get(lli),
6253                        cl.cl_layout_gen);
6254                 ll_layout_version_set(lli, cl.cl_layout_gen);
6255         }
6256
6257 out:
6258         cl_env_put(env, &refcheck);
6259
6260         RETURN(rc < 0 ? rc : 0);
6261 }
6262
6263 /* Fetch layout from MDT with getxattr request, if it's not ready yet */
6264 static int ll_layout_fetch(struct inode *inode, struct ldlm_lock *lock)
6265
6266 {
6267         struct ll_sb_info *sbi = ll_i2sbi(inode);
6268         struct ptlrpc_request *req;
6269         void *lvbdata;
6270         void *lmm;
6271         int lmmsize;
6272         int rc;
6273         ENTRY;
6274
6275         CDEBUG(D_INODE, DFID" LVB_READY=%d l_lvb_data=%p l_lvb_len=%d\n",
6276                PFID(ll_inode2fid(inode)), ldlm_is_lvb_ready(lock),
6277                lock->l_lvb_data, lock->l_lvb_len);
6278
6279         if (lock->l_lvb_data != NULL)
6280                 RETURN(0);
6281
6282         /* if layout lock was granted right away, the layout is returned
6283          * within DLM_LVB of dlm reply; otherwise if the lock was ever
6284          * blocked and then granted via completion ast, we have to fetch
6285          * layout here. Please note that we can't use the LVB buffer in
6286          * completion AST because it doesn't have a large enough buffer */
6287         rc = ll_get_default_mdsize(sbi, &lmmsize);
6288         if (rc < 0)
6289                 RETURN(rc);
6290
6291         rc = md_getxattr(sbi->ll_md_exp, ll_inode2fid(inode), OBD_MD_FLXATTR,
6292                          XATTR_NAME_LOV, lmmsize, &req);
6293         if (rc < 0) {
6294                 if (rc == -ENODATA)
6295                         GOTO(out, rc = 0); /* empty layout */
6296                 else
6297                         RETURN(rc);
6298         }
6299
6300         lmmsize = rc;
6301         rc = 0;
6302         if (lmmsize == 0) /* empty layout */
6303                 GOTO(out, rc = 0);
6304
6305         lmm = req_capsule_server_sized_get(&req->rq_pill, &RMF_EADATA, lmmsize);
6306         if (lmm == NULL)
6307                 GOTO(out, rc = -EFAULT);
6308
6309         OBD_ALLOC_LARGE(lvbdata, lmmsize);
6310         if (lvbdata == NULL)
6311                 GOTO(out, rc = -ENOMEM);
6312
6313         memcpy(lvbdata, lmm, lmmsize);
6314         lock_res_and_lock(lock);
6315         if (unlikely(lock->l_lvb_data == NULL)) {
6316                 lock->l_lvb_type = LVB_T_LAYOUT;
6317                 lock->l_lvb_data = lvbdata;
6318                 lock->l_lvb_len = lmmsize;
6319                 lvbdata = NULL;
6320         }
6321         unlock_res_and_lock(lock);
6322
6323         if (lvbdata)
6324                 OBD_FREE_LARGE(lvbdata, lmmsize);
6325
6326         EXIT;
6327
6328 out:
6329         ptlrpc_req_finished(req);
6330         return rc;
6331 }
6332
6333 /**
6334  * Apply the layout to the inode. Layout lock is held and will be released
6335  * in this function.
6336  */
6337 static int ll_layout_lock_set(struct lustre_handle *lockh, enum ldlm_mode mode,
6338                               struct inode *inode, bool try)
6339 {
6340         struct ll_inode_info *lli = ll_i2info(inode);
6341         struct ll_sb_info    *sbi = ll_i2sbi(inode);
6342         struct ldlm_lock *lock;
6343         struct cl_object_conf conf;
6344         int rc = 0;
6345         bool lvb_ready;
6346         bool wait_layout = false;
6347         ENTRY;
6348
6349         LASSERT(lustre_handle_is_used(lockh));
6350
6351         lock = ldlm_handle2lock(lockh);
6352         LASSERT(lock != NULL);
6353
6354         if (!ldlm_has_layout(lock))
6355                 GOTO(out, rc = -EAGAIN);
6356
6357         LDLM_DEBUG(lock, "file "DFID"(%p) being reconfigured",
6358                    PFID(&lli->lli_fid), inode);
6359
6360         /* in case this is a caching lock and reinstate with new inode */
6361         md_set_lock_data(sbi->ll_md_exp, lockh, inode, NULL);
6362
6363         lock_res_and_lock(lock);
6364         lvb_ready = ldlm_is_lvb_ready(lock);
6365         unlock_res_and_lock(lock);
6366
6367         /* checking lvb_ready is racy but this is okay. The worst case is
6368          * that multi processes may configure the file on the same time. */
6369         if (lvb_ready)
6370                 GOTO(out, rc = 0);
6371
6372         rc = ll_layout_fetch(inode, lock);
6373         if (rc < 0)
6374                 GOTO(out, rc);
6375
6376         /* for layout lock, lmm is stored in lock's lvb.
6377          * lvb_data is immutable if the lock is held so it's safe to access it
6378          * without res lock.
6379          *
6380          * set layout to file. Unlikely this will fail as old layout was
6381          * surely eliminated */
6382         memset(&conf, 0, sizeof conf);
6383         conf.coc_opc = OBJECT_CONF_SET;
6384         conf.coc_inode = inode;
6385         conf.coc_lock = lock;
6386         conf.coc_try = try;
6387         conf.u.coc_layout.lb_buf = lock->l_lvb_data;
6388         conf.u.coc_layout.lb_len = lock->l_lvb_len;
6389         rc = ll_layout_conf(inode, &conf);
6390
6391         /* refresh layout failed, need to wait */
6392         wait_layout = rc == -EBUSY;
6393         EXIT;
6394 out:
6395         LDLM_LOCK_PUT(lock);
6396         ldlm_lock_decref(lockh, mode);
6397
6398         /* wait for IO to complete if it's still being used. */
6399         if (wait_layout) {
6400                 CDEBUG(D_INODE, "%s: "DFID"(%p) wait for layout reconf\n",
6401                        sbi->ll_fsname, PFID(&lli->lli_fid), inode);
6402
6403                 memset(&conf, 0, sizeof conf);
6404                 conf.coc_opc = OBJECT_CONF_WAIT;
6405                 conf.coc_inode = inode;
6406                 rc = ll_layout_conf(inode, &conf);
6407                 if (rc == 0)
6408                         rc = -ERESTARTSYS;
6409
6410                 CDEBUG(D_INODE, "%s file="DFID" waiting layout return: %d\n",
6411                        sbi->ll_fsname, PFID(&lli->lli_fid), rc);
6412         }
6413
6414         if (rc == -ERESTARTSYS) {
6415                 __u16 refcheck;
6416                 struct lu_env *env;
6417                 struct cl_object * obj = lli->lli_clob;
6418
6419                 env = cl_env_get(&refcheck);
6420                 if (IS_ERR(env))
6421                         RETURN(PTR_ERR(env));
6422
6423                 CDEBUG(D_INODE, "prune without lock "DFID"\n",
6424                                 PFID(lu_object_fid(&obj->co_lu)));
6425
6426                 trunc_sem_down_write(&lli->lli_trunc_sem);
6427                 cl_object_prune(env, obj);
6428                 trunc_sem_up_write(&lli->lli_trunc_sem);
6429                 cl_env_put(env, &refcheck);
6430
6431                 rc = -EAGAIN;
6432         }
6433
6434         RETURN(rc);
6435 }
6436
6437 /**
6438  * Issue layout intent RPC to MDS.
6439  * \param inode [in]    file inode
6440  * \param intent [in]   layout intent
6441  *
6442  * \retval 0    on success
6443  * \retval < 0  error code
6444  */
6445 static int ll_layout_intent(struct inode *inode, struct layout_intent *intent)
6446 {
6447         struct ll_inode_info  *lli = ll_i2info(inode);
6448         struct ll_sb_info     *sbi = ll_i2sbi(inode);
6449         struct md_op_data     *op_data;
6450         struct lookup_intent it;
6451         struct ptlrpc_request *req;
6452         int rc;
6453         ENTRY;
6454
6455         op_data = ll_prep_md_op_data(NULL, inode, inode, NULL,
6456                                      0, 0, LUSTRE_OPC_ANY, NULL);
6457         if (IS_ERR(op_data))
6458                 RETURN(PTR_ERR(op_data));
6459
6460         op_data->op_data = intent;
6461         op_data->op_data_size = sizeof(*intent);
6462
6463         memset(&it, 0, sizeof(it));
6464         it.it_op = IT_LAYOUT;
6465         if (intent->lai_opc == LAYOUT_INTENT_WRITE ||
6466             intent->lai_opc == LAYOUT_INTENT_TRUNC)
6467                 it.it_flags = FMODE_WRITE;
6468
6469         LDLM_DEBUG_NOLOCK("%s: requeue layout lock for file "DFID"(%p)",
6470                           sbi->ll_fsname, PFID(&lli->lli_fid), inode);
6471
6472         rc = md_intent_lock(sbi->ll_md_exp, op_data, &it, &req,
6473                             &ll_md_blocking_ast, 0);
6474         if (it.it_request != NULL)
6475                 ptlrpc_req_finished(it.it_request);
6476         it.it_request = NULL;
6477
6478         ll_finish_md_op_data(op_data);
6479
6480         /* set lock data in case this is a new lock */
6481         if (!rc)
6482                 ll_set_lock_data(sbi->ll_md_exp, inode, &it, NULL);
6483
6484         ll_intent_drop_lock(&it);
6485
6486         RETURN(rc);
6487 }
6488
6489 /**
6490  * This function checks if there exists a LAYOUT lock on the client side,
6491  * or enqueues it if it doesn't have one in cache.
6492  *
6493  * This function will not hold layout lock so it may be revoked any time after
6494  * this function returns. Any operations depend on layout should be redone
6495  * in that case.
6496  *
6497  * This function should be called before lov_io_init() to get an uptodate
6498  * layout version, the caller should save the version number and after IO
6499  * is finished, this function should be called again to verify that layout
6500  * is not changed during IO time.
6501  */
6502 int ll_layout_refresh(struct inode *inode, __u32 *gen)
6503 {
6504         struct ll_inode_info    *lli = ll_i2info(inode);
6505         struct ll_sb_info       *sbi = ll_i2sbi(inode);
6506         struct lustre_handle lockh;
6507         struct layout_intent intent = {
6508                 .lai_opc = LAYOUT_INTENT_ACCESS,
6509         };
6510         enum ldlm_mode mode;
6511         int rc;
6512         bool try = true;
6513         ENTRY;
6514
6515         *gen = ll_layout_version_get(lli);
6516         if (!test_bit(LL_SBI_LAYOUT_LOCK, sbi->ll_flags) ||
6517             *gen != CL_LAYOUT_GEN_NONE)
6518                 RETURN(0);
6519
6520         /* sanity checks */
6521         LASSERT(fid_is_sane(ll_inode2fid(inode)));
6522         LASSERT(S_ISREG(inode->i_mode));
6523
6524         while (1) {
6525                 /* mostly layout lock is caching on the local side, so try to
6526                  * match it before grabbing layout lock mutex. */
6527                 mode = ll_take_md_lock(inode, MDS_INODELOCK_LAYOUT, &lockh, 0,
6528                                        LCK_CR | LCK_CW | LCK_PR |
6529                                        LCK_PW | LCK_EX);
6530                 if (mode != 0) { /* hit cached lock */
6531                         rc = ll_layout_lock_set(&lockh, mode, inode, try);
6532                         try = false;
6533                         if (rc == -EAGAIN)
6534                                 continue;
6535                         break;
6536                 }
6537
6538                 /* take layout lock mutex to enqueue layout lock exclusively. */
6539                 mutex_lock(&lli->lli_layout_mutex);
6540                 rc = ll_layout_intent(inode, &intent);
6541                 mutex_unlock(&lli->lli_layout_mutex);
6542                 if (rc != 0)
6543                         break;
6544         }
6545
6546         if (rc == 0)
6547                 *gen = ll_layout_version_get(lli);
6548
6549         RETURN(rc);
6550 }
6551
6552 /**
6553  * Issue layout intent RPC indicating where in a file an IO is about to write.
6554  *
6555  * \param[in] inode     file inode.
6556  * \param[in] ext       write range with start offset of fille in bytes where
6557  *                      an IO is about to write, and exclusive end offset in
6558  *                      bytes.
6559  *
6560  * \retval 0    on success
6561  * \retval < 0  error code
6562  */
6563 int ll_layout_write_intent(struct inode *inode, enum layout_intent_opc opc,
6564                            struct lu_extent *ext)
6565 {
6566         struct layout_intent intent = {
6567                 .lai_opc = opc,
6568                 .lai_extent.e_start = ext->e_start,
6569                 .lai_extent.e_end = ext->e_end,
6570         };
6571         int rc;
6572         ENTRY;
6573
6574         rc = ll_layout_intent(inode, &intent);
6575
6576         RETURN(rc);
6577 }
6578
6579 /**
6580  *  This function send a restore request to the MDT
6581  */
6582 int ll_layout_restore(struct inode *inode, loff_t offset, __u64 length)
6583 {
6584         struct ll_inode_info *lli = ll_i2info(inode);
6585         struct hsm_user_request *hur;
6586         int len, rc;
6587
6588         ENTRY;
6589
6590         len = sizeof(struct hsm_user_request) +
6591               sizeof(struct hsm_user_item);
6592         OBD_ALLOC(hur, len);
6593         if (hur == NULL)
6594                 RETURN(-ENOMEM);
6595
6596         hur->hur_request.hr_action = HUA_RESTORE;
6597         hur->hur_request.hr_archive_id = 0;
6598         hur->hur_request.hr_flags = 0;
6599         memcpy(&hur->hur_user_item[0].hui_fid, &ll_i2info(inode)->lli_fid,
6600                sizeof(hur->hur_user_item[0].hui_fid));
6601         hur->hur_user_item[0].hui_extent.offset = offset;
6602         hur->hur_user_item[0].hui_extent.length = length;
6603         hur->hur_request.hr_itemcount = 1;
6604         rc = mutex_lock_interruptible(&lli->lli_layout_mutex);
6605         if (rc)
6606                 GOTO(out_free, rc);
6607         rc = obd_iocontrol(LL_IOC_HSM_REQUEST, ll_i2sbi(inode)->ll_md_exp,
6608                            len, hur, NULL);
6609         mutex_unlock(&lli->lli_layout_mutex);
6610 out_free:
6611         OBD_FREE(hur, len);
6612         RETURN(rc);
6613 }