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