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