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