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