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