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