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