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