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