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