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