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