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