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