Whamcloud - gitweb
LU-10948 llite: Introduce inode open heat counter
[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, 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         struct cl_io *io;
1600         ssize_t result = 0;
1601         int rc = 0;
1602         unsigned int retried = 0, dio_lock = 0;
1603         bool is_aio = false;
1604         struct cl_dio_aio *ci_aio = NULL;
1605         size_t per_bytes;
1606         bool partial_io = false;
1607         size_t max_io_pages, max_cached_pages;
1608
1609         ENTRY;
1610
1611         CDEBUG(D_VFSTRACE, "%s: %s ppos: %llu, count: %zu\n",
1612                 file_dentry(file)->d_name.name,
1613                 iot == CIT_READ ? "read" : "write", *ppos, count);
1614
1615         max_io_pages = PTLRPC_MAX_BRW_PAGES * OBD_MAX_RIF_DEFAULT;
1616         max_cached_pages = sbi->ll_cache->ccc_lru_max;
1617         if (max_io_pages > (max_cached_pages >> 2))
1618                 max_io_pages = max_cached_pages >> 2;
1619
1620         io = vvp_env_thread_io(env);
1621         if (file->f_flags & O_DIRECT) {
1622                 if (!is_sync_kiocb(args->u.normal.via_iocb))
1623                         is_aio = true;
1624                 ci_aio = cl_aio_alloc(args->u.normal.via_iocb);
1625                 if (!ci_aio)
1626                         GOTO(out, rc = -ENOMEM);
1627         }
1628
1629 restart:
1630         /**
1631          * IO block size need be aware of cached page limit, otherwise
1632          * if we have small max_cached_mb but large block IO issued, io
1633          * could not be finished and blocked whole client.
1634          */
1635         if (file->f_flags & O_DIRECT)
1636                 per_bytes = count;
1637         else
1638                 per_bytes = min(max_io_pages << PAGE_SHIFT, count);
1639         partial_io = per_bytes < count;
1640         io = vvp_env_thread_io(env);
1641         ll_io_init(io, file, iot, args);
1642         io->ci_aio = ci_aio;
1643         io->ci_dio_lock = dio_lock;
1644         io->ci_ndelay_tried = retried;
1645
1646         if (cl_io_rw_init(env, io, iot, *ppos, per_bytes) == 0) {
1647                 bool range_locked = false;
1648
1649                 if (file->f_flags & O_APPEND)
1650                         range_lock_init(&range, 0, LUSTRE_EOF);
1651                 else
1652                         range_lock_init(&range, *ppos, *ppos + per_bytes - 1);
1653
1654                 vio->vui_fd  = file->private_data;
1655                 vio->vui_iter = args->u.normal.via_iter;
1656                 vio->vui_iocb = args->u.normal.via_iocb;
1657                 /* Direct IO reads must also take range lock,
1658                  * or multiple reads will try to work on the same pages
1659                  * See LU-6227 for details.
1660                  */
1661                 if (((iot == CIT_WRITE) ||
1662                     (iot == CIT_READ && (file->f_flags & O_DIRECT))) &&
1663                     !(vio->vui_fd->fd_flags & LL_FILE_GROUP_LOCKED)) {
1664                         CDEBUG(D_VFSTRACE, "Range lock "RL_FMT"\n",
1665                                RL_PARA(&range));
1666                         rc = range_lock(&lli->lli_write_tree, &range);
1667                         if (rc < 0)
1668                                 GOTO(out, rc);
1669
1670                         range_locked = true;
1671                 }
1672
1673                 ll_cl_add(file, env, io, LCC_RW);
1674                 rc = cl_io_loop(env, io);
1675                 ll_cl_remove(file, env);
1676
1677                 if (range_locked) {
1678                         CDEBUG(D_VFSTRACE, "Range unlock "RL_FMT"\n",
1679                                RL_PARA(&range));
1680                         range_unlock(&lli->lli_write_tree, &range);
1681                 }
1682         } else {
1683                 /* cl_io_rw_init() handled IO */
1684                 rc = io->ci_result;
1685         }
1686
1687         /*
1688          * In order to move forward AIO, ci_nob was increased,
1689          * but that doesn't mean io have been finished, it just
1690          * means io have been submited, we will always return
1691          * EIOCBQUEUED to the caller, So we could only return
1692          * number of bytes in non-AIO case.
1693          */
1694         if (io->ci_nob > 0) {
1695                 if (!is_aio) {
1696                         result += io->ci_nob;
1697                         *ppos = io->u.ci_wr.wr.crw_pos; /* for splice */
1698                 }
1699                 count -= io->ci_nob;
1700
1701                 /* prepare IO restart */
1702                 if (count > 0)
1703                         args->u.normal.via_iter = vio->vui_iter;
1704
1705                 if (partial_io) {
1706                         /**
1707                          * Reexpand iov count because it was zero
1708                          * after IO finish.
1709                          */
1710                         iov_iter_reexpand(vio->vui_iter, count);
1711                         if (per_bytes == io->ci_nob)
1712                                 io->ci_need_restart = 1;
1713                 }
1714         }
1715 out:
1716         cl_io_fini(env, io);
1717
1718         CDEBUG(D_VFSTRACE,
1719                "%s: %d io complete with rc: %d, result: %zd, restart: %d\n",
1720                file->f_path.dentry->d_name.name,
1721                iot, rc, result, io->ci_need_restart);
1722
1723         if ((rc == 0 || rc == -ENODATA || rc == -ENOLCK) &&
1724             count > 0 && io->ci_need_restart) {
1725                 CDEBUG(D_VFSTRACE,
1726                        "%s: restart %s from %lld, count: %zu, ret: %zd, rc: %d\n",
1727                        file_dentry(file)->d_name.name,
1728                        iot == CIT_READ ? "read" : "write",
1729                        *ppos, count, result, rc);
1730                 /* preserve the tried count for FLR */
1731                 retried = io->ci_ndelay_tried;
1732                 dio_lock = io->ci_dio_lock;
1733                 goto restart;
1734         }
1735
1736         if (io->ci_aio) {
1737                 /*
1738                  * VFS will call aio_complete() if no -EIOCBQUEUED
1739                  * is returned for AIO, so we can not call aio_complete()
1740                  * in our end_io().
1741                  */
1742                 if (rc != -EIOCBQUEUED)
1743                         io->ci_aio->cda_no_aio_complete = 1;
1744                 /**
1745                  * Drop one extra reference so that end_io() could be
1746                  * called for this IO context, we could call it after
1747                  * we make sure all AIO requests have been proceed.
1748                  */
1749                 cl_sync_io_note(env, &io->ci_aio->cda_sync,
1750                                 rc == -EIOCBQUEUED ? 0 : rc);
1751                 if (!is_aio) {
1752                         cl_aio_free(io->ci_aio);
1753                         io->ci_aio = NULL;
1754                 }
1755         }
1756
1757         if (iot == CIT_READ) {
1758                 if (result > 0)
1759                         ll_stats_ops_tally(ll_i2sbi(inode),
1760                                            LPROC_LL_READ_BYTES, result);
1761         } else if (iot == CIT_WRITE) {
1762                 if (result > 0) {
1763                         ll_stats_ops_tally(ll_i2sbi(inode),
1764                                            LPROC_LL_WRITE_BYTES, result);
1765                         fd->fd_write_failed = false;
1766                 } else if (result == 0 && rc == 0) {
1767                         rc = io->ci_result;
1768                         if (rc < 0)
1769                                 fd->fd_write_failed = true;
1770                         else
1771                                 fd->fd_write_failed = false;
1772                 } else if (rc != -ERESTARTSYS) {
1773                         fd->fd_write_failed = true;
1774                 }
1775         }
1776
1777         CDEBUG(D_VFSTRACE, "iot: %d, result: %zd\n", iot, result);
1778         if (result > 0)
1779                 ll_heat_add(inode, iot, result);
1780
1781         RETURN(result > 0 ? result : rc);
1782 }
1783
1784 /**
1785  * The purpose of fast read is to overcome per I/O overhead and improve IOPS
1786  * especially for small I/O.
1787  *
1788  * To serve a read request, CLIO has to create and initialize a cl_io and
1789  * then request DLM lock. This has turned out to have siginificant overhead
1790  * and affects the performance of small I/O dramatically.
1791  *
1792  * It's not necessary to create a cl_io for each I/O. Under the help of read
1793  * ahead, most of the pages being read are already in memory cache and we can
1794  * read those pages directly because if the pages exist, the corresponding DLM
1795  * lock must exist so that page content must be valid.
1796  *
1797  * In fast read implementation, the llite speculatively finds and reads pages
1798  * in memory cache. There are three scenarios for fast read:
1799  *   - If the page exists and is uptodate, kernel VM will provide the data and
1800  *     CLIO won't be intervened;
1801  *   - If the page was brought into memory by read ahead, it will be exported
1802  *     and read ahead parameters will be updated;
1803  *   - Otherwise the page is not in memory, we can't do fast read. Therefore,
1804  *     it will go back and invoke normal read, i.e., a cl_io will be created
1805  *     and DLM lock will be requested.
1806  *
1807  * POSIX compliance: posix standard states that read is intended to be atomic.
1808  * Lustre read implementation is in line with Linux kernel read implementation
1809  * and neither of them complies with POSIX standard in this matter. Fast read
1810  * doesn't make the situation worse on single node but it may interleave write
1811  * results from multiple nodes due to short read handling in ll_file_aio_read().
1812  *
1813  * \param env - lu_env
1814  * \param iocb - kiocb from kernel
1815  * \param iter - user space buffers where the data will be copied
1816  *
1817  * \retval - number of bytes have been read, or error code if error occurred.
1818  */
1819 static ssize_t
1820 ll_do_fast_read(struct kiocb *iocb, struct iov_iter *iter)
1821 {
1822         ssize_t result;
1823
1824         if (!ll_sbi_has_fast_read(ll_i2sbi(file_inode(iocb->ki_filp))))
1825                 return 0;
1826
1827         /* NB: we can't do direct IO for fast read because it will need a lock
1828          * to make IO engine happy. */
1829         if (iocb->ki_filp->f_flags & O_DIRECT)
1830                 return 0;
1831
1832         result = generic_file_read_iter(iocb, iter);
1833
1834         /* If the first page is not in cache, generic_file_aio_read() will be
1835          * returned with -ENODATA.
1836          * See corresponding code in ll_readpage(). */
1837         if (result == -ENODATA)
1838                 result = 0;
1839
1840         if (result > 0) {
1841                 ll_heat_add(file_inode(iocb->ki_filp), CIT_READ, result);
1842                 ll_stats_ops_tally(ll_i2sbi(file_inode(iocb->ki_filp)),
1843                                    LPROC_LL_READ_BYTES, result);
1844         }
1845
1846         return result;
1847 }
1848
1849 /*
1850  * Read from a file (through the page cache).
1851  */
1852 static ssize_t ll_file_read_iter(struct kiocb *iocb, struct iov_iter *to)
1853 {
1854         struct lu_env *env;
1855         struct vvp_io_args *args;
1856         struct file *file = iocb->ki_filp;
1857         ssize_t result;
1858         ssize_t rc2;
1859         __u16 refcheck;
1860         ktime_t kstart = ktime_get();
1861         bool cached;
1862
1863         if (!iov_iter_count(to))
1864                 return 0;
1865
1866         /**
1867          * Currently when PCC read failed, we do not fall back to the
1868          * normal read path, just return the error.
1869          * The resaon is that: for RW-PCC, the file data may be modified
1870          * in the PCC and inconsistent with the data on OSTs (or file
1871          * data has been removed from the Lustre file system), at this
1872          * time, fallback to the normal read path may read the wrong
1873          * data.
1874          * TODO: for RO-PCC (readonly PCC), fall back to normal read
1875          * path: read data from data copy on OSTs.
1876          */
1877         result = pcc_file_read_iter(iocb, to, &cached);
1878         if (cached)
1879                 GOTO(out, result);
1880
1881         ll_ras_enter(file, iocb->ki_pos, iov_iter_count(to));
1882
1883         result = ll_do_fast_read(iocb, to);
1884         if (result < 0 || iov_iter_count(to) == 0)
1885                 GOTO(out, result);
1886
1887         env = cl_env_get(&refcheck);
1888         if (IS_ERR(env))
1889                 return PTR_ERR(env);
1890
1891         args = ll_env_args(env);
1892         args->u.normal.via_iter = to;
1893         args->u.normal.via_iocb = iocb;
1894
1895         rc2 = ll_file_io_generic(env, args, file, CIT_READ,
1896                                  &iocb->ki_pos, iov_iter_count(to));
1897         if (rc2 > 0)
1898                 result += rc2;
1899         else if (result == 0)
1900                 result = rc2;
1901
1902         cl_env_put(env, &refcheck);
1903 out:
1904         if (result > 0) {
1905                 ll_rw_stats_tally(ll_i2sbi(file_inode(file)), current->pid,
1906                                   file->private_data, iocb->ki_pos, result,
1907                                   READ);
1908                 ll_stats_ops_tally(ll_i2sbi(file_inode(file)), LPROC_LL_READ,
1909                                    ktime_us_delta(ktime_get(), kstart));
1910         }
1911
1912         return result;
1913 }
1914
1915 /**
1916  * Similar trick to ll_do_fast_read, this improves write speed for tiny writes.
1917  * If a page is already in the page cache and dirty (and some other things -
1918  * See ll_tiny_write_begin for the instantiation of these rules), then we can
1919  * write to it without doing a full I/O, because Lustre already knows about it
1920  * and will write it out.  This saves a lot of processing time.
1921  *
1922  * All writes here are within one page, so exclusion is handled by the page
1923  * lock on the vm page.  We do not do tiny writes for writes which touch
1924  * multiple pages because it's very unlikely multiple sequential pages are
1925  * are already dirty.
1926  *
1927  * We limit these to < PAGE_SIZE because PAGE_SIZE writes are relatively common
1928  * and are unlikely to be to already dirty pages.
1929  *
1930  * Attribute updates are important here, we do them in ll_tiny_write_end.
1931  */
1932 static ssize_t ll_do_tiny_write(struct kiocb *iocb, struct iov_iter *iter)
1933 {
1934         ssize_t count = iov_iter_count(iter);
1935         struct  file *file = iocb->ki_filp;
1936         struct  inode *inode = file_inode(file);
1937         bool    lock_inode = !IS_NOSEC(inode);
1938         ssize_t result = 0;
1939
1940         ENTRY;
1941
1942         /* Restrict writes to single page and < PAGE_SIZE.  See comment at top
1943          * of function for why.
1944          */
1945         if (count >= PAGE_SIZE ||
1946             (iocb->ki_pos & (PAGE_SIZE-1)) + count > PAGE_SIZE)
1947                 RETURN(0);
1948
1949         if (unlikely(lock_inode))
1950                 inode_lock(inode);
1951         result = __generic_file_write_iter(iocb, iter);
1952
1953         if (unlikely(lock_inode))
1954                 inode_unlock(inode);
1955
1956         /* If the page is not already dirty, ll_tiny_write_begin returns
1957          * -ENODATA.  We continue on to normal write.
1958          */
1959         if (result == -ENODATA)
1960                 result = 0;
1961
1962         if (result > 0) {
1963                 ll_heat_add(inode, CIT_WRITE, result);
1964                 ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_WRITE_BYTES,
1965                                    result);
1966                 set_bit(LLIF_DATA_MODIFIED, &ll_i2info(inode)->lli_flags);
1967         }
1968
1969         CDEBUG(D_VFSTRACE, "result: %zu, original count %zu\n", result, count);
1970
1971         RETURN(result);
1972 }
1973
1974 /*
1975  * Write to a file (through the page cache).
1976  */
1977 static ssize_t ll_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
1978 {
1979         struct vvp_io_args *args;
1980         struct lu_env *env;
1981         ssize_t rc_tiny = 0, rc_normal;
1982         struct file *file = iocb->ki_filp;
1983         __u16 refcheck;
1984         bool cached;
1985         ktime_t kstart = ktime_get();
1986         int result;
1987
1988         ENTRY;
1989
1990         if (!iov_iter_count(from))
1991                 GOTO(out, rc_normal = 0);
1992
1993         /**
1994          * When PCC write failed, we usually do not fall back to the normal
1995          * write path, just return the error. But there is a special case when
1996          * returned error code is -ENOSPC due to running out of space on PCC HSM
1997          * bakcend. At this time, it will fall back to normal I/O path and
1998          * retry the I/O. As the file is in HSM released state, it will restore
1999          * the file data to OSTs first and redo the write again. And the
2000          * restore process will revoke the layout lock and detach the file
2001          * from PCC cache automatically.
2002          */
2003         result = pcc_file_write_iter(iocb, from, &cached);
2004         if (cached && result != -ENOSPC && result != -EDQUOT)
2005                 GOTO(out, rc_normal = result);
2006
2007         /* NB: we can't do direct IO for tiny writes because they use the page
2008          * cache, we can't do sync writes because tiny writes can't flush
2009          * pages, and we can't do append writes because we can't guarantee the
2010          * required DLM locks are held to protect file size.
2011          */
2012         if (ll_sbi_has_tiny_write(ll_i2sbi(file_inode(file))) &&
2013             !(file->f_flags & (O_DIRECT | O_SYNC | O_APPEND)))
2014                 rc_tiny = ll_do_tiny_write(iocb, from);
2015
2016         /* In case of error, go on and try normal write - Only stop if tiny
2017          * write completed I/O.
2018          */
2019         if (iov_iter_count(from) == 0)
2020                 GOTO(out, rc_normal = rc_tiny);
2021
2022         env = cl_env_get(&refcheck);
2023         if (IS_ERR(env))
2024                 return PTR_ERR(env);
2025
2026         args = ll_env_args(env);
2027         args->u.normal.via_iter = from;
2028         args->u.normal.via_iocb = iocb;
2029
2030         rc_normal = ll_file_io_generic(env, args, file, CIT_WRITE,
2031                                        &iocb->ki_pos, iov_iter_count(from));
2032
2033         /* On success, combine bytes written. */
2034         if (rc_tiny >= 0 && rc_normal > 0)
2035                 rc_normal += rc_tiny;
2036         /* On error, only return error from normal write if tiny write did not
2037          * write any bytes.  Otherwise return bytes written by tiny write.
2038          */
2039         else if (rc_tiny > 0)
2040                 rc_normal = rc_tiny;
2041
2042         cl_env_put(env, &refcheck);
2043 out:
2044         if (rc_normal > 0) {
2045                 ll_rw_stats_tally(ll_i2sbi(file_inode(file)), current->pid,
2046                                   file->private_data, iocb->ki_pos,
2047                                   rc_normal, WRITE);
2048                 ll_stats_ops_tally(ll_i2sbi(file_inode(file)), LPROC_LL_WRITE,
2049                                    ktime_us_delta(ktime_get(), kstart));
2050         }
2051
2052         RETURN(rc_normal);
2053 }
2054
2055 #ifndef HAVE_FILE_OPERATIONS_READ_WRITE_ITER
2056 /*
2057  * XXX: exact copy from kernel code (__generic_file_aio_write_nolock)
2058  */
2059 static int ll_file_get_iov_count(const struct iovec *iov,
2060                                  unsigned long *nr_segs, size_t *count,
2061                                  int access_flags)
2062 {
2063         size_t cnt = 0;
2064         unsigned long seg;
2065
2066         for (seg = 0; seg < *nr_segs; seg++) {
2067                 const struct iovec *iv = &iov[seg];
2068
2069                 /*
2070                  * If any segment has a negative length, or the cumulative
2071                  * length ever wraps negative then return -EINVAL.
2072                  */
2073                 cnt += iv->iov_len;
2074                 if (unlikely((ssize_t)(cnt|iv->iov_len) < 0))
2075                         return -EINVAL;
2076                 if (access_ok(access_flags, iv->iov_base, iv->iov_len))
2077                         continue;
2078                 if (seg == 0)
2079                         return -EFAULT;
2080                 *nr_segs = seg;
2081                 cnt -= iv->iov_len;     /* This segment is no good */
2082                 break;
2083         }
2084         *count = cnt;
2085         return 0;
2086 }
2087
2088 static ssize_t ll_file_aio_read(struct kiocb *iocb, const struct iovec *iov,
2089                                 unsigned long nr_segs, loff_t pos)
2090 {
2091         struct iov_iter to;
2092         size_t iov_count;
2093         ssize_t result;
2094         ENTRY;
2095
2096         result = ll_file_get_iov_count(iov, &nr_segs, &iov_count, VERIFY_READ);
2097         if (result)
2098                 RETURN(result);
2099
2100         if (!iov_count)
2101                 RETURN(0);
2102
2103 # ifdef HAVE_IOV_ITER_INIT_DIRECTION
2104         iov_iter_init(&to, READ, iov, nr_segs, iov_count);
2105 # else /* !HAVE_IOV_ITER_INIT_DIRECTION */
2106         iov_iter_init(&to, iov, nr_segs, iov_count, 0);
2107 # endif /* HAVE_IOV_ITER_INIT_DIRECTION */
2108
2109         result = ll_file_read_iter(iocb, &to);
2110
2111         RETURN(result);
2112 }
2113
2114 static ssize_t ll_file_read(struct file *file, char __user *buf, size_t count,
2115                             loff_t *ppos)
2116 {
2117         struct iovec   iov = { .iov_base = buf, .iov_len = count };
2118         struct kiocb   kiocb;
2119         ssize_t        result;
2120
2121         ENTRY;
2122
2123         if (!count)
2124                 RETURN(0);
2125
2126         init_sync_kiocb(&kiocb, file);
2127         kiocb.ki_pos = *ppos;
2128 #ifdef HAVE_KIOCB_KI_LEFT
2129         kiocb.ki_left = count;
2130 #elif defined(HAVE_KI_NBYTES)
2131         kiocb.i_nbytes = count;
2132 #endif
2133
2134         result = ll_file_aio_read(&kiocb, &iov, 1, kiocb.ki_pos);
2135         *ppos = kiocb.ki_pos;
2136
2137         RETURN(result);
2138 }
2139
2140 /*
2141  * Write to a file (through the page cache).
2142  * AIO stuff
2143  */
2144 static ssize_t ll_file_aio_write(struct kiocb *iocb, const struct iovec *iov,
2145                                  unsigned long nr_segs, loff_t pos)
2146 {
2147         struct iov_iter from;
2148         size_t iov_count;
2149         ssize_t result;
2150         ENTRY;
2151
2152         result = ll_file_get_iov_count(iov, &nr_segs, &iov_count, VERIFY_WRITE);
2153         if (result)
2154                 RETURN(result);
2155
2156         if (!iov_count)
2157                 RETURN(0);
2158
2159 # ifdef HAVE_IOV_ITER_INIT_DIRECTION
2160         iov_iter_init(&from, WRITE, iov, nr_segs, iov_count);
2161 # else /* !HAVE_IOV_ITER_INIT_DIRECTION */
2162         iov_iter_init(&from, iov, nr_segs, iov_count, 0);
2163 # endif /* HAVE_IOV_ITER_INIT_DIRECTION */
2164
2165         result = ll_file_write_iter(iocb, &from);
2166
2167         RETURN(result);
2168 }
2169
2170 static ssize_t ll_file_write(struct file *file, const char __user *buf,
2171                              size_t count, loff_t *ppos)
2172 {
2173         struct iovec   iov = { .iov_base = (void __user *)buf,
2174                                .iov_len = count };
2175         struct kiocb   kiocb;
2176         ssize_t        result;
2177
2178         ENTRY;
2179
2180         if (!count)
2181                 RETURN(0);
2182
2183         init_sync_kiocb(&kiocb, file);
2184         kiocb.ki_pos = *ppos;
2185 #ifdef HAVE_KIOCB_KI_LEFT
2186         kiocb.ki_left = count;
2187 #elif defined(HAVE_KI_NBYTES)
2188         kiocb.ki_nbytes = count;
2189 #endif
2190
2191         result = ll_file_aio_write(&kiocb, &iov, 1, kiocb.ki_pos);
2192         *ppos = kiocb.ki_pos;
2193
2194         RETURN(result);
2195 }
2196 #endif /* !HAVE_FILE_OPERATIONS_READ_WRITE_ITER */
2197
2198 int ll_lov_setstripe_ea_info(struct inode *inode, struct dentry *dentry,
2199                              __u64 flags, struct lov_user_md *lum, int lum_size)
2200 {
2201         struct lookup_intent oit = {
2202                 .it_op = IT_OPEN,
2203                 .it_flags = flags | MDS_OPEN_BY_FID,
2204         };
2205         int rc;
2206         ENTRY;
2207
2208         if ((__swab32(lum->lmm_magic) & le32_to_cpu(LOV_MAGIC_MASK)) ==
2209             le32_to_cpu(LOV_MAGIC_MAGIC)) {
2210                 /* this code will only exist for big-endian systems */
2211                 lustre_swab_lov_user_md(lum, 0);
2212         }
2213
2214         ll_inode_size_lock(inode);
2215         rc = ll_intent_file_open(dentry, lum, lum_size, &oit);
2216         if (rc < 0)
2217                 GOTO(out_unlock, rc);
2218
2219         ll_release_openhandle(dentry, &oit);
2220
2221 out_unlock:
2222         ll_inode_size_unlock(inode);
2223         ll_intent_release(&oit);
2224
2225         RETURN(rc);
2226 }
2227
2228 int ll_lov_getstripe_ea_info(struct inode *inode, const char *filename,
2229                              struct lov_mds_md **lmmp, int *lmm_size,
2230                              struct ptlrpc_request **request)
2231 {
2232         struct ll_sb_info *sbi = ll_i2sbi(inode);
2233         struct mdt_body *body;
2234         struct lov_mds_md *lmm = NULL;
2235         struct ptlrpc_request *req = NULL;
2236         struct md_op_data *op_data;
2237         int rc, lmmsize;
2238
2239         ENTRY;
2240
2241         rc = ll_get_default_mdsize(sbi, &lmmsize);
2242         if (rc)
2243                 RETURN(rc);
2244
2245         op_data = ll_prep_md_op_data(NULL, inode, NULL, filename,
2246                                      strlen(filename), lmmsize,
2247                                      LUSTRE_OPC_ANY, NULL);
2248         if (IS_ERR(op_data))
2249                 RETURN(PTR_ERR(op_data));
2250
2251         op_data->op_valid = OBD_MD_FLEASIZE | OBD_MD_FLDIREA;
2252         rc = md_getattr_name(sbi->ll_md_exp, op_data, &req);
2253         ll_finish_md_op_data(op_data);
2254         if (rc < 0) {
2255                 CDEBUG(D_INFO, "md_getattr_name failed "
2256                        "on %s: rc %d\n", filename, rc);
2257                 GOTO(out, rc);
2258         }
2259
2260         body = req_capsule_server_get(&req->rq_pill, &RMF_MDT_BODY);
2261         LASSERT(body != NULL); /* checked by mdc_getattr_name */
2262
2263         lmmsize = body->mbo_eadatasize;
2264
2265         if (!(body->mbo_valid & (OBD_MD_FLEASIZE | OBD_MD_FLDIREA)) ||
2266             lmmsize == 0)
2267                 GOTO(out, rc = -ENODATA);
2268
2269         lmm = req_capsule_server_sized_get(&req->rq_pill, &RMF_MDT_MD, lmmsize);
2270         LASSERT(lmm != NULL);
2271
2272         if (lmm->lmm_magic != cpu_to_le32(LOV_MAGIC_V1) &&
2273             lmm->lmm_magic != cpu_to_le32(LOV_MAGIC_V3) &&
2274             lmm->lmm_magic != cpu_to_le32(LOV_MAGIC_COMP_V1) &&
2275             lmm->lmm_magic != cpu_to_le32(LOV_MAGIC_FOREIGN))
2276                 GOTO(out, rc = -EPROTO);
2277
2278         /*
2279          * This is coming from the MDS, so is probably in
2280          * little endian. We convert it to host endian before
2281          * passing it to userspace.
2282          */
2283         if (cpu_to_le32(LOV_MAGIC) != LOV_MAGIC) {
2284                 int stripe_count = 0;
2285
2286                 if (lmm->lmm_magic == cpu_to_le32(LOV_MAGIC_V1) ||
2287                     lmm->lmm_magic == cpu_to_le32(LOV_MAGIC_V3)) {
2288                         stripe_count = le16_to_cpu(lmm->lmm_stripe_count);
2289                         if (le32_to_cpu(lmm->lmm_pattern) &
2290                             LOV_PATTERN_F_RELEASED)
2291                                 stripe_count = 0;
2292                         lustre_swab_lov_user_md((struct lov_user_md *)lmm, 0);
2293
2294                         /* if function called for directory - we should
2295                          * avoid swab not existent lsm objects
2296                          */
2297                         if (lmm->lmm_magic == LOV_MAGIC_V1 &&
2298                             S_ISREG(body->mbo_mode))
2299                                 lustre_swab_lov_user_md_objects(
2300                                 ((struct lov_user_md_v1 *)lmm)->lmm_objects,
2301                                 stripe_count);
2302                         else if (lmm->lmm_magic == LOV_MAGIC_V3 &&
2303                                  S_ISREG(body->mbo_mode))
2304                                 lustre_swab_lov_user_md_objects(
2305                                 ((struct lov_user_md_v3 *)lmm)->lmm_objects,
2306                                 stripe_count);
2307                 } else if (lmm->lmm_magic == cpu_to_le32(LOV_MAGIC_COMP_V1)) {
2308                         lustre_swab_lov_comp_md_v1(
2309                                 (struct lov_comp_md_v1 *)lmm);
2310                 }
2311         }
2312
2313         if (lmm->lmm_magic == LOV_MAGIC_COMP_V1) {
2314                 struct lov_comp_md_v1 *comp_v1 = NULL;
2315                 struct lov_comp_md_entry_v1 *ent;
2316                 struct lov_user_md_v1 *v1;
2317                 __u32 off;
2318                 int i = 0;
2319
2320                 comp_v1 = (struct lov_comp_md_v1 *)lmm;
2321                 /* Dump the striping information */
2322                 for (; i < comp_v1->lcm_entry_count; i++) {
2323                         ent = &comp_v1->lcm_entries[i];
2324                         off = ent->lcme_offset;
2325                         v1 = (struct lov_user_md_v1 *)((char *)lmm + off);
2326                         CDEBUG(D_INFO,
2327                                "comp[%d]: stripe_count=%u, stripe_size=%u\n",
2328                                i, v1->lmm_stripe_count, v1->lmm_stripe_size);
2329                 }
2330
2331                 /**
2332                  * Return valid stripe_count and stripe_size instead of 0 for
2333                  * DoM files to avoid divide-by-zero for older userspace that
2334                  * calls this ioctl, e.g. lustre ADIO driver.
2335                  */
2336                 if (lmm->lmm_stripe_count == 0)
2337                         lmm->lmm_stripe_count = 1;
2338                 if (lmm->lmm_stripe_size == 0) {
2339                         /* Since the first component of the file data is placed
2340                          * on the MDT for faster access, the stripe_size of the
2341                          * second one is always that applications which are
2342                          * doing large IOs.
2343                          */
2344                         if (lmm->lmm_pattern == LOV_PATTERN_MDT)
2345                                 i = comp_v1->lcm_entry_count > 1 ? 1 : 0;
2346                         else
2347                                 i = comp_v1->lcm_entry_count > 1 ?
2348                                     comp_v1->lcm_entry_count - 1 : 0;
2349                         ent = &comp_v1->lcm_entries[i];
2350                         off = ent->lcme_offset;
2351                         v1 = (struct lov_user_md_v1 *)((char *)lmm + off);
2352                         lmm->lmm_stripe_size = v1->lmm_stripe_size;
2353                 }
2354         }
2355 out:
2356         *lmmp = lmm;
2357         *lmm_size = lmmsize;
2358         *request = req;
2359         RETURN(rc);
2360 }
2361
2362 static int ll_lov_setea(struct inode *inode, struct file *file,
2363                         void __user *arg)
2364 {
2365         __u64                    flags = MDS_OPEN_HAS_OBJS | FMODE_WRITE;
2366         struct lov_user_md      *lump;
2367         int                      lum_size = sizeof(struct lov_user_md) +
2368                                             sizeof(struct lov_user_ost_data);
2369         int                      rc;
2370         ENTRY;
2371
2372         if (!capable(CAP_SYS_ADMIN))
2373                 RETURN(-EPERM);
2374
2375         OBD_ALLOC_LARGE(lump, lum_size);
2376         if (lump == NULL)
2377                 RETURN(-ENOMEM);
2378
2379         if (copy_from_user(lump, arg, lum_size))
2380                 GOTO(out_lump, rc = -EFAULT);
2381
2382         rc = ll_lov_setstripe_ea_info(inode, file_dentry(file), flags, lump,
2383                                       lum_size);
2384         cl_lov_delay_create_clear(&file->f_flags);
2385
2386 out_lump:
2387         OBD_FREE_LARGE(lump, lum_size);
2388         RETURN(rc);
2389 }
2390
2391 static int ll_file_getstripe(struct inode *inode, void __user *lum, size_t size)
2392 {
2393         struct lu_env   *env;
2394         __u16           refcheck;
2395         int             rc;
2396         ENTRY;
2397
2398         env = cl_env_get(&refcheck);
2399         if (IS_ERR(env))
2400                 RETURN(PTR_ERR(env));
2401
2402         rc = cl_object_getstripe(env, ll_i2info(inode)->lli_clob, lum, size);
2403         cl_env_put(env, &refcheck);
2404         RETURN(rc);
2405 }
2406
2407 static int ll_lov_setstripe(struct inode *inode, struct file *file,
2408                             void __user *arg)
2409 {
2410         struct lov_user_md __user *lum = (struct lov_user_md __user *)arg;
2411         struct lov_user_md        *klum;
2412         int                        lum_size, rc;
2413         __u64                      flags = FMODE_WRITE;
2414         ENTRY;
2415
2416         rc = ll_copy_user_md(lum, &klum);
2417         if (rc < 0)
2418                 RETURN(rc);
2419
2420         lum_size = rc;
2421         rc = ll_lov_setstripe_ea_info(inode, file_dentry(file), flags, klum,
2422                                       lum_size);
2423         if (!rc) {
2424                 __u32 gen;
2425
2426                 rc = put_user(0, &lum->lmm_stripe_count);
2427                 if (rc)
2428                         GOTO(out, rc);
2429
2430                 rc = ll_layout_refresh(inode, &gen);
2431                 if (rc)
2432                         GOTO(out, rc);
2433
2434                 rc = ll_file_getstripe(inode, arg, lum_size);
2435                 if (S_ISREG(inode->i_mode) && IS_ENCRYPTED(inode) &&
2436                     ll_i2info(inode)->lli_clob) {
2437                         struct iattr attr = { 0 };
2438
2439                         rc = cl_setattr_ost(ll_i2info(inode)->lli_clob, &attr,
2440                                             OP_XVALID_FLAGS, LUSTRE_ENCRYPT_FL);
2441                 }
2442         }
2443         cl_lov_delay_create_clear(&file->f_flags);
2444
2445 out:
2446         OBD_FREE_LARGE(klum, lum_size);
2447         RETURN(rc);
2448 }
2449
2450
2451 static int
2452 ll_get_grouplock(struct inode *inode, struct file *file, unsigned long arg)
2453 {
2454         struct ll_inode_info *lli = ll_i2info(inode);
2455         struct cl_object *obj = lli->lli_clob;
2456         struct ll_file_data *fd = file->private_data;
2457         struct ll_grouplock grouplock;
2458         int rc;
2459         ENTRY;
2460
2461         if (arg == 0) {
2462                 CWARN("group id for group lock must not be 0\n");
2463                 RETURN(-EINVAL);
2464         }
2465
2466         if (ll_file_nolock(file))
2467                 RETURN(-EOPNOTSUPP);
2468 retry:
2469         if (file->f_flags & O_NONBLOCK) {
2470                 if (!mutex_trylock(&lli->lli_group_mutex))
2471                         RETURN(-EAGAIN);
2472         } else
2473                 mutex_lock(&lli->lli_group_mutex);
2474
2475         if (fd->fd_flags & LL_FILE_GROUP_LOCKED) {
2476                 CWARN("group lock already existed with gid %lu\n",
2477                       fd->fd_grouplock.lg_gid);
2478                 GOTO(out, rc = -EINVAL);
2479         }
2480         if (arg != lli->lli_group_gid && lli->lli_group_users != 0) {
2481                 if (file->f_flags & O_NONBLOCK)
2482                         GOTO(out, rc = -EAGAIN);
2483                 mutex_unlock(&lli->lli_group_mutex);
2484                 wait_var_event(&lli->lli_group_users, !lli->lli_group_users);
2485                 GOTO(retry, rc = 0);
2486         }
2487         LASSERT(fd->fd_grouplock.lg_lock == NULL);
2488
2489         /**
2490          * XXX: group lock needs to protect all OST objects while PFL
2491          * can add new OST objects during the IO, so we'd instantiate
2492          * all OST objects before getting its group lock.
2493          */
2494         if (obj) {
2495                 struct lu_env *env;
2496                 __u16 refcheck;
2497                 struct cl_layout cl = {
2498                         .cl_is_composite = false,
2499                 };
2500                 struct lu_extent ext = {
2501                         .e_start = 0,
2502                         .e_end = OBD_OBJECT_EOF,
2503                 };
2504
2505                 env = cl_env_get(&refcheck);
2506                 if (IS_ERR(env))
2507                         GOTO(out, rc = PTR_ERR(env));
2508
2509                 rc = cl_object_layout_get(env, obj, &cl);
2510                 if (rc >= 0 && cl.cl_is_composite)
2511                         rc = ll_layout_write_intent(inode, LAYOUT_INTENT_WRITE,
2512                                                     &ext);
2513
2514                 cl_env_put(env, &refcheck);
2515                 if (rc < 0)
2516                         GOTO(out, rc);
2517         }
2518
2519         rc = cl_get_grouplock(ll_i2info(inode)->lli_clob,
2520                               arg, (file->f_flags & O_NONBLOCK), &grouplock);
2521
2522         if (rc)
2523                 GOTO(out, rc);
2524
2525         fd->fd_flags |= LL_FILE_GROUP_LOCKED;
2526         fd->fd_grouplock = grouplock;
2527         if (lli->lli_group_users == 0)
2528                 lli->lli_group_gid = grouplock.lg_gid;
2529         lli->lli_group_users++;
2530
2531         CDEBUG(D_INFO, "group lock %lu obtained\n", arg);
2532 out:
2533         mutex_unlock(&lli->lli_group_mutex);
2534
2535         RETURN(rc);
2536 }
2537
2538 static int ll_put_grouplock(struct inode *inode, struct file *file,
2539                             unsigned long arg)
2540 {
2541         struct ll_inode_info   *lli = ll_i2info(inode);
2542         struct ll_file_data    *fd = file->private_data;
2543         struct ll_grouplock     grouplock;
2544         int                     rc;
2545         ENTRY;
2546
2547         mutex_lock(&lli->lli_group_mutex);
2548         if (!(fd->fd_flags & LL_FILE_GROUP_LOCKED)) {
2549                 CWARN("no group lock held\n");
2550                 GOTO(out, rc = -EINVAL);
2551         }
2552
2553         LASSERT(fd->fd_grouplock.lg_lock != NULL);
2554
2555         if (fd->fd_grouplock.lg_gid != arg) {
2556                 CWARN("group lock %lu doesn't match current id %lu\n",
2557                       arg, fd->fd_grouplock.lg_gid);
2558                 GOTO(out, rc = -EINVAL);
2559         }
2560
2561         grouplock = fd->fd_grouplock;
2562         memset(&fd->fd_grouplock, 0, sizeof(fd->fd_grouplock));
2563         fd->fd_flags &= ~LL_FILE_GROUP_LOCKED;
2564
2565         cl_put_grouplock(&grouplock);
2566
2567         lli->lli_group_users--;
2568         if (lli->lli_group_users == 0) {
2569                 lli->lli_group_gid = 0;
2570                 wake_up_var(&lli->lli_group_users);
2571         }
2572         CDEBUG(D_INFO, "group lock %lu released\n", arg);
2573         GOTO(out, rc = 0);
2574 out:
2575         mutex_unlock(&lli->lli_group_mutex);
2576
2577         RETURN(rc);
2578 }
2579
2580 /**
2581  * Close inode open handle
2582  *
2583  * \param dentry [in]     dentry which contains the inode
2584  * \param it     [in,out] intent which contains open info and result
2585  *
2586  * \retval 0     success
2587  * \retval <0    failure
2588  */
2589 int ll_release_openhandle(struct dentry *dentry, struct lookup_intent *it)
2590 {
2591         struct inode *inode = dentry->d_inode;
2592         struct obd_client_handle *och;
2593         int rc;
2594         ENTRY;
2595
2596         LASSERT(inode);
2597
2598         /* Root ? Do nothing. */
2599         if (is_root_inode(inode))
2600                 RETURN(0);
2601
2602         /* No open handle to close? Move away */
2603         if (!it_disposition(it, DISP_OPEN_OPEN))
2604                 RETURN(0);
2605
2606         LASSERT(it_open_error(DISP_OPEN_OPEN, it) == 0);
2607
2608         OBD_ALLOC(och, sizeof(*och));
2609         if (!och)
2610                 GOTO(out, rc = -ENOMEM);
2611
2612         rc = ll_och_fill(ll_i2sbi(inode)->ll_md_exp, it, och);
2613         if (rc)
2614                 GOTO(out, rc);
2615
2616         rc = ll_close_inode_openhandle(inode, och, 0, NULL);
2617 out:
2618         /* this one is in place of ll_file_open */
2619         if (it_disposition(it, DISP_ENQ_OPEN_REF)) {
2620                 ptlrpc_req_finished(it->it_request);
2621                 it_clear_disposition(it, DISP_ENQ_OPEN_REF);
2622         }
2623         RETURN(rc);
2624 }
2625
2626 /**
2627  * Get size for inode for which FIEMAP mapping is requested.
2628  * Make the FIEMAP get_info call and returns the result.
2629  * \param fiemap        kernel buffer to hold extens
2630  * \param num_bytes     kernel buffer size
2631  */
2632 static int ll_do_fiemap(struct inode *inode, struct fiemap *fiemap,
2633                         size_t num_bytes)
2634 {
2635         struct lu_env                   *env;
2636         __u16                           refcheck;
2637         int                             rc = 0;
2638         struct ll_fiemap_info_key       fmkey = { .lfik_name = KEY_FIEMAP, };
2639         ENTRY;
2640
2641         /* Checks for fiemap flags */
2642         if (fiemap->fm_flags & ~LUSTRE_FIEMAP_FLAGS_COMPAT) {
2643                 fiemap->fm_flags &= ~LUSTRE_FIEMAP_FLAGS_COMPAT;
2644                 return -EBADR;
2645         }
2646
2647         /* Check for FIEMAP_FLAG_SYNC */
2648         if (fiemap->fm_flags & FIEMAP_FLAG_SYNC) {
2649                 rc = filemap_fdatawrite(inode->i_mapping);
2650                 if (rc)
2651                         return rc;
2652         }
2653
2654         env = cl_env_get(&refcheck);
2655         if (IS_ERR(env))
2656                 RETURN(PTR_ERR(env));
2657
2658         if (i_size_read(inode) == 0) {
2659                 rc = ll_glimpse_size(inode);
2660                 if (rc)
2661                         GOTO(out, rc);
2662         }
2663
2664         fmkey.lfik_oa.o_valid = OBD_MD_FLID | OBD_MD_FLGROUP;
2665         obdo_from_inode(&fmkey.lfik_oa, inode, OBD_MD_FLSIZE);
2666         obdo_set_parent_fid(&fmkey.lfik_oa, &ll_i2info(inode)->lli_fid);
2667
2668         /* If filesize is 0, then there would be no objects for mapping */
2669         if (fmkey.lfik_oa.o_size == 0) {
2670                 fiemap->fm_mapped_extents = 0;
2671                 GOTO(out, rc = 0);
2672         }
2673
2674         fmkey.lfik_fiemap = *fiemap;
2675
2676         rc = cl_object_fiemap(env, ll_i2info(inode)->lli_clob,
2677                               &fmkey, fiemap, &num_bytes);
2678 out:
2679         cl_env_put(env, &refcheck);
2680         RETURN(rc);
2681 }
2682
2683 int ll_fid2path(struct inode *inode, void __user *arg)
2684 {
2685         struct obd_export       *exp = ll_i2mdexp(inode);
2686         const struct getinfo_fid2path __user *gfin = arg;
2687         __u32                    pathlen;
2688         struct getinfo_fid2path *gfout;
2689         size_t                   outsize;
2690         int                      rc;
2691
2692         ENTRY;
2693
2694         if (!capable(CAP_DAC_READ_SEARCH) &&
2695             !(ll_i2sbi(inode)->ll_flags & LL_SBI_USER_FID2PATH))
2696                 RETURN(-EPERM);
2697
2698         /* Only need to get the buflen */
2699         if (get_user(pathlen, &gfin->gf_pathlen))
2700                 RETURN(-EFAULT);
2701
2702         if (pathlen > PATH_MAX)
2703                 RETURN(-EINVAL);
2704
2705         outsize = sizeof(*gfout) + pathlen;
2706         OBD_ALLOC(gfout, outsize);
2707         if (gfout == NULL)
2708                 RETURN(-ENOMEM);
2709
2710         if (copy_from_user(gfout, arg, sizeof(*gfout)))
2711                 GOTO(gf_free, rc = -EFAULT);
2712         /* append root FID after gfout to let MDT know the root FID so that it
2713          * can lookup the correct path, this is mainly for fileset.
2714          * old server without fileset mount support will ignore this. */
2715         *gfout->gf_u.gf_root_fid = *ll_inode2fid(inode);
2716
2717         /* Call mdc_iocontrol */
2718         rc = obd_iocontrol(OBD_IOC_FID2PATH, exp, outsize, gfout, NULL);
2719         if (rc != 0)
2720                 GOTO(gf_free, rc);
2721
2722         if (copy_to_user(arg, gfout, outsize))
2723                 rc = -EFAULT;
2724
2725 gf_free:
2726         OBD_FREE(gfout, outsize);
2727         RETURN(rc);
2728 }
2729
2730 static int
2731 ll_ioc_data_version(struct inode *inode, struct ioc_data_version *ioc)
2732 {
2733         struct cl_object *obj = ll_i2info(inode)->lli_clob;
2734         struct lu_env *env;
2735         struct cl_io *io;
2736         __u16  refcheck;
2737         int result;
2738
2739         ENTRY;
2740
2741         ioc->idv_version = 0;
2742         ioc->idv_layout_version = UINT_MAX;
2743
2744         /* If no file object initialized, we consider its version is 0. */
2745         if (obj == NULL)
2746                 RETURN(0);
2747
2748         env = cl_env_get(&refcheck);
2749         if (IS_ERR(env))
2750                 RETURN(PTR_ERR(env));
2751
2752         io = vvp_env_thread_io(env);
2753         io->ci_obj = obj;
2754         io->u.ci_data_version.dv_data_version = 0;
2755         io->u.ci_data_version.dv_layout_version = UINT_MAX;
2756         io->u.ci_data_version.dv_flags = ioc->idv_flags;
2757
2758 restart:
2759         if (cl_io_init(env, io, CIT_DATA_VERSION, io->ci_obj) == 0)
2760                 result = cl_io_loop(env, io);
2761         else
2762                 result = io->ci_result;
2763
2764         ioc->idv_version = io->u.ci_data_version.dv_data_version;
2765         ioc->idv_layout_version = io->u.ci_data_version.dv_layout_version;
2766
2767         cl_io_fini(env, io);
2768
2769         if (unlikely(io->ci_need_restart))
2770                 goto restart;
2771
2772         cl_env_put(env, &refcheck);
2773
2774         RETURN(result);
2775 }
2776
2777 /*
2778  * Read the data_version for inode.
2779  *
2780  * This value is computed using stripe object version on OST.
2781  * Version is computed using server side locking.
2782  *
2783  * @param flags if do sync on the OST side;
2784  *              0: no sync
2785  *              LL_DV_RD_FLUSH: flush dirty pages, LCK_PR on OSTs
2786  *              LL_DV_WR_FLUSH: drop all caching pages, LCK_PW on OSTs
2787  */
2788 int ll_data_version(struct inode *inode, __u64 *data_version, int flags)
2789 {
2790         struct ioc_data_version ioc = { .idv_flags = flags };
2791         int rc;
2792
2793         rc = ll_ioc_data_version(inode, &ioc);
2794         if (!rc)
2795                 *data_version = ioc.idv_version;
2796
2797         return rc;
2798 }
2799
2800 /*
2801  * Trigger a HSM release request for the provided inode.
2802  */
2803 int ll_hsm_release(struct inode *inode)
2804 {
2805         struct lu_env *env;
2806         struct obd_client_handle *och = NULL;
2807         __u64 data_version = 0;
2808         int rc;
2809         __u16 refcheck;
2810         ENTRY;
2811
2812         CDEBUG(D_INODE, "%s: Releasing file "DFID".\n",
2813                ll_i2sbi(inode)->ll_fsname,
2814                PFID(&ll_i2info(inode)->lli_fid));
2815
2816         och = ll_lease_open(inode, NULL, FMODE_WRITE, MDS_OPEN_RELEASE);
2817         if (IS_ERR(och))
2818                 GOTO(out, rc = PTR_ERR(och));
2819
2820         /* Grab latest data_version and [am]time values */
2821         rc = ll_data_version(inode, &data_version, LL_DV_WR_FLUSH);
2822         if (rc != 0)
2823                 GOTO(out, rc);
2824
2825         env = cl_env_get(&refcheck);
2826         if (IS_ERR(env))
2827                 GOTO(out, rc = PTR_ERR(env));
2828
2829         rc = ll_merge_attr(env, inode);
2830         cl_env_put(env, &refcheck);
2831
2832         /* If error happen, we have the wrong size for a file.
2833          * Don't release it.
2834          */
2835         if (rc != 0)
2836                 GOTO(out, rc);
2837
2838         /* Release the file.
2839          * NB: lease lock handle is released in mdc_hsm_release_pack() because
2840          * we still need it to pack l_remote_handle to MDT. */
2841         rc = ll_close_inode_openhandle(inode, och, MDS_HSM_RELEASE,
2842                                        &data_version);
2843         och = NULL;
2844
2845         EXIT;
2846 out:
2847         if (och != NULL && !IS_ERR(och)) /* close the file */
2848                 ll_lease_close(och, inode, NULL);
2849
2850         return rc;
2851 }
2852
2853 struct ll_swap_stack {
2854         __u64                    dv1;
2855         __u64                    dv2;
2856         struct inode            *inode1;
2857         struct inode            *inode2;
2858         bool                     check_dv1;
2859         bool                     check_dv2;
2860 };
2861
2862 static int ll_swap_layouts(struct file *file1, struct file *file2,
2863                            struct lustre_swap_layouts *lsl)
2864 {
2865         struct mdc_swap_layouts  msl;
2866         struct md_op_data       *op_data;
2867         __u32                    gid;
2868         __u64                    dv;
2869         struct ll_swap_stack    *llss = NULL;
2870         int                      rc;
2871
2872         OBD_ALLOC_PTR(llss);
2873         if (llss == NULL)
2874                 RETURN(-ENOMEM);
2875
2876         llss->inode1 = file_inode(file1);
2877         llss->inode2 = file_inode(file2);
2878
2879         rc = ll_check_swap_layouts_validity(llss->inode1, llss->inode2);
2880         if (rc < 0)
2881                 GOTO(free, rc);
2882
2883         /* we use 2 bool because it is easier to swap than 2 bits */
2884         if (lsl->sl_flags & SWAP_LAYOUTS_CHECK_DV1)
2885                 llss->check_dv1 = true;
2886
2887         if (lsl->sl_flags & SWAP_LAYOUTS_CHECK_DV2)
2888                 llss->check_dv2 = true;
2889
2890         /* we cannot use lsl->sl_dvX directly because we may swap them */
2891         llss->dv1 = lsl->sl_dv1;
2892         llss->dv2 = lsl->sl_dv2;
2893
2894         rc = lu_fid_cmp(ll_inode2fid(llss->inode1), ll_inode2fid(llss->inode2));
2895         if (rc == 0) /* same file, done! */
2896                 GOTO(free, rc);
2897
2898         if (rc < 0) { /* sequentialize it */
2899                 swap(llss->inode1, llss->inode2);
2900                 swap(file1, file2);
2901                 swap(llss->dv1, llss->dv2);
2902                 swap(llss->check_dv1, llss->check_dv2);
2903         }
2904
2905         gid = lsl->sl_gid;
2906         if (gid != 0) { /* application asks to flush dirty cache */
2907                 rc = ll_get_grouplock(llss->inode1, file1, gid);
2908                 if (rc < 0)
2909                         GOTO(free, rc);
2910
2911                 rc = ll_get_grouplock(llss->inode2, file2, gid);
2912                 if (rc < 0) {
2913                         ll_put_grouplock(llss->inode1, file1, gid);
2914                         GOTO(free, rc);
2915                 }
2916         }
2917
2918         /* ultimate check, before swaping the layouts we check if
2919          * dataversion has changed (if requested) */
2920         if (llss->check_dv1) {
2921                 rc = ll_data_version(llss->inode1, &dv, 0);
2922                 if (rc)
2923                         GOTO(putgl, rc);
2924                 if (dv != llss->dv1)
2925                         GOTO(putgl, rc = -EAGAIN);
2926         }
2927
2928         if (llss->check_dv2) {
2929                 rc = ll_data_version(llss->inode2, &dv, 0);
2930                 if (rc)
2931                         GOTO(putgl, rc);
2932                 if (dv != llss->dv2)
2933                         GOTO(putgl, rc = -EAGAIN);
2934         }
2935
2936         /* struct md_op_data is used to send the swap args to the mdt
2937          * only flags is missing, so we use struct mdc_swap_layouts
2938          * through the md_op_data->op_data */
2939         /* flags from user space have to be converted before they are send to
2940          * server, no flag is sent today, they are only used on the client */
2941         msl.msl_flags = 0;
2942         rc = -ENOMEM;
2943         op_data = ll_prep_md_op_data(NULL, llss->inode1, llss->inode2, NULL, 0,
2944                                      0, LUSTRE_OPC_ANY, &msl);
2945         if (IS_ERR(op_data))
2946                 GOTO(free, rc = PTR_ERR(op_data));
2947
2948         rc = obd_iocontrol(LL_IOC_LOV_SWAP_LAYOUTS, ll_i2mdexp(llss->inode1),
2949                            sizeof(*op_data), op_data, NULL);
2950         ll_finish_md_op_data(op_data);
2951
2952         if (rc < 0)
2953                 GOTO(putgl, rc);
2954
2955 putgl:
2956         if (gid != 0) {
2957                 ll_put_grouplock(llss->inode2, file2, gid);
2958                 ll_put_grouplock(llss->inode1, file1, gid);
2959         }
2960
2961 free:
2962         if (llss != NULL)
2963                 OBD_FREE_PTR(llss);
2964
2965         RETURN(rc);
2966 }
2967
2968 int ll_hsm_state_set(struct inode *inode, struct hsm_state_set *hss)
2969 {
2970         struct obd_export *exp = ll_i2mdexp(inode);
2971         struct md_op_data *op_data;
2972         int rc;
2973         ENTRY;
2974
2975         /* Detect out-of range masks */
2976         if ((hss->hss_setmask | hss->hss_clearmask) & ~HSM_FLAGS_MASK)
2977                 RETURN(-EINVAL);
2978
2979         /* Non-root users are forbidden to set or clear flags which are
2980          * NOT defined in HSM_USER_MASK. */
2981         if (((hss->hss_setmask | hss->hss_clearmask) & ~HSM_USER_MASK) &&
2982             !capable(CAP_SYS_ADMIN))
2983                 RETURN(-EPERM);
2984
2985         if (!exp_connect_archive_id_array(exp)) {
2986                 /* Detect out-of range archive id */
2987                 if ((hss->hss_valid & HSS_ARCHIVE_ID) &&
2988                     (hss->hss_archive_id > LL_HSM_ORIGIN_MAX_ARCHIVE))
2989                         RETURN(-EINVAL);
2990         }
2991
2992         op_data = ll_prep_md_op_data(NULL, inode, NULL, NULL, 0, 0,
2993                                      LUSTRE_OPC_ANY, hss);
2994         if (IS_ERR(op_data))
2995                 RETURN(PTR_ERR(op_data));
2996
2997         rc = obd_iocontrol(LL_IOC_HSM_STATE_SET, exp, sizeof(*op_data),
2998                            op_data, NULL);
2999
3000         ll_finish_md_op_data(op_data);
3001
3002         RETURN(rc);
3003 }
3004
3005 static int ll_hsm_import(struct inode *inode, struct file *file,
3006                          struct hsm_user_import *hui)
3007 {
3008         struct hsm_state_set    *hss = NULL;
3009         struct iattr            *attr = NULL;
3010         int                      rc;
3011         ENTRY;
3012
3013         if (!S_ISREG(inode->i_mode))
3014                 RETURN(-EINVAL);
3015
3016         /* set HSM flags */
3017         OBD_ALLOC_PTR(hss);
3018         if (hss == NULL)
3019                 GOTO(out, rc = -ENOMEM);
3020
3021         hss->hss_valid = HSS_SETMASK | HSS_ARCHIVE_ID;
3022         hss->hss_archive_id = hui->hui_archive_id;
3023         hss->hss_setmask = HS_ARCHIVED | HS_EXISTS | HS_RELEASED;
3024         rc = ll_hsm_state_set(inode, hss);
3025         if (rc != 0)
3026                 GOTO(out, rc);
3027
3028         OBD_ALLOC_PTR(attr);
3029         if (attr == NULL)
3030                 GOTO(out, rc = -ENOMEM);
3031
3032         attr->ia_mode = hui->hui_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
3033         attr->ia_mode |= S_IFREG;
3034         attr->ia_uid = make_kuid(&init_user_ns, hui->hui_uid);
3035         attr->ia_gid = make_kgid(&init_user_ns, hui->hui_gid);
3036         attr->ia_size = hui->hui_size;
3037         attr->ia_mtime.tv_sec = hui->hui_mtime;
3038         attr->ia_mtime.tv_nsec = hui->hui_mtime_ns;
3039         attr->ia_atime.tv_sec = hui->hui_atime;
3040         attr->ia_atime.tv_nsec = hui->hui_atime_ns;
3041
3042         attr->ia_valid = ATTR_SIZE | ATTR_MODE | ATTR_FORCE |
3043                          ATTR_UID | ATTR_GID |
3044                          ATTR_MTIME | ATTR_MTIME_SET |
3045                          ATTR_ATIME | ATTR_ATIME_SET;
3046
3047         inode_lock(inode);
3048
3049         rc = ll_setattr_raw(file_dentry(file), attr, 0, true);
3050         if (rc == -ENODATA)
3051                 rc = 0;
3052
3053         inode_unlock(inode);
3054
3055 out:
3056         if (hss != NULL)
3057                 OBD_FREE_PTR(hss);
3058
3059         if (attr != NULL)
3060                 OBD_FREE_PTR(attr);
3061
3062         RETURN(rc);
3063 }
3064
3065 static inline long ll_lease_type_from_fmode(fmode_t fmode)
3066 {
3067         return ((fmode & FMODE_READ) ? LL_LEASE_RDLCK : 0) |
3068                ((fmode & FMODE_WRITE) ? LL_LEASE_WRLCK : 0);
3069 }
3070
3071 static int ll_file_futimes_3(struct file *file, const struct ll_futimes_3 *lfu)
3072 {
3073         struct inode *inode = file_inode(file);
3074         struct iattr ia = {
3075                 .ia_valid = ATTR_ATIME | ATTR_ATIME_SET |
3076                             ATTR_MTIME | ATTR_MTIME_SET |
3077                             ATTR_CTIME,
3078                 .ia_atime = {
3079                         .tv_sec = lfu->lfu_atime_sec,
3080                         .tv_nsec = lfu->lfu_atime_nsec,
3081                 },
3082                 .ia_mtime = {
3083                         .tv_sec = lfu->lfu_mtime_sec,
3084                         .tv_nsec = lfu->lfu_mtime_nsec,
3085                 },
3086                 .ia_ctime = {
3087                         .tv_sec = lfu->lfu_ctime_sec,
3088                         .tv_nsec = lfu->lfu_ctime_nsec,
3089                 },
3090         };
3091         int rc;
3092         ENTRY;
3093
3094         if (!capable(CAP_SYS_ADMIN))
3095                 RETURN(-EPERM);
3096
3097         if (!S_ISREG(inode->i_mode))
3098                 RETURN(-EINVAL);
3099
3100         inode_lock(inode);
3101         rc = ll_setattr_raw(file_dentry(file), &ia, OP_XVALID_CTIME_SET,
3102                             false);
3103         inode_unlock(inode);
3104
3105         RETURN(rc);
3106 }
3107
3108 static enum cl_lock_mode cl_mode_user_to_kernel(enum lock_mode_user mode)
3109 {
3110         switch (mode) {
3111         case MODE_READ_USER:
3112                 return CLM_READ;
3113         case MODE_WRITE_USER:
3114                 return CLM_WRITE;
3115         default:
3116                 return -EINVAL;
3117         }
3118 }
3119
3120 static const char *const user_lockname[] = LOCK_MODE_NAMES;
3121
3122 /* Used to allow the upper layers of the client to request an LDLM lock
3123  * without doing an actual read or write.
3124  *
3125  * Used for ladvise lockahead to manually request specific locks.
3126  *
3127  * \param[in] file      file this ladvise lock request is on
3128  * \param[in] ladvise   ladvise struct describing this lock request
3129  *
3130  * \retval 0            success, no detailed result available (sync requests
3131  *                      and requests sent to the server [not handled locally]
3132  *                      cannot return detailed results)
3133  * \retval LLA_RESULT_{SAME,DIFFERENT} - detailed result of the lock request,
3134  *                                       see definitions for details.
3135  * \retval negative     negative errno on error
3136  */
3137 int ll_file_lock_ahead(struct file *file, struct llapi_lu_ladvise *ladvise)
3138 {
3139         struct lu_env *env = NULL;
3140         struct cl_io *io  = NULL;
3141         struct cl_lock *lock = NULL;
3142         struct cl_lock_descr *descr = NULL;
3143         struct dentry *dentry = file->f_path.dentry;
3144         struct inode *inode = dentry->d_inode;
3145         enum cl_lock_mode cl_mode;
3146         off_t start = ladvise->lla_start;
3147         off_t end = ladvise->lla_end;
3148         int result;
3149         __u16 refcheck;
3150
3151         ENTRY;
3152
3153         CDEBUG(D_VFSTRACE,
3154                "Lock request: file=%pd, inode=%p, mode=%s start=%llu, end=%llu\n",
3155                dentry, dentry->d_inode,
3156                user_lockname[ladvise->lla_lockahead_mode], (__u64) start,
3157                (__u64) end);
3158
3159         cl_mode = cl_mode_user_to_kernel(ladvise->lla_lockahead_mode);
3160         if (cl_mode < 0)
3161                 GOTO(out, result = cl_mode);
3162
3163         /* Get IO environment */
3164         result = cl_io_get(inode, &env, &io, &refcheck);
3165         if (result <= 0)
3166                 GOTO(out, result);
3167
3168         result = cl_io_init(env, io, CIT_MISC, io->ci_obj);
3169         if (result > 0) {
3170                 /*
3171                  * nothing to do for this io. This currently happens when
3172                  * stripe sub-object's are not yet created.
3173                  */
3174                 result = io->ci_result;
3175         } else if (result == 0) {
3176                 lock = vvp_env_lock(env);
3177                 descr = &lock->cll_descr;
3178
3179                 descr->cld_obj   = io->ci_obj;
3180                 /* Convert byte offsets to pages */
3181                 descr->cld_start = cl_index(io->ci_obj, start);
3182                 descr->cld_end   = cl_index(io->ci_obj, end);
3183                 descr->cld_mode  = cl_mode;
3184                 /* CEF_MUST is used because we do not want to convert a
3185                  * lockahead request to a lockless lock */
3186                 descr->cld_enq_flags = CEF_MUST | CEF_LOCK_NO_EXPAND;
3187
3188                 if (ladvise->lla_peradvice_flags & LF_ASYNC)
3189                         descr->cld_enq_flags |= CEF_SPECULATIVE;
3190
3191                 result = cl_lock_request(env, io, lock);
3192
3193                 /* On success, we need to release the lock */
3194                 if (result >= 0)
3195                         cl_lock_release(env, lock);
3196         }
3197         cl_io_fini(env, io);
3198         cl_env_put(env, &refcheck);
3199
3200         /* -ECANCELED indicates a matching lock with a different extent
3201          * was already present, and -EEXIST indicates a matching lock
3202          * on exactly the same extent was already present.
3203          * We convert them to positive values for userspace to make
3204          * recognizing true errors easier.
3205          * Note we can only return these detailed results on async requests,
3206          * as sync requests look the same as i/o requests for locking. */
3207         if (result == -ECANCELED)
3208                 result = LLA_RESULT_DIFFERENT;
3209         else if (result == -EEXIST)
3210                 result = LLA_RESULT_SAME;
3211
3212 out:
3213         RETURN(result);
3214 }
3215 static const char *const ladvise_names[] = LU_LADVISE_NAMES;
3216
3217 static int ll_ladvise_sanity(struct inode *inode,
3218                              struct llapi_lu_ladvise *ladvise)
3219 {
3220         struct ll_sb_info *sbi = ll_i2sbi(inode);
3221         enum lu_ladvise_type advice = ladvise->lla_advice;
3222         /* Note the peradvice flags is a 32 bit field, so per advice flags must
3223          * be in the first 32 bits of enum ladvise_flags */
3224         __u32 flags = ladvise->lla_peradvice_flags;
3225         /* 3 lines at 80 characters per line, should be plenty */
3226         int rc = 0;
3227
3228         if (advice > LU_LADVISE_MAX || advice == LU_LADVISE_INVALID) {
3229                 rc = -EINVAL;
3230                 CDEBUG(D_VFSTRACE,
3231                        "%s: advice with value '%d' not recognized, last supported advice is %s (value '%d'): rc = %d\n",
3232                        sbi->ll_fsname, advice,
3233                        ladvise_names[LU_LADVISE_MAX-1], LU_LADVISE_MAX-1, rc);
3234                 GOTO(out, rc);
3235         }
3236
3237         /* Per-advice checks */
3238         switch (advice) {
3239         case LU_LADVISE_LOCKNOEXPAND:
3240                 if (flags & ~LF_LOCKNOEXPAND_MASK) {
3241                         rc = -EINVAL;
3242                         CDEBUG(D_VFSTRACE, "%s: Invalid flags (%x) for %s: "
3243                                "rc = %d\n", sbi->ll_fsname, flags,
3244                                ladvise_names[advice], rc);
3245                         GOTO(out, rc);
3246                 }
3247                 break;
3248         case LU_LADVISE_LOCKAHEAD:
3249                 /* Currently only READ and WRITE modes can be requested */
3250                 if (ladvise->lla_lockahead_mode >= MODE_MAX_USER ||
3251                     ladvise->lla_lockahead_mode == 0) {
3252                         rc = -EINVAL;
3253                         CDEBUG(D_VFSTRACE, "%s: Invalid mode (%d) for %s: "
3254                                "rc = %d\n", sbi->ll_fsname,
3255                                ladvise->lla_lockahead_mode,
3256                                ladvise_names[advice], rc);
3257                         GOTO(out, rc);
3258                 }
3259                 /* fallthrough */
3260         case LU_LADVISE_WILLREAD:
3261         case LU_LADVISE_DONTNEED:
3262         default:
3263                 /* Note fall through above - These checks apply to all advices
3264                  * except LOCKNOEXPAND */
3265                 if (flags & ~LF_DEFAULT_MASK) {
3266                         rc = -EINVAL;
3267                         CDEBUG(D_VFSTRACE, "%s: Invalid flags (%x) for %s: "
3268                                "rc = %d\n", sbi->ll_fsname, flags,
3269                                ladvise_names[advice], rc);
3270                         GOTO(out, rc);
3271                 }
3272                 if (ladvise->lla_start >= ladvise->lla_end) {
3273                         rc = -EINVAL;
3274                         CDEBUG(D_VFSTRACE, "%s: Invalid range (%llu to %llu) "
3275                                "for %s: rc = %d\n", sbi->ll_fsname,
3276                                ladvise->lla_start, ladvise->lla_end,
3277                                ladvise_names[advice], rc);
3278                         GOTO(out, rc);
3279                 }
3280                 break;
3281         }
3282
3283 out:
3284         return rc;
3285 }
3286 #undef ERRSIZE
3287
3288 /*
3289  * Give file access advices
3290  *
3291  * The ladvise interface is similar to Linux fadvise() system call, except it
3292  * forwards the advices directly from Lustre client to server. The server side
3293  * codes will apply appropriate read-ahead and caching techniques for the
3294  * corresponding files.
3295  *
3296  * A typical workload for ladvise is e.g. a bunch of different clients are
3297  * doing small random reads of a file, so prefetching pages into OSS cache
3298  * with big linear reads before the random IO is a net benefit. Fetching
3299  * all that data into each client cache with fadvise() may not be, due to
3300  * much more data being sent to the client.
3301  */
3302 static int ll_ladvise(struct inode *inode, struct file *file, __u64 flags,
3303                       struct llapi_lu_ladvise *ladvise)
3304 {
3305         struct lu_env *env;
3306         struct cl_io *io;
3307         struct cl_ladvise_io *lio;
3308         int rc;
3309         __u16 refcheck;
3310         ENTRY;
3311
3312         env = cl_env_get(&refcheck);
3313         if (IS_ERR(env))
3314                 RETURN(PTR_ERR(env));
3315
3316         io = vvp_env_thread_io(env);
3317         io->ci_obj = ll_i2info(inode)->lli_clob;
3318
3319         /* initialize parameters for ladvise */
3320         lio = &io->u.ci_ladvise;
3321         lio->li_start = ladvise->lla_start;
3322         lio->li_end = ladvise->lla_end;
3323         lio->li_fid = ll_inode2fid(inode);
3324         lio->li_advice = ladvise->lla_advice;
3325         lio->li_flags = flags;
3326
3327         if (cl_io_init(env, io, CIT_LADVISE, io->ci_obj) == 0)
3328                 rc = cl_io_loop(env, io);
3329         else
3330                 rc = io->ci_result;
3331
3332         cl_io_fini(env, io);
3333         cl_env_put(env, &refcheck);
3334         RETURN(rc);
3335 }
3336
3337 static int ll_lock_noexpand(struct file *file, int flags)
3338 {
3339         struct ll_file_data *fd = file->private_data;
3340
3341         fd->ll_lock_no_expand = !(flags & LF_UNSET);
3342
3343         return 0;
3344 }
3345
3346 int ll_ioctl_fsgetxattr(struct inode *inode, unsigned int cmd,
3347                         unsigned long arg)
3348 {
3349         struct fsxattr fsxattr;
3350
3351         if (copy_from_user(&fsxattr,
3352                            (const struct fsxattr __user *)arg,
3353                            sizeof(fsxattr)))
3354                 RETURN(-EFAULT);
3355
3356         fsxattr.fsx_xflags = ll_inode_flags_to_xflags(inode->i_flags);
3357         if (test_bit(LLIF_PROJECT_INHERIT, &ll_i2info(inode)->lli_flags))
3358                 fsxattr.fsx_xflags |= FS_XFLAG_PROJINHERIT;
3359         fsxattr.fsx_projid = ll_i2info(inode)->lli_projid;
3360         if (copy_to_user((struct fsxattr __user *)arg,
3361                          &fsxattr, sizeof(fsxattr)))
3362                 RETURN(-EFAULT);
3363
3364         RETURN(0);
3365 }
3366
3367 int ll_ioctl_check_project(struct inode *inode, struct fsxattr *fa)
3368 {
3369         /*
3370          * Project Quota ID state is only allowed to change from within the init
3371          * namespace. Enforce that restriction only if we are trying to change
3372          * the quota ID state. Everything else is allowed in user namespaces.
3373          */
3374         if (current_user_ns() == &init_user_ns)
3375                 return 0;
3376
3377         if (ll_i2info(inode)->lli_projid != fa->fsx_projid)
3378                 return -EINVAL;
3379
3380         if (test_bit(LLIF_PROJECT_INHERIT, &ll_i2info(inode)->lli_flags)) {
3381                 if (!(fa->fsx_xflags & FS_XFLAG_PROJINHERIT))
3382                         return -EINVAL;
3383         } else {
3384                 if (fa->fsx_xflags & FS_XFLAG_PROJINHERIT)
3385                         return -EINVAL;
3386         }
3387
3388         return 0;
3389 }
3390
3391 int ll_ioctl_fssetxattr(struct inode *inode, unsigned int cmd,
3392                         unsigned long arg)
3393 {
3394         struct md_op_data *op_data;
3395         struct ptlrpc_request *req = NULL;
3396         struct fsxattr fsxattr;
3397         struct cl_object *obj;
3398         unsigned int inode_flags;
3399         int rc = 0;
3400
3401         if (copy_from_user(&fsxattr,
3402                            (const struct fsxattr __user *)arg,
3403                            sizeof(fsxattr)))
3404                 RETURN(-EFAULT);
3405
3406         rc = ll_ioctl_check_project(inode, &fsxattr);
3407         if (rc)
3408                 RETURN(rc);
3409
3410         op_data = ll_prep_md_op_data(NULL, inode, NULL, NULL, 0, 0,
3411                                      LUSTRE_OPC_ANY, NULL);
3412         if (IS_ERR(op_data))
3413                 RETURN(PTR_ERR(op_data));
3414
3415         inode_flags = ll_xflags_to_inode_flags(fsxattr.fsx_xflags);
3416         op_data->op_attr_flags = ll_inode_to_ext_flags(inode_flags);
3417         if (fsxattr.fsx_xflags & FS_XFLAG_PROJINHERIT)
3418                 op_data->op_attr_flags |= LUSTRE_PROJINHERIT_FL;
3419         op_data->op_projid = fsxattr.fsx_projid;
3420         op_data->op_xvalid |= OP_XVALID_PROJID | OP_XVALID_FLAGS;
3421         rc = md_setattr(ll_i2sbi(inode)->ll_md_exp, op_data, NULL, 0, &req);
3422         ptlrpc_req_finished(req);
3423         if (rc)
3424                 GOTO(out_fsxattr, rc);
3425         ll_update_inode_flags(inode, op_data->op_attr_flags);
3426
3427         /* Avoid OST RPC if this is only ioctl setting project inherit flag */
3428         if (fsxattr.fsx_xflags == 0 ||
3429             fsxattr.fsx_xflags == FS_XFLAG_PROJINHERIT)
3430                 GOTO(out_fsxattr, rc);
3431
3432         obj = ll_i2info(inode)->lli_clob;
3433         if (obj) {
3434                 struct iattr attr = { 0 };
3435
3436                 rc = cl_setattr_ost(obj, &attr, OP_XVALID_FLAGS,
3437                                     fsxattr.fsx_xflags);
3438         }
3439
3440 out_fsxattr:
3441         ll_finish_md_op_data(op_data);
3442         RETURN(rc);
3443 }
3444
3445 static long ll_file_unlock_lease(struct file *file, struct ll_ioc_lease *ioc,
3446                                  unsigned long arg)
3447 {
3448         struct inode            *inode = file_inode(file);
3449         struct ll_file_data     *fd = file->private_data;
3450         struct ll_inode_info    *lli = ll_i2info(inode);
3451         struct obd_client_handle *och = NULL;
3452         struct split_param sp;
3453         struct pcc_param param;
3454         bool lease_broken = false;
3455         fmode_t fmode = 0;
3456         enum mds_op_bias bias = 0;
3457         struct file *layout_file = NULL;
3458         void *data = NULL;
3459         size_t data_size = 0;
3460         bool attached = false;
3461         long rc, rc2 = 0;
3462
3463         ENTRY;
3464
3465         mutex_lock(&lli->lli_och_mutex);
3466         if (fd->fd_lease_och != NULL) {
3467                 och = fd->fd_lease_och;
3468                 fd->fd_lease_och = NULL;
3469         }
3470         mutex_unlock(&lli->lli_och_mutex);
3471
3472         if (och == NULL)
3473                 RETURN(-ENOLCK);
3474
3475         fmode = och->och_flags;
3476
3477         switch (ioc->lil_flags) {
3478         case LL_LEASE_RESYNC_DONE:
3479                 if (ioc->lil_count > IOC_IDS_MAX)
3480                         GOTO(out_lease_close, rc = -EINVAL);
3481
3482                 data_size = offsetof(typeof(*ioc), lil_ids[ioc->lil_count]);
3483                 OBD_ALLOC(data, data_size);
3484                 if (!data)
3485                         GOTO(out_lease_close, rc = -ENOMEM);
3486
3487                 if (copy_from_user(data, (void __user *)arg, data_size))
3488                         GOTO(out_lease_close, rc = -EFAULT);
3489
3490                 bias = MDS_CLOSE_RESYNC_DONE;
3491                 break;
3492         case LL_LEASE_LAYOUT_MERGE: {
3493                 int fd;
3494
3495                 if (ioc->lil_count != 1)
3496                         GOTO(out_lease_close, rc = -EINVAL);
3497
3498                 arg += sizeof(*ioc);
3499                 if (copy_from_user(&fd, (void __user *)arg, sizeof(__u32)))
3500                         GOTO(out_lease_close, rc = -EFAULT);
3501
3502                 layout_file = fget(fd);
3503                 if (!layout_file)
3504                         GOTO(out_lease_close, rc = -EBADF);
3505
3506                 if ((file->f_flags & O_ACCMODE) == O_RDONLY ||
3507                                 (layout_file->f_flags & O_ACCMODE) == O_RDONLY)
3508                         GOTO(out_lease_close, rc = -EPERM);
3509
3510                 data = file_inode(layout_file);
3511                 bias = MDS_CLOSE_LAYOUT_MERGE;
3512                 break;
3513         }
3514         case LL_LEASE_LAYOUT_SPLIT: {
3515                 int fdv;
3516                 int mirror_id;
3517
3518                 if (ioc->lil_count != 2)
3519                         GOTO(out_lease_close, rc = -EINVAL);
3520
3521                 arg += sizeof(*ioc);
3522                 if (copy_from_user(&fdv, (void __user *)arg, sizeof(__u32)))
3523                         GOTO(out_lease_close, rc = -EFAULT);
3524
3525                 arg += sizeof(__u32);
3526                 if (copy_from_user(&mirror_id, (void __user *)arg,
3527                                    sizeof(__u32)))
3528                         GOTO(out_lease_close, rc = -EFAULT);
3529
3530                 layout_file = fget(fdv);
3531                 if (!layout_file)
3532                         GOTO(out_lease_close, rc = -EBADF);
3533
3534                 /* if layout_file == file, it means to destroy the mirror */
3535                 sp.sp_inode = file_inode(layout_file);
3536                 sp.sp_mirror_id = (__u16)mirror_id;
3537                 data = &sp;
3538                 bias = MDS_CLOSE_LAYOUT_SPLIT;
3539                 break;
3540         }
3541         case LL_LEASE_PCC_ATTACH:
3542                 if (ioc->lil_count != 1)
3543                         RETURN(-EINVAL);
3544
3545                 arg += sizeof(*ioc);
3546                 if (copy_from_user(&param.pa_archive_id, (void __user *)arg,
3547                                    sizeof(__u32)))
3548                         GOTO(out_lease_close, rc2 = -EFAULT);
3549
3550                 rc2 = pcc_readwrite_attach(file, inode, param.pa_archive_id);
3551                 if (rc2)
3552                         GOTO(out_lease_close, rc2);
3553
3554                 attached = true;
3555                 /* Grab latest data version */
3556                 rc2 = ll_data_version(inode, &param.pa_data_version,
3557                                      LL_DV_WR_FLUSH);
3558                 if (rc2)
3559                         GOTO(out_lease_close, rc2);
3560
3561                 data = &param;
3562                 bias = MDS_PCC_ATTACH;
3563                 break;
3564         default:
3565                 /* without close intent */
3566                 break;
3567         }
3568
3569 out_lease_close:
3570         rc = ll_lease_close_intent(och, inode, &lease_broken, bias, data);
3571         if (rc < 0)
3572                 GOTO(out, rc);
3573
3574         rc = ll_lease_och_release(inode, file);
3575         if (rc < 0)
3576                 GOTO(out, rc);
3577
3578         if (lease_broken)
3579                 fmode = 0;
3580         EXIT;
3581
3582 out:
3583         switch (ioc->lil_flags) {
3584         case LL_LEASE_RESYNC_DONE:
3585                 if (data)
3586                         OBD_FREE(data, data_size);
3587                 break;
3588         case LL_LEASE_LAYOUT_MERGE:
3589         case LL_LEASE_LAYOUT_SPLIT:
3590                 if (layout_file)
3591                         fput(layout_file);
3592                 break;
3593         case LL_LEASE_PCC_ATTACH:
3594                 if (!rc)
3595                         rc = rc2;
3596                 rc = pcc_readwrite_attach_fini(file, inode,
3597                                                param.pa_layout_gen,
3598                                                lease_broken, rc,
3599                                                attached);
3600                 break;
3601         }
3602
3603         if (!rc)
3604                 rc = ll_lease_type_from_fmode(fmode);
3605         RETURN(rc);
3606 }
3607
3608 static long ll_file_set_lease(struct file *file, struct ll_ioc_lease *ioc,
3609                               unsigned long arg)
3610 {
3611         struct inode *inode = file_inode(file);
3612         struct ll_inode_info *lli = ll_i2info(inode);
3613         struct ll_file_data *fd = file->private_data;
3614         struct obd_client_handle *och = NULL;
3615         __u64 open_flags = 0;
3616         bool lease_broken;
3617         fmode_t fmode;
3618         long rc;
3619         ENTRY;
3620
3621         switch (ioc->lil_mode) {
3622         case LL_LEASE_WRLCK:
3623                 if (!(file->f_mode & FMODE_WRITE))
3624                         RETURN(-EPERM);
3625                 fmode = FMODE_WRITE;
3626                 break;
3627         case LL_LEASE_RDLCK:
3628                 if (!(file->f_mode & FMODE_READ))
3629                         RETURN(-EPERM);
3630                 fmode = FMODE_READ;
3631                 break;
3632         case LL_LEASE_UNLCK:
3633                 RETURN(ll_file_unlock_lease(file, ioc, arg));
3634         default:
3635                 RETURN(-EINVAL);
3636         }
3637
3638         CDEBUG(D_INODE, "Set lease with mode %u\n", fmode);
3639
3640         /* apply for lease */
3641         if (ioc->lil_flags & LL_LEASE_RESYNC)
3642                 open_flags = MDS_OPEN_RESYNC;
3643         och = ll_lease_open(inode, file, fmode, open_flags);
3644         if (IS_ERR(och))
3645                 RETURN(PTR_ERR(och));
3646
3647         if (ioc->lil_flags & LL_LEASE_RESYNC) {
3648                 rc = ll_lease_file_resync(och, inode, arg);
3649                 if (rc) {
3650                         ll_lease_close(och, inode, NULL);
3651                         RETURN(rc);
3652                 }
3653                 rc = ll_layout_refresh(inode, &fd->fd_layout_version);
3654                 if (rc) {
3655                         ll_lease_close(och, inode, NULL);
3656                         RETURN(rc);
3657                 }
3658         }
3659
3660         rc = 0;
3661         mutex_lock(&lli->lli_och_mutex);
3662         if (fd->fd_lease_och == NULL) {
3663                 fd->fd_lease_och = och;
3664                 och = NULL;
3665         }
3666         mutex_unlock(&lli->lli_och_mutex);
3667         if (och != NULL) {
3668                 /* impossible now that only excl is supported for now */
3669                 ll_lease_close(och, inode, &lease_broken);
3670                 rc = -EBUSY;
3671         }
3672         RETURN(rc);
3673 }
3674
3675 static void ll_heat_get(struct inode *inode, struct lu_heat *heat)
3676 {
3677         struct ll_inode_info *lli = ll_i2info(inode);
3678         struct ll_sb_info *sbi = ll_i2sbi(inode);
3679         __u64 now = ktime_get_real_seconds();
3680         int i;
3681
3682         spin_lock(&lli->lli_heat_lock);
3683         heat->lh_flags = lli->lli_heat_flags;
3684         for (i = 0; i < heat->lh_count; i++)
3685                 heat->lh_heat[i] = obd_heat_get(&lli->lli_heat_instances[i],
3686                                                 now, sbi->ll_heat_decay_weight,
3687                                                 sbi->ll_heat_period_second);
3688         spin_unlock(&lli->lli_heat_lock);
3689 }
3690
3691 static int ll_heat_set(struct inode *inode, enum lu_heat_flag flags)
3692 {
3693         struct ll_inode_info *lli = ll_i2info(inode);
3694         int rc = 0;
3695
3696         spin_lock(&lli->lli_heat_lock);
3697         if (flags & LU_HEAT_FLAG_CLEAR)
3698                 obd_heat_clear(lli->lli_heat_instances, OBD_HEAT_COUNT);
3699
3700         if (flags & LU_HEAT_FLAG_OFF)
3701                 lli->lli_heat_flags |= LU_HEAT_FLAG_OFF;
3702         else
3703                 lli->lli_heat_flags &= ~LU_HEAT_FLAG_OFF;
3704
3705         spin_unlock(&lli->lli_heat_lock);
3706
3707         RETURN(rc);
3708 }
3709
3710 static long
3711 ll_file_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
3712 {
3713         struct inode            *inode = file_inode(file);
3714         struct ll_file_data     *fd = file->private_data;
3715         int                      flags, rc;
3716         ENTRY;
3717
3718         CDEBUG(D_VFSTRACE, "VFS Op:inode="DFID"(%p), cmd=%x\n",
3719                PFID(ll_inode2fid(inode)), inode, cmd);
3720         ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_IOCTL, 1);
3721
3722         /* asm-ppc{,64} declares TCGETS, et. al. as type 't' not 'T' */
3723         if (_IOC_TYPE(cmd) == 'T' || _IOC_TYPE(cmd) == 't') /* tty ioctls */
3724                 RETURN(-ENOTTY);
3725
3726         switch (cmd) {
3727         case LL_IOC_GETFLAGS:
3728                 /* Get the current value of the file flags */
3729                 return put_user(fd->fd_flags, (int __user *)arg);
3730         case LL_IOC_SETFLAGS:
3731         case LL_IOC_CLRFLAGS:
3732                 /* Set or clear specific file flags */
3733                 /* XXX This probably needs checks to ensure the flags are
3734                  *     not abused, and to handle any flag side effects.
3735                  */
3736                 if (get_user(flags, (int __user *) arg))
3737                         RETURN(-EFAULT);
3738
3739                 if (cmd == LL_IOC_SETFLAGS) {
3740                         if ((flags & LL_FILE_IGNORE_LOCK) &&
3741                             !(file->f_flags & O_DIRECT)) {
3742                                 CERROR("%s: unable to disable locking on "
3743                                        "non-O_DIRECT file\n", current->comm);
3744                                 RETURN(-EINVAL);
3745                         }
3746
3747                         fd->fd_flags |= flags;
3748                 } else {
3749                         fd->fd_flags &= ~flags;
3750                 }
3751                 RETURN(0);
3752         case LL_IOC_LOV_SETSTRIPE:
3753         case LL_IOC_LOV_SETSTRIPE_NEW:
3754                 RETURN(ll_lov_setstripe(inode, file, (void __user *)arg));
3755         case LL_IOC_LOV_SETEA:
3756                 RETURN(ll_lov_setea(inode, file, (void __user *)arg));
3757         case LL_IOC_LOV_SWAP_LAYOUTS: {
3758                 struct file *file2;
3759                 struct lustre_swap_layouts lsl;
3760
3761                 if (copy_from_user(&lsl, (char __user *)arg,
3762                                    sizeof(struct lustre_swap_layouts)))
3763                         RETURN(-EFAULT);
3764
3765                 if ((file->f_flags & O_ACCMODE) == O_RDONLY)
3766                         RETURN(-EPERM);
3767
3768                 file2 = fget(lsl.sl_fd);
3769                 if (file2 == NULL)
3770                         RETURN(-EBADF);
3771
3772                 /* O_WRONLY or O_RDWR */
3773                 if ((file2->f_flags & O_ACCMODE) == O_RDONLY)
3774                         GOTO(out, rc = -EPERM);
3775
3776                 if (lsl.sl_flags & SWAP_LAYOUTS_CLOSE) {
3777                         struct inode                    *inode2;
3778                         struct ll_inode_info            *lli;
3779                         struct obd_client_handle        *och = NULL;
3780
3781                         lli = ll_i2info(inode);
3782                         mutex_lock(&lli->lli_och_mutex);
3783                         if (fd->fd_lease_och != NULL) {
3784                                 och = fd->fd_lease_och;
3785                                 fd->fd_lease_och = NULL;
3786                         }
3787                         mutex_unlock(&lli->lli_och_mutex);
3788                         if (och == NULL)
3789                                 GOTO(out, rc = -ENOLCK);
3790                         inode2 = file_inode(file2);
3791                         rc = ll_swap_layouts_close(och, inode, inode2);
3792                 } else {
3793                         rc = ll_swap_layouts(file, file2, &lsl);
3794                 }
3795 out:
3796                 fput(file2);
3797                 RETURN(rc);
3798         }
3799         case LL_IOC_LOV_GETSTRIPE:
3800         case LL_IOC_LOV_GETSTRIPE_NEW:
3801                 RETURN(ll_file_getstripe(inode, (void __user *)arg, 0));
3802         case FS_IOC_GETFLAGS:
3803         case FS_IOC_SETFLAGS:
3804                 RETURN(ll_iocontrol(inode, file, cmd, arg));
3805         case FSFILT_IOC_GETVERSION:
3806         case FS_IOC_GETVERSION:
3807                 RETURN(put_user(inode->i_generation, (int __user *)arg));
3808         /* We need to special case any other ioctls we want to handle,
3809          * to send them to the MDS/OST as appropriate and to properly
3810          * network encode the arg field. */
3811         case FS_IOC_SETVERSION:
3812                 RETURN(-ENOTSUPP);
3813
3814         case LL_IOC_GROUP_LOCK:
3815                 RETURN(ll_get_grouplock(inode, file, arg));
3816         case LL_IOC_GROUP_UNLOCK:
3817                 RETURN(ll_put_grouplock(inode, file, arg));
3818         case IOC_OBD_STATFS:
3819                 RETURN(ll_obd_statfs(inode, (void __user *)arg));
3820
3821         case LL_IOC_FLUSHCTX:
3822                 RETURN(ll_flush_ctx(inode));
3823         case LL_IOC_PATH2FID: {
3824                 if (copy_to_user((void __user *)arg, ll_inode2fid(inode),
3825                                  sizeof(struct lu_fid)))
3826                         RETURN(-EFAULT);
3827
3828                 RETURN(0);
3829         }
3830         case LL_IOC_GETPARENT:
3831                 RETURN(ll_getparent(file, (struct getparent __user *)arg));
3832
3833         case OBD_IOC_FID2PATH:
3834                 RETURN(ll_fid2path(inode, (void __user *)arg));
3835         case LL_IOC_DATA_VERSION: {
3836                 struct ioc_data_version idv;
3837                 int rc;
3838
3839                 if (copy_from_user(&idv, (char __user *)arg, sizeof(idv)))
3840                         RETURN(-EFAULT);
3841
3842                 idv.idv_flags &= LL_DV_RD_FLUSH | LL_DV_WR_FLUSH;
3843                 rc = ll_ioc_data_version(inode, &idv);
3844
3845                 if (rc == 0 &&
3846                     copy_to_user((char __user *)arg, &idv, sizeof(idv)))
3847                         RETURN(-EFAULT);
3848
3849                 RETURN(rc);
3850         }
3851
3852         case LL_IOC_GET_MDTIDX: {
3853                 int mdtidx;
3854
3855                 mdtidx = ll_get_mdt_idx(inode);
3856                 if (mdtidx < 0)
3857                         RETURN(mdtidx);
3858
3859                 if (put_user((int)mdtidx, (int __user *)arg))
3860                         RETURN(-EFAULT);
3861
3862                 RETURN(0);
3863         }
3864         case OBD_IOC_GETNAME_OLD:
3865                 /* fall through */
3866         case OBD_IOC_GETDTNAME:
3867                 /* fall through */
3868         case OBD_IOC_GETMDNAME:
3869                 RETURN(ll_get_obd_name(inode, cmd, arg));
3870         case LL_IOC_HSM_STATE_GET: {
3871                 struct md_op_data       *op_data;
3872                 struct hsm_user_state   *hus;
3873                 int                      rc;
3874
3875                 OBD_ALLOC_PTR(hus);
3876                 if (hus == NULL)
3877                         RETURN(-ENOMEM);
3878
3879                 op_data = ll_prep_md_op_data(NULL, inode, NULL, NULL, 0, 0,
3880                                              LUSTRE_OPC_ANY, hus);
3881                 if (IS_ERR(op_data)) {
3882                         OBD_FREE_PTR(hus);
3883                         RETURN(PTR_ERR(op_data));
3884                 }
3885
3886                 rc = obd_iocontrol(cmd, ll_i2mdexp(inode), sizeof(*op_data),
3887                                    op_data, NULL);
3888
3889                 if (copy_to_user((void __user *)arg, hus, sizeof(*hus)))
3890                         rc = -EFAULT;
3891
3892                 ll_finish_md_op_data(op_data);
3893                 OBD_FREE_PTR(hus);
3894                 RETURN(rc);
3895         }
3896         case LL_IOC_HSM_STATE_SET: {
3897                 struct hsm_state_set    *hss;
3898                 int                      rc;
3899
3900                 OBD_ALLOC_PTR(hss);
3901                 if (hss == NULL)
3902                         RETURN(-ENOMEM);
3903
3904                 if (copy_from_user(hss, (char __user *)arg, sizeof(*hss))) {
3905                         OBD_FREE_PTR(hss);
3906                         RETURN(-EFAULT);
3907                 }
3908
3909                 rc = ll_hsm_state_set(inode, hss);
3910
3911                 OBD_FREE_PTR(hss);
3912                 RETURN(rc);
3913         }
3914         case LL_IOC_HSM_ACTION: {
3915                 struct md_op_data               *op_data;
3916                 struct hsm_current_action       *hca;
3917                 int                              rc;
3918
3919                 OBD_ALLOC_PTR(hca);
3920                 if (hca == NULL)
3921                         RETURN(-ENOMEM);
3922
3923                 op_data = ll_prep_md_op_data(NULL, inode, NULL, NULL, 0, 0,
3924                                              LUSTRE_OPC_ANY, hca);
3925                 if (IS_ERR(op_data)) {
3926                         OBD_FREE_PTR(hca);
3927                         RETURN(PTR_ERR(op_data));
3928                 }
3929
3930                 rc = obd_iocontrol(cmd, ll_i2mdexp(inode), sizeof(*op_data),
3931                                    op_data, NULL);
3932
3933                 if (copy_to_user((char __user *)arg, hca, sizeof(*hca)))
3934                         rc = -EFAULT;
3935
3936                 ll_finish_md_op_data(op_data);
3937                 OBD_FREE_PTR(hca);
3938                 RETURN(rc);
3939         }
3940         case LL_IOC_SET_LEASE_OLD: {
3941                 struct ll_ioc_lease ioc = { .lil_mode = (__u32)arg };
3942
3943                 RETURN(ll_file_set_lease(file, &ioc, 0));
3944         }
3945         case LL_IOC_SET_LEASE: {
3946                 struct ll_ioc_lease ioc;
3947
3948                 if (copy_from_user(&ioc, (void __user *)arg, sizeof(ioc)))
3949                         RETURN(-EFAULT);
3950
3951                 RETURN(ll_file_set_lease(file, &ioc, arg));
3952         }
3953         case LL_IOC_GET_LEASE: {
3954                 struct ll_inode_info *lli = ll_i2info(inode);
3955                 struct ldlm_lock *lock = NULL;
3956                 fmode_t fmode = 0;
3957
3958                 mutex_lock(&lli->lli_och_mutex);
3959                 if (fd->fd_lease_och != NULL) {
3960                         struct obd_client_handle *och = fd->fd_lease_och;
3961
3962                         lock = ldlm_handle2lock(&och->och_lease_handle);
3963                         if (lock != NULL) {
3964                                 lock_res_and_lock(lock);
3965                                 if (!ldlm_is_cancel(lock))
3966                                         fmode = och->och_flags;
3967
3968                                 unlock_res_and_lock(lock);
3969                                 LDLM_LOCK_PUT(lock);
3970                         }
3971                 }
3972                 mutex_unlock(&lli->lli_och_mutex);
3973
3974                 RETURN(ll_lease_type_from_fmode(fmode));
3975         }
3976         case LL_IOC_HSM_IMPORT: {
3977                 struct hsm_user_import *hui;
3978
3979                 OBD_ALLOC_PTR(hui);
3980                 if (hui == NULL)
3981                         RETURN(-ENOMEM);
3982
3983                 if (copy_from_user(hui, (void __user *)arg, sizeof(*hui))) {
3984                         OBD_FREE_PTR(hui);
3985                         RETURN(-EFAULT);
3986                 }
3987
3988                 rc = ll_hsm_import(inode, file, hui);
3989
3990                 OBD_FREE_PTR(hui);
3991                 RETURN(rc);
3992         }
3993         case LL_IOC_FUTIMES_3: {
3994                 struct ll_futimes_3 lfu;
3995
3996                 if (copy_from_user(&lfu,
3997                                    (const struct ll_futimes_3 __user *)arg,
3998                                    sizeof(lfu)))
3999                         RETURN(-EFAULT);
4000
4001                 RETURN(ll_file_futimes_3(file, &lfu));
4002         }
4003         case LL_IOC_LADVISE: {
4004                 struct llapi_ladvise_hdr *k_ladvise_hdr;
4005                 struct llapi_ladvise_hdr __user *u_ladvise_hdr;
4006                 int i;
4007                 int num_advise;
4008                 int alloc_size = sizeof(*k_ladvise_hdr);
4009
4010                 rc = 0;
4011                 u_ladvise_hdr = (void __user *)arg;
4012                 OBD_ALLOC_PTR(k_ladvise_hdr);
4013                 if (k_ladvise_hdr == NULL)
4014                         RETURN(-ENOMEM);
4015
4016                 if (copy_from_user(k_ladvise_hdr, u_ladvise_hdr, alloc_size))
4017                         GOTO(out_ladvise, rc = -EFAULT);
4018
4019                 if (k_ladvise_hdr->lah_magic != LADVISE_MAGIC ||
4020                     k_ladvise_hdr->lah_count < 1)
4021                         GOTO(out_ladvise, rc = -EINVAL);
4022
4023                 num_advise = k_ladvise_hdr->lah_count;
4024                 if (num_advise >= LAH_COUNT_MAX)
4025                         GOTO(out_ladvise, rc = -EFBIG);
4026
4027                 OBD_FREE_PTR(k_ladvise_hdr);
4028                 alloc_size = offsetof(typeof(*k_ladvise_hdr),
4029                                       lah_advise[num_advise]);
4030                 OBD_ALLOC(k_ladvise_hdr, alloc_size);
4031                 if (k_ladvise_hdr == NULL)
4032                         RETURN(-ENOMEM);
4033
4034                 /*
4035                  * TODO: submit multiple advices to one server in a single RPC
4036                  */
4037                 if (copy_from_user(k_ladvise_hdr, u_ladvise_hdr, alloc_size))
4038                         GOTO(out_ladvise, rc = -EFAULT);
4039
4040                 for (i = 0; i < num_advise; i++) {
4041                         struct llapi_lu_ladvise *k_ladvise =
4042                                         &k_ladvise_hdr->lah_advise[i];
4043                         struct llapi_lu_ladvise __user *u_ladvise =
4044                                         &u_ladvise_hdr->lah_advise[i];
4045
4046                         rc = ll_ladvise_sanity(inode, k_ladvise);
4047                         if (rc)
4048                                 GOTO(out_ladvise, rc);
4049
4050                         switch (k_ladvise->lla_advice) {
4051                         case LU_LADVISE_LOCKNOEXPAND:
4052                                 rc = ll_lock_noexpand(file,
4053                                                k_ladvise->lla_peradvice_flags);
4054                                 GOTO(out_ladvise, rc);
4055                         case LU_LADVISE_LOCKAHEAD:
4056
4057                                 rc = ll_file_lock_ahead(file, k_ladvise);
4058
4059                                 if (rc < 0)
4060                                         GOTO(out_ladvise, rc);
4061
4062                                 if (put_user(rc,
4063                                              &u_ladvise->lla_lockahead_result))
4064                                         GOTO(out_ladvise, rc = -EFAULT);
4065                                 break;
4066                         default:
4067                                 rc = ll_ladvise(inode, file,
4068                                                 k_ladvise_hdr->lah_flags,
4069                                                 k_ladvise);
4070                                 if (rc)
4071                                         GOTO(out_ladvise, rc);
4072                                 break;
4073                         }
4074
4075                 }
4076
4077 out_ladvise:
4078                 OBD_FREE(k_ladvise_hdr, alloc_size);
4079                 RETURN(rc);
4080         }
4081         case LL_IOC_FLR_SET_MIRROR: {
4082                 /* mirror I/O must be direct to avoid polluting page cache
4083                  * by stale data. */
4084                 if (!(file->f_flags & O_DIRECT))
4085                         RETURN(-EINVAL);
4086
4087                 fd->fd_designated_mirror = (__u32)arg;
4088                 RETURN(0);
4089         }
4090         case FS_IOC_FSGETXATTR:
4091                 RETURN(ll_ioctl_fsgetxattr(inode, cmd, arg));
4092         case FS_IOC_FSSETXATTR:
4093                 RETURN(ll_ioctl_fssetxattr(inode, cmd, arg));
4094         case BLKSSZGET:
4095                 RETURN(put_user(PAGE_SIZE, (int __user *)arg));
4096         case LL_IOC_HEAT_GET: {
4097                 struct lu_heat uheat;
4098                 struct lu_heat *heat;
4099                 int size;
4100
4101                 if (copy_from_user(&uheat, (void __user *)arg, sizeof(uheat)))
4102                         RETURN(-EFAULT);
4103
4104                 if (uheat.lh_count > OBD_HEAT_COUNT)
4105                         uheat.lh_count = OBD_HEAT_COUNT;
4106
4107                 size = offsetof(typeof(uheat), lh_heat[uheat.lh_count]);
4108                 OBD_ALLOC(heat, size);
4109                 if (heat == NULL)
4110                         RETURN(-ENOMEM);
4111
4112                 heat->lh_count = uheat.lh_count;
4113                 ll_heat_get(inode, heat);
4114                 rc = copy_to_user((char __user *)arg, heat, size);
4115                 OBD_FREE(heat, size);
4116                 RETURN(rc ? -EFAULT : 0);
4117         }
4118         case LL_IOC_HEAT_SET: {
4119                 __u64 flags;
4120
4121                 if (copy_from_user(&flags, (void __user *)arg, sizeof(flags)))
4122                         RETURN(-EFAULT);
4123
4124                 rc = ll_heat_set(inode, flags);
4125                 RETURN(rc);
4126         }
4127         case LL_IOC_PCC_DETACH: {
4128                 struct lu_pcc_detach *detach;
4129
4130                 OBD_ALLOC_PTR(detach);
4131                 if (detach == NULL)
4132                         RETURN(-ENOMEM);
4133
4134                 if (copy_from_user(detach,
4135                                    (const struct lu_pcc_detach __user *)arg,
4136                                    sizeof(*detach)))
4137                         GOTO(out_detach_free, rc = -EFAULT);
4138
4139                 if (!S_ISREG(inode->i_mode))
4140                         GOTO(out_detach_free, rc = -EINVAL);
4141
4142                 if (!inode_owner_or_capable(inode))
4143                         GOTO(out_detach_free, rc = -EPERM);
4144
4145                 rc = pcc_ioctl_detach(inode, detach->pccd_opt);
4146 out_detach_free:
4147                 OBD_FREE_PTR(detach);
4148                 RETURN(rc);
4149         }
4150         case LL_IOC_PCC_STATE: {
4151                 struct lu_pcc_state __user *ustate =
4152                         (struct lu_pcc_state __user *)arg;
4153                 struct lu_pcc_state *state;
4154
4155                 OBD_ALLOC_PTR(state);
4156                 if (state == NULL)
4157                         RETURN(-ENOMEM);
4158
4159                 if (copy_from_user(state, ustate, sizeof(*state)))
4160                         GOTO(out_state, rc = -EFAULT);
4161
4162                 rc = pcc_ioctl_state(file, inode, state);
4163                 if (rc)
4164                         GOTO(out_state, rc);
4165
4166                 if (copy_to_user(ustate, state, sizeof(*state)))
4167                         GOTO(out_state, rc = -EFAULT);
4168
4169 out_state:
4170                 OBD_FREE_PTR(state);
4171                 RETURN(rc);
4172         }
4173 #ifdef HAVE_LUSTRE_CRYPTO
4174         case LL_IOC_SET_ENCRYPTION_POLICY:
4175                 if (!ll_sbi_has_encrypt(ll_i2sbi(inode)))
4176                         return -EOPNOTSUPP;
4177                 return llcrypt_ioctl_set_policy(file, (const void __user *)arg);
4178         case LL_IOC_GET_ENCRYPTION_POLICY_EX:
4179                 if (!ll_sbi_has_encrypt(ll_i2sbi(inode)))
4180                         return -EOPNOTSUPP;
4181                 return llcrypt_ioctl_get_policy_ex(file, (void __user *)arg);
4182         case LL_IOC_ADD_ENCRYPTION_KEY:
4183                 if (!ll_sbi_has_encrypt(ll_i2sbi(inode)))
4184                         return -EOPNOTSUPP;
4185                 return llcrypt_ioctl_add_key(file, (void __user *)arg);
4186         case LL_IOC_REMOVE_ENCRYPTION_KEY:
4187                 if (!ll_sbi_has_encrypt(ll_i2sbi(inode)))
4188                         return -EOPNOTSUPP;
4189                 return llcrypt_ioctl_remove_key(file, (void __user *)arg);
4190         case LL_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS:
4191                 if (!ll_sbi_has_encrypt(ll_i2sbi(inode)))
4192                         return -EOPNOTSUPP;
4193                 return llcrypt_ioctl_remove_key_all_users(file,
4194                                                           (void __user *)arg);
4195         case LL_IOC_GET_ENCRYPTION_KEY_STATUS:
4196                 if (!ll_sbi_has_encrypt(ll_i2sbi(inode)))
4197                         return -EOPNOTSUPP;
4198                 return llcrypt_ioctl_get_key_status(file, (void __user *)arg);
4199 #endif
4200
4201         case LL_IOC_UNLOCK_FOREIGN: {
4202                 struct dentry *dentry = file_dentry(file);
4203
4204                 /* if not a foreign symlink do nothing */
4205                 if (ll_foreign_is_removable(dentry, true)) {
4206                         CDEBUG(D_INFO,
4207                                "prevent unlink of non-foreign file ("DFID")\n",
4208                                PFID(ll_inode2fid(inode)));
4209                         RETURN(-EOPNOTSUPP);
4210                 }
4211                 RETURN(0);
4212         }
4213
4214         default:
4215                 RETURN(obd_iocontrol(cmd, ll_i2dtexp(inode), 0, NULL,
4216                                      (void __user *)arg));
4217         }
4218 }
4219
4220 loff_t ll_lseek(struct file *file, loff_t offset, int whence)
4221 {
4222         struct inode *inode = file_inode(file);
4223         struct lu_env *env;
4224         struct cl_io *io;
4225         struct cl_lseek_io *lsio;
4226         __u16 refcheck;
4227         int rc;
4228         loff_t retval;
4229
4230         ENTRY;
4231
4232         env = cl_env_get(&refcheck);
4233         if (IS_ERR(env))
4234                 RETURN(PTR_ERR(env));
4235
4236         io = vvp_env_thread_io(env);
4237         io->ci_obj = ll_i2info(inode)->lli_clob;
4238         ll_io_set_mirror(io, file);
4239
4240         lsio = &io->u.ci_lseek;
4241         lsio->ls_start = offset;
4242         lsio->ls_whence = whence;
4243         lsio->ls_result = -ENXIO;
4244
4245         do {
4246                 rc = cl_io_init(env, io, CIT_LSEEK, io->ci_obj);
4247                 if (!rc) {
4248                         struct vvp_io *vio = vvp_env_io(env);
4249
4250                         vio->vui_fd = file->private_data;
4251                         rc = cl_io_loop(env, io);
4252                 } else {
4253                         rc = io->ci_result;
4254                 }
4255                 retval = rc ? : lsio->ls_result;
4256                 cl_io_fini(env, io);
4257         } while (unlikely(io->ci_need_restart));
4258
4259         cl_env_put(env, &refcheck);
4260
4261         RETURN(retval);
4262 }
4263
4264 static loff_t ll_file_seek(struct file *file, loff_t offset, int origin)
4265 {
4266         struct inode *inode = file_inode(file);
4267         loff_t retval = offset, eof = 0;
4268         ktime_t kstart = ktime_get();
4269
4270         ENTRY;
4271
4272         CDEBUG(D_VFSTRACE, "VFS Op:inode="DFID"(%p), to=%llu=%#llx(%d)\n",
4273                PFID(ll_inode2fid(inode)), inode, retval, retval,
4274                origin);
4275
4276         if (origin == SEEK_END) {
4277                 retval = ll_glimpse_size(inode);
4278                 if (retval != 0)
4279                         RETURN(retval);
4280                 eof = i_size_read(inode);
4281         }
4282
4283         if (origin == SEEK_HOLE || origin == SEEK_DATA) {
4284                 if (offset < 0)
4285                         return -ENXIO;
4286
4287                 /* flush local cache first if any */
4288                 cl_sync_file_range(inode, offset, OBD_OBJECT_EOF,
4289                                    CL_FSYNC_LOCAL, 0);
4290
4291                 retval = ll_lseek(file, offset, origin);
4292                 if (retval < 0)
4293                         return retval;
4294                 retval = vfs_setpos(file, retval, ll_file_maxbytes(inode));
4295         } else {
4296                 retval = generic_file_llseek_size(file, offset, origin,
4297                                                   ll_file_maxbytes(inode), eof);
4298         }
4299         if (retval >= 0)
4300                 ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_LLSEEK,
4301                                    ktime_us_delta(ktime_get(), kstart));
4302         RETURN(retval);
4303 }
4304
4305 static int ll_flush(struct file *file, fl_owner_t id)
4306 {
4307         struct inode *inode = file_inode(file);
4308         struct ll_inode_info *lli = ll_i2info(inode);
4309         struct ll_file_data *fd = file->private_data;
4310         int rc, err;
4311
4312         LASSERT(!S_ISDIR(inode->i_mode));
4313
4314         /* catch async errors that were recorded back when async writeback
4315          * failed for pages in this mapping. */
4316         rc = lli->lli_async_rc;
4317         lli->lli_async_rc = 0;
4318         if (lli->lli_clob != NULL) {
4319                 err = lov_read_and_clear_async_rc(lli->lli_clob);
4320                 if (rc == 0)
4321                         rc = err;
4322         }
4323
4324         /* The application has been told write failure already.
4325          * Do not report failure again. */
4326         if (fd->fd_write_failed)
4327                 return 0;
4328         return rc ? -EIO : 0;
4329 }
4330
4331 /**
4332  * Called to make sure a portion of file has been written out.
4333  * if @mode is not CL_FSYNC_LOCAL, it will send OST_SYNC RPCs to OST.
4334  *
4335  * Return how many pages have been written.
4336  */
4337 int cl_sync_file_range(struct inode *inode, loff_t start, loff_t end,
4338                        enum cl_fsync_mode mode, int ignore_layout)
4339 {
4340         struct lu_env *env;
4341         struct cl_io *io;
4342         struct cl_fsync_io *fio;
4343         int result;
4344         __u16 refcheck;
4345         ENTRY;
4346
4347         if (mode != CL_FSYNC_NONE && mode != CL_FSYNC_LOCAL &&
4348             mode != CL_FSYNC_DISCARD && mode != CL_FSYNC_ALL)
4349                 RETURN(-EINVAL);
4350
4351         env = cl_env_get(&refcheck);
4352         if (IS_ERR(env))
4353                 RETURN(PTR_ERR(env));
4354
4355         io = vvp_env_thread_io(env);
4356         io->ci_obj = ll_i2info(inode)->lli_clob;
4357         io->ci_ignore_layout = ignore_layout;
4358
4359         /* initialize parameters for sync */
4360         fio = &io->u.ci_fsync;
4361         fio->fi_start = start;
4362         fio->fi_end = end;
4363         fio->fi_fid = ll_inode2fid(inode);
4364         fio->fi_mode = mode;
4365         fio->fi_nr_written = 0;
4366
4367         if (cl_io_init(env, io, CIT_FSYNC, io->ci_obj) == 0)
4368                 result = cl_io_loop(env, io);
4369         else
4370                 result = io->ci_result;
4371         if (result == 0)
4372                 result = fio->fi_nr_written;
4373         cl_io_fini(env, io);
4374         cl_env_put(env, &refcheck);
4375
4376         RETURN(result);
4377 }
4378
4379 /*
4380  * When dentry is provided (the 'else' case), file_dentry() may be
4381  * null and dentry must be used directly rather than pulled from
4382  * file_dentry() as is done otherwise.
4383  */
4384
4385 int ll_fsync(struct file *file, loff_t start, loff_t end, int datasync)
4386 {
4387         struct dentry *dentry = file_dentry(file);
4388         struct inode *inode = dentry->d_inode;
4389         struct ll_inode_info *lli = ll_i2info(inode);
4390         struct ptlrpc_request *req;
4391         ktime_t kstart = ktime_get();
4392         int rc, err;
4393
4394         ENTRY;
4395
4396         CDEBUG(D_VFSTRACE,
4397                "VFS Op:inode="DFID"(%p), start %lld, end %lld, datasync %d\n",
4398                PFID(ll_inode2fid(inode)), inode, start, end, datasync);
4399
4400         /* fsync's caller has already called _fdata{sync,write}, we want
4401          * that IO to finish before calling the osc and mdc sync methods */
4402         rc = filemap_write_and_wait_range(inode->i_mapping, start, end);
4403         inode_lock(inode);
4404
4405         /* catch async errors that were recorded back when async writeback
4406          * failed for pages in this mapping. */
4407         if (!S_ISDIR(inode->i_mode)) {
4408                 err = lli->lli_async_rc;
4409                 lli->lli_async_rc = 0;
4410                 if (rc == 0)
4411                         rc = err;
4412                 if (lli->lli_clob != NULL) {
4413                         err = lov_read_and_clear_async_rc(lli->lli_clob);
4414                         if (rc == 0)
4415                                 rc = err;
4416                 }
4417         }
4418
4419         err = md_fsync(ll_i2sbi(inode)->ll_md_exp, ll_inode2fid(inode), &req);
4420         if (!rc)
4421                 rc = err;
4422         if (!err)
4423                 ptlrpc_req_finished(req);
4424
4425         if (S_ISREG(inode->i_mode)) {
4426                 struct ll_file_data *fd = file->private_data;
4427                 bool cached;
4428
4429                 /* Sync metadata on MDT first, and then sync the cached data
4430                  * on PCC.
4431                  */
4432                 err = pcc_fsync(file, start, end, datasync, &cached);
4433                 if (!cached)
4434                         err = cl_sync_file_range(inode, start, end,
4435                                                  CL_FSYNC_ALL, 0);
4436                 if (rc == 0 && err < 0)
4437                         rc = err;
4438                 if (rc < 0)
4439                         fd->fd_write_failed = true;
4440                 else
4441                         fd->fd_write_failed = false;
4442         }
4443
4444         inode_unlock(inode);
4445
4446         if (!rc)
4447                 ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_FSYNC,
4448                                    ktime_us_delta(ktime_get(), kstart));
4449         RETURN(rc);
4450 }
4451
4452 static int
4453 ll_file_flock(struct file *file, int cmd, struct file_lock *file_lock)
4454 {
4455         struct inode *inode = file_inode(file);
4456         struct ll_sb_info *sbi = ll_i2sbi(inode);
4457         struct ldlm_enqueue_info einfo = {
4458                 .ei_type        = LDLM_FLOCK,
4459                 .ei_cb_cp       = ldlm_flock_completion_ast,
4460                 .ei_cbdata      = file_lock,
4461         };
4462         struct md_op_data *op_data;
4463         struct lustre_handle lockh = { 0 };
4464         union ldlm_policy_data flock = { { 0 } };
4465         int fl_type = file_lock->fl_type;
4466         ktime_t kstart = ktime_get();
4467         __u64 flags = 0;
4468         int rc;
4469         int rc2 = 0;
4470         ENTRY;
4471
4472         CDEBUG(D_VFSTRACE, "VFS Op:inode="DFID" file_lock=%p\n",
4473                PFID(ll_inode2fid(inode)), file_lock);
4474
4475         if (file_lock->fl_flags & FL_FLOCK) {
4476                 LASSERT((cmd == F_SETLKW) || (cmd == F_SETLK));
4477                 /* flocks are whole-file locks */
4478                 flock.l_flock.end = OFFSET_MAX;
4479                 /* For flocks owner is determined by the local file desctiptor*/
4480                 flock.l_flock.owner = (unsigned long)file_lock->fl_file;
4481         } else if (file_lock->fl_flags & FL_POSIX) {
4482                 flock.l_flock.owner = (unsigned long)file_lock->fl_owner;
4483                 flock.l_flock.start = file_lock->fl_start;
4484                 flock.l_flock.end = file_lock->fl_end;
4485         } else {
4486                 RETURN(-EINVAL);
4487         }
4488         flock.l_flock.pid = file_lock->fl_pid;
4489
4490 #if defined(HAVE_LM_COMPARE_OWNER) || defined(lm_compare_owner)
4491         /* Somewhat ugly workaround for svc lockd.
4492          * lockd installs custom fl_lmops->lm_compare_owner that checks
4493          * for the fl_owner to be the same (which it always is on local node
4494          * I guess between lockd processes) and then compares pid.
4495          * As such we assign pid to the owner field to make it all work,
4496          * conflict with normal locks is unlikely since pid space and
4497          * pointer space for current->files are not intersecting */
4498         if (file_lock->fl_lmops && file_lock->fl_lmops->lm_compare_owner)
4499                 flock.l_flock.owner = (unsigned long)file_lock->fl_pid;
4500 #endif
4501
4502         switch (fl_type) {
4503         case F_RDLCK:
4504                 einfo.ei_mode = LCK_PR;
4505                 break;
4506         case F_UNLCK:
4507                 /* An unlock request may or may not have any relation to
4508                  * existing locks so we may not be able to pass a lock handle
4509                  * via a normal ldlm_lock_cancel() request. The request may even
4510                  * unlock a byte range in the middle of an existing lock. In
4511                  * order to process an unlock request we need all of the same
4512                  * information that is given with a normal read or write record
4513                  * lock request. To avoid creating another ldlm unlock (cancel)
4514                  * message we'll treat a LCK_NL flock request as an unlock. */
4515                 einfo.ei_mode = LCK_NL;
4516                 break;
4517         case F_WRLCK:
4518                 einfo.ei_mode = LCK_PW;
4519                 break;
4520         default:
4521                 CDEBUG(D_INFO, "Unknown fcntl lock type: %d\n", fl_type);
4522                 RETURN (-ENOTSUPP);
4523         }
4524
4525         switch (cmd) {
4526         case F_SETLKW:
4527 #ifdef F_SETLKW64
4528         case F_SETLKW64:
4529 #endif
4530                 flags = 0;
4531                 break;
4532         case F_SETLK:
4533 #ifdef F_SETLK64
4534         case F_SETLK64:
4535 #endif
4536                 flags = LDLM_FL_BLOCK_NOWAIT;
4537                 break;
4538         case F_GETLK:
4539 #ifdef F_GETLK64
4540         case F_GETLK64:
4541 #endif
4542                 flags = LDLM_FL_TEST_LOCK;
4543                 break;
4544         default:
4545                 CERROR("unknown fcntl lock command: %d\n", cmd);
4546                 RETURN (-EINVAL);
4547         }
4548
4549         /* Save the old mode so that if the mode in the lock changes we
4550          * can decrement the appropriate reader or writer refcount. */
4551         file_lock->fl_type = einfo.ei_mode;
4552
4553         op_data = ll_prep_md_op_data(NULL, inode, NULL, NULL, 0, 0,
4554                                      LUSTRE_OPC_ANY, NULL);
4555         if (IS_ERR(op_data))
4556                 RETURN(PTR_ERR(op_data));
4557
4558         CDEBUG(D_DLMTRACE, "inode="DFID", pid=%u, flags=%#llx, mode=%u, "
4559                "start=%llu, end=%llu\n", PFID(ll_inode2fid(inode)),
4560                flock.l_flock.pid, flags, einfo.ei_mode,
4561                flock.l_flock.start, flock.l_flock.end);
4562
4563         rc = md_enqueue(sbi->ll_md_exp, &einfo, &flock, op_data, &lockh,
4564                         flags);
4565
4566         /* Restore the file lock type if not TEST lock. */
4567         if (!(flags & LDLM_FL_TEST_LOCK))
4568                 file_lock->fl_type = fl_type;
4569
4570 #ifdef HAVE_LOCKS_LOCK_FILE_WAIT
4571         if ((rc == 0 || file_lock->fl_type == F_UNLCK) &&
4572             !(flags & LDLM_FL_TEST_LOCK))
4573                 rc2  = locks_lock_file_wait(file, file_lock);
4574 #else
4575         if ((file_lock->fl_flags & FL_FLOCK) &&
4576             (rc == 0 || file_lock->fl_type == F_UNLCK))
4577                 rc2  = flock_lock_file_wait(file, file_lock);
4578         if ((file_lock->fl_flags & FL_POSIX) &&
4579             (rc == 0 || file_lock->fl_type == F_UNLCK) &&
4580             !(flags & LDLM_FL_TEST_LOCK))
4581                 rc2  = posix_lock_file_wait(file, file_lock);
4582 #endif /* HAVE_LOCKS_LOCK_FILE_WAIT */
4583
4584         if (rc2 && file_lock->fl_type != F_UNLCK) {
4585                 einfo.ei_mode = LCK_NL;
4586                 md_enqueue(sbi->ll_md_exp, &einfo, &flock, op_data,
4587                            &lockh, flags);
4588                 rc = rc2;
4589         }
4590
4591         ll_finish_md_op_data(op_data);
4592
4593         if (!rc)
4594                 ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_FLOCK,
4595                                    ktime_us_delta(ktime_get(), kstart));
4596         RETURN(rc);
4597 }
4598
4599 int ll_get_fid_by_name(struct inode *parent, const char *name,
4600                        int namelen, struct lu_fid *fid,
4601                        struct inode **inode)
4602 {
4603         struct md_op_data       *op_data = NULL;
4604         struct mdt_body         *body;
4605         struct ptlrpc_request   *req;
4606         int                     rc;
4607         ENTRY;
4608
4609         op_data = ll_prep_md_op_data(NULL, parent, NULL, name, namelen, 0,
4610                                      LUSTRE_OPC_ANY, NULL);
4611         if (IS_ERR(op_data))
4612                 RETURN(PTR_ERR(op_data));
4613
4614         op_data->op_valid = OBD_MD_FLID | OBD_MD_FLTYPE;
4615         rc = md_getattr_name(ll_i2sbi(parent)->ll_md_exp, op_data, &req);
4616         ll_finish_md_op_data(op_data);
4617         if (rc < 0)
4618                 RETURN(rc);
4619
4620         body = req_capsule_server_get(&req->rq_pill, &RMF_MDT_BODY);
4621         if (body == NULL)
4622                 GOTO(out_req, rc = -EFAULT);
4623         if (fid != NULL)
4624                 *fid = body->mbo_fid1;
4625
4626         if (inode != NULL)
4627                 rc = ll_prep_inode(inode, req, parent->i_sb, NULL);
4628 out_req:
4629         ptlrpc_req_finished(req);
4630         RETURN(rc);
4631 }
4632
4633 int ll_migrate(struct inode *parent, struct file *file, struct lmv_user_md *lum,
4634                const char *name)
4635 {
4636         struct dentry *dchild = NULL;
4637         struct inode *child_inode = NULL;
4638         struct md_op_data *op_data;
4639         struct ptlrpc_request *request = NULL;
4640         struct obd_client_handle *och = NULL;
4641         struct qstr qstr;
4642         struct mdt_body *body;
4643         __u64 data_version = 0;
4644         size_t namelen = strlen(name);
4645         int lumlen = lmv_user_md_size(lum->lum_stripe_count, lum->lum_magic);
4646         int rc;
4647         ENTRY;
4648
4649         CDEBUG(D_VFSTRACE, "migrate "DFID"/%s to MDT%04x stripe count %d\n",
4650                PFID(ll_inode2fid(parent)), name,
4651                lum->lum_stripe_offset, lum->lum_stripe_count);
4652
4653         if (lum->lum_magic != cpu_to_le32(LMV_USER_MAGIC) &&
4654             lum->lum_magic != cpu_to_le32(LMV_USER_MAGIC_SPECIFIC))
4655                 lustre_swab_lmv_user_md(lum);
4656
4657         /* Get child FID first */
4658         qstr.hash = ll_full_name_hash(file_dentry(file), name, namelen);
4659         qstr.name = name;
4660         qstr.len = namelen;
4661         dchild = d_lookup(file_dentry(file), &qstr);
4662         if (dchild) {
4663                 if (dchild->d_inode)
4664                         child_inode = igrab(dchild->d_inode);
4665                 dput(dchild);
4666         }
4667
4668         if (!child_inode) {
4669                 rc = ll_get_fid_by_name(parent, name, namelen, NULL,
4670                                         &child_inode);
4671                 if (rc)
4672                         RETURN(rc);
4673         }
4674
4675         if (!child_inode)
4676                 RETURN(-ENOENT);
4677
4678         if (!(exp_connect_flags2(ll_i2sbi(parent)->ll_md_exp) &
4679               OBD_CONNECT2_DIR_MIGRATE)) {
4680                 if (le32_to_cpu(lum->lum_stripe_count) > 1 ||
4681                     ll_dir_striped(child_inode)) {
4682                         CERROR("%s: MDT doesn't support stripe directory "
4683                                "migration!\n", ll_i2sbi(parent)->ll_fsname);
4684                         GOTO(out_iput, rc = -EOPNOTSUPP);
4685                 }
4686         }
4687
4688         /*
4689          * lfs migrate command needs to be blocked on the client
4690          * by checking the migrate FID against the FID of the
4691          * filesystem root.
4692          */
4693         if (is_root_inode(child_inode))
4694                 GOTO(out_iput, rc = -EINVAL);
4695
4696         if (IS_ENCRYPTED(child_inode)) {
4697                 rc = llcrypt_get_encryption_info(child_inode);
4698                 if (rc)
4699                         GOTO(out_iput, rc);
4700                 if (!llcrypt_has_encryption_key(child_inode)) {
4701                         CDEBUG(D_SEC, "no enc key for "DFID"\n",
4702                                PFID(ll_inode2fid(child_inode)));
4703                         GOTO(out_iput, rc = -ENOKEY);
4704                 }
4705         }
4706
4707         op_data = ll_prep_md_op_data(NULL, parent, NULL, name, namelen,
4708                                      child_inode->i_mode, LUSTRE_OPC_ANY, NULL);
4709         if (IS_ERR(op_data))
4710                 GOTO(out_iput, rc = PTR_ERR(op_data));
4711
4712         inode_lock(child_inode);
4713         op_data->op_fid3 = *ll_inode2fid(child_inode);
4714         if (!fid_is_sane(&op_data->op_fid3)) {
4715                 CERROR("%s: migrate %s, but FID "DFID" is insane\n",
4716                        ll_i2sbi(parent)->ll_fsname, name,
4717                        PFID(&op_data->op_fid3));
4718                 GOTO(out_unlock, rc = -EINVAL);
4719         }
4720
4721         op_data->op_cli_flags |= CLI_MIGRATE | CLI_SET_MEA;
4722         op_data->op_data = lum;
4723         op_data->op_data_size = lumlen;
4724
4725 again:
4726         if (S_ISREG(child_inode->i_mode)) {
4727                 och = ll_lease_open(child_inode, NULL, FMODE_WRITE, 0);
4728                 if (IS_ERR(och)) {
4729                         rc = PTR_ERR(och);
4730                         och = NULL;
4731                         GOTO(out_unlock, rc);
4732                 }
4733
4734                 rc = ll_data_version(child_inode, &data_version,
4735                                      LL_DV_WR_FLUSH);
4736                 if (rc != 0)
4737                         GOTO(out_close, rc);
4738
4739                 op_data->op_open_handle = och->och_open_handle;
4740                 op_data->op_data_version = data_version;
4741                 op_data->op_lease_handle = och->och_lease_handle;
4742                 op_data->op_bias |= MDS_CLOSE_MIGRATE;
4743
4744                 spin_lock(&och->och_mod->mod_open_req->rq_lock);
4745                 och->och_mod->mod_open_req->rq_replay = 0;
4746                 spin_unlock(&och->och_mod->mod_open_req->rq_lock);
4747         }
4748
4749         rc = md_rename(ll_i2sbi(parent)->ll_md_exp, op_data, name, namelen,
4750                        name, namelen, &request);
4751         if (rc == 0) {
4752                 LASSERT(request != NULL);
4753                 ll_update_times(request, parent);
4754         }
4755
4756         if (rc == 0 || rc == -EAGAIN) {
4757                 body = req_capsule_server_get(&request->rq_pill, &RMF_MDT_BODY);
4758                 LASSERT(body != NULL);
4759
4760                 /* If the server does release layout lock, then we cleanup
4761                  * the client och here, otherwise release it in out_close: */
4762                 if (och && body->mbo_valid & OBD_MD_CLOSE_INTENT_EXECED) {
4763                         obd_mod_put(och->och_mod);
4764                         md_clear_open_replay_data(ll_i2sbi(parent)->ll_md_exp,
4765                                                   och);
4766                         och->och_open_handle.cookie = DEAD_HANDLE_MAGIC;
4767                         OBD_FREE_PTR(och);
4768                         och = NULL;
4769                 }
4770         }
4771
4772         if (request != NULL) {
4773                 ptlrpc_req_finished(request);
4774                 request = NULL;
4775         }
4776
4777         /* Try again if the lease has cancelled. */
4778         if (rc == -EAGAIN && S_ISREG(child_inode->i_mode))
4779                 goto again;
4780
4781 out_close:
4782         if (och)
4783                 ll_lease_close(och, child_inode, NULL);
4784         if (!rc)
4785                 clear_nlink(child_inode);
4786 out_unlock:
4787         inode_unlock(child_inode);
4788         ll_finish_md_op_data(op_data);
4789 out_iput:
4790         iput(child_inode);
4791         RETURN(rc);
4792 }
4793
4794 static int
4795 ll_file_noflock(struct file *file, int cmd, struct file_lock *file_lock)
4796 {
4797         struct ll_file_data *fd = file->private_data;
4798         ENTRY;
4799
4800         /*
4801          * In order to avoid flood of warning messages, only print one message
4802          * for one file. And the entire message rate on the client is limited
4803          * by CDEBUG_LIMIT too.
4804          */
4805         if (!(fd->fd_flags & LL_FILE_FLOCK_WARNING)) {
4806                 fd->fd_flags |= LL_FILE_FLOCK_WARNING;
4807                 CDEBUG_LIMIT(D_TTY | D_CONSOLE,
4808                              "flock disabled, mount with '-o [local]flock' to enable\r\n");
4809         }
4810         RETURN(-ENOSYS);
4811 }
4812
4813 /**
4814  * test if some locks matching bits and l_req_mode are acquired
4815  * - bits can be in different locks
4816  * - if found clear the common lock bits in *bits
4817  * - the bits not found, are kept in *bits
4818  * \param inode [IN]
4819  * \param bits [IN] searched lock bits [IN]
4820  * \param l_req_mode [IN] searched lock mode
4821  * \retval boolean, true iff all bits are found
4822  */
4823 int ll_have_md_lock(struct inode *inode, __u64 *bits, enum ldlm_mode l_req_mode)
4824 {
4825         struct lustre_handle lockh;
4826         union ldlm_policy_data policy;
4827         enum ldlm_mode mode = (l_req_mode == LCK_MINMODE) ?
4828                               (LCK_CR | LCK_CW | LCK_PR | LCK_PW) : l_req_mode;
4829         struct lu_fid *fid;
4830         __u64 flags;
4831         int i;
4832         ENTRY;
4833
4834         if (!inode)
4835                RETURN(0);
4836
4837         fid = &ll_i2info(inode)->lli_fid;
4838         CDEBUG(D_INFO, "trying to match res "DFID" mode %s\n", PFID(fid),
4839                ldlm_lockname[mode]);
4840
4841         flags = LDLM_FL_BLOCK_GRANTED | LDLM_FL_CBPENDING | LDLM_FL_TEST_LOCK;
4842         for (i = 0; i < MDS_INODELOCK_NUMBITS && *bits != 0; i++) {
4843                 policy.l_inodebits.bits = *bits & BIT(i);
4844                 if (policy.l_inodebits.bits == 0)
4845                         continue;
4846
4847                 if (md_lock_match(ll_i2mdexp(inode), flags, fid, LDLM_IBITS,
4848                                   &policy, mode, &lockh)) {
4849                         struct ldlm_lock *lock;
4850
4851                         lock = ldlm_handle2lock(&lockh);
4852                         if (lock) {
4853                                 *bits &=
4854                                         ~(lock->l_policy_data.l_inodebits.bits);
4855                                 LDLM_LOCK_PUT(lock);
4856                         } else {
4857                                 *bits &= ~policy.l_inodebits.bits;
4858                         }
4859                 }
4860         }
4861         RETURN(*bits == 0);
4862 }
4863
4864 enum ldlm_mode ll_take_md_lock(struct inode *inode, __u64 bits,
4865                                struct lustre_handle *lockh, __u64 flags,
4866                                enum ldlm_mode mode)
4867 {
4868         union ldlm_policy_data policy = { .l_inodebits = { bits } };
4869         struct lu_fid *fid;
4870         enum ldlm_mode rc;
4871         ENTRY;
4872
4873         fid = &ll_i2info(inode)->lli_fid;
4874         CDEBUG(D_INFO, "trying to match res "DFID"\n", PFID(fid));
4875
4876         rc = md_lock_match(ll_i2mdexp(inode), LDLM_FL_BLOCK_GRANTED|flags,
4877                            fid, LDLM_IBITS, &policy, mode, lockh);
4878
4879         RETURN(rc);
4880 }
4881
4882 static int ll_inode_revalidate_fini(struct inode *inode, int rc)
4883 {
4884         /* Already unlinked. Just update nlink and return success */
4885         if (rc == -ENOENT) {
4886                 clear_nlink(inode);
4887                 /* If it is striped directory, and there is bad stripe
4888                  * Let's revalidate the dentry again, instead of returning
4889                  * error */
4890                 if (ll_dir_striped(inode))
4891                         return 0;
4892
4893                 /* This path cannot be hit for regular files unless in
4894                  * case of obscure races, so no need to to validate
4895                  * size. */
4896                 if (!S_ISREG(inode->i_mode) && !S_ISDIR(inode->i_mode))
4897                         return 0;
4898         } else if (rc != 0) {
4899                 CDEBUG_LIMIT((rc == -EACCES || rc == -EIDRM) ? D_INFO : D_ERROR,
4900                              "%s: revalidate FID "DFID" error: rc = %d\n",
4901                              ll_i2sbi(inode)->ll_fsname,
4902                              PFID(ll_inode2fid(inode)), rc);
4903         }
4904
4905         return rc;
4906 }
4907
4908 static int ll_inode_revalidate(struct dentry *dentry, enum ldlm_intent_flags op)
4909 {
4910         struct inode *parent;
4911         struct inode *inode = dentry->d_inode;
4912         struct obd_export *exp = ll_i2mdexp(inode);
4913         struct lookup_intent oit = {
4914                 .it_op = op,
4915         };
4916         struct ptlrpc_request *req = NULL;
4917         struct md_op_data *op_data;
4918         const char *name = NULL;
4919         size_t namelen = 0;
4920         int rc = 0;
4921         ENTRY;
4922
4923         CDEBUG(D_VFSTRACE, "VFS Op:inode="DFID"(%p),name=%s\n",
4924                PFID(ll_inode2fid(inode)), inode, dentry->d_name.name);
4925
4926         if (exp_connect_flags2(exp) & OBD_CONNECT2_GETATTR_PFID) {
4927                 parent = dentry->d_parent->d_inode;
4928                 name = dentry->d_name.name;
4929                 namelen = dentry->d_name.len;
4930         } else {
4931                 parent = inode;
4932         }
4933
4934         op_data = ll_prep_md_op_data(NULL, parent, inode, name, namelen, 0,
4935                                      LUSTRE_OPC_ANY, NULL);
4936         if (IS_ERR(op_data))
4937                 RETURN(PTR_ERR(op_data));
4938
4939         /* Call getattr by fid */
4940         if (exp_connect_flags2(exp) & OBD_CONNECT2_GETATTR_PFID)
4941                 op_data->op_flags = MF_GETATTR_BY_FID;
4942         rc = md_intent_lock(exp, op_data, &oit, &req, &ll_md_blocking_ast, 0);
4943         ll_finish_md_op_data(op_data);
4944         if (rc < 0) {
4945                 rc = ll_inode_revalidate_fini(inode, rc);
4946                 GOTO(out, rc);
4947         }
4948
4949         rc = ll_revalidate_it_finish(req, &oit, dentry);
4950         if (rc != 0) {
4951                 ll_intent_release(&oit);
4952                 GOTO(out, rc);
4953         }
4954
4955         /* Unlinked? Unhash dentry, so it is not picked up later by
4956          * do_lookup() -> ll_revalidate_it(). We cannot use d_drop
4957          * here to preserve get_cwd functionality on 2.6.
4958          * Bug 10503 */
4959         if (!dentry->d_inode->i_nlink)
4960                 d_lustre_invalidate(dentry);
4961
4962         ll_lookup_finish_locks(&oit, dentry);
4963 out:
4964         ptlrpc_req_finished(req);
4965
4966         return rc;
4967 }
4968
4969 static int ll_merge_md_attr(struct inode *inode)
4970 {
4971         struct ll_inode_info *lli = ll_i2info(inode);
4972         struct cl_attr attr = { 0 };
4973         int rc;
4974
4975         LASSERT(lli->lli_lsm_md != NULL);
4976
4977         if (!lmv_dir_striped(lli->lli_lsm_md))
4978                 RETURN(0);
4979
4980         down_read(&lli->lli_lsm_sem);
4981         rc = md_merge_attr(ll_i2mdexp(inode), ll_i2info(inode)->lli_lsm_md,
4982                            &attr, ll_md_blocking_ast);
4983         up_read(&lli->lli_lsm_sem);
4984         if (rc != 0)
4985                 RETURN(rc);
4986
4987         set_nlink(inode, attr.cat_nlink);
4988         inode->i_blocks = attr.cat_blocks;
4989         i_size_write(inode, attr.cat_size);
4990
4991         ll_i2info(inode)->lli_atime = attr.cat_atime;
4992         ll_i2info(inode)->lli_mtime = attr.cat_mtime;
4993         ll_i2info(inode)->lli_ctime = attr.cat_ctime;
4994
4995         RETURN(0);
4996 }
4997
4998 int ll_getattr_dentry(struct dentry *de, struct kstat *stat, u32 request_mask,
4999                       unsigned int flags, bool foreign)
5000 {
5001         struct inode *inode = de->d_inode;
5002         struct ll_sb_info *sbi = ll_i2sbi(inode);
5003         struct ll_inode_info *lli = ll_i2info(inode);
5004         struct inode *dir = de->d_parent->d_inode;
5005         bool need_glimpse = true;
5006         ktime_t kstart = ktime_get();
5007         int rc;
5008
5009         /* The OST object(s) determine the file size, blocks and mtime. */
5010         if (!(request_mask & STATX_SIZE || request_mask & STATX_BLOCKS ||
5011               request_mask & STATX_MTIME))
5012                 need_glimpse = false;
5013
5014         if (dentry_may_statahead(dir, de))
5015                 ll_start_statahead(dir, de, need_glimpse &&
5016                                    !(flags & AT_STATX_DONT_SYNC));
5017
5018         if (flags & AT_STATX_DONT_SYNC)
5019                 GOTO(fill_attr, rc = 0);
5020
5021         rc = ll_inode_revalidate(de, IT_GETATTR);
5022         if (rc < 0)
5023                 RETURN(rc);
5024
5025         /* foreign file/dir are always of zero length, so don't
5026          * need to validate size.
5027          */
5028         if (S_ISREG(inode->i_mode) && !foreign) {
5029                 bool cached;
5030
5031                 if (!need_glimpse)
5032                         GOTO(fill_attr, rc);
5033
5034                 rc = pcc_inode_getattr(inode, request_mask, flags, &cached);
5035                 if (cached && rc < 0)
5036                         RETURN(rc);
5037
5038                 if (cached)
5039                         GOTO(fill_attr, rc);
5040
5041                 /*
5042                  * If the returned attr is masked with OBD_MD_FLSIZE &
5043                  * OBD_MD_FLBLOCKS & OBD_MD_FLMTIME, it means that the file size
5044                  * or blocks obtained from MDT is strictly correct, and the file
5045                  * is usually not being modified by clients, and the [a|m|c]time
5046                  * got from MDT is also strictly correct.
5047                  * Under this circumstance, it does not need to send glimpse
5048                  * RPCs to OSTs for file attributes such as the size and blocks.
5049                  */
5050                 if (lli->lli_attr_valid & OBD_MD_FLSIZE &&
5051                     lli->lli_attr_valid & OBD_MD_FLBLOCKS &&
5052                     lli->lli_attr_valid & OBD_MD_FLMTIME) {
5053                         inode->i_mtime.tv_sec = lli->lli_mtime;
5054                         if (lli->lli_attr_valid & OBD_MD_FLATIME)
5055                                 inode->i_atime.tv_sec = lli->lli_atime;
5056                         if (lli->lli_attr_valid & OBD_MD_FLCTIME)
5057                                 inode->i_ctime.tv_sec = lli->lli_ctime;
5058                         GOTO(fill_attr, rc);
5059                 }
5060
5061                 /* In case of restore, the MDT has the right size and has
5062                  * already send it back without granting the layout lock,
5063                  * inode is up-to-date so glimpse is useless.
5064                  * Also to glimpse we need the layout, in case of a running
5065                  * restore the MDT holds the layout lock so the glimpse will
5066                  * block up to the end of restore (getattr will block)
5067                  */
5068                 if (!test_bit(LLIF_FILE_RESTORING, &lli->lli_flags)) {
5069                         rc = ll_glimpse_size(inode);
5070                         if (rc < 0)
5071                                 RETURN(rc);
5072                 }
5073         } else {
5074                 /* If object isn't regular a file then don't validate size. */
5075                 /* foreign dir is not striped dir */
5076                 if (ll_dir_striped(inode) && !foreign) {
5077                         rc = ll_merge_md_attr(inode);
5078                         if (rc < 0)
5079                                 RETURN(rc);
5080                 }
5081
5082                 if (lli->lli_attr_valid & OBD_MD_FLATIME)
5083                         inode->i_atime.tv_sec = lli->lli_atime;
5084                 if (lli->lli_attr_valid & OBD_MD_FLMTIME)
5085                         inode->i_mtime.tv_sec = lli->lli_mtime;
5086                 if (lli->lli_attr_valid & OBD_MD_FLCTIME)
5087                         inode->i_ctime.tv_sec = lli->lli_ctime;
5088         }
5089
5090 fill_attr:
5091         OBD_FAIL_TIMEOUT(OBD_FAIL_GETATTR_DELAY, 30);
5092
5093         if (ll_need_32bit_api(sbi)) {
5094                 stat->ino = cl_fid_build_ino(&lli->lli_fid, 1);
5095                 stat->dev = ll_compat_encode_dev(inode->i_sb->s_dev);
5096                 stat->rdev = ll_compat_encode_dev(inode->i_rdev);
5097         } else {
5098                 stat->ino = inode->i_ino;
5099                 stat->dev = inode->i_sb->s_dev;
5100                 stat->rdev = inode->i_rdev;
5101         }
5102
5103         /* foreign symlink to be exposed as a real symlink */
5104         if (!foreign)
5105                 stat->mode = inode->i_mode;
5106         else
5107                 stat->mode = (inode->i_mode & ~S_IFMT) | S_IFLNK;
5108
5109         stat->uid = inode->i_uid;
5110         stat->gid = inode->i_gid;
5111         stat->atime = inode->i_atime;
5112         stat->mtime = inode->i_mtime;
5113         stat->ctime = inode->i_ctime;
5114         /* stat->blksize is used to tell about preferred IO size */
5115         if (sbi->ll_stat_blksize)
5116                 stat->blksize = sbi->ll_stat_blksize;
5117         else if (S_ISREG(inode->i_mode))
5118                 stat->blksize = 1 << min(PTLRPC_MAX_BRW_BITS + 1,
5119                                          LL_MAX_BLKSIZE_BITS);
5120         else
5121                 stat->blksize = 1 << inode->i_sb->s_blocksize_bits;
5122
5123         stat->nlink = inode->i_nlink;
5124         stat->size = i_size_read(inode);
5125         stat->blocks = inode->i_blocks;
5126
5127 #ifdef HAVE_INODEOPS_ENHANCED_GETATTR
5128         if (flags & AT_STATX_DONT_SYNC) {
5129                 if (stat->size == 0 &&
5130                     lli->lli_attr_valid & OBD_MD_FLLAZYSIZE)
5131                         stat->size = lli->lli_lazysize;
5132                 if (stat->blocks == 0 &&
5133                     lli->lli_attr_valid & OBD_MD_FLLAZYBLOCKS)
5134                         stat->blocks = lli->lli_lazyblocks;
5135         }
5136
5137         if (lli->lli_attr_valid & OBD_MD_FLBTIME) {
5138                 stat->result_mask |= STATX_BTIME;
5139                 stat->btime.tv_sec = lli->lli_btime;
5140         }
5141
5142         stat->attributes_mask = STATX_ATTR_IMMUTABLE | STATX_ATTR_APPEND;
5143         stat->attributes |= ll_inode_to_ext_flags(inode->i_flags);
5144         stat->result_mask &= request_mask;
5145 #endif
5146
5147         ll_stats_ops_tally(sbi, LPROC_LL_GETATTR,
5148                            ktime_us_delta(ktime_get(), kstart));
5149
5150         return 0;
5151 }
5152
5153 #ifdef HAVE_INODEOPS_ENHANCED_GETATTR
5154 int ll_getattr(const struct path *path, struct kstat *stat,
5155                u32 request_mask, unsigned int flags)
5156 {
5157         return ll_getattr_dentry(path->dentry, stat, request_mask, flags,
5158                                  false);
5159 }
5160 #else
5161 int ll_getattr(struct vfsmount *mnt, struct dentry *de, struct kstat *stat)
5162 {
5163         return ll_getattr_dentry(de, stat, STATX_BASIC_STATS,
5164                                  AT_STATX_SYNC_AS_STAT, false);
5165 }
5166 #endif
5167
5168 int cl_falloc(struct inode *inode, int mode, loff_t offset, loff_t len)
5169 {
5170         struct lu_env *env;
5171         struct cl_io *io;
5172         __u16 refcheck;
5173         int rc;
5174         loff_t size = i_size_read(inode);
5175
5176         ENTRY;
5177
5178         env = cl_env_get(&refcheck);
5179         if (IS_ERR(env))
5180                 RETURN(PTR_ERR(env));
5181
5182         io = vvp_env_thread_io(env);
5183         io->ci_obj = ll_i2info(inode)->lli_clob;
5184         io->ci_verify_layout = 1;
5185         io->u.ci_setattr.sa_parent_fid = lu_object_fid(&io->ci_obj->co_lu);
5186         io->u.ci_setattr.sa_falloc_mode = mode;
5187         io->u.ci_setattr.sa_falloc_offset = offset;
5188         io->u.ci_setattr.sa_falloc_end = offset + len;
5189         io->u.ci_setattr.sa_subtype = CL_SETATTR_FALLOCATE;
5190         if (io->u.ci_setattr.sa_falloc_end > size) {
5191                 loff_t newsize = io->u.ci_setattr.sa_falloc_end;
5192
5193                 /* Check new size against VFS/VM file size limit and rlimit */
5194                 rc = inode_newsize_ok(inode, newsize);
5195                 if (rc)
5196                         goto out;
5197                 if (newsize > ll_file_maxbytes(inode)) {
5198                         CDEBUG(D_INODE, "file size too large %llu > %llu\n",
5199                                (unsigned long long)newsize,
5200                                ll_file_maxbytes(inode));
5201                         rc = -EFBIG;
5202                         goto out;
5203                 }
5204         }
5205
5206         do {
5207                 rc = cl_io_init(env, io, CIT_SETATTR, io->ci_obj);
5208                 if (!rc)
5209                         rc = cl_io_loop(env, io);
5210                 else
5211                         rc = io->ci_result;
5212                 cl_io_fini(env, io);
5213         } while (unlikely(io->ci_need_restart));
5214
5215 out:
5216         cl_env_put(env, &refcheck);
5217         RETURN(rc);
5218 }
5219
5220 long ll_fallocate(struct file *filp, int mode, loff_t offset, loff_t len)
5221 {
5222         struct inode *inode = filp->f_path.dentry->d_inode;
5223         int rc;
5224
5225         if (offset < 0 || len <= 0)
5226                 RETURN(-EINVAL);
5227         /*
5228          * Encrypted inodes can't handle collapse range or zero range or insert
5229          * range since we would need to re-encrypt blocks with a different IV or
5230          * XTS tweak (which are based on the logical block number).
5231          * Similar to what ext4 does.
5232          */
5233         if (IS_ENCRYPTED(inode) &&
5234             (mode & (FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_INSERT_RANGE |
5235                      FALLOC_FL_ZERO_RANGE)))
5236                 RETURN(-EOPNOTSUPP);
5237
5238         /*
5239          * mode == 0 (which is standard prealloc) and PUNCH is supported
5240          * Rest of mode options are not supported yet.
5241          */
5242         if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE))
5243                 RETURN(-EOPNOTSUPP);
5244
5245         ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_FALLOCATE, 1);
5246
5247         rc = cl_falloc(inode, mode, offset, len);
5248         /*
5249          * ENOTSUPP (524) is an NFSv3 specific error code erroneously
5250          * used by Lustre in several places. Retuning it here would
5251          * confuse applications that explicity test for EOPNOTSUPP
5252          * (95) and fall back to ftruncate().
5253          */
5254         if (rc == -ENOTSUPP)
5255                 rc = -EOPNOTSUPP;
5256
5257         RETURN(rc);
5258 }
5259
5260 static int ll_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
5261                      __u64 start, __u64 len)
5262 {
5263         int             rc;
5264         size_t          num_bytes;
5265         struct fiemap   *fiemap;
5266         unsigned int    extent_count = fieinfo->fi_extents_max;
5267
5268         num_bytes = sizeof(*fiemap) + (extent_count *
5269                                        sizeof(struct fiemap_extent));
5270         OBD_ALLOC_LARGE(fiemap, num_bytes);
5271
5272         if (fiemap == NULL)
5273                 RETURN(-ENOMEM);
5274
5275         fiemap->fm_flags = fieinfo->fi_flags;
5276         fiemap->fm_extent_count = fieinfo->fi_extents_max;
5277         fiemap->fm_start = start;
5278         fiemap->fm_length = len;
5279         if (extent_count > 0 &&
5280             copy_from_user(&fiemap->fm_extents[0], fieinfo->fi_extents_start,
5281                            sizeof(struct fiemap_extent)) != 0)
5282                 GOTO(out, rc = -EFAULT);
5283
5284         rc = ll_do_fiemap(inode, fiemap, num_bytes);
5285
5286         if (IS_ENCRYPTED(inode)) {
5287                 int i;
5288
5289                 for (i = 0; i < fiemap->fm_mapped_extents; i++)
5290                         fiemap->fm_extents[i].fe_flags |=
5291                                 FIEMAP_EXTENT_DATA_ENCRYPTED |
5292                                 FIEMAP_EXTENT_ENCODED;
5293         }
5294
5295         fieinfo->fi_flags = fiemap->fm_flags;
5296         fieinfo->fi_extents_mapped = fiemap->fm_mapped_extents;
5297         if (extent_count > 0 &&
5298             copy_to_user(fieinfo->fi_extents_start, &fiemap->fm_extents[0],
5299                          fiemap->fm_mapped_extents *
5300                          sizeof(struct fiemap_extent)) != 0)
5301                 GOTO(out, rc = -EFAULT);
5302 out:
5303         OBD_FREE_LARGE(fiemap, num_bytes);
5304         return rc;
5305 }
5306
5307 int ll_inode_permission(struct inode *inode, int mask)
5308 {
5309         int rc = 0;
5310         struct ll_sb_info *sbi;
5311         struct root_squash_info *squash;
5312         struct cred *cred = NULL;
5313         const struct cred *old_cred = NULL;
5314         bool squash_id = false;
5315         ktime_t kstart = ktime_get();
5316
5317         ENTRY;
5318
5319         if (mask & MAY_NOT_BLOCK)
5320                 return -ECHILD;
5321
5322         /*
5323          * as root inode are NOT getting validated in lookup operation,
5324          * need to do it before permission check.
5325          */
5326
5327         if (is_root_inode(inode)) {
5328                 rc = ll_inode_revalidate(inode->i_sb->s_root, IT_LOOKUP);
5329                 if (rc)
5330                         RETURN(rc);
5331         }
5332
5333         CDEBUG(D_VFSTRACE, "VFS Op:inode="DFID"(%p), inode mode %x mask %o\n",
5334                PFID(ll_inode2fid(inode)), inode, inode->i_mode, mask);
5335
5336         /* squash fsuid/fsgid if needed */
5337         sbi = ll_i2sbi(inode);
5338         squash = &sbi->ll_squash;
5339         if (unlikely(squash->rsi_uid != 0 &&
5340                      uid_eq(current_fsuid(), GLOBAL_ROOT_UID) &&
5341                      !(sbi->ll_flags & LL_SBI_NOROOTSQUASH))) {
5342                         squash_id = true;
5343         }
5344         if (squash_id) {
5345                 CDEBUG(D_OTHER, "squash creds (%d:%d)=>(%d:%d)\n",
5346                        __kuid_val(current_fsuid()), __kgid_val(current_fsgid()),
5347                        squash->rsi_uid, squash->rsi_gid);
5348
5349                 /* update current process's credentials
5350                  * and FS capability */
5351                 cred = prepare_creds();
5352                 if (cred == NULL)
5353                         RETURN(-ENOMEM);
5354
5355                 cred->fsuid = make_kuid(&init_user_ns, squash->rsi_uid);
5356                 cred->fsgid = make_kgid(&init_user_ns, squash->rsi_gid);
5357                 cred->cap_effective = cap_drop_nfsd_set(cred->cap_effective);
5358                 cred->cap_effective = cap_drop_fs_set(cred->cap_effective);
5359
5360                 old_cred = override_creds(cred);
5361         }
5362
5363         rc = generic_permission(inode, mask);
5364         /* restore current process's credentials and FS capability */
5365         if (squash_id) {
5366                 revert_creds(old_cred);
5367                 put_cred(cred);
5368         }
5369
5370         if (!rc)
5371                 ll_stats_ops_tally(sbi, LPROC_LL_INODE_PERM,
5372                                    ktime_us_delta(ktime_get(), kstart));
5373
5374         RETURN(rc);
5375 }
5376
5377 /* -o localflock - only provides locally consistent flock locks */
5378 static const struct file_operations ll_file_operations = {
5379 #ifdef HAVE_FILE_OPERATIONS_READ_WRITE_ITER
5380 # ifdef HAVE_SYNC_READ_WRITE
5381         .read           = new_sync_read,
5382         .write          = new_sync_write,
5383 # endif
5384         .read_iter      = ll_file_read_iter,
5385         .write_iter     = ll_file_write_iter,
5386 #else /* !HAVE_FILE_OPERATIONS_READ_WRITE_ITER */
5387         .read           = ll_file_read,
5388         .aio_read       = ll_file_aio_read,
5389         .write          = ll_file_write,
5390         .aio_write      = ll_file_aio_write,
5391 #endif /* HAVE_FILE_OPERATIONS_READ_WRITE_ITER */
5392         .unlocked_ioctl = ll_file_ioctl,
5393         .open           = ll_file_open,
5394         .release        = ll_file_release,
5395         .mmap           = ll_file_mmap,
5396         .llseek         = ll_file_seek,
5397 #ifndef HAVE_DEFAULT_FILE_SPLICE_READ_EXPORT
5398         .splice_read    = generic_file_splice_read,
5399 #else
5400         .splice_read    = pcc_file_splice_read,
5401 #endif
5402         .fsync          = ll_fsync,
5403         .flush          = ll_flush,
5404         .fallocate      = ll_fallocate,
5405 };
5406
5407 static const struct file_operations ll_file_operations_flock = {
5408 #ifdef HAVE_FILE_OPERATIONS_READ_WRITE_ITER
5409 # ifdef HAVE_SYNC_READ_WRITE
5410         .read           = new_sync_read,
5411         .write          = new_sync_write,
5412 # endif /* HAVE_SYNC_READ_WRITE */
5413         .read_iter      = ll_file_read_iter,
5414         .write_iter     = ll_file_write_iter,
5415 #else /* !HAVE_FILE_OPERATIONS_READ_WRITE_ITER */
5416         .read           = ll_file_read,
5417         .aio_read       = ll_file_aio_read,
5418         .write          = ll_file_write,
5419         .aio_write      = ll_file_aio_write,
5420 #endif /* HAVE_FILE_OPERATIONS_READ_WRITE_ITER */
5421         .unlocked_ioctl = ll_file_ioctl,
5422         .open           = ll_file_open,
5423         .release        = ll_file_release,
5424         .mmap           = ll_file_mmap,
5425         .llseek         = ll_file_seek,
5426 #ifndef HAVE_DEFAULT_FILE_SPLICE_READ_EXPORT
5427         .splice_read    = generic_file_splice_read,
5428 #else
5429         .splice_read    = pcc_file_splice_read,
5430 #endif
5431         .fsync          = ll_fsync,
5432         .flush          = ll_flush,
5433         .flock          = ll_file_flock,
5434         .lock           = ll_file_flock,
5435         .fallocate      = ll_fallocate,
5436 };
5437
5438 /* These are for -o noflock - to return ENOSYS on flock calls */
5439 static const struct file_operations ll_file_operations_noflock = {
5440 #ifdef HAVE_FILE_OPERATIONS_READ_WRITE_ITER
5441 # ifdef HAVE_SYNC_READ_WRITE
5442         .read           = new_sync_read,
5443         .write          = new_sync_write,
5444 # endif /* HAVE_SYNC_READ_WRITE */
5445         .read_iter      = ll_file_read_iter,
5446         .write_iter     = ll_file_write_iter,
5447 #else /* !HAVE_FILE_OPERATIONS_READ_WRITE_ITER */
5448         .read           = ll_file_read,
5449         .aio_read       = ll_file_aio_read,
5450         .write          = ll_file_write,
5451         .aio_write      = ll_file_aio_write,
5452 #endif /* HAVE_FILE_OPERATIONS_READ_WRITE_ITER */
5453         .unlocked_ioctl = ll_file_ioctl,
5454         .open           = ll_file_open,
5455         .release        = ll_file_release,
5456         .mmap           = ll_file_mmap,
5457         .llseek         = ll_file_seek,
5458 #ifndef HAVE_DEFAULT_FILE_SPLICE_READ_EXPORT
5459         .splice_read    = generic_file_splice_read,
5460 #else
5461         .splice_read    = pcc_file_splice_read,
5462 #endif
5463         .fsync          = ll_fsync,
5464         .flush          = ll_flush,
5465         .flock          = ll_file_noflock,
5466         .lock           = ll_file_noflock,
5467         .fallocate      = ll_fallocate,
5468 };
5469
5470 const struct inode_operations ll_file_inode_operations = {
5471         .setattr        = ll_setattr,
5472         .getattr        = ll_getattr,
5473         .permission     = ll_inode_permission,
5474 #ifdef HAVE_IOP_XATTR
5475         .setxattr       = ll_setxattr,
5476         .getxattr       = ll_getxattr,
5477         .removexattr    = ll_removexattr,
5478 #endif
5479         .listxattr      = ll_listxattr,
5480         .fiemap         = ll_fiemap,
5481         .get_acl        = ll_get_acl,
5482 #ifdef HAVE_IOP_SET_ACL
5483         .set_acl        = ll_set_acl,
5484 #endif
5485 };
5486
5487 const struct file_operations *ll_select_file_operations(struct ll_sb_info *sbi)
5488 {
5489         const struct file_operations *fops = &ll_file_operations_noflock;
5490
5491         if (sbi->ll_flags & LL_SBI_FLOCK)
5492                 fops = &ll_file_operations_flock;
5493         else if (sbi->ll_flags & LL_SBI_LOCALFLOCK)
5494                 fops = &ll_file_operations;
5495
5496         return fops;
5497 }
5498
5499 int ll_layout_conf(struct inode *inode, const struct cl_object_conf *conf)
5500 {
5501         struct ll_inode_info *lli = ll_i2info(inode);
5502         struct cl_object *obj = lli->lli_clob;
5503         struct lu_env *env;
5504         int rc;
5505         __u16 refcheck;
5506         ENTRY;
5507
5508         if (obj == NULL)
5509                 RETURN(0);
5510
5511         env = cl_env_get(&refcheck);
5512         if (IS_ERR(env))
5513                 RETURN(PTR_ERR(env));
5514
5515         rc = cl_conf_set(env, lli->lli_clob, conf);
5516         if (rc < 0)
5517                 GOTO(out, rc);
5518
5519         if (conf->coc_opc == OBJECT_CONF_SET) {
5520                 struct ldlm_lock *lock = conf->coc_lock;
5521                 struct cl_layout cl = {
5522                         .cl_layout_gen = 0,
5523                 };
5524
5525                 LASSERT(lock != NULL);
5526                 LASSERT(ldlm_has_layout(lock));
5527
5528                 /* it can only be allowed to match after layout is
5529                  * applied to inode otherwise false layout would be
5530                  * seen. Applying layout shoud happen before dropping
5531                  * the intent lock. */
5532                 ldlm_lock_allow_match(lock);
5533
5534                 rc = cl_object_layout_get(env, obj, &cl);
5535                 if (rc < 0)
5536                         GOTO(out, rc);
5537
5538                 CDEBUG(D_VFSTRACE,
5539                        DFID": layout version change: %u -> %u\n",
5540                        PFID(&lli->lli_fid), ll_layout_version_get(lli),
5541                        cl.cl_layout_gen);
5542                 ll_layout_version_set(lli, cl.cl_layout_gen);
5543         }
5544
5545 out:
5546         cl_env_put(env, &refcheck);
5547
5548         RETURN(rc < 0 ? rc : 0);
5549 }
5550
5551 /* Fetch layout from MDT with getxattr request, if it's not ready yet */
5552 static int ll_layout_fetch(struct inode *inode, struct ldlm_lock *lock)
5553
5554 {
5555         struct ll_sb_info *sbi = ll_i2sbi(inode);
5556         struct ptlrpc_request *req;
5557         void *lvbdata;
5558         void *lmm;
5559         int lmmsize;
5560         int rc;
5561         ENTRY;
5562
5563         CDEBUG(D_INODE, DFID" LVB_READY=%d l_lvb_data=%p l_lvb_len=%d\n",
5564                PFID(ll_inode2fid(inode)), ldlm_is_lvb_ready(lock),
5565                lock->l_lvb_data, lock->l_lvb_len);
5566
5567         if (lock->l_lvb_data != NULL)
5568                 RETURN(0);
5569
5570         /* if layout lock was granted right away, the layout is returned
5571          * within DLM_LVB of dlm reply; otherwise if the lock was ever
5572          * blocked and then granted via completion ast, we have to fetch
5573          * layout here. Please note that we can't use the LVB buffer in
5574          * completion AST because it doesn't have a large enough buffer */
5575         rc = ll_get_default_mdsize(sbi, &lmmsize);
5576         if (rc < 0)
5577                 RETURN(rc);
5578
5579         rc = md_getxattr(sbi->ll_md_exp, ll_inode2fid(inode), OBD_MD_FLXATTR,
5580                          XATTR_NAME_LOV, lmmsize, &req);
5581         if (rc < 0) {
5582                 if (rc == -ENODATA)
5583                         GOTO(out, rc = 0); /* empty layout */
5584                 else
5585                         RETURN(rc);
5586         }
5587
5588         lmmsize = rc;
5589         rc = 0;
5590         if (lmmsize == 0) /* empty layout */
5591                 GOTO(out, rc = 0);
5592
5593         lmm = req_capsule_server_sized_get(&req->rq_pill, &RMF_EADATA, lmmsize);
5594         if (lmm == NULL)
5595                 GOTO(out, rc = -EFAULT);
5596
5597         OBD_ALLOC_LARGE(lvbdata, lmmsize);
5598         if (lvbdata == NULL)
5599                 GOTO(out, rc = -ENOMEM);
5600
5601         memcpy(lvbdata, lmm, lmmsize);
5602         lock_res_and_lock(lock);
5603         if (unlikely(lock->l_lvb_data == NULL)) {
5604                 lock->l_lvb_type = LVB_T_LAYOUT;
5605                 lock->l_lvb_data = lvbdata;
5606                 lock->l_lvb_len = lmmsize;
5607                 lvbdata = NULL;
5608         }
5609         unlock_res_and_lock(lock);
5610
5611         if (lvbdata)
5612                 OBD_FREE_LARGE(lvbdata, lmmsize);
5613
5614         EXIT;
5615
5616 out:
5617         ptlrpc_req_finished(req);
5618         return rc;
5619 }
5620
5621 /**
5622  * Apply the layout to the inode. Layout lock is held and will be released
5623  * in this function.
5624  */
5625 static int ll_layout_lock_set(struct lustre_handle *lockh, enum ldlm_mode mode,
5626                               struct inode *inode)
5627 {
5628         struct ll_inode_info *lli = ll_i2info(inode);
5629         struct ll_sb_info    *sbi = ll_i2sbi(inode);
5630         struct ldlm_lock *lock;
5631         struct cl_object_conf conf;
5632         int rc = 0;
5633         bool lvb_ready;
5634         bool wait_layout = false;
5635         ENTRY;
5636
5637         LASSERT(lustre_handle_is_used(lockh));
5638
5639         lock = ldlm_handle2lock(lockh);
5640         LASSERT(lock != NULL);
5641         LASSERT(ldlm_has_layout(lock));
5642
5643         LDLM_DEBUG(lock, "file "DFID"(%p) being reconfigured",
5644                    PFID(&lli->lli_fid), inode);
5645
5646         /* in case this is a caching lock and reinstate with new inode */
5647         md_set_lock_data(sbi->ll_md_exp, lockh, inode, NULL);
5648
5649         lock_res_and_lock(lock);
5650         lvb_ready = ldlm_is_lvb_ready(lock);
5651         unlock_res_and_lock(lock);
5652
5653         /* checking lvb_ready is racy but this is okay. The worst case is
5654          * that multi processes may configure the file on the same time. */
5655         if (lvb_ready)
5656                 GOTO(out, rc = 0);
5657
5658         rc = ll_layout_fetch(inode, lock);
5659         if (rc < 0)
5660                 GOTO(out, rc);
5661
5662         /* for layout lock, lmm is stored in lock's lvb.
5663          * lvb_data is immutable if the lock is held so it's safe to access it
5664          * without res lock.
5665          *
5666          * set layout to file. Unlikely this will fail as old layout was
5667          * surely eliminated */
5668         memset(&conf, 0, sizeof conf);
5669         conf.coc_opc = OBJECT_CONF_SET;
5670         conf.coc_inode = inode;
5671         conf.coc_lock = lock;
5672         conf.u.coc_layout.lb_buf = lock->l_lvb_data;
5673         conf.u.coc_layout.lb_len = lock->l_lvb_len;
5674         rc = ll_layout_conf(inode, &conf);
5675
5676         /* refresh layout failed, need to wait */
5677         wait_layout = rc == -EBUSY;
5678         EXIT;
5679 out:
5680         LDLM_LOCK_PUT(lock);
5681         ldlm_lock_decref(lockh, mode);
5682
5683         /* wait for IO to complete if it's still being used. */
5684         if (wait_layout) {
5685                 CDEBUG(D_INODE, "%s: "DFID"(%p) wait for layout reconf\n",
5686                        sbi->ll_fsname, PFID(&lli->lli_fid), inode);
5687
5688                 memset(&conf, 0, sizeof conf);
5689                 conf.coc_opc = OBJECT_CONF_WAIT;
5690                 conf.coc_inode = inode;
5691                 rc = ll_layout_conf(inode, &conf);
5692                 if (rc == 0)
5693                         rc = -EAGAIN;
5694
5695                 CDEBUG(D_INODE, "%s file="DFID" waiting layout return: %d\n",
5696                        sbi->ll_fsname, PFID(&lli->lli_fid), rc);
5697         }
5698         RETURN(rc);
5699 }
5700
5701 /**
5702  * Issue layout intent RPC to MDS.
5703  * \param inode [in]    file inode
5704  * \param intent [in]   layout intent
5705  *
5706  * \retval 0    on success
5707  * \retval < 0  error code
5708  */
5709 static int ll_layout_intent(struct inode *inode, struct layout_intent *intent)
5710 {
5711         struct ll_inode_info  *lli = ll_i2info(inode);
5712         struct ll_sb_info     *sbi = ll_i2sbi(inode);
5713         struct md_op_data     *op_data;
5714         struct lookup_intent it;
5715         struct ptlrpc_request *req;
5716         int rc;
5717         ENTRY;
5718
5719         op_data = ll_prep_md_op_data(NULL, inode, inode, NULL,
5720                                      0, 0, LUSTRE_OPC_ANY, NULL);
5721         if (IS_ERR(op_data))
5722                 RETURN(PTR_ERR(op_data));
5723
5724         op_data->op_data = intent;
5725         op_data->op_data_size = sizeof(*intent);
5726
5727         memset(&it, 0, sizeof(it));
5728         it.it_op = IT_LAYOUT;
5729         if (intent->li_opc == LAYOUT_INTENT_WRITE ||
5730             intent->li_opc == LAYOUT_INTENT_TRUNC)
5731                 it.it_flags = FMODE_WRITE;
5732
5733         LDLM_DEBUG_NOLOCK("%s: requeue layout lock for file "DFID"(%p)",
5734                           sbi->ll_fsname, PFID(&lli->lli_fid), inode);
5735
5736         rc = md_intent_lock(sbi->ll_md_exp, op_data, &it, &req,
5737                             &ll_md_blocking_ast, 0);
5738         if (it.it_request != NULL)
5739                 ptlrpc_req_finished(it.it_request);
5740         it.it_request = NULL;
5741
5742         ll_finish_md_op_data(op_data);
5743
5744         /* set lock data in case this is a new lock */
5745         if (!rc)
5746                 ll_set_lock_data(sbi->ll_md_exp, inode, &it, NULL);
5747
5748         ll_intent_drop_lock(&it);
5749
5750         RETURN(rc);
5751 }
5752
5753 /**
5754  * This function checks if there exists a LAYOUT lock on the client side,
5755  * or enqueues it if it doesn't have one in cache.
5756  *
5757  * This function will not hold layout lock so it may be revoked any time after
5758  * this function returns. Any operations depend on layout should be redone
5759  * in that case.
5760  *
5761  * This function should be called before lov_io_init() to get an uptodate
5762  * layout version, the caller should save the version number and after IO
5763  * is finished, this function should be called again to verify that layout
5764  * is not changed during IO time.
5765  */
5766 int ll_layout_refresh(struct inode *inode, __u32 *gen)
5767 {
5768         struct ll_inode_info    *lli = ll_i2info(inode);
5769         struct ll_sb_info       *sbi = ll_i2sbi(inode);
5770         struct lustre_handle lockh;
5771         struct layout_intent intent = {
5772                 .li_opc = LAYOUT_INTENT_ACCESS,
5773         };
5774         enum ldlm_mode mode;
5775         int rc;
5776         ENTRY;
5777
5778         *gen = ll_layout_version_get(lli);
5779         if (!(sbi->ll_flags & LL_SBI_LAYOUT_LOCK) || *gen != CL_LAYOUT_GEN_NONE)
5780                 RETURN(0);
5781
5782         /* sanity checks */
5783         LASSERT(fid_is_sane(ll_inode2fid(inode)));
5784         LASSERT(S_ISREG(inode->i_mode));
5785
5786         /* take layout lock mutex to enqueue layout lock exclusively. */
5787         mutex_lock(&lli->lli_layout_mutex);
5788
5789         while (1) {
5790                 /* mostly layout lock is caching on the local side, so try to
5791                  * match it before grabbing layout lock mutex. */
5792                 mode = ll_take_md_lock(inode, MDS_INODELOCK_LAYOUT, &lockh, 0,
5793                                        LCK_CR | LCK_CW | LCK_PR |
5794                                        LCK_PW | LCK_EX);
5795                 if (mode != 0) { /* hit cached lock */
5796                         rc = ll_layout_lock_set(&lockh, mode, inode);
5797                         if (rc == -EAGAIN)
5798                                 continue;
5799                         break;
5800                 }
5801
5802                 rc = ll_layout_intent(inode, &intent);
5803                 if (rc != 0)
5804                         break;
5805         }
5806
5807         if (rc == 0)
5808                 *gen = ll_layout_version_get(lli);
5809         mutex_unlock(&lli->lli_layout_mutex);
5810
5811         RETURN(rc);
5812 }
5813
5814 /**
5815  * Issue layout intent RPC indicating where in a file an IO is about to write.
5816  *
5817  * \param[in] inode     file inode.
5818  * \param[in] ext       write range with start offset of fille in bytes where
5819  *                      an IO is about to write, and exclusive end offset in
5820  *                      bytes.
5821  *
5822  * \retval 0    on success
5823  * \retval < 0  error code
5824  */
5825 int ll_layout_write_intent(struct inode *inode, enum layout_intent_opc opc,
5826                            struct lu_extent *ext)
5827 {
5828         struct layout_intent intent = {
5829                 .li_opc = opc,
5830                 .li_extent.e_start = ext->e_start,
5831                 .li_extent.e_end = ext->e_end,
5832         };
5833         int rc;
5834         ENTRY;
5835
5836         rc = ll_layout_intent(inode, &intent);
5837
5838         RETURN(rc);
5839 }
5840
5841 /**
5842  *  This function send a restore request to the MDT
5843  */
5844 int ll_layout_restore(struct inode *inode, loff_t offset, __u64 length)
5845 {
5846         struct hsm_user_request *hur;
5847         int                      len, rc;
5848         ENTRY;
5849
5850         len = sizeof(struct hsm_user_request) +
5851               sizeof(struct hsm_user_item);
5852         OBD_ALLOC(hur, len);
5853         if (hur == NULL)
5854                 RETURN(-ENOMEM);
5855
5856         hur->hur_request.hr_action = HUA_RESTORE;
5857         hur->hur_request.hr_archive_id = 0;
5858         hur->hur_request.hr_flags = 0;
5859         memcpy(&hur->hur_user_item[0].hui_fid, &ll_i2info(inode)->lli_fid,
5860                sizeof(hur->hur_user_item[0].hui_fid));
5861         hur->hur_user_item[0].hui_extent.offset = offset;
5862         hur->hur_user_item[0].hui_extent.length = length;
5863         hur->hur_request.hr_itemcount = 1;
5864         rc = obd_iocontrol(LL_IOC_HSM_REQUEST, ll_i2sbi(inode)->ll_md_exp,
5865                            len, hur, NULL);
5866         OBD_FREE(hur, len);
5867         RETURN(rc);
5868 }