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