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