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