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