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