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