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