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