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