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