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