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