Whamcloud - gitweb
LU-10092 First phase of persistent client cache project merging
[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 static 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
1405         /* FLR: only use non-delay I/O for read as there is only one
1406          * avaliable mirror for write. */
1407         io->ci_ndelay = !(iot == CIT_WRITE);
1408
1409         ll_io_set_mirror(io, file);
1410 }
1411
1412 static void ll_heat_add(struct inode *inode, enum cl_io_type iot,
1413                         __u64 count)
1414 {
1415         struct ll_inode_info *lli = ll_i2info(inode);
1416         struct ll_sb_info *sbi = ll_i2sbi(inode);
1417         enum obd_heat_type sample_type;
1418         enum obd_heat_type iobyte_type;
1419         __u64 now = ktime_get_real_seconds();
1420
1421         if (!ll_sbi_has_file_heat(sbi) ||
1422             lli->lli_heat_flags & LU_HEAT_FLAG_OFF)
1423                 return;
1424
1425         if (iot == CIT_READ) {
1426                 sample_type = OBD_HEAT_READSAMPLE;
1427                 iobyte_type = OBD_HEAT_READBYTE;
1428         } else if (iot == CIT_WRITE) {
1429                 sample_type = OBD_HEAT_WRITESAMPLE;
1430                 iobyte_type = OBD_HEAT_WRITEBYTE;
1431         } else {
1432                 return;
1433         }
1434
1435         spin_lock(&lli->lli_heat_lock);
1436         obd_heat_add(&lli->lli_heat_instances[sample_type], now, 1,
1437                      sbi->ll_heat_decay_weight, sbi->ll_heat_period_second);
1438         obd_heat_add(&lli->lli_heat_instances[iobyte_type], now, count,
1439                      sbi->ll_heat_decay_weight, sbi->ll_heat_period_second);
1440         spin_unlock(&lli->lli_heat_lock);
1441 }
1442
1443 static ssize_t
1444 ll_file_io_generic(const struct lu_env *env, struct vvp_io_args *args,
1445                    struct file *file, enum cl_io_type iot,
1446                    loff_t *ppos, size_t count)
1447 {
1448         struct vvp_io           *vio = vvp_env_io(env);
1449         struct inode            *inode = file_inode(file);
1450         struct ll_inode_info    *lli = ll_i2info(inode);
1451         struct ll_file_data     *fd  = LUSTRE_FPRIVATE(file);
1452         struct range_lock       range;
1453         struct cl_io            *io;
1454         ssize_t                 result = 0;
1455         int                     rc = 0;
1456         unsigned                retried = 0;
1457         bool                    restarted = false;
1458
1459         ENTRY;
1460
1461         CDEBUG(D_VFSTRACE, "%s: %s ppos: %llu, count: %zu\n",
1462                 file_dentry(file)->d_name.name,
1463                 iot == CIT_READ ? "read" : "write", *ppos, count);
1464
1465 restart:
1466         io = vvp_env_thread_io(env);
1467         ll_io_init(io, file, iot);
1468         io->ci_ndelay_tried = retried;
1469
1470         if (cl_io_rw_init(env, io, iot, *ppos, count) == 0) {
1471                 bool range_locked = false;
1472
1473                 if (file->f_flags & O_APPEND)
1474                         range_lock_init(&range, 0, LUSTRE_EOF);
1475                 else
1476                         range_lock_init(&range, *ppos, *ppos + count - 1);
1477
1478                 vio->vui_fd  = LUSTRE_FPRIVATE(file);
1479                 vio->vui_io_subtype = args->via_io_subtype;
1480
1481                 switch (vio->vui_io_subtype) {
1482                 case IO_NORMAL:
1483                         vio->vui_iter = args->u.normal.via_iter;
1484                         vio->vui_iocb = args->u.normal.via_iocb;
1485                         /* Direct IO reads must also take range lock,
1486                          * or multiple reads will try to work on the same pages
1487                          * See LU-6227 for details. */
1488                         if (((iot == CIT_WRITE) ||
1489                             (iot == CIT_READ && (file->f_flags & O_DIRECT))) &&
1490                             !(vio->vui_fd->fd_flags & LL_FILE_GROUP_LOCKED)) {
1491                                 CDEBUG(D_VFSTRACE, "Range lock "RL_FMT"\n",
1492                                        RL_PARA(&range));
1493                                 rc = range_lock(&lli->lli_write_tree, &range);
1494                                 if (rc < 0)
1495                                         GOTO(out, rc);
1496
1497                                 range_locked = true;
1498                         }
1499                         break;
1500                 case IO_SPLICE:
1501                         vio->u.splice.vui_pipe = args->u.splice.via_pipe;
1502                         vio->u.splice.vui_flags = args->u.splice.via_flags;
1503                         break;
1504                 default:
1505                         CERROR("unknown IO subtype %u\n", vio->vui_io_subtype);
1506                         LBUG();
1507                 }
1508
1509                 ll_cl_add(file, env, io, LCC_RW);
1510                 rc = cl_io_loop(env, io);
1511                 ll_cl_remove(file, env);
1512
1513                 if (range_locked) {
1514                         CDEBUG(D_VFSTRACE, "Range unlock "RL_FMT"\n",
1515                                RL_PARA(&range));
1516                         range_unlock(&lli->lli_write_tree, &range);
1517                 }
1518         } else {
1519                 /* cl_io_rw_init() handled IO */
1520                 rc = io->ci_result;
1521         }
1522
1523         if (io->ci_nob > 0) {
1524                 result += io->ci_nob;
1525                 count  -= io->ci_nob;
1526                 *ppos = io->u.ci_wr.wr.crw_pos; /* for splice */
1527
1528                 /* prepare IO restart */
1529                 if (count > 0 && args->via_io_subtype == IO_NORMAL)
1530                         args->u.normal.via_iter = vio->vui_iter;
1531         }
1532 out:
1533         cl_io_fini(env, io);
1534
1535         CDEBUG(D_VFSTRACE,
1536                "%s: %d io complete with rc: %d, result: %zd, restart: %d\n",
1537                file->f_path.dentry->d_name.name,
1538                iot, rc, result, io->ci_need_restart);
1539
1540         if ((rc == 0 || rc == -ENODATA) && count > 0 && io->ci_need_restart) {
1541                 CDEBUG(D_VFSTRACE,
1542                        "%s: restart %s from %lld, count: %zu, ret: %zd, rc: %d\n",
1543                        file_dentry(file)->d_name.name,
1544                        iot == CIT_READ ? "read" : "write",
1545                        *ppos, count, result, rc);
1546                 /* preserve the tried count for FLR */
1547                 retried = io->ci_ndelay_tried;
1548                 restarted = true;
1549                 goto restart;
1550         }
1551
1552         if (iot == CIT_READ) {
1553                 if (result > 0)
1554                         ll_stats_ops_tally(ll_i2sbi(inode),
1555                                            LPROC_LL_READ_BYTES, result);
1556         } else if (iot == CIT_WRITE) {
1557                 if (result > 0) {
1558                         ll_stats_ops_tally(ll_i2sbi(inode),
1559                                            LPROC_LL_WRITE_BYTES, result);
1560                         fd->fd_write_failed = false;
1561                 } else if (result == 0 && rc == 0) {
1562                         rc = io->ci_result;
1563                         if (rc < 0)
1564                                 fd->fd_write_failed = true;
1565                         else
1566                                 fd->fd_write_failed = false;
1567                 } else if (rc != -ERESTARTSYS) {
1568                         fd->fd_write_failed = true;
1569                 }
1570         }
1571
1572         CDEBUG(D_VFSTRACE, "iot: %d, result: %zd\n", iot, result);
1573         if (result > 0)
1574                 ll_heat_add(inode, iot, result);
1575
1576         RETURN(result > 0 ? result : rc);
1577 }
1578
1579 /**
1580  * The purpose of fast read is to overcome per I/O overhead and improve IOPS
1581  * especially for small I/O.
1582  *
1583  * To serve a read request, CLIO has to create and initialize a cl_io and
1584  * then request DLM lock. This has turned out to have siginificant overhead
1585  * and affects the performance of small I/O dramatically.
1586  *
1587  * It's not necessary to create a cl_io for each I/O. Under the help of read
1588  * ahead, most of the pages being read are already in memory cache and we can
1589  * read those pages directly because if the pages exist, the corresponding DLM
1590  * lock must exist so that page content must be valid.
1591  *
1592  * In fast read implementation, the llite speculatively finds and reads pages
1593  * in memory cache. There are three scenarios for fast read:
1594  *   - If the page exists and is uptodate, kernel VM will provide the data and
1595  *     CLIO won't be intervened;
1596  *   - If the page was brought into memory by read ahead, it will be exported
1597  *     and read ahead parameters will be updated;
1598  *   - Otherwise the page is not in memory, we can't do fast read. Therefore,
1599  *     it will go back and invoke normal read, i.e., a cl_io will be created
1600  *     and DLM lock will be requested.
1601  *
1602  * POSIX compliance: posix standard states that read is intended to be atomic.
1603  * Lustre read implementation is in line with Linux kernel read implementation
1604  * and neither of them complies with POSIX standard in this matter. Fast read
1605  * doesn't make the situation worse on single node but it may interleave write
1606  * results from multiple nodes due to short read handling in ll_file_aio_read().
1607  *
1608  * \param env - lu_env
1609  * \param iocb - kiocb from kernel
1610  * \param iter - user space buffers where the data will be copied
1611  *
1612  * \retval - number of bytes have been read, or error code if error occurred.
1613  */
1614 static ssize_t
1615 ll_do_fast_read(struct kiocb *iocb, struct iov_iter *iter)
1616 {
1617         ssize_t result;
1618
1619         if (!ll_sbi_has_fast_read(ll_i2sbi(file_inode(iocb->ki_filp))))
1620                 return 0;
1621
1622         /* NB: we can't do direct IO for fast read because it will need a lock
1623          * to make IO engine happy. */
1624         if (iocb->ki_filp->f_flags & O_DIRECT)
1625                 return 0;
1626
1627         result = generic_file_read_iter(iocb, iter);
1628
1629         /* If the first page is not in cache, generic_file_aio_read() will be
1630          * returned with -ENODATA.
1631          * See corresponding code in ll_readpage(). */
1632         if (result == -ENODATA)
1633                 result = 0;
1634
1635         if (result > 0) {
1636                 ll_heat_add(file_inode(iocb->ki_filp), CIT_READ, result);
1637                 ll_stats_ops_tally(ll_i2sbi(file_inode(iocb->ki_filp)),
1638                                 LPROC_LL_READ_BYTES, result);
1639         }
1640
1641         return result;
1642 }
1643
1644 /*
1645  * Read from a file (through the page cache).
1646  */
1647 static ssize_t ll_file_read_iter(struct kiocb *iocb, struct iov_iter *to)
1648 {
1649         struct lu_env *env;
1650         struct vvp_io_args *args;
1651         ssize_t result;
1652         ssize_t rc2;
1653         __u16 refcheck;
1654         bool cached;
1655
1656         /**
1657          * Currently when PCC read failed, we do not fall back to the
1658          * normal read path, just return the error.
1659          * The resaon is that: for RW-PCC, the file data may be modified
1660          * in the PCC and inconsistent with the data on OSTs (or file
1661          * data has been removed from the Lustre file system), at this
1662          * time, fallback to the normal read path may read the wrong
1663          * data.
1664          * TODO: for RO-PCC (readonly PCC), fall back to normal read
1665          * path: read data from data copy on OSTs.
1666          */
1667         result = pcc_file_read_iter(iocb, to, &cached);
1668         if (cached)
1669                 return result;
1670
1671         ll_ras_enter(iocb->ki_filp);
1672
1673         result = ll_do_fast_read(iocb, to);
1674         if (result < 0 || iov_iter_count(to) == 0)
1675                 GOTO(out, result);
1676
1677         env = cl_env_get(&refcheck);
1678         if (IS_ERR(env))
1679                 return PTR_ERR(env);
1680
1681         args = ll_env_args(env, IO_NORMAL);
1682         args->u.normal.via_iter = to;
1683         args->u.normal.via_iocb = iocb;
1684
1685         rc2 = ll_file_io_generic(env, args, iocb->ki_filp, CIT_READ,
1686                                  &iocb->ki_pos, iov_iter_count(to));
1687         if (rc2 > 0)
1688                 result += rc2;
1689         else if (result == 0)
1690                 result = rc2;
1691
1692         cl_env_put(env, &refcheck);
1693 out:
1694         return result;
1695 }
1696
1697 /**
1698  * Similar trick to ll_do_fast_read, this improves write speed for tiny writes.
1699  * If a page is already in the page cache and dirty (and some other things -
1700  * See ll_tiny_write_begin for the instantiation of these rules), then we can
1701  * write to it without doing a full I/O, because Lustre already knows about it
1702  * and will write it out.  This saves a lot of processing time.
1703  *
1704  * All writes here are within one page, so exclusion is handled by the page
1705  * lock on the vm page.  We do not do tiny writes for writes which touch
1706  * multiple pages because it's very unlikely multiple sequential pages are
1707  * are already dirty.
1708  *
1709  * We limit these to < PAGE_SIZE because PAGE_SIZE writes are relatively common
1710  * and are unlikely to be to already dirty pages.
1711  *
1712  * Attribute updates are important here, we do them in ll_tiny_write_end.
1713  */
1714 static ssize_t ll_do_tiny_write(struct kiocb *iocb, struct iov_iter *iter)
1715 {
1716         ssize_t count = iov_iter_count(iter);
1717         struct  file *file = iocb->ki_filp;
1718         struct  inode *inode = file_inode(file);
1719         bool    lock_inode = !IS_NOSEC(inode);
1720         ssize_t result = 0;
1721
1722         ENTRY;
1723
1724         /* Restrict writes to single page and < PAGE_SIZE.  See comment at top
1725          * of function for why.
1726          */
1727         if (count >= PAGE_SIZE ||
1728             (iocb->ki_pos & (PAGE_SIZE-1)) + count > PAGE_SIZE)
1729                 RETURN(0);
1730
1731         if (unlikely(lock_inode))
1732                 inode_lock(inode);
1733         result = __generic_file_write_iter(iocb, iter);
1734
1735         if (unlikely(lock_inode))
1736                 inode_unlock(inode);
1737
1738         /* If the page is not already dirty, ll_tiny_write_begin returns
1739          * -ENODATA.  We continue on to normal write.
1740          */
1741         if (result == -ENODATA)
1742                 result = 0;
1743
1744         if (result > 0) {
1745                 ll_heat_add(inode, CIT_WRITE, result);
1746                 ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_WRITE_BYTES,
1747                                    result);
1748                 ll_file_set_flag(ll_i2info(inode), LLIF_DATA_MODIFIED);
1749         }
1750
1751         CDEBUG(D_VFSTRACE, "result: %zu, original count %zu\n", result, count);
1752
1753         RETURN(result);
1754 }
1755
1756 /*
1757  * Write to a file (through the page cache).
1758  */
1759 static ssize_t ll_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
1760 {
1761         struct vvp_io_args *args;
1762         struct lu_env *env;
1763         ssize_t rc_tiny = 0, rc_normal;
1764         __u16 refcheck;
1765         bool cached;
1766         int result;
1767
1768         ENTRY;
1769
1770         /**
1771          * When PCC write failed, we usually do not fall back to the normal
1772          * write path, just return the error. But there is a special case when
1773          * returned error code is -ENOSPC due to running out of space on PCC HSM
1774          * bakcend. At this time, it will fall back to normal I/O path and
1775          * retry the I/O. As the file is in HSM released state, it will restore
1776          * the file data to OSTs first and redo the write again. And the
1777          * restore process will revoke the layout lock and detach the file
1778          * from PCC cache automatically.
1779          */
1780         result = pcc_file_write_iter(iocb, from, &cached);
1781         if (cached && result != -ENOSPC && result != -EDQUOT)
1782                 return result;
1783
1784         /* NB: we can't do direct IO for tiny writes because they use the page
1785          * cache, we can't do sync writes because tiny writes can't flush
1786          * pages, and we can't do append writes because we can't guarantee the
1787          * required DLM locks are held to protect file size.
1788          */
1789         if (ll_sbi_has_tiny_write(ll_i2sbi(file_inode(iocb->ki_filp))) &&
1790             !(iocb->ki_filp->f_flags & (O_DIRECT | O_SYNC | O_APPEND)))
1791                 rc_tiny = ll_do_tiny_write(iocb, from);
1792
1793         /* In case of error, go on and try normal write - Only stop if tiny
1794          * write completed I/O.
1795          */
1796         if (iov_iter_count(from) == 0)
1797                 GOTO(out, rc_normal = rc_tiny);
1798
1799         env = cl_env_get(&refcheck);
1800         if (IS_ERR(env))
1801                 return PTR_ERR(env);
1802
1803         args = ll_env_args(env, IO_NORMAL);
1804         args->u.normal.via_iter = from;
1805         args->u.normal.via_iocb = iocb;
1806
1807         rc_normal = ll_file_io_generic(env, args, iocb->ki_filp, CIT_WRITE,
1808                                     &iocb->ki_pos, iov_iter_count(from));
1809
1810         /* On success, combine bytes written. */
1811         if (rc_tiny >= 0 && rc_normal > 0)
1812                 rc_normal += rc_tiny;
1813         /* On error, only return error from normal write if tiny write did not
1814          * write any bytes.  Otherwise return bytes written by tiny write.
1815          */
1816         else if (rc_tiny > 0)
1817                 rc_normal = rc_tiny;
1818
1819         cl_env_put(env, &refcheck);
1820 out:
1821         RETURN(rc_normal);
1822 }
1823
1824 #ifndef HAVE_FILE_OPERATIONS_READ_WRITE_ITER
1825 /*
1826  * XXX: exact copy from kernel code (__generic_file_aio_write_nolock)
1827  */
1828 static int ll_file_get_iov_count(const struct iovec *iov,
1829                                  unsigned long *nr_segs, size_t *count)
1830 {
1831         size_t cnt = 0;
1832         unsigned long seg;
1833
1834         for (seg = 0; seg < *nr_segs; seg++) {
1835                 const struct iovec *iv = &iov[seg];
1836
1837                 /*
1838                  * If any segment has a negative length, or the cumulative
1839                  * length ever wraps negative then return -EINVAL.
1840                  */
1841                 cnt += iv->iov_len;
1842                 if (unlikely((ssize_t)(cnt|iv->iov_len) < 0))
1843                         return -EINVAL;
1844                 if (access_ok(VERIFY_READ, iv->iov_base, iv->iov_len))
1845                         continue;
1846                 if (seg == 0)
1847                         return -EFAULT;
1848                 *nr_segs = seg;
1849                 cnt -= iv->iov_len;     /* This segment is no good */
1850                 break;
1851         }
1852         *count = cnt;
1853         return 0;
1854 }
1855
1856 static ssize_t ll_file_aio_read(struct kiocb *iocb, const struct iovec *iov,
1857                                 unsigned long nr_segs, loff_t pos)
1858 {
1859         struct iov_iter to;
1860         size_t iov_count;
1861         ssize_t result;
1862         ENTRY;
1863
1864         result = ll_file_get_iov_count(iov, &nr_segs, &iov_count);
1865         if (result)
1866                 RETURN(result);
1867
1868 # ifdef HAVE_IOV_ITER_INIT_DIRECTION
1869         iov_iter_init(&to, READ, iov, nr_segs, iov_count);
1870 # else /* !HAVE_IOV_ITER_INIT_DIRECTION */
1871         iov_iter_init(&to, iov, nr_segs, iov_count, 0);
1872 # endif /* HAVE_IOV_ITER_INIT_DIRECTION */
1873
1874         result = ll_file_read_iter(iocb, &to);
1875
1876         RETURN(result);
1877 }
1878
1879 static ssize_t ll_file_read(struct file *file, char __user *buf, size_t count,
1880                             loff_t *ppos)
1881 {
1882         struct iovec   iov = { .iov_base = buf, .iov_len = count };
1883         struct kiocb   kiocb;
1884         ssize_t        result;
1885         ENTRY;
1886
1887         init_sync_kiocb(&kiocb, file);
1888         kiocb.ki_pos = *ppos;
1889 #ifdef HAVE_KIOCB_KI_LEFT
1890         kiocb.ki_left = count;
1891 #elif defined(HAVE_KI_NBYTES)
1892         kiocb.i_nbytes = count;
1893 #endif
1894
1895         result = ll_file_aio_read(&kiocb, &iov, 1, kiocb.ki_pos);
1896         *ppos = kiocb.ki_pos;
1897
1898         RETURN(result);
1899 }
1900
1901 /*
1902  * Write to a file (through the page cache).
1903  * AIO stuff
1904  */
1905 static ssize_t ll_file_aio_write(struct kiocb *iocb, const struct iovec *iov,
1906                                  unsigned long nr_segs, loff_t pos)
1907 {
1908         struct iov_iter from;
1909         size_t iov_count;
1910         ssize_t result;
1911         ENTRY;
1912
1913         result = ll_file_get_iov_count(iov, &nr_segs, &iov_count);
1914         if (result)
1915                 RETURN(result);
1916
1917 # ifdef HAVE_IOV_ITER_INIT_DIRECTION
1918         iov_iter_init(&from, WRITE, iov, nr_segs, iov_count);
1919 # else /* !HAVE_IOV_ITER_INIT_DIRECTION */
1920         iov_iter_init(&from, iov, nr_segs, iov_count, 0);
1921 # endif /* HAVE_IOV_ITER_INIT_DIRECTION */
1922
1923         result = ll_file_write_iter(iocb, &from);
1924
1925         RETURN(result);
1926 }
1927
1928 static ssize_t ll_file_write(struct file *file, const char __user *buf,
1929                              size_t count, loff_t *ppos)
1930 {
1931         struct iovec   iov = { .iov_base = (void __user *)buf,
1932                                .iov_len = count };
1933         struct kiocb   kiocb;
1934         ssize_t        result;
1935
1936         ENTRY;
1937
1938         init_sync_kiocb(&kiocb, file);
1939         kiocb.ki_pos = *ppos;
1940 #ifdef HAVE_KIOCB_KI_LEFT
1941         kiocb.ki_left = count;
1942 #elif defined(HAVE_KI_NBYTES)
1943         kiocb.ki_nbytes = count;
1944 #endif
1945
1946         result = ll_file_aio_write(&kiocb, &iov, 1, kiocb.ki_pos);
1947         *ppos = kiocb.ki_pos;
1948
1949         RETURN(result);
1950 }
1951 #endif /* !HAVE_FILE_OPERATIONS_READ_WRITE_ITER */
1952
1953 /*
1954  * Send file content (through pagecache) somewhere with helper
1955  */
1956 static ssize_t ll_file_splice_read(struct file *in_file, loff_t *ppos,
1957                                    struct pipe_inode_info *pipe, size_t count,
1958                                    unsigned int flags)
1959 {
1960         struct lu_env *env;
1961         struct vvp_io_args *args;
1962         ssize_t result;
1963         __u16 refcheck;
1964         bool cached;
1965
1966         ENTRY;
1967
1968         result = pcc_file_splice_read(in_file, ppos, pipe,
1969                                       count, flags, &cached);
1970         if (cached)
1971                 RETURN(result);
1972
1973         ll_ras_enter(in_file);
1974
1975         env = cl_env_get(&refcheck);
1976         if (IS_ERR(env))
1977                 RETURN(PTR_ERR(env));
1978
1979         args = ll_env_args(env, IO_SPLICE);
1980         args->u.splice.via_pipe = pipe;
1981         args->u.splice.via_flags = flags;
1982
1983         result = ll_file_io_generic(env, args, in_file, CIT_READ, ppos, count);
1984         cl_env_put(env, &refcheck);
1985         RETURN(result);
1986 }
1987
1988 int ll_lov_setstripe_ea_info(struct inode *inode, struct dentry *dentry,
1989                              __u64 flags, struct lov_user_md *lum, int lum_size)
1990 {
1991         struct lookup_intent oit = {
1992                 .it_op = IT_OPEN,
1993                 .it_flags = flags | MDS_OPEN_BY_FID,
1994         };
1995         int rc;
1996         ENTRY;
1997
1998         ll_inode_size_lock(inode);
1999         rc = ll_intent_file_open(dentry, lum, lum_size, &oit);
2000         if (rc < 0)
2001                 GOTO(out_unlock, rc);
2002
2003         ll_release_openhandle(dentry, &oit);
2004
2005 out_unlock:
2006         ll_inode_size_unlock(inode);
2007         ll_intent_release(&oit);
2008
2009         RETURN(rc);
2010 }
2011
2012 int ll_lov_getstripe_ea_info(struct inode *inode, const char *filename,
2013                              struct lov_mds_md **lmmp, int *lmm_size,
2014                              struct ptlrpc_request **request)
2015 {
2016         struct ll_sb_info *sbi = ll_i2sbi(inode);
2017         struct mdt_body  *body;
2018         struct lov_mds_md *lmm = NULL;
2019         struct ptlrpc_request *req = NULL;
2020         struct md_op_data *op_data;
2021         int rc, lmmsize;
2022
2023         rc = ll_get_default_mdsize(sbi, &lmmsize);
2024         if (rc)
2025                 RETURN(rc);
2026
2027         op_data = ll_prep_md_op_data(NULL, inode, NULL, filename,
2028                                      strlen(filename), lmmsize,
2029                                      LUSTRE_OPC_ANY, NULL);
2030         if (IS_ERR(op_data))
2031                 RETURN(PTR_ERR(op_data));
2032
2033         op_data->op_valid = OBD_MD_FLEASIZE | OBD_MD_FLDIREA;
2034         rc = md_getattr_name(sbi->ll_md_exp, op_data, &req);
2035         ll_finish_md_op_data(op_data);
2036         if (rc < 0) {
2037                 CDEBUG(D_INFO, "md_getattr_name failed "
2038                        "on %s: rc %d\n", filename, rc);
2039                 GOTO(out, rc);
2040         }
2041
2042         body = req_capsule_server_get(&req->rq_pill, &RMF_MDT_BODY);
2043         LASSERT(body != NULL); /* checked by mdc_getattr_name */
2044
2045         lmmsize = body->mbo_eadatasize;
2046
2047         if (!(body->mbo_valid & (OBD_MD_FLEASIZE | OBD_MD_FLDIREA)) ||
2048                         lmmsize == 0) {
2049                 GOTO(out, rc = -ENODATA);
2050         }
2051
2052         lmm = req_capsule_server_sized_get(&req->rq_pill, &RMF_MDT_MD, lmmsize);
2053         LASSERT(lmm != NULL);
2054
2055         if (lmm->lmm_magic != cpu_to_le32(LOV_MAGIC_V1) &&
2056             lmm->lmm_magic != cpu_to_le32(LOV_MAGIC_V3) &&
2057             lmm->lmm_magic != cpu_to_le32(LOV_MAGIC_COMP_V1) &&
2058             lmm->lmm_magic != cpu_to_le32(LOV_MAGIC_FOREIGN))
2059                 GOTO(out, rc = -EPROTO);
2060
2061         /*
2062          * This is coming from the MDS, so is probably in
2063          * little endian.  We convert it to host endian before
2064          * passing it to userspace.
2065          */
2066         if (LOV_MAGIC != cpu_to_le32(LOV_MAGIC)) {
2067                 int stripe_count;
2068
2069                 if (lmm->lmm_magic == cpu_to_le32(LOV_MAGIC_V1) ||
2070                     lmm->lmm_magic == cpu_to_le32(LOV_MAGIC_V3)) {
2071                         stripe_count = le16_to_cpu(lmm->lmm_stripe_count);
2072                         if (le32_to_cpu(lmm->lmm_pattern) &
2073                             LOV_PATTERN_F_RELEASED)
2074                                 stripe_count = 0;
2075                 }
2076
2077                 /* if function called for directory - we should
2078                  * avoid swab not existent lsm objects */
2079                 if (lmm->lmm_magic == cpu_to_le32(LOV_MAGIC_V1)) {
2080                         lustre_swab_lov_user_md_v1(
2081                                         (struct lov_user_md_v1 *)lmm);
2082                         if (S_ISREG(body->mbo_mode))
2083                                 lustre_swab_lov_user_md_objects(
2084                                     ((struct lov_user_md_v1 *)lmm)->lmm_objects,
2085                                     stripe_count);
2086                 } else if (lmm->lmm_magic == cpu_to_le32(LOV_MAGIC_V3)) {
2087                         lustre_swab_lov_user_md_v3(
2088                                         (struct lov_user_md_v3 *)lmm);
2089                         if (S_ISREG(body->mbo_mode))
2090                                 lustre_swab_lov_user_md_objects(
2091                                     ((struct lov_user_md_v3 *)lmm)->lmm_objects,
2092                                     stripe_count);
2093                 } else if (lmm->lmm_magic ==
2094                            cpu_to_le32(LOV_MAGIC_COMP_V1)) {
2095                         lustre_swab_lov_comp_md_v1(
2096                                         (struct lov_comp_md_v1 *)lmm);
2097                 } else if (lmm->lmm_magic ==
2098                            cpu_to_le32(LOV_MAGIC_FOREIGN)) {
2099                         struct lov_foreign_md *lfm;
2100
2101                         lfm = (struct lov_foreign_md *)lmm;
2102                         __swab32s(&lfm->lfm_magic);
2103                         __swab32s(&lfm->lfm_length);
2104                         __swab32s(&lfm->lfm_type);
2105                         __swab32s(&lfm->lfm_flags);
2106                 }
2107         }
2108
2109 out:
2110         *lmmp = lmm;
2111         *lmm_size = lmmsize;
2112         *request = req;
2113         return rc;
2114 }
2115
2116 static int ll_lov_setea(struct inode *inode, struct file *file,
2117                         void __user *arg)
2118 {
2119         __u64                    flags = MDS_OPEN_HAS_OBJS | FMODE_WRITE;
2120         struct lov_user_md      *lump;
2121         int                      lum_size = sizeof(struct lov_user_md) +
2122                                             sizeof(struct lov_user_ost_data);
2123         int                      rc;
2124         ENTRY;
2125
2126         if (!cfs_capable(CFS_CAP_SYS_ADMIN))
2127                 RETURN(-EPERM);
2128
2129         OBD_ALLOC_LARGE(lump, lum_size);
2130         if (lump == NULL)
2131                 RETURN(-ENOMEM);
2132
2133         if (copy_from_user(lump, arg, lum_size))
2134                 GOTO(out_lump, rc = -EFAULT);
2135
2136         rc = ll_lov_setstripe_ea_info(inode, file_dentry(file), flags, lump,
2137                                       lum_size);
2138         cl_lov_delay_create_clear(&file->f_flags);
2139
2140 out_lump:
2141         OBD_FREE_LARGE(lump, lum_size);
2142         RETURN(rc);
2143 }
2144
2145 static int ll_file_getstripe(struct inode *inode, void __user *lum, size_t size)
2146 {
2147         struct lu_env   *env;
2148         __u16           refcheck;
2149         int             rc;
2150         ENTRY;
2151
2152         env = cl_env_get(&refcheck);
2153         if (IS_ERR(env))
2154                 RETURN(PTR_ERR(env));
2155
2156         rc = cl_object_getstripe(env, ll_i2info(inode)->lli_clob, lum, size);
2157         cl_env_put(env, &refcheck);
2158         RETURN(rc);
2159 }
2160
2161 static int ll_lov_setstripe(struct inode *inode, struct file *file,
2162                             void __user *arg)
2163 {
2164         struct lov_user_md __user *lum = (struct lov_user_md __user *)arg;
2165         struct lov_user_md        *klum;
2166         int                        lum_size, rc;
2167         __u64                      flags = FMODE_WRITE;
2168         ENTRY;
2169
2170         rc = ll_copy_user_md(lum, &klum);
2171         if (rc < 0)
2172                 RETURN(rc);
2173
2174         lum_size = rc;
2175         rc = ll_lov_setstripe_ea_info(inode, file_dentry(file), flags, klum,
2176                                       lum_size);
2177         if (!rc) {
2178                 __u32 gen;
2179
2180                 rc = put_user(0, &lum->lmm_stripe_count);
2181                 if (rc)
2182                         GOTO(out, rc);
2183
2184                 rc = ll_layout_refresh(inode, &gen);
2185                 if (rc)
2186                         GOTO(out, rc);
2187
2188                 rc = ll_file_getstripe(inode, arg, lum_size);
2189         }
2190         cl_lov_delay_create_clear(&file->f_flags);
2191
2192 out:
2193         OBD_FREE(klum, lum_size);
2194         RETURN(rc);
2195 }
2196
2197 static int
2198 ll_get_grouplock(struct inode *inode, struct file *file, unsigned long arg)
2199 {
2200         struct ll_inode_info *lli = ll_i2info(inode);
2201         struct cl_object *obj = lli->lli_clob;
2202         struct ll_file_data *fd = LUSTRE_FPRIVATE(file);
2203         struct ll_grouplock grouplock;
2204         int rc;
2205         ENTRY;
2206
2207         if (arg == 0) {
2208                 CWARN("group id for group lock must not be 0\n");
2209                 RETURN(-EINVAL);
2210         }
2211
2212         if (ll_file_nolock(file))
2213                 RETURN(-EOPNOTSUPP);
2214
2215         spin_lock(&lli->lli_lock);
2216         if (fd->fd_flags & LL_FILE_GROUP_LOCKED) {
2217                 CWARN("group lock already existed with gid %lu\n",
2218                       fd->fd_grouplock.lg_gid);
2219                 spin_unlock(&lli->lli_lock);
2220                 RETURN(-EINVAL);
2221         }
2222         LASSERT(fd->fd_grouplock.lg_lock == NULL);
2223         spin_unlock(&lli->lli_lock);
2224
2225         /**
2226          * XXX: group lock needs to protect all OST objects while PFL
2227          * can add new OST objects during the IO, so we'd instantiate
2228          * all OST objects before getting its group lock.
2229          */
2230         if (obj) {
2231                 struct lu_env *env;
2232                 __u16 refcheck;
2233                 struct cl_layout cl = {
2234                         .cl_is_composite = false,
2235                 };
2236                 struct lu_extent ext = {
2237                         .e_start = 0,
2238                         .e_end = OBD_OBJECT_EOF,
2239                 };
2240
2241                 env = cl_env_get(&refcheck);
2242                 if (IS_ERR(env))
2243                         RETURN(PTR_ERR(env));
2244
2245                 rc = cl_object_layout_get(env, obj, &cl);
2246                 if (!rc && cl.cl_is_composite)
2247                         rc = ll_layout_write_intent(inode, LAYOUT_INTENT_WRITE,
2248                                                     &ext);
2249
2250                 cl_env_put(env, &refcheck);
2251                 if (rc)
2252                         RETURN(rc);
2253         }
2254
2255         rc = cl_get_grouplock(ll_i2info(inode)->lli_clob,
2256                               arg, (file->f_flags & O_NONBLOCK), &grouplock);
2257         if (rc)
2258                 RETURN(rc);
2259
2260         spin_lock(&lli->lli_lock);
2261         if (fd->fd_flags & LL_FILE_GROUP_LOCKED) {
2262                 spin_unlock(&lli->lli_lock);
2263                 CERROR("another thread just won the race\n");
2264                 cl_put_grouplock(&grouplock);
2265                 RETURN(-EINVAL);
2266         }
2267
2268         fd->fd_flags |= LL_FILE_GROUP_LOCKED;
2269         fd->fd_grouplock = grouplock;
2270         spin_unlock(&lli->lli_lock);
2271
2272         CDEBUG(D_INFO, "group lock %lu obtained\n", arg);
2273         RETURN(0);
2274 }
2275
2276 static int ll_put_grouplock(struct inode *inode, struct file *file,
2277                             unsigned long arg)
2278 {
2279         struct ll_inode_info   *lli = ll_i2info(inode);
2280         struct ll_file_data    *fd = LUSTRE_FPRIVATE(file);
2281         struct ll_grouplock     grouplock;
2282         ENTRY;
2283
2284         spin_lock(&lli->lli_lock);
2285         if (!(fd->fd_flags & LL_FILE_GROUP_LOCKED)) {
2286                 spin_unlock(&lli->lli_lock);
2287                 CWARN("no group lock held\n");
2288                 RETURN(-EINVAL);
2289         }
2290
2291         LASSERT(fd->fd_grouplock.lg_lock != NULL);
2292
2293         if (fd->fd_grouplock.lg_gid != arg) {
2294                 CWARN("group lock %lu doesn't match current id %lu\n",
2295                       arg, fd->fd_grouplock.lg_gid);
2296                 spin_unlock(&lli->lli_lock);
2297                 RETURN(-EINVAL);
2298         }
2299
2300         grouplock = fd->fd_grouplock;
2301         memset(&fd->fd_grouplock, 0, sizeof(fd->fd_grouplock));
2302         fd->fd_flags &= ~LL_FILE_GROUP_LOCKED;
2303         spin_unlock(&lli->lli_lock);
2304
2305         cl_put_grouplock(&grouplock);
2306         CDEBUG(D_INFO, "group lock %lu released\n", arg);
2307         RETURN(0);
2308 }
2309
2310 /**
2311  * Close inode open handle
2312  *
2313  * \param dentry [in]     dentry which contains the inode
2314  * \param it     [in,out] intent which contains open info and result
2315  *
2316  * \retval 0     success
2317  * \retval <0    failure
2318  */
2319 int ll_release_openhandle(struct dentry *dentry, struct lookup_intent *it)
2320 {
2321         struct inode *inode = dentry->d_inode;
2322         struct obd_client_handle *och;
2323         int rc;
2324         ENTRY;
2325
2326         LASSERT(inode);
2327
2328         /* Root ? Do nothing. */
2329         if (dentry->d_inode->i_sb->s_root == dentry)
2330                 RETURN(0);
2331
2332         /* No open handle to close? Move away */
2333         if (!it_disposition(it, DISP_OPEN_OPEN))
2334                 RETURN(0);
2335
2336         LASSERT(it_open_error(DISP_OPEN_OPEN, it) == 0);
2337
2338         OBD_ALLOC(och, sizeof(*och));
2339         if (!och)
2340                 GOTO(out, rc = -ENOMEM);
2341
2342         ll_och_fill(ll_i2sbi(inode)->ll_md_exp, it, och);
2343
2344         rc = ll_close_inode_openhandle(inode, och, 0, NULL);
2345 out:
2346         /* this one is in place of ll_file_open */
2347         if (it_disposition(it, DISP_ENQ_OPEN_REF)) {
2348                 ptlrpc_req_finished(it->it_request);
2349                 it_clear_disposition(it, DISP_ENQ_OPEN_REF);
2350         }
2351         RETURN(rc);
2352 }
2353
2354 /**
2355  * Get size for inode for which FIEMAP mapping is requested.
2356  * Make the FIEMAP get_info call and returns the result.
2357  * \param fiemap        kernel buffer to hold extens
2358  * \param num_bytes     kernel buffer size
2359  */
2360 static int ll_do_fiemap(struct inode *inode, struct fiemap *fiemap,
2361                         size_t num_bytes)
2362 {
2363         struct lu_env                   *env;
2364         __u16                           refcheck;
2365         int                             rc = 0;
2366         struct ll_fiemap_info_key       fmkey = { .lfik_name = KEY_FIEMAP, };
2367         ENTRY;
2368
2369         /* Checks for fiemap flags */
2370         if (fiemap->fm_flags & ~LUSTRE_FIEMAP_FLAGS_COMPAT) {
2371                 fiemap->fm_flags &= ~LUSTRE_FIEMAP_FLAGS_COMPAT;
2372                 return -EBADR;
2373         }
2374
2375         /* Check for FIEMAP_FLAG_SYNC */
2376         if (fiemap->fm_flags & FIEMAP_FLAG_SYNC) {
2377                 rc = filemap_fdatawrite(inode->i_mapping);
2378                 if (rc)
2379                         return rc;
2380         }
2381
2382         env = cl_env_get(&refcheck);
2383         if (IS_ERR(env))
2384                 RETURN(PTR_ERR(env));
2385
2386         if (i_size_read(inode) == 0) {
2387                 rc = ll_glimpse_size(inode);
2388                 if (rc)
2389                         GOTO(out, rc);
2390         }
2391
2392         fmkey.lfik_oa.o_valid = OBD_MD_FLID | OBD_MD_FLGROUP;
2393         obdo_from_inode(&fmkey.lfik_oa, inode, OBD_MD_FLSIZE);
2394         obdo_set_parent_fid(&fmkey.lfik_oa, &ll_i2info(inode)->lli_fid);
2395
2396         /* If filesize is 0, then there would be no objects for mapping */
2397         if (fmkey.lfik_oa.o_size == 0) {
2398                 fiemap->fm_mapped_extents = 0;
2399                 GOTO(out, rc = 0);
2400         }
2401
2402         fmkey.lfik_fiemap = *fiemap;
2403
2404         rc = cl_object_fiemap(env, ll_i2info(inode)->lli_clob,
2405                               &fmkey, fiemap, &num_bytes);
2406 out:
2407         cl_env_put(env, &refcheck);
2408         RETURN(rc);
2409 }
2410
2411 int ll_fid2path(struct inode *inode, void __user *arg)
2412 {
2413         struct obd_export       *exp = ll_i2mdexp(inode);
2414         const struct getinfo_fid2path __user *gfin = arg;
2415         __u32                    pathlen;
2416         struct getinfo_fid2path *gfout;
2417         size_t                   outsize;
2418         int                      rc;
2419
2420         ENTRY;
2421
2422         if (!cfs_capable(CFS_CAP_DAC_READ_SEARCH) &&
2423             !(ll_i2sbi(inode)->ll_flags & LL_SBI_USER_FID2PATH))
2424                 RETURN(-EPERM);
2425
2426         /* Only need to get the buflen */
2427         if (get_user(pathlen, &gfin->gf_pathlen))
2428                 RETURN(-EFAULT);
2429
2430         if (pathlen > PATH_MAX)
2431                 RETURN(-EINVAL);
2432
2433         outsize = sizeof(*gfout) + pathlen;
2434         OBD_ALLOC(gfout, outsize);
2435         if (gfout == NULL)
2436                 RETURN(-ENOMEM);
2437
2438         if (copy_from_user(gfout, arg, sizeof(*gfout)))
2439                 GOTO(gf_free, rc = -EFAULT);
2440         /* append root FID after gfout to let MDT know the root FID so that it
2441          * can lookup the correct path, this is mainly for fileset.
2442          * old server without fileset mount support will ignore this. */
2443         *gfout->gf_u.gf_root_fid = *ll_inode2fid(inode);
2444
2445         /* Call mdc_iocontrol */
2446         rc = obd_iocontrol(OBD_IOC_FID2PATH, exp, outsize, gfout, NULL);
2447         if (rc != 0)
2448                 GOTO(gf_free, rc);
2449
2450         if (copy_to_user(arg, gfout, outsize))
2451                 rc = -EFAULT;
2452
2453 gf_free:
2454         OBD_FREE(gfout, outsize);
2455         RETURN(rc);
2456 }
2457
2458 static int
2459 ll_ioc_data_version(struct inode *inode, struct ioc_data_version *ioc)
2460 {
2461         struct cl_object *obj = ll_i2info(inode)->lli_clob;
2462         struct lu_env *env;
2463         struct cl_io *io;
2464         __u16  refcheck;
2465         int result;
2466
2467         ENTRY;
2468
2469         ioc->idv_version = 0;
2470         ioc->idv_layout_version = UINT_MAX;
2471
2472         /* If no file object initialized, we consider its version is 0. */
2473         if (obj == NULL)
2474                 RETURN(0);
2475
2476         env = cl_env_get(&refcheck);
2477         if (IS_ERR(env))
2478                 RETURN(PTR_ERR(env));
2479
2480         io = vvp_env_thread_io(env);
2481         io->ci_obj = obj;
2482         io->u.ci_data_version.dv_data_version = 0;
2483         io->u.ci_data_version.dv_layout_version = UINT_MAX;
2484         io->u.ci_data_version.dv_flags = ioc->idv_flags;
2485
2486 restart:
2487         if (cl_io_init(env, io, CIT_DATA_VERSION, io->ci_obj) == 0)
2488                 result = cl_io_loop(env, io);
2489         else
2490                 result = io->ci_result;
2491
2492         ioc->idv_version = io->u.ci_data_version.dv_data_version;
2493         ioc->idv_layout_version = io->u.ci_data_version.dv_layout_version;
2494
2495         cl_io_fini(env, io);
2496
2497         if (unlikely(io->ci_need_restart))
2498                 goto restart;
2499
2500         cl_env_put(env, &refcheck);
2501
2502         RETURN(result);
2503 }
2504
2505 /*
2506  * Read the data_version for inode.
2507  *
2508  * This value is computed using stripe object version on OST.
2509  * Version is computed using server side locking.
2510  *
2511  * @param flags if do sync on the OST side;
2512  *              0: no sync
2513  *              LL_DV_RD_FLUSH: flush dirty pages, LCK_PR on OSTs
2514  *              LL_DV_WR_FLUSH: drop all caching pages, LCK_PW on OSTs
2515  */
2516 int ll_data_version(struct inode *inode, __u64 *data_version, int flags)
2517 {
2518         struct ioc_data_version ioc = { .idv_flags = flags };
2519         int rc;
2520
2521         rc = ll_ioc_data_version(inode, &ioc);
2522         if (!rc)
2523                 *data_version = ioc.idv_version;
2524
2525         return rc;
2526 }
2527
2528 /*
2529  * Trigger a HSM release request for the provided inode.
2530  */
2531 int ll_hsm_release(struct inode *inode)
2532 {
2533         struct lu_env *env;
2534         struct obd_client_handle *och = NULL;
2535         __u64 data_version = 0;
2536         int rc;
2537         __u16 refcheck;
2538         ENTRY;
2539
2540         CDEBUG(D_INODE, "%s: Releasing file "DFID".\n",
2541                ll_i2sbi(inode)->ll_fsname,
2542                PFID(&ll_i2info(inode)->lli_fid));
2543
2544         och = ll_lease_open(inode, NULL, FMODE_WRITE, MDS_OPEN_RELEASE);
2545         if (IS_ERR(och))
2546                 GOTO(out, rc = PTR_ERR(och));
2547
2548         /* Grab latest data_version and [am]time values */
2549         rc = ll_data_version(inode, &data_version, LL_DV_WR_FLUSH);
2550         if (rc != 0)
2551                 GOTO(out, rc);
2552
2553         env = cl_env_get(&refcheck);
2554         if (IS_ERR(env))
2555                 GOTO(out, rc = PTR_ERR(env));
2556
2557         rc = ll_merge_attr(env, inode);
2558         cl_env_put(env, &refcheck);
2559
2560         /* If error happen, we have the wrong size for a file.
2561          * Don't release it.
2562          */
2563         if (rc != 0)
2564                 GOTO(out, rc);
2565
2566         /* Release the file.
2567          * NB: lease lock handle is released in mdc_hsm_release_pack() because
2568          * we still need it to pack l_remote_handle to MDT. */
2569         rc = ll_close_inode_openhandle(inode, och, MDS_HSM_RELEASE,
2570                                        &data_version);
2571         och = NULL;
2572
2573         EXIT;
2574 out:
2575         if (och != NULL && !IS_ERR(och)) /* close the file */
2576                 ll_lease_close(och, inode, NULL);
2577
2578         return rc;
2579 }
2580
2581 struct ll_swap_stack {
2582         __u64                    dv1;
2583         __u64                    dv2;
2584         struct inode            *inode1;
2585         struct inode            *inode2;
2586         bool                     check_dv1;
2587         bool                     check_dv2;
2588 };
2589
2590 static int ll_swap_layouts(struct file *file1, struct file *file2,
2591                            struct lustre_swap_layouts *lsl)
2592 {
2593         struct mdc_swap_layouts  msl;
2594         struct md_op_data       *op_data;
2595         __u32                    gid;
2596         __u64                    dv;
2597         struct ll_swap_stack    *llss = NULL;
2598         int                      rc;
2599
2600         OBD_ALLOC_PTR(llss);
2601         if (llss == NULL)
2602                 RETURN(-ENOMEM);
2603
2604         llss->inode1 = file_inode(file1);
2605         llss->inode2 = file_inode(file2);
2606
2607         rc = ll_check_swap_layouts_validity(llss->inode1, llss->inode2);
2608         if (rc < 0)
2609                 GOTO(free, rc);
2610
2611         /* we use 2 bool because it is easier to swap than 2 bits */
2612         if (lsl->sl_flags & SWAP_LAYOUTS_CHECK_DV1)
2613                 llss->check_dv1 = true;
2614
2615         if (lsl->sl_flags & SWAP_LAYOUTS_CHECK_DV2)
2616                 llss->check_dv2 = true;
2617
2618         /* we cannot use lsl->sl_dvX directly because we may swap them */
2619         llss->dv1 = lsl->sl_dv1;
2620         llss->dv2 = lsl->sl_dv2;
2621
2622         rc = lu_fid_cmp(ll_inode2fid(llss->inode1), ll_inode2fid(llss->inode2));
2623         if (rc == 0) /* same file, done! */
2624                 GOTO(free, rc);
2625
2626         if (rc < 0) { /* sequentialize it */
2627                 swap(llss->inode1, llss->inode2);
2628                 swap(file1, file2);
2629                 swap(llss->dv1, llss->dv2);
2630                 swap(llss->check_dv1, llss->check_dv2);
2631         }
2632
2633         gid = lsl->sl_gid;
2634         if (gid != 0) { /* application asks to flush dirty cache */
2635                 rc = ll_get_grouplock(llss->inode1, file1, gid);
2636                 if (rc < 0)
2637                         GOTO(free, rc);
2638
2639                 rc = ll_get_grouplock(llss->inode2, file2, gid);
2640                 if (rc < 0) {
2641                         ll_put_grouplock(llss->inode1, file1, gid);
2642                         GOTO(free, rc);
2643                 }
2644         }
2645
2646         /* ultimate check, before swaping the layouts we check if
2647          * dataversion has changed (if requested) */
2648         if (llss->check_dv1) {
2649                 rc = ll_data_version(llss->inode1, &dv, 0);
2650                 if (rc)
2651                         GOTO(putgl, rc);
2652                 if (dv != llss->dv1)
2653                         GOTO(putgl, rc = -EAGAIN);
2654         }
2655
2656         if (llss->check_dv2) {
2657                 rc = ll_data_version(llss->inode2, &dv, 0);
2658                 if (rc)
2659                         GOTO(putgl, rc);
2660                 if (dv != llss->dv2)
2661                         GOTO(putgl, rc = -EAGAIN);
2662         }
2663
2664         /* struct md_op_data is used to send the swap args to the mdt
2665          * only flags is missing, so we use struct mdc_swap_layouts
2666          * through the md_op_data->op_data */
2667         /* flags from user space have to be converted before they are send to
2668          * server, no flag is sent today, they are only used on the client */
2669         msl.msl_flags = 0;
2670         rc = -ENOMEM;
2671         op_data = ll_prep_md_op_data(NULL, llss->inode1, llss->inode2, NULL, 0,
2672                                      0, LUSTRE_OPC_ANY, &msl);
2673         if (IS_ERR(op_data))
2674                 GOTO(free, rc = PTR_ERR(op_data));
2675
2676         rc = obd_iocontrol(LL_IOC_LOV_SWAP_LAYOUTS, ll_i2mdexp(llss->inode1),
2677                            sizeof(*op_data), op_data, NULL);
2678         ll_finish_md_op_data(op_data);
2679
2680         if (rc < 0)
2681                 GOTO(putgl, rc);
2682
2683 putgl:
2684         if (gid != 0) {
2685                 ll_put_grouplock(llss->inode2, file2, gid);
2686                 ll_put_grouplock(llss->inode1, file1, gid);
2687         }
2688
2689 free:
2690         if (llss != NULL)
2691                 OBD_FREE_PTR(llss);
2692
2693         RETURN(rc);
2694 }
2695
2696 int ll_hsm_state_set(struct inode *inode, struct hsm_state_set *hss)
2697 {
2698         struct obd_export *exp = ll_i2mdexp(inode);
2699         struct md_op_data *op_data;
2700         int rc;
2701         ENTRY;
2702
2703         /* Detect out-of range masks */
2704         if ((hss->hss_setmask | hss->hss_clearmask) & ~HSM_FLAGS_MASK)
2705                 RETURN(-EINVAL);
2706
2707         /* Non-root users are forbidden to set or clear flags which are
2708          * NOT defined in HSM_USER_MASK. */
2709         if (((hss->hss_setmask | hss->hss_clearmask) & ~HSM_USER_MASK) &&
2710             !cfs_capable(CFS_CAP_SYS_ADMIN))
2711                 RETURN(-EPERM);
2712
2713         if (!exp_connect_archive_id_array(exp)) {
2714                 /* Detect out-of range archive id */
2715                 if ((hss->hss_valid & HSS_ARCHIVE_ID) &&
2716                     (hss->hss_archive_id > LL_HSM_ORIGIN_MAX_ARCHIVE))
2717                         RETURN(-EINVAL);
2718         }
2719
2720         op_data = ll_prep_md_op_data(NULL, inode, NULL, NULL, 0, 0,
2721                                      LUSTRE_OPC_ANY, hss);
2722         if (IS_ERR(op_data))
2723                 RETURN(PTR_ERR(op_data));
2724
2725         rc = obd_iocontrol(LL_IOC_HSM_STATE_SET, exp, sizeof(*op_data),
2726                            op_data, NULL);
2727
2728         ll_finish_md_op_data(op_data);
2729
2730         RETURN(rc);
2731 }
2732
2733 static int ll_hsm_import(struct inode *inode, struct file *file,
2734                          struct hsm_user_import *hui)
2735 {
2736         struct hsm_state_set    *hss = NULL;
2737         struct iattr            *attr = NULL;
2738         int                      rc;
2739         ENTRY;
2740
2741         if (!S_ISREG(inode->i_mode))
2742                 RETURN(-EINVAL);
2743
2744         /* set HSM flags */
2745         OBD_ALLOC_PTR(hss);
2746         if (hss == NULL)
2747                 GOTO(out, rc = -ENOMEM);
2748
2749         hss->hss_valid = HSS_SETMASK | HSS_ARCHIVE_ID;
2750         hss->hss_archive_id = hui->hui_archive_id;
2751         hss->hss_setmask = HS_ARCHIVED | HS_EXISTS | HS_RELEASED;
2752         rc = ll_hsm_state_set(inode, hss);
2753         if (rc != 0)
2754                 GOTO(out, rc);
2755
2756         OBD_ALLOC_PTR(attr);
2757         if (attr == NULL)
2758                 GOTO(out, rc = -ENOMEM);
2759
2760         attr->ia_mode = hui->hui_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
2761         attr->ia_mode |= S_IFREG;
2762         attr->ia_uid = make_kuid(&init_user_ns, hui->hui_uid);
2763         attr->ia_gid = make_kgid(&init_user_ns, hui->hui_gid);
2764         attr->ia_size = hui->hui_size;
2765         attr->ia_mtime.tv_sec = hui->hui_mtime;
2766         attr->ia_mtime.tv_nsec = hui->hui_mtime_ns;
2767         attr->ia_atime.tv_sec = hui->hui_atime;
2768         attr->ia_atime.tv_nsec = hui->hui_atime_ns;
2769
2770         attr->ia_valid = ATTR_SIZE | ATTR_MODE | ATTR_FORCE |
2771                          ATTR_UID | ATTR_GID |
2772                          ATTR_MTIME | ATTR_MTIME_SET |
2773                          ATTR_ATIME | ATTR_ATIME_SET;
2774
2775         inode_lock(inode);
2776
2777         rc = ll_setattr_raw(file_dentry(file), attr, 0, true);
2778         if (rc == -ENODATA)
2779                 rc = 0;
2780
2781         inode_unlock(inode);
2782
2783 out:
2784         if (hss != NULL)
2785                 OBD_FREE_PTR(hss);
2786
2787         if (attr != NULL)
2788                 OBD_FREE_PTR(attr);
2789
2790         RETURN(rc);
2791 }
2792
2793 static inline long ll_lease_type_from_fmode(fmode_t fmode)
2794 {
2795         return ((fmode & FMODE_READ) ? LL_LEASE_RDLCK : 0) |
2796                ((fmode & FMODE_WRITE) ? LL_LEASE_WRLCK : 0);
2797 }
2798
2799 static int ll_file_futimes_3(struct file *file, const struct ll_futimes_3 *lfu)
2800 {
2801         struct inode *inode = file_inode(file);
2802         struct iattr ia = {
2803                 .ia_valid = ATTR_ATIME | ATTR_ATIME_SET |
2804                             ATTR_MTIME | ATTR_MTIME_SET |
2805                             ATTR_CTIME,
2806                 .ia_atime = {
2807                         .tv_sec = lfu->lfu_atime_sec,
2808                         .tv_nsec = lfu->lfu_atime_nsec,
2809                 },
2810                 .ia_mtime = {
2811                         .tv_sec = lfu->lfu_mtime_sec,
2812                         .tv_nsec = lfu->lfu_mtime_nsec,
2813                 },
2814                 .ia_ctime = {
2815                         .tv_sec = lfu->lfu_ctime_sec,
2816                         .tv_nsec = lfu->lfu_ctime_nsec,
2817                 },
2818         };
2819         int rc;
2820         ENTRY;
2821
2822         if (!capable(CAP_SYS_ADMIN))
2823                 RETURN(-EPERM);
2824
2825         if (!S_ISREG(inode->i_mode))
2826                 RETURN(-EINVAL);
2827
2828         inode_lock(inode);
2829         rc = ll_setattr_raw(file_dentry(file), &ia, OP_XVALID_CTIME_SET,
2830                             false);
2831         inode_unlock(inode);
2832
2833         RETURN(rc);
2834 }
2835
2836 static enum cl_lock_mode cl_mode_user_to_kernel(enum lock_mode_user mode)
2837 {
2838         switch (mode) {
2839         case MODE_READ_USER:
2840                 return CLM_READ;
2841         case MODE_WRITE_USER:
2842                 return CLM_WRITE;
2843         default:
2844                 return -EINVAL;
2845         }
2846 }
2847
2848 static const char *const user_lockname[] = LOCK_MODE_NAMES;
2849
2850 /* Used to allow the upper layers of the client to request an LDLM lock
2851  * without doing an actual read or write.
2852  *
2853  * Used for ladvise lockahead to manually request specific locks.
2854  *
2855  * \param[in] file      file this ladvise lock request is on
2856  * \param[in] ladvise   ladvise struct describing this lock request
2857  *
2858  * \retval 0            success, no detailed result available (sync requests
2859  *                      and requests sent to the server [not handled locally]
2860  *                      cannot return detailed results)
2861  * \retval LLA_RESULT_{SAME,DIFFERENT} - detailed result of the lock request,
2862  *                                       see definitions for details.
2863  * \retval negative     negative errno on error
2864  */
2865 int ll_file_lock_ahead(struct file *file, struct llapi_lu_ladvise *ladvise)
2866 {
2867         struct lu_env *env = NULL;
2868         struct cl_io *io  = NULL;
2869         struct cl_lock *lock = NULL;
2870         struct cl_lock_descr *descr = NULL;
2871         struct dentry *dentry = file->f_path.dentry;
2872         struct inode *inode = dentry->d_inode;
2873         enum cl_lock_mode cl_mode;
2874         off_t start = ladvise->lla_start;
2875         off_t end = ladvise->lla_end;
2876         int result;
2877         __u16 refcheck;
2878
2879         ENTRY;
2880
2881         CDEBUG(D_VFSTRACE, "Lock request: file=%.*s, inode=%p, mode=%s "
2882                "start=%llu, end=%llu\n", dentry->d_name.len,
2883                dentry->d_name.name, dentry->d_inode,
2884                user_lockname[ladvise->lla_lockahead_mode], (__u64) start,
2885                (__u64) end);
2886
2887         cl_mode = cl_mode_user_to_kernel(ladvise->lla_lockahead_mode);
2888         if (cl_mode < 0)
2889                 GOTO(out, result = cl_mode);
2890
2891         /* Get IO environment */
2892         result = cl_io_get(inode, &env, &io, &refcheck);
2893         if (result <= 0)
2894                 GOTO(out, result);
2895
2896         result = cl_io_init(env, io, CIT_MISC, io->ci_obj);
2897         if (result > 0) {
2898                 /*
2899                  * nothing to do for this io. This currently happens when
2900                  * stripe sub-object's are not yet created.
2901                  */
2902                 result = io->ci_result;
2903         } else if (result == 0) {
2904                 lock = vvp_env_lock(env);
2905                 descr = &lock->cll_descr;
2906
2907                 descr->cld_obj   = io->ci_obj;
2908                 /* Convert byte offsets to pages */
2909                 descr->cld_start = cl_index(io->ci_obj, start);
2910                 descr->cld_end   = cl_index(io->ci_obj, end);
2911                 descr->cld_mode  = cl_mode;
2912                 /* CEF_MUST is used because we do not want to convert a
2913                  * lockahead request to a lockless lock */
2914                 descr->cld_enq_flags = CEF_MUST | CEF_LOCK_NO_EXPAND |
2915                                        CEF_NONBLOCK;
2916
2917                 if (ladvise->lla_peradvice_flags & LF_ASYNC)
2918                         descr->cld_enq_flags |= CEF_SPECULATIVE;
2919
2920                 result = cl_lock_request(env, io, lock);
2921
2922                 /* On success, we need to release the lock */
2923                 if (result >= 0)
2924                         cl_lock_release(env, lock);
2925         }
2926         cl_io_fini(env, io);
2927         cl_env_put(env, &refcheck);
2928
2929         /* -ECANCELED indicates a matching lock with a different extent
2930          * was already present, and -EEXIST indicates a matching lock
2931          * on exactly the same extent was already present.
2932          * We convert them to positive values for userspace to make
2933          * recognizing true errors easier.
2934          * Note we can only return these detailed results on async requests,
2935          * as sync requests look the same as i/o requests for locking. */
2936         if (result == -ECANCELED)
2937                 result = LLA_RESULT_DIFFERENT;
2938         else if (result == -EEXIST)
2939                 result = LLA_RESULT_SAME;
2940
2941 out:
2942         RETURN(result);
2943 }
2944 static const char *const ladvise_names[] = LU_LADVISE_NAMES;
2945
2946 static int ll_ladvise_sanity(struct inode *inode,
2947                              struct llapi_lu_ladvise *ladvise)
2948 {
2949         struct ll_sb_info *sbi = ll_i2sbi(inode);
2950         enum lu_ladvise_type advice = ladvise->lla_advice;
2951         /* Note the peradvice flags is a 32 bit field, so per advice flags must
2952          * be in the first 32 bits of enum ladvise_flags */
2953         __u32 flags = ladvise->lla_peradvice_flags;
2954         /* 3 lines at 80 characters per line, should be plenty */
2955         int rc = 0;
2956
2957         if (advice > LU_LADVISE_MAX || advice == LU_LADVISE_INVALID) {
2958                 rc = -EINVAL;
2959                 CDEBUG(D_VFSTRACE, "%s: advice with value '%d' not recognized,"
2960                        "last supported advice is %s (value '%d'): rc = %d\n",
2961                        sbi->ll_fsname, advice,
2962                        ladvise_names[LU_LADVISE_MAX-1], LU_LADVISE_MAX-1, rc);
2963                 GOTO(out, rc);
2964         }
2965
2966         /* Per-advice checks */
2967         switch (advice) {
2968         case LU_LADVISE_LOCKNOEXPAND:
2969                 if (flags & ~LF_LOCKNOEXPAND_MASK) {
2970                         rc = -EINVAL;
2971                         CDEBUG(D_VFSTRACE, "%s: Invalid flags (%x) for %s: "
2972                                "rc = %d\n", sbi->ll_fsname, flags,
2973                                ladvise_names[advice], rc);
2974                         GOTO(out, rc);
2975                 }
2976                 break;
2977         case LU_LADVISE_LOCKAHEAD:
2978                 /* Currently only READ and WRITE modes can be requested */
2979                 if (ladvise->lla_lockahead_mode >= MODE_MAX_USER ||
2980                     ladvise->lla_lockahead_mode == 0) {
2981                         rc = -EINVAL;
2982                         CDEBUG(D_VFSTRACE, "%s: Invalid mode (%d) for %s: "
2983                                "rc = %d\n", sbi->ll_fsname,
2984                                ladvise->lla_lockahead_mode,
2985                                ladvise_names[advice], rc);
2986                         GOTO(out, rc);
2987                 }
2988         case LU_LADVISE_WILLREAD:
2989         case LU_LADVISE_DONTNEED:
2990         default:
2991                 /* Note fall through above - These checks apply to all advices
2992                  * except LOCKNOEXPAND */
2993                 if (flags & ~LF_DEFAULT_MASK) {
2994                         rc = -EINVAL;
2995                         CDEBUG(D_VFSTRACE, "%s: Invalid flags (%x) for %s: "
2996                                "rc = %d\n", sbi->ll_fsname, flags,
2997                                ladvise_names[advice], rc);
2998                         GOTO(out, rc);
2999                 }
3000                 if (ladvise->lla_start >= ladvise->lla_end) {
3001                         rc = -EINVAL;
3002                         CDEBUG(D_VFSTRACE, "%s: Invalid range (%llu to %llu) "
3003                                "for %s: rc = %d\n", sbi->ll_fsname,
3004                                ladvise->lla_start, ladvise->lla_end,
3005                                ladvise_names[advice], rc);
3006                         GOTO(out, rc);
3007                 }
3008                 break;
3009         }
3010
3011 out:
3012         return rc;
3013 }
3014 #undef ERRSIZE
3015
3016 /*
3017  * Give file access advices
3018  *
3019  * The ladvise interface is similar to Linux fadvise() system call, except it
3020  * forwards the advices directly from Lustre client to server. The server side
3021  * codes will apply appropriate read-ahead and caching techniques for the
3022  * corresponding files.
3023  *
3024  * A typical workload for ladvise is e.g. a bunch of different clients are
3025  * doing small random reads of a file, so prefetching pages into OSS cache
3026  * with big linear reads before the random IO is a net benefit. Fetching
3027  * all that data into each client cache with fadvise() may not be, due to
3028  * much more data being sent to the client.
3029  */
3030 static int ll_ladvise(struct inode *inode, struct file *file, __u64 flags,
3031                       struct llapi_lu_ladvise *ladvise)
3032 {
3033         struct lu_env *env;
3034         struct cl_io *io;
3035         struct cl_ladvise_io *lio;
3036         int rc;
3037         __u16 refcheck;
3038         ENTRY;
3039
3040         env = cl_env_get(&refcheck);
3041         if (IS_ERR(env))
3042                 RETURN(PTR_ERR(env));
3043
3044         io = vvp_env_thread_io(env);
3045         io->ci_obj = ll_i2info(inode)->lli_clob;
3046
3047         /* initialize parameters for ladvise */
3048         lio = &io->u.ci_ladvise;
3049         lio->li_start = ladvise->lla_start;
3050         lio->li_end = ladvise->lla_end;
3051         lio->li_fid = ll_inode2fid(inode);
3052         lio->li_advice = ladvise->lla_advice;
3053         lio->li_flags = flags;
3054
3055         if (cl_io_init(env, io, CIT_LADVISE, io->ci_obj) == 0)
3056                 rc = cl_io_loop(env, io);
3057         else
3058                 rc = io->ci_result;
3059
3060         cl_io_fini(env, io);
3061         cl_env_put(env, &refcheck);
3062         RETURN(rc);
3063 }
3064
3065 static int ll_lock_noexpand(struct file *file, int flags)
3066 {
3067         struct ll_file_data *fd = LUSTRE_FPRIVATE(file);
3068
3069         fd->ll_lock_no_expand = !(flags & LF_UNSET);
3070
3071         return 0;
3072 }
3073
3074 int ll_ioctl_fsgetxattr(struct inode *inode, unsigned int cmd,
3075                         unsigned long arg)
3076 {
3077         struct fsxattr fsxattr;
3078
3079         if (copy_from_user(&fsxattr,
3080                            (const struct fsxattr __user *)arg,
3081                            sizeof(fsxattr)))
3082                 RETURN(-EFAULT);
3083
3084         fsxattr.fsx_xflags = ll_inode_flags_to_xflags(inode->i_flags);
3085         if (ll_file_test_flag(ll_i2info(inode), LLIF_PROJECT_INHERIT))
3086                 fsxattr.fsx_xflags |= FS_XFLAG_PROJINHERIT;
3087         fsxattr.fsx_projid = ll_i2info(inode)->lli_projid;
3088         if (copy_to_user((struct fsxattr __user *)arg,
3089                          &fsxattr, sizeof(fsxattr)))
3090                 RETURN(-EFAULT);
3091
3092         RETURN(0);
3093 }
3094
3095 int ll_ioctl_check_project(struct inode *inode, struct fsxattr *fa)
3096 {
3097         /*
3098          * Project Quota ID state is only allowed to change from within the init
3099          * namespace. Enforce that restriction only if we are trying to change
3100          * the quota ID state. Everything else is allowed in user namespaces.
3101          */
3102         if (current_user_ns() == &init_user_ns)
3103                 return 0;
3104
3105         if (ll_i2info(inode)->lli_projid != fa->fsx_projid)
3106                 return -EINVAL;
3107
3108         if (ll_file_test_flag(ll_i2info(inode), LLIF_PROJECT_INHERIT)) {
3109                 if (!(fa->fsx_xflags & FS_XFLAG_PROJINHERIT))
3110                         return -EINVAL;
3111         } else {
3112                 if (fa->fsx_xflags & FS_XFLAG_PROJINHERIT)
3113                         return -EINVAL;
3114         }
3115
3116         return 0;
3117 }
3118
3119 int ll_ioctl_fssetxattr(struct inode *inode, unsigned int cmd,
3120                         unsigned long arg)
3121 {
3122
3123         struct md_op_data *op_data;
3124         struct ptlrpc_request *req = NULL;
3125         int rc = 0;
3126         struct fsxattr fsxattr;
3127         struct cl_object *obj;
3128         struct iattr *attr;
3129         int flags;
3130
3131         if (copy_from_user(&fsxattr,
3132                            (const struct fsxattr __user *)arg,
3133                            sizeof(fsxattr)))
3134                 RETURN(-EFAULT);
3135
3136         rc = ll_ioctl_check_project(inode, &fsxattr);
3137         if (rc)
3138                 RETURN(rc);
3139
3140         op_data = ll_prep_md_op_data(NULL, inode, NULL, NULL, 0, 0,
3141                                      LUSTRE_OPC_ANY, NULL);
3142         if (IS_ERR(op_data))
3143                 RETURN(PTR_ERR(op_data));
3144
3145         flags = ll_xflags_to_inode_flags(fsxattr.fsx_xflags);
3146         op_data->op_attr_flags = ll_inode_to_ext_flags(flags);
3147         if (fsxattr.fsx_xflags & FS_XFLAG_PROJINHERIT)
3148                 op_data->op_attr_flags |= LUSTRE_PROJINHERIT_FL;
3149         op_data->op_projid = fsxattr.fsx_projid;
3150         op_data->op_xvalid |= OP_XVALID_PROJID | OP_XVALID_FLAGS;
3151         rc = md_setattr(ll_i2sbi(inode)->ll_md_exp, op_data, NULL,
3152                         0, &req);
3153         ptlrpc_req_finished(req);
3154         if (rc)
3155                 GOTO(out_fsxattr, rc);
3156         ll_update_inode_flags(inode, op_data->op_attr_flags);
3157         obj = ll_i2info(inode)->lli_clob;
3158         if (obj == NULL)
3159                 GOTO(out_fsxattr, rc);
3160
3161         OBD_ALLOC_PTR(attr);
3162         if (attr == NULL)
3163                 GOTO(out_fsxattr, rc = -ENOMEM);
3164
3165         rc = cl_setattr_ost(obj, attr, OP_XVALID_FLAGS,
3166                             fsxattr.fsx_xflags);
3167         OBD_FREE_PTR(attr);
3168 out_fsxattr:
3169         ll_finish_md_op_data(op_data);
3170         RETURN(rc);
3171 }
3172
3173 static long ll_file_unlock_lease(struct file *file, struct ll_ioc_lease *ioc,
3174                                  unsigned long arg)
3175 {
3176         struct inode            *inode = file_inode(file);
3177         struct ll_file_data     *fd = LUSTRE_FPRIVATE(file);
3178         struct ll_inode_info    *lli = ll_i2info(inode);
3179         struct obd_client_handle *och = NULL;
3180         struct split_param sp;
3181         struct pcc_param param;
3182         bool lease_broken = false;
3183         fmode_t fmode = 0;
3184         enum mds_op_bias bias = 0;
3185         struct file *layout_file = NULL;
3186         void *data = NULL;
3187         size_t data_size = 0;
3188         bool attached = false;
3189         long rc, rc2 = 0;
3190
3191         ENTRY;
3192
3193         mutex_lock(&lli->lli_och_mutex);
3194         if (fd->fd_lease_och != NULL) {
3195                 och = fd->fd_lease_och;
3196                 fd->fd_lease_och = NULL;
3197         }
3198         mutex_unlock(&lli->lli_och_mutex);
3199
3200         if (och == NULL)
3201                 RETURN(-ENOLCK);
3202
3203         fmode = och->och_flags;
3204
3205         switch (ioc->lil_flags) {
3206         case LL_LEASE_RESYNC_DONE:
3207                 if (ioc->lil_count > IOC_IDS_MAX)
3208                         GOTO(out_lease_close, rc = -EINVAL);
3209
3210                 data_size = offsetof(typeof(*ioc), lil_ids[ioc->lil_count]);
3211                 OBD_ALLOC(data, data_size);
3212                 if (!data)
3213                         GOTO(out_lease_close, rc = -ENOMEM);
3214
3215                 if (copy_from_user(data, (void __user *)arg, data_size))
3216                         GOTO(out_lease_close, rc = -EFAULT);
3217
3218                 bias = MDS_CLOSE_RESYNC_DONE;
3219                 break;
3220         case LL_LEASE_LAYOUT_MERGE: {
3221                 int fd;
3222
3223                 if (ioc->lil_count != 1)
3224                         GOTO(out_lease_close, rc = -EINVAL);
3225
3226                 arg += sizeof(*ioc);
3227                 if (copy_from_user(&fd, (void __user *)arg, sizeof(__u32)))
3228                         GOTO(out_lease_close, rc = -EFAULT);
3229
3230                 layout_file = fget(fd);
3231                 if (!layout_file)
3232                         GOTO(out_lease_close, rc = -EBADF);
3233
3234                 if ((file->f_flags & O_ACCMODE) == O_RDONLY ||
3235                                 (layout_file->f_flags & O_ACCMODE) == O_RDONLY)
3236                         GOTO(out_lease_close, rc = -EPERM);
3237
3238                 data = file_inode(layout_file);
3239                 bias = MDS_CLOSE_LAYOUT_MERGE;
3240                 break;
3241         }
3242         case LL_LEASE_LAYOUT_SPLIT: {
3243                 int fdv;
3244                 int mirror_id;
3245
3246                 if (ioc->lil_count != 2)
3247                         GOTO(out_lease_close, rc = -EINVAL);
3248
3249                 arg += sizeof(*ioc);
3250                 if (copy_from_user(&fdv, (void __user *)arg, sizeof(__u32)))
3251                         GOTO(out_lease_close, rc = -EFAULT);
3252
3253                 arg += sizeof(__u32);
3254                 if (copy_from_user(&mirror_id, (void __user *)arg,
3255                                    sizeof(__u32)))
3256                         GOTO(out_lease_close, rc = -EFAULT);
3257
3258                 layout_file = fget(fdv);
3259                 if (!layout_file)
3260                         GOTO(out_lease_close, rc = -EBADF);
3261
3262                 sp.sp_inode = file_inode(layout_file);
3263                 sp.sp_mirror_id = (__u16)mirror_id;
3264                 data = &sp;
3265                 bias = MDS_CLOSE_LAYOUT_SPLIT;
3266                 break;
3267         }
3268         case LL_LEASE_PCC_ATTACH:
3269                 if (ioc->lil_count != 1)
3270                         RETURN(-EINVAL);
3271
3272                 arg += sizeof(*ioc);
3273                 if (copy_from_user(&param.pa_archive_id, (void __user *)arg,
3274                                    sizeof(__u32)))
3275                         GOTO(out_lease_close, rc2 = -EFAULT);
3276
3277                 rc2 = pcc_readwrite_attach(file, inode, param.pa_archive_id);
3278                 if (rc2)
3279                         GOTO(out_lease_close, rc2);
3280
3281                 attached = true;
3282                 /* Grab latest data version */
3283                 rc2 = ll_data_version(inode, &param.pa_data_version,
3284                                      LL_DV_WR_FLUSH);
3285                 if (rc2)
3286                         GOTO(out_lease_close, rc2);
3287
3288                 data = &param;
3289                 bias = MDS_PCC_ATTACH;
3290                 break;
3291         default:
3292                 /* without close intent */
3293                 break;
3294         }
3295
3296 out_lease_close:
3297         rc = ll_lease_close_intent(och, inode, &lease_broken, bias, data);
3298         if (rc < 0)
3299                 GOTO(out, rc);
3300
3301         rc = ll_lease_och_release(inode, file);
3302         if (rc < 0)
3303                 GOTO(out, rc);
3304
3305         if (lease_broken)
3306                 fmode = 0;
3307         EXIT;
3308
3309 out:
3310         switch (ioc->lil_flags) {
3311         case LL_LEASE_RESYNC_DONE:
3312                 if (data)
3313                         OBD_FREE(data, data_size);
3314                 break;
3315         case LL_LEASE_LAYOUT_MERGE:
3316         case LL_LEASE_LAYOUT_SPLIT:
3317                 if (layout_file)
3318                         fput(layout_file);
3319                 break;
3320         case LL_LEASE_PCC_ATTACH:
3321                 if (!rc)
3322                         rc = rc2;
3323                 rc = pcc_readwrite_attach_fini(file, inode,
3324                                                param.pa_layout_gen,
3325                                                lease_broken, rc,
3326                                                attached);
3327                 break;
3328         }
3329
3330         if (!rc)
3331                 rc = ll_lease_type_from_fmode(fmode);
3332         RETURN(rc);
3333 }
3334
3335 static long ll_file_set_lease(struct file *file, struct ll_ioc_lease *ioc,
3336                               unsigned long arg)
3337 {
3338         struct inode *inode = file_inode(file);
3339         struct ll_inode_info *lli = ll_i2info(inode);
3340         struct ll_file_data *fd = LUSTRE_FPRIVATE(file);
3341         struct obd_client_handle *och = NULL;
3342         __u64 open_flags = 0;
3343         bool lease_broken;
3344         fmode_t fmode;
3345         long rc;
3346         ENTRY;
3347
3348         switch (ioc->lil_mode) {
3349         case LL_LEASE_WRLCK:
3350                 if (!(file->f_mode & FMODE_WRITE))
3351                         RETURN(-EPERM);
3352                 fmode = FMODE_WRITE;
3353                 break;
3354         case LL_LEASE_RDLCK:
3355                 if (!(file->f_mode & FMODE_READ))
3356                         RETURN(-EPERM);
3357                 fmode = FMODE_READ;
3358                 break;
3359         case LL_LEASE_UNLCK:
3360                 RETURN(ll_file_unlock_lease(file, ioc, arg));
3361         default:
3362                 RETURN(-EINVAL);
3363         }
3364
3365         CDEBUG(D_INODE, "Set lease with mode %u\n", fmode);
3366
3367         /* apply for lease */
3368         if (ioc->lil_flags & LL_LEASE_RESYNC)
3369                 open_flags = MDS_OPEN_RESYNC;
3370         och = ll_lease_open(inode, file, fmode, open_flags);
3371         if (IS_ERR(och))
3372                 RETURN(PTR_ERR(och));
3373
3374         if (ioc->lil_flags & LL_LEASE_RESYNC) {
3375                 rc = ll_lease_file_resync(och, inode, arg);
3376                 if (rc) {
3377                         ll_lease_close(och, inode, NULL);
3378                         RETURN(rc);
3379                 }
3380                 rc = ll_layout_refresh(inode, &fd->fd_layout_version);
3381                 if (rc) {
3382                         ll_lease_close(och, inode, NULL);
3383                         RETURN(rc);
3384                 }
3385         }
3386
3387         rc = 0;
3388         mutex_lock(&lli->lli_och_mutex);
3389         if (fd->fd_lease_och == NULL) {
3390                 fd->fd_lease_och = och;
3391                 och = NULL;
3392         }
3393         mutex_unlock(&lli->lli_och_mutex);
3394         if (och != NULL) {
3395                 /* impossible now that only excl is supported for now */
3396                 ll_lease_close(och, inode, &lease_broken);
3397                 rc = -EBUSY;
3398         }
3399         RETURN(rc);
3400 }
3401
3402 static void ll_heat_get(struct inode *inode, struct lu_heat *heat)
3403 {
3404         struct ll_inode_info *lli = ll_i2info(inode);
3405         struct ll_sb_info *sbi = ll_i2sbi(inode);
3406         __u64 now = ktime_get_real_seconds();
3407         int i;
3408
3409         spin_lock(&lli->lli_heat_lock);
3410         heat->lh_flags = lli->lli_heat_flags;
3411         for (i = 0; i < heat->lh_count; i++)
3412                 heat->lh_heat[i] = obd_heat_get(&lli->lli_heat_instances[i],
3413                                                 now, sbi->ll_heat_decay_weight,
3414                                                 sbi->ll_heat_period_second);
3415         spin_unlock(&lli->lli_heat_lock);
3416 }
3417
3418 static int ll_heat_set(struct inode *inode, enum lu_heat_flag flags)
3419 {
3420         struct ll_inode_info *lli = ll_i2info(inode);
3421         int rc = 0;
3422
3423         spin_lock(&lli->lli_heat_lock);
3424         if (flags & LU_HEAT_FLAG_CLEAR)
3425                 obd_heat_clear(lli->lli_heat_instances, OBD_HEAT_COUNT);
3426
3427         if (flags & LU_HEAT_FLAG_OFF)
3428                 lli->lli_heat_flags |= LU_HEAT_FLAG_OFF;
3429         else
3430                 lli->lli_heat_flags &= ~LU_HEAT_FLAG_OFF;
3431
3432         spin_unlock(&lli->lli_heat_lock);
3433
3434         RETURN(rc);
3435 }
3436
3437 static long
3438 ll_file_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
3439 {
3440         struct inode            *inode = file_inode(file);
3441         struct ll_file_data     *fd = LUSTRE_FPRIVATE(file);
3442         int                      flags, rc;
3443         ENTRY;
3444
3445         CDEBUG(D_VFSTRACE, "VFS Op:inode="DFID"(%p), cmd=%x\n",
3446                PFID(ll_inode2fid(inode)), inode, cmd);
3447         ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_IOCTL, 1);
3448
3449         /* asm-ppc{,64} declares TCGETS, et. al. as type 't' not 'T' */
3450         if (_IOC_TYPE(cmd) == 'T' || _IOC_TYPE(cmd) == 't') /* tty ioctls */
3451                 RETURN(-ENOTTY);
3452
3453         switch (cmd) {
3454         case LL_IOC_GETFLAGS:
3455                 /* Get the current value of the file flags */
3456                 return put_user(fd->fd_flags, (int __user *)arg);
3457         case LL_IOC_SETFLAGS:
3458         case LL_IOC_CLRFLAGS:
3459                 /* Set or clear specific file flags */
3460                 /* XXX This probably needs checks to ensure the flags are
3461                  *     not abused, and to handle any flag side effects.
3462                  */
3463                 if (get_user(flags, (int __user *) arg))
3464                         RETURN(-EFAULT);
3465
3466                 if (cmd == LL_IOC_SETFLAGS) {
3467                         if ((flags & LL_FILE_IGNORE_LOCK) &&
3468                             !(file->f_flags & O_DIRECT)) {
3469                                 CERROR("%s: unable to disable locking on "
3470                                        "non-O_DIRECT file\n", current->comm);
3471                                 RETURN(-EINVAL);
3472                         }
3473
3474                         fd->fd_flags |= flags;
3475                 } else {
3476                         fd->fd_flags &= ~flags;
3477                 }
3478                 RETURN(0);
3479         case LL_IOC_LOV_SETSTRIPE:
3480         case LL_IOC_LOV_SETSTRIPE_NEW:
3481                 RETURN(ll_lov_setstripe(inode, file, (void __user *)arg));
3482         case LL_IOC_LOV_SETEA:
3483                 RETURN(ll_lov_setea(inode, file, (void __user *)arg));
3484         case LL_IOC_LOV_SWAP_LAYOUTS: {
3485                 struct file *file2;
3486                 struct lustre_swap_layouts lsl;
3487
3488                 if (copy_from_user(&lsl, (char __user *)arg,
3489                                    sizeof(struct lustre_swap_layouts)))
3490                         RETURN(-EFAULT);
3491
3492                 if ((file->f_flags & O_ACCMODE) == O_RDONLY)
3493                         RETURN(-EPERM);
3494
3495                 file2 = fget(lsl.sl_fd);
3496                 if (file2 == NULL)
3497                         RETURN(-EBADF);
3498
3499                 /* O_WRONLY or O_RDWR */
3500                 if ((file2->f_flags & O_ACCMODE) == O_RDONLY)
3501                         GOTO(out, rc = -EPERM);
3502
3503                 if (lsl.sl_flags & SWAP_LAYOUTS_CLOSE) {
3504                         struct inode                    *inode2;
3505                         struct ll_inode_info            *lli;
3506                         struct obd_client_handle        *och = NULL;
3507
3508                         lli = ll_i2info(inode);
3509                         mutex_lock(&lli->lli_och_mutex);
3510                         if (fd->fd_lease_och != NULL) {
3511                                 och = fd->fd_lease_och;
3512                                 fd->fd_lease_och = NULL;
3513                         }
3514                         mutex_unlock(&lli->lli_och_mutex);
3515                         if (och == NULL)
3516                                 GOTO(out, rc = -ENOLCK);
3517                         inode2 = file_inode(file2);
3518                         rc = ll_swap_layouts_close(och, inode, inode2);
3519                 } else {
3520                         rc = ll_swap_layouts(file, file2, &lsl);
3521                 }
3522 out:
3523                 fput(file2);
3524                 RETURN(rc);
3525         }
3526         case LL_IOC_LOV_GETSTRIPE:
3527         case LL_IOC_LOV_GETSTRIPE_NEW:
3528                 RETURN(ll_file_getstripe(inode, (void __user *)arg, 0));
3529         case FS_IOC_GETFLAGS:
3530         case FS_IOC_SETFLAGS:
3531                 RETURN(ll_iocontrol(inode, file, cmd, arg));
3532         case FSFILT_IOC_GETVERSION:
3533         case FS_IOC_GETVERSION:
3534                 RETURN(put_user(inode->i_generation, (int __user *)arg));
3535         /* We need to special case any other ioctls we want to handle,
3536          * to send them to the MDS/OST as appropriate and to properly
3537          * network encode the arg field. */
3538         case FS_IOC_SETVERSION:
3539                 RETURN(-ENOTSUPP);
3540
3541         case LL_IOC_GROUP_LOCK:
3542                 RETURN(ll_get_grouplock(inode, file, arg));
3543         case LL_IOC_GROUP_UNLOCK:
3544                 RETURN(ll_put_grouplock(inode, file, arg));
3545         case IOC_OBD_STATFS:
3546                 RETURN(ll_obd_statfs(inode, (void __user *)arg));
3547
3548         case LL_IOC_FLUSHCTX:
3549                 RETURN(ll_flush_ctx(inode));
3550         case LL_IOC_PATH2FID: {
3551                 if (copy_to_user((void __user *)arg, ll_inode2fid(inode),
3552                                  sizeof(struct lu_fid)))
3553                         RETURN(-EFAULT);
3554
3555                 RETURN(0);
3556         }
3557         case LL_IOC_GETPARENT:
3558                 RETURN(ll_getparent(file, (struct getparent __user *)arg));
3559
3560         case OBD_IOC_FID2PATH:
3561                 RETURN(ll_fid2path(inode, (void __user *)arg));
3562         case LL_IOC_DATA_VERSION: {
3563                 struct ioc_data_version idv;
3564                 int rc;
3565
3566                 if (copy_from_user(&idv, (char __user *)arg, sizeof(idv)))
3567                         RETURN(-EFAULT);
3568
3569                 idv.idv_flags &= LL_DV_RD_FLUSH | LL_DV_WR_FLUSH;
3570                 rc = ll_ioc_data_version(inode, &idv);
3571
3572                 if (rc == 0 &&
3573                     copy_to_user((char __user *)arg, &idv, sizeof(idv)))
3574                         RETURN(-EFAULT);
3575
3576                 RETURN(rc);
3577         }
3578
3579         case LL_IOC_GET_MDTIDX: {
3580                 int mdtidx;
3581
3582                 mdtidx = ll_get_mdt_idx(inode);
3583                 if (mdtidx < 0)
3584                         RETURN(mdtidx);
3585
3586                 if (put_user((int)mdtidx, (int __user *)arg))
3587                         RETURN(-EFAULT);
3588
3589                 RETURN(0);
3590         }
3591         case OBD_IOC_GETDTNAME:
3592         case OBD_IOC_GETMDNAME:
3593                 RETURN(ll_get_obd_name(inode, cmd, arg));
3594         case LL_IOC_HSM_STATE_GET: {
3595                 struct md_op_data       *op_data;
3596                 struct hsm_user_state   *hus;
3597                 int                      rc;
3598
3599                 OBD_ALLOC_PTR(hus);
3600                 if (hus == NULL)
3601                         RETURN(-ENOMEM);
3602
3603                 op_data = ll_prep_md_op_data(NULL, inode, NULL, NULL, 0, 0,
3604                                              LUSTRE_OPC_ANY, hus);
3605                 if (IS_ERR(op_data)) {
3606                         OBD_FREE_PTR(hus);
3607                         RETURN(PTR_ERR(op_data));
3608                 }
3609
3610                 rc = obd_iocontrol(cmd, ll_i2mdexp(inode), sizeof(*op_data),
3611                                    op_data, NULL);
3612
3613                 if (copy_to_user((void __user *)arg, hus, sizeof(*hus)))
3614                         rc = -EFAULT;
3615
3616                 ll_finish_md_op_data(op_data);
3617                 OBD_FREE_PTR(hus);
3618                 RETURN(rc);
3619         }
3620         case LL_IOC_HSM_STATE_SET: {
3621                 struct hsm_state_set    *hss;
3622                 int                      rc;
3623
3624                 OBD_ALLOC_PTR(hss);
3625                 if (hss == NULL)
3626                         RETURN(-ENOMEM);
3627
3628                 if (copy_from_user(hss, (char __user *)arg, sizeof(*hss))) {
3629                         OBD_FREE_PTR(hss);
3630                         RETURN(-EFAULT);
3631                 }
3632
3633                 rc = ll_hsm_state_set(inode, hss);
3634
3635                 OBD_FREE_PTR(hss);
3636                 RETURN(rc);
3637         }
3638         case LL_IOC_HSM_ACTION: {
3639                 struct md_op_data               *op_data;
3640                 struct hsm_current_action       *hca;
3641                 int                              rc;
3642
3643                 OBD_ALLOC_PTR(hca);
3644                 if (hca == NULL)
3645                         RETURN(-ENOMEM);
3646
3647                 op_data = ll_prep_md_op_data(NULL, inode, NULL, NULL, 0, 0,
3648                                              LUSTRE_OPC_ANY, hca);
3649                 if (IS_ERR(op_data)) {
3650                         OBD_FREE_PTR(hca);
3651                         RETURN(PTR_ERR(op_data));
3652                 }
3653
3654                 rc = obd_iocontrol(cmd, ll_i2mdexp(inode), sizeof(*op_data),
3655                                    op_data, NULL);
3656
3657                 if (copy_to_user((char __user *)arg, hca, sizeof(*hca)))
3658                         rc = -EFAULT;
3659
3660                 ll_finish_md_op_data(op_data);
3661                 OBD_FREE_PTR(hca);
3662                 RETURN(rc);
3663         }
3664         case LL_IOC_SET_LEASE_OLD: {
3665                 struct ll_ioc_lease ioc = { .lil_mode = (__u32)arg };
3666
3667                 RETURN(ll_file_set_lease(file, &ioc, 0));
3668         }
3669         case LL_IOC_SET_LEASE: {
3670                 struct ll_ioc_lease ioc;
3671
3672                 if (copy_from_user(&ioc, (void __user *)arg, sizeof(ioc)))
3673                         RETURN(-EFAULT);
3674
3675                 RETURN(ll_file_set_lease(file, &ioc, arg));
3676         }
3677         case LL_IOC_GET_LEASE: {
3678                 struct ll_inode_info *lli = ll_i2info(inode);
3679                 struct ldlm_lock *lock = NULL;
3680                 fmode_t fmode = 0;
3681
3682                 mutex_lock(&lli->lli_och_mutex);
3683                 if (fd->fd_lease_och != NULL) {
3684                         struct obd_client_handle *och = fd->fd_lease_och;
3685
3686                         lock = ldlm_handle2lock(&och->och_lease_handle);
3687                         if (lock != NULL) {
3688                                 lock_res_and_lock(lock);
3689                                 if (!ldlm_is_cancel(lock))
3690                                         fmode = och->och_flags;
3691
3692                                 unlock_res_and_lock(lock);
3693                                 LDLM_LOCK_PUT(lock);
3694                         }
3695                 }
3696                 mutex_unlock(&lli->lli_och_mutex);
3697
3698                 RETURN(ll_lease_type_from_fmode(fmode));
3699         }
3700         case LL_IOC_HSM_IMPORT: {
3701                 struct hsm_user_import *hui;
3702
3703                 OBD_ALLOC_PTR(hui);
3704                 if (hui == NULL)
3705                         RETURN(-ENOMEM);
3706
3707                 if (copy_from_user(hui, (void __user *)arg, sizeof(*hui))) {
3708                         OBD_FREE_PTR(hui);
3709                         RETURN(-EFAULT);
3710                 }
3711
3712                 rc = ll_hsm_import(inode, file, hui);
3713
3714                 OBD_FREE_PTR(hui);
3715                 RETURN(rc);
3716         }
3717         case LL_IOC_FUTIMES_3: {
3718                 struct ll_futimes_3 lfu;
3719
3720                 if (copy_from_user(&lfu,
3721                                    (const struct ll_futimes_3 __user *)arg,
3722                                    sizeof(lfu)))
3723                         RETURN(-EFAULT);
3724
3725                 RETURN(ll_file_futimes_3(file, &lfu));
3726         }
3727         case LL_IOC_LADVISE: {
3728                 struct llapi_ladvise_hdr *k_ladvise_hdr;
3729                 struct llapi_ladvise_hdr __user *u_ladvise_hdr;
3730                 int i;
3731                 int num_advise;
3732                 int alloc_size = sizeof(*k_ladvise_hdr);
3733
3734                 rc = 0;
3735                 u_ladvise_hdr = (void __user *)arg;
3736                 OBD_ALLOC_PTR(k_ladvise_hdr);
3737                 if (k_ladvise_hdr == NULL)
3738                         RETURN(-ENOMEM);
3739
3740                 if (copy_from_user(k_ladvise_hdr, u_ladvise_hdr, alloc_size))
3741                         GOTO(out_ladvise, rc = -EFAULT);
3742
3743                 if (k_ladvise_hdr->lah_magic != LADVISE_MAGIC ||
3744                     k_ladvise_hdr->lah_count < 1)
3745                         GOTO(out_ladvise, rc = -EINVAL);
3746
3747                 num_advise = k_ladvise_hdr->lah_count;
3748                 if (num_advise >= LAH_COUNT_MAX)
3749                         GOTO(out_ladvise, rc = -EFBIG);
3750
3751                 OBD_FREE_PTR(k_ladvise_hdr);
3752                 alloc_size = offsetof(typeof(*k_ladvise_hdr),
3753                                       lah_advise[num_advise]);
3754                 OBD_ALLOC(k_ladvise_hdr, alloc_size);
3755                 if (k_ladvise_hdr == NULL)
3756                         RETURN(-ENOMEM);
3757
3758                 /*
3759                  * TODO: submit multiple advices to one server in a single RPC
3760                  */
3761                 if (copy_from_user(k_ladvise_hdr, u_ladvise_hdr, alloc_size))
3762                         GOTO(out_ladvise, rc = -EFAULT);
3763
3764                 for (i = 0; i < num_advise; i++) {
3765                         struct llapi_lu_ladvise *k_ladvise =
3766                                         &k_ladvise_hdr->lah_advise[i];
3767                         struct llapi_lu_ladvise __user *u_ladvise =
3768                                         &u_ladvise_hdr->lah_advise[i];
3769
3770                         rc = ll_ladvise_sanity(inode, k_ladvise);
3771                         if (rc)
3772                                 GOTO(out_ladvise, rc);
3773
3774                         switch (k_ladvise->lla_advice) {
3775                         case LU_LADVISE_LOCKNOEXPAND:
3776                                 rc = ll_lock_noexpand(file,
3777                                                k_ladvise->lla_peradvice_flags);
3778                                 GOTO(out_ladvise, rc);
3779                         case LU_LADVISE_LOCKAHEAD:
3780
3781                                 rc = ll_file_lock_ahead(file, k_ladvise);
3782
3783                                 if (rc < 0)
3784                                         GOTO(out_ladvise, rc);
3785
3786                                 if (put_user(rc,
3787                                              &u_ladvise->lla_lockahead_result))
3788                                         GOTO(out_ladvise, rc = -EFAULT);
3789                                 break;
3790                         default:
3791                                 rc = ll_ladvise(inode, file,
3792                                                 k_ladvise_hdr->lah_flags,
3793                                                 k_ladvise);
3794                                 if (rc)
3795                                         GOTO(out_ladvise, rc);
3796                                 break;
3797                         }
3798
3799                 }
3800
3801 out_ladvise:
3802                 OBD_FREE(k_ladvise_hdr, alloc_size);
3803                 RETURN(rc);
3804         }
3805         case LL_IOC_FLR_SET_MIRROR: {
3806                 /* mirror I/O must be direct to avoid polluting page cache
3807                  * by stale data. */
3808                 if (!(file->f_flags & O_DIRECT))
3809                         RETURN(-EINVAL);
3810
3811                 fd->fd_designated_mirror = (__u32)arg;
3812                 RETURN(0);
3813         }
3814         case LL_IOC_FSGETXATTR:
3815                 RETURN(ll_ioctl_fsgetxattr(inode, cmd, arg));
3816         case LL_IOC_FSSETXATTR:
3817                 RETURN(ll_ioctl_fssetxattr(inode, cmd, arg));
3818         case BLKSSZGET:
3819                 RETURN(put_user(PAGE_SIZE, (int __user *)arg));
3820         case LL_IOC_HEAT_GET: {
3821                 struct lu_heat uheat;
3822                 struct lu_heat *heat;
3823                 int size;
3824
3825                 if (copy_from_user(&uheat, (void __user *)arg, sizeof(uheat)))
3826                         RETURN(-EFAULT);
3827
3828                 if (uheat.lh_count > OBD_HEAT_COUNT)
3829                         uheat.lh_count = OBD_HEAT_COUNT;
3830
3831                 size = offsetof(typeof(uheat), lh_heat[uheat.lh_count]);
3832                 OBD_ALLOC(heat, size);
3833                 if (heat == NULL)
3834                         RETURN(-ENOMEM);
3835
3836                 heat->lh_count = uheat.lh_count;
3837                 ll_heat_get(inode, heat);
3838                 rc = copy_to_user((char __user *)arg, heat, size);
3839                 OBD_FREE(heat, size);
3840                 RETURN(rc ? -EFAULT : 0);
3841         }
3842         case LL_IOC_HEAT_SET: {
3843                 __u64 flags;
3844
3845                 if (copy_from_user(&flags, (void __user *)arg, sizeof(flags)))
3846                         RETURN(-EFAULT);
3847
3848                 rc = ll_heat_set(inode, flags);
3849                 RETURN(rc);
3850         }
3851         case LL_IOC_PCC_DETACH: {
3852                 struct lu_pcc_detach *detach;
3853
3854                 OBD_ALLOC_PTR(detach);
3855                 if (detach == NULL)
3856                         RETURN(-ENOMEM);
3857
3858                 if (copy_from_user(detach,
3859                                    (const struct lu_pcc_detach __user *)arg,
3860                                    sizeof(*detach)))
3861                         GOTO(out_detach_free, rc = -EFAULT);
3862
3863                 if (!S_ISREG(inode->i_mode))
3864                         GOTO(out_detach_free, rc = -EINVAL);
3865
3866                 if (!inode_owner_or_capable(inode))
3867                         GOTO(out_detach_free, rc = -EPERM);
3868
3869                 rc = pcc_ioctl_detach(inode, detach->pccd_opt);
3870 out_detach_free:
3871                 OBD_FREE_PTR(detach);
3872                 RETURN(rc);
3873         }
3874         case LL_IOC_PCC_STATE: {
3875                 struct lu_pcc_state __user *ustate =
3876                         (struct lu_pcc_state __user *)arg;
3877                 struct lu_pcc_state *state;
3878
3879                 OBD_ALLOC_PTR(state);
3880                 if (state == NULL)
3881                         RETURN(-ENOMEM);
3882
3883                 if (copy_from_user(state, ustate, sizeof(*state)))
3884                         GOTO(out_state, rc = -EFAULT);
3885
3886                 rc = pcc_ioctl_state(file, inode, state);
3887                 if (rc)
3888                         GOTO(out_state, rc);
3889
3890                 if (copy_to_user(ustate, state, sizeof(*state)))
3891                         GOTO(out_state, rc = -EFAULT);
3892
3893 out_state:
3894                 OBD_FREE_PTR(state);
3895                 RETURN(rc);
3896         }
3897         default:
3898                 RETURN(obd_iocontrol(cmd, ll_i2dtexp(inode), 0, NULL,
3899                                      (void __user *)arg));
3900         }
3901 }
3902
3903 #ifndef HAVE_FILE_LLSEEK_SIZE
3904 static inline loff_t
3905 llseek_execute(struct file *file, loff_t offset, loff_t maxsize)
3906 {
3907         if (offset < 0 && !(file->f_mode & FMODE_UNSIGNED_OFFSET))
3908                 return -EINVAL;
3909         if (offset > maxsize)
3910                 return -EINVAL;
3911
3912         if (offset != file->f_pos) {
3913                 file->f_pos = offset;
3914                 file->f_version = 0;
3915         }
3916         return offset;
3917 }
3918
3919 static loff_t
3920 generic_file_llseek_size(struct file *file, loff_t offset, int origin,
3921                 loff_t maxsize, loff_t eof)
3922 {
3923         struct inode *inode = file_inode(file);
3924
3925         switch (origin) {
3926         case SEEK_END:
3927                 offset += eof;
3928                 break;
3929         case SEEK_CUR:
3930                 /*
3931                  * Here we special-case the lseek(fd, 0, SEEK_CUR)
3932                  * position-querying operation.  Avoid rewriting the "same"
3933                  * f_pos value back to the file because a concurrent read(),
3934                  * write() or lseek() might have altered it
3935                  */
3936                 if (offset == 0)
3937                         return file->f_pos;
3938                 /*
3939                  * f_lock protects against read/modify/write race with other
3940                  * SEEK_CURs. Note that parallel writes and reads behave
3941                  * like SEEK_SET.
3942                  */
3943                 inode_lock(inode);
3944                 offset = llseek_execute(file, file->f_pos + offset, maxsize);
3945                 inode_unlock(inode);
3946                 return offset;
3947         case SEEK_DATA:
3948                 /*
3949                  * In the generic case the entire file is data, so as long as
3950                  * offset isn't at the end of the file then the offset is data.
3951                  */
3952                 if (offset >= eof)
3953                         return -ENXIO;
3954                 break;
3955         case SEEK_HOLE:
3956                 /*
3957                  * There is a virtual hole at the end of the file, so as long as
3958                  * offset isn't i_size or larger, return i_size.
3959                  */
3960                 if (offset >= eof)
3961                         return -ENXIO;
3962                 offset = eof;
3963                 break;
3964         }
3965
3966         return llseek_execute(file, offset, maxsize);
3967 }
3968 #endif
3969
3970 static loff_t ll_file_seek(struct file *file, loff_t offset, int origin)
3971 {
3972         struct inode *inode = file_inode(file);
3973         loff_t retval, eof = 0;
3974
3975         ENTRY;
3976         retval = offset + ((origin == SEEK_END) ? i_size_read(inode) :
3977                            (origin == SEEK_CUR) ? file->f_pos : 0);
3978         CDEBUG(D_VFSTRACE, "VFS Op:inode="DFID"(%p), to=%llu=%#llx(%d)\n",
3979                PFID(ll_inode2fid(inode)), inode, retval, retval,
3980                origin);
3981         ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_LLSEEK, 1);
3982
3983         if (origin == SEEK_END || origin == SEEK_HOLE || origin == SEEK_DATA) {
3984                 retval = ll_glimpse_size(inode);
3985                 if (retval != 0)
3986                         RETURN(retval);
3987                 eof = i_size_read(inode);
3988         }
3989
3990         retval = ll_generic_file_llseek_size(file, offset, origin,
3991                                           ll_file_maxbytes(inode), eof);
3992         RETURN(retval);
3993 }
3994
3995 static int ll_flush(struct file *file, fl_owner_t id)
3996 {
3997         struct inode *inode = file_inode(file);
3998         struct ll_inode_info *lli = ll_i2info(inode);
3999         struct ll_file_data *fd = LUSTRE_FPRIVATE(file);
4000         int rc, err;
4001
4002         LASSERT(!S_ISDIR(inode->i_mode));
4003
4004         /* catch async errors that were recorded back when async writeback
4005          * failed for pages in this mapping. */
4006         rc = lli->lli_async_rc;
4007         lli->lli_async_rc = 0;
4008         if (lli->lli_clob != NULL) {
4009                 err = lov_read_and_clear_async_rc(lli->lli_clob);
4010                 if (rc == 0)
4011                         rc = err;
4012         }
4013
4014         /* The application has been told write failure already.
4015          * Do not report failure again. */
4016         if (fd->fd_write_failed)
4017                 return 0;
4018         return rc ? -EIO : 0;
4019 }
4020
4021 /**
4022  * Called to make sure a portion of file has been written out.
4023  * if @mode is not CL_FSYNC_LOCAL, it will send OST_SYNC RPCs to OST.
4024  *
4025  * Return how many pages have been written.
4026  */
4027 int cl_sync_file_range(struct inode *inode, loff_t start, loff_t end,
4028                        enum cl_fsync_mode mode, int ignore_layout)
4029 {
4030         struct lu_env *env;
4031         struct cl_io *io;
4032         struct cl_fsync_io *fio;
4033         int result;
4034         __u16 refcheck;
4035         ENTRY;
4036
4037         if (mode != CL_FSYNC_NONE && mode != CL_FSYNC_LOCAL &&
4038             mode != CL_FSYNC_DISCARD && mode != CL_FSYNC_ALL)
4039                 RETURN(-EINVAL);
4040
4041         env = cl_env_get(&refcheck);
4042         if (IS_ERR(env))
4043                 RETURN(PTR_ERR(env));
4044
4045         io = vvp_env_thread_io(env);
4046         io->ci_obj = ll_i2info(inode)->lli_clob;
4047         io->ci_ignore_layout = ignore_layout;
4048
4049         /* initialize parameters for sync */
4050         fio = &io->u.ci_fsync;
4051         fio->fi_start = start;
4052         fio->fi_end = end;
4053         fio->fi_fid = ll_inode2fid(inode);
4054         fio->fi_mode = mode;
4055         fio->fi_nr_written = 0;
4056
4057         if (cl_io_init(env, io, CIT_FSYNC, io->ci_obj) == 0)
4058                 result = cl_io_loop(env, io);
4059         else
4060                 result = io->ci_result;
4061         if (result == 0)
4062                 result = fio->fi_nr_written;
4063         cl_io_fini(env, io);
4064         cl_env_put(env, &refcheck);
4065
4066         RETURN(result);
4067 }
4068
4069 /*
4070  * When dentry is provided (the 'else' case), file_dentry() may be
4071  * null and dentry must be used directly rather than pulled from
4072  * file_dentry() as is done otherwise.
4073  */
4074
4075 #ifdef HAVE_FILE_FSYNC_4ARGS
4076 int ll_fsync(struct file *file, loff_t start, loff_t end, int datasync)
4077 {
4078         struct dentry *dentry = file_dentry(file);
4079 #elif defined(HAVE_FILE_FSYNC_2ARGS)
4080 int ll_fsync(struct file *file, int datasync)
4081 {
4082         struct dentry *dentry = file_dentry(file);
4083         loff_t start = 0;
4084         loff_t end = LLONG_MAX;
4085 #else
4086 int ll_fsync(struct file *file, struct dentry *dentry, int datasync)
4087 {
4088         loff_t start = 0;
4089         loff_t end = LLONG_MAX;
4090 #endif
4091         struct inode *inode = dentry->d_inode;
4092         struct ll_inode_info *lli = ll_i2info(inode);
4093         struct ptlrpc_request *req;
4094         int rc, err;
4095
4096         ENTRY;
4097
4098         CDEBUG(D_VFSTRACE, "VFS Op:inode="DFID"(%p)\n",
4099                PFID(ll_inode2fid(inode)), inode);
4100         ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_FSYNC, 1);
4101
4102 #ifdef HAVE_FILE_FSYNC_4ARGS
4103         rc = filemap_write_and_wait_range(inode->i_mapping, start, end);
4104         inode_lock(inode);
4105 #else
4106         /* fsync's caller has already called _fdata{sync,write}, we want
4107          * that IO to finish before calling the osc and mdc sync methods */
4108         rc = filemap_fdatawait(inode->i_mapping);
4109 #endif
4110
4111         /* catch async errors that were recorded back when async writeback
4112          * failed for pages in this mapping. */
4113         if (!S_ISDIR(inode->i_mode)) {
4114                 err = lli->lli_async_rc;
4115                 lli->lli_async_rc = 0;
4116                 if (rc == 0)
4117                         rc = err;
4118                 if (lli->lli_clob != NULL) {
4119                         err = lov_read_and_clear_async_rc(lli->lli_clob);
4120                         if (rc == 0)
4121                                 rc = err;
4122                 }
4123         }
4124
4125         err = md_fsync(ll_i2sbi(inode)->ll_md_exp, ll_inode2fid(inode), &req);
4126         if (!rc)
4127                 rc = err;
4128         if (!err)
4129                 ptlrpc_req_finished(req);
4130
4131         if (S_ISREG(inode->i_mode)) {
4132                 struct ll_file_data *fd = LUSTRE_FPRIVATE(file);
4133                 bool cached;
4134
4135                 /* Sync metadata on MDT first, and then sync the cached data
4136                  * on PCC.
4137                  */
4138                 err = pcc_fsync(file, start, end, datasync, &cached);
4139                 if (!cached)
4140                         err = cl_sync_file_range(inode, start, end,
4141                                                  CL_FSYNC_ALL, 0);
4142                 if (rc == 0 && err < 0)
4143                         rc = err;
4144                 if (rc < 0)
4145                         fd->fd_write_failed = true;
4146                 else
4147                         fd->fd_write_failed = false;
4148         }
4149
4150 #ifdef HAVE_FILE_FSYNC_4ARGS
4151         inode_unlock(inode);
4152 #endif
4153         RETURN(rc);
4154 }
4155
4156 static int
4157 ll_file_flock(struct file *file, int cmd, struct file_lock *file_lock)
4158 {
4159         struct inode *inode = file_inode(file);
4160         struct ll_sb_info *sbi = ll_i2sbi(inode);
4161         struct ldlm_enqueue_info einfo = {
4162                 .ei_type        = LDLM_FLOCK,
4163                 .ei_cb_cp       = ldlm_flock_completion_ast,
4164                 .ei_cbdata      = file_lock,
4165         };
4166         struct md_op_data *op_data;
4167         struct lustre_handle lockh = { 0 };
4168         union ldlm_policy_data flock = { { 0 } };
4169         int fl_type = file_lock->fl_type;
4170         __u64 flags = 0;
4171         int rc;
4172         int rc2 = 0;
4173         ENTRY;
4174
4175         CDEBUG(D_VFSTRACE, "VFS Op:inode="DFID" file_lock=%p\n",
4176                PFID(ll_inode2fid(inode)), file_lock);
4177
4178         ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_FLOCK, 1);
4179
4180         if (file_lock->fl_flags & FL_FLOCK) {
4181                 LASSERT((cmd == F_SETLKW) || (cmd == F_SETLK));
4182                 /* flocks are whole-file locks */
4183                 flock.l_flock.end = OFFSET_MAX;
4184                 /* For flocks owner is determined by the local file desctiptor*/
4185                 flock.l_flock.owner = (unsigned long)file_lock->fl_file;
4186         } else if (file_lock->fl_flags & FL_POSIX) {
4187                 flock.l_flock.owner = (unsigned long)file_lock->fl_owner;
4188                 flock.l_flock.start = file_lock->fl_start;
4189                 flock.l_flock.end = file_lock->fl_end;
4190         } else {
4191                 RETURN(-EINVAL);
4192         }
4193         flock.l_flock.pid = file_lock->fl_pid;
4194
4195         /* Somewhat ugly workaround for svc lockd.
4196          * lockd installs custom fl_lmops->lm_compare_owner that checks
4197          * for the fl_owner to be the same (which it always is on local node
4198          * I guess between lockd processes) and then compares pid.
4199          * As such we assign pid to the owner field to make it all work,
4200          * conflict with normal locks is unlikely since pid space and
4201          * pointer space for current->files are not intersecting */
4202         if (file_lock->fl_lmops && file_lock->fl_lmops->lm_compare_owner)
4203                 flock.l_flock.owner = (unsigned long)file_lock->fl_pid;
4204
4205         switch (fl_type) {
4206         case F_RDLCK:
4207                 einfo.ei_mode = LCK_PR;
4208                 break;
4209         case F_UNLCK:
4210                 /* An unlock request may or may not have any relation to
4211                  * existing locks so we may not be able to pass a lock handle
4212                  * via a normal ldlm_lock_cancel() request. The request may even
4213                  * unlock a byte range in the middle of an existing lock. In
4214                  * order to process an unlock request we need all of the same
4215                  * information that is given with a normal read or write record
4216                  * lock request. To avoid creating another ldlm unlock (cancel)
4217                  * message we'll treat a LCK_NL flock request as an unlock. */
4218                 einfo.ei_mode = LCK_NL;
4219                 break;
4220         case F_WRLCK:
4221                 einfo.ei_mode = LCK_PW;
4222                 break;
4223         default:
4224                 CDEBUG(D_INFO, "Unknown fcntl lock type: %d\n", fl_type);
4225                 RETURN (-ENOTSUPP);
4226         }
4227
4228         switch (cmd) {
4229         case F_SETLKW:
4230 #ifdef F_SETLKW64
4231         case F_SETLKW64:
4232 #endif
4233                 flags = 0;
4234                 break;
4235         case F_SETLK:
4236 #ifdef F_SETLK64
4237         case F_SETLK64:
4238 #endif
4239                 flags = LDLM_FL_BLOCK_NOWAIT;
4240                 break;
4241         case F_GETLK:
4242 #ifdef F_GETLK64
4243         case F_GETLK64:
4244 #endif
4245                 flags = LDLM_FL_TEST_LOCK;
4246                 break;
4247         default:
4248                 CERROR("unknown fcntl lock command: %d\n", cmd);
4249                 RETURN (-EINVAL);
4250         }
4251
4252         /* Save the old mode so that if the mode in the lock changes we
4253          * can decrement the appropriate reader or writer refcount. */
4254         file_lock->fl_type = einfo.ei_mode;
4255
4256         op_data = ll_prep_md_op_data(NULL, inode, NULL, NULL, 0, 0,
4257                                      LUSTRE_OPC_ANY, NULL);
4258         if (IS_ERR(op_data))
4259                 RETURN(PTR_ERR(op_data));
4260
4261         CDEBUG(D_DLMTRACE, "inode="DFID", pid=%u, flags=%#llx, mode=%u, "
4262                "start=%llu, end=%llu\n", PFID(ll_inode2fid(inode)),
4263                flock.l_flock.pid, flags, einfo.ei_mode,
4264                flock.l_flock.start, flock.l_flock.end);
4265
4266         rc = md_enqueue(sbi->ll_md_exp, &einfo, &flock, op_data, &lockh,
4267                         flags);
4268
4269         /* Restore the file lock type if not TEST lock. */
4270         if (!(flags & LDLM_FL_TEST_LOCK))
4271                 file_lock->fl_type = fl_type;
4272
4273 #ifdef HAVE_LOCKS_LOCK_FILE_WAIT
4274         if ((rc == 0 || file_lock->fl_type == F_UNLCK) &&
4275             !(flags & LDLM_FL_TEST_LOCK))
4276                 rc2  = locks_lock_file_wait(file, file_lock);
4277 #else
4278         if ((file_lock->fl_flags & FL_FLOCK) &&
4279             (rc == 0 || file_lock->fl_type == F_UNLCK))
4280                 rc2  = flock_lock_file_wait(file, file_lock);
4281         if ((file_lock->fl_flags & FL_POSIX) &&
4282             (rc == 0 || file_lock->fl_type == F_UNLCK) &&
4283             !(flags & LDLM_FL_TEST_LOCK))
4284                 rc2  = posix_lock_file_wait(file, file_lock);
4285 #endif /* HAVE_LOCKS_LOCK_FILE_WAIT */
4286
4287         if (rc2 && file_lock->fl_type != F_UNLCK) {
4288                 einfo.ei_mode = LCK_NL;
4289                 md_enqueue(sbi->ll_md_exp, &einfo, &flock, op_data,
4290                            &lockh, flags);
4291                 rc = rc2;
4292         }
4293
4294         ll_finish_md_op_data(op_data);
4295
4296         RETURN(rc);
4297 }
4298
4299 int ll_get_fid_by_name(struct inode *parent, const char *name,
4300                        int namelen, struct lu_fid *fid,
4301                        struct inode **inode)
4302 {
4303         struct md_op_data       *op_data = NULL;
4304         struct mdt_body         *body;
4305         struct ptlrpc_request   *req;
4306         int                     rc;
4307         ENTRY;
4308
4309         op_data = ll_prep_md_op_data(NULL, parent, NULL, name, namelen, 0,
4310                                      LUSTRE_OPC_ANY, NULL);
4311         if (IS_ERR(op_data))
4312                 RETURN(PTR_ERR(op_data));
4313
4314         op_data->op_valid = OBD_MD_FLID | OBD_MD_FLTYPE;
4315         rc = md_getattr_name(ll_i2sbi(parent)->ll_md_exp, op_data, &req);
4316         ll_finish_md_op_data(op_data);
4317         if (rc < 0)
4318                 RETURN(rc);
4319
4320         body = req_capsule_server_get(&req->rq_pill, &RMF_MDT_BODY);
4321         if (body == NULL)
4322                 GOTO(out_req, rc = -EFAULT);
4323         if (fid != NULL)
4324                 *fid = body->mbo_fid1;
4325
4326         if (inode != NULL)
4327                 rc = ll_prep_inode(inode, req, parent->i_sb, NULL);
4328 out_req:
4329         ptlrpc_req_finished(req);
4330         RETURN(rc);
4331 }
4332
4333 int ll_migrate(struct inode *parent, struct file *file, struct lmv_user_md *lum,
4334                const char *name)
4335 {
4336         struct dentry *dchild = NULL;
4337         struct inode *child_inode = NULL;
4338         struct md_op_data *op_data;
4339         struct ptlrpc_request *request = NULL;
4340         struct obd_client_handle *och = NULL;
4341         struct qstr qstr;
4342         struct mdt_body *body;
4343         __u64 data_version = 0;
4344         size_t namelen = strlen(name);
4345         int lumlen = lmv_user_md_size(lum->lum_stripe_count, lum->lum_magic);
4346         int rc;
4347         ENTRY;
4348
4349         CDEBUG(D_VFSTRACE, "migrate "DFID"/%s to MDT%04x stripe count %d\n",
4350                PFID(ll_inode2fid(parent)), name,
4351                lum->lum_stripe_offset, lum->lum_stripe_count);
4352
4353         if (lum->lum_magic != cpu_to_le32(LMV_USER_MAGIC) &&
4354             lum->lum_magic != cpu_to_le32(LMV_USER_MAGIC_SPECIFIC))
4355                 lustre_swab_lmv_user_md(lum);
4356
4357         /* Get child FID first */
4358         qstr.hash = ll_full_name_hash(file_dentry(file), name, namelen);
4359         qstr.name = name;
4360         qstr.len = namelen;
4361         dchild = d_lookup(file_dentry(file), &qstr);
4362         if (dchild) {
4363                 if (dchild->d_inode)
4364                         child_inode = igrab(dchild->d_inode);
4365                 dput(dchild);
4366         }
4367
4368         if (!child_inode) {
4369                 rc = ll_get_fid_by_name(parent, name, namelen, NULL,
4370                                         &child_inode);
4371                 if (rc)
4372                         RETURN(rc);
4373         }
4374
4375         if (!child_inode)
4376                 RETURN(-ENOENT);
4377
4378         if (!(exp_connect_flags2(ll_i2sbi(parent)->ll_md_exp) &
4379               OBD_CONNECT2_DIR_MIGRATE)) {
4380                 if (le32_to_cpu(lum->lum_stripe_count) > 1 ||
4381                     ll_dir_striped(child_inode)) {
4382                         CERROR("%s: MDT doesn't support stripe directory "
4383                                "migration!\n", ll_i2sbi(parent)->ll_fsname);
4384                         GOTO(out_iput, rc = -EOPNOTSUPP);
4385                 }
4386         }
4387
4388         /*
4389          * lfs migrate command needs to be blocked on the client
4390          * by checking the migrate FID against the FID of the
4391          * filesystem root.
4392          */
4393         if (child_inode == parent->i_sb->s_root->d_inode)
4394                 GOTO(out_iput, rc = -EINVAL);
4395
4396         op_data = ll_prep_md_op_data(NULL, parent, NULL, name, namelen,
4397                                      child_inode->i_mode, LUSTRE_OPC_ANY, NULL);
4398         if (IS_ERR(op_data))
4399                 GOTO(out_iput, rc = PTR_ERR(op_data));
4400
4401         inode_lock(child_inode);
4402         op_data->op_fid3 = *ll_inode2fid(child_inode);
4403         if (!fid_is_sane(&op_data->op_fid3)) {
4404                 CERROR("%s: migrate %s, but FID "DFID" is insane\n",
4405                        ll_i2sbi(parent)->ll_fsname, name,
4406                        PFID(&op_data->op_fid3));
4407                 GOTO(out_unlock, rc = -EINVAL);
4408         }
4409
4410         op_data->op_cli_flags |= CLI_MIGRATE | CLI_SET_MEA;
4411         op_data->op_data = lum;
4412         op_data->op_data_size = lumlen;
4413
4414 again:
4415         if (S_ISREG(child_inode->i_mode)) {
4416                 och = ll_lease_open(child_inode, NULL, FMODE_WRITE, 0);
4417                 if (IS_ERR(och)) {
4418                         rc = PTR_ERR(och);
4419                         och = NULL;
4420                         GOTO(out_unlock, rc);
4421                 }
4422
4423                 rc = ll_data_version(child_inode, &data_version,
4424                                      LL_DV_WR_FLUSH);
4425                 if (rc != 0)
4426                         GOTO(out_close, rc);
4427
4428                 op_data->op_open_handle = och->och_open_handle;
4429                 op_data->op_data_version = data_version;
4430                 op_data->op_lease_handle = och->och_lease_handle;
4431                 op_data->op_bias |= MDS_CLOSE_MIGRATE;
4432
4433                 spin_lock(&och->och_mod->mod_open_req->rq_lock);
4434                 och->och_mod->mod_open_req->rq_replay = 0;
4435                 spin_unlock(&och->och_mod->mod_open_req->rq_lock);
4436         }
4437
4438         rc = md_rename(ll_i2sbi(parent)->ll_md_exp, op_data, name, namelen,
4439                        name, namelen, &request);
4440         if (rc == 0) {
4441                 LASSERT(request != NULL);
4442                 ll_update_times(request, parent);
4443         }
4444
4445         if (rc == 0 || rc == -EAGAIN) {
4446                 body = req_capsule_server_get(&request->rq_pill, &RMF_MDT_BODY);
4447                 LASSERT(body != NULL);
4448
4449                 /* If the server does release layout lock, then we cleanup
4450                  * the client och here, otherwise release it in out_close: */
4451                 if (och && body->mbo_valid & OBD_MD_CLOSE_INTENT_EXECED) {
4452                         obd_mod_put(och->och_mod);
4453                         md_clear_open_replay_data(ll_i2sbi(parent)->ll_md_exp,
4454                                                   och);
4455                         och->och_open_handle.cookie = DEAD_HANDLE_MAGIC;
4456                         OBD_FREE_PTR(och);
4457                         och = NULL;
4458                 }
4459         }
4460
4461         if (request != NULL) {
4462                 ptlrpc_req_finished(request);
4463                 request = NULL;
4464         }
4465
4466         /* Try again if the lease has cancelled. */
4467         if (rc == -EAGAIN && S_ISREG(child_inode->i_mode))
4468                 goto again;
4469
4470 out_close:
4471         if (och)
4472                 ll_lease_close(och, child_inode, NULL);
4473         if (!rc)
4474                 clear_nlink(child_inode);
4475 out_unlock:
4476         inode_unlock(child_inode);
4477         ll_finish_md_op_data(op_data);
4478 out_iput:
4479         iput(child_inode);
4480         RETURN(rc);
4481 }
4482
4483 static int
4484 ll_file_noflock(struct file *file, int cmd, struct file_lock *file_lock)
4485 {
4486         ENTRY;
4487
4488         RETURN(-ENOSYS);
4489 }
4490
4491 /**
4492  * test if some locks matching bits and l_req_mode are acquired
4493  * - bits can be in different locks
4494  * - if found clear the common lock bits in *bits
4495  * - the bits not found, are kept in *bits
4496  * \param inode [IN]
4497  * \param bits [IN] searched lock bits [IN]
4498  * \param l_req_mode [IN] searched lock mode
4499  * \retval boolean, true iff all bits are found
4500  */
4501 int ll_have_md_lock(struct inode *inode, __u64 *bits, enum ldlm_mode l_req_mode)
4502 {
4503         struct lustre_handle lockh;
4504         union ldlm_policy_data policy;
4505         enum ldlm_mode mode = (l_req_mode == LCK_MINMODE) ?
4506                               (LCK_CR | LCK_CW | LCK_PR | LCK_PW) : l_req_mode;
4507         struct lu_fid *fid;
4508         __u64 flags;
4509         int i;
4510         ENTRY;
4511
4512         if (!inode)
4513                RETURN(0);
4514
4515         fid = &ll_i2info(inode)->lli_fid;
4516         CDEBUG(D_INFO, "trying to match res "DFID" mode %s\n", PFID(fid),
4517                ldlm_lockname[mode]);
4518
4519         flags = LDLM_FL_BLOCK_GRANTED | LDLM_FL_CBPENDING | LDLM_FL_TEST_LOCK;
4520         for (i = 0; i <= MDS_INODELOCK_MAXSHIFT && *bits != 0; i++) {
4521                 policy.l_inodebits.bits = *bits & (1 << i);
4522                 if (policy.l_inodebits.bits == 0)
4523                         continue;
4524
4525                 if (md_lock_match(ll_i2mdexp(inode), flags, fid, LDLM_IBITS,
4526                                   &policy, mode, &lockh)) {
4527                         struct ldlm_lock *lock;
4528
4529                         lock = ldlm_handle2lock(&lockh);
4530                         if (lock) {
4531                                 *bits &=
4532                                       ~(lock->l_policy_data.l_inodebits.bits);
4533                                 LDLM_LOCK_PUT(lock);
4534                         } else {
4535                                 *bits &= ~policy.l_inodebits.bits;
4536                         }
4537                 }
4538         }
4539         RETURN(*bits == 0);
4540 }
4541
4542 enum ldlm_mode ll_take_md_lock(struct inode *inode, __u64 bits,
4543                                struct lustre_handle *lockh, __u64 flags,
4544                                enum ldlm_mode mode)
4545 {
4546         union ldlm_policy_data policy = { .l_inodebits = { bits } };
4547         struct lu_fid *fid;
4548         enum ldlm_mode rc;
4549         ENTRY;
4550
4551         fid = &ll_i2info(inode)->lli_fid;
4552         CDEBUG(D_INFO, "trying to match res "DFID"\n", PFID(fid));
4553
4554         rc = md_lock_match(ll_i2mdexp(inode), LDLM_FL_BLOCK_GRANTED|flags,
4555                            fid, LDLM_IBITS, &policy, mode, lockh);
4556
4557         RETURN(rc);
4558 }
4559
4560 static int ll_inode_revalidate_fini(struct inode *inode, int rc)
4561 {
4562         /* Already unlinked. Just update nlink and return success */
4563         if (rc == -ENOENT) {
4564                 clear_nlink(inode);
4565                 /* If it is striped directory, and there is bad stripe
4566                  * Let's revalidate the dentry again, instead of returning
4567                  * error */
4568                 if (ll_dir_striped(inode))
4569                         return 0;
4570
4571                 /* This path cannot be hit for regular files unless in
4572                  * case of obscure races, so no need to to validate
4573                  * size. */
4574                 if (!S_ISREG(inode->i_mode) && !S_ISDIR(inode->i_mode))
4575                         return 0;
4576         } else if (rc != 0) {
4577                 CDEBUG_LIMIT((rc == -EACCES || rc == -EIDRM) ? D_INFO : D_ERROR,
4578                              "%s: revalidate FID "DFID" error: rc = %d\n",
4579                              ll_i2sbi(inode)->ll_fsname,
4580                              PFID(ll_inode2fid(inode)), rc);
4581         }
4582
4583         return rc;
4584 }
4585
4586 static int ll_inode_revalidate(struct dentry *dentry, enum ldlm_intent_flags op)
4587 {
4588         struct inode *inode = dentry->d_inode;
4589         struct obd_export *exp = ll_i2mdexp(inode);
4590         struct lookup_intent oit = {
4591                 .it_op = op,
4592         };
4593         struct ptlrpc_request *req = NULL;
4594         struct md_op_data *op_data;
4595         int rc = 0;
4596         ENTRY;
4597
4598         CDEBUG(D_VFSTRACE, "VFS Op:inode="DFID"(%p),name=%s\n",
4599                PFID(ll_inode2fid(inode)), inode, dentry->d_name.name);
4600
4601         /* Call getattr by fid, so do not provide name at all. */
4602         op_data = ll_prep_md_op_data(NULL, inode, inode, NULL, 0, 0,
4603                                      LUSTRE_OPC_ANY, NULL);
4604         if (IS_ERR(op_data))
4605                 RETURN(PTR_ERR(op_data));
4606
4607         rc = md_intent_lock(exp, op_data, &oit, &req, &ll_md_blocking_ast, 0);
4608         ll_finish_md_op_data(op_data);
4609         if (rc < 0) {
4610                 rc = ll_inode_revalidate_fini(inode, rc);
4611                 GOTO(out, rc);
4612         }
4613
4614         rc = ll_revalidate_it_finish(req, &oit, dentry);
4615         if (rc != 0) {
4616                 ll_intent_release(&oit);
4617                 GOTO(out, rc);
4618         }
4619
4620         /* Unlinked? Unhash dentry, so it is not picked up later by
4621          * do_lookup() -> ll_revalidate_it(). We cannot use d_drop
4622          * here to preserve get_cwd functionality on 2.6.
4623          * Bug 10503 */
4624         if (!dentry->d_inode->i_nlink) {
4625                 ll_lock_dcache(inode);
4626                 d_lustre_invalidate(dentry, 0);
4627                 ll_unlock_dcache(inode);
4628         }
4629
4630         ll_lookup_finish_locks(&oit, dentry);
4631 out:
4632         ptlrpc_req_finished(req);
4633
4634         return rc;
4635 }
4636
4637 static int ll_merge_md_attr(struct inode *inode)
4638 {
4639         struct ll_inode_info *lli = ll_i2info(inode);
4640         struct cl_attr attr = { 0 };
4641         int rc;
4642
4643         LASSERT(lli->lli_lsm_md != NULL);
4644
4645         if (!lmv_dir_striped(lli->lli_lsm_md))
4646                 RETURN(0);
4647
4648         down_read(&lli->lli_lsm_sem);
4649         rc = md_merge_attr(ll_i2mdexp(inode), ll_i2info(inode)->lli_lsm_md,
4650                            &attr, ll_md_blocking_ast);
4651         up_read(&lli->lli_lsm_sem);
4652         if (rc != 0)
4653                 RETURN(rc);
4654
4655         set_nlink(inode, attr.cat_nlink);
4656         inode->i_blocks = attr.cat_blocks;
4657         i_size_write(inode, attr.cat_size);
4658
4659         ll_i2info(inode)->lli_atime = attr.cat_atime;
4660         ll_i2info(inode)->lli_mtime = attr.cat_mtime;
4661         ll_i2info(inode)->lli_ctime = attr.cat_ctime;
4662
4663         RETURN(0);
4664 }
4665
4666 int ll_getattr_dentry(struct dentry *de, struct kstat *stat)
4667 {
4668         struct inode *inode = de->d_inode;
4669         struct ll_sb_info *sbi = ll_i2sbi(inode);
4670         struct ll_inode_info *lli = ll_i2info(inode);
4671         int rc;
4672
4673         ll_stats_ops_tally(sbi, LPROC_LL_GETATTR, 1);
4674
4675         rc = ll_inode_revalidate(de, IT_GETATTR);
4676         if (rc < 0)
4677                 RETURN(rc);
4678
4679         if (S_ISREG(inode->i_mode)) {
4680                 bool cached;
4681
4682                 rc = pcc_inode_getattr(inode, &cached);
4683                 if (cached && rc < 0)
4684                         RETURN(rc);
4685
4686                 /* In case of restore, the MDT has the right size and has
4687                  * already send it back without granting the layout lock,
4688                  * inode is up-to-date so glimpse is useless.
4689                  * Also to glimpse we need the layout, in case of a running
4690                  * restore the MDT holds the layout lock so the glimpse will
4691                  * block up to the end of restore (getattr will block)
4692                  */
4693                 if (!cached && !ll_file_test_flag(lli, LLIF_FILE_RESTORING)) {
4694                         rc = ll_glimpse_size(inode);
4695                         if (rc < 0)
4696                                 RETURN(rc);
4697                 }
4698         } else {
4699                 /* If object isn't regular a file then don't validate size. */
4700                 if (ll_dir_striped(inode)) {
4701                         rc = ll_merge_md_attr(inode);
4702                         if (rc < 0)
4703                                 RETURN(rc);
4704                 }
4705
4706                 inode->i_atime.tv_sec = lli->lli_atime;
4707                 inode->i_mtime.tv_sec = lli->lli_mtime;
4708                 inode->i_ctime.tv_sec = lli->lli_ctime;
4709         }
4710
4711         OBD_FAIL_TIMEOUT(OBD_FAIL_GETATTR_DELAY, 30);
4712
4713         if (ll_need_32bit_api(sbi)) {
4714                 stat->ino = cl_fid_build_ino(&lli->lli_fid, 1);
4715                 stat->dev = ll_compat_encode_dev(inode->i_sb->s_dev);
4716                 stat->rdev = ll_compat_encode_dev(inode->i_rdev);
4717         } else {
4718                 stat->ino = inode->i_ino;
4719                 stat->dev = inode->i_sb->s_dev;
4720                 stat->rdev = inode->i_rdev;
4721         }
4722
4723         stat->mode = inode->i_mode;
4724         stat->uid = inode->i_uid;
4725         stat->gid = inode->i_gid;
4726         stat->atime = inode->i_atime;
4727         stat->mtime = inode->i_mtime;
4728         stat->ctime = inode->i_ctime;
4729         stat->blksize = sbi->ll_stat_blksize ?: 1 << inode->i_blkbits;
4730
4731         stat->nlink = inode->i_nlink;
4732         stat->size = i_size_read(inode);
4733         stat->blocks = inode->i_blocks;
4734
4735         return 0;
4736 }
4737
4738 #ifdef HAVE_INODEOPS_ENHANCED_GETATTR
4739 int ll_getattr(const struct path *path, struct kstat *stat,
4740                u32 request_mask, unsigned int flags)
4741 {
4742         struct dentry *de = path->dentry;
4743 #else
4744 int ll_getattr(struct vfsmount *mnt, struct dentry *de, struct kstat *stat)
4745 {
4746 #endif
4747         return ll_getattr_dentry(de, stat);
4748 }
4749
4750 static int ll_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
4751                      __u64 start, __u64 len)
4752 {
4753         int             rc;
4754         size_t          num_bytes;
4755         struct fiemap   *fiemap;
4756         unsigned int    extent_count = fieinfo->fi_extents_max;
4757
4758         num_bytes = sizeof(*fiemap) + (extent_count *
4759                                        sizeof(struct fiemap_extent));
4760         OBD_ALLOC_LARGE(fiemap, num_bytes);
4761
4762         if (fiemap == NULL)
4763                 RETURN(-ENOMEM);
4764
4765         fiemap->fm_flags = fieinfo->fi_flags;
4766         fiemap->fm_extent_count = fieinfo->fi_extents_max;
4767         fiemap->fm_start = start;
4768         fiemap->fm_length = len;
4769         if (extent_count > 0 &&
4770             copy_from_user(&fiemap->fm_extents[0], fieinfo->fi_extents_start,
4771                            sizeof(struct fiemap_extent)) != 0)
4772                 GOTO(out, rc = -EFAULT);
4773
4774         rc = ll_do_fiemap(inode, fiemap, num_bytes);
4775
4776         fieinfo->fi_flags = fiemap->fm_flags;
4777         fieinfo->fi_extents_mapped = fiemap->fm_mapped_extents;
4778         if (extent_count > 0 &&
4779             copy_to_user(fieinfo->fi_extents_start, &fiemap->fm_extents[0],
4780                          fiemap->fm_mapped_extents *
4781                          sizeof(struct fiemap_extent)) != 0)
4782                 GOTO(out, rc = -EFAULT);
4783 out:
4784         OBD_FREE_LARGE(fiemap, num_bytes);
4785         return rc;
4786 }
4787
4788 struct posix_acl *ll_get_acl(struct inode *inode, int type)
4789 {
4790         struct ll_inode_info *lli = ll_i2info(inode);
4791         struct posix_acl *acl = NULL;
4792         ENTRY;
4793
4794         spin_lock(&lli->lli_lock);
4795         /* VFS' acl_permission_check->check_acl will release the refcount */
4796         acl = posix_acl_dup(lli->lli_posix_acl);
4797         spin_unlock(&lli->lli_lock);
4798
4799         RETURN(acl);
4800 }
4801
4802 #ifdef HAVE_IOP_SET_ACL
4803 #ifdef CONFIG_FS_POSIX_ACL
4804 int ll_set_acl(struct inode *inode, struct posix_acl *acl, int type)
4805 {
4806         struct ll_sb_info *sbi = ll_i2sbi(inode);
4807         struct ptlrpc_request *req = NULL;
4808         const char *name = NULL;
4809         char *value = NULL;
4810         size_t value_size = 0;
4811         int rc = 0;
4812         ENTRY;
4813
4814         switch (type) {
4815         case ACL_TYPE_ACCESS:
4816                 name = XATTR_NAME_POSIX_ACL_ACCESS;
4817                 if (acl)
4818                         rc = posix_acl_update_mode(inode, &inode->i_mode, &acl);
4819                 break;
4820
4821         case ACL_TYPE_DEFAULT:
4822                 name = XATTR_NAME_POSIX_ACL_DEFAULT;
4823                 if (!S_ISDIR(inode->i_mode))
4824                         rc = acl ? -EACCES : 0;
4825                 break;
4826
4827         default:
4828                 rc = -EINVAL;
4829                 break;
4830         }
4831         if (rc)
4832                 return rc;
4833
4834         if (acl) {
4835                 value_size = posix_acl_xattr_size(acl->a_count);
4836                 value = kmalloc(value_size, GFP_NOFS);
4837                 if (value == NULL)
4838                         GOTO(out, rc = -ENOMEM);
4839
4840                 rc = posix_acl_to_xattr(&init_user_ns, acl, value, value_size);
4841                 if (rc < 0)
4842                         GOTO(out_value, rc);
4843         }
4844
4845         rc = md_setxattr(sbi->ll_md_exp, ll_inode2fid(inode),
4846                          value ? OBD_MD_FLXATTR : OBD_MD_FLXATTRRM,
4847                          name, value, value_size, 0, 0, &req);
4848
4849         ptlrpc_req_finished(req);
4850 out_value:
4851         kfree(value);
4852 out:
4853         if (rc)
4854                 forget_cached_acl(inode, type);
4855         else
4856                 set_cached_acl(inode, type, acl);
4857         RETURN(rc);
4858 }
4859 #endif /* CONFIG_FS_POSIX_ACL */
4860 #endif /* HAVE_IOP_SET_ACL */
4861
4862 #ifndef HAVE_GENERIC_PERMISSION_2ARGS
4863 static int
4864 # ifdef HAVE_GENERIC_PERMISSION_4ARGS
4865 ll_check_acl(struct inode *inode, int mask, unsigned int flags)
4866 # else
4867 ll_check_acl(struct inode *inode, int mask)
4868 # endif
4869 {
4870 # ifdef CONFIG_FS_POSIX_ACL
4871         struct posix_acl *acl;
4872         int rc;
4873         ENTRY;
4874
4875 #  ifdef HAVE_GENERIC_PERMISSION_4ARGS
4876         if (flags & IPERM_FLAG_RCU)
4877                 return -ECHILD;
4878 #  endif
4879         acl = ll_get_acl(inode, ACL_TYPE_ACCESS);
4880
4881         if (!acl)
4882                 RETURN(-EAGAIN);
4883
4884         rc = posix_acl_permission(inode, acl, mask);
4885         posix_acl_release(acl);
4886
4887         RETURN(rc);
4888 # else /* !CONFIG_FS_POSIX_ACL */
4889         return -EAGAIN;
4890 # endif /* CONFIG_FS_POSIX_ACL */
4891 }
4892 #endif /* HAVE_GENERIC_PERMISSION_2ARGS */
4893
4894 #ifdef HAVE_GENERIC_PERMISSION_4ARGS
4895 int ll_inode_permission(struct inode *inode, int mask, unsigned int flags)
4896 #else
4897 # ifdef HAVE_INODE_PERMISION_2ARGS
4898 int ll_inode_permission(struct inode *inode, int mask)
4899 # else
4900 int ll_inode_permission(struct inode *inode, int mask, struct nameidata *nd)
4901 # endif
4902 #endif
4903 {
4904         int rc = 0;
4905         struct ll_sb_info *sbi;
4906         struct root_squash_info *squash;
4907         struct cred *cred = NULL;
4908         const struct cred *old_cred = NULL;
4909         cfs_cap_t cap;
4910         bool squash_id = false;
4911         ENTRY;
4912
4913 #ifdef MAY_NOT_BLOCK
4914         if (mask & MAY_NOT_BLOCK)
4915                 return -ECHILD;
4916 #elif defined(HAVE_GENERIC_PERMISSION_4ARGS)
4917         if (flags & IPERM_FLAG_RCU)
4918                 return -ECHILD;
4919 #endif
4920
4921        /* as root inode are NOT getting validated in lookup operation,
4922         * need to do it before permission check. */
4923
4924         if (inode == inode->i_sb->s_root->d_inode) {
4925                 rc = ll_inode_revalidate(inode->i_sb->s_root, IT_LOOKUP);
4926                 if (rc)
4927                         RETURN(rc);
4928         }
4929
4930         CDEBUG(D_VFSTRACE, "VFS Op:inode="DFID"(%p), inode mode %x mask %o\n",
4931                PFID(ll_inode2fid(inode)), inode, inode->i_mode, mask);
4932
4933         /* squash fsuid/fsgid if needed */
4934         sbi = ll_i2sbi(inode);
4935         squash = &sbi->ll_squash;
4936         if (unlikely(squash->rsi_uid != 0 &&
4937                      uid_eq(current_fsuid(), GLOBAL_ROOT_UID) &&
4938                      !(sbi->ll_flags & LL_SBI_NOROOTSQUASH))) {
4939                         squash_id = true;
4940         }
4941         if (squash_id) {
4942                 CDEBUG(D_OTHER, "squash creds (%d:%d)=>(%d:%d)\n",
4943                        __kuid_val(current_fsuid()), __kgid_val(current_fsgid()),
4944                        squash->rsi_uid, squash->rsi_gid);
4945
4946                 /* update current process's credentials
4947                  * and FS capability */
4948                 cred = prepare_creds();
4949                 if (cred == NULL)
4950                         RETURN(-ENOMEM);
4951
4952                 cred->fsuid = make_kuid(&init_user_ns, squash->rsi_uid);
4953                 cred->fsgid = make_kgid(&init_user_ns, squash->rsi_gid);
4954                 for (cap = 0; cap < sizeof(cfs_cap_t) * 8; cap++) {
4955                         if ((1 << cap) & CFS_CAP_FS_MASK)
4956                                 cap_lower(cred->cap_effective, cap);
4957                 }
4958                 old_cred = override_creds(cred);
4959         }
4960
4961         ll_stats_ops_tally(sbi, LPROC_LL_INODE_PERM, 1);
4962         rc = ll_generic_permission(inode, mask, flags, ll_check_acl);
4963         /* restore current process's credentials and FS capability */
4964         if (squash_id) {
4965                 revert_creds(old_cred);
4966                 put_cred(cred);
4967         }
4968
4969         RETURN(rc);
4970 }
4971
4972 /* -o localflock - only provides locally consistent flock locks */
4973 struct file_operations ll_file_operations = {
4974 #ifdef HAVE_FILE_OPERATIONS_READ_WRITE_ITER
4975 # ifdef HAVE_SYNC_READ_WRITE
4976         .read           = new_sync_read,
4977         .write          = new_sync_write,
4978 # endif
4979         .read_iter      = ll_file_read_iter,
4980         .write_iter     = ll_file_write_iter,
4981 #else /* !HAVE_FILE_OPERATIONS_READ_WRITE_ITER */
4982         .read           = ll_file_read,
4983         .aio_read       = ll_file_aio_read,
4984         .write          = ll_file_write,
4985         .aio_write      = ll_file_aio_write,
4986 #endif /* HAVE_FILE_OPERATIONS_READ_WRITE_ITER */
4987         .unlocked_ioctl = ll_file_ioctl,
4988         .open           = ll_file_open,
4989         .release        = ll_file_release,
4990         .mmap           = ll_file_mmap,
4991         .llseek         = ll_file_seek,
4992         .splice_read    = ll_file_splice_read,
4993         .fsync          = ll_fsync,
4994         .flush          = ll_flush
4995 };
4996
4997 struct file_operations ll_file_operations_flock = {
4998 #ifdef HAVE_FILE_OPERATIONS_READ_WRITE_ITER
4999 # ifdef HAVE_SYNC_READ_WRITE
5000         .read           = new_sync_read,
5001         .write          = new_sync_write,
5002 # endif /* HAVE_SYNC_READ_WRITE */
5003         .read_iter      = ll_file_read_iter,
5004         .write_iter     = ll_file_write_iter,
5005 #else /* !HAVE_FILE_OPERATIONS_READ_WRITE_ITER */
5006         .read           = ll_file_read,
5007         .aio_read       = ll_file_aio_read,
5008         .write          = ll_file_write,
5009         .aio_write      = ll_file_aio_write,
5010 #endif /* HAVE_FILE_OPERATIONS_READ_WRITE_ITER */
5011         .unlocked_ioctl = ll_file_ioctl,
5012         .open           = ll_file_open,
5013         .release        = ll_file_release,
5014         .mmap           = ll_file_mmap,
5015         .llseek         = ll_file_seek,
5016         .splice_read    = ll_file_splice_read,
5017         .fsync          = ll_fsync,
5018         .flush          = ll_flush,
5019         .flock          = ll_file_flock,
5020         .lock           = ll_file_flock
5021 };
5022
5023 /* These are for -o noflock - to return ENOSYS on flock calls */
5024 struct file_operations ll_file_operations_noflock = {
5025 #ifdef HAVE_FILE_OPERATIONS_READ_WRITE_ITER
5026 # ifdef HAVE_SYNC_READ_WRITE
5027         .read           = new_sync_read,
5028         .write          = new_sync_write,
5029 # endif /* HAVE_SYNC_READ_WRITE */
5030         .read_iter      = ll_file_read_iter,
5031         .write_iter     = ll_file_write_iter,
5032 #else /* !HAVE_FILE_OPERATIONS_READ_WRITE_ITER */
5033         .read           = ll_file_read,
5034         .aio_read       = ll_file_aio_read,
5035         .write          = ll_file_write,
5036         .aio_write      = ll_file_aio_write,
5037 #endif /* HAVE_FILE_OPERATIONS_READ_WRITE_ITER */
5038         .unlocked_ioctl = ll_file_ioctl,
5039         .open           = ll_file_open,
5040         .release        = ll_file_release,
5041         .mmap           = ll_file_mmap,
5042         .llseek         = ll_file_seek,
5043         .splice_read    = ll_file_splice_read,
5044         .fsync          = ll_fsync,
5045         .flush          = ll_flush,
5046         .flock          = ll_file_noflock,
5047         .lock           = ll_file_noflock
5048 };
5049
5050 struct inode_operations ll_file_inode_operations = {
5051         .setattr        = ll_setattr,
5052         .getattr        = ll_getattr,
5053         .permission     = ll_inode_permission,
5054 #ifdef HAVE_IOP_XATTR
5055         .setxattr       = ll_setxattr,
5056         .getxattr       = ll_getxattr,
5057         .removexattr    = ll_removexattr,
5058 #endif
5059         .listxattr      = ll_listxattr,
5060         .fiemap         = ll_fiemap,
5061 #ifdef HAVE_IOP_GET_ACL
5062         .get_acl        = ll_get_acl,
5063 #endif
5064 #ifdef HAVE_IOP_SET_ACL
5065         .set_acl        = ll_set_acl,
5066 #endif
5067 };
5068
5069 int ll_layout_conf(struct inode *inode, const struct cl_object_conf *conf)
5070 {
5071         struct ll_inode_info *lli = ll_i2info(inode);
5072         struct cl_object *obj = lli->lli_clob;
5073         struct lu_env *env;
5074         int rc;
5075         __u16 refcheck;
5076         ENTRY;
5077
5078         if (obj == NULL)
5079                 RETURN(0);
5080
5081         env = cl_env_get(&refcheck);
5082         if (IS_ERR(env))
5083                 RETURN(PTR_ERR(env));
5084
5085         rc = cl_conf_set(env, lli->lli_clob, conf);
5086         if (rc < 0)
5087                 GOTO(out, rc);
5088
5089         if (conf->coc_opc == OBJECT_CONF_SET) {
5090                 struct ldlm_lock *lock = conf->coc_lock;
5091                 struct cl_layout cl = {
5092                         .cl_layout_gen = 0,
5093                 };
5094
5095                 LASSERT(lock != NULL);
5096                 LASSERT(ldlm_has_layout(lock));
5097
5098                 /* it can only be allowed to match after layout is
5099                  * applied to inode otherwise false layout would be
5100                  * seen. Applying layout shoud happen before dropping
5101                  * the intent lock. */
5102                 ldlm_lock_allow_match(lock);
5103
5104                 rc = cl_object_layout_get(env, obj, &cl);
5105                 if (rc < 0)
5106                         GOTO(out, rc);
5107
5108                 CDEBUG(D_VFSTRACE,
5109                        DFID": layout version change: %u -> %u\n",
5110                        PFID(&lli->lli_fid), ll_layout_version_get(lli),
5111                        cl.cl_layout_gen);
5112                 ll_layout_version_set(lli, cl.cl_layout_gen);
5113         }
5114
5115 out:
5116         cl_env_put(env, &refcheck);
5117
5118         RETURN(rc);
5119 }
5120
5121 /* Fetch layout from MDT with getxattr request, if it's not ready yet */
5122 static int ll_layout_fetch(struct inode *inode, struct ldlm_lock *lock)
5123
5124 {
5125         struct ll_sb_info *sbi = ll_i2sbi(inode);
5126         struct ptlrpc_request *req;
5127         void *lvbdata;
5128         void *lmm;
5129         int lmmsize;
5130         int rc;
5131         ENTRY;
5132
5133         CDEBUG(D_INODE, DFID" LVB_READY=%d l_lvb_data=%p l_lvb_len=%d\n",
5134                PFID(ll_inode2fid(inode)), ldlm_is_lvb_ready(lock),
5135                lock->l_lvb_data, lock->l_lvb_len);
5136
5137         if (lock->l_lvb_data != NULL)
5138                 RETURN(0);
5139
5140         /* if layout lock was granted right away, the layout is returned
5141          * within DLM_LVB of dlm reply; otherwise if the lock was ever
5142          * blocked and then granted via completion ast, we have to fetch
5143          * layout here. Please note that we can't use the LVB buffer in
5144          * completion AST because it doesn't have a large enough buffer */
5145         rc = ll_get_default_mdsize(sbi, &lmmsize);
5146         if (rc < 0)
5147                 RETURN(rc);
5148
5149         rc = md_getxattr(sbi->ll_md_exp, ll_inode2fid(inode), OBD_MD_FLXATTR,
5150                          XATTR_NAME_LOV, lmmsize, &req);
5151         if (rc < 0) {
5152                 if (rc == -ENODATA)
5153                         GOTO(out, rc = 0); /* empty layout */
5154                 else
5155                         RETURN(rc);
5156         }
5157
5158         lmmsize = rc;
5159         rc = 0;
5160         if (lmmsize == 0) /* empty layout */
5161                 GOTO(out, rc = 0);
5162
5163         lmm = req_capsule_server_sized_get(&req->rq_pill, &RMF_EADATA, lmmsize);
5164         if (lmm == NULL)
5165                 GOTO(out, rc = -EFAULT);
5166
5167         OBD_ALLOC_LARGE(lvbdata, lmmsize);
5168         if (lvbdata == NULL)
5169                 GOTO(out, rc = -ENOMEM);
5170
5171         memcpy(lvbdata, lmm, lmmsize);
5172         lock_res_and_lock(lock);
5173         if (unlikely(lock->l_lvb_data == NULL)) {
5174                 lock->l_lvb_type = LVB_T_LAYOUT;
5175                 lock->l_lvb_data = lvbdata;
5176                 lock->l_lvb_len = lmmsize;
5177                 lvbdata = NULL;
5178         }
5179         unlock_res_and_lock(lock);
5180
5181         if (lvbdata)
5182                 OBD_FREE_LARGE(lvbdata, lmmsize);
5183
5184         EXIT;
5185
5186 out:
5187         ptlrpc_req_finished(req);
5188         return rc;
5189 }
5190
5191 /**
5192  * Apply the layout to the inode. Layout lock is held and will be released
5193  * in this function.
5194  */
5195 static int ll_layout_lock_set(struct lustre_handle *lockh, enum ldlm_mode mode,
5196                               struct inode *inode)
5197 {
5198         struct ll_inode_info *lli = ll_i2info(inode);
5199         struct ll_sb_info    *sbi = ll_i2sbi(inode);
5200         struct ldlm_lock *lock;
5201         struct cl_object_conf conf;
5202         int rc = 0;
5203         bool lvb_ready;
5204         bool wait_layout = false;
5205         ENTRY;
5206
5207         LASSERT(lustre_handle_is_used(lockh));
5208
5209         lock = ldlm_handle2lock(lockh);
5210         LASSERT(lock != NULL);
5211         LASSERT(ldlm_has_layout(lock));
5212
5213         LDLM_DEBUG(lock, "file "DFID"(%p) being reconfigured",
5214                    PFID(&lli->lli_fid), inode);
5215
5216         /* in case this is a caching lock and reinstate with new inode */
5217         md_set_lock_data(sbi->ll_md_exp, lockh, inode, NULL);
5218
5219         lock_res_and_lock(lock);
5220         lvb_ready = ldlm_is_lvb_ready(lock);
5221         unlock_res_and_lock(lock);
5222
5223         /* checking lvb_ready is racy but this is okay. The worst case is
5224          * that multi processes may configure the file on the same time. */
5225         if (lvb_ready)
5226                 GOTO(out, rc = 0);
5227
5228         rc = ll_layout_fetch(inode, lock);
5229         if (rc < 0)
5230                 GOTO(out, rc);
5231
5232         /* for layout lock, lmm is stored in lock's lvb.
5233          * lvb_data is immutable if the lock is held so it's safe to access it
5234          * without res lock.
5235          *
5236          * set layout to file. Unlikely this will fail as old layout was
5237          * surely eliminated */
5238         memset(&conf, 0, sizeof conf);
5239         conf.coc_opc = OBJECT_CONF_SET;
5240         conf.coc_inode = inode;
5241         conf.coc_lock = lock;
5242         conf.u.coc_layout.lb_buf = lock->l_lvb_data;
5243         conf.u.coc_layout.lb_len = lock->l_lvb_len;
5244         rc = ll_layout_conf(inode, &conf);
5245
5246         /* refresh layout failed, need to wait */
5247         wait_layout = rc == -EBUSY;
5248         EXIT;
5249 out:
5250         LDLM_LOCK_PUT(lock);
5251         ldlm_lock_decref(lockh, mode);
5252
5253         /* wait for IO to complete if it's still being used. */
5254         if (wait_layout) {
5255                 CDEBUG(D_INODE, "%s: "DFID"(%p) wait for layout reconf\n",
5256                        sbi->ll_fsname, PFID(&lli->lli_fid), inode);
5257
5258                 memset(&conf, 0, sizeof conf);
5259                 conf.coc_opc = OBJECT_CONF_WAIT;
5260                 conf.coc_inode = inode;
5261                 rc = ll_layout_conf(inode, &conf);
5262                 if (rc == 0)
5263                         rc = -EAGAIN;
5264
5265                 CDEBUG(D_INODE, "%s file="DFID" waiting layout return: %d\n",
5266                        sbi->ll_fsname, PFID(&lli->lli_fid), rc);
5267         }
5268         RETURN(rc);
5269 }
5270
5271 /**
5272  * Issue layout intent RPC to MDS.
5273  * \param inode [in]    file inode
5274  * \param intent [in]   layout intent
5275  *
5276  * \retval 0    on success
5277  * \retval < 0  error code
5278  */
5279 static int ll_layout_intent(struct inode *inode, struct layout_intent *intent)
5280 {
5281         struct ll_inode_info  *lli = ll_i2info(inode);
5282         struct ll_sb_info     *sbi = ll_i2sbi(inode);
5283         struct md_op_data     *op_data;
5284         struct lookup_intent it;
5285         struct ptlrpc_request *req;
5286         int rc;
5287         ENTRY;
5288
5289         op_data = ll_prep_md_op_data(NULL, inode, inode, NULL,
5290                                      0, 0, LUSTRE_OPC_ANY, NULL);
5291         if (IS_ERR(op_data))
5292                 RETURN(PTR_ERR(op_data));
5293
5294         op_data->op_data = intent;
5295         op_data->op_data_size = sizeof(*intent);
5296
5297         memset(&it, 0, sizeof(it));
5298         it.it_op = IT_LAYOUT;
5299         if (intent->li_opc == LAYOUT_INTENT_WRITE ||
5300             intent->li_opc == LAYOUT_INTENT_TRUNC)
5301                 it.it_flags = FMODE_WRITE;
5302
5303         LDLM_DEBUG_NOLOCK("%s: requeue layout lock for file "DFID"(%p)",
5304                           sbi->ll_fsname, PFID(&lli->lli_fid), inode);
5305
5306         rc = md_intent_lock(sbi->ll_md_exp, op_data, &it, &req,
5307                             &ll_md_blocking_ast, 0);
5308         if (it.it_request != NULL)
5309                 ptlrpc_req_finished(it.it_request);
5310         it.it_request = NULL;
5311
5312         ll_finish_md_op_data(op_data);
5313
5314         /* set lock data in case this is a new lock */
5315         if (!rc)
5316                 ll_set_lock_data(sbi->ll_md_exp, inode, &it, NULL);
5317
5318         ll_intent_drop_lock(&it);
5319
5320         RETURN(rc);
5321 }
5322
5323 /**
5324  * This function checks if there exists a LAYOUT lock on the client side,
5325  * or enqueues it if it doesn't have one in cache.
5326  *
5327  * This function will not hold layout lock so it may be revoked any time after
5328  * this function returns. Any operations depend on layout should be redone
5329  * in that case.
5330  *
5331  * This function should be called before lov_io_init() to get an uptodate
5332  * layout version, the caller should save the version number and after IO
5333  * is finished, this function should be called again to verify that layout
5334  * is not changed during IO time.
5335  */
5336 int ll_layout_refresh(struct inode *inode, __u32 *gen)
5337 {
5338         struct ll_inode_info    *lli = ll_i2info(inode);
5339         struct ll_sb_info       *sbi = ll_i2sbi(inode);
5340         struct lustre_handle lockh;
5341         struct layout_intent intent = {
5342                 .li_opc = LAYOUT_INTENT_ACCESS,
5343         };
5344         enum ldlm_mode mode;
5345         int rc;
5346         ENTRY;
5347
5348         *gen = ll_layout_version_get(lli);
5349         if (!(sbi->ll_flags & LL_SBI_LAYOUT_LOCK) || *gen != CL_LAYOUT_GEN_NONE)
5350                 RETURN(0);
5351
5352         /* sanity checks */
5353         LASSERT(fid_is_sane(ll_inode2fid(inode)));
5354         LASSERT(S_ISREG(inode->i_mode));
5355
5356         /* take layout lock mutex to enqueue layout lock exclusively. */
5357         mutex_lock(&lli->lli_layout_mutex);
5358
5359         while (1) {
5360                 /* mostly layout lock is caching on the local side, so try to
5361                  * match it before grabbing layout lock mutex. */
5362                 mode = ll_take_md_lock(inode, MDS_INODELOCK_LAYOUT, &lockh, 0,
5363                                        LCK_CR | LCK_CW | LCK_PR | LCK_PW);
5364                 if (mode != 0) { /* hit cached lock */
5365                         rc = ll_layout_lock_set(&lockh, mode, inode);
5366                         if (rc == -EAGAIN)
5367                                 continue;
5368                         break;
5369                 }
5370
5371                 rc = ll_layout_intent(inode, &intent);
5372                 if (rc != 0)
5373                         break;
5374         }
5375
5376         if (rc == 0)
5377                 *gen = ll_layout_version_get(lli);
5378         mutex_unlock(&lli->lli_layout_mutex);
5379
5380         RETURN(rc);
5381 }
5382
5383 /**
5384  * Issue layout intent RPC indicating where in a file an IO is about to write.
5385  *
5386  * \param[in] inode     file inode.
5387  * \param[in] ext       write range with start offset of fille in bytes where
5388  *                      an IO is about to write, and exclusive end offset in
5389  *                      bytes.
5390  *
5391  * \retval 0    on success
5392  * \retval < 0  error code
5393  */
5394 int ll_layout_write_intent(struct inode *inode, enum layout_intent_opc opc,
5395                            struct lu_extent *ext)
5396 {
5397         struct layout_intent intent = {
5398                 .li_opc = opc,
5399                 .li_extent.e_start = ext->e_start,
5400                 .li_extent.e_end = ext->e_end,
5401         };
5402         int rc;
5403         ENTRY;
5404
5405         rc = ll_layout_intent(inode, &intent);
5406
5407         RETURN(rc);
5408 }
5409
5410 /**
5411  *  This function send a restore request to the MDT
5412  */
5413 int ll_layout_restore(struct inode *inode, loff_t offset, __u64 length)
5414 {
5415         struct hsm_user_request *hur;
5416         int                      len, rc;
5417         ENTRY;
5418
5419         len = sizeof(struct hsm_user_request) +
5420               sizeof(struct hsm_user_item);
5421         OBD_ALLOC(hur, len);
5422         if (hur == NULL)
5423                 RETURN(-ENOMEM);
5424
5425         hur->hur_request.hr_action = HUA_RESTORE;
5426         hur->hur_request.hr_archive_id = 0;
5427         hur->hur_request.hr_flags = 0;
5428         memcpy(&hur->hur_user_item[0].hui_fid, &ll_i2info(inode)->lli_fid,
5429                sizeof(hur->hur_user_item[0].hui_fid));
5430         hur->hur_user_item[0].hui_extent.offset = offset;
5431         hur->hur_user_item[0].hui_extent.length = length;
5432         hur->hur_request.hr_itemcount = 1;
5433         rc = obd_iocontrol(LL_IOC_HSM_REQUEST, ll_i2sbi(inode)->ll_md_exp,
5434                            len, hur, NULL);
5435         OBD_FREE(hur, len);
5436         RETURN(rc);
5437 }