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