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