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