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