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