Whamcloud - gitweb
LU-5971 llite: reorganize variable and data structures
[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.sun.com/software/products/lustre/docs/GPLv2.pdf
19  *
20  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
21  * CA 95054 USA or visit www.sun.com if you need additional information or
22  * have any questions.
23  *
24  * GPL HEADER END
25  */
26 /*
27  * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2011, 2014, Intel Corporation.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * lustre/llite/file.c
37  *
38  * Author: Peter Braam <braam@clusterfs.com>
39  * Author: Phil Schwan <phil@clusterfs.com>
40  * Author: Andreas Dilger <adilger@clusterfs.com>
41  */
42
43 #define DEBUG_SUBSYSTEM S_LLITE
44 #include <lustre_dlm.h>
45 #include <linux/pagemap.h>
46 #include <linux/file.h>
47 #include <linux/sched.h>
48 #include <lustre/ll_fiemap.h>
49 #include <lustre_ioctl.h>
50
51 #include "cl_object.h"
52
53 #include "llite_internal.h"
54 #include "vvp_internal.h"
55
56 static int
57 ll_put_grouplock(struct inode *inode, struct file *file, unsigned long arg);
58
59 static int ll_lease_close(struct obd_client_handle *och, struct inode *inode,
60                           bool *lease_broken);
61
62 static enum llioc_iter
63 ll_iocontrol_call(struct inode *inode, struct file *file,
64                   unsigned int cmd, unsigned long arg, int *rcp);
65
66 static struct ll_file_data *ll_file_data_get(void)
67 {
68         struct ll_file_data *fd;
69
70         OBD_SLAB_ALLOC_PTR_GFP(fd, ll_file_data_slab, GFP_NOFS);
71         if (fd == NULL)
72                 return NULL;
73
74         fd->fd_write_failed = false;
75
76         return fd;
77 }
78
79 static void ll_file_data_put(struct ll_file_data *fd)
80 {
81         if (fd != NULL)
82                 OBD_SLAB_FREE_PTR(fd, ll_file_data_slab);
83 }
84
85 void ll_pack_inode2opdata(struct inode *inode, struct md_op_data *op_data,
86                           struct lustre_handle *fh)
87 {
88         op_data->op_fid1 = ll_i2info(inode)->lli_fid;
89         op_data->op_attr.ia_mode = inode->i_mode;
90         op_data->op_attr.ia_atime = inode->i_atime;
91         op_data->op_attr.ia_mtime = inode->i_mtime;
92         op_data->op_attr.ia_ctime = inode->i_ctime;
93         op_data->op_attr.ia_size = i_size_read(inode);
94         op_data->op_attr_blocks = inode->i_blocks;
95         op_data->op_attr_flags = ll_inode_to_ext_flags(inode->i_flags);
96         if (fh)
97                 op_data->op_handle = *fh;
98         op_data->op_capa1 = ll_mdscapa_get(inode);
99
100         if (LLIF_DATA_MODIFIED & ll_i2info(inode)->lli_flags)
101                 op_data->op_bias |= MDS_DATA_MODIFIED;
102 }
103
104 /**
105  * Packs all the attributes into @op_data for the CLOSE rpc.
106  */
107 static void ll_prepare_close(struct inode *inode, struct md_op_data *op_data,
108                              struct obd_client_handle *och)
109 {
110         ENTRY;
111
112         op_data->op_attr.ia_valid = ATTR_MODE | ATTR_ATIME | ATTR_ATIME_SET |
113                                         ATTR_MTIME | ATTR_MTIME_SET |
114                                         ATTR_CTIME | ATTR_CTIME_SET;
115
116         if (!(och->och_flags & FMODE_WRITE))
117                 goto out;
118
119         op_data->op_attr.ia_valid |= ATTR_SIZE | ATTR_BLOCKS;
120
121 out:
122         ll_pack_inode2opdata(inode, op_data, &och->och_fh);
123         ll_prep_md_op_data(op_data, inode, NULL, NULL,
124                            0, 0, LUSTRE_OPC_ANY, NULL);
125         EXIT;
126 }
127
128 static int ll_close_inode_openhandle(struct obd_export *md_exp,
129                                      struct inode *inode,
130                                      struct obd_client_handle *och,
131                                      const __u64 *data_version)
132 {
133         struct obd_export *exp = ll_i2mdexp(inode);
134         struct md_op_data *op_data;
135         struct ptlrpc_request *req = NULL;
136         struct obd_device *obd = class_exp2obd(exp);
137         int rc;
138         ENTRY;
139
140         if (obd == NULL) {
141                 /*
142                  * XXX: in case of LMV, is this correct to access
143                  * ->exp_handle?
144                  */
145                 CERROR("Invalid MDC connection handle "LPX64"\n",
146                        ll_i2mdexp(inode)->exp_handle.h_cookie);
147                 GOTO(out, rc = 0);
148         }
149
150         OBD_ALLOC_PTR(op_data);
151         if (op_data == NULL)
152                 GOTO(out, rc = -ENOMEM); // XXX We leak openhandle and request here.
153
154         ll_prepare_close(inode, op_data, och);
155         if (data_version != NULL) {
156                 /* Pass in data_version implies release. */
157                 op_data->op_bias |= MDS_HSM_RELEASE;
158                 op_data->op_data_version = *data_version;
159                 op_data->op_lease_handle = och->och_lease_handle;
160                 op_data->op_attr.ia_valid |= ATTR_SIZE | ATTR_BLOCKS;
161         }
162
163         rc = md_close(md_exp, op_data, och->och_mod, &req);
164         if (rc) {
165                 CERROR("%s: inode "DFID" mdc close failed: rc = %d\n",
166                        ll_i2mdexp(inode)->exp_obd->obd_name,
167                        PFID(ll_inode2fid(inode)), rc);
168         }
169
170         /* DATA_MODIFIED flag was successfully sent on close, cancel data
171          * modification flag. */
172         if (rc == 0 && (op_data->op_bias & MDS_DATA_MODIFIED)) {
173                 struct ll_inode_info *lli = ll_i2info(inode);
174
175                 spin_lock(&lli->lli_lock);
176                 lli->lli_flags &= ~LLIF_DATA_MODIFIED;
177                 spin_unlock(&lli->lli_lock);
178         }
179
180         if (rc == 0 && op_data->op_bias & MDS_HSM_RELEASE) {
181                 struct mdt_body *body;
182                 body = req_capsule_server_get(&req->rq_pill, &RMF_MDT_BODY);
183                 if (!(body->mbo_valid & OBD_MD_FLRELEASED))
184                         rc = -EBUSY;
185         }
186
187         ll_finish_md_op_data(op_data);
188         EXIT;
189 out:
190
191         md_clear_open_replay_data(md_exp, och);
192         och->och_fh.cookie = DEAD_HANDLE_MAGIC;
193         OBD_FREE_PTR(och);
194
195         if (req) /* This is close request */
196                 ptlrpc_req_finished(req);
197         return rc;
198 }
199
200 int ll_md_real_close(struct inode *inode, fmode_t fmode)
201 {
202         struct ll_inode_info *lli = ll_i2info(inode);
203         struct obd_client_handle **och_p;
204         struct obd_client_handle *och;
205         __u64 *och_usecount;
206         int rc = 0;
207         ENTRY;
208
209         if (fmode & FMODE_WRITE) {
210                 och_p = &lli->lli_mds_write_och;
211                 och_usecount = &lli->lli_open_fd_write_count;
212         } else if (fmode & FMODE_EXEC) {
213                 och_p = &lli->lli_mds_exec_och;
214                 och_usecount = &lli->lli_open_fd_exec_count;
215         } else {
216                 LASSERT(fmode & FMODE_READ);
217                 och_p = &lli->lli_mds_read_och;
218                 och_usecount = &lli->lli_open_fd_read_count;
219         }
220
221         mutex_lock(&lli->lli_och_mutex);
222         if (*och_usecount > 0) {
223                 /* There are still users of this handle, so skip
224                  * freeing it. */
225                 mutex_unlock(&lli->lli_och_mutex);
226                 RETURN(0);
227         }
228
229         och = *och_p;
230         *och_p = NULL;
231         mutex_unlock(&lli->lli_och_mutex);
232
233         if (och != NULL) {
234                 /* There might be a race and this handle may already
235                  * be closed. */
236                 rc = ll_close_inode_openhandle(ll_i2sbi(inode)->ll_md_exp,
237                                                inode, och, NULL);
238         }
239
240         RETURN(rc);
241 }
242
243 static int ll_md_close(struct obd_export *md_exp, struct inode *inode,
244                        struct file *file)
245 {
246         struct ll_file_data *fd = LUSTRE_FPRIVATE(file);
247         struct ll_inode_info *lli = ll_i2info(inode);
248         int rc = 0;
249         ENTRY;
250
251         /* clear group lock, if present */
252         if (unlikely(fd->fd_flags & LL_FILE_GROUP_LOCKED))
253                 ll_put_grouplock(inode, file, fd->fd_grouplock.lg_gid);
254
255         if (fd->fd_lease_och != NULL) {
256                 bool lease_broken;
257
258                 /* Usually the lease is not released when the
259                  * application crashed, we need to release here. */
260                 rc = ll_lease_close(fd->fd_lease_och, inode, &lease_broken);
261                 CDEBUG(rc ? D_ERROR : D_INODE, "Clean up lease "DFID" %d/%d\n",
262                         PFID(&lli->lli_fid), rc, lease_broken);
263
264                 fd->fd_lease_och = NULL;
265         }
266
267         if (fd->fd_och != NULL) {
268                 rc = ll_close_inode_openhandle(md_exp, inode, fd->fd_och, NULL);
269                 fd->fd_och = NULL;
270                 GOTO(out, rc);
271         }
272
273         /* Let's see if we have good enough OPEN lock on the file and if
274            we can skip talking to MDS */
275         if (file->f_dentry->d_inode) { /* Can this ever be false? */
276                 int lockmode;
277                 __u64 flags = LDLM_FL_BLOCK_GRANTED | LDLM_FL_TEST_LOCK;
278                 struct lustre_handle lockh;
279                 struct inode *inode = file->f_dentry->d_inode;
280                 ldlm_policy_data_t policy = {.l_inodebits={MDS_INODELOCK_OPEN}};
281
282                 mutex_lock(&lli->lli_och_mutex);
283                 if (fd->fd_omode & FMODE_WRITE) {
284                         lockmode = LCK_CW;
285                         LASSERT(lli->lli_open_fd_write_count);
286                         lli->lli_open_fd_write_count--;
287                 } else if (fd->fd_omode & FMODE_EXEC) {
288                         lockmode = LCK_PR;
289                         LASSERT(lli->lli_open_fd_exec_count);
290                         lli->lli_open_fd_exec_count--;
291                 } else {
292                         lockmode = LCK_CR;
293                         LASSERT(lli->lli_open_fd_read_count);
294                         lli->lli_open_fd_read_count--;
295                 }
296                 mutex_unlock(&lli->lli_och_mutex);
297
298                 if (!md_lock_match(md_exp, flags, ll_inode2fid(inode),
299                                    LDLM_IBITS, &policy, lockmode,
300                                    &lockh)) {
301                         rc = ll_md_real_close(file->f_dentry->d_inode,
302                                               fd->fd_omode);
303                 }
304         } else {
305                 CERROR("released file has negative dentry: file = %p, "
306                        "dentry = %p, name = %s\n",
307                        file, file->f_dentry, file->f_dentry->d_name.name);
308         }
309
310 out:
311         LUSTRE_FPRIVATE(file) = NULL;
312         ll_file_data_put(fd);
313         ll_capa_close(inode);
314
315         RETURN(rc);
316 }
317
318 /* While this returns an error code, fput() the caller does not, so we need
319  * to make every effort to clean up all of our state here.  Also, applications
320  * rarely check close errors and even if an error is returned they will not
321  * re-try the close call.
322  */
323 int ll_file_release(struct inode *inode, struct file *file)
324 {
325         struct ll_file_data *fd;
326         struct ll_sb_info *sbi = ll_i2sbi(inode);
327         struct ll_inode_info *lli = ll_i2info(inode);
328         int rc;
329         ENTRY;
330
331         CDEBUG(D_VFSTRACE, "VFS Op:inode="DFID"(%p)\n",
332                PFID(ll_inode2fid(inode)), inode);
333
334 #ifdef CONFIG_FS_POSIX_ACL
335         if (sbi->ll_flags & LL_SBI_RMT_CLIENT &&
336             inode == inode->i_sb->s_root->d_inode) {
337                 struct ll_file_data *fd = LUSTRE_FPRIVATE(file);
338
339                 LASSERT(fd != NULL);
340                 if (unlikely(fd->fd_flags & LL_FILE_RMTACL)) {
341                         fd->fd_flags &= ~LL_FILE_RMTACL;
342                         rct_del(&sbi->ll_rct, current_pid());
343                         et_search_free(&sbi->ll_et, current_pid());
344                 }
345         }
346 #endif
347
348         if (inode->i_sb->s_root != file->f_dentry)
349                 ll_stats_ops_tally(sbi, LPROC_LL_RELEASE, 1);
350         fd = LUSTRE_FPRIVATE(file);
351         LASSERT(fd != NULL);
352
353         /* The last ref on @file, maybe not the the owner pid of statahead,
354          * because parent and child process can share the same file handle. */
355         if (S_ISDIR(inode->i_mode) && lli->lli_opendir_key == fd)
356                 ll_deauthorize_statahead(inode, fd);
357
358         if (inode->i_sb->s_root == file->f_dentry) {
359                 LUSTRE_FPRIVATE(file) = NULL;
360                 ll_file_data_put(fd);
361                 RETURN(0);
362         }
363
364         if (!S_ISDIR(inode->i_mode)) {
365                 if (lli->lli_clob != NULL)
366                         lov_read_and_clear_async_rc(lli->lli_clob);
367                 lli->lli_async_rc = 0;
368         }
369
370         rc = ll_md_close(sbi->ll_md_exp, inode, file);
371
372         if (CFS_FAIL_TIMEOUT_MS(OBD_FAIL_PTLRPC_DUMP_LOG, cfs_fail_val))
373                 libcfs_debug_dumplog();
374
375         RETURN(rc);
376 }
377
378 static int ll_intent_file_open(struct file *file, void *lmm, int lmmsize,
379                                 struct lookup_intent *itp)
380 {
381         struct dentry *de = file->f_dentry;
382         struct ll_sb_info *sbi = ll_i2sbi(de->d_inode);
383         struct dentry *parent = de->d_parent;
384         const char *name = NULL;
385         int len = 0;
386         struct md_op_data *op_data;
387         struct ptlrpc_request *req = NULL;
388         int rc;
389         ENTRY;
390
391         LASSERT(parent != NULL);
392         LASSERT(itp->it_flags & MDS_OPEN_BY_FID);
393
394         /* if server supports open-by-fid, or file name is invalid, don't pack
395          * name in open request */
396         if (!(exp_connect_flags(sbi->ll_md_exp) & OBD_CONNECT_OPEN_BY_FID) &&
397             lu_name_is_valid_2(de->d_name.name, de->d_name.len)) {
398                 name = de->d_name.name;
399                 len = de->d_name.len;
400         }
401
402         op_data = ll_prep_md_op_data(NULL, parent->d_inode, de->d_inode,
403                                      name, len, 0, LUSTRE_OPC_ANY, NULL);
404         if (IS_ERR(op_data))
405                 RETURN(PTR_ERR(op_data));
406         op_data->op_data = lmm;
407         op_data->op_data_size = lmmsize;
408
409         rc = md_intent_lock(sbi->ll_md_exp, op_data, itp, &req,
410                             &ll_md_blocking_ast, 0);
411         ll_finish_md_op_data(op_data);
412         if (rc == -ESTALE) {
413                 /* reason for keep own exit path - don`t flood log
414                  * with messages with -ESTALE errors.
415                  */
416                 if (!it_disposition(itp, DISP_OPEN_OPEN) ||
417                      it_open_error(DISP_OPEN_OPEN, itp))
418                         GOTO(out, rc);
419                 ll_release_openhandle(de, itp);
420                 GOTO(out, rc);
421         }
422
423         if (it_disposition(itp, DISP_LOOKUP_NEG))
424                 GOTO(out, rc = -ENOENT);
425
426         if (rc != 0 || it_open_error(DISP_OPEN_OPEN, itp)) {
427                 rc = rc ? rc : it_open_error(DISP_OPEN_OPEN, itp);
428                 CDEBUG(D_VFSTRACE, "lock enqueue: err: %d\n", rc);
429                 GOTO(out, rc);
430         }
431
432         rc = ll_prep_inode(&de->d_inode, req, NULL, itp);
433         if (!rc && itp->d.lustre.it_lock_mode)
434                 ll_set_lock_data(sbi->ll_md_exp, de->d_inode, itp, NULL);
435
436 out:
437         ptlrpc_req_finished(req);
438         ll_intent_drop_lock(itp);
439
440         RETURN(rc);
441 }
442
443 static int ll_och_fill(struct obd_export *md_exp, struct lookup_intent *it,
444                        struct obd_client_handle *och)
445 {
446         struct ptlrpc_request *req = it->d.lustre.it_data;
447         struct mdt_body *body;
448
449         body = req_capsule_server_get(&req->rq_pill, &RMF_MDT_BODY);
450         och->och_fh = body->mbo_handle;
451         och->och_fid = body->mbo_fid1;
452         och->och_lease_handle.cookie = it->d.lustre.it_lock_handle;
453         och->och_magic = OBD_CLIENT_HANDLE_MAGIC;
454         och->och_flags = it->it_flags;
455
456         return md_set_open_replay_data(md_exp, och, it);
457 }
458
459 static int ll_local_open(struct file *file, struct lookup_intent *it,
460                          struct ll_file_data *fd, struct obd_client_handle *och)
461 {
462         struct inode *inode = file->f_dentry->d_inode;
463         ENTRY;
464
465         LASSERT(!LUSTRE_FPRIVATE(file));
466
467         LASSERT(fd != NULL);
468
469         if (och) {
470                 int rc;
471
472                 rc = ll_och_fill(ll_i2sbi(inode)->ll_md_exp, it, och);
473                 if (rc != 0)
474                         RETURN(rc);
475         }
476
477         LUSTRE_FPRIVATE(file) = fd;
478         ll_readahead_init(inode, &fd->fd_ras);
479         fd->fd_omode = it->it_flags & (FMODE_READ | FMODE_WRITE | FMODE_EXEC);
480
481         /* ll_cl_context initialize */
482         rwlock_init(&fd->fd_lock);
483         INIT_LIST_HEAD(&fd->fd_lccs);
484
485         RETURN(0);
486 }
487
488 /* Open a file, and (for the very first open) create objects on the OSTs at
489  * this time.  If opened with O_LOV_DELAY_CREATE, then we don't do the object
490  * creation or open until ll_lov_setstripe() ioctl is called.
491  *
492  * If we already have the stripe MD locally then we don't request it in
493  * md_open(), by passing a lmm_size = 0.
494  *
495  * It is up to the application to ensure no other processes open this file
496  * in the O_LOV_DELAY_CREATE case, or the default striping pattern will be
497  * used.  We might be able to avoid races of that sort by getting lli_open_sem
498  * before returning in the O_LOV_DELAY_CREATE case and dropping it here
499  * or in ll_file_release(), but I'm not sure that is desirable/necessary.
500  */
501 int ll_file_open(struct inode *inode, struct file *file)
502 {
503         struct ll_inode_info *lli = ll_i2info(inode);
504         struct lookup_intent *it, oit = { .it_op = IT_OPEN,
505                                           .it_flags = file->f_flags };
506         struct obd_client_handle **och_p = NULL;
507         __u64 *och_usecount = NULL;
508         struct ll_file_data *fd;
509         int rc = 0;
510         ENTRY;
511
512         CDEBUG(D_VFSTRACE, "VFS Op:inode="DFID"(%p), flags %o\n",
513                PFID(ll_inode2fid(inode)), inode, file->f_flags);
514
515         it = file->private_data; /* XXX: compat macro */
516         file->private_data = NULL; /* prevent ll_local_open assertion */
517
518         fd = ll_file_data_get();
519         if (fd == NULL)
520                 GOTO(out_openerr, rc = -ENOMEM);
521
522         fd->fd_file = file;
523         if (S_ISDIR(inode->i_mode))
524                 ll_authorize_statahead(inode, fd);
525
526         if (inode->i_sb->s_root == file->f_dentry) {
527                 LUSTRE_FPRIVATE(file) = fd;
528                 RETURN(0);
529         }
530
531         if (!it || !it->d.lustre.it_disposition) {
532                 /* Convert f_flags into access mode. We cannot use file->f_mode,
533                  * because everything but O_ACCMODE mask was stripped from
534                  * there */
535                 if ((oit.it_flags + 1) & O_ACCMODE)
536                         oit.it_flags++;
537                 if (file->f_flags & O_TRUNC)
538                         oit.it_flags |= FMODE_WRITE;
539
540                 /* kernel only call f_op->open in dentry_open.  filp_open calls
541                  * dentry_open after call to open_namei that checks permissions.
542                  * Only nfsd_open call dentry_open directly without checking
543                  * permissions and because of that this code below is safe. */
544                 if (oit.it_flags & (FMODE_WRITE | FMODE_READ))
545                         oit.it_flags |= MDS_OPEN_OWNEROVERRIDE;
546
547                 /* We do not want O_EXCL here, presumably we opened the file
548                  * already? XXX - NFS implications? */
549                 oit.it_flags &= ~O_EXCL;
550
551                 /* bug20584, if "it_flags" contains O_CREAT, the file will be
552                  * created if necessary, then "IT_CREAT" should be set to keep
553                  * consistent with it */
554                 if (oit.it_flags & O_CREAT)
555                         oit.it_op |= IT_CREAT;
556
557                 it = &oit;
558         }
559
560 restart:
561         /* Let's see if we have file open on MDS already. */
562         if (it->it_flags & FMODE_WRITE) {
563                 och_p = &lli->lli_mds_write_och;
564                 och_usecount = &lli->lli_open_fd_write_count;
565         } else if (it->it_flags & FMODE_EXEC) {
566                 och_p = &lli->lli_mds_exec_och;
567                 och_usecount = &lli->lli_open_fd_exec_count;
568          } else {
569                 och_p = &lli->lli_mds_read_och;
570                 och_usecount = &lli->lli_open_fd_read_count;
571         }
572
573         mutex_lock(&lli->lli_och_mutex);
574         if (*och_p) { /* Open handle is present */
575                 if (it_disposition(it, DISP_OPEN_OPEN)) {
576                         /* Well, there's extra open request that we do not need,
577                            let's close it somehow. This will decref request. */
578                         rc = it_open_error(DISP_OPEN_OPEN, it);
579                         if (rc) {
580                                 mutex_unlock(&lli->lli_och_mutex);
581                                 GOTO(out_openerr, rc);
582                         }
583
584                         ll_release_openhandle(file->f_dentry, it);
585                 }
586                 (*och_usecount)++;
587
588                 rc = ll_local_open(file, it, fd, NULL);
589                 if (rc) {
590                         (*och_usecount)--;
591                         mutex_unlock(&lli->lli_och_mutex);
592                         GOTO(out_openerr, rc);
593                 }
594         } else {
595                 LASSERT(*och_usecount == 0);
596                 if (!it->d.lustre.it_disposition) {
597                         /* We cannot just request lock handle now, new ELC code
598                            means that one of other OPEN locks for this file
599                            could be cancelled, and since blocking ast handler
600                            would attempt to grab och_mutex as well, that would
601                            result in a deadlock */
602                         mutex_unlock(&lli->lli_och_mutex);
603                         /*
604                          * Normally called under two situations:
605                          * 1. NFS export.
606                          * 2. A race/condition on MDS resulting in no open
607                          *    handle to be returned from LOOKUP|OPEN request,
608                          *    for example if the target entry was a symlink.
609                          *
610                          * Always fetch MDS_OPEN_LOCK if this is not setstripe.
611                          *
612                          * Always specify MDS_OPEN_BY_FID because we don't want
613                          * to get file with different fid.
614                          */
615                         it->it_flags |= MDS_OPEN_LOCK | MDS_OPEN_BY_FID;
616                         rc = ll_intent_file_open(file, NULL, 0, it);
617                         if (rc)
618                                 GOTO(out_openerr, rc);
619
620                         goto restart;
621                 }
622                 OBD_ALLOC(*och_p, sizeof (struct obd_client_handle));
623                 if (!*och_p)
624                         GOTO(out_och_free, rc = -ENOMEM);
625
626                 (*och_usecount)++;
627
628                 /* md_intent_lock() didn't get a request ref if there was an
629                  * open error, so don't do cleanup on the request here
630                  * (bug 3430) */
631                 /* XXX (green): Should not we bail out on any error here, not
632                  * just open error? */
633                 rc = it_open_error(DISP_OPEN_OPEN, it);
634                 if (rc != 0)
635                         GOTO(out_och_free, rc);
636
637                 LASSERTF(it_disposition(it, DISP_ENQ_OPEN_REF),
638                          "inode %p: disposition %x, status %d\n", inode,
639                          it_disposition(it, ~0), it->d.lustre.it_status);
640
641                 rc = ll_local_open(file, it, fd, *och_p);
642                 if (rc)
643                         GOTO(out_och_free, rc);
644         }
645         mutex_unlock(&lli->lli_och_mutex);
646         fd = NULL;
647
648         /* Must do this outside lli_och_mutex lock to prevent deadlock where
649            different kind of OPEN lock for this same inode gets cancelled
650            by ldlm_cancel_lru */
651         if (!S_ISREG(inode->i_mode))
652                 GOTO(out_och_free, rc);
653
654         ll_capa_open(inode);
655
656         if (!lli->lli_has_smd &&
657             (cl_is_lov_delay_create(file->f_flags) ||
658              (file->f_mode & FMODE_WRITE) == 0)) {
659                 CDEBUG(D_INODE, "object creation was delayed\n");
660                 GOTO(out_och_free, rc);
661         }
662         cl_lov_delay_create_clear(&file->f_flags);
663         GOTO(out_och_free, rc);
664
665 out_och_free:
666         if (rc) {
667                 if (och_p && *och_p) {
668                         OBD_FREE(*och_p, sizeof (struct obd_client_handle));
669                         *och_p = NULL; /* OBD_FREE writes some magic there */
670                         (*och_usecount)--;
671                 }
672                 mutex_unlock(&lli->lli_och_mutex);
673
674 out_openerr:
675                 if (lli->lli_opendir_key == fd)
676                         ll_deauthorize_statahead(inode, fd);
677                 if (fd != NULL)
678                         ll_file_data_put(fd);
679         } else {
680                 ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_OPEN, 1);
681         }
682
683         if (it && it_disposition(it, DISP_ENQ_OPEN_REF)) {
684                 ptlrpc_req_finished(it->d.lustre.it_data);
685                 it_clear_disposition(it, DISP_ENQ_OPEN_REF);
686         }
687
688         return rc;
689 }
690
691 static int ll_md_blocking_lease_ast(struct ldlm_lock *lock,
692                         struct ldlm_lock_desc *desc, void *data, int flag)
693 {
694         int rc;
695         struct lustre_handle lockh;
696         ENTRY;
697
698         switch (flag) {
699         case LDLM_CB_BLOCKING:
700                 ldlm_lock2handle(lock, &lockh);
701                 rc = ldlm_cli_cancel(&lockh, LCF_ASYNC);
702                 if (rc < 0) {
703                         CDEBUG(D_INODE, "ldlm_cli_cancel: %d\n", rc);
704                         RETURN(rc);
705                 }
706                 break;
707         case LDLM_CB_CANCELING:
708                 /* do nothing */
709                 break;
710         }
711         RETURN(0);
712 }
713
714 /**
715  * Acquire a lease and open the file.
716  */
717 static struct obd_client_handle *
718 ll_lease_open(struct inode *inode, struct file *file, fmode_t fmode,
719               __u64 open_flags)
720 {
721         struct lookup_intent it = { .it_op = IT_OPEN };
722         struct ll_sb_info *sbi = ll_i2sbi(inode);
723         struct md_op_data *op_data;
724         struct ptlrpc_request *req = NULL;
725         struct lustre_handle old_handle = { 0 };
726         struct obd_client_handle *och = NULL;
727         int rc;
728         int rc2;
729         ENTRY;
730
731         if (fmode != FMODE_WRITE && fmode != FMODE_READ)
732                 RETURN(ERR_PTR(-EINVAL));
733
734         if (file != NULL) {
735                 struct ll_inode_info *lli = ll_i2info(inode);
736                 struct ll_file_data *fd = LUSTRE_FPRIVATE(file);
737                 struct obd_client_handle **och_p;
738                 __u64 *och_usecount;
739
740                 if (!(fmode & file->f_mode) || (file->f_mode & FMODE_EXEC))
741                         RETURN(ERR_PTR(-EPERM));
742
743                 /* Get the openhandle of the file */
744                 rc = -EBUSY;
745                 mutex_lock(&lli->lli_och_mutex);
746                 if (fd->fd_lease_och != NULL) {
747                         mutex_unlock(&lli->lli_och_mutex);
748                         RETURN(ERR_PTR(rc));
749                 }
750
751                 if (fd->fd_och == NULL) {
752                         if (file->f_mode & FMODE_WRITE) {
753                                 LASSERT(lli->lli_mds_write_och != NULL);
754                                 och_p = &lli->lli_mds_write_och;
755                                 och_usecount = &lli->lli_open_fd_write_count;
756                         } else {
757                                 LASSERT(lli->lli_mds_read_och != NULL);
758                                 och_p = &lli->lli_mds_read_och;
759                                 och_usecount = &lli->lli_open_fd_read_count;
760                         }
761                         if (*och_usecount == 1) {
762                                 fd->fd_och = *och_p;
763                                 *och_p = NULL;
764                                 *och_usecount = 0;
765                                 rc = 0;
766                         }
767                 }
768                 mutex_unlock(&lli->lli_och_mutex);
769                 if (rc < 0) /* more than 1 opener */
770                         RETURN(ERR_PTR(rc));
771
772                 LASSERT(fd->fd_och != NULL);
773                 old_handle = fd->fd_och->och_fh;
774         }
775
776         OBD_ALLOC_PTR(och);
777         if (och == NULL)
778                 RETURN(ERR_PTR(-ENOMEM));
779
780         op_data = ll_prep_md_op_data(NULL, inode, inode, NULL, 0, 0,
781                                         LUSTRE_OPC_ANY, NULL);
782         if (IS_ERR(op_data))
783                 GOTO(out, rc = PTR_ERR(op_data));
784
785         /* To tell the MDT this openhandle is from the same owner */
786         op_data->op_handle = old_handle;
787
788         it.it_flags = fmode | open_flags;
789         it.it_flags |= MDS_OPEN_LOCK | MDS_OPEN_BY_FID | MDS_OPEN_LEASE;
790         rc = md_intent_lock(sbi->ll_md_exp, op_data, &it, &req,
791                             &ll_md_blocking_lease_ast,
792         /* LDLM_FL_NO_LRU: To not put the lease lock into LRU list, otherwise
793          * it can be cancelled which may mislead applications that the lease is
794          * broken;
795          * LDLM_FL_EXCL: Set this flag so that it won't be matched by normal
796          * open in ll_md_blocking_ast(). Otherwise as ll_md_blocking_lease_ast
797          * doesn't deal with openhandle, so normal openhandle will be leaked. */
798                             LDLM_FL_NO_LRU | LDLM_FL_EXCL);
799         ll_finish_md_op_data(op_data);
800         ptlrpc_req_finished(req);
801         if (rc < 0)
802                 GOTO(out_release_it, rc);
803
804         if (it_disposition(&it, DISP_LOOKUP_NEG))
805                 GOTO(out_release_it, rc = -ENOENT);
806
807         rc = it_open_error(DISP_OPEN_OPEN, &it);
808         if (rc)
809                 GOTO(out_release_it, rc);
810
811         LASSERT(it_disposition(&it, DISP_ENQ_OPEN_REF));
812         ll_och_fill(sbi->ll_md_exp, &it, och);
813
814         if (!it_disposition(&it, DISP_OPEN_LEASE)) /* old server? */
815                 GOTO(out_close, rc = -EOPNOTSUPP);
816
817         /* already get lease, handle lease lock */
818         ll_set_lock_data(sbi->ll_md_exp, inode, &it, NULL);
819         if (it.d.lustre.it_lock_mode == 0 ||
820             it.d.lustre.it_lock_bits != MDS_INODELOCK_OPEN) {
821                 /* open lock must return for lease */
822                 CERROR(DFID "lease granted but no open lock, %d/"LPU64".\n",
823                         PFID(ll_inode2fid(inode)), it.d.lustre.it_lock_mode,
824                         it.d.lustre.it_lock_bits);
825                 GOTO(out_close, rc = -EPROTO);
826         }
827
828         ll_intent_release(&it);
829         RETURN(och);
830
831 out_close:
832         /* Cancel open lock */
833         if (it.d.lustre.it_lock_mode != 0) {
834                 ldlm_lock_decref_and_cancel(&och->och_lease_handle,
835                                             it.d.lustre.it_lock_mode);
836                 it.d.lustre.it_lock_mode = 0;
837                 och->och_lease_handle.cookie = 0ULL;
838         }
839         rc2 = ll_close_inode_openhandle(sbi->ll_md_exp, inode, och, NULL);
840         if (rc2 < 0)
841                 CERROR("%s: error closing file "DFID": %d\n",
842                        ll_get_fsname(inode->i_sb, NULL, 0),
843                        PFID(&ll_i2info(inode)->lli_fid), rc2);
844         och = NULL; /* och has been freed in ll_close_inode_openhandle() */
845 out_release_it:
846         ll_intent_release(&it);
847 out:
848         if (och != NULL)
849                 OBD_FREE_PTR(och);
850         RETURN(ERR_PTR(rc));
851 }
852
853 /**
854  * Release lease and close the file.
855  * It will check if the lease has ever broken.
856  */
857 static int ll_lease_close(struct obd_client_handle *och, struct inode *inode,
858                           bool *lease_broken)
859 {
860         struct ldlm_lock *lock;
861         bool cancelled = true;
862         int rc;
863         ENTRY;
864
865         lock = ldlm_handle2lock(&och->och_lease_handle);
866         if (lock != NULL) {
867                 lock_res_and_lock(lock);
868                 cancelled = ldlm_is_cancel(lock);
869                 unlock_res_and_lock(lock);
870                 LDLM_LOCK_PUT(lock);
871         }
872
873         CDEBUG(D_INODE, "lease for "DFID" broken? %d\n",
874                 PFID(&ll_i2info(inode)->lli_fid), cancelled);
875
876         if (!cancelled)
877                 ldlm_cli_cancel(&och->och_lease_handle, 0);
878         if (lease_broken != NULL)
879                 *lease_broken = cancelled;
880
881         rc = ll_close_inode_openhandle(ll_i2sbi(inode)->ll_md_exp, inode, och,
882                                        NULL);
883         RETURN(rc);
884 }
885
886 int ll_merge_attr(const struct lu_env *env, struct inode *inode)
887 {
888         struct ll_inode_info *lli = ll_i2info(inode);
889         struct cl_object *obj = lli->lli_clob;
890         struct cl_attr *attr = vvp_env_thread_attr(env);
891         s64 atime;
892         s64 mtime;
893         s64 ctime;
894         int rc = 0;
895
896         ENTRY;
897
898         ll_inode_size_lock(inode);
899
900         /* merge timestamps the most recently obtained from mds with
901            timestamps obtained from osts */
902         LTIME_S(inode->i_atime) = lli->lli_atime;
903         LTIME_S(inode->i_mtime) = lli->lli_mtime;
904         LTIME_S(inode->i_ctime) = lli->lli_ctime;
905
906         atime = LTIME_S(inode->i_atime);
907         mtime = LTIME_S(inode->i_mtime);
908         ctime = LTIME_S(inode->i_ctime);
909
910         cl_object_attr_lock(obj);
911         rc = cl_object_attr_get(env, obj, attr);
912         cl_object_attr_unlock(obj);
913
914         if (rc != 0)
915                 GOTO(out_size_unlock, rc);
916
917         if (atime < attr->cat_atime)
918                 atime = attr->cat_atime;
919
920         if (ctime < attr->cat_ctime)
921                 ctime = attr->cat_ctime;
922
923         if (mtime < attr->cat_mtime)
924                 mtime = attr->cat_mtime;
925
926         CDEBUG(D_VFSTRACE, DFID" updating i_size "LPU64"\n",
927                PFID(&lli->lli_fid), attr->cat_size);
928
929         i_size_write(inode, attr->cat_size);
930         inode->i_blocks = attr->cat_blocks;
931
932         LTIME_S(inode->i_atime) = atime;
933         LTIME_S(inode->i_mtime) = mtime;
934         LTIME_S(inode->i_ctime) = ctime;
935
936 out_size_unlock:
937         ll_inode_size_unlock(inode);
938
939         RETURN(rc);
940 }
941
942 static bool file_is_noatime(const struct file *file)
943 {
944         const struct vfsmount *mnt = file->f_path.mnt;
945         const struct inode *inode = file->f_path.dentry->d_inode;
946
947         /* Adapted from file_accessed() and touch_atime().*/
948         if (file->f_flags & O_NOATIME)
949                 return true;
950
951         if (inode->i_flags & S_NOATIME)
952                 return true;
953
954         if (IS_NOATIME(inode))
955                 return true;
956
957         if (mnt->mnt_flags & (MNT_NOATIME | MNT_READONLY))
958                 return true;
959
960         if ((mnt->mnt_flags & MNT_NODIRATIME) && S_ISDIR(inode->i_mode))
961                 return true;
962
963         if ((inode->i_sb->s_flags & MS_NODIRATIME) && S_ISDIR(inode->i_mode))
964                 return true;
965
966         return false;
967 }
968
969 static void ll_io_init(struct cl_io *io, const struct file *file, int write)
970 {
971         struct inode *inode = file->f_dentry->d_inode;
972
973         io->u.ci_rw.crw_nonblock = file->f_flags & O_NONBLOCK;
974         if (write) {
975                 io->u.ci_wr.wr_append = !!(file->f_flags & O_APPEND);
976                 io->u.ci_wr.wr_sync = file->f_flags & O_SYNC ||
977                                       file->f_flags & O_DIRECT ||
978                                       IS_SYNC(inode);
979         }
980         io->ci_obj     = ll_i2info(inode)->lli_clob;
981         io->ci_lockreq = CILR_MAYBE;
982         if (ll_file_nolock(file)) {
983                 io->ci_lockreq = CILR_NEVER;
984                 io->ci_no_srvlock = 1;
985         } else if (file->f_flags & O_APPEND) {
986                 io->ci_lockreq = CILR_MANDATORY;
987         }
988
989         io->ci_noatime = file_is_noatime(file);
990 }
991
992 static ssize_t
993 ll_file_io_generic(const struct lu_env *env, struct vvp_io_args *args,
994                    struct file *file, enum cl_io_type iot,
995                    loff_t *ppos, size_t count)
996 {
997         struct inode *inode = file->f_dentry->d_inode;
998         struct ll_inode_info *lli = ll_i2info(inode);
999         loff_t               end;
1000         struct ll_file_data  *fd  = LUSTRE_FPRIVATE(file);
1001         struct cl_io         *io;
1002         ssize_t               result;
1003         struct range_lock     range;
1004         ENTRY;
1005
1006         CDEBUG(D_VFSTRACE, "file: %s, type: %d ppos: "LPU64", count: %zu\n",
1007                 file->f_dentry->d_name.name, iot, *ppos, count);
1008
1009 restart:
1010         io = vvp_env_thread_io(env);
1011         ll_io_init(io, file, iot == CIT_WRITE);
1012
1013         /* The maximum Lustre file size is variable, based on the
1014          * OST maximum object size and number of stripes.  This
1015          * needs another check in addition to the VFS checks earlier. */
1016         end = (io->u.ci_wr.wr_append ? i_size_read(inode) : *ppos) + count;
1017         if (end > ll_file_maxbytes(inode)) {
1018                 result = -EFBIG;
1019                 CDEBUG(D_INODE, "%s: file "DFID" offset %llu > maxbytes "LPU64
1020                        ": rc = %zd\n", ll_get_fsname(inode->i_sb, NULL, 0),
1021                        PFID(&lli->lli_fid), end, ll_file_maxbytes(inode),
1022                        result);
1023                 RETURN(result);
1024         }
1025
1026         if (cl_io_rw_init(env, io, iot, *ppos, count) == 0) {
1027                 struct vvp_io *vio = vvp_env_io(env);
1028                 bool range_locked = false;
1029
1030                 if (file->f_flags & O_APPEND)
1031                         range_lock_init(&range, 0, LUSTRE_EOF);
1032                 else
1033                         range_lock_init(&range, *ppos, *ppos + count - 1);
1034
1035                 vio->vui_fd  = LUSTRE_FPRIVATE(file);
1036                 vio->vui_io_subtype = args->via_io_subtype;
1037
1038                 switch (vio->vui_io_subtype) {
1039                 case IO_NORMAL:
1040                         vio->vui_iov = args->u.normal.via_iov;
1041                         vio->vui_nrsegs = args->u.normal.via_nrsegs;
1042                         vio->vui_tot_nrsegs = vio->vui_nrsegs;
1043                         vio->vui_iocb = args->u.normal.via_iocb;
1044                         if ((iot == CIT_WRITE) &&
1045                             !(vio->vui_fd->fd_flags & LL_FILE_GROUP_LOCKED)) {
1046                                 CDEBUG(D_VFSTRACE, "Range lock "RL_FMT"\n",
1047                                        RL_PARA(&range));
1048                                 result = range_lock(&lli->lli_write_tree,
1049                                                     &range);
1050                                 if (result < 0)
1051                                         GOTO(out, result);
1052
1053                                 range_locked = true;
1054                         }
1055                         down_read(&lli->lli_trunc_sem);
1056                         break;
1057                 case IO_SPLICE:
1058                         vio->u.splice.vui_pipe = args->u.splice.via_pipe;
1059                         vio->u.splice.vui_flags = args->u.splice.via_flags;
1060                         break;
1061                 default:
1062                         CERROR("unknown IO subtype %u\n", vio->vui_io_subtype);
1063                         LBUG();
1064                 }
1065
1066                 ll_cl_add(file, env, io);
1067                 result = cl_io_loop(env, io);
1068                 ll_cl_remove(file, env);
1069
1070                 if (args->via_io_subtype == IO_NORMAL)
1071                         up_read(&lli->lli_trunc_sem);
1072                 if (range_locked) {
1073                         CDEBUG(D_VFSTRACE, "Range unlock "RL_FMT"\n",
1074                                RL_PARA(&range));
1075                         range_unlock(&lli->lli_write_tree, &range);
1076                 }
1077         } else {
1078                 /* cl_io_rw_init() handled IO */
1079                 result = io->ci_result;
1080         }
1081
1082         if (io->ci_nob > 0) {
1083                 result = io->ci_nob;
1084                 *ppos = io->u.ci_wr.wr.crw_pos;
1085         }
1086         GOTO(out, result);
1087 out:
1088         cl_io_fini(env, io);
1089         /* If any bit been read/written (result != 0), we just return
1090          * short read/write instead of restart io. */
1091         if ((result == 0 || result == -ENODATA) && io->ci_need_restart) {
1092                 CDEBUG(D_VFSTRACE, "Restart %s on %s from %lld, count:%zu\n",
1093                        iot == CIT_READ ? "read" : "write",
1094                        file->f_dentry->d_name.name, *ppos, count);
1095                 LASSERTF(io->ci_nob == 0, "%zd\n", io->ci_nob);
1096                 goto restart;
1097         }
1098
1099         if (iot == CIT_READ) {
1100                 if (result >= 0)
1101                         ll_stats_ops_tally(ll_i2sbi(file->f_dentry->d_inode),
1102                                            LPROC_LL_READ_BYTES, result);
1103         } else if (iot == CIT_WRITE) {
1104                 if (result >= 0) {
1105                         ll_stats_ops_tally(ll_i2sbi(file->f_dentry->d_inode),
1106                                            LPROC_LL_WRITE_BYTES, result);
1107                         fd->fd_write_failed = false;
1108                 } else if (result != -ERESTARTSYS) {
1109                         fd->fd_write_failed = true;
1110                 }
1111         }
1112         CDEBUG(D_VFSTRACE, "iot: %d, result: %zd\n", iot, result);
1113
1114         return result;
1115 }
1116
1117
1118 /*
1119  * XXX: exact copy from kernel code (__generic_file_aio_write_nolock)
1120  */
1121 static int ll_file_get_iov_count(const struct iovec *iov,
1122                                  unsigned long *nr_segs, size_t *count)
1123 {
1124         size_t cnt = 0;
1125         unsigned long seg;
1126
1127         for (seg = 0; seg < *nr_segs; seg++) {
1128                 const struct iovec *iv = &iov[seg];
1129
1130                 /*
1131                  * If any segment has a negative length, or the cumulative
1132                  * length ever wraps negative then return -EINVAL.
1133                  */
1134                 cnt += iv->iov_len;
1135                 if (unlikely((ssize_t)(cnt|iv->iov_len) < 0))
1136                         return -EINVAL;
1137                 if (access_ok(VERIFY_READ, iv->iov_base, iv->iov_len))
1138                         continue;
1139                 if (seg == 0)
1140                         return -EFAULT;
1141                 *nr_segs = seg;
1142                 cnt -= iv->iov_len;   /* This segment is no good */
1143                 break;
1144         }
1145         *count = cnt;
1146         return 0;
1147 }
1148
1149 static ssize_t ll_file_aio_read(struct kiocb *iocb, const struct iovec *iov,
1150                                 unsigned long nr_segs, loff_t pos)
1151 {
1152         struct lu_env      *env;
1153         struct vvp_io_args *args;
1154         size_t              count;
1155         ssize_t             result;
1156         int                 refcheck;
1157         ENTRY;
1158
1159         result = ll_file_get_iov_count(iov, &nr_segs, &count);
1160         if (result)
1161                 RETURN(result);
1162
1163         env = cl_env_get(&refcheck);
1164         if (IS_ERR(env))
1165                 RETURN(PTR_ERR(env));
1166
1167         args = ll_env_args(env, IO_NORMAL);
1168         args->u.normal.via_iov = (struct iovec *)iov;
1169         args->u.normal.via_nrsegs = nr_segs;
1170         args->u.normal.via_iocb = iocb;
1171
1172         result = ll_file_io_generic(env, args, iocb->ki_filp, CIT_READ,
1173                                     &iocb->ki_pos, count);
1174         cl_env_put(env, &refcheck);
1175         RETURN(result);
1176 }
1177
1178 static ssize_t ll_file_read(struct file *file, char __user *buf, size_t count,
1179                             loff_t *ppos)
1180 {
1181         struct lu_env *env;
1182         struct iovec  *local_iov;
1183         struct kiocb  *kiocb;
1184         ssize_t        result;
1185         int            refcheck;
1186         ENTRY;
1187
1188         env = cl_env_get(&refcheck);
1189         if (IS_ERR(env))
1190                 RETURN(PTR_ERR(env));
1191
1192         local_iov = &ll_env_info(env)->lti_local_iov;
1193         kiocb = &ll_env_info(env)->lti_kiocb;
1194         local_iov->iov_base = (void __user *)buf;
1195         local_iov->iov_len = count;
1196         init_sync_kiocb(kiocb, file);
1197         kiocb->ki_pos = *ppos;
1198 #ifdef HAVE_KIOCB_KI_LEFT
1199         kiocb->ki_left = count;
1200 #else
1201         kiocb->ki_nbytes = count;
1202 #endif
1203
1204         result = ll_file_aio_read(kiocb, local_iov, 1, kiocb->ki_pos);
1205         *ppos = kiocb->ki_pos;
1206
1207         cl_env_put(env, &refcheck);
1208         RETURN(result);
1209 }
1210
1211 /*
1212  * Write to a file (through the page cache).
1213  * AIO stuff
1214  */
1215 static ssize_t ll_file_aio_write(struct kiocb *iocb, const struct iovec *iov,
1216                                  unsigned long nr_segs, loff_t pos)
1217 {
1218         struct lu_env      *env;
1219         struct vvp_io_args *args;
1220         size_t              count;
1221         ssize_t             result;
1222         int                 refcheck;
1223         ENTRY;
1224
1225         result = ll_file_get_iov_count(iov, &nr_segs, &count);
1226         if (result)
1227                 RETURN(result);
1228
1229         env = cl_env_get(&refcheck);
1230         if (IS_ERR(env))
1231                 RETURN(PTR_ERR(env));
1232
1233         args = ll_env_args(env, IO_NORMAL);
1234         args->u.normal.via_iov = (struct iovec *)iov;
1235         args->u.normal.via_nrsegs = nr_segs;
1236         args->u.normal.via_iocb = iocb;
1237
1238         result = ll_file_io_generic(env, args, iocb->ki_filp, CIT_WRITE,
1239                                   &iocb->ki_pos, count);
1240         cl_env_put(env, &refcheck);
1241         RETURN(result);
1242 }
1243
1244 static ssize_t ll_file_write(struct file *file, const char __user *buf,
1245                              size_t count, loff_t *ppos)
1246 {
1247         struct lu_env *env;
1248         struct iovec  *local_iov;
1249         struct kiocb  *kiocb;
1250         ssize_t        result;
1251         int            refcheck;
1252         ENTRY;
1253
1254         env = cl_env_get(&refcheck);
1255         if (IS_ERR(env))
1256                 RETURN(PTR_ERR(env));
1257
1258         local_iov = &ll_env_info(env)->lti_local_iov;
1259         kiocb = &ll_env_info(env)->lti_kiocb;
1260         local_iov->iov_base = (void __user *)buf;
1261         local_iov->iov_len = count;
1262         init_sync_kiocb(kiocb, file);
1263         kiocb->ki_pos = *ppos;
1264 #ifdef HAVE_KIOCB_KI_LEFT
1265         kiocb->ki_left = count;
1266 #else
1267         kiocb->ki_nbytes = count;
1268 #endif
1269
1270         result = ll_file_aio_write(kiocb, local_iov, 1, kiocb->ki_pos);
1271         *ppos = kiocb->ki_pos;
1272
1273         cl_env_put(env, &refcheck);
1274         RETURN(result);
1275 }
1276
1277 /*
1278  * Send file content (through pagecache) somewhere with helper
1279  */
1280 static ssize_t ll_file_splice_read(struct file *in_file, loff_t *ppos,
1281                                    struct pipe_inode_info *pipe, size_t count,
1282                                    unsigned int flags)
1283 {
1284         struct lu_env      *env;
1285         struct vvp_io_args *args;
1286         ssize_t             result;
1287         int                 refcheck;
1288         ENTRY;
1289
1290         env = cl_env_get(&refcheck);
1291         if (IS_ERR(env))
1292                 RETURN(PTR_ERR(env));
1293
1294         args = ll_env_args(env, IO_SPLICE);
1295         args->u.splice.via_pipe = pipe;
1296         args->u.splice.via_flags = flags;
1297
1298         result = ll_file_io_generic(env, args, in_file, CIT_READ, ppos, count);
1299         cl_env_put(env, &refcheck);
1300         RETURN(result);
1301 }
1302
1303 int ll_lov_setstripe_ea_info(struct inode *inode, struct file *file,
1304                              __u64  flags, struct lov_user_md *lum,
1305                              int lum_size)
1306 {
1307         struct lov_stripe_md *lsm = NULL;
1308         struct lookup_intent oit = {
1309                 .it_op = IT_OPEN,
1310                 .it_flags = flags | MDS_OPEN_BY_FID,
1311         };
1312         int rc;
1313         ENTRY;
1314
1315         lsm = ccc_inode_lsm_get(inode);
1316         if (lsm != NULL) {
1317                 ccc_inode_lsm_put(inode, lsm);
1318                 CDEBUG(D_IOCTL, "stripe already exists for inode "DFID"\n",
1319                        PFID(ll_inode2fid(inode)));
1320                 GOTO(out, rc = -EEXIST);
1321         }
1322
1323         ll_inode_size_lock(inode);
1324         rc = ll_intent_file_open(file, lum, lum_size, &oit);
1325         if (rc < 0)
1326                 GOTO(out_unlock, rc);
1327
1328         rc = oit.d.lustre.it_status;
1329         if (rc < 0)
1330                 GOTO(out_unlock, rc);
1331
1332         ll_release_openhandle(file->f_dentry, &oit);
1333
1334 out_unlock:
1335         ll_inode_size_unlock(inode);
1336         ll_intent_release(&oit);
1337         ccc_inode_lsm_put(inode, lsm);
1338 out:
1339         cl_lov_delay_create_clear(&file->f_flags);
1340
1341         RETURN(rc);
1342 }
1343
1344 int ll_lov_getstripe_ea_info(struct inode *inode, const char *filename,
1345                              struct lov_mds_md **lmmp, int *lmm_size,
1346                              struct ptlrpc_request **request)
1347 {
1348         struct ll_sb_info *sbi = ll_i2sbi(inode);
1349         struct mdt_body  *body;
1350         struct lov_mds_md *lmm = NULL;
1351         struct ptlrpc_request *req = NULL;
1352         struct md_op_data *op_data;
1353         int rc, lmmsize;
1354
1355         rc = ll_get_default_mdsize(sbi, &lmmsize);
1356         if (rc)
1357                 RETURN(rc);
1358
1359         op_data = ll_prep_md_op_data(NULL, inode, NULL, filename,
1360                                      strlen(filename), lmmsize,
1361                                      LUSTRE_OPC_ANY, NULL);
1362         if (IS_ERR(op_data))
1363                 RETURN(PTR_ERR(op_data));
1364
1365         op_data->op_valid = OBD_MD_FLEASIZE | OBD_MD_FLDIREA;
1366         rc = md_getattr_name(sbi->ll_md_exp, op_data, &req);
1367         ll_finish_md_op_data(op_data);
1368         if (rc < 0) {
1369                 CDEBUG(D_INFO, "md_getattr_name failed "
1370                        "on %s: rc %d\n", filename, rc);
1371                 GOTO(out, rc);
1372         }
1373
1374         body = req_capsule_server_get(&req->rq_pill, &RMF_MDT_BODY);
1375         LASSERT(body != NULL); /* checked by mdc_getattr_name */
1376
1377         lmmsize = body->mbo_eadatasize;
1378
1379         if (!(body->mbo_valid & (OBD_MD_FLEASIZE | OBD_MD_FLDIREA)) ||
1380                         lmmsize == 0) {
1381                 GOTO(out, rc = -ENODATA);
1382         }
1383
1384         lmm = req_capsule_server_sized_get(&req->rq_pill, &RMF_MDT_MD, lmmsize);
1385         LASSERT(lmm != NULL);
1386
1387         if ((lmm->lmm_magic != cpu_to_le32(LOV_MAGIC_V1)) &&
1388             (lmm->lmm_magic != cpu_to_le32(LOV_MAGIC_V3))) {
1389                 GOTO(out, rc = -EPROTO);
1390         }
1391
1392         /*
1393          * This is coming from the MDS, so is probably in
1394          * little endian.  We convert it to host endian before
1395          * passing it to userspace.
1396          */
1397         if (LOV_MAGIC != cpu_to_le32(LOV_MAGIC)) {
1398                 int stripe_count;
1399
1400                 stripe_count = le16_to_cpu(lmm->lmm_stripe_count);
1401                 if (le32_to_cpu(lmm->lmm_pattern) & LOV_PATTERN_F_RELEASED)
1402                         stripe_count = 0;
1403
1404                 /* if function called for directory - we should
1405                  * avoid swab not existent lsm objects */
1406                 if (lmm->lmm_magic == cpu_to_le32(LOV_MAGIC_V1)) {
1407                         lustre_swab_lov_user_md_v1((struct lov_user_md_v1 *)lmm);
1408                         if (S_ISREG(body->mbo_mode))
1409                                 lustre_swab_lov_user_md_objects(
1410                                     ((struct lov_user_md_v1 *)lmm)->lmm_objects,
1411                                     stripe_count);
1412                 } else if (lmm->lmm_magic == cpu_to_le32(LOV_MAGIC_V3)) {
1413                         lustre_swab_lov_user_md_v3(
1414                                 (struct lov_user_md_v3 *)lmm);
1415                         if (S_ISREG(body->mbo_mode))
1416                                 lustre_swab_lov_user_md_objects(
1417                                  ((struct lov_user_md_v3 *)lmm)->lmm_objects,
1418                                  stripe_count);
1419                 }
1420         }
1421
1422 out:
1423         *lmmp = lmm;
1424         *lmm_size = lmmsize;
1425         *request = req;
1426         return rc;
1427 }
1428
1429 static int ll_lov_setea(struct inode *inode, struct file *file,
1430                             unsigned long arg)
1431 {
1432         __u64                    flags = MDS_OPEN_HAS_OBJS | FMODE_WRITE;
1433         struct lov_user_md      *lump;
1434         int                      lum_size = sizeof(struct lov_user_md) +
1435                                             sizeof(struct lov_user_ost_data);
1436         int                      rc;
1437         ENTRY;
1438
1439         if (!cfs_capable(CFS_CAP_SYS_ADMIN))
1440                 RETURN(-EPERM);
1441
1442         OBD_ALLOC_LARGE(lump, lum_size);
1443         if (lump == NULL)
1444                 RETURN(-ENOMEM);
1445
1446         if (copy_from_user(lump, (struct lov_user_md __user *)arg, lum_size)) {
1447                 OBD_FREE_LARGE(lump, lum_size);
1448                 RETURN(-EFAULT);
1449         }
1450
1451         rc = ll_lov_setstripe_ea_info(inode, file, flags, lump, lum_size);
1452
1453         OBD_FREE_LARGE(lump, lum_size);
1454         RETURN(rc);
1455 }
1456
1457 static int ll_file_getstripe(struct inode *inode,
1458                              struct lov_user_md __user *lum)
1459 {
1460         struct lu_env   *env;
1461         int             refcheck;
1462         int             rc;
1463         ENTRY;
1464
1465         env = cl_env_get(&refcheck);
1466         if (IS_ERR(env))
1467                 RETURN(PTR_ERR(env));
1468
1469         rc = cl_object_getstripe(env, ll_i2info(inode)->lli_clob, lum);
1470         cl_env_put(env, &refcheck);
1471         RETURN(rc);
1472 }
1473
1474 static int ll_lov_setstripe(struct inode *inode, struct file *file,
1475                             unsigned long arg)
1476 {
1477         struct lov_user_md __user *lum = (struct lov_user_md __user *)arg;
1478         struct lov_user_md        *klum;
1479         int                        lum_size, rc;
1480         __u64                      flags = FMODE_WRITE;
1481         ENTRY;
1482
1483         rc = ll_copy_user_md(lum, &klum);
1484         if (rc < 0)
1485                 RETURN(rc);
1486
1487         lum_size = rc;
1488         rc = ll_lov_setstripe_ea_info(inode, file, flags, klum, lum_size);
1489         if (rc == 0) {
1490                 __u32 gen;
1491
1492                 put_user(0, &lum->lmm_stripe_count);
1493
1494                 ll_layout_refresh(inode, &gen);
1495                 rc = ll_file_getstripe(inode, (struct lov_user_md __user *)arg);
1496         }
1497
1498         OBD_FREE(klum, lum_size);
1499         RETURN(rc);
1500 }
1501
1502 static int
1503 ll_get_grouplock(struct inode *inode, struct file *file, unsigned long arg)
1504 {
1505         struct ll_inode_info   *lli = ll_i2info(inode);
1506         struct ll_file_data    *fd = LUSTRE_FPRIVATE(file);
1507         struct ll_grouplock     grouplock;
1508         int                     rc;
1509         ENTRY;
1510
1511         if (arg == 0) {
1512                 CWARN("group id for group lock must not be 0\n");
1513                 RETURN(-EINVAL);
1514         }
1515
1516         if (ll_file_nolock(file))
1517                 RETURN(-EOPNOTSUPP);
1518
1519         spin_lock(&lli->lli_lock);
1520         if (fd->fd_flags & LL_FILE_GROUP_LOCKED) {
1521                 CWARN("group lock already existed with gid %lu\n",
1522                       fd->fd_grouplock.lg_gid);
1523                 spin_unlock(&lli->lli_lock);
1524                 RETURN(-EINVAL);
1525         }
1526         LASSERT(fd->fd_grouplock.lg_lock == NULL);
1527         spin_unlock(&lli->lli_lock);
1528
1529         rc = cl_get_grouplock(ll_i2info(inode)->lli_clob,
1530                               arg, (file->f_flags & O_NONBLOCK), &grouplock);
1531         if (rc)
1532                 RETURN(rc);
1533
1534         spin_lock(&lli->lli_lock);
1535         if (fd->fd_flags & LL_FILE_GROUP_LOCKED) {
1536                 spin_unlock(&lli->lli_lock);
1537                 CERROR("another thread just won the race\n");
1538                 cl_put_grouplock(&grouplock);
1539                 RETURN(-EINVAL);
1540         }
1541
1542         fd->fd_flags |= LL_FILE_GROUP_LOCKED;
1543         fd->fd_grouplock = grouplock;
1544         spin_unlock(&lli->lli_lock);
1545
1546         CDEBUG(D_INFO, "group lock %lu obtained\n", arg);
1547         RETURN(0);
1548 }
1549
1550 static int ll_put_grouplock(struct inode *inode, struct file *file,
1551                             unsigned long arg)
1552 {
1553         struct ll_inode_info   *lli = ll_i2info(inode);
1554         struct ll_file_data    *fd = LUSTRE_FPRIVATE(file);
1555         struct ll_grouplock     grouplock;
1556         ENTRY;
1557
1558         spin_lock(&lli->lli_lock);
1559         if (!(fd->fd_flags & LL_FILE_GROUP_LOCKED)) {
1560                 spin_unlock(&lli->lli_lock);
1561                 CWARN("no group lock held\n");
1562                 RETURN(-EINVAL);
1563         }
1564
1565         LASSERT(fd->fd_grouplock.lg_lock != NULL);
1566
1567         if (fd->fd_grouplock.lg_gid != arg) {
1568                 CWARN("group lock %lu doesn't match current id %lu\n",
1569                       arg, fd->fd_grouplock.lg_gid);
1570                 spin_unlock(&lli->lli_lock);
1571                 RETURN(-EINVAL);
1572         }
1573
1574         grouplock = fd->fd_grouplock;
1575         memset(&fd->fd_grouplock, 0, sizeof(fd->fd_grouplock));
1576         fd->fd_flags &= ~LL_FILE_GROUP_LOCKED;
1577         spin_unlock(&lli->lli_lock);
1578
1579         cl_put_grouplock(&grouplock);
1580         CDEBUG(D_INFO, "group lock %lu released\n", arg);
1581         RETURN(0);
1582 }
1583
1584 /**
1585  * Close inode open handle
1586  *
1587  * \param dentry [in]     dentry which contains the inode
1588  * \param it     [in,out] intent which contains open info and result
1589  *
1590  * \retval 0     success
1591  * \retval <0    failure
1592  */
1593 int ll_release_openhandle(struct dentry *dentry, struct lookup_intent *it)
1594 {
1595         struct inode *inode = dentry->d_inode;
1596         struct obd_client_handle *och;
1597         int rc;
1598         ENTRY;
1599
1600         LASSERT(inode);
1601
1602         /* Root ? Do nothing. */
1603         if (dentry->d_inode->i_sb->s_root == dentry)
1604                 RETURN(0);
1605
1606         /* No open handle to close? Move away */
1607         if (!it_disposition(it, DISP_OPEN_OPEN))
1608                 RETURN(0);
1609
1610         LASSERT(it_open_error(DISP_OPEN_OPEN, it) == 0);
1611
1612         OBD_ALLOC(och, sizeof(*och));
1613         if (!och)
1614                 GOTO(out, rc = -ENOMEM);
1615
1616         ll_och_fill(ll_i2sbi(inode)->ll_md_exp, it, och);
1617
1618         rc = ll_close_inode_openhandle(ll_i2sbi(inode)->ll_md_exp,
1619                                        inode, och, NULL);
1620 out:
1621         /* this one is in place of ll_file_open */
1622         if (it_disposition(it, DISP_ENQ_OPEN_REF)) {
1623                 ptlrpc_req_finished(it->d.lustre.it_data);
1624                 it_clear_disposition(it, DISP_ENQ_OPEN_REF);
1625         }
1626         RETURN(rc);
1627 }
1628
1629 /**
1630  * Get size for inode for which FIEMAP mapping is requested.
1631  * Make the FIEMAP get_info call and returns the result.
1632  * \param fiemap        kernel buffer to hold extens
1633  * \param num_bytes     kernel buffer size
1634  */
1635 static int ll_do_fiemap(struct inode *inode, struct fiemap *fiemap,
1636                         size_t num_bytes)
1637 {
1638         struct lu_env                   *env;
1639         int                             refcheck;
1640         int                             rc = 0;
1641         struct ll_fiemap_info_key       fmkey = { .name = KEY_FIEMAP, };
1642         ENTRY;
1643
1644         /* Checks for fiemap flags */
1645         if (fiemap->fm_flags & ~LUSTRE_FIEMAP_FLAGS_COMPAT) {
1646                 fiemap->fm_flags &= ~LUSTRE_FIEMAP_FLAGS_COMPAT;
1647                 return -EBADR;
1648         }
1649
1650         /* Check for FIEMAP_FLAG_SYNC */
1651         if (fiemap->fm_flags & FIEMAP_FLAG_SYNC) {
1652                 rc = filemap_fdatawrite(inode->i_mapping);
1653                 if (rc)
1654                         return rc;
1655         }
1656
1657         env = cl_env_get(&refcheck);
1658         if (IS_ERR(env))
1659                 RETURN(PTR_ERR(env));
1660
1661         if (i_size_read(inode) == 0) {
1662                 rc = ll_glimpse_size(inode);
1663                 if (rc)
1664                         GOTO(out, rc);
1665         }
1666
1667         fmkey.oa.o_valid = OBD_MD_FLID | OBD_MD_FLGROUP;
1668         obdo_from_inode(&fmkey.oa, inode, OBD_MD_FLSIZE);
1669         obdo_set_parent_fid(&fmkey.oa, &ll_i2info(inode)->lli_fid);
1670
1671         /* If filesize is 0, then there would be no objects for mapping */
1672         if (fmkey.oa.o_size == 0) {
1673                 fiemap->fm_mapped_extents = 0;
1674                 GOTO(out, rc = 0);
1675         }
1676
1677         fmkey.fiemap = *fiemap;
1678
1679         rc = cl_object_fiemap(env, ll_i2info(inode)->lli_clob,
1680                               &fmkey, fiemap, &num_bytes);
1681 out:
1682         cl_env_put(env, &refcheck);
1683         RETURN(rc);
1684 }
1685
1686 int ll_fid2path(struct inode *inode, void __user *arg)
1687 {
1688         struct obd_export       *exp = ll_i2mdexp(inode);
1689         const struct getinfo_fid2path __user *gfin = arg;
1690         __u32                    pathlen;
1691         struct getinfo_fid2path *gfout;
1692         size_t                   outsize;
1693         int                      rc;
1694
1695         ENTRY;
1696
1697         if (!cfs_capable(CFS_CAP_DAC_READ_SEARCH) &&
1698             !(ll_i2sbi(inode)->ll_flags & LL_SBI_USER_FID2PATH))
1699                 RETURN(-EPERM);
1700
1701         /* Only need to get the buflen */
1702         if (get_user(pathlen, &gfin->gf_pathlen))
1703                 RETURN(-EFAULT);
1704
1705         if (pathlen > PATH_MAX)
1706                 RETURN(-EINVAL);
1707
1708         outsize = sizeof(*gfout) + pathlen;
1709         OBD_ALLOC(gfout, outsize);
1710         if (gfout == NULL)
1711                 RETURN(-ENOMEM);
1712
1713         if (copy_from_user(gfout, arg, sizeof(*gfout)))
1714                 GOTO(gf_free, rc = -EFAULT);
1715
1716         /* Call mdc_iocontrol */
1717         rc = obd_iocontrol(OBD_IOC_FID2PATH, exp, outsize, gfout, NULL);
1718         if (rc != 0)
1719                 GOTO(gf_free, rc);
1720
1721         if (copy_to_user(arg, gfout, outsize))
1722                 rc = -EFAULT;
1723
1724 gf_free:
1725         OBD_FREE(gfout, outsize);
1726         RETURN(rc);
1727 }
1728
1729 static int ll_ioctl_fiemap(struct inode *inode, struct fiemap __user *arg)
1730 {
1731         struct fiemap   *fiemap;
1732         size_t          num_bytes;
1733         size_t          ret_bytes;
1734         __u32           extent_count;
1735         int             rc = 0;
1736
1737         /* Get the extent count so we can calculate the size of
1738          * required fiemap buffer */
1739         if (get_user(extent_count, &arg->fm_extent_count))
1740                 RETURN(-EFAULT);
1741
1742         if (extent_count >=
1743             (SIZE_MAX - sizeof(*fiemap)) / sizeof(struct ll_fiemap_extent))
1744                 RETURN(-EINVAL);
1745         num_bytes = sizeof(*fiemap) + (extent_count *
1746                                        sizeof(struct ll_fiemap_extent));
1747
1748         OBD_ALLOC_LARGE(fiemap, num_bytes);
1749         if (fiemap == NULL)
1750                 RETURN(-ENOMEM);
1751
1752         /* get the fiemap value */
1753         if (copy_from_user(fiemap, arg, sizeof(*fiemap)))
1754                 GOTO(error, rc = -EFAULT);
1755
1756         /* If fm_extent_count is non-zero, read the first extent since
1757          * it is used to calculate end_offset and device from previous
1758          * fiemap call. */
1759         if (extent_count != 0) {
1760                 if (copy_from_user(&fiemap->fm_extents[0],
1761                                    (char __user *)arg + sizeof(*fiemap),
1762                                    sizeof(struct ll_fiemap_extent)))
1763                         GOTO(error, rc = -EFAULT);
1764         }
1765
1766         rc = ll_do_fiemap(inode, fiemap, num_bytes);
1767         if (rc)
1768                 GOTO(error, rc);
1769
1770         ret_bytes = sizeof(struct fiemap);
1771
1772         if (extent_count != 0)
1773                 ret_bytes += (fiemap->fm_mapped_extents *
1774                                  sizeof(struct ll_fiemap_extent));
1775
1776         if (copy_to_user((void __user *)arg, fiemap, ret_bytes))
1777                 rc = -EFAULT;
1778
1779 error:
1780         OBD_FREE_LARGE(fiemap, num_bytes);
1781         RETURN(rc);
1782 }
1783
1784 /*
1785  * Read the data_version for inode.
1786  *
1787  * This value is computed using stripe object version on OST.
1788  * Version is computed using server side locking.
1789  *
1790  * @param flags if do sync on the OST side;
1791  *              0: no sync
1792  *              LL_DV_RD_FLUSH: flush dirty pages, LCK_PR on OSTs
1793  *              LL_DV_WR_FLUSH: drop all caching pages, LCK_PW on OSTs
1794  */
1795 int ll_data_version(struct inode *inode, __u64 *data_version, int flags)
1796 {
1797         struct lu_env   *env;
1798         int             refcheck;
1799         int             rc;
1800         ENTRY;
1801
1802         /* If no file object initialized, we consider its version is 0. */
1803         if (ll_i2info(inode)->lli_clob == NULL) {
1804                 *data_version = 0;
1805                 RETURN(0);
1806         }
1807
1808         env = cl_env_get(&refcheck);
1809         if (IS_ERR(env))
1810                 RETURN(PTR_ERR(env));
1811
1812         rc = cl_object_data_version(env, ll_i2info(inode)->lli_clob,
1813                                     data_version, flags);
1814         cl_env_put(env, &refcheck);
1815         RETURN(rc);
1816 }
1817
1818 /*
1819  * Trigger a HSM release request for the provided inode.
1820  */
1821 int ll_hsm_release(struct inode *inode)
1822 {
1823         struct cl_env_nest nest;
1824         struct lu_env *env;
1825         struct obd_client_handle *och = NULL;
1826         __u64 data_version = 0;
1827         int rc;
1828         ENTRY;
1829
1830         CDEBUG(D_INODE, "%s: Releasing file "DFID".\n",
1831                ll_get_fsname(inode->i_sb, NULL, 0),
1832                PFID(&ll_i2info(inode)->lli_fid));
1833
1834         och = ll_lease_open(inode, NULL, FMODE_WRITE, MDS_OPEN_RELEASE);
1835         if (IS_ERR(och))
1836                 GOTO(out, rc = PTR_ERR(och));
1837
1838         /* Grab latest data_version and [am]time values */
1839         rc = ll_data_version(inode, &data_version, LL_DV_WR_FLUSH);
1840         if (rc != 0)
1841                 GOTO(out, rc);
1842
1843         env = cl_env_nested_get(&nest);
1844         if (IS_ERR(env))
1845                 GOTO(out, rc = PTR_ERR(env));
1846
1847         ll_merge_attr(env, inode);
1848         cl_env_nested_put(&nest, env);
1849
1850         /* Release the file.
1851          * NB: lease lock handle is released in mdc_hsm_release_pack() because
1852          * we still need it to pack l_remote_handle to MDT. */
1853         rc = ll_close_inode_openhandle(ll_i2sbi(inode)->ll_md_exp, inode, och,
1854                                        &data_version);
1855         och = NULL;
1856
1857         EXIT;
1858 out:
1859         if (och != NULL && !IS_ERR(och)) /* close the file */
1860                 ll_lease_close(och, inode, NULL);
1861
1862         return rc;
1863 }
1864
1865 struct ll_swap_stack {
1866         struct iattr             ia1, ia2;
1867         __u64                    dv1, dv2;
1868         struct inode            *inode1, *inode2;
1869         bool                     check_dv1, check_dv2;
1870 };
1871
1872 static int ll_swap_layouts(struct file *file1, struct file *file2,
1873                            struct lustre_swap_layouts *lsl)
1874 {
1875         struct mdc_swap_layouts  msl;
1876         struct md_op_data       *op_data;
1877         __u32                    gid;
1878         __u64                    dv;
1879         struct ll_swap_stack    *llss = NULL;
1880         int                      rc;
1881
1882         OBD_ALLOC_PTR(llss);
1883         if (llss == NULL)
1884                 RETURN(-ENOMEM);
1885
1886         llss->inode1 = file1->f_dentry->d_inode;
1887         llss->inode2 = file2->f_dentry->d_inode;
1888
1889         if (!S_ISREG(llss->inode2->i_mode))
1890                 GOTO(free, rc = -EINVAL);
1891
1892         if (inode_permission(llss->inode1, MAY_WRITE) ||
1893             inode_permission(llss->inode2, MAY_WRITE))
1894                 GOTO(free, rc = -EPERM);
1895
1896         if (llss->inode2->i_sb != llss->inode1->i_sb)
1897                 GOTO(free, rc = -EXDEV);
1898
1899         /* we use 2 bool because it is easier to swap than 2 bits */
1900         if (lsl->sl_flags & SWAP_LAYOUTS_CHECK_DV1)
1901                 llss->check_dv1 = true;
1902
1903         if (lsl->sl_flags & SWAP_LAYOUTS_CHECK_DV2)
1904                 llss->check_dv2 = true;
1905
1906         /* we cannot use lsl->sl_dvX directly because we may swap them */
1907         llss->dv1 = lsl->sl_dv1;
1908         llss->dv2 = lsl->sl_dv2;
1909
1910         rc = lu_fid_cmp(ll_inode2fid(llss->inode1), ll_inode2fid(llss->inode2));
1911         if (rc == 0) /* same file, done! */
1912                 GOTO(free, rc = 0);
1913
1914         if (rc < 0) { /* sequentialize it */
1915                 swap(llss->inode1, llss->inode2);
1916                 swap(file1, file2);
1917                 swap(llss->dv1, llss->dv2);
1918                 swap(llss->check_dv1, llss->check_dv2);
1919         }
1920
1921         gid = lsl->sl_gid;
1922         if (gid != 0) { /* application asks to flush dirty cache */
1923                 rc = ll_get_grouplock(llss->inode1, file1, gid);
1924                 if (rc < 0)
1925                         GOTO(free, rc);
1926
1927                 rc = ll_get_grouplock(llss->inode2, file2, gid);
1928                 if (rc < 0) {
1929                         ll_put_grouplock(llss->inode1, file1, gid);
1930                         GOTO(free, rc);
1931                 }
1932         }
1933
1934         /* to be able to restore mtime and atime after swap
1935          * we need to first save them */
1936         if (lsl->sl_flags &
1937             (SWAP_LAYOUTS_KEEP_MTIME | SWAP_LAYOUTS_KEEP_ATIME)) {
1938                 llss->ia1.ia_mtime = llss->inode1->i_mtime;
1939                 llss->ia1.ia_atime = llss->inode1->i_atime;
1940                 llss->ia1.ia_valid = ATTR_MTIME | ATTR_ATIME;
1941                 llss->ia2.ia_mtime = llss->inode2->i_mtime;
1942                 llss->ia2.ia_atime = llss->inode2->i_atime;
1943                 llss->ia2.ia_valid = ATTR_MTIME | ATTR_ATIME;
1944         }
1945
1946         /* ultimate check, before swaping the layouts we check if
1947          * dataversion has changed (if requested) */
1948         if (llss->check_dv1) {
1949                 rc = ll_data_version(llss->inode1, &dv, 0);
1950                 if (rc)
1951                         GOTO(putgl, rc);
1952                 if (dv != llss->dv1)
1953                         GOTO(putgl, rc = -EAGAIN);
1954         }
1955
1956         if (llss->check_dv2) {
1957                 rc = ll_data_version(llss->inode2, &dv, 0);
1958                 if (rc)
1959                         GOTO(putgl, rc);
1960                 if (dv != llss->dv2)
1961                         GOTO(putgl, rc = -EAGAIN);
1962         }
1963
1964         /* struct md_op_data is used to send the swap args to the mdt
1965          * only flags is missing, so we use struct mdc_swap_layouts
1966          * through the md_op_data->op_data */
1967         /* flags from user space have to be converted before they are send to
1968          * server, no flag is sent today, they are only used on the client */
1969         msl.msl_flags = 0;
1970         rc = -ENOMEM;
1971         op_data = ll_prep_md_op_data(NULL, llss->inode1, llss->inode2, NULL, 0,
1972                                      0, LUSTRE_OPC_ANY, &msl);
1973         if (IS_ERR(op_data))
1974                 GOTO(free, rc = PTR_ERR(op_data));
1975
1976         rc = obd_iocontrol(LL_IOC_LOV_SWAP_LAYOUTS, ll_i2mdexp(llss->inode1),
1977                            sizeof(*op_data), op_data, NULL);
1978         ll_finish_md_op_data(op_data);
1979
1980 putgl:
1981         if (gid != 0) {
1982                 ll_put_grouplock(llss->inode2, file2, gid);
1983                 ll_put_grouplock(llss->inode1, file1, gid);
1984         }
1985
1986         /* rc can be set from obd_iocontrol() or from a GOTO(putgl, ...) */
1987         if (rc != 0)
1988                 GOTO(free, rc);
1989
1990         /* clear useless flags */
1991         if (!(lsl->sl_flags & SWAP_LAYOUTS_KEEP_MTIME)) {
1992                 llss->ia1.ia_valid &= ~ATTR_MTIME;
1993                 llss->ia2.ia_valid &= ~ATTR_MTIME;
1994         }
1995
1996         if (!(lsl->sl_flags & SWAP_LAYOUTS_KEEP_ATIME)) {
1997                 llss->ia1.ia_valid &= ~ATTR_ATIME;
1998                 llss->ia2.ia_valid &= ~ATTR_ATIME;
1999         }
2000
2001         /* update time if requested */
2002         rc = 0;
2003         if (llss->ia2.ia_valid != 0) {
2004                 mutex_lock(&llss->inode1->i_mutex);
2005                 rc = ll_setattr(file1->f_dentry, &llss->ia2);
2006                 mutex_unlock(&llss->inode1->i_mutex);
2007         }
2008
2009         if (llss->ia1.ia_valid != 0) {
2010                 int rc1;
2011
2012                 mutex_lock(&llss->inode2->i_mutex);
2013                 rc1 = ll_setattr(file2->f_dentry, &llss->ia1);
2014                 mutex_unlock(&llss->inode2->i_mutex);
2015                 if (rc == 0)
2016                         rc = rc1;
2017         }
2018
2019 free:
2020         if (llss != NULL)
2021                 OBD_FREE_PTR(llss);
2022
2023         RETURN(rc);
2024 }
2025
2026 static int ll_hsm_state_set(struct inode *inode, struct hsm_state_set *hss)
2027 {
2028         struct md_op_data       *op_data;
2029         int                      rc;
2030         ENTRY;
2031
2032         /* Detect out-of range masks */
2033         if ((hss->hss_setmask | hss->hss_clearmask) & ~HSM_FLAGS_MASK)
2034                 RETURN(-EINVAL);
2035
2036         /* Non-root users are forbidden to set or clear flags which are
2037          * NOT defined in HSM_USER_MASK. */
2038         if (((hss->hss_setmask | hss->hss_clearmask) & ~HSM_USER_MASK) &&
2039             !cfs_capable(CFS_CAP_SYS_ADMIN))
2040                 RETURN(-EPERM);
2041
2042         /* Detect out-of range archive id */
2043         if ((hss->hss_valid & HSS_ARCHIVE_ID) &&
2044             (hss->hss_archive_id > LL_HSM_MAX_ARCHIVE))
2045                 RETURN(-EINVAL);
2046
2047         op_data = ll_prep_md_op_data(NULL, inode, NULL, NULL, 0, 0,
2048                                      LUSTRE_OPC_ANY, hss);
2049         if (IS_ERR(op_data))
2050                 RETURN(PTR_ERR(op_data));
2051
2052         rc = obd_iocontrol(LL_IOC_HSM_STATE_SET, ll_i2mdexp(inode),
2053                            sizeof(*op_data), op_data, NULL);
2054
2055         ll_finish_md_op_data(op_data);
2056
2057         RETURN(rc);
2058 }
2059
2060 static int ll_hsm_import(struct inode *inode, struct file *file,
2061                          struct hsm_user_import *hui)
2062 {
2063         struct hsm_state_set    *hss = NULL;
2064         struct iattr            *attr = NULL;
2065         int                      rc;
2066         ENTRY;
2067
2068         if (!S_ISREG(inode->i_mode))
2069                 RETURN(-EINVAL);
2070
2071         /* set HSM flags */
2072         OBD_ALLOC_PTR(hss);
2073         if (hss == NULL)
2074                 GOTO(out, rc = -ENOMEM);
2075
2076         hss->hss_valid = HSS_SETMASK | HSS_ARCHIVE_ID;
2077         hss->hss_archive_id = hui->hui_archive_id;
2078         hss->hss_setmask = HS_ARCHIVED | HS_EXISTS | HS_RELEASED;
2079         rc = ll_hsm_state_set(inode, hss);
2080         if (rc != 0)
2081                 GOTO(out, rc);
2082
2083         OBD_ALLOC_PTR(attr);
2084         if (attr == NULL)
2085                 GOTO(out, rc = -ENOMEM);
2086
2087         attr->ia_mode = hui->hui_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
2088         attr->ia_mode |= S_IFREG;
2089         attr->ia_uid = make_kuid(&init_user_ns, hui->hui_uid);
2090         attr->ia_gid = make_kgid(&init_user_ns, hui->hui_gid);
2091         attr->ia_size = hui->hui_size;
2092         attr->ia_mtime.tv_sec = hui->hui_mtime;
2093         attr->ia_mtime.tv_nsec = hui->hui_mtime_ns;
2094         attr->ia_atime.tv_sec = hui->hui_atime;
2095         attr->ia_atime.tv_nsec = hui->hui_atime_ns;
2096
2097         attr->ia_valid = ATTR_SIZE | ATTR_MODE | ATTR_FORCE |
2098                          ATTR_UID | ATTR_GID |
2099                          ATTR_MTIME | ATTR_MTIME_SET |
2100                          ATTR_ATIME | ATTR_ATIME_SET;
2101
2102         mutex_lock(&inode->i_mutex);
2103
2104         rc = ll_setattr_raw(file->f_dentry, attr, true);
2105         if (rc == -ENODATA)
2106                 rc = 0;
2107
2108         mutex_unlock(&inode->i_mutex);
2109
2110 out:
2111         if (hss != NULL)
2112                 OBD_FREE_PTR(hss);
2113
2114         if (attr != NULL)
2115                 OBD_FREE_PTR(attr);
2116
2117         RETURN(rc);
2118 }
2119
2120 static inline long ll_lease_type_from_fmode(fmode_t fmode)
2121 {
2122         return ((fmode & FMODE_READ) ? LL_LEASE_RDLCK : 0) |
2123                ((fmode & FMODE_WRITE) ? LL_LEASE_WRLCK : 0);
2124 }
2125
2126 static long
2127 ll_file_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
2128 {
2129         struct inode            *inode = file->f_dentry->d_inode;
2130         struct ll_file_data     *fd = LUSTRE_FPRIVATE(file);
2131         int                      flags, rc;
2132         ENTRY;
2133
2134         CDEBUG(D_VFSTRACE, "VFS Op:inode="DFID"(%p), cmd=%x\n",
2135                PFID(ll_inode2fid(inode)), inode, cmd);
2136         ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_IOCTL, 1);
2137
2138         /* asm-ppc{,64} declares TCGETS, et. al. as type 't' not 'T' */
2139         if (_IOC_TYPE(cmd) == 'T' || _IOC_TYPE(cmd) == 't') /* tty ioctls */
2140                 RETURN(-ENOTTY);
2141
2142         switch(cmd) {
2143         case LL_IOC_GETFLAGS:
2144                 /* Get the current value of the file flags */
2145                 return put_user(fd->fd_flags, (int __user *)arg);
2146         case LL_IOC_SETFLAGS:
2147         case LL_IOC_CLRFLAGS:
2148                 /* Set or clear specific file flags */
2149                 /* XXX This probably needs checks to ensure the flags are
2150                  *     not abused, and to handle any flag side effects.
2151                  */
2152                 if (get_user(flags, (int __user *) arg))
2153                         RETURN(-EFAULT);
2154
2155                 if (cmd == LL_IOC_SETFLAGS) {
2156                         if ((flags & LL_FILE_IGNORE_LOCK) &&
2157                             !(file->f_flags & O_DIRECT)) {
2158                                 CERROR("%s: unable to disable locking on "
2159                                        "non-O_DIRECT file\n", current->comm);
2160                                 RETURN(-EINVAL);
2161                         }
2162
2163                         fd->fd_flags |= flags;
2164                 } else {
2165                         fd->fd_flags &= ~flags;
2166                 }
2167                 RETURN(0);
2168         case LL_IOC_LOV_SETSTRIPE:
2169                 RETURN(ll_lov_setstripe(inode, file, arg));
2170         case LL_IOC_LOV_SETEA:
2171                 RETURN(ll_lov_setea(inode, file, arg));
2172         case LL_IOC_LOV_SWAP_LAYOUTS: {
2173                 struct file *file2;
2174                 struct lustre_swap_layouts lsl;
2175
2176                 if (copy_from_user(&lsl, (char __user *)arg,
2177                                        sizeof(struct lustre_swap_layouts)))
2178                         RETURN(-EFAULT);
2179
2180                 if ((file->f_flags & O_ACCMODE) == 0) /* O_RDONLY */
2181                         RETURN(-EPERM);
2182
2183                 file2 = fget(lsl.sl_fd);
2184                 if (file2 == NULL)
2185                         RETURN(-EBADF);
2186
2187                 rc = -EPERM;
2188                 if ((file2->f_flags & O_ACCMODE) != 0) /* O_WRONLY or O_RDWR */
2189                         rc = ll_swap_layouts(file, file2, &lsl);
2190                 fput(file2);
2191                 RETURN(rc);
2192         }
2193         case LL_IOC_LOV_GETSTRIPE:
2194                 RETURN(ll_file_getstripe(inode,
2195                                          (struct lov_user_md __user *)arg));
2196         case FSFILT_IOC_FIEMAP:
2197                 RETURN(ll_ioctl_fiemap(inode, (struct fiemap __user *)arg));
2198         case FSFILT_IOC_GETFLAGS:
2199         case FSFILT_IOC_SETFLAGS:
2200                 RETURN(ll_iocontrol(inode, file, cmd, arg));
2201         case FSFILT_IOC_GETVERSION_OLD:
2202         case FSFILT_IOC_GETVERSION:
2203                 RETURN(put_user(inode->i_generation, (int __user *)arg));
2204         case LL_IOC_GROUP_LOCK:
2205                 RETURN(ll_get_grouplock(inode, file, arg));
2206         case LL_IOC_GROUP_UNLOCK:
2207                 RETURN(ll_put_grouplock(inode, file, arg));
2208         case IOC_OBD_STATFS:
2209                 RETURN(ll_obd_statfs(inode, (void __user *)arg));
2210
2211         /* We need to special case any other ioctls we want to handle,
2212          * to send them to the MDS/OST as appropriate and to properly
2213          * network encode the arg field.
2214         case FSFILT_IOC_SETVERSION_OLD:
2215         case FSFILT_IOC_SETVERSION:
2216         */
2217         case LL_IOC_FLUSHCTX:
2218                 RETURN(ll_flush_ctx(inode));
2219         case LL_IOC_PATH2FID: {
2220                 if (copy_to_user((void __user *)arg, ll_inode2fid(inode),
2221                                  sizeof(struct lu_fid)))
2222                         RETURN(-EFAULT);
2223
2224                 RETURN(0);
2225         }
2226         case LL_IOC_GETPARENT:
2227                 RETURN(ll_getparent(file, (struct getparent __user *)arg));
2228
2229         case OBD_IOC_FID2PATH:
2230                 RETURN(ll_fid2path(inode, (void __user *)arg));
2231         case LL_IOC_DATA_VERSION: {
2232                 struct ioc_data_version idv;
2233                 int rc;
2234
2235                 if (copy_from_user(&idv, (char __user *)arg, sizeof(idv)))
2236                         RETURN(-EFAULT);
2237
2238                 idv.idv_flags &= LL_DV_RD_FLUSH | LL_DV_WR_FLUSH;
2239                 rc = ll_data_version(inode, &idv.idv_version, idv.idv_flags);
2240
2241                 if (rc == 0 &&
2242                     copy_to_user((char __user *)arg, &idv, sizeof(idv)))
2243                         RETURN(-EFAULT);
2244
2245                 RETURN(rc);
2246         }
2247
2248         case LL_IOC_GET_MDTIDX: {
2249                 int mdtidx;
2250
2251                 mdtidx = ll_get_mdt_idx(inode);
2252                 if (mdtidx < 0)
2253                         RETURN(mdtidx);
2254
2255                 if (put_user((int)mdtidx, (int __user *)arg))
2256                         RETURN(-EFAULT);
2257
2258                 RETURN(0);
2259         }
2260         case OBD_IOC_GETDTNAME:
2261         case OBD_IOC_GETMDNAME:
2262                 RETURN(ll_get_obd_name(inode, cmd, arg));
2263         case LL_IOC_HSM_STATE_GET: {
2264                 struct md_op_data       *op_data;
2265                 struct hsm_user_state   *hus;
2266                 int                      rc;
2267
2268                 OBD_ALLOC_PTR(hus);
2269                 if (hus == NULL)
2270                         RETURN(-ENOMEM);
2271
2272                 op_data = ll_prep_md_op_data(NULL, inode, NULL, NULL, 0, 0,
2273                                              LUSTRE_OPC_ANY, hus);
2274                 if (IS_ERR(op_data)) {
2275                         OBD_FREE_PTR(hus);
2276                         RETURN(PTR_ERR(op_data));
2277                 }
2278
2279                 rc = obd_iocontrol(cmd, ll_i2mdexp(inode), sizeof(*op_data),
2280                                    op_data, NULL);
2281
2282                 if (copy_to_user((void __user *)arg, hus, sizeof(*hus)))
2283                         rc = -EFAULT;
2284
2285                 ll_finish_md_op_data(op_data);
2286                 OBD_FREE_PTR(hus);
2287                 RETURN(rc);
2288         }
2289         case LL_IOC_HSM_STATE_SET: {
2290                 struct hsm_state_set    *hss;
2291                 int                      rc;
2292
2293                 OBD_ALLOC_PTR(hss);
2294                 if (hss == NULL)
2295                         RETURN(-ENOMEM);
2296
2297                 if (copy_from_user(hss, (char __user *)arg, sizeof(*hss))) {
2298                         OBD_FREE_PTR(hss);
2299                         RETURN(-EFAULT);
2300                 }
2301
2302                 rc = ll_hsm_state_set(inode, hss);
2303
2304                 OBD_FREE_PTR(hss);
2305                 RETURN(rc);
2306         }
2307         case LL_IOC_HSM_ACTION: {
2308                 struct md_op_data               *op_data;
2309                 struct hsm_current_action       *hca;
2310                 int                              rc;
2311
2312                 OBD_ALLOC_PTR(hca);
2313                 if (hca == NULL)
2314                         RETURN(-ENOMEM);
2315
2316                 op_data = ll_prep_md_op_data(NULL, inode, NULL, NULL, 0, 0,
2317                                              LUSTRE_OPC_ANY, hca);
2318                 if (IS_ERR(op_data)) {
2319                         OBD_FREE_PTR(hca);
2320                         RETURN(PTR_ERR(op_data));
2321                 }
2322
2323                 rc = obd_iocontrol(cmd, ll_i2mdexp(inode), sizeof(*op_data),
2324                                    op_data, NULL);
2325
2326                 if (copy_to_user((char __user *)arg, hca, sizeof(*hca)))
2327                         rc = -EFAULT;
2328
2329                 ll_finish_md_op_data(op_data);
2330                 OBD_FREE_PTR(hca);
2331                 RETURN(rc);
2332         }
2333         case LL_IOC_SET_LEASE: {
2334                 struct ll_inode_info *lli = ll_i2info(inode);
2335                 struct obd_client_handle *och = NULL;
2336                 bool lease_broken;
2337                 fmode_t fmode;
2338
2339                 switch (arg) {
2340                 case LL_LEASE_WRLCK:
2341                         if (!(file->f_mode & FMODE_WRITE))
2342                                 RETURN(-EPERM);
2343                         fmode = FMODE_WRITE;
2344                         break;
2345                 case LL_LEASE_RDLCK:
2346                         if (!(file->f_mode & FMODE_READ))
2347                                 RETURN(-EPERM);
2348                         fmode = FMODE_READ;
2349                         break;
2350                 case LL_LEASE_UNLCK:
2351                         mutex_lock(&lli->lli_och_mutex);
2352                         if (fd->fd_lease_och != NULL) {
2353                                 och = fd->fd_lease_och;
2354                                 fd->fd_lease_och = NULL;
2355                         }
2356                         mutex_unlock(&lli->lli_och_mutex);
2357
2358                         if (och == NULL)
2359                                 RETURN(-ENOLCK);
2360
2361                         fmode = och->och_flags;
2362                         rc = ll_lease_close(och, inode, &lease_broken);
2363                         if (rc < 0)
2364                                 RETURN(rc);
2365
2366                         if (lease_broken)
2367                                 fmode = 0;
2368
2369                         RETURN(ll_lease_type_from_fmode(fmode));
2370                 default:
2371                         RETURN(-EINVAL);
2372                 }
2373
2374                 CDEBUG(D_INODE, "Set lease with mode %u\n", fmode);
2375
2376                 /* apply for lease */
2377                 och = ll_lease_open(inode, file, fmode, 0);
2378                 if (IS_ERR(och))
2379                         RETURN(PTR_ERR(och));
2380
2381                 rc = 0;
2382                 mutex_lock(&lli->lli_och_mutex);
2383                 if (fd->fd_lease_och == NULL) {
2384                         fd->fd_lease_och = och;
2385                         och = NULL;
2386                 }
2387                 mutex_unlock(&lli->lli_och_mutex);
2388                 if (och != NULL) {
2389                         /* impossible now that only excl is supported for now */
2390                         ll_lease_close(och, inode, &lease_broken);
2391                         rc = -EBUSY;
2392                 }
2393                 RETURN(rc);
2394         }
2395         case LL_IOC_GET_LEASE: {
2396                 struct ll_inode_info *lli = ll_i2info(inode);
2397                 struct ldlm_lock *lock = NULL;
2398                 fmode_t fmode = 0;
2399
2400                 mutex_lock(&lli->lli_och_mutex);
2401                 if (fd->fd_lease_och != NULL) {
2402                         struct obd_client_handle *och = fd->fd_lease_och;
2403
2404                         lock = ldlm_handle2lock(&och->och_lease_handle);
2405                         if (lock != NULL) {
2406                                 lock_res_and_lock(lock);
2407                                 if (!ldlm_is_cancel(lock))
2408                                         fmode = och->och_flags;
2409
2410                                 unlock_res_and_lock(lock);
2411                                 LDLM_LOCK_PUT(lock);
2412                         }
2413                 }
2414                 mutex_unlock(&lli->lli_och_mutex);
2415
2416                 RETURN(ll_lease_type_from_fmode(fmode));
2417         }
2418         case LL_IOC_HSM_IMPORT: {
2419                 struct hsm_user_import *hui;
2420
2421                 OBD_ALLOC_PTR(hui);
2422                 if (hui == NULL)
2423                         RETURN(-ENOMEM);
2424
2425                 if (copy_from_user(hui, (void __user *)arg, sizeof(*hui))) {
2426                         OBD_FREE_PTR(hui);
2427                         RETURN(-EFAULT);
2428                 }
2429
2430                 rc = ll_hsm_import(inode, file, hui);
2431
2432                 OBD_FREE_PTR(hui);
2433                 RETURN(rc);
2434         }
2435
2436         default: {
2437                 int err;
2438
2439                 if (LLIOC_STOP ==
2440                      ll_iocontrol_call(inode, file, cmd, arg, &err))
2441                         RETURN(err);
2442
2443                 RETURN(obd_iocontrol(cmd, ll_i2dtexp(inode), 0, NULL,
2444                                      (void __user *)arg));
2445         }
2446         }
2447 }
2448
2449 #ifndef HAVE_FILE_LLSEEK_SIZE
2450 static inline loff_t
2451 llseek_execute(struct file *file, loff_t offset, loff_t maxsize)
2452 {
2453         if (offset < 0 && !(file->f_mode & FMODE_UNSIGNED_OFFSET))
2454                 return -EINVAL;
2455         if (offset > maxsize)
2456                 return -EINVAL;
2457
2458         if (offset != file->f_pos) {
2459                 file->f_pos = offset;
2460                 file->f_version = 0;
2461         }
2462         return offset;
2463 }
2464
2465 static loff_t
2466 generic_file_llseek_size(struct file *file, loff_t offset, int origin,
2467                 loff_t maxsize, loff_t eof)
2468 {
2469         struct inode *inode = file->f_dentry->d_inode;
2470
2471         switch (origin) {
2472         case SEEK_END:
2473                 offset += eof;
2474                 break;
2475         case SEEK_CUR:
2476                 /*
2477                  * Here we special-case the lseek(fd, 0, SEEK_CUR)
2478                  * position-querying operation.  Avoid rewriting the "same"
2479                  * f_pos value back to the file because a concurrent read(),
2480                  * write() or lseek() might have altered it
2481                  */
2482                 if (offset == 0)
2483                         return file->f_pos;
2484                 /*
2485                  * f_lock protects against read/modify/write race with other
2486                  * SEEK_CURs. Note that parallel writes and reads behave
2487                  * like SEEK_SET.
2488                  */
2489                 mutex_lock(&inode->i_mutex);
2490                 offset = llseek_execute(file, file->f_pos + offset, maxsize);
2491                 mutex_unlock(&inode->i_mutex);
2492                 return offset;
2493         case SEEK_DATA:
2494                 /*
2495                  * In the generic case the entire file is data, so as long as
2496                  * offset isn't at the end of the file then the offset is data.
2497                  */
2498                 if (offset >= eof)
2499                         return -ENXIO;
2500                 break;
2501         case SEEK_HOLE:
2502                 /*
2503                  * There is a virtual hole at the end of the file, so as long as
2504                  * offset isn't i_size or larger, return i_size.
2505                  */
2506                 if (offset >= eof)
2507                         return -ENXIO;
2508                 offset = eof;
2509                 break;
2510         }
2511
2512         return llseek_execute(file, offset, maxsize);
2513 }
2514 #endif
2515
2516 static loff_t ll_file_seek(struct file *file, loff_t offset, int origin)
2517 {
2518         struct inode *inode = file->f_dentry->d_inode;
2519         loff_t retval, eof = 0;
2520
2521         ENTRY;
2522         retval = offset + ((origin == SEEK_END) ? i_size_read(inode) :
2523                            (origin == SEEK_CUR) ? file->f_pos : 0);
2524         CDEBUG(D_VFSTRACE, "VFS Op:inode="DFID"(%p), to=%llu=%#llx(%d)\n",
2525                PFID(ll_inode2fid(inode)), inode, retval, retval,
2526                origin);
2527         ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_LLSEEK, 1);
2528
2529         if (origin == SEEK_END || origin == SEEK_HOLE || origin == SEEK_DATA) {
2530                 retval = ll_glimpse_size(inode);
2531                 if (retval != 0)
2532                         RETURN(retval);
2533                 eof = i_size_read(inode);
2534         }
2535
2536         retval = ll_generic_file_llseek_size(file, offset, origin,
2537                                           ll_file_maxbytes(inode), eof);
2538         RETURN(retval);
2539 }
2540
2541 static int ll_flush(struct file *file, fl_owner_t id)
2542 {
2543         struct inode *inode = file->f_dentry->d_inode;
2544         struct ll_inode_info *lli = ll_i2info(inode);
2545         struct ll_file_data *fd = LUSTRE_FPRIVATE(file);
2546         int rc, err;
2547
2548         LASSERT(!S_ISDIR(inode->i_mode));
2549
2550         /* catch async errors that were recorded back when async writeback
2551          * failed for pages in this mapping. */
2552         rc = lli->lli_async_rc;
2553         lli->lli_async_rc = 0;
2554         if (lli->lli_clob != NULL) {
2555                 err = lov_read_and_clear_async_rc(lli->lli_clob);
2556                 if (rc == 0)
2557                         rc = err;
2558         }
2559
2560         /* The application has been told write failure already.
2561          * Do not report failure again. */
2562         if (fd->fd_write_failed)
2563                 return 0;
2564         return rc ? -EIO : 0;
2565 }
2566
2567 /**
2568  * Called to make sure a portion of file has been written out.
2569  * if @mode is not CL_FSYNC_LOCAL, it will send OST_SYNC RPCs to OST.
2570  *
2571  * Return how many pages have been written.
2572  */
2573 int cl_sync_file_range(struct inode *inode, loff_t start, loff_t end,
2574                        enum cl_fsync_mode mode, int ignore_layout)
2575 {
2576         struct cl_env_nest nest;
2577         struct lu_env *env;
2578         struct cl_io *io;
2579         struct obd_capa *capa = NULL;
2580         struct cl_fsync_io *fio;
2581         int result;
2582         ENTRY;
2583
2584         if (mode != CL_FSYNC_NONE && mode != CL_FSYNC_LOCAL &&
2585             mode != CL_FSYNC_DISCARD && mode != CL_FSYNC_ALL)
2586                 RETURN(-EINVAL);
2587
2588         env = cl_env_nested_get(&nest);
2589         if (IS_ERR(env))
2590                 RETURN(PTR_ERR(env));
2591
2592         capa = ll_osscapa_get(inode, CAPA_OPC_OSS_WRITE);
2593
2594         io = vvp_env_thread_io(env);
2595         io->ci_obj = ll_i2info(inode)->lli_clob;
2596         io->ci_ignore_layout = ignore_layout;
2597
2598         /* initialize parameters for sync */
2599         fio = &io->u.ci_fsync;
2600         fio->fi_capa = capa;
2601         fio->fi_start = start;
2602         fio->fi_end = end;
2603         fio->fi_fid = ll_inode2fid(inode);
2604         fio->fi_mode = mode;
2605         fio->fi_nr_written = 0;
2606
2607         if (cl_io_init(env, io, CIT_FSYNC, io->ci_obj) == 0)
2608                 result = cl_io_loop(env, io);
2609         else
2610                 result = io->ci_result;
2611         if (result == 0)
2612                 result = fio->fi_nr_written;
2613         cl_io_fini(env, io);
2614         cl_env_nested_put(&nest, env);
2615
2616         capa_put(capa);
2617
2618         RETURN(result);
2619 }
2620
2621 /*
2622  * When dentry is provided (the 'else' case), *file->f_dentry may be
2623  * null and dentry must be used directly rather than pulled from
2624  * *file->f_dentry as is done otherwise.
2625  */
2626
2627 #ifdef HAVE_FILE_FSYNC_4ARGS
2628 int ll_fsync(struct file *file, loff_t start, loff_t end, int datasync)
2629 {
2630         struct dentry *dentry = file->f_dentry;
2631 #elif defined(HAVE_FILE_FSYNC_2ARGS)
2632 int ll_fsync(struct file *file, int datasync)
2633 {
2634         struct dentry *dentry = file->f_dentry;
2635         loff_t start = 0;
2636         loff_t end = LLONG_MAX;
2637 #else
2638 int ll_fsync(struct file *file, struct dentry *dentry, int datasync)
2639 {
2640         loff_t start = 0;
2641         loff_t end = LLONG_MAX;
2642 #endif
2643         struct inode *inode = dentry->d_inode;
2644         struct ll_inode_info *lli = ll_i2info(inode);
2645         struct ptlrpc_request *req;
2646         struct obd_capa *oc;
2647         int rc, err;
2648         ENTRY;
2649
2650         CDEBUG(D_VFSTRACE, "VFS Op:inode="DFID"(%p)\n",
2651                PFID(ll_inode2fid(inode)), inode);
2652         ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_FSYNC, 1);
2653
2654 #ifdef HAVE_FILE_FSYNC_4ARGS
2655         rc = filemap_write_and_wait_range(inode->i_mapping, start, end);
2656         mutex_lock(&inode->i_mutex);
2657 #else
2658         /* fsync's caller has already called _fdata{sync,write}, we want
2659          * that IO to finish before calling the osc and mdc sync methods */
2660         rc = filemap_fdatawait(inode->i_mapping);
2661 #endif
2662
2663         /* catch async errors that were recorded back when async writeback
2664          * failed for pages in this mapping. */
2665         if (!S_ISDIR(inode->i_mode)) {
2666                 err = lli->lli_async_rc;
2667                 lli->lli_async_rc = 0;
2668                 if (rc == 0)
2669                         rc = err;
2670                 err = lov_read_and_clear_async_rc(lli->lli_clob);
2671                 if (rc == 0)
2672                         rc = err;
2673         }
2674
2675         oc = ll_mdscapa_get(inode);
2676         err = md_fsync(ll_i2sbi(inode)->ll_md_exp, ll_inode2fid(inode), oc,
2677                        &req);
2678         capa_put(oc);
2679         if (!rc)
2680                 rc = err;
2681         if (!err)
2682                 ptlrpc_req_finished(req);
2683
2684         if (S_ISREG(inode->i_mode)) {
2685                 struct ll_file_data *fd = LUSTRE_FPRIVATE(file);
2686
2687                 err = cl_sync_file_range(inode, start, end, CL_FSYNC_ALL, 0);
2688                 if (rc == 0 && err < 0)
2689                         rc = err;
2690                 if (rc < 0)
2691                         fd->fd_write_failed = true;
2692                 else
2693                         fd->fd_write_failed = false;
2694         }
2695
2696 #ifdef HAVE_FILE_FSYNC_4ARGS
2697         mutex_unlock(&inode->i_mutex);
2698 #endif
2699         RETURN(rc);
2700 }
2701
2702 static int
2703 ll_file_flock(struct file *file, int cmd, struct file_lock *file_lock)
2704 {
2705         struct inode *inode = file->f_dentry->d_inode;
2706         struct ll_sb_info *sbi = ll_i2sbi(inode);
2707         struct ldlm_enqueue_info einfo = {
2708                 .ei_type        = LDLM_FLOCK,
2709                 .ei_cb_cp       = ldlm_flock_completion_ast,
2710                 .ei_cbdata      = file_lock,
2711         };
2712         struct md_op_data *op_data;
2713         struct lustre_handle lockh = {0};
2714         ldlm_policy_data_t flock = {{0}};
2715         int fl_type = file_lock->fl_type;
2716         __u64 flags = 0;
2717         int rc;
2718         int rc2 = 0;
2719         ENTRY;
2720
2721         CDEBUG(D_VFSTRACE, "VFS Op:inode="DFID" file_lock=%p\n",
2722                PFID(ll_inode2fid(inode)), file_lock);
2723
2724         ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_FLOCK, 1);
2725
2726         if (file_lock->fl_flags & FL_FLOCK) {
2727                 LASSERT((cmd == F_SETLKW) || (cmd == F_SETLK));
2728                 /* flocks are whole-file locks */
2729                 flock.l_flock.end = OFFSET_MAX;
2730                 /* For flocks owner is determined by the local file desctiptor*/
2731                 flock.l_flock.owner = (unsigned long)file_lock->fl_file;
2732         } else if (file_lock->fl_flags & FL_POSIX) {
2733                 flock.l_flock.owner = (unsigned long)file_lock->fl_owner;
2734                 flock.l_flock.start = file_lock->fl_start;
2735                 flock.l_flock.end = file_lock->fl_end;
2736         } else {
2737                 RETURN(-EINVAL);
2738         }
2739         flock.l_flock.pid = file_lock->fl_pid;
2740
2741         /* Somewhat ugly workaround for svc lockd.
2742          * lockd installs custom fl_lmops->lm_compare_owner that checks
2743          * for the fl_owner to be the same (which it always is on local node
2744          * I guess between lockd processes) and then compares pid.
2745          * As such we assign pid to the owner field to make it all work,
2746          * conflict with normal locks is unlikely since pid space and
2747          * pointer space for current->files are not intersecting */
2748         if (file_lock->fl_lmops && file_lock->fl_lmops->lm_compare_owner)
2749                 flock.l_flock.owner = (unsigned long)file_lock->fl_pid;
2750
2751         switch (fl_type) {
2752         case F_RDLCK:
2753                 einfo.ei_mode = LCK_PR;
2754                 break;
2755         case F_UNLCK:
2756                 /* An unlock request may or may not have any relation to
2757                  * existing locks so we may not be able to pass a lock handle
2758                  * via a normal ldlm_lock_cancel() request. The request may even
2759                  * unlock a byte range in the middle of an existing lock. In
2760                  * order to process an unlock request we need all of the same
2761                  * information that is given with a normal read or write record
2762                  * lock request. To avoid creating another ldlm unlock (cancel)
2763                  * message we'll treat a LCK_NL flock request as an unlock. */
2764                 einfo.ei_mode = LCK_NL;
2765                 break;
2766         case F_WRLCK:
2767                 einfo.ei_mode = LCK_PW;
2768                 break;
2769         default:
2770                 CDEBUG(D_INFO, "Unknown fcntl lock type: %d\n", fl_type);
2771                 RETURN (-ENOTSUPP);
2772         }
2773
2774         switch (cmd) {
2775         case F_SETLKW:
2776 #ifdef F_SETLKW64
2777         case F_SETLKW64:
2778 #endif
2779                 flags = 0;
2780                 break;
2781         case F_SETLK:
2782 #ifdef F_SETLK64
2783         case F_SETLK64:
2784 #endif
2785                 flags = LDLM_FL_BLOCK_NOWAIT;
2786                 break;
2787         case F_GETLK:
2788 #ifdef F_GETLK64
2789         case F_GETLK64:
2790 #endif
2791                 flags = LDLM_FL_TEST_LOCK;
2792                 break;
2793         default:
2794                 CERROR("unknown fcntl lock command: %d\n", cmd);
2795                 RETURN (-EINVAL);
2796         }
2797
2798         /* Save the old mode so that if the mode in the lock changes we
2799          * can decrement the appropriate reader or writer refcount. */
2800         file_lock->fl_type = einfo.ei_mode;
2801
2802         op_data = ll_prep_md_op_data(NULL, inode, NULL, NULL, 0, 0,
2803                                      LUSTRE_OPC_ANY, NULL);
2804         if (IS_ERR(op_data))
2805                 RETURN(PTR_ERR(op_data));
2806
2807         CDEBUG(D_DLMTRACE, "inode="DFID", pid=%u, flags="LPX64", mode=%u, "
2808                "start="LPU64", end="LPU64"\n", PFID(ll_inode2fid(inode)),
2809                flock.l_flock.pid, flags, einfo.ei_mode,
2810                flock.l_flock.start, flock.l_flock.end);
2811
2812         rc = md_enqueue(sbi->ll_md_exp, &einfo, &flock, NULL, op_data, &lockh,
2813                         flags);
2814
2815         /* Restore the file lock type if not TEST lock. */
2816         if (!(flags & LDLM_FL_TEST_LOCK))
2817                 file_lock->fl_type = fl_type;
2818
2819         if ((file_lock->fl_flags & FL_FLOCK) &&
2820             (rc == 0 || file_lock->fl_type == F_UNLCK))
2821                 rc2  = flock_lock_file_wait(file, file_lock);
2822         if ((file_lock->fl_flags & FL_POSIX) &&
2823             (rc == 0 || file_lock->fl_type == F_UNLCK) &&
2824             !(flags & LDLM_FL_TEST_LOCK))
2825                 rc2  = posix_lock_file_wait(file, file_lock);
2826
2827         if (rc2 && file_lock->fl_type != F_UNLCK) {
2828                 einfo.ei_mode = LCK_NL;
2829                 md_enqueue(sbi->ll_md_exp, &einfo, &flock, NULL, op_data,
2830                            &lockh, flags);
2831                 rc = rc2;
2832         }
2833
2834         ll_finish_md_op_data(op_data);
2835
2836         RETURN(rc);
2837 }
2838
2839 int ll_get_fid_by_name(struct inode *parent, const char *name,
2840                        int namelen, struct lu_fid *fid)
2841 {
2842         struct md_op_data       *op_data = NULL;
2843         struct mdt_body         *body;
2844         struct ptlrpc_request   *req;
2845         int                     rc;
2846         ENTRY;
2847
2848         op_data = ll_prep_md_op_data(NULL, parent, NULL, name, namelen, 0,
2849                                      LUSTRE_OPC_ANY, NULL);
2850         if (IS_ERR(op_data))
2851                 RETURN(PTR_ERR(op_data));
2852
2853         op_data->op_valid = OBD_MD_FLID;
2854         rc = md_getattr_name(ll_i2sbi(parent)->ll_md_exp, op_data, &req);
2855         ll_finish_md_op_data(op_data);
2856         if (rc < 0)
2857                 RETURN(rc);
2858
2859         body = req_capsule_server_get(&req->rq_pill, &RMF_MDT_BODY);
2860         if (body == NULL)
2861                 GOTO(out_req, rc = -EFAULT);
2862         if (fid != NULL)
2863                 *fid = body->mbo_fid1;
2864 out_req:
2865         ptlrpc_req_finished(req);
2866         RETURN(rc);
2867 }
2868
2869 int ll_migrate(struct inode *parent, struct file *file, int mdtidx,
2870                const char *name, int namelen)
2871 {
2872         struct dentry         *dchild = NULL;
2873         struct inode          *child_inode = NULL;
2874         struct md_op_data     *op_data;
2875         struct ptlrpc_request *request = NULL;
2876         struct qstr           qstr;
2877         int                    rc;
2878         ENTRY;
2879
2880         CDEBUG(D_VFSTRACE, "migrate %s under "DFID" to MDT%04x\n",
2881                name, PFID(ll_inode2fid(parent)), mdtidx);
2882
2883         op_data = ll_prep_md_op_data(NULL, parent, NULL, name, namelen,
2884                                      0, LUSTRE_OPC_ANY, NULL);
2885         if (IS_ERR(op_data))
2886                 RETURN(PTR_ERR(op_data));
2887
2888         /* Get child FID first */
2889         qstr.hash = full_name_hash(name, namelen);
2890         qstr.name = name;
2891         qstr.len = namelen;
2892         dchild = d_lookup(file->f_dentry, &qstr);
2893         if (dchild != NULL) {
2894                 if (dchild->d_inode != NULL) {
2895                         child_inode = igrab(dchild->d_inode);
2896                         if (child_inode != NULL) {
2897                                 mutex_lock(&child_inode->i_mutex);
2898                                 op_data->op_fid3 = *ll_inode2fid(child_inode);
2899                                 ll_invalidate_aliases(child_inode);
2900                         }
2901                 }
2902                 dput(dchild);
2903         } else {
2904                 rc = ll_get_fid_by_name(parent, name, namelen,
2905                                         &op_data->op_fid3);
2906                 if (rc != 0)
2907                         GOTO(out_free, rc);
2908         }
2909
2910         if (!fid_is_sane(&op_data->op_fid3)) {
2911                 CERROR("%s: migrate %s , but fid "DFID" is insane\n",
2912                        ll_get_fsname(parent->i_sb, NULL, 0), name,
2913                        PFID(&op_data->op_fid3));
2914                 GOTO(out_free, rc = -EINVAL);
2915         }
2916
2917         rc = ll_get_mdt_idx_by_fid(ll_i2sbi(parent), &op_data->op_fid3);
2918         if (rc < 0)
2919                 GOTO(out_free, rc);
2920
2921         if (rc == mdtidx) {
2922                 CDEBUG(D_INFO, "%s:"DFID" is already on MDT%d.\n", name,
2923                        PFID(&op_data->op_fid3), mdtidx);
2924                 GOTO(out_free, rc = 0);
2925         }
2926
2927         op_data->op_mds = mdtidx;
2928         op_data->op_cli_flags = CLI_MIGRATE;
2929         rc = md_rename(ll_i2sbi(parent)->ll_md_exp, op_data, name,
2930                        namelen, name, namelen, &request);
2931         if (rc == 0)
2932                 ll_update_times(request, parent);
2933
2934         ptlrpc_req_finished(request);
2935         if (rc != 0)
2936                 GOTO(out_free, rc);
2937
2938 out_free:
2939         if (child_inode != NULL) {
2940                 clear_nlink(child_inode);
2941                 mutex_unlock(&child_inode->i_mutex);
2942                 iput(child_inode);
2943         }
2944
2945         ll_finish_md_op_data(op_data);
2946         RETURN(rc);
2947 }
2948
2949 static int
2950 ll_file_noflock(struct file *file, int cmd, struct file_lock *file_lock)
2951 {
2952         ENTRY;
2953
2954         RETURN(-ENOSYS);
2955 }
2956
2957 /**
2958  * test if some locks matching bits and l_req_mode are acquired
2959  * - bits can be in different locks
2960  * - if found clear the common lock bits in *bits
2961  * - the bits not found, are kept in *bits
2962  * \param inode [IN]
2963  * \param bits [IN] searched lock bits [IN]
2964  * \param l_req_mode [IN] searched lock mode
2965  * \retval boolean, true iff all bits are found
2966  */
2967 int ll_have_md_lock(struct inode *inode, __u64 *bits,  ldlm_mode_t l_req_mode)
2968 {
2969         struct lustre_handle lockh;
2970         ldlm_policy_data_t policy;
2971         ldlm_mode_t mode = (l_req_mode == LCK_MINMODE) ?
2972                                 (LCK_CR|LCK_CW|LCK_PR|LCK_PW) : l_req_mode;
2973         struct lu_fid *fid;
2974         __u64 flags;
2975         int i;
2976         ENTRY;
2977
2978         if (!inode)
2979                RETURN(0);
2980
2981         fid = &ll_i2info(inode)->lli_fid;
2982         CDEBUG(D_INFO, "trying to match res "DFID" mode %s\n", PFID(fid),
2983                ldlm_lockname[mode]);
2984
2985         flags = LDLM_FL_BLOCK_GRANTED | LDLM_FL_CBPENDING | LDLM_FL_TEST_LOCK;
2986         for (i = 0; i <= MDS_INODELOCK_MAXSHIFT && *bits != 0; i++) {
2987                 policy.l_inodebits.bits = *bits & (1 << i);
2988                 if (policy.l_inodebits.bits == 0)
2989                         continue;
2990
2991                 if (md_lock_match(ll_i2mdexp(inode), flags, fid, LDLM_IBITS,
2992                                   &policy, mode, &lockh)) {
2993                         struct ldlm_lock *lock;
2994
2995                         lock = ldlm_handle2lock(&lockh);
2996                         if (lock) {
2997                                 *bits &=
2998                                       ~(lock->l_policy_data.l_inodebits.bits);
2999                                 LDLM_LOCK_PUT(lock);
3000                         } else {
3001                                 *bits &= ~policy.l_inodebits.bits;
3002                         }
3003                 }
3004         }
3005         RETURN(*bits == 0);
3006 }
3007
3008 ldlm_mode_t ll_take_md_lock(struct inode *inode, __u64 bits,
3009                             struct lustre_handle *lockh, __u64 flags,
3010                             ldlm_mode_t mode)
3011 {
3012         ldlm_policy_data_t policy = { .l_inodebits = {bits}};
3013         struct lu_fid *fid;
3014         ldlm_mode_t rc;
3015         ENTRY;
3016
3017         fid = &ll_i2info(inode)->lli_fid;
3018         CDEBUG(D_INFO, "trying to match res "DFID"\n", PFID(fid));
3019
3020         rc = md_lock_match(ll_i2mdexp(inode), LDLM_FL_BLOCK_GRANTED|flags,
3021                            fid, LDLM_IBITS, &policy, mode, lockh);
3022
3023         RETURN(rc);
3024 }
3025
3026 static int ll_inode_revalidate_fini(struct inode *inode, int rc)
3027 {
3028         /* Already unlinked. Just update nlink and return success */
3029         if (rc == -ENOENT) {
3030                 clear_nlink(inode);
3031                 /* This path cannot be hit for regular files unless in
3032                  * case of obscure races, so no need to to validate
3033                  * size. */
3034                 if (!S_ISREG(inode->i_mode) && !S_ISDIR(inode->i_mode))
3035                         return 0;
3036         } else if (rc != 0) {
3037                 CDEBUG_LIMIT((rc == -EACCES || rc == -EIDRM) ? D_INFO : D_ERROR,
3038                              "%s: revalidate FID "DFID" error: rc = %d\n",
3039                              ll_get_fsname(inode->i_sb, NULL, 0),
3040                              PFID(ll_inode2fid(inode)), rc);
3041         }
3042
3043         return rc;
3044 }
3045
3046 static int __ll_inode_revalidate(struct dentry *dentry, __u64 ibits)
3047 {
3048         struct inode *inode = dentry->d_inode;
3049         struct ptlrpc_request *req = NULL;
3050         struct obd_export *exp;
3051         int rc = 0;
3052         ENTRY;
3053
3054         LASSERT(inode != NULL);
3055
3056         CDEBUG(D_VFSTRACE, "VFS Op:inode="DFID"(%p),name=%s\n",
3057                PFID(ll_inode2fid(inode)), inode, dentry->d_name.name);
3058
3059         exp = ll_i2mdexp(inode);
3060
3061         /* XXX: Enable OBD_CONNECT_ATTRFID to reduce unnecessary getattr RPC.
3062          *      But under CMD case, it caused some lock issues, should be fixed
3063          *      with new CMD ibits lock. See bug 12718 */
3064         if (exp_connect_flags(exp) & OBD_CONNECT_ATTRFID) {
3065                 struct lookup_intent oit = { .it_op = IT_GETATTR };
3066                 struct md_op_data *op_data;
3067
3068                 if (ibits == MDS_INODELOCK_LOOKUP)
3069                         oit.it_op = IT_LOOKUP;
3070
3071                 /* Call getattr by fid, so do not provide name at all. */
3072                 op_data = ll_prep_md_op_data(NULL, dentry->d_inode,
3073                                              dentry->d_inode, NULL, 0, 0,
3074                                              LUSTRE_OPC_ANY, NULL);
3075                 if (IS_ERR(op_data))
3076                         RETURN(PTR_ERR(op_data));
3077
3078                 rc = md_intent_lock(exp, op_data, &oit, &req,
3079                                     &ll_md_blocking_ast, 0);
3080                 ll_finish_md_op_data(op_data);
3081                 if (rc < 0) {
3082                         rc = ll_inode_revalidate_fini(inode, rc);
3083                         GOTO (out, rc);
3084                 }
3085
3086                 rc = ll_revalidate_it_finish(req, &oit, dentry);
3087                 if (rc != 0) {
3088                         ll_intent_release(&oit);
3089                         GOTO(out, rc);
3090                 }
3091
3092                 /* Unlinked? Unhash dentry, so it is not picked up later by
3093                    do_lookup() -> ll_revalidate_it(). We cannot use d_drop
3094                    here to preserve get_cwd functionality on 2.6.
3095                    Bug 10503 */
3096                 if (!dentry->d_inode->i_nlink)
3097                         d_lustre_invalidate(dentry, 0);
3098
3099                 ll_lookup_finish_locks(&oit, dentry);
3100         } else if (!ll_have_md_lock(dentry->d_inode, &ibits, LCK_MINMODE)) {
3101                 struct ll_sb_info *sbi = ll_i2sbi(dentry->d_inode);
3102                 u64 valid = OBD_MD_FLGETATTR;
3103                 struct md_op_data *op_data;
3104                 int ealen = 0;
3105
3106                 if (S_ISREG(inode->i_mode)) {
3107                         rc = ll_get_default_mdsize(sbi, &ealen);
3108                         if (rc)
3109                                 RETURN(rc);
3110                         valid |= OBD_MD_FLEASIZE | OBD_MD_FLMODEASIZE;
3111                 }
3112
3113                 op_data = ll_prep_md_op_data(NULL, inode, NULL, NULL,
3114                                              0, ealen, LUSTRE_OPC_ANY,
3115                                              NULL);
3116                 if (IS_ERR(op_data))
3117                         RETURN(PTR_ERR(op_data));
3118
3119                 op_data->op_valid = valid;
3120                 /* Once OBD_CONNECT_ATTRFID is not supported, we can't find one
3121                  * capa for this inode. Because we only keep capas of dirs
3122                  * fresh. */
3123                 rc = md_getattr(sbi->ll_md_exp, op_data, &req);
3124                 ll_finish_md_op_data(op_data);
3125                 if (rc) {
3126                         rc = ll_inode_revalidate_fini(inode, rc);
3127                         RETURN(rc);
3128                 }
3129
3130                 rc = ll_prep_inode(&inode, req, NULL, NULL);
3131         }
3132 out:
3133         ptlrpc_req_finished(req);
3134         return rc;
3135 }
3136
3137 static int ll_merge_md_attr(struct inode *inode)
3138 {
3139         struct cl_attr attr = { 0 };
3140         int rc;
3141
3142         LASSERT(ll_i2info(inode)->lli_lsm_md != NULL);
3143         rc = md_merge_attr(ll_i2mdexp(inode), ll_i2info(inode)->lli_lsm_md,
3144                            &attr, ll_md_blocking_ast);
3145         if (rc != 0)
3146                 RETURN(rc);
3147
3148         set_nlink(inode, attr.cat_nlink);
3149         inode->i_blocks = attr.cat_blocks;
3150         i_size_write(inode, attr.cat_size);
3151
3152         ll_i2info(inode)->lli_atime = attr.cat_atime;
3153         ll_i2info(inode)->lli_mtime = attr.cat_mtime;
3154         ll_i2info(inode)->lli_ctime = attr.cat_ctime;
3155
3156         RETURN(0);
3157 }
3158
3159 static int
3160 ll_inode_revalidate(struct dentry *dentry, __u64 ibits)
3161 {
3162         struct inode    *inode = dentry->d_inode;
3163         int              rc;
3164         ENTRY;
3165
3166         rc = __ll_inode_revalidate(dentry, ibits);
3167         if (rc != 0)
3168                 RETURN(rc);
3169
3170         /* if object isn't regular file, don't validate size */
3171         if (!S_ISREG(inode->i_mode)) {
3172                 if (S_ISDIR(inode->i_mode) &&
3173                     ll_i2info(inode)->lli_lsm_md != NULL) {
3174                         rc = ll_merge_md_attr(inode);
3175                         if (rc != 0)
3176                                 RETURN(rc);
3177                 }
3178
3179                 LTIME_S(inode->i_atime) = ll_i2info(inode)->lli_atime;
3180                 LTIME_S(inode->i_mtime) = ll_i2info(inode)->lli_mtime;
3181                 LTIME_S(inode->i_ctime) = ll_i2info(inode)->lli_ctime;
3182         } else {
3183                 /* In case of restore, the MDT has the right size and has
3184                  * already send it back without granting the layout lock,
3185                  * inode is up-to-date so glimpse is useless.
3186                  * Also to glimpse we need the layout, in case of a running
3187                  * restore the MDT holds the layout lock so the glimpse will
3188                  * block up to the end of restore (getattr will block)
3189                  */
3190                 if (!(ll_i2info(inode)->lli_flags & LLIF_FILE_RESTORING))
3191                         rc = ll_glimpse_size(inode);
3192         }
3193         RETURN(rc);
3194 }
3195
3196 int ll_getattr(struct vfsmount *mnt, struct dentry *de, struct kstat *stat)
3197 {
3198         struct inode *inode = de->d_inode;
3199         struct ll_sb_info *sbi = ll_i2sbi(inode);
3200         struct ll_inode_info *lli = ll_i2info(inode);
3201         int res = 0;
3202
3203         res = ll_inode_revalidate(de, MDS_INODELOCK_UPDATE |
3204                                       MDS_INODELOCK_LOOKUP);
3205         ll_stats_ops_tally(sbi, LPROC_LL_GETATTR, 1);
3206
3207         if (res)
3208                 return res;
3209
3210         stat->dev = inode->i_sb->s_dev;
3211         if (ll_need_32bit_api(sbi))
3212                 stat->ino = cl_fid_build_ino(&lli->lli_fid, 1);
3213         else
3214                 stat->ino = inode->i_ino;
3215         stat->mode = inode->i_mode;
3216         stat->uid = inode->i_uid;
3217         stat->gid = inode->i_gid;
3218         stat->rdev = inode->i_rdev;
3219         stat->atime = inode->i_atime;
3220         stat->mtime = inode->i_mtime;
3221         stat->ctime = inode->i_ctime;
3222         stat->blksize = 1 << inode->i_blkbits;
3223
3224         stat->nlink = inode->i_nlink;
3225         stat->size = i_size_read(inode);
3226         stat->blocks = inode->i_blocks;
3227
3228         return 0;
3229 }
3230
3231 static int ll_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
3232                      __u64 start, __u64 len)
3233 {
3234         int rc;
3235         size_t num_bytes;
3236         struct ll_user_fiemap *fiemap;
3237         unsigned int extent_count = fieinfo->fi_extents_max;
3238
3239         num_bytes = sizeof(*fiemap) + (extent_count *
3240                                        sizeof(struct ll_fiemap_extent));
3241         OBD_ALLOC_LARGE(fiemap, num_bytes);
3242
3243         if (fiemap == NULL)
3244                 RETURN(-ENOMEM);
3245
3246         fiemap->fm_flags = fieinfo->fi_flags;
3247         fiemap->fm_extent_count = fieinfo->fi_extents_max;
3248         fiemap->fm_start = start;
3249         fiemap->fm_length = len;
3250         if (extent_count > 0)
3251                 memcpy(&fiemap->fm_extents[0], fieinfo->fi_extents_start,
3252                        sizeof(struct ll_fiemap_extent));
3253
3254         rc = ll_do_fiemap(inode, fiemap, num_bytes);
3255
3256         fieinfo->fi_flags = fiemap->fm_flags;
3257         fieinfo->fi_extents_mapped = fiemap->fm_mapped_extents;
3258         if (extent_count > 0)
3259                 memcpy(fieinfo->fi_extents_start, &fiemap->fm_extents[0],
3260                        fiemap->fm_mapped_extents *
3261                        sizeof(struct ll_fiemap_extent));
3262
3263         OBD_FREE_LARGE(fiemap, num_bytes);
3264         return rc;
3265 }
3266
3267 struct posix_acl *ll_get_acl(struct inode *inode, int type)
3268 {
3269         struct ll_inode_info *lli = ll_i2info(inode);
3270         struct posix_acl *acl = NULL;
3271         ENTRY;
3272
3273         spin_lock(&lli->lli_lock);
3274         /* VFS' acl_permission_check->check_acl will release the refcount */
3275         acl = posix_acl_dup(lli->lli_posix_acl);
3276         spin_unlock(&lli->lli_lock);
3277
3278         RETURN(acl);
3279 }
3280
3281 #ifndef HAVE_GENERIC_PERMISSION_2ARGS
3282 static int
3283 # ifdef HAVE_GENERIC_PERMISSION_4ARGS
3284 ll_check_acl(struct inode *inode, int mask, unsigned int flags)
3285 # else
3286 ll_check_acl(struct inode *inode, int mask)
3287 # endif
3288 {
3289 # ifdef CONFIG_FS_POSIX_ACL
3290         struct posix_acl *acl;
3291         int rc;
3292         ENTRY;
3293
3294 #  ifdef HAVE_GENERIC_PERMISSION_4ARGS
3295         if (flags & IPERM_FLAG_RCU)
3296                 return -ECHILD;
3297 #  endif
3298         acl = ll_get_acl(inode, ACL_TYPE_ACCESS);
3299
3300         if (!acl)
3301                 RETURN(-EAGAIN);
3302
3303         rc = posix_acl_permission(inode, acl, mask);
3304         posix_acl_release(acl);
3305
3306         RETURN(rc);
3307 # else /* !CONFIG_FS_POSIX_ACL */
3308         return -EAGAIN;
3309 # endif /* CONFIG_FS_POSIX_ACL */
3310 }
3311 #endif /* HAVE_GENERIC_PERMISSION_2ARGS */
3312
3313 #ifdef HAVE_GENERIC_PERMISSION_4ARGS
3314 int ll_inode_permission(struct inode *inode, int mask, unsigned int flags)
3315 #else
3316 # ifdef HAVE_INODE_PERMISION_2ARGS
3317 int ll_inode_permission(struct inode *inode, int mask)
3318 # else
3319 int ll_inode_permission(struct inode *inode, int mask, struct nameidata *nd)
3320 # endif
3321 #endif
3322 {
3323         int rc = 0;
3324         struct ll_sb_info *sbi;
3325         struct root_squash_info *squash;
3326         struct cred *cred = NULL;
3327         const struct cred *old_cred = NULL;
3328         cfs_cap_t cap;
3329         bool squash_id = false;
3330         ENTRY;
3331
3332 #ifdef MAY_NOT_BLOCK
3333         if (mask & MAY_NOT_BLOCK)
3334                 return -ECHILD;
3335 #elif defined(HAVE_GENERIC_PERMISSION_4ARGS)
3336         if (flags & IPERM_FLAG_RCU)
3337                 return -ECHILD;
3338 #endif
3339
3340        /* as root inode are NOT getting validated in lookup operation,
3341         * need to do it before permission check. */
3342
3343         if (inode == inode->i_sb->s_root->d_inode) {
3344                 rc = __ll_inode_revalidate(inode->i_sb->s_root,
3345                                            MDS_INODELOCK_LOOKUP);
3346                 if (rc)
3347                         RETURN(rc);
3348         }
3349
3350         CDEBUG(D_VFSTRACE, "VFS Op:inode="DFID"(%p), inode mode %x mask %o\n",
3351                PFID(ll_inode2fid(inode)), inode, inode->i_mode, mask);
3352
3353         /* squash fsuid/fsgid if needed */
3354         sbi = ll_i2sbi(inode);
3355         squash = &sbi->ll_squash;
3356         if (unlikely(squash->rsi_uid != 0 &&
3357                      uid_eq(current_fsuid(), GLOBAL_ROOT_UID) &&
3358                      !(sbi->ll_flags & LL_SBI_NOROOTSQUASH))) {
3359                         squash_id = true;
3360         }
3361         if (squash_id) {
3362                 CDEBUG(D_OTHER, "squash creds (%d:%d)=>(%d:%d)\n",
3363                        __kuid_val(current_fsuid()), __kgid_val(current_fsgid()),
3364                        squash->rsi_uid, squash->rsi_gid);
3365
3366                 /* update current process's credentials
3367                  * and FS capability */
3368                 cred = prepare_creds();
3369                 if (cred == NULL)
3370                         RETURN(-ENOMEM);
3371
3372                 cred->fsuid = make_kuid(&init_user_ns, squash->rsi_uid);
3373                 cred->fsgid = make_kgid(&init_user_ns, squash->rsi_gid);
3374                 for (cap = 0; cap < sizeof(cfs_cap_t) * 8; cap++) {
3375                         if ((1 << cap) & CFS_CAP_FS_MASK)
3376                                 cap_lower(cred->cap_effective, cap);
3377                 }
3378                 old_cred = override_creds(cred);
3379         }
3380
3381         ll_stats_ops_tally(sbi, LPROC_LL_INODE_PERM, 1);
3382
3383         if (sbi->ll_flags & LL_SBI_RMT_CLIENT)
3384                 rc = lustre_check_remote_perm(inode, mask);
3385         else
3386                 rc = ll_generic_permission(inode, mask, flags, ll_check_acl);
3387
3388         /* restore current process's credentials and FS capability */
3389         if (squash_id) {
3390                 revert_creds(old_cred);
3391                 put_cred(cred);
3392         }
3393
3394         RETURN(rc);
3395 }
3396
3397 /* -o localflock - only provides locally consistent flock locks */
3398 struct file_operations ll_file_operations = {
3399         .read           = ll_file_read,
3400         .aio_read    = ll_file_aio_read,
3401         .write          = ll_file_write,
3402         .aio_write   = ll_file_aio_write,
3403         .unlocked_ioctl = ll_file_ioctl,
3404         .open           = ll_file_open,
3405         .release        = ll_file_release,
3406         .mmap           = ll_file_mmap,
3407         .llseek         = ll_file_seek,
3408         .splice_read    = ll_file_splice_read,
3409         .fsync          = ll_fsync,
3410         .flush          = ll_flush
3411 };
3412
3413 struct file_operations ll_file_operations_flock = {
3414         .read           = ll_file_read,
3415         .aio_read    = ll_file_aio_read,
3416         .write          = ll_file_write,
3417         .aio_write   = ll_file_aio_write,
3418         .unlocked_ioctl = ll_file_ioctl,
3419         .open           = ll_file_open,
3420         .release        = ll_file_release,
3421         .mmap           = ll_file_mmap,
3422         .llseek         = ll_file_seek,
3423         .splice_read    = ll_file_splice_read,
3424         .fsync          = ll_fsync,
3425         .flush          = ll_flush,
3426         .flock          = ll_file_flock,
3427         .lock           = ll_file_flock
3428 };
3429
3430 /* These are for -o noflock - to return ENOSYS on flock calls */
3431 struct file_operations ll_file_operations_noflock = {
3432         .read           = ll_file_read,
3433         .aio_read    = ll_file_aio_read,
3434         .write          = ll_file_write,
3435         .aio_write   = ll_file_aio_write,
3436         .unlocked_ioctl = ll_file_ioctl,
3437         .open           = ll_file_open,
3438         .release        = ll_file_release,
3439         .mmap           = ll_file_mmap,
3440         .llseek         = ll_file_seek,
3441         .splice_read    = ll_file_splice_read,
3442         .fsync          = ll_fsync,
3443         .flush          = ll_flush,
3444         .flock          = ll_file_noflock,
3445         .lock           = ll_file_noflock
3446 };
3447
3448 struct inode_operations ll_file_inode_operations = {
3449         .setattr        = ll_setattr,
3450         .getattr        = ll_getattr,
3451         .permission     = ll_inode_permission,
3452         .setxattr       = ll_setxattr,
3453         .getxattr       = ll_getxattr,
3454         .listxattr      = ll_listxattr,
3455         .removexattr    = ll_removexattr,
3456         .fiemap         = ll_fiemap,
3457 #ifdef HAVE_IOP_GET_ACL
3458         .get_acl        = ll_get_acl,
3459 #endif
3460 };
3461
3462 /* dynamic ioctl number support routins */
3463 static struct llioc_ctl_data {
3464         struct rw_semaphore     ioc_sem;
3465         struct list_head        ioc_head;
3466 } llioc = {
3467         __RWSEM_INITIALIZER(llioc.ioc_sem),
3468         LIST_HEAD_INIT(llioc.ioc_head)
3469 };
3470
3471
3472 struct llioc_data {
3473         struct list_head        iocd_list;
3474         unsigned int            iocd_size;
3475         llioc_callback_t        iocd_cb;
3476         unsigned int            iocd_count;
3477         unsigned int            iocd_cmd[0];
3478 };
3479
3480 void *ll_iocontrol_register(llioc_callback_t cb, int count, unsigned int *cmd)
3481 {
3482         unsigned int size;
3483         struct llioc_data *in_data = NULL;
3484         ENTRY;
3485
3486         if (cb == NULL || cmd == NULL ||
3487             count > LLIOC_MAX_CMD || count < 0)
3488                 RETURN(NULL);
3489
3490         size = sizeof(*in_data) + count * sizeof(unsigned int);
3491         OBD_ALLOC(in_data, size);
3492         if (in_data == NULL)
3493                 RETURN(NULL);
3494
3495         memset(in_data, 0, sizeof(*in_data));
3496         in_data->iocd_size = size;
3497         in_data->iocd_cb = cb;
3498         in_data->iocd_count = count;
3499         memcpy(in_data->iocd_cmd, cmd, sizeof(unsigned int) * count);
3500
3501         down_write(&llioc.ioc_sem);
3502         list_add_tail(&in_data->iocd_list, &llioc.ioc_head);
3503         up_write(&llioc.ioc_sem);
3504
3505         RETURN(in_data);
3506 }
3507
3508 void ll_iocontrol_unregister(void *magic)
3509 {
3510         struct llioc_data *tmp;
3511
3512         if (magic == NULL)
3513                 return;
3514
3515         down_write(&llioc.ioc_sem);
3516         list_for_each_entry(tmp, &llioc.ioc_head, iocd_list) {
3517                 if (tmp == magic) {
3518                         unsigned int size = tmp->iocd_size;
3519
3520                         list_del(&tmp->iocd_list);
3521                         up_write(&llioc.ioc_sem);
3522
3523                         OBD_FREE(tmp, size);
3524                         return;
3525                 }
3526         }
3527         up_write(&llioc.ioc_sem);
3528
3529         CWARN("didn't find iocontrol register block with magic: %p\n", magic);
3530 }
3531
3532 EXPORT_SYMBOL(ll_iocontrol_register);
3533 EXPORT_SYMBOL(ll_iocontrol_unregister);
3534
3535 static enum llioc_iter
3536 ll_iocontrol_call(struct inode *inode, struct file *file,
3537                   unsigned int cmd, unsigned long arg, int *rcp)
3538 {
3539         enum llioc_iter ret = LLIOC_CONT;
3540         struct llioc_data *data;
3541         int rc = -EINVAL, i;
3542
3543         down_read(&llioc.ioc_sem);
3544         list_for_each_entry(data, &llioc.ioc_head, iocd_list) {
3545                 for (i = 0; i < data->iocd_count; i++) {
3546                         if (cmd != data->iocd_cmd[i])
3547                                 continue;
3548
3549                         ret = data->iocd_cb(inode, file, cmd, arg, data, &rc);
3550                         break;
3551                 }
3552
3553                 if (ret == LLIOC_STOP)
3554                         break;
3555         }
3556         up_read(&llioc.ioc_sem);
3557
3558         if (rcp)
3559                 *rcp = rc;
3560         return ret;
3561 }
3562
3563 int ll_layout_conf(struct inode *inode, const struct cl_object_conf *conf)
3564 {
3565         struct ll_inode_info *lli = ll_i2info(inode);
3566         struct cl_env_nest nest;
3567         struct lu_env *env;
3568         int result;
3569         ENTRY;
3570
3571         if (lli->lli_clob == NULL)
3572                 RETURN(0);
3573
3574         env = cl_env_nested_get(&nest);
3575         if (IS_ERR(env))
3576                 RETURN(PTR_ERR(env));
3577
3578         result = cl_conf_set(env, lli->lli_clob, conf);
3579         cl_env_nested_put(&nest, env);
3580
3581         if (conf->coc_opc == OBJECT_CONF_SET) {
3582                 struct ldlm_lock *lock = conf->coc_lock;
3583
3584                 LASSERT(lock != NULL);
3585                 LASSERT(ldlm_has_layout(lock));
3586                 if (result == 0) {
3587                         struct lustre_md *md = conf->u.coc_md;
3588                         __u32 gen = LL_LAYOUT_GEN_EMPTY;
3589
3590                         /* it can only be allowed to match after layout is
3591                          * applied to inode otherwise false layout would be
3592                          * seen. Applying layout shoud happen before dropping
3593                          * the intent lock. */
3594                         ldlm_lock_allow_match(lock);
3595
3596                         lli->lli_has_smd = lsm_has_objects(md->lsm);
3597                         if (md->lsm != NULL)
3598                                 gen = md->lsm->lsm_layout_gen;
3599
3600                         CDEBUG(D_VFSTRACE,
3601                                DFID ": layout version change: %u -> %u\n",
3602                                PFID(&lli->lli_fid), ll_layout_version_get(lli),
3603                                gen);
3604                         ll_layout_version_set(lli, gen);
3605                 }
3606         }
3607         RETURN(result);
3608 }
3609
3610 /* Fetch layout from MDT with getxattr request, if it's not ready yet */
3611 static int ll_layout_fetch(struct inode *inode, struct ldlm_lock *lock)
3612
3613 {
3614         struct ll_sb_info *sbi = ll_i2sbi(inode);
3615         struct obd_capa *oc;
3616         struct ptlrpc_request *req;
3617         struct mdt_body *body;
3618         void *lvbdata;
3619         void *lmm;
3620         int lmmsize;
3621         int rc;
3622         ENTRY;
3623
3624         CDEBUG(D_INODE, DFID" LVB_READY=%d l_lvb_data=%p l_lvb_len=%d\n",
3625                PFID(ll_inode2fid(inode)), ldlm_is_lvb_ready(lock),
3626                lock->l_lvb_data, lock->l_lvb_len);
3627
3628         if ((lock->l_lvb_data != NULL) && ldlm_is_lvb_ready(lock))
3629                 RETURN(0);
3630
3631         /* if layout lock was granted right away, the layout is returned
3632          * within DLM_LVB of dlm reply; otherwise if the lock was ever
3633          * blocked and then granted via completion ast, we have to fetch
3634          * layout here. Please note that we can't use the LVB buffer in
3635          * completion AST because it doesn't have a large enough buffer */
3636         oc = ll_mdscapa_get(inode);
3637         rc = ll_get_default_mdsize(sbi, &lmmsize);
3638         if (rc == 0)
3639                 rc = md_getxattr(sbi->ll_md_exp, ll_inode2fid(inode), oc,
3640                                 OBD_MD_FLXATTR, XATTR_NAME_LOV, NULL, 0,
3641                                 lmmsize, 0, &req);
3642         capa_put(oc);
3643         if (rc < 0)
3644                 RETURN(rc);
3645
3646         body = req_capsule_server_get(&req->rq_pill, &RMF_MDT_BODY);
3647         if (body == NULL)
3648                 GOTO(out, rc = -EPROTO);
3649
3650         lmmsize = body->mbo_eadatasize;
3651         if (lmmsize == 0) /* empty layout */
3652                 GOTO(out, rc = 0);
3653
3654         lmm = req_capsule_server_sized_get(&req->rq_pill, &RMF_EADATA, lmmsize);
3655         if (lmm == NULL)
3656                 GOTO(out, rc = -EFAULT);
3657
3658         OBD_ALLOC_LARGE(lvbdata, lmmsize);
3659         if (lvbdata == NULL)
3660                 GOTO(out, rc = -ENOMEM);
3661
3662         memcpy(lvbdata, lmm, lmmsize);
3663         lock_res_and_lock(lock);
3664         if (lock->l_lvb_data != NULL)
3665                 OBD_FREE_LARGE(lock->l_lvb_data, lock->l_lvb_len);
3666
3667         lock->l_lvb_data = lvbdata;
3668         lock->l_lvb_len = lmmsize;
3669         unlock_res_and_lock(lock);
3670
3671         EXIT;
3672
3673 out:
3674         ptlrpc_req_finished(req);
3675         return rc;
3676 }
3677
3678 /**
3679  * Apply the layout to the inode. Layout lock is held and will be released
3680  * in this function.
3681  */
3682 static int ll_layout_lock_set(struct lustre_handle *lockh, ldlm_mode_t mode,
3683                                 struct inode *inode, __u32 *gen, bool reconf)
3684 {
3685         struct ll_inode_info *lli = ll_i2info(inode);
3686         struct ll_sb_info    *sbi = ll_i2sbi(inode);
3687         struct ldlm_lock *lock;
3688         struct lustre_md md = { NULL };
3689         struct cl_object_conf conf;
3690         int rc = 0;
3691         bool lvb_ready;
3692         bool wait_layout = false;
3693         ENTRY;
3694
3695         LASSERT(lustre_handle_is_used(lockh));
3696
3697         lock = ldlm_handle2lock(lockh);
3698         LASSERT(lock != NULL);
3699         LASSERT(ldlm_has_layout(lock));
3700
3701         LDLM_DEBUG(lock, "file "DFID"(%p) being reconfigured: %d",
3702                    PFID(&lli->lli_fid), inode, reconf);
3703
3704         /* in case this is a caching lock and reinstate with new inode */
3705         md_set_lock_data(sbi->ll_md_exp, &lockh->cookie, inode, NULL);
3706
3707         lock_res_and_lock(lock);
3708         lvb_ready = ldlm_is_lvb_ready(lock);
3709         unlock_res_and_lock(lock);
3710         /* checking lvb_ready is racy but this is okay. The worst case is
3711          * that multi processes may configure the file on the same time. */
3712
3713         if (lvb_ready || !reconf) {
3714                 rc = -ENODATA;
3715                 if (lvb_ready) {
3716                         /* layout_gen must be valid if layout lock is not
3717                          * cancelled and stripe has already set */
3718                         *gen = ll_layout_version_get(lli);
3719                         rc = 0;
3720                 }
3721                 GOTO(out, rc);
3722         }
3723
3724         rc = ll_layout_fetch(inode, lock);
3725         if (rc < 0)
3726                 GOTO(out, rc);
3727
3728         /* for layout lock, lmm is returned in lock's lvb.
3729          * lvb_data is immutable if the lock is held so it's safe to access it
3730          * without res lock. See the description in ldlm_lock_decref_internal()
3731          * for the condition to free lvb_data of layout lock */
3732         if (lock->l_lvb_data != NULL) {
3733                 rc = obd_unpackmd(sbi->ll_dt_exp, &md.lsm,
3734                                   lock->l_lvb_data, lock->l_lvb_len);
3735                 if (rc >= 0) {
3736                         *gen = LL_LAYOUT_GEN_EMPTY;
3737                         if (md.lsm != NULL)
3738                                 *gen = md.lsm->lsm_layout_gen;
3739                         rc = 0;
3740                 } else {
3741                         CERROR("%s: file "DFID" unpackmd error: %d\n",
3742                                 ll_get_fsname(inode->i_sb, NULL, 0),
3743                                 PFID(&lli->lli_fid), rc);
3744                 }
3745         }
3746         if (rc < 0)
3747                 GOTO(out, rc);
3748
3749         /* set layout to file. Unlikely this will fail as old layout was
3750          * surely eliminated */
3751         memset(&conf, 0, sizeof conf);
3752         conf.coc_opc = OBJECT_CONF_SET;
3753         conf.coc_inode = inode;
3754         conf.coc_lock = lock;
3755         conf.u.coc_md = &md;
3756         rc = ll_layout_conf(inode, &conf);
3757
3758         if (md.lsm != NULL)
3759                 obd_free_memmd(sbi->ll_dt_exp, &md.lsm);
3760
3761         /* refresh layout failed, need to wait */
3762         wait_layout = rc == -EBUSY;
3763         EXIT;
3764
3765 out:
3766         LDLM_LOCK_PUT(lock);
3767         ldlm_lock_decref(lockh, mode);
3768
3769         /* wait for IO to complete if it's still being used. */
3770         if (wait_layout) {
3771                 CDEBUG(D_INODE, "%s: "DFID"(%p) wait for layout reconf\n",
3772                        ll_get_fsname(inode->i_sb, NULL, 0),
3773                        PFID(&lli->lli_fid), inode);
3774
3775                 memset(&conf, 0, sizeof conf);
3776                 conf.coc_opc = OBJECT_CONF_WAIT;
3777                 conf.coc_inode = inode;
3778                 rc = ll_layout_conf(inode, &conf);
3779                 if (rc == 0)
3780                         rc = -EAGAIN;
3781
3782                 CDEBUG(D_INODE, "%s file="DFID" waiting layout return: %d\n",
3783                        ll_get_fsname(inode->i_sb, NULL, 0),
3784                        PFID(&lli->lli_fid), rc);
3785         }
3786         RETURN(rc);
3787 }
3788
3789 /**
3790  * This function checks if there exists a LAYOUT lock on the client side,
3791  * or enqueues it if it doesn't have one in cache.
3792  *
3793  * This function will not hold layout lock so it may be revoked any time after
3794  * this function returns. Any operations depend on layout should be redone
3795  * in that case.
3796  *
3797  * This function should be called before lov_io_init() to get an uptodate
3798  * layout version, the caller should save the version number and after IO
3799  * is finished, this function should be called again to verify that layout
3800  * is not changed during IO time.
3801  */
3802 int ll_layout_refresh(struct inode *inode, __u32 *gen)
3803 {
3804         struct ll_inode_info  *lli = ll_i2info(inode);
3805         struct ll_sb_info     *sbi = ll_i2sbi(inode);
3806         struct md_op_data     *op_data;
3807         struct lookup_intent   it;
3808         struct lustre_handle   lockh;
3809         ldlm_mode_t            mode;
3810         struct ldlm_enqueue_info einfo = {
3811                 .ei_type = LDLM_IBITS,
3812                 .ei_mode = LCK_CR,
3813                 .ei_cb_bl = &ll_md_blocking_ast,
3814                 .ei_cb_cp = &ldlm_completion_ast,
3815         };
3816         int rc;
3817         ENTRY;
3818
3819         *gen = ll_layout_version_get(lli);
3820         if (!(sbi->ll_flags & LL_SBI_LAYOUT_LOCK) || *gen != LL_LAYOUT_GEN_NONE)
3821                 RETURN(0);
3822
3823         /* sanity checks */
3824         LASSERT(fid_is_sane(ll_inode2fid(inode)));
3825         LASSERT(S_ISREG(inode->i_mode));
3826
3827         /* take layout lock mutex to enqueue layout lock exclusively. */
3828         mutex_lock(&lli->lli_layout_mutex);
3829
3830 again:
3831         /* mostly layout lock is caching on the local side, so try to match
3832          * it before grabbing layout lock mutex. */
3833         mode = ll_take_md_lock(inode, MDS_INODELOCK_LAYOUT, &lockh, 0,
3834                                LCK_CR | LCK_CW | LCK_PR | LCK_PW);
3835         if (mode != 0) { /* hit cached lock */
3836                 rc = ll_layout_lock_set(&lockh, mode, inode, gen, true);
3837                 if (rc == -EAGAIN)
3838                         goto again;
3839
3840                 mutex_unlock(&lli->lli_layout_mutex);
3841                 RETURN(rc);
3842         }
3843
3844         op_data = ll_prep_md_op_data(NULL, inode, inode, NULL,
3845                                      0, 0, LUSTRE_OPC_ANY, NULL);
3846         if (IS_ERR(op_data)) {
3847                 mutex_unlock(&lli->lli_layout_mutex);
3848                 RETURN(PTR_ERR(op_data));
3849         }
3850
3851         /* have to enqueue one */
3852         memset(&it, 0, sizeof(it));
3853         it.it_op = IT_LAYOUT;
3854         lockh.cookie = 0ULL;
3855
3856         LDLM_DEBUG_NOLOCK("%s: requeue layout lock for file "DFID"(%p)",
3857                           ll_get_fsname(inode->i_sb, NULL, 0),
3858                           PFID(&lli->lli_fid), inode);
3859
3860         rc = md_enqueue(sbi->ll_md_exp, &einfo, NULL, &it, op_data, &lockh, 0);
3861         if (it.d.lustre.it_data != NULL)
3862                 ptlrpc_req_finished(it.d.lustre.it_data);
3863         it.d.lustre.it_data = NULL;
3864
3865         ll_finish_md_op_data(op_data);
3866
3867         mode = it.d.lustre.it_lock_mode;
3868         it.d.lustre.it_lock_mode = 0;
3869         ll_intent_drop_lock(&it);
3870
3871         if (rc == 0) {
3872                 /* set lock data in case this is a new lock */
3873                 ll_set_lock_data(sbi->ll_md_exp, inode, &it, NULL);
3874                 rc = ll_layout_lock_set(&lockh, mode, inode, gen, true);
3875                 if (rc == -EAGAIN)
3876                         goto again;
3877         }
3878         mutex_unlock(&lli->lli_layout_mutex);
3879
3880         RETURN(rc);
3881 }
3882
3883 /**
3884  *  This function send a restore request to the MDT
3885  */
3886 int ll_layout_restore(struct inode *inode, loff_t offset, __u64 length)
3887 {
3888         struct hsm_user_request *hur;
3889         int                      len, rc;
3890         ENTRY;
3891
3892         len = sizeof(struct hsm_user_request) +
3893               sizeof(struct hsm_user_item);
3894         OBD_ALLOC(hur, len);
3895         if (hur == NULL)
3896                 RETURN(-ENOMEM);
3897
3898         hur->hur_request.hr_action = HUA_RESTORE;
3899         hur->hur_request.hr_archive_id = 0;
3900         hur->hur_request.hr_flags = 0;
3901         memcpy(&hur->hur_user_item[0].hui_fid, &ll_i2info(inode)->lli_fid,
3902                sizeof(hur->hur_user_item[0].hui_fid));
3903         hur->hur_user_item[0].hui_extent.offset = offset;
3904         hur->hur_user_item[0].hui_extent.length = length;
3905         hur->hur_request.hr_itemcount = 1;
3906         rc = obd_iocontrol(LL_IOC_HSM_REQUEST, ll_i2sbi(inode)->ll_md_exp,
3907                            len, hur, NULL);
3908         OBD_FREE(hur, len);
3909         RETURN(rc);
3910 }