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