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