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