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