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