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