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