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