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