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