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