Whamcloud - gitweb
LU-15535 llite: deadlock on lli_lsm_sem
[fs/lustre-release.git] / lustre / llite / namei.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
32 #include <linux/fs.h>
33 #include <linux/sched.h>
34 #include <linux/mm.h>
35 #include <linux/file.h>
36 #include <linux/quotaops.h>
37 #include <linux/highmem.h>
38 #include <linux/pagemap.h>
39 #include <linux/user_namespace.h>
40 #include <linux/uidgid.h>
41
42 #define DEBUG_SUBSYSTEM S_LLITE
43
44 #include <obd_support.h>
45 #include <lustre_fid.h>
46 #include <lustre_dlm.h>
47 #include "llite_internal.h"
48
49 #ifndef HAVE_USER_NAMESPACE_ARG
50 #define ll_create_nd(ns, dir, de, mode, ex)     ll_create_nd(dir, de, mode, ex)
51 #define ll_mkdir(ns, dir, dch, mode)            ll_mkdir(dir, dch, mode)
52 #define ll_mknod(ns, dir, dch, mode, rd)        ll_mknod(dir, dch, mode, rd)
53 #ifdef HAVE_IOPS_RENAME_WITH_FLAGS
54 #define ll_rename(ns, src, sdc, tgt, tdc, fl)   ll_rename(src, sdc, tgt, tdc, fl)
55 #else
56 #define ll_rename(ns, src, sdc, tgt, tdc)       ll_rename(src, sdc, tgt, tdc)
57 #endif /* HAVE_IOPS_RENAME_WITH_FLAGS */
58 #define ll_symlink(nd, dir, dch, old)           ll_symlink(dir, dch, old)
59 #endif
60
61 static int ll_create_it(struct inode *dir, struct dentry *dentry,
62                         struct lookup_intent *it,
63                         void *secctx, __u32 secctxlen, bool encrypt,
64                         void *encctx, __u32 encctxlen, unsigned int open_flags);
65
66 /* called from iget5_locked->find_inode() under inode_lock spinlock */
67 static int ll_test_inode(struct inode *inode, void *opaque)
68 {
69         struct ll_inode_info    *lli = ll_i2info(inode);
70         struct lustre_md        *md = opaque;
71
72         if (unlikely(!(md->body->mbo_valid & OBD_MD_FLID))) {
73                 CERROR("MDS body missing FID\n");
74                 return 0;
75         }
76
77         if (!lu_fid_eq(&lli->lli_fid, &md->body->mbo_fid1))
78                 return 0;
79
80         return 1;
81 }
82
83 static int ll_set_inode(struct inode *inode, void *opaque)
84 {
85         struct ll_inode_info *lli = ll_i2info(inode);
86         struct mdt_body *body = ((struct lustre_md *)opaque)->body;
87
88         if (unlikely(!(body->mbo_valid & OBD_MD_FLID))) {
89                 CERROR("MDS body missing FID\n");
90                 return -EINVAL;
91         }
92
93         lli->lli_fid = body->mbo_fid1;
94         if (unlikely(!(body->mbo_valid & OBD_MD_FLTYPE))) {
95                 CERROR("Can not initialize inode "DFID" without object type: "
96                        "valid = %#llx\n",
97                        PFID(&lli->lli_fid), body->mbo_valid);
98                 return -EINVAL;
99         }
100
101         inode->i_mode = (inode->i_mode & ~S_IFMT) | (body->mbo_mode & S_IFMT);
102         if (unlikely(inode->i_mode == 0)) {
103                 CERROR("Invalid inode "DFID" type\n", PFID(&lli->lli_fid));
104                 return -EINVAL;
105         }
106
107         ll_lli_init(lli);
108
109         return 0;
110 }
111
112
113 /**
114  * Get an inode by inode number(@hash), which is already instantiated by
115  * the intent lookup).
116  */
117 struct inode *ll_iget(struct super_block *sb, ino_t hash,
118                       struct lustre_md *md)
119 {
120         struct inode    *inode;
121         int             rc = 0;
122
123         ENTRY;
124
125         LASSERT(hash != 0);
126         inode = iget5_locked(sb, hash, ll_test_inode, ll_set_inode, md);
127         if (inode == NULL)
128                 RETURN(ERR_PTR(-ENOMEM));
129
130         if (inode->i_state & I_NEW) {
131                 rc = ll_read_inode2(inode, md);
132                 if (rc == 0 && S_ISREG(inode->i_mode) &&
133                     ll_i2info(inode)->lli_clob == NULL)
134                         rc = cl_file_inode_init(inode, md);
135
136                 if (rc != 0) {
137                         /* Let's clear directory lsm here, otherwise
138                          * make_bad_inode() will reset the inode mode
139                          * to regular, then ll_clear_inode will not
140                          * be able to clear lsm_md */
141                         if (S_ISDIR(inode->i_mode))
142                                 ll_dir_clear_lsm_md(inode);
143                         make_bad_inode(inode);
144                         unlock_new_inode(inode);
145                         iput(inode);
146                         inode = ERR_PTR(rc);
147                 } else {
148                         inode_has_no_xattr(inode);
149                         unlock_new_inode(inode);
150                 }
151         } else if (is_bad_inode(inode)) {
152                 iput(inode);
153                 inode = ERR_PTR(-ESTALE);
154         } else if (!(inode->i_state & (I_FREEING | I_CLEAR))) {
155                 rc = ll_update_inode(inode, md);
156                 CDEBUG(D_VFSTRACE, "got inode: "DFID"(%p): rc = %d\n",
157                        PFID(&md->body->mbo_fid1), inode, rc);
158                 if (rc != 0) {
159                         if (S_ISDIR(inode->i_mode))
160                                 ll_dir_clear_lsm_md(inode);
161                         iput(inode);
162                         inode = ERR_PTR(rc);
163                 }
164         }
165
166         RETURN(inode);
167 }
168
169 /* mark negative sub file dentries invalid and prune unused dentries */
170 static void ll_prune_negative_children(struct inode *dir)
171 {
172         struct dentry *dentry;
173         struct dentry *child;
174
175         ENTRY;
176
177 restart:
178         spin_lock(&dir->i_lock);
179         hlist_for_each_entry(dentry, &dir->i_dentry, d_alias) {
180                 spin_lock(&dentry->d_lock);
181                 list_for_each_entry(child, &dentry->d_subdirs, d_child) {
182                         if (child->d_inode)
183                                 continue;
184
185                         spin_lock_nested(&child->d_lock, DENTRY_D_LOCK_NESTED);
186                         if (lld_is_init(child))
187                                 ll_d2d(child)->lld_invalid = 1;
188                         if (!ll_d_count(child)) {
189                                 dget_dlock(child);
190                                 __d_drop(child);
191                                 spin_unlock(&child->d_lock);
192                                 spin_unlock(&dentry->d_lock);
193                                 spin_unlock(&dir->i_lock);
194
195                                 CDEBUG(D_DENTRY, "prune negative dentry %pd\n",
196                                        child);
197
198                                 dput(child);
199                                 goto restart;
200                         }
201                         spin_unlock(&child->d_lock);
202                 }
203                 spin_unlock(&dentry->d_lock);
204         }
205         spin_unlock(&dir->i_lock);
206
207         EXIT;
208 }
209
210 int ll_test_inode_by_fid(struct inode *inode, void *opaque)
211 {
212         return lu_fid_eq(&ll_i2info(inode)->lli_fid, opaque);
213 }
214
215 static int ll_dom_lock_cancel(struct inode *inode, struct ldlm_lock *lock)
216 {
217         struct lu_env *env;
218         struct ll_inode_info *lli = ll_i2info(inode);
219         __u16 refcheck;
220         int rc;
221         ENTRY;
222
223         env = cl_env_get(&refcheck);
224         if (IS_ERR(env))
225                 RETURN(PTR_ERR(env));
226
227         CFS_FAIL_TIMEOUT(OBD_FAIL_LDLM_REPLAY_PAUSE, cfs_fail_val);
228
229         /* reach MDC layer to flush data under  the DoM ldlm lock */
230         rc = cl_object_flush(env, lli->lli_clob, lock);
231         if (rc == -ENODATA) {
232                 CDEBUG(D_INODE, "inode "DFID" layout has no DoM stripe\n",
233                        PFID(ll_inode2fid(inode)));
234                 /* most likely result of layout change, do nothing */
235                 rc = 0;
236         }
237
238         cl_env_put(env, &refcheck);
239         RETURN(rc);
240 }
241
242 static void ll_lock_cancel_bits(struct ldlm_lock *lock, __u64 to_cancel)
243 {
244         struct inode *inode = ll_inode_from_resource_lock(lock);
245         struct ll_inode_info *lli;
246         __u64 bits = to_cancel;
247         int rc;
248
249         ENTRY;
250
251         if (!inode) {
252                 /* That means the inode is evicted most likely and may cause
253                  * the skipping of lock cleanups below, so print the message
254                  * about that in log.
255                  */
256                 if (lock->l_resource->lr_lvb_inode)
257                         LDLM_DEBUG(lock,
258                                    "can't take inode for the lock (%sevicted)",
259                                    lock->l_resource->lr_lvb_inode->i_state &
260                                    I_FREEING ? "" : "not ");
261                 RETURN_EXIT;
262         }
263
264         if (!fid_res_name_eq(ll_inode2fid(inode),
265                              &lock->l_resource->lr_name)) {
266                 LDLM_ERROR(lock, "data mismatch with object "DFID"(%p)",
267                            PFID(ll_inode2fid(inode)), inode);
268                 LBUG();
269         }
270
271         if (bits & MDS_INODELOCK_XATTR) {
272                 ll_xattr_cache_empty(inode);
273                 bits &= ~MDS_INODELOCK_XATTR;
274         }
275
276         /* For OPEN locks we differentiate between lock modes
277          * LCK_CR, LCK_CW, LCK_PR - bug 22891 */
278         if (bits & MDS_INODELOCK_OPEN)
279                 ll_have_md_lock(lock->l_conn_export, inode, &bits,
280                                 lock->l_req_mode);
281
282         if (bits & MDS_INODELOCK_OPEN) {
283                 fmode_t fmode;
284
285                 switch (lock->l_req_mode) {
286                 case LCK_CW:
287                         fmode = FMODE_WRITE;
288                         break;
289                 case LCK_PR:
290                         fmode = FMODE_EXEC;
291                         break;
292                 case LCK_CR:
293                         fmode = FMODE_READ;
294                         break;
295                 default:
296                         LDLM_ERROR(lock, "bad lock mode for OPEN lock");
297                         LBUG();
298                 }
299
300                 ll_md_real_close(inode, fmode);
301
302                 bits &= ~MDS_INODELOCK_OPEN;
303         }
304
305         if (bits & (MDS_INODELOCK_LOOKUP | MDS_INODELOCK_UPDATE |
306                     MDS_INODELOCK_LAYOUT | MDS_INODELOCK_PERM |
307                     MDS_INODELOCK_DOM))
308                 ll_have_md_lock(lock->l_conn_export, inode, &bits, LCK_MINMODE);
309
310         if (bits & MDS_INODELOCK_DOM) {
311                 rc =  ll_dom_lock_cancel(inode, lock);
312                 if (rc < 0)
313                         CDEBUG(D_INODE, "cannot flush DoM data "
314                                DFID": rc = %d\n",
315                                PFID(ll_inode2fid(inode)), rc);
316         }
317
318         if (bits & MDS_INODELOCK_LAYOUT) {
319                 struct cl_object_conf conf = {
320                         .coc_opc = OBJECT_CONF_INVALIDATE,
321                         .coc_inode = inode,
322                 };
323
324                 rc = ll_layout_conf(inode, &conf);
325                 if (rc < 0)
326                         CDEBUG(D_INODE, "cannot invalidate layout of "
327                                DFID": rc = %d\n",
328                                PFID(ll_inode2fid(inode)), rc);
329         }
330
331         lli = ll_i2info(inode);
332
333         if (bits & MDS_INODELOCK_UPDATE)
334                 set_bit(LLIF_UPDATE_ATIME, &lli->lli_flags);
335
336         if ((bits & MDS_INODELOCK_UPDATE) && S_ISDIR(inode->i_mode)) {
337                 CDEBUG(D_INODE, "invalidating inode "DFID" lli = %p, "
338                        "pfid  = "DFID"\n", PFID(ll_inode2fid(inode)),
339                        lli, PFID(&lli->lli_pfid));
340                 truncate_inode_pages(inode->i_mapping, 0);
341
342                 if (unlikely(!fid_is_zero(&lli->lli_pfid))) {
343                         struct inode *master_inode = NULL;
344                         unsigned long hash;
345
346                         /* This is slave inode, since all of the child dentry
347                          * is connected on the master inode, so we have to
348                          * invalidate the negative children on master inode */
349                         CDEBUG(D_INODE, "Invalidate s"DFID" m"DFID"\n",
350                                PFID(ll_inode2fid(inode)), PFID(&lli->lli_pfid));
351
352                         hash = cl_fid_build_ino(&lli->lli_pfid,
353                                         ll_need_32bit_api(ll_i2sbi(inode)));
354
355                         /* Do not lookup the inode with ilookup5, otherwise
356                          * it will cause dead lock,
357                          * 1. Client1 send chmod req to the MDT0, then on MDT0,
358                          * it enqueues master and all of its slaves lock,
359                          * (mdt_attr_set() -> mdt_lock_slaves()), after gets
360                          * master and stripe0 lock, it will send the enqueue
361                          * req (for stripe1) to MDT1, then MDT1 finds the lock
362                          * has been granted to client2. Then MDT1 sends blocking
363                          * ast to client2.
364                          * 2. At the same time, client2 tries to unlink
365                          * the striped dir (rm -rf striped_dir), and during
366                          * lookup, it will hold the master inode of the striped
367                          * directory, whose inode state is NEW, then tries to
368                          * revalidate all of its slaves, (ll_prep_inode()->
369                          * ll_iget()->ll_read_inode2()-> ll_update_inode().).
370                          * And it will be blocked on the server side because
371                          * of 1.
372                          * 3. Then the client get the blocking_ast req, cancel
373                          * the lock, but being blocked if using ->ilookup5()),
374                          * because master inode state is NEW. */
375                         master_inode = ilookup5_nowait(inode->i_sb, hash,
376                                                         ll_test_inode_by_fid,
377                                                         (void *)&lli->lli_pfid);
378                         if (master_inode) {
379                                 ll_prune_negative_children(master_inode);
380                                 iput(master_inode);
381                         }
382                 } else {
383                         ll_prune_negative_children(inode);
384                 }
385         }
386
387         /* at umount s_root becomes NULL */
388         if ((bits & (MDS_INODELOCK_LOOKUP | MDS_INODELOCK_PERM)) &&
389             inode->i_sb->s_root && !is_root_inode(inode))
390                 ll_prune_aliases(inode);
391
392         if (bits & (MDS_INODELOCK_LOOKUP | MDS_INODELOCK_PERM))
393                 forget_all_cached_acls(inode);
394
395         iput(inode);
396         RETURN_EXIT;
397 }
398
399 /* Check if the given lock may be downgraded instead of canceling and
400  * that convert is really needed. */
401 static int ll_md_need_convert(struct ldlm_lock *lock)
402 {
403         struct ldlm_namespace *ns = ldlm_lock_to_ns(lock);
404         struct inode *inode;
405         __u64 wanted = lock->l_policy_data.l_inodebits.cancel_bits;
406         __u64 bits = lock->l_policy_data.l_inodebits.bits & ~wanted;
407         enum ldlm_mode mode = LCK_MINMODE;
408
409         if (!lock->l_conn_export ||
410             !exp_connect_lock_convert(lock->l_conn_export))
411                 return 0;
412
413         if (!wanted || !bits || ldlm_is_cancel(lock))
414                 return 0;
415
416         /* do not convert locks other than DOM for now */
417         if (!((bits | wanted) & MDS_INODELOCK_DOM))
418                 return 0;
419
420         /* We may have already remaining bits in some other lock so
421          * lock convert will leave us just extra lock for the same bit.
422          * Check if client has other lock with the same bits and the same
423          * or lower mode and don't convert if any.
424          */
425         switch (lock->l_req_mode) {
426         case LCK_PR:
427                 mode = LCK_PR;
428                 fallthrough;
429         case LCK_PW:
430                 mode |= LCK_CR;
431                 break;
432         case LCK_CW:
433                 mode = LCK_CW;
434                 fallthrough;
435         case LCK_CR:
436                 mode |= LCK_CR;
437                 break;
438         default:
439                 /* do not convert other modes */
440                 return 0;
441         }
442
443         /* is lock is too old to be converted? */
444         lock_res_and_lock(lock);
445         if (ktime_after(ktime_get(),
446                         ktime_add(lock->l_last_used, ns->ns_dirty_age_limit))) {
447                 unlock_res_and_lock(lock);
448                 return 0;
449         }
450         unlock_res_and_lock(lock);
451
452         inode = ll_inode_from_resource_lock(lock);
453         ll_have_md_lock(lock->l_conn_export, inode, &bits, mode);
454         iput(inode);
455         return !!(bits);
456 }
457
458 int ll_md_blocking_ast(struct ldlm_lock *lock, struct ldlm_lock_desc *ld,
459                        void *data, int flag)
460 {
461         struct lustre_handle lockh;
462         int rc;
463
464         ENTRY;
465
466         switch (flag) {
467         case LDLM_CB_BLOCKING:
468         {
469                 __u64 cancel_flags = LCF_ASYNC;
470
471                 /* if lock convert is not needed then still have to
472                  * pass lock via ldlm_cli_convert() to keep all states
473                  * correct, set cancel_bits to full lock bits to cause
474                  * full cancel to happen.
475                  */
476                 if (!ll_md_need_convert(lock)) {
477                         lock_res_and_lock(lock);
478                         lock->l_policy_data.l_inodebits.cancel_bits =
479                                         lock->l_policy_data.l_inodebits.bits;
480                         unlock_res_and_lock(lock);
481                 }
482                 rc = ldlm_cli_convert(lock, cancel_flags);
483                 if (!rc)
484                         RETURN(0);
485                 /* continue with cancel otherwise */
486                 ldlm_lock2handle(lock, &lockh);
487                 rc = ldlm_cli_cancel(&lockh, cancel_flags);
488                 if (rc < 0) {
489                         CDEBUG(D_INODE, "ldlm_cli_cancel: rc = %d\n", rc);
490                         RETURN(rc);
491                 }
492                 break;
493         }
494         case LDLM_CB_CANCELING:
495         {
496                 __u64 to_cancel = lock->l_policy_data.l_inodebits.bits;
497
498                 /* Nothing to do for non-granted locks */
499                 if (!ldlm_is_granted(lock))
500                         break;
501
502                 /* If 'ld' is supplied then bits to be cancelled are passed
503                  * implicitly by lock converting and cancel_bits from 'ld'
504                  * should be used. Otherwise full cancel is being performed
505                  * and lock inodebits are used.
506                  *
507                  * Note: we cannot rely on cancel_bits in lock itself at this
508                  * moment because they can be changed by concurrent thread,
509                  * so ldlm_cli_inodebits_convert() pass cancel bits implicitly
510                  * in 'ld' parameter.
511                  */
512                 if (ld) {
513                         /* partial bits cancel allowed only during convert */
514                         LASSERT(ldlm_is_converting(lock));
515                         /* mask cancel bits by lock bits so only no any unused
516                          * bits are passed to ll_lock_cancel_bits()
517                          */
518                         to_cancel &= ld->l_policy_data.l_inodebits.cancel_bits;
519                 }
520                 ll_lock_cancel_bits(lock, to_cancel);
521                 break;
522         }
523         default:
524                 LBUG();
525         }
526
527         RETURN(0);
528 }
529
530 __u32 ll_i2suppgid(struct inode *i)
531 {
532         if (in_group_p(i->i_gid))
533                 return (__u32)from_kgid(&init_user_ns, i->i_gid);
534         else
535                 return (__u32) __kgid_val(INVALID_GID);
536 }
537
538 /* Pack the required supplementary groups into the supplied groups array. */
539 void ll_i2gids(__u32 *suppgids, struct inode *i1, struct inode *i2)
540 {
541         LASSERT(i1 != NULL);
542         LASSERT(suppgids != NULL);
543
544         suppgids[0] = ll_i2suppgid(i1);
545
546         if (i2)
547                 suppgids[1] = ll_i2suppgid(i2);
548         else
549                 suppgids[1] = -1;
550 }
551
552 /*
553  * try to reuse three types of dentry:
554  * 1. unhashed alias, this one is unhashed by d_invalidate (but it may be valid
555  *    by concurrent .revalidate).
556  * 2. INVALID alias (common case for no valid ldlm lock held, but this flag may
557  *    be cleared by others calling d_lustre_revalidate).
558  * 3. DISCONNECTED alias.
559  */
560 static struct dentry *ll_find_alias(struct inode *inode, struct dentry *dentry)
561 {
562         struct dentry *alias, *discon_alias, *invalid_alias;
563
564         if (hlist_empty(&inode->i_dentry))
565                 return NULL;
566
567         discon_alias = invalid_alias = NULL;
568
569         spin_lock(&inode->i_lock);
570         hlist_for_each_entry(alias, &inode->i_dentry, d_alias) {
571                 LASSERT(alias != dentry);
572
573                 spin_lock(&alias->d_lock);
574                 if ((alias->d_flags & DCACHE_DISCONNECTED) &&
575                     S_ISDIR(inode->i_mode))
576                         /* LASSERT(last_discon == NULL); LU-405, bz 20055 */
577                         discon_alias = alias;
578                 else if (alias->d_parent == dentry->d_parent             &&
579                          alias->d_name.hash == dentry->d_name.hash       &&
580                          alias->d_name.len == dentry->d_name.len         &&
581                          memcmp(alias->d_name.name, dentry->d_name.name,
582                                 dentry->d_name.len) == 0)
583                         invalid_alias = alias;
584                 spin_unlock(&alias->d_lock);
585
586                 if (invalid_alias)
587                         break;
588         }
589         alias = invalid_alias ?: discon_alias ?: NULL;
590         if (alias) {
591                 spin_lock(&alias->d_lock);
592                 dget_dlock(alias);
593                 spin_unlock(&alias->d_lock);
594         }
595         spin_unlock(&inode->i_lock);
596
597         return alias;
598 }
599
600 /*
601  * Similar to d_splice_alias(), but lustre treats invalid alias
602  * similar to DCACHE_DISCONNECTED, and tries to use it anyway.
603  */
604 struct dentry *ll_splice_alias(struct inode *inode, struct dentry *de)
605 {
606         struct dentry *new;
607
608         if (inode) {
609                 new = ll_find_alias(inode, de);
610                 if (new) {
611                         if (!ll_d_setup(new, true))
612                                 return ERR_PTR(-ENOMEM);
613                         d_move(new, de);
614                         iput(inode);
615                         CDEBUG(D_DENTRY,
616                                "Reuse dentry %p inode %p refc %d flags %#x\n",
617                               new, new->d_inode, ll_d_count(new), new->d_flags);
618                         return new;
619                 }
620         }
621         if (!ll_d_setup(de, false))
622                 return ERR_PTR(-ENOMEM);
623         d_add(de, inode);
624
625         /* this needs only to be done for foreign symlink dirs as
626          * DCACHE_SYMLINK_TYPE is already set by d_flags_for_inode()
627          * kernel routine for files with symlink ops (ie, real symlink)
628          */
629         if (inode && S_ISDIR(inode->i_mode) &&
630             ll_sbi_has_foreign_symlink(ll_i2sbi(inode)) &&
631 #ifdef HAVE_IOP_GET_LINK
632             inode->i_op->get_link) {
633 #else
634             inode->i_op->follow_link) {
635 #endif
636                 CDEBUG(D_INFO, "%s: inode "DFID": faking foreign dir as a symlink\n",
637                        ll_i2sbi(inode)->ll_fsname, PFID(ll_inode2fid(inode)));
638                 spin_lock(&de->d_lock);
639                 /* like d_flags_for_inode() already does for files */
640                 de->d_flags = (de->d_flags & ~DCACHE_ENTRY_TYPE) |
641                               DCACHE_SYMLINK_TYPE;
642                 spin_unlock(&de->d_lock);
643         }
644
645         CDEBUG(D_DENTRY, "Add dentry %p inode %p refc %d flags %#x\n",
646                de, de->d_inode, ll_d_count(de), de->d_flags);
647         return de;
648 }
649
650 static int ll_lookup_it_finish(struct ptlrpc_request *request,
651                                struct lookup_intent *it,
652                                struct inode *parent, struct dentry **de,
653                                void *secctx, __u32 secctxlen,
654                                void *encctx, __u32 encctxlen,
655                                ktime_t kstart, bool encrypt)
656 {
657         struct inode             *inode = NULL;
658         __u64                     bits = 0;
659         int                       rc;
660         struct dentry *alias;
661         ENTRY;
662
663         /* NB 1 request reference will be taken away by ll_intent_lock()
664          * when I return */
665         CDEBUG(D_DENTRY, "it %p it_disposition %x\n", it,
666                it->it_disposition);
667         if (!it_disposition(it, DISP_LOOKUP_NEG)) {
668                 struct req_capsule *pill = &request->rq_pill;
669                 struct mdt_body *body = req_capsule_server_get(pill,
670                                                                &RMF_MDT_BODY);
671
672                 rc = ll_prep_inode(&inode, &request->rq_pill, (*de)->d_sb, it);
673                 if (rc)
674                         RETURN(rc);
675
676                 /* If encryption context was returned by MDT, put it in
677                  * inode now to save an extra getxattr and avoid deadlock.
678                  */
679                 if (body->mbo_valid & OBD_MD_ENCCTX) {
680                         encctx = req_capsule_server_get(pill, &RMF_FILE_ENCCTX);
681                         encctxlen = req_capsule_get_size(pill,
682                                                          &RMF_FILE_ENCCTX,
683                                                          RCL_SERVER);
684
685                         if (encctxlen) {
686                                 CDEBUG(D_SEC,
687                                        "server returned encryption ctx for "DFID"\n",
688                                        PFID(ll_inode2fid(inode)));
689                                 rc = ll_xattr_cache_insert(inode,
690                                                            xattr_for_enc(inode),
691                                                            encctx, encctxlen);
692                                 if (rc)
693                                         CWARN("%s: cannot set enc ctx for "DFID": rc = %d\n",
694                                               ll_i2sbi(inode)->ll_fsname,
695                                               PFID(ll_inode2fid(inode)), rc);
696                                 else if (encrypt) {
697                                         rc = llcrypt_prepare_readdir(inode);
698                                         if (rc)
699                                                 CDEBUG(D_SEC,
700                                                  "cannot get enc info for "DFID": rc = %d\n",
701                                                  PFID(ll_inode2fid(inode)), rc);
702                                 }
703                         }
704                 }
705
706                 ll_set_lock_data(ll_i2sbi(parent)->ll_md_exp, inode, it, &bits);
707                 /* OPEN can return data if lock has DoM+LAYOUT bits set */
708                 if (it->it_op & IT_OPEN &&
709                     bits & MDS_INODELOCK_DOM && bits & MDS_INODELOCK_LAYOUT)
710                         ll_dom_finish_open(inode, request);
711
712                 /* We used to query real size from OSTs here, but actually
713                  * this is not needed. For stat() calls size would be updated
714                  * from subsequent do_revalidate()->ll_inode_revalidate_it() in
715                  * 2.4 and
716                  * vfs_getattr_it->ll_getattr()->ll_inode_revalidate_it() in 2.6
717                  * Everybody else who needs correct file size would call
718                  * ll_glimpse_size or some equivalent themselves anyway.
719                  * Also see bug 7198.
720                  */
721
722                 /* If security context was returned by MDT, put it in
723                  * inode now to save an extra getxattr from security hooks,
724                  * and avoid deadlock.
725                  */
726                 if (body->mbo_valid & OBD_MD_SECCTX) {
727                         secctx = req_capsule_server_get(pill, &RMF_FILE_SECCTX);
728                         secctxlen = req_capsule_get_size(pill,
729                                                            &RMF_FILE_SECCTX,
730                                                            RCL_SERVER);
731
732                         if (secctxlen)
733                                 CDEBUG(D_SEC, "server returned security context"
734                                        " for "DFID"\n",
735                                        PFID(ll_inode2fid(inode)));
736                 }
737
738                 /* resume normally on error */
739                 ll_inode_notifysecctx(inode, secctx, secctxlen);
740         }
741
742         /* Only hash *de if it is unhashed (new dentry).
743          * Atoimc_open may passin hashed dentries for open.
744          */
745         alias = ll_splice_alias(inode, *de);
746         if (IS_ERR(alias))
747                 GOTO(out, rc = PTR_ERR(alias));
748
749         *de = alias;
750
751         if (!it_disposition(it, DISP_LOOKUP_NEG)) {
752                 /* We have the "lookup" lock, so unhide dentry */
753                 if (bits & MDS_INODELOCK_LOOKUP)
754                         d_lustre_revalidate(*de);
755                 /* open may not fetch LOOKUP lock, update dir depth/dmv anyway
756                  * in case it's used uninitialized.
757                  */
758                 if (S_ISDIR(inode->i_mode))
759                         ll_update_dir_depth_dmv(parent, *de);
760
761                 if (encrypt) {
762                         rc = llcrypt_prepare_readdir(inode);
763                         if (rc)
764                                 GOTO(out, rc);
765                 }
766         } else if (!it_disposition(it, DISP_OPEN_CREATE)) {
767                 /*
768                  * If file was created on the server, the dentry is revalidated
769                  * in ll_create_it if the lock allows for it.
770                  */
771                 /* Check that parent has UPDATE lock. */
772                 struct lookup_intent parent_it = {
773                                         .it_op = IT_GETATTR,
774                                         .it_lock_handle = 0 };
775                 struct lu_fid   fid = ll_i2info(parent)->lli_fid;
776
777                 /* If it is striped directory, get the real stripe parent */
778                 if (unlikely(ll_dir_striped(parent))) {
779                         down_read(&ll_i2info(parent)->lli_lsm_sem);
780                         rc = md_get_fid_from_lsm(ll_i2mdexp(parent),
781                                                  ll_i2info(parent)->lli_lsm_obj,
782                                                  (*de)->d_name.name,
783                                                  (*de)->d_name.len, &fid);
784                         up_read(&ll_i2info(parent)->lli_lsm_sem);
785                         if (rc != 0)
786                                 GOTO(out, rc);
787                 }
788
789                 if (md_revalidate_lock(ll_i2mdexp(parent), &parent_it, &fid,
790                                        NULL)) {
791                         d_lustre_revalidate(*de);
792                         ll_intent_release(&parent_it);
793                 }
794         }
795
796         if (it_disposition(it, DISP_OPEN_CREATE)) {
797                 ll_stats_ops_tally(ll_i2sbi(parent), LPROC_LL_MKNOD,
798                                    ktime_us_delta(ktime_get(), kstart));
799         }
800
801         GOTO(out, rc = 0);
802
803 out:
804         if (rc != 0 && it->it_op & IT_OPEN) {
805                 ll_intent_drop_lock(it);
806                 ll_open_cleanup((*de)->d_sb, &request->rq_pill);
807         }
808
809         return rc;
810 }
811
812 static struct dentry *ll_lookup_it(struct inode *parent, struct dentry *dentry,
813                                    struct lookup_intent *it,
814                                    void **secctx, __u32 *secctxlen,
815                                    int *secctxslot,
816                                    struct pcc_create_attach *pca,
817                                    bool encrypt,
818                                    void **encctx, __u32 *encctxlen)
819 {
820         ktime_t kstart = ktime_get();
821         struct lookup_intent lookup_it = { .it_op = IT_LOOKUP };
822         struct dentry *save = dentry, *retval;
823         struct ptlrpc_request *req = NULL;
824         struct md_op_data *op_data = NULL;
825         struct lov_user_md *lum = NULL;
826         struct ll_sb_info *sbi = ll_i2sbi(parent);
827         __u32 opc;
828         int rc;
829         struct llcrypt_name fname;
830         struct lu_fid fid;
831         ENTRY;
832
833         if (dentry->d_name.len > sbi->ll_namelen)
834                 RETURN(ERR_PTR(-ENAMETOOLONG));
835
836         CDEBUG(D_VFSTRACE, "VFS Op:name=%pd, dir="DFID"(%p), intent=%s\n",
837                dentry, PFID(ll_inode2fid(parent)), parent, LL_IT2STR(it));
838
839         if (d_mountpoint(dentry))
840                 CERROR("Tell Peter, lookup on mtpt, it %s\n", LL_IT2STR(it));
841
842         if (it == NULL || it->it_op == IT_GETXATTR)
843                 it = &lookup_it;
844
845         if (it->it_op == IT_GETATTR && dentry_may_statahead(parent, dentry)) {
846                 rc = ll_revalidate_statahead(parent, &dentry, 0);
847                 if (rc == 1)
848                         RETURN(dentry == save ? NULL : dentry);
849         }
850
851         if (it->it_op & IT_OPEN && it->it_flags & FMODE_WRITE &&
852             dentry->d_sb->s_flags & SB_RDONLY)
853                 RETURN(ERR_PTR(-EROFS));
854
855         if (it->it_op & IT_CREAT)
856                 opc = LUSTRE_OPC_CREATE;
857         else
858                 opc = LUSTRE_OPC_LOOKUP;
859
860         rc = ll_prepare_lookup(parent, dentry, &fname, &fid);
861         if (rc)
862                 RETURN(rc != -ENOENT ? ERR_PTR(rc) : NULL);
863
864         op_data = ll_prep_md_op_data(NULL, parent, NULL, fname.disk_name.name,
865                                      fname.disk_name.len, 0, opc, NULL);
866         if (IS_ERR(op_data)) {
867                 llcrypt_free_filename(&fname);
868                 RETURN(ERR_CAST(op_data));
869         }
870         if (!fid_is_zero(&fid)) {
871                 op_data->op_fid2 = fid;
872                 op_data->op_bias = MDS_FID_OP;
873                 if (it->it_op & IT_OPEN)
874                         it->it_flags |= MDS_OPEN_BY_FID;
875         }
876
877         /* enforce umask if acl disabled or MDS doesn't support umask */
878         if (!IS_POSIXACL(parent) || !exp_connect_umask(ll_i2mdexp(parent)))
879                 it->it_create_mode &= ~current_umask();
880
881         if (it->it_op & IT_CREAT &&
882             test_bit(LL_SBI_FILE_SECCTX, sbi->ll_flags)) {
883                 rc = ll_dentry_init_security(dentry, it->it_create_mode,
884                                              &dentry->d_name,
885                                              &op_data->op_file_secctx_name,
886                                              &op_data->op_file_secctx_name_size,
887                                              &op_data->op_file_secctx,
888                                              &op_data->op_file_secctx_size,
889                                              &op_data->op_file_secctx_slot);
890                 if (rc < 0)
891                         GOTO(out, retval = ERR_PTR(rc));
892                 if (secctx != NULL)
893                         *secctx = op_data->op_file_secctx;
894                 if (secctxlen != NULL)
895                         *secctxlen = op_data->op_file_secctx_size;
896                 if (secctxslot != NULL)
897                         *secctxslot = op_data->op_file_secctx_slot;
898         } else {
899                 if (secctx != NULL)
900                         *secctx = NULL;
901                 if (secctxlen != NULL)
902                         *secctxlen = 0;
903                 if (secctxslot != NULL)
904                         *secctxslot = 0;
905         }
906         if (it->it_op & IT_CREAT && encrypt) {
907                 if (unlikely(filename_is_volatile(dentry->d_name.name,
908                                                   dentry->d_name.len, NULL))) {
909                         /* get encryption context from reference file */
910                         int ctx_size = LLCRYPT_ENC_CTX_SIZE;
911                         struct lustre_sb_info *lsi;
912                         struct file *ref_file;
913                         struct inode *ref_inode;
914                         void *ctx;
915
916                         rc = volatile_ref_file(dentry->d_name.name,
917                                                dentry->d_name.len,
918                                                &ref_file);
919                         if (rc)
920                                 GOTO(out, retval = ERR_PTR(rc));
921
922                         ref_inode = file_inode(ref_file);
923                         if (!ref_inode) {
924                                 fput(ref_file);
925                                 GOTO(inherit, rc = -EINVAL);
926                         }
927
928                         lsi = s2lsi(ref_inode->i_sb);
929
930 getctx:
931                         OBD_ALLOC(ctx, ctx_size);
932                         if (!ctx)
933                                 GOTO(out, retval = ERR_PTR(-ENOMEM));
934
935 #ifdef CONFIG_LL_ENCRYPTION
936                         rc = lsi->lsi_cop->get_context(ref_inode,
937                                                        ctx, ctx_size);
938 #elif defined(HAVE_LUSTRE_CRYPTO)
939                         rc = ref_inode->i_sb->s_cop->get_context(ref_inode,
940                                                                  ctx, ctx_size);
941 #else
942                         rc = -ENODATA;
943 #endif
944                         if (rc == -ERANGE) {
945                                 OBD_FREE(ctx, ctx_size);
946                                 ctx_size *= 2;
947                                 goto getctx;
948                         }
949                         fput(ref_file);
950                         if (rc < 0) {
951                                 OBD_FREE(ctx, ctx_size);
952                                 GOTO(inherit, rc);
953                         }
954
955                         op_data->op_file_encctx_size = rc;
956                         if (rc == ctx_size) {
957                                 op_data->op_file_encctx = ctx;
958                         } else {
959                                 OBD_ALLOC(op_data->op_file_encctx,
960                                           op_data->op_file_encctx_size);
961                                 if (!op_data->op_file_encctx) {
962                                         OBD_FREE(ctx, ctx_size);
963                                         GOTO(out, retval = ERR_PTR(-ENOMEM));
964                                 }
965                                 memcpy(op_data->op_file_encctx, ctx,
966                                        op_data->op_file_encctx_size);
967                                 OBD_FREE(ctx, ctx_size);
968                         }
969                 } else {
970 inherit:
971                         rc = llcrypt_inherit_context(parent, NULL, op_data,
972                                                      false);
973                         if (rc)
974                                 GOTO(out, retval = ERR_PTR(rc));
975                 }
976                 if (encctx != NULL)
977                         *encctx = op_data->op_file_encctx;
978                 if (encctxlen != NULL)
979                         *encctxlen = op_data->op_file_encctx_size;
980         } else {
981                 if (encctx != NULL)
982                         *encctx = NULL;
983                 if (encctxlen != NULL)
984                         *encctxlen = 0;
985         }
986
987         /* ask for security context upon intent:
988          * get name of security xattr to request to server
989          */
990         if (it->it_op & (IT_LOOKUP | IT_GETATTR | IT_OPEN))
991                 op_data->op_file_secctx_name_size =
992                         ll_secctx_name_get(sbi, &op_data->op_file_secctx_name);
993
994         if (pca && pca->pca_dataset) {
995                 OBD_ALLOC_PTR(lum);
996                 if (lum == NULL)
997                         GOTO(out, retval = ERR_PTR(-ENOMEM));
998
999                 lum->lmm_magic = LOV_USER_MAGIC_V1;
1000                 lum->lmm_pattern = LOV_PATTERN_F_RELEASED | LOV_PATTERN_RAID0;
1001                 op_data->op_data = lum;
1002                 op_data->op_data_size = sizeof(*lum);
1003                 op_data->op_archive_id = pca->pca_dataset->pccd_rwid;
1004                 it->it_flags |= MDS_OPEN_PCC;
1005         }
1006
1007         rc = md_intent_lock(ll_i2mdexp(parent), op_data, it, &req,
1008                             &ll_md_blocking_ast, 0);
1009         /* If the MDS allows the client to chgrp (CFS_SETGRP_PERM), but the
1010          * client does not know which suppgid should be sent to the MDS, or
1011          * some other(s) changed the target file's GID after this RPC sent
1012          * to the MDS with the suppgid as the original GID, then we should
1013          * try again with right suppgid. */
1014         if (rc == -EACCES && it->it_op & IT_OPEN &&
1015             it_disposition(it, DISP_OPEN_DENY)) {
1016                 struct mdt_body *body;
1017
1018                 LASSERT(req != NULL);
1019
1020                 body = req_capsule_server_get(&req->rq_pill, &RMF_MDT_BODY);
1021                 if (op_data->op_suppgids[0] == body->mbo_gid ||
1022                     op_data->op_suppgids[1] == body->mbo_gid ||
1023                     !in_group_p(make_kgid(&init_user_ns, body->mbo_gid)))
1024                         GOTO(out, retval = ERR_PTR(-EACCES));
1025
1026                 fid_zero(&op_data->op_fid2);
1027                 op_data->op_suppgids[1] = body->mbo_gid;
1028                 ptlrpc_req_finished(req);
1029                 req = NULL;
1030                 ll_intent_release(it);
1031                 rc = md_intent_lock(ll_i2mdexp(parent), op_data, it, &req,
1032                                     &ll_md_blocking_ast, 0);
1033         }
1034
1035         if (rc < 0)
1036                 GOTO(out, retval = ERR_PTR(rc));
1037
1038         if (pca && pca->pca_dataset) {
1039                 rc = pcc_inode_create(parent->i_sb, pca->pca_dataset,
1040                                       &op_data->op_fid2,
1041                                       &pca->pca_dentry);
1042                 if (rc)
1043                         GOTO(out, retval = ERR_PTR(rc));
1044         }
1045
1046         /* dir layout may change */
1047         ll_unlock_md_op_lsm(op_data);
1048         rc = ll_lookup_it_finish(req, it, parent, &dentry,
1049                                  secctx != NULL ? *secctx : NULL,
1050                                  secctxlen != NULL ? *secctxlen : 0,
1051                                  encctx != NULL ? *encctx : NULL,
1052                                  encctxlen != NULL ? *encctxlen : 0,
1053                                  kstart, encrypt);
1054         if (rc != 0) {
1055                 ll_intent_release(it);
1056                 GOTO(out, retval = ERR_PTR(rc));
1057         }
1058
1059         if ((it->it_op & IT_OPEN) && dentry->d_inode &&
1060             !S_ISREG(dentry->d_inode->i_mode) &&
1061             !S_ISDIR(dentry->d_inode->i_mode)) {
1062                 ll_release_openhandle(dentry, it);
1063         }
1064         ll_lookup_finish_locks(it, dentry);
1065
1066         GOTO(out, retval = (dentry == save) ? NULL : dentry);
1067
1068 out:
1069         if (op_data != NULL && !IS_ERR(op_data)) {
1070                 if (secctx != NULL && secctxlen != NULL) {
1071                         /* caller needs sec ctx info, so reset it in op_data to
1072                          * prevent it from being freed */
1073                         op_data->op_file_secctx = NULL;
1074                         op_data->op_file_secctx_size = 0;
1075                 }
1076                 if (encctx != NULL && encctxlen != NULL &&
1077                     it->it_op & IT_CREAT && encrypt) {
1078                         /* caller needs enc ctx info, so reset it in op_data to
1079                          * prevent it from being freed
1080                          */
1081                         op_data->op_file_encctx = NULL;
1082                         op_data->op_file_encctx_size = 0;
1083                 }
1084                 llcrypt_free_filename(&fname);
1085                 ll_finish_md_op_data(op_data);
1086         }
1087
1088         if (lum != NULL)
1089                 OBD_FREE_PTR(lum);
1090
1091         ptlrpc_req_finished(req);
1092         return retval;
1093 }
1094
1095 static struct dentry *ll_lookup_nd(struct inode *parent, struct dentry *dentry,
1096                                    unsigned int flags)
1097 {
1098         struct lookup_intent *itp, it = { .it_op = IT_GETATTR };
1099         struct dentry *de = NULL;
1100
1101         /* VFS has locked the inode before calling this */
1102         ll_set_inode_lock_owner(parent);
1103
1104         CDEBUG(D_VFSTRACE, "VFS Op:name=%pd, dir="DFID"(%p), flags=%u\n",
1105                dentry, PFID(ll_inode2fid(parent)), parent, flags);
1106
1107         /*
1108          * Optimize away (CREATE && !OPEN). Let .create handle the race.
1109          * but only if we have write permissions there, otherwise we need
1110          * to proceed with lookup. LU-4185
1111          */
1112         if ((flags & LOOKUP_CREATE) && !(flags & LOOKUP_OPEN) &&
1113             (inode_permission(&nop_mnt_idmap,
1114                               parent, MAY_WRITE | MAY_EXEC) == 0))
1115                 goto clear;
1116
1117         if (flags & (LOOKUP_PARENT|LOOKUP_OPEN|LOOKUP_CREATE))
1118                 itp = NULL;
1119         else
1120                 itp = &it;
1121         de = ll_lookup_it(parent, dentry, itp, NULL, NULL, NULL, NULL, false,
1122                           NULL, NULL);
1123
1124         if (itp != NULL)
1125                 ll_intent_release(itp);
1126
1127 clear:
1128         ll_clear_inode_lock_owner(parent);
1129
1130         return de;
1131 }
1132
1133 #ifdef FMODE_CREATED /* added in Linux v4.18-rc1-20-g73a09dd */
1134 # define ll_is_opened(o, f)             ((f)->f_mode & FMODE_OPENED)
1135 # define ll_finish_open(f, d, o)        finish_open((f), (d), NULL)
1136 # define ll_last_arg
1137 # define ll_set_created(o, f)                                           \
1138 do {                                                                    \
1139         (f)->f_mode |= FMODE_CREATED;                                   \
1140 } while (0)
1141
1142 #else
1143 # define ll_is_opened(o, f)             (*(o))
1144 # define ll_finish_open(f, d, o)        finish_open((f), (d), NULL, (o))
1145 # define ll_last_arg                    , int *opened
1146 # define ll_set_created(o, f)                                           \
1147 do {                                                                    \
1148         *(o) |= FILE_CREATED;                                           \
1149 } while (0)
1150
1151 #endif
1152
1153 /*
1154  * For cached negative dentry and new dentry, handle lookup/create/open
1155  * together.
1156  */
1157 static int ll_atomic_open(struct inode *dir, struct dentry *dentry,
1158                           struct file *file, unsigned open_flags,
1159                           umode_t mode ll_last_arg)
1160 {
1161         struct lookup_intent *it;
1162         struct dentry *de;
1163         long long lookup_flags = LOOKUP_OPEN;
1164         void *secctx = NULL;
1165         __u32 secctxlen = 0;
1166         int secctxslot = 0;
1167         void *encctx = NULL;
1168         __u32 encctxlen = 0;
1169         struct ll_sb_info *sbi = NULL;
1170         struct pcc_create_attach pca = { NULL, NULL };
1171         bool encrypt = false;
1172         int open_threshold;
1173         int rc = 0;
1174
1175         ENTRY;
1176         /* VFS has locked the inode before calling this */
1177         ll_set_inode_lock_owner(dir);
1178
1179         CDEBUG(D_VFSTRACE,
1180                "VFS Op:name=%pd, dir="DFID"(%p), file %p, open_flags %x, mode %x opened %d\n",
1181                dentry, PFID(ll_inode2fid(dir)), dir, file, open_flags, mode,
1182                ll_is_opened(opened, file));
1183
1184         /* Only negative dentries enter here */
1185         LASSERT(dentry->d_inode == NULL);
1186
1187         if (!d_unhashed(dentry)) {
1188                 /* A valid negative dentry that just passed revalidation,
1189                  * there's little point to try and open it server-side,
1190                  * even though there's a minuscule chance it might succeed.
1191                  * Either way it's a valid race to just return -ENOENT here.
1192                  */
1193                 if (!(open_flags & O_CREAT))
1194                         GOTO(clear, rc = -ENOENT);
1195
1196                 /* Otherwise we just unhash it to be rehashed afresh via
1197                  * lookup if necessary
1198                  */
1199                 d_drop(dentry);
1200         }
1201
1202         OBD_ALLOC(it, sizeof(*it));
1203         if (!it)
1204                 GOTO(clear, rc = -ENOMEM);
1205
1206         it->it_op = IT_OPEN;
1207         if (open_flags & O_CREAT) {
1208                 it->it_op |= IT_CREAT;
1209                 lookup_flags |= LOOKUP_CREATE;
1210                 sbi = ll_i2sbi(dir);
1211                 /* Volatile file is used for HSM restore, so do not use PCC */
1212                 if (!filename_is_volatile(dentry->d_name.name,
1213                                           dentry->d_name.len, NULL)) {
1214                         struct pcc_matcher item;
1215                         struct pcc_dataset *dataset;
1216
1217                         item.pm_uid = from_kuid(&init_user_ns, current_uid());
1218                         item.pm_gid = from_kgid(&init_user_ns, current_gid());
1219                         item.pm_projid = ll_i2info(dir)->lli_projid;
1220                         item.pm_name = &dentry->d_name;
1221                         dataset = pcc_dataset_match_get(&sbi->ll_pcc_super,
1222                                                         &item);
1223                         pca.pca_dataset = dataset;
1224                 }
1225         }
1226         it->it_create_mode = (mode & S_IALLUGO) | S_IFREG;
1227         it->it_flags = (open_flags & ~O_ACCMODE) | OPEN_FMODE(open_flags);
1228         it->it_flags &= ~MDS_OPEN_FL_INTERNAL;
1229
1230         if (ll_sbi_has_encrypt(ll_i2sbi(dir)) && IS_ENCRYPTED(dir)) {
1231                 /* in case of create, this is going to be a regular file because
1232                  * we set S_IFREG bit on it->it_create_mode above
1233                  */
1234                 rc = llcrypt_prepare_readdir(dir);
1235                 if (rc)
1236                         GOTO(out_release, rc);
1237                 encrypt = true;
1238                 if (open_flags & O_CREAT) {
1239                         /* For migration or mirroring without enc key, we still
1240                          * need to be able to create a volatile file.
1241                          */
1242                         if (!llcrypt_has_encryption_key(dir) &&
1243                             (!filename_is_volatile(dentry->d_name.name,
1244                                                    dentry->d_name.len, NULL) ||
1245                             (open_flags & O_FILE_ENC) != O_FILE_ENC ||
1246                             !(open_flags & O_DIRECT)))
1247                                 GOTO(out_release, rc = -ENOKEY);
1248                 }
1249         }
1250
1251         CFS_FAIL_TIMEOUT(OBD_FAIL_LLITE_CREATE_FILE_PAUSE2, cfs_fail_val);
1252
1253         /* We can only arrive at this path when we have no inode, so
1254          * we only need to request open lock if it was requested
1255          * for every open
1256          */
1257         if (ll_i2info(dir)->lli_open_thrsh_count != UINT_MAX)
1258                 open_threshold = ll_i2info(dir)->lli_open_thrsh_count;
1259         else
1260                 open_threshold = ll_i2sbi(dir)->ll_oc_thrsh_count;
1261
1262         if (open_threshold == 1 &&
1263             exp_connect_flags2(ll_i2mdexp(dir)) &
1264             OBD_CONNECT2_ATOMIC_OPEN_LOCK)
1265                 it->it_flags |= MDS_OPEN_LOCK;
1266
1267         /* Dentry added to dcache tree in ll_lookup_it */
1268         de = ll_lookup_it(dir, dentry, it, &secctx, &secctxlen, &secctxslot,
1269                           &pca, encrypt, &encctx, &encctxlen);
1270         if (IS_ERR(de))
1271                 rc = PTR_ERR(de);
1272         else if (de != NULL)
1273                 dentry = de;
1274
1275         CFS_FAIL_TIMEOUT(OBD_FAIL_LLITE_CREATE_FILE_PAUSE, cfs_fail_val);
1276
1277         if (!rc) {
1278                 if (it_disposition(it, DISP_OPEN_CREATE)) {
1279                         /* Dentry instantiated in ll_create_it. */
1280                         rc = ll_create_it(dir, dentry, it, secctx, secctxlen,
1281                                           encrypt, encctx, encctxlen,
1282                                           open_flags);
1283                         ll_security_release_secctx(secctx, secctxlen,
1284                                                    secctxslot);
1285                         llcrypt_free_ctx(encctx, encctxlen);
1286                         if (rc) {
1287                                 /* We dget in ll_splice_alias. */
1288                                 if (de != NULL)
1289                                         dput(de);
1290                                 goto out_release;
1291                         }
1292
1293                         rc = pcc_inode_create_fini(dentry->d_inode, &pca);
1294                         if (rc) {
1295                                 if (de != NULL)
1296                                         dput(de);
1297                                 GOTO(out_release, rc);
1298                         }
1299
1300                         ll_set_created(opened, file);
1301                 } else {
1302                         /* Open the file with O_CREAT, but the file already
1303                          * existed on MDT. This may happend in the case that
1304                          * the LOOKUP ibits lock is revoked and the
1305                          * corresponding dentry cache is deleted.
1306                          * i.e. In the current Lustre, the truncate operation
1307                          * will revoke the LOOKUP ibits lock, and the file
1308                          * dentry cache will be invalidated. The following open
1309                          * with O_CREAT flag will call into ->atomic_open, the
1310                          * file was wrongly though as newly created file and
1311                          * try to auto cache the file. So after client knows it
1312                          * is not a DISP_OPEN_CREATE, it should cleanup the
1313                          * already created PCC copy.
1314                          */
1315                         pcc_create_attach_cleanup(dir->i_sb, &pca);
1316
1317                         if (open_flags & O_CREAT && encrypt &&
1318                             dentry->d_inode) {
1319                                 rc = ll_set_encflags(dentry->d_inode, encctx,
1320                                                      encctxlen, true);
1321                                 llcrypt_free_ctx(encctx, encctxlen);
1322                                 if (rc)
1323                                         GOTO(out_release, rc);
1324                         }
1325                 }
1326
1327                 /* check also if a foreign file is openable */
1328                 if (dentry->d_inode && it_disposition(it, DISP_OPEN_OPEN) &&
1329                     ll_foreign_is_openable(dentry, open_flags)) {
1330                         /* Open dentry. */
1331                         if (S_ISFIFO(dentry->d_inode->i_mode)) {
1332                                 /* We cannot call open here as it might
1333                                  * deadlock. This case is unreachable in
1334                                  * practice because of OBD_CONNECT_NODEVOH. */
1335                                 rc = finish_no_open(file, de);
1336                         } else {
1337                                 file->private_data = it;
1338                                 rc = ll_finish_open(file, dentry, opened);
1339                                 /* We dget in ll_splice_alias. finish_open takes
1340                                  * care of dget for fd open.
1341                                  */
1342                                 if (de != NULL)
1343                                         dput(de);
1344                         }
1345                 } else {
1346                         rc = finish_no_open(file, de);
1347                 }
1348         } else {
1349                 pcc_create_attach_cleanup(dir->i_sb, &pca);
1350         }
1351
1352 out_release:
1353         ll_intent_release(it);
1354         OBD_FREE(it, sizeof(*it));
1355 clear:
1356         ll_clear_inode_lock_owner(dir);
1357
1358         RETURN(rc);
1359 }
1360
1361 /* We depend on "mode" being set with the proper file type/umask by now */
1362 static struct inode *ll_create_node(struct inode *dir, struct lookup_intent *it)
1363 {
1364         struct inode *inode = NULL;
1365         struct ptlrpc_request *request = NULL;
1366         struct ll_sb_info *sbi = ll_i2sbi(dir);
1367         int rc;
1368         ENTRY;
1369
1370         LASSERT(it && it->it_disposition);
1371
1372         LASSERT(it_disposition(it, DISP_ENQ_CREATE_REF));
1373         request = it->it_request;
1374         it_clear_disposition(it, DISP_ENQ_CREATE_REF);
1375         rc = ll_prep_inode(&inode, &request->rq_pill, dir->i_sb, it);
1376         if (rc)
1377                 GOTO(out, inode = ERR_PTR(rc));
1378
1379         /* Pause to allow for a race with concurrent access by fid */
1380         CFS_FAIL_TIMEOUT(OBD_FAIL_LLITE_CREATE_NODE_PAUSE, cfs_fail_val);
1381
1382         /* We asked for a lock on the directory, but were granted a
1383          * lock on the inode.  Since we finally have an inode pointer,
1384          * stuff it in the lock. */
1385         CDEBUG(D_DLMTRACE, "setting l_ast_data to inode "DFID"(%p)\n",
1386                PFID(ll_inode2fid(inode)), inode);
1387         ll_set_lock_data(sbi->ll_md_exp, inode, it, NULL);
1388         EXIT;
1389  out:
1390         ptlrpc_req_finished(request);
1391         return inode;
1392 }
1393
1394 /*
1395  * By the time this is called, we already have created the directory cache
1396  * entry for the new file, but it is so far negative - it has no inode.
1397  *
1398  * We defer creating the OBD object(s) until open, to keep the intent and
1399  * non-intent code paths similar, and also because we do not have the MDS
1400  * inode number before calling ll_create_node() (which is needed for LOV),
1401  * so we would need to do yet another RPC to the MDS to store the LOV EA
1402  * data on the MDS.  If needed, we would pass the PACKED lmm as data and
1403  * lmm_size in datalen (the MDS still has code which will handle that).
1404  *
1405  * If the create succeeds, we fill in the inode information
1406  * with d_instantiate().
1407  */
1408 static int ll_create_it(struct inode *dir, struct dentry *dentry,
1409                         struct lookup_intent *it,
1410                         void *secctx, __u32 secctxlen, bool encrypt,
1411                         void *encctx, __u32 encctxlen, unsigned int open_flags)
1412 {
1413         struct inode *inode;
1414         __u64 bits = 0;
1415         int rc = 0;
1416         ENTRY;
1417
1418         CDEBUG(D_VFSTRACE, "VFS Op:name=%pd, dir="DFID"(%p), intent=%s\n",
1419                dentry, PFID(ll_inode2fid(dir)), dir, LL_IT2STR(it));
1420
1421         rc = it_open_error(DISP_OPEN_CREATE, it);
1422         if (rc)
1423                 RETURN(rc);
1424
1425         inode = ll_create_node(dir, it);
1426         if (IS_ERR(inode))
1427                 RETURN(PTR_ERR(inode));
1428
1429         /* must be done before d_instantiate, because it calls
1430          * security_d_instantiate, which means a getxattr if security
1431          * context is not set yet
1432          */
1433         rc = ll_inode_notifysecctx(inode, secctx, secctxlen);
1434         if (rc)
1435                 RETURN(rc);
1436
1437         d_instantiate(dentry, inode);
1438
1439         if (encrypt) {
1440                 bool preload = true;
1441
1442                 /* For migration or mirroring without enc key, we
1443                  * create a volatile file without enc context.
1444                  */
1445                 if (!llcrypt_has_encryption_key(dir) &&
1446                     filename_is_volatile(dentry->d_name.name,
1447                                          dentry->d_name.len, NULL) &&
1448                     (open_flags & O_FILE_ENC) == O_FILE_ENC &&
1449                     open_flags & O_DIRECT)
1450                         preload = false;
1451                 rc = ll_set_encflags(inode, encctx, encctxlen, preload);
1452                 if (rc)
1453                         RETURN(rc);
1454         }
1455
1456         if (!test_bit(LL_SBI_FILE_SECCTX, ll_i2sbi(inode)->ll_flags)) {
1457                 rc = ll_inode_init_security(dentry, inode, dir);
1458                 if (rc)
1459                         RETURN(rc);
1460         }
1461
1462         ll_set_lock_data(ll_i2sbi(dir)->ll_md_exp, inode, it, &bits);
1463         if (bits & MDS_INODELOCK_LOOKUP) {
1464                 d_lustre_revalidate(dentry);
1465                 if (S_ISDIR(inode->i_mode))
1466                         ll_update_dir_depth_dmv(dir, dentry);
1467         }
1468
1469         RETURN(0);
1470 }
1471
1472 void ll_update_times(struct ptlrpc_request *request, struct inode *inode)
1473 {
1474         struct mdt_body *body = req_capsule_server_get(&request->rq_pill,
1475                                                        &RMF_MDT_BODY);
1476
1477         LASSERT(body);
1478         if (body->mbo_valid & OBD_MD_FLMTIME &&
1479             body->mbo_mtime > inode->i_mtime.tv_sec) {
1480                 CDEBUG(D_INODE,
1481                        "setting fid " DFID " mtime from %lld to %llu\n",
1482                        PFID(ll_inode2fid(inode)),
1483                        (s64)inode->i_mtime.tv_sec, body->mbo_mtime);
1484                 inode->i_mtime.tv_sec = body->mbo_mtime;
1485         }
1486
1487         if (body->mbo_valid & OBD_MD_FLCTIME &&
1488             body->mbo_ctime > inode->i_ctime.tv_sec)
1489                 inode->i_ctime.tv_sec = body->mbo_ctime;
1490 }
1491
1492 /* once default LMV (space balanced) is set on ROOT, it should take effect if
1493  * default LMV is not set on parent directory.
1494  */
1495 static void ll_qos_mkdir_prep(struct md_op_data *op_data, struct inode *dir)
1496 {
1497         struct inode *root = dir->i_sb->s_root->d_inode;
1498         struct ll_inode_info *rlli = ll_i2info(root);
1499         struct ll_inode_info *lli = ll_i2info(dir);
1500         struct lmv_stripe_md *lsm;
1501         unsigned short depth;
1502
1503         op_data->op_dir_depth = lli->lli_inherit_depth ?: lli->lli_dir_depth;
1504         depth = lli->lli_dir_depth;
1505
1506         /* parent directory is striped */
1507         if (unlikely(ll_dir_striped(dir)))
1508                 return;
1509
1510         /* default LMV set on parent directory */
1511         if (unlikely(lli->lli_def_lsm_obj))
1512                 return;
1513
1514         /* parent is ROOT */
1515         if (unlikely(dir == root))
1516                 return;
1517
1518         /* default LMV not set on ROOT */
1519         if (!rlli->lli_def_lsm_obj)
1520                 return;
1521
1522         down_read(&rlli->lli_lsm_sem);
1523         if (!rlli->lli_def_lsm_obj)
1524                 goto unlock;
1525         lsm = &rlli->lli_def_lsm_obj->lso_lsm;
1526
1527         /* not space balanced */
1528         if (lsm->lsm_md_master_mdt_index != LMV_OFFSET_DEFAULT)
1529                 goto unlock;
1530
1531         /**
1532          * Check if the fs default is to be applied.
1533          * depth == 0 means 'not inited' for not root dir.
1534          */
1535         if (lsm->lsm_md_max_inherit != LMV_INHERIT_NONE &&
1536             (lsm->lsm_md_max_inherit == LMV_INHERIT_UNLIMITED ||
1537              (depth && lsm->lsm_md_max_inherit > depth))) {
1538                 op_data->op_flags |= MF_QOS_MKDIR;
1539                 if (lsm->lsm_md_max_inherit_rr != LMV_INHERIT_RR_NONE &&
1540                     (lsm->lsm_md_max_inherit_rr == LMV_INHERIT_RR_UNLIMITED ||
1541                      (depth && lsm->lsm_md_max_inherit_rr > depth)))
1542                         op_data->op_flags |= MF_RR_MKDIR;
1543                 CDEBUG(D_INODE, DFID" requests qos mkdir %#x\n",
1544                        PFID(&lli->lli_fid), op_data->op_flags);
1545         }
1546 unlock:
1547         up_read(&rlli->lli_lsm_sem);
1548 }
1549
1550 static int ll_new_node(struct inode *dir, struct dentry *dchild,
1551                        const char *tgt, umode_t mode, __u64 rdev, __u32 opc)
1552 {
1553         struct qstr *name = &dchild->d_name;
1554         struct ptlrpc_request *request = NULL;
1555         struct md_op_data *op_data = NULL;
1556         struct inode *inode = NULL;
1557         struct ll_sb_info *sbi = ll_i2sbi(dir);
1558         struct llcrypt_str *disk_link = NULL;
1559         bool encrypt = false;
1560         struct lmv_user_md *lum = NULL;
1561         const void *data = NULL;
1562         size_t datalen = 0;
1563         int err;
1564
1565         ENTRY;
1566         if (unlikely(tgt != NULL)) {
1567                 disk_link = (struct llcrypt_str *)rdev;
1568                 rdev = 0;
1569                 if (!disk_link)
1570                         RETURN(-EINVAL);
1571                 data = disk_link->name;
1572                 datalen = disk_link->len;
1573         }
1574
1575 again:
1576         op_data = ll_prep_md_op_data(NULL, dir, NULL, name->name,
1577                                      name->len, 0, opc, NULL);
1578         if (IS_ERR(op_data))
1579                 GOTO(err_exit, err = PTR_ERR(op_data));
1580
1581         if (S_ISDIR(mode)) {
1582                 ll_qos_mkdir_prep(op_data, dir);
1583                 if ((exp_connect_flags2(ll_i2mdexp(dir)) &
1584                      OBD_CONNECT2_DMV_IMP_INHERIT) &&
1585                     op_data->op_default_lso1 && !lum) {
1586                         const struct lmv_stripe_md *lsm;
1587
1588                         /* once DMV_IMP_INHERIT is set, pack default LMV in
1589                          * create request.
1590                          */
1591                         OBD_ALLOC_PTR(lum);
1592                         if (!lum)
1593                                 GOTO(err_exit, err = -ENOMEM);
1594
1595                         lsm = &op_data->op_default_lso1->lso_lsm;
1596                         lum->lum_magic = cpu_to_le32(lsm->lsm_md_magic);
1597                         lum->lum_stripe_count =
1598                                 cpu_to_le32(lsm->lsm_md_stripe_count);
1599                         lum->lum_stripe_offset =
1600                                 cpu_to_le32(lsm->lsm_md_master_mdt_index);
1601                         lum->lum_hash_type =
1602                                 cpu_to_le32(lsm->lsm_md_hash_type);
1603                         lum->lum_max_inherit = lsm->lsm_md_max_inherit;
1604                         lum->lum_max_inherit_rr = lsm->lsm_md_max_inherit_rr;
1605                         lum->lum_pool_name[0] = 0;
1606                         op_data->op_bias |= MDS_CREATE_DEFAULT_LMV;
1607                         data = lum;
1608                         datalen = sizeof(*lum);
1609                 }
1610         }
1611
1612         if (test_bit(LL_SBI_FILE_SECCTX, sbi->ll_flags)) {
1613                 err = ll_dentry_init_security(dchild, mode, &dchild->d_name,
1614                                               &op_data->op_file_secctx_name,
1615                                               &op_data->op_file_secctx_name_size,
1616                                               &op_data->op_file_secctx,
1617                                               &op_data->op_file_secctx_size,
1618                                               &op_data->op_file_secctx_slot);
1619                 if (err < 0)
1620                         GOTO(err_exit, err);
1621         }
1622
1623         if (ll_sbi_has_encrypt(sbi) &&
1624             ((IS_ENCRYPTED(dir) &&
1625             (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) ||
1626              (unlikely(ll_sb_has_test_dummy_encryption(dir->i_sb)) &&
1627               S_ISDIR(mode)))) {
1628                 err = llcrypt_prepare_readdir(dir);
1629                 if (err)
1630                         GOTO(err_exit, err);
1631                 if (!llcrypt_has_encryption_key(dir))
1632                         GOTO(err_exit, err = -ENOKEY);
1633                 encrypt = true;
1634         }
1635
1636         if (encrypt) {
1637                 err = llcrypt_inherit_context(dir, NULL, op_data, false);
1638                 if (err)
1639                         GOTO(err_exit, err);
1640
1641                 if (S_ISLNK(mode)) {
1642                         /* llcrypt needs inode to encrypt target name, so create
1643                          * a fake inode and associate encryption context got
1644                          * from llcrypt_inherit_context.
1645                          */
1646                         struct inode *fakeinode =
1647                                 dchild->d_sb->s_op->alloc_inode(dchild->d_sb);
1648
1649                         if (!fakeinode)
1650                                 GOTO(err_exit, err = -ENOMEM);
1651                         fakeinode->i_sb = dchild->d_sb;
1652                         fakeinode->i_mode |= S_IFLNK;
1653 #ifdef IOP_XATTR
1654                         fakeinode->i_opflags |= IOP_XATTR;
1655 #endif
1656                         ll_lli_init(ll_i2info(fakeinode));
1657                         err = ll_set_encflags(fakeinode,
1658                                               op_data->op_file_encctx,
1659                                               op_data->op_file_encctx_size,
1660                                               true);
1661                         if (!err)
1662                                 err = __llcrypt_encrypt_symlink(fakeinode, tgt,
1663                                                                 strlen(tgt),
1664                                                                 disk_link);
1665
1666                         ll_xattr_cache_destroy(fakeinode);
1667                         llcrypt_put_encryption_info(fakeinode);
1668                         dchild->d_sb->s_op->destroy_inode(fakeinode);
1669                         if (err)
1670                                 GOTO(err_exit, err);
1671
1672                         data = disk_link->name;
1673                         datalen = disk_link->len;
1674                 }
1675         }
1676
1677         err = md_create(sbi->ll_md_exp, op_data, data, datalen, mode,
1678                         from_kuid(&init_user_ns, current_fsuid()),
1679                         from_kgid(&init_user_ns, current_fsgid()),
1680                         current_cap(), rdev, &request);
1681 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 17, 58, 0)
1682         /*
1683          * server < 2.12.58 doesn't pack default LMV in intent_getattr reply,
1684          * fetch default LMV here.
1685          */
1686         if (unlikely(err == -EREMOTE)) {
1687                 struct ll_inode_info    *lli = ll_i2info(dir);
1688                 struct lmv_user_md      *lum;
1689                 int                     lumsize;
1690                 int                     err2;
1691
1692                 ptlrpc_req_finished(request);
1693                 request = NULL;
1694                 ll_finish_md_op_data(op_data);
1695                 op_data = NULL;
1696
1697                 err2 = ll_dir_getstripe(dir, (void **)&lum, &lumsize, &request,
1698                                         OBD_MD_DEFAULT_MEA);
1699                 if (err2 == 0) {
1700                         struct lustre_md md = { NULL };
1701
1702
1703                         md.body = req_capsule_server_get(&request->rq_pill,
1704                                                          &RMF_MDT_BODY);
1705                         if (!md.body)
1706                                 GOTO(err_exit, err = -EPROTO);
1707
1708                         OBD_ALLOC_PTR(md.def_lsm_obj);
1709                         if (!md.def_lsm_obj)
1710                                 GOTO(err_exit, err = -ENOMEM);
1711
1712                         md.def_lsm_obj->lso_lsm.lsm_md_magic = lum->lum_magic;
1713                         md.def_lsm_obj->lso_lsm.lsm_md_stripe_count =
1714                                 lum->lum_stripe_count;
1715                         md.def_lsm_obj->lso_lsm.lsm_md_master_mdt_index =
1716                                 lum->lum_stripe_offset;
1717                         md.def_lsm_obj->lso_lsm.lsm_md_hash_type =
1718                                 lum->lum_hash_type;
1719                         md.def_lsm_obj->lso_lsm.lsm_md_max_inherit =
1720                                 lum->lum_max_inherit;
1721                         md.def_lsm_obj->lso_lsm.lsm_md_max_inherit_rr =
1722                                 lum->lum_max_inherit_rr;
1723                         atomic_set(&md.def_lsm_obj->lso_refs, 1);
1724
1725                         err = ll_update_inode(dir, &md);
1726                         md_put_lustre_md(sbi->ll_md_exp, &md);
1727                         if (err)
1728                                 GOTO(err_exit, err);
1729                 } else if (err2 == -ENODATA && lli->lli_def_lsm_obj) {
1730                         /*
1731                          * If there are no default stripe EA on the MDT, but the
1732                          * client has default stripe, then it probably means
1733                          * default stripe EA has just been deleted.
1734                          */
1735                         down_write(&lli->lli_lsm_sem);
1736                         lmv_stripe_object_put(&lli->lli_def_lsm_obj);
1737                         up_write(&lli->lli_lsm_sem);
1738                 } else {
1739                         GOTO(err_exit, err);
1740                 }
1741
1742                 ptlrpc_req_finished(request);
1743                 request = NULL;
1744                 goto again;
1745         }
1746 #endif
1747
1748         if (err < 0)
1749                 GOTO(err_exit, err);
1750
1751         ll_update_times(request, dir);
1752
1753         CFS_FAIL_TIMEOUT(OBD_FAIL_LLITE_NEWNODE_PAUSE, cfs_fail_val);
1754
1755         err = ll_prep_inode(&inode, &request->rq_pill, dchild->d_sb, NULL);
1756         if (err)
1757                 GOTO(err_exit, err);
1758
1759         /* must be done before d_instantiate, because it calls
1760          * security_d_instantiate, which means a getxattr if security
1761          * context is not set yet
1762          */
1763         err = ll_inode_notifysecctx(inode,
1764                                     op_data->op_file_secctx,
1765                                     op_data->op_file_secctx_size);
1766         if (err)
1767                 GOTO(err_exit, err);
1768
1769         d_instantiate(dchild, inode);
1770
1771         if (encrypt) {
1772                 err = ll_set_encflags(inode, op_data->op_file_encctx,
1773                                       op_data->op_file_encctx_size, true);
1774                 if (err)
1775                         GOTO(err_exit, err);
1776
1777                 if (S_ISLNK(mode)) {
1778                         struct ll_inode_info *lli = ll_i2info(inode);
1779
1780                         /* Cache the plaintext symlink target
1781                          * for later use by get_link()
1782                          */
1783                         OBD_ALLOC(lli->lli_symlink_name, strlen(tgt) + 1);
1784                         /* do not return an error if we cannot
1785                          * cache the symlink locally
1786                          */
1787                         if (lli->lli_symlink_name)
1788                                 memcpy(lli->lli_symlink_name,
1789                                        tgt, strlen(tgt) + 1);
1790                 }
1791         }
1792
1793         if (!test_bit(LL_SBI_FILE_SECCTX, sbi->ll_flags)) {
1794                 err = ll_inode_init_security(dchild, inode, dir);
1795                 if (err)
1796                         GOTO(err_exit, err);
1797         }
1798
1799         EXIT;
1800 err_exit:
1801         if (request != NULL)
1802                 ptlrpc_req_finished(request);
1803         if (!IS_ERR_OR_NULL(op_data))
1804                 ll_finish_md_op_data(op_data);
1805         if (lum)
1806                 OBD_FREE_PTR(lum);
1807
1808         RETURN(err);
1809 }
1810
1811 static int ll_mknod(struct mnt_idmap *map, struct inode *dir,
1812                     struct dentry *dchild, umode_t mode, dev_t rdev)
1813 {
1814         ktime_t kstart = ktime_get();
1815         int err;
1816         ENTRY;
1817
1818         /* VFS has locked the inode before calling this */
1819         ll_set_inode_lock_owner(dir);
1820
1821         CDEBUG(D_VFSTRACE, "VFS Op:name=%pd, dir="DFID"(%p) mode %o dev %x\n",
1822                dchild, PFID(ll_inode2fid(dir)), dir, mode, rdev);
1823
1824         if (!IS_POSIXACL(dir) || !exp_connect_umask(ll_i2mdexp(dir)))
1825                 mode &= ~current_umask();
1826
1827         switch (mode & S_IFMT) {
1828         case 0:
1829                 mode |= S_IFREG;
1830                 fallthrough;
1831         case S_IFREG:
1832         case S_IFCHR:
1833         case S_IFBLK:
1834         case S_IFIFO:
1835         case S_IFSOCK:
1836                 err = ll_new_node(dir, dchild, NULL, mode, old_encode_dev(rdev),
1837                                   LUSTRE_OPC_MKNOD);
1838                 break;
1839         case S_IFDIR:
1840                 err = -EPERM;
1841                 break;
1842         default:
1843                 err = -EINVAL;
1844         }
1845
1846         if (!err)
1847                 ll_stats_ops_tally(ll_i2sbi(dir), LPROC_LL_MKNOD,
1848                                    ktime_us_delta(ktime_get(), kstart));
1849         ll_clear_inode_lock_owner(dir);
1850
1851         RETURN(err);
1852 }
1853
1854 /*
1855  * Plain create. Intent create is handled in atomic_open.
1856  */
1857 static int ll_create_nd(struct mnt_idmap *map, struct inode *dir,
1858                         struct dentry *dentry, umode_t mode, bool want_excl)
1859 {
1860         ktime_t kstart = ktime_get();
1861         int rc;
1862
1863         /* VFS has locked the inode before calling this */
1864         ll_set_inode_lock_owner(dir);
1865
1866         CFS_FAIL_TIMEOUT(OBD_FAIL_LLITE_CREATE_FILE_PAUSE, cfs_fail_val);
1867
1868         CDEBUG(D_VFSTRACE,
1869                "VFS Op:name=%pd, dir="DFID"(%p), flags=%u, excl=%d\n",
1870                dentry, PFID(ll_inode2fid(dir)), dir, mode, want_excl);
1871
1872         /* Using mknod(2) to create a regular file is designed to not recognize
1873          * volatile file name, so we use ll_mknod() here. */
1874         rc = ll_mknod(map, dir, dentry, mode, 0);
1875
1876         CDEBUG(D_VFSTRACE, "VFS Op:name=%pd, unhashed %d\n",
1877                dentry, d_unhashed(dentry));
1878
1879         if (!rc)
1880                 ll_stats_ops_tally(ll_i2sbi(dir), LPROC_LL_CREATE,
1881                                    ktime_us_delta(ktime_get(), kstart));
1882
1883         ll_clear_inode_lock_owner(dir);
1884
1885         return rc;
1886 }
1887
1888 static int ll_symlink(struct mnt_idmap *map, struct inode *dir,
1889                       struct dentry *dchild, const char *oldpath)
1890 {
1891         ktime_t kstart = ktime_get();
1892         int len = strlen(oldpath);
1893         struct llcrypt_str disk_link;
1894         int err;
1895         ENTRY;
1896
1897         /* VFS has locked the inode before calling this */
1898         ll_set_inode_lock_owner(dir);
1899
1900         CDEBUG(D_VFSTRACE, "VFS Op:name=%pd, dir="DFID"(%p), target=%.*s\n",
1901                dchild, PFID(ll_inode2fid(dir)), dir, 3000, oldpath);
1902
1903         err = llcrypt_prepare_symlink(dir, oldpath, len, dir->i_sb->s_blocksize,
1904                                       &disk_link);
1905         if (err)
1906                 GOTO(out, err);
1907
1908         err = ll_new_node(dir, dchild, oldpath, S_IFLNK | S_IRWXUGO,
1909                           (__u64)&disk_link, LUSTRE_OPC_SYMLINK);
1910
1911         if (disk_link.name != (unsigned char *)oldpath)
1912                 kfree(disk_link.name);
1913
1914         if (!err)
1915                 ll_stats_ops_tally(ll_i2sbi(dir), LPROC_LL_SYMLINK,
1916                                    ktime_us_delta(ktime_get(), kstart));
1917
1918 out:
1919         ll_clear_inode_lock_owner(dir);
1920
1921         RETURN(err);
1922 }
1923
1924 static int ll_link(struct dentry *old_dentry, struct inode *dir,
1925                    struct dentry *new_dentry)
1926 {
1927         struct inode *src = old_dentry->d_inode;
1928         struct qstr *name = &new_dentry->d_name;
1929         struct ll_sb_info *sbi = ll_i2sbi(dir);
1930         struct ptlrpc_request *request = NULL;
1931         struct md_op_data *op_data;
1932         ktime_t kstart = ktime_get();
1933         int err;
1934
1935         ENTRY;
1936         /* VFS has locked the inodes before calling this */
1937         ll_set_inode_lock_owner(src);
1938         ll_set_inode_lock_owner(dir);
1939
1940         CDEBUG(D_VFSTRACE,
1941                "VFS Op: inode="DFID"(%p), dir="DFID"(%p), target=%pd\n",
1942                PFID(ll_inode2fid(src)), src,
1943                PFID(ll_inode2fid(dir)), dir, new_dentry);
1944
1945         err = llcrypt_prepare_link(old_dentry, dir, new_dentry);
1946         if (err)
1947                 GOTO(clear, err);
1948
1949         op_data = ll_prep_md_op_data(NULL, src, dir, name->name, name->len,
1950                                      0, LUSTRE_OPC_ANY, NULL);
1951         if (IS_ERR(op_data))
1952                 GOTO(clear, err = PTR_ERR(op_data));
1953
1954         err = md_link(sbi->ll_md_exp, op_data, &request);
1955         ll_finish_md_op_data(op_data);
1956         if (err)
1957                 GOTO(out, err);
1958
1959         ll_update_times(request, dir);
1960         ll_stats_ops_tally(sbi, LPROC_LL_LINK,
1961                            ktime_us_delta(ktime_get(), kstart));
1962         EXIT;
1963 out:
1964         ptlrpc_req_finished(request);
1965 clear:
1966         ll_clear_inode_lock_owner(src);
1967         ll_clear_inode_lock_owner(dir);
1968
1969         RETURN(err);
1970 }
1971
1972 static int ll_mkdir(struct mnt_idmap *map, struct inode *dir,
1973                     struct dentry *dchild, umode_t mode)
1974 {
1975         ktime_t kstart = ktime_get();
1976         int err;
1977         ENTRY;
1978
1979         /* VFS has locked the inode before calling this */
1980         ll_set_inode_lock_owner(dir);
1981
1982         CDEBUG(D_VFSTRACE, "VFS Op:name=%pd, dir="DFID"(%p)\n",
1983                dchild, PFID(ll_inode2fid(dir)), dir);
1984
1985         if (!IS_POSIXACL(dir) || !exp_connect_umask(ll_i2mdexp(dir)))
1986                 mode &= ~current_umask();
1987
1988         mode = (mode & (S_IRWXUGO|S_ISVTX)) | S_IFDIR;
1989
1990         err = ll_new_node(dir, dchild, NULL, mode, 0, LUSTRE_OPC_MKDIR);
1991         if (err == 0)
1992                 ll_stats_ops_tally(ll_i2sbi(dir), LPROC_LL_MKDIR,
1993                                    ktime_us_delta(ktime_get(), kstart));
1994
1995         ll_clear_inode_lock_owner(dir);
1996
1997         RETURN(err);
1998 }
1999
2000 static int ll_rmdir(struct inode *dir, struct dentry *dchild)
2001 {
2002         struct qstr *name = &dchild->d_name;
2003         struct ptlrpc_request *request = NULL;
2004         struct md_op_data *op_data;
2005         ktime_t kstart = ktime_get();
2006         int rc;
2007
2008         ENTRY;
2009
2010         /* VFS has locked the inodes before calling this */
2011         ll_set_inode_lock_owner(dir);
2012         ll_set_inode_lock_owner(dchild->d_inode);
2013
2014         CDEBUG(D_VFSTRACE, "VFS Op:name=%pd, dir="DFID"(%p)\n",
2015                dchild, PFID(ll_inode2fid(dir)), dir);
2016
2017         if (unlikely(d_mountpoint(dchild)))
2018                 GOTO(out, rc = -EBUSY);
2019
2020         /* some foreign dir may not be allowed to be removed */
2021         if (!ll_foreign_is_removable(dchild, false))
2022                 GOTO(out, rc = -EPERM);
2023
2024         op_data = ll_prep_md_op_data(NULL, dir, NULL, name->name, name->len,
2025                                      S_IFDIR, LUSTRE_OPC_ANY, NULL);
2026         if (IS_ERR(op_data))
2027                 GOTO(out, rc = PTR_ERR(op_data));
2028
2029         if (dchild->d_inode != NULL)
2030                 op_data->op_fid3 = *ll_inode2fid(dchild->d_inode);
2031
2032         if (fid_is_zero(&op_data->op_fid2))
2033                 op_data->op_fid2 = op_data->op_fid3;
2034         rc = md_unlink(ll_i2sbi(dir)->ll_md_exp, op_data, &request);
2035         ll_finish_md_op_data(op_data);
2036         if (!rc) {
2037                 struct mdt_body *body;
2038
2039                 ll_update_times(request, dir);
2040                 ll_stats_ops_tally(ll_i2sbi(dir), LPROC_LL_RMDIR,
2041                                    ktime_us_delta(ktime_get(), kstart));
2042
2043                 /*
2044                  * The server puts attributes in on the last unlink, use them
2045                  * to update the link count so the inode can be freed
2046                  * immediately.
2047                  */
2048                 body = req_capsule_server_get(&request->rq_pill, &RMF_MDT_BODY);
2049                 if (body->mbo_valid & OBD_MD_FLNLINK) {
2050                         spin_lock(&dchild->d_inode->i_lock);
2051                         set_nlink(dchild->d_inode, body->mbo_nlink);
2052                         spin_unlock(&dchild->d_inode->i_lock);
2053                 }
2054         }
2055
2056         ptlrpc_req_finished(request);
2057 out:
2058         ll_clear_inode_lock_owner(dir);
2059         ll_clear_inode_lock_owner(dchild->d_inode);
2060
2061         RETURN(rc);
2062 }
2063
2064 /**
2065  * Remove dir entry
2066  **/
2067 int ll_rmdir_entry(struct inode *dir, char *name, int namelen)
2068 {
2069         struct ptlrpc_request *request = NULL;
2070         struct md_op_data *op_data;
2071         ktime_t kstart = ktime_get();
2072         int rc;
2073         ENTRY;
2074
2075         CDEBUG(D_VFSTRACE, "VFS Op:name=%.*s, dir="DFID"(%p)\n",
2076                namelen, name, PFID(ll_inode2fid(dir)), dir);
2077
2078         op_data = ll_prep_md_op_data(NULL, dir, NULL, name, strlen(name),
2079                                      S_IFDIR, LUSTRE_OPC_ANY, NULL);
2080         if (IS_ERR(op_data))
2081                 RETURN(PTR_ERR(op_data));
2082         op_data->op_cli_flags |= CLI_RM_ENTRY;
2083         rc = md_unlink(ll_i2sbi(dir)->ll_md_exp, op_data, &request);
2084         ll_finish_md_op_data(op_data);
2085         if (!rc)
2086                 ll_update_times(request, dir);
2087
2088         ptlrpc_req_finished(request);
2089         if (!rc)
2090                 ll_stats_ops_tally(ll_i2sbi(dir), LPROC_LL_RMDIR,
2091                                    ktime_us_delta(ktime_get(), kstart));
2092         RETURN(rc);
2093 }
2094
2095 static int ll_unlink(struct inode *dir, struct dentry *dchild)
2096 {
2097         struct qstr *name = &dchild->d_name;
2098         struct ptlrpc_request *request = NULL;
2099         struct md_op_data *op_data;
2100         struct mdt_body *body;
2101         ktime_t kstart = ktime_get();
2102         int rc;
2103
2104         ENTRY;
2105
2106         /* VFS has locked the inodes before calling this */
2107         ll_set_inode_lock_owner(dir);
2108         ll_set_inode_lock_owner(dchild->d_inode);
2109
2110         CDEBUG(D_VFSTRACE, "VFS Op:name=%pd, dir="DFID"(%p)\n",
2111                dchild, PFID(ll_inode2fid(dir)), dir);
2112
2113         /*
2114          * XXX: unlink bind mountpoint maybe call to here,
2115          * just check it as vfs_unlink does.
2116          */
2117         if (unlikely(d_mountpoint(dchild)))
2118                 GOTO(clear, rc = -EBUSY);
2119
2120         /* some foreign file/dir may not be allowed to be unlinked */
2121         if (!ll_foreign_is_removable(dchild, false))
2122                 GOTO(clear, rc = -EPERM);
2123
2124         op_data = ll_prep_md_op_data(NULL, dir, NULL, name->name, name->len, 0,
2125                                      LUSTRE_OPC_ANY, NULL);
2126         if (IS_ERR(op_data))
2127                 GOTO(clear, rc = PTR_ERR(op_data));
2128
2129         op_data->op_fid3 = *ll_inode2fid(dchild->d_inode);
2130         /* notify lower layer if inode has dirty pages */
2131         if (S_ISREG(dchild->d_inode->i_mode) &&
2132             ll_i2info(dchild->d_inode)->lli_clob &&
2133             dirty_cnt(dchild->d_inode))
2134                 op_data->op_cli_flags |= CLI_DIRTY_DATA;
2135         if (fid_is_zero(&op_data->op_fid2))
2136                 op_data->op_fid2 = op_data->op_fid3;
2137         rc = md_unlink(ll_i2sbi(dir)->ll_md_exp, op_data, &request);
2138         ll_finish_md_op_data(op_data);
2139         if (rc)
2140                 GOTO(out, rc);
2141
2142         /*
2143          * The server puts attributes in on the last unlink, use them to update
2144          * the link count so the inode can be freed immediately.
2145          */
2146         body = req_capsule_server_get(&request->rq_pill, &RMF_MDT_BODY);
2147         if (body->mbo_valid & OBD_MD_FLNLINK) {
2148                 spin_lock(&dchild->d_inode->i_lock);
2149                 set_nlink(dchild->d_inode, body->mbo_nlink);
2150                 spin_unlock(&dchild->d_inode->i_lock);
2151         }
2152
2153         ll_update_times(request, dir);
2154
2155 out:
2156         ptlrpc_req_finished(request);
2157         if (!rc)
2158                 ll_stats_ops_tally(ll_i2sbi(dir), LPROC_LL_UNLINK,
2159                                    ktime_us_delta(ktime_get(), kstart));
2160 clear:
2161         ll_clear_inode_lock_owner(dir);
2162         ll_clear_inode_lock_owner(dchild->d_inode);
2163         RETURN(rc);
2164 }
2165
2166 static int ll_rename(struct mnt_idmap *map,
2167                      struct inode *src, struct dentry *src_dchild,
2168                      struct inode *tgt, struct dentry *tgt_dchild
2169 #if defined(HAVE_USER_NAMESPACE_ARG) || defined(HAVE_IOPS_RENAME_WITH_FLAGS)
2170                      , unsigned int flags
2171 #endif
2172                      )
2173 {
2174         struct ptlrpc_request *request = NULL;
2175         struct ll_sb_info *sbi = ll_i2sbi(src);
2176         struct md_op_data *op_data;
2177         ktime_t kstart = ktime_get();
2178         umode_t mode = 0;
2179         struct llcrypt_name foldname, fnewname;
2180         int err;
2181         ENTRY;
2182
2183         /* VFS has locked the inodes before calling this */
2184         ll_set_inode_lock_owner(src);
2185         ll_set_inode_lock_owner(tgt);
2186         if (tgt_dchild->d_inode)
2187                 ll_set_inode_lock_owner(tgt_dchild->d_inode);
2188
2189 #if defined(HAVE_USER_NAMESPACE_ARG) || defined(HAVE_IOPS_RENAME_WITH_FLAGS)
2190         if (flags)
2191                 GOTO(out, err = -EINVAL);
2192 #endif
2193
2194         CDEBUG(D_VFSTRACE,
2195                "VFS Op:oldname=%pd, src_dir="DFID"(%p), newname=%pd, tgt_dir="DFID"(%p)\n",
2196                src_dchild, PFID(ll_inode2fid(src)), src,
2197                tgt_dchild, PFID(ll_inode2fid(tgt)), tgt);
2198
2199         if (unlikely(d_mountpoint(src_dchild) || d_mountpoint(tgt_dchild)))
2200                 GOTO(out, err = -EBUSY);
2201
2202 #if defined(HAVE_USER_NAMESPACE_ARG) || defined(HAVE_IOPS_RENAME_WITH_FLAGS)
2203         err = llcrypt_prepare_rename(src, src_dchild, tgt, tgt_dchild, flags);
2204 #else
2205         err = llcrypt_prepare_rename(src, src_dchild, tgt, tgt_dchild, 0);
2206 #endif
2207         if (err)
2208                 GOTO(out, err);
2209         /* we prevent an encrypted file from being renamed
2210          * into an unencrypted dir
2211          */
2212         if (IS_ENCRYPTED(src) && !IS_ENCRYPTED(tgt))
2213                 GOTO(out, err = -EXDEV);
2214
2215         if (src_dchild->d_inode)
2216                 mode = src_dchild->d_inode->i_mode;
2217
2218         if (tgt_dchild->d_inode)
2219                 mode = tgt_dchild->d_inode->i_mode;
2220
2221         op_data = ll_prep_md_op_data(NULL, src, tgt, NULL, 0, mode,
2222                                      LUSTRE_OPC_ANY, NULL);
2223         if (IS_ERR(op_data))
2224                 GOTO(out, err = PTR_ERR(op_data));
2225
2226         /* If the client is using a subdir mount and does a rename to what it
2227          * sees as /.fscrypt, interpret it as the .fscrypt dir at fs root.
2228          */
2229         if (unlikely(is_root_inode(tgt) && !fid_is_root(ll_inode2fid(tgt)) &&
2230                      tgt_dchild->d_name.len == strlen(dot_fscrypt_name) &&
2231                      strncmp(tgt_dchild->d_name.name, dot_fscrypt_name,
2232                              tgt_dchild->d_name.len) == 0))
2233                 lu_root_fid(&op_data->op_fid2);
2234
2235         if (src_dchild->d_inode)
2236                 op_data->op_fid3 = *ll_inode2fid(src_dchild->d_inode);
2237
2238         if (tgt_dchild->d_inode)
2239                 op_data->op_fid4 = *ll_inode2fid(tgt_dchild->d_inode);
2240
2241         err = ll_setup_filename(src, &src_dchild->d_name, 1, &foldname, NULL);
2242         if (err)
2243                 GOTO(out, err);
2244         err = ll_setup_filename(tgt, &tgt_dchild->d_name, 1, &fnewname, NULL);
2245         if (err) {
2246                 llcrypt_free_filename(&foldname);
2247                 GOTO(out, err);
2248         }
2249         err = md_rename(sbi->ll_md_exp, op_data,
2250                         foldname.disk_name.name, foldname.disk_name.len,
2251                         fnewname.disk_name.name, fnewname.disk_name.len,
2252                         &request);
2253         llcrypt_free_filename(&foldname);
2254         llcrypt_free_filename(&fnewname);
2255         ll_finish_md_op_data(op_data);
2256         if (!err) {
2257                 ll_update_times(request, src);
2258                 ll_update_times(request, tgt);
2259         }
2260
2261         ptlrpc_req_finished(request);
2262
2263         if (!err) {
2264                 d_move(src_dchild, tgt_dchild);
2265                 ll_stats_ops_tally(sbi, LPROC_LL_RENAME,
2266                                    ktime_us_delta(ktime_get(), kstart));
2267         }
2268 out:
2269         ll_clear_inode_lock_owner(src);
2270         ll_clear_inode_lock_owner(tgt);
2271         if (tgt_dchild->d_inode)
2272                 ll_clear_inode_lock_owner(tgt_dchild->d_inode);
2273         RETURN(err);
2274 }
2275
2276 const struct inode_operations ll_dir_inode_operations = {
2277         .mknod          = ll_mknod,
2278         .atomic_open    = ll_atomic_open,
2279         .lookup         = ll_lookup_nd,
2280         .create         = ll_create_nd,
2281         /* We need all these non-raw things for NFSD, to not patch it. */
2282         .unlink         = ll_unlink,
2283         .mkdir          = ll_mkdir,
2284         .rmdir          = ll_rmdir,
2285         .symlink        = ll_symlink,
2286         .link           = ll_link,
2287         .rename         = ll_rename,
2288         .setattr        = ll_setattr,
2289         .getattr        = ll_getattr,
2290         .permission     = ll_inode_permission,
2291 #ifdef HAVE_IOP_XATTR
2292         .setxattr       = ll_setxattr,
2293         .getxattr       = ll_getxattr,
2294         .removexattr    = ll_removexattr,
2295 #endif
2296         .listxattr      = ll_listxattr,
2297         .get_acl        = ll_get_acl,
2298 #ifdef HAVE_IOP_SET_ACL
2299         .set_acl        = ll_set_acl,
2300 #endif
2301 #ifdef HAVE_FILEATTR_GET
2302         .fileattr_get   = ll_fileattr_get,
2303         .fileattr_set   = ll_fileattr_set,
2304 #endif
2305 };
2306
2307 const struct inode_operations ll_special_inode_operations = {
2308         .setattr        = ll_setattr,
2309         .getattr        = ll_getattr,
2310         .permission     = ll_inode_permission,
2311 #ifdef HAVE_IOP_XATTR
2312         .setxattr       = ll_setxattr,
2313         .getxattr       = ll_getxattr,
2314         .removexattr    = ll_removexattr,
2315 #endif
2316         .listxattr      = ll_listxattr,
2317         .get_acl        = ll_get_acl,
2318 #ifdef HAVE_IOP_SET_ACL
2319         .set_acl        = ll_set_acl,
2320 #endif
2321 };