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