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