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