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