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