GNU Linux-libre 4.14.266-gnu1
[releases.git] / drivers / staging / lustre / lustre / llite / statahead.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) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2015, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  * Lustre is a trademark of Sun Microsystems, Inc.
31  */
32
33 #include <linux/fs.h>
34 #include <linux/sched.h>
35 #include <linux/mm.h>
36 #include <linux/highmem.h>
37 #include <linux/pagemap.h>
38
39 #define DEBUG_SUBSYSTEM S_LLITE
40
41 #include <obd_support.h>
42 #include <lustre_dlm.h>
43 #include "llite_internal.h"
44
45 #define SA_OMITTED_ENTRY_MAX 8ULL
46
47 enum se_stat {
48         /** negative values are for error cases */
49         SA_ENTRY_INIT = 0,      /** init entry */
50         SA_ENTRY_SUCC = 1,      /** stat succeed */
51         SA_ENTRY_INVA = 2,      /** invalid entry */
52 };
53
54 /*
55  * sa_entry is not refcounted: statahead thread allocates it and do async stat,
56  * and in async stat callback ll_statahead_interpret() will add it into
57  * sai_interim_entries, later statahead thread will call sa_handle_callback() to
58  * instantiate entry and move it into sai_entries, and then only scanner process
59  * can access and free it.
60  */
61 struct sa_entry {
62         /* link into sai_interim_entries or sai_entries */
63         struct list_head              se_list;
64         /* link into sai hash table locally */
65         struct list_head              se_hash;
66         /* entry index in the sai */
67         __u64              se_index;
68         /* low layer ldlm lock handle */
69         __u64              se_handle;
70         /* entry status */
71         enum se_stat            se_state;
72         /* entry size, contains name */
73         int                  se_size;
74         /* pointer to async getattr enqueue info */
75         struct md_enqueue_info *se_minfo;
76         /* pointer to the async getattr request */
77         struct ptlrpc_request  *se_req;
78         /* pointer to the target inode */
79         struct inode       *se_inode;
80         /* entry name */
81         struct qstr          se_qstr;
82         /* entry fid */
83         struct lu_fid           se_fid;
84 };
85
86 static unsigned int sai_generation;
87 static DEFINE_SPINLOCK(sai_generation_lock);
88
89 /* sa_entry is ready to use */
90 static inline int sa_ready(struct sa_entry *entry)
91 {
92         smp_rmb();
93         return (entry->se_state != SA_ENTRY_INIT);
94 }
95
96 /* hash value to put in sai_cache */
97 static inline int sa_hash(int val)
98 {
99         return val & LL_SA_CACHE_MASK;
100 }
101
102 /* hash entry into sai_cache */
103 static inline void
104 sa_rehash(struct ll_statahead_info *sai, struct sa_entry *entry)
105 {
106         int i = sa_hash(entry->se_qstr.hash);
107
108         spin_lock(&sai->sai_cache_lock[i]);
109         list_add_tail(&entry->se_hash, &sai->sai_cache[i]);
110         spin_unlock(&sai->sai_cache_lock[i]);
111 }
112
113 /*
114  * Remove entry from SA table.
115  */
116 static inline void
117 sa_unhash(struct ll_statahead_info *sai, struct sa_entry *entry)
118 {
119         int i = sa_hash(entry->se_qstr.hash);
120
121         spin_lock(&sai->sai_cache_lock[i]);
122         list_del_init(&entry->se_hash);
123         spin_unlock(&sai->sai_cache_lock[i]);
124 }
125
126 static inline int agl_should_run(struct ll_statahead_info *sai,
127                                  struct inode *inode)
128 {
129         return (inode && S_ISREG(inode->i_mode) && sai->sai_agl_valid);
130 }
131
132 /* statahead window is full */
133 static inline int sa_sent_full(struct ll_statahead_info *sai)
134 {
135         return atomic_read(&sai->sai_cache_count) >= sai->sai_max;
136 }
137
138 /* got async stat replies */
139 static inline int sa_has_callback(struct ll_statahead_info *sai)
140 {
141         return !list_empty(&sai->sai_interim_entries);
142 }
143
144 static inline int agl_list_empty(struct ll_statahead_info *sai)
145 {
146         return list_empty(&sai->sai_agls);
147 }
148
149 /**
150  * (1) hit ratio less than 80%
151  * or
152  * (2) consecutive miss more than 8
153  * then means low hit.
154  */
155 static inline int sa_low_hit(struct ll_statahead_info *sai)
156 {
157         return ((sai->sai_hit > 7 && sai->sai_hit < 4 * sai->sai_miss) ||
158                 (sai->sai_consecutive_miss > 8));
159 }
160
161 /*
162  * if the given index is behind of statahead window more than
163  * SA_OMITTED_ENTRY_MAX, then it is old.
164  */
165 static inline int is_omitted_entry(struct ll_statahead_info *sai, __u64 index)
166 {
167         return ((__u64)sai->sai_max + index + SA_OMITTED_ENTRY_MAX <
168                  sai->sai_index);
169 }
170
171 /* allocate sa_entry and hash it to allow scanner process to find it */
172 static struct sa_entry *
173 sa_alloc(struct dentry *parent, struct ll_statahead_info *sai, __u64 index,
174          const char *name, int len, const struct lu_fid *fid)
175 {
176         struct ll_inode_info *lli;
177         struct sa_entry   *entry;
178         int                entry_size;
179         char             *dname;
180
181         entry_size = sizeof(struct sa_entry) + (len & ~3) + 4;
182         entry = kzalloc(entry_size, GFP_NOFS);
183         if (unlikely(!entry))
184                 return ERR_PTR(-ENOMEM);
185
186         CDEBUG(D_READA, "alloc sa entry %.*s(%p) index %llu\n",
187                len, name, entry, index);
188
189         entry->se_index = index;
190         entry->se_state = SA_ENTRY_INIT;
191         entry->se_size = entry_size;
192         dname = (char *)entry + sizeof(struct sa_entry);
193         memcpy(dname, name, len);
194         dname[len] = 0;
195
196         entry->se_qstr.hash = full_name_hash(parent, name, len);
197         entry->se_qstr.len = len;
198         entry->se_qstr.name = dname;
199         entry->se_fid = *fid;
200
201         lli = ll_i2info(sai->sai_dentry->d_inode);
202         spin_lock(&lli->lli_sa_lock);
203         INIT_LIST_HEAD(&entry->se_list);
204         sa_rehash(sai, entry);
205         spin_unlock(&lli->lli_sa_lock);
206
207         atomic_inc(&sai->sai_cache_count);
208
209         return entry;
210 }
211
212 /* free sa_entry, which should have been unhashed and not in any list */
213 static void sa_free(struct ll_statahead_info *sai, struct sa_entry *entry)
214 {
215         CDEBUG(D_READA, "free sa entry %.*s(%p) index %llu\n",
216                entry->se_qstr.len, entry->se_qstr.name, entry,
217                entry->se_index);
218
219         LASSERT(list_empty(&entry->se_list));
220         LASSERT(list_empty(&entry->se_hash));
221
222         kfree(entry);
223         atomic_dec(&sai->sai_cache_count);
224 }
225
226 /*
227  * find sa_entry by name, used by directory scanner, lock is not needed because
228  * only scanner can remove the entry from cache.
229  */
230 static struct sa_entry *
231 sa_get(struct ll_statahead_info *sai, const struct qstr *qstr)
232 {
233         struct sa_entry *entry;
234         int i = sa_hash(qstr->hash);
235
236         list_for_each_entry(entry, &sai->sai_cache[i], se_hash) {
237                 if (entry->se_qstr.hash == qstr->hash &&
238                     entry->se_qstr.len == qstr->len &&
239                     memcmp(entry->se_qstr.name, qstr->name, qstr->len) == 0)
240                         return entry;
241         }
242         return NULL;
243 }
244
245 /* unhash and unlink sa_entry, and then free it */
246 static inline void
247 sa_kill(struct ll_statahead_info *sai, struct sa_entry *entry)
248 {
249         struct ll_inode_info *lli = ll_i2info(sai->sai_dentry->d_inode);
250
251         LASSERT(!list_empty(&entry->se_hash));
252         LASSERT(!list_empty(&entry->se_list));
253         LASSERT(sa_ready(entry));
254
255         sa_unhash(sai, entry);
256
257         spin_lock(&lli->lli_sa_lock);
258         list_del_init(&entry->se_list);
259         spin_unlock(&lli->lli_sa_lock);
260
261         if (entry->se_inode)
262                 iput(entry->se_inode);
263
264         sa_free(sai, entry);
265 }
266
267 /* called by scanner after use, sa_entry will be killed */
268 static void
269 sa_put(struct ll_statahead_info *sai, struct sa_entry *entry)
270 {
271         struct sa_entry *tmp, *next;
272
273         if (entry && entry->se_state == SA_ENTRY_SUCC) {
274                 struct ll_sb_info *sbi = ll_i2sbi(sai->sai_dentry->d_inode);
275
276                 sai->sai_hit++;
277                 sai->sai_consecutive_miss = 0;
278                 sai->sai_max = min(2 * sai->sai_max, sbi->ll_sa_max);
279         } else {
280                 sai->sai_miss++;
281                 sai->sai_consecutive_miss++;
282         }
283
284         if (entry)
285                 sa_kill(sai, entry);
286
287         /*
288          * kill old completed entries, only scanner process does this, no need
289          * to lock
290          */
291         list_for_each_entry_safe(tmp, next, &sai->sai_entries, se_list) {
292                 if (!is_omitted_entry(sai, tmp->se_index))
293                         break;
294                 sa_kill(sai, tmp);
295         }
296
297         wake_up(&sai->sai_thread.t_ctl_waitq);
298 }
299
300 /*
301  * update state and sort add entry to sai_entries by index, return true if
302  * scanner is waiting on this entry.
303  */
304 static bool
305 __sa_make_ready(struct ll_statahead_info *sai, struct sa_entry *entry, int ret)
306 {
307         struct list_head *pos = &sai->sai_entries;
308         __u64 index = entry->se_index;
309         struct sa_entry *se;
310
311         LASSERT(!sa_ready(entry));
312         LASSERT(list_empty(&entry->se_list));
313
314         list_for_each_entry_reverse(se, &sai->sai_entries, se_list) {
315                 if (se->se_index < entry->se_index) {
316                         pos = &se->se_list;
317                         break;
318                 }
319         }
320         list_add(&entry->se_list, pos);
321         entry->se_state = ret < 0 ? SA_ENTRY_INVA : SA_ENTRY_SUCC;
322
323         return (index == sai->sai_index_wait);
324 }
325
326 /*
327  * release resources used in async stat RPC, update entry state and wakeup if
328  * scanner process it waiting on this entry.
329  */
330 static void
331 sa_make_ready(struct ll_statahead_info *sai, struct sa_entry *entry, int ret)
332 {
333         struct ll_inode_info *lli = ll_i2info(sai->sai_dentry->d_inode);
334         struct md_enqueue_info *minfo = entry->se_minfo;
335         struct ptlrpc_request *req = entry->se_req;
336         bool wakeup;
337
338         /* release resources used in RPC */
339         if (minfo) {
340                 entry->se_minfo = NULL;
341                 ll_intent_release(&minfo->mi_it);
342                 iput(minfo->mi_dir);
343                 kfree(minfo);
344         }
345
346         if (req) {
347                 entry->se_req = NULL;
348                 ptlrpc_req_finished(req);
349         }
350
351         spin_lock(&lli->lli_sa_lock);
352         wakeup = __sa_make_ready(sai, entry, ret);
353         spin_unlock(&lli->lli_sa_lock);
354
355         if (wakeup)
356                 wake_up(&sai->sai_waitq);
357 }
358
359 /* Insert inode into the list of sai_agls. */
360 static void ll_agl_add(struct ll_statahead_info *sai,
361                        struct inode *inode, int index)
362 {
363         struct ll_inode_info *child  = ll_i2info(inode);
364         struct ll_inode_info *parent = ll_i2info(sai->sai_dentry->d_inode);
365         int                added  = 0;
366
367         spin_lock(&child->lli_agl_lock);
368         if (child->lli_agl_index == 0) {
369                 child->lli_agl_index = index;
370                 spin_unlock(&child->lli_agl_lock);
371
372                 LASSERT(list_empty(&child->lli_agl_list));
373
374                 igrab(inode);
375                 spin_lock(&parent->lli_agl_lock);
376                 if (list_empty(&sai->sai_agls))
377                         added = 1;
378                 list_add_tail(&child->lli_agl_list, &sai->sai_agls);
379                 spin_unlock(&parent->lli_agl_lock);
380         } else {
381                 spin_unlock(&child->lli_agl_lock);
382         }
383
384         if (added > 0)
385                 wake_up(&sai->sai_agl_thread.t_ctl_waitq);
386 }
387
388 /* allocate sai */
389 static struct ll_statahead_info *ll_sai_alloc(struct dentry *dentry)
390 {
391         struct ll_inode_info *lli = ll_i2info(dentry->d_inode);
392         struct ll_statahead_info *sai;
393         int                    i;
394
395         sai = kzalloc(sizeof(*sai), GFP_NOFS);
396         if (!sai)
397                 return NULL;
398
399         sai->sai_dentry = dget(dentry);
400         atomic_set(&sai->sai_refcount, 1);
401
402         sai->sai_max = LL_SA_RPC_MIN;
403         sai->sai_index = 1;
404         init_waitqueue_head(&sai->sai_waitq);
405         init_waitqueue_head(&sai->sai_thread.t_ctl_waitq);
406         init_waitqueue_head(&sai->sai_agl_thread.t_ctl_waitq);
407
408         INIT_LIST_HEAD(&sai->sai_interim_entries);
409         INIT_LIST_HEAD(&sai->sai_entries);
410         INIT_LIST_HEAD(&sai->sai_agls);
411
412         for (i = 0; i < LL_SA_CACHE_SIZE; i++) {
413                 INIT_LIST_HEAD(&sai->sai_cache[i]);
414                 spin_lock_init(&sai->sai_cache_lock[i]);
415         }
416         atomic_set(&sai->sai_cache_count, 0);
417
418         spin_lock(&sai_generation_lock);
419         lli->lli_sa_generation = ++sai_generation;
420         if (unlikely(!sai_generation))
421                 lli->lli_sa_generation = ++sai_generation;
422         spin_unlock(&sai_generation_lock);
423
424         return sai;
425 }
426
427 /* free sai */
428 static inline void ll_sai_free(struct ll_statahead_info *sai)
429 {
430         LASSERT(sai->sai_dentry);
431         dput(sai->sai_dentry);
432         kfree(sai);
433 }
434
435 /*
436  * take refcount of sai if sai for @dir exists, which means statahead is on for
437  * this directory.
438  */
439 static inline struct ll_statahead_info *ll_sai_get(struct inode *dir)
440 {
441         struct ll_inode_info *lli = ll_i2info(dir);
442         struct ll_statahead_info *sai = NULL;
443
444         spin_lock(&lli->lli_sa_lock);
445         sai = lli->lli_sai;
446         if (sai)
447                 atomic_inc(&sai->sai_refcount);
448         spin_unlock(&lli->lli_sa_lock);
449
450         return sai;
451 }
452
453 /*
454  * put sai refcount after use, if refcount reaches zero, free sai and sa_entries
455  * attached to it.
456  */
457 static void ll_sai_put(struct ll_statahead_info *sai)
458 {
459         struct ll_inode_info *lli = ll_i2info(sai->sai_dentry->d_inode);
460
461         if (atomic_dec_and_lock(&sai->sai_refcount, &lli->lli_sa_lock)) {
462                 struct ll_sb_info *sbi = ll_i2sbi(sai->sai_dentry->d_inode);
463                 struct sa_entry *entry, *next;
464
465                 lli->lli_sai = NULL;
466                 spin_unlock(&lli->lli_sa_lock);
467
468                 LASSERT(thread_is_stopped(&sai->sai_thread));
469                 LASSERT(thread_is_stopped(&sai->sai_agl_thread));
470                 LASSERT(sai->sai_sent == sai->sai_replied);
471                 LASSERT(!sa_has_callback(sai));
472
473                 list_for_each_entry_safe(entry, next, &sai->sai_entries,
474                                          se_list)
475                         sa_kill(sai, entry);
476
477                 LASSERT(atomic_read(&sai->sai_cache_count) == 0);
478                 LASSERT(list_empty(&sai->sai_agls));
479
480                 ll_sai_free(sai);
481                 atomic_dec(&sbi->ll_sa_running);
482         }
483 }
484
485 /* Do NOT forget to drop inode refcount when into sai_agls. */
486 static void ll_agl_trigger(struct inode *inode, struct ll_statahead_info *sai)
487 {
488         struct ll_inode_info *lli   = ll_i2info(inode);
489         __u64            index = lli->lli_agl_index;
490         int                rc;
491
492         LASSERT(list_empty(&lli->lli_agl_list));
493
494         /* AGL maybe fall behind statahead with one entry */
495         if (is_omitted_entry(sai, index + 1)) {
496                 lli->lli_agl_index = 0;
497                 iput(inode);
498                 return;
499         }
500
501         /* Someone is in glimpse (sync or async), do nothing. */
502         rc = down_write_trylock(&lli->lli_glimpse_sem);
503         if (rc == 0) {
504                 lli->lli_agl_index = 0;
505                 iput(inode);
506                 return;
507         }
508
509         /*
510          * Someone triggered glimpse within 1 sec before.
511          * 1) The former glimpse succeeded with glimpse lock granted by OST, and
512          *    if the lock is still cached on client, AGL needs to do nothing. If
513          *    it is cancelled by other client, AGL maybe cannot obtain new lock
514          *    for no glimpse callback triggered by AGL.
515          * 2) The former glimpse succeeded, but OST did not grant glimpse lock.
516          *    Under such case, it is quite possible that the OST will not grant
517          *    glimpse lock for AGL also.
518          * 3) The former glimpse failed, compared with other two cases, it is
519          *    relative rare. AGL can ignore such case, and it will not muchly
520          *    affect the performance.
521          */
522         if (lli->lli_glimpse_time != 0 &&
523             time_before(cfs_time_shift(-1), lli->lli_glimpse_time)) {
524                 up_write(&lli->lli_glimpse_sem);
525                 lli->lli_agl_index = 0;
526                 iput(inode);
527                 return;
528         }
529
530         CDEBUG(D_READA, "Handling (init) async glimpse: inode = "
531                DFID ", idx = %llu\n", PFID(&lli->lli_fid), index);
532
533         cl_agl(inode);
534         lli->lli_agl_index = 0;
535         lli->lli_glimpse_time = cfs_time_current();
536         up_write(&lli->lli_glimpse_sem);
537
538         CDEBUG(D_READA, "Handled (init) async glimpse: inode= "
539                DFID ", idx = %llu, rc = %d\n",
540                PFID(&lli->lli_fid), index, rc);
541
542         iput(inode);
543 }
544
545 /*
546  * prepare inode for sa entry, add it into agl list, now sa_entry is ready
547  * to be used by scanner process.
548  */
549 static void sa_instantiate(struct ll_statahead_info *sai,
550                            struct sa_entry *entry)
551 {
552         struct inode *dir = sai->sai_dentry->d_inode;
553         struct inode       *child;
554         struct md_enqueue_info *minfo;
555         struct lookup_intent   *it;
556         struct ptlrpc_request  *req;
557         struct mdt_body *body;
558         int                  rc    = 0;
559
560         LASSERT(entry->se_handle != 0);
561
562         minfo = entry->se_minfo;
563         it = &minfo->mi_it;
564         req = entry->se_req;
565         body = req_capsule_server_get(&req->rq_pill, &RMF_MDT_BODY);
566         if (!body) {
567                 rc = -EFAULT;
568                 goto out;
569         }
570
571         child = entry->se_inode;
572         if (child) {
573                 /* revalidate; unlinked and re-created with the same name */
574                 if (unlikely(!lu_fid_eq(&minfo->mi_data.op_fid2, &body->mbo_fid1))) {
575                         entry->se_inode = NULL;
576                         iput(child);
577                         child = NULL;
578                 }
579         }
580
581         it->it_lock_handle = entry->se_handle;
582         rc = md_revalidate_lock(ll_i2mdexp(dir), it, ll_inode2fid(dir), NULL);
583         if (rc != 1) {
584                 rc = -EAGAIN;
585                 goto out;
586         }
587
588         rc = ll_prep_inode(&child, req, dir->i_sb, it);
589         if (rc)
590                 goto out;
591
592         CDEBUG(D_READA, "%s: setting %.*s" DFID " l_data to inode %p\n",
593                ll_get_fsname(child->i_sb, NULL, 0),
594                entry->se_qstr.len, entry->se_qstr.name,
595                PFID(ll_inode2fid(child)), child);
596         ll_set_lock_data(ll_i2sbi(dir)->ll_md_exp, child, it, NULL);
597
598         entry->se_inode = child;
599
600         if (agl_should_run(sai, child))
601                 ll_agl_add(sai, child, entry->se_index);
602
603 out:
604         /*
605          * sa_make_ready() will drop ldlm ibits lock refcount by calling
606          * ll_intent_drop_lock() in spite of failures. Do not worry about
607          * calling ll_intent_drop_lock() more than once.
608          */
609         sa_make_ready(sai, entry, rc);
610 }
611
612 /* once there are async stat replies, instantiate sa_entry from replies */
613 static void sa_handle_callback(struct ll_statahead_info *sai)
614 {
615         struct ll_inode_info *lli;
616
617         lli = ll_i2info(sai->sai_dentry->d_inode);
618
619         while (sa_has_callback(sai)) {
620                 struct sa_entry *entry;
621
622                 spin_lock(&lli->lli_sa_lock);
623                 if (unlikely(!sa_has_callback(sai))) {
624                         spin_unlock(&lli->lli_sa_lock);
625                         break;
626                 }
627                 entry = list_entry(sai->sai_interim_entries.next,
628                                    struct sa_entry, se_list);
629                 list_del_init(&entry->se_list);
630                 spin_unlock(&lli->lli_sa_lock);
631
632                 sa_instantiate(sai, entry);
633         }
634 }
635
636 /*
637  * callback for async stat, because this is called in ptlrpcd context, we only
638  * put sa_entry in sai_cb_entries list, and let sa_handle_callback() to really
639  * prepare inode and instantiate sa_entry later.
640  */
641 static int ll_statahead_interpret(struct ptlrpc_request *req,
642                                   struct md_enqueue_info *minfo, int rc)
643 {
644         struct lookup_intent     *it  = &minfo->mi_it;
645         struct inode         *dir = minfo->mi_dir;
646         struct ll_inode_info     *lli = ll_i2info(dir);
647         struct ll_statahead_info *sai = lli->lli_sai;
648         struct sa_entry *entry = (struct sa_entry *)minfo->mi_cbdata;
649         wait_queue_head_t *waitq = NULL;
650         __u64 handle = 0;
651
652         if (it_disposition(it, DISP_LOOKUP_NEG))
653                 rc = -ENOENT;
654
655         /*
656          * because statahead thread will wait for all inflight RPC to finish,
657          * sai should be always valid, no need to refcount
658          */
659         LASSERT(sai);
660         LASSERT(!thread_is_stopped(&sai->sai_thread));
661         LASSERT(entry);
662
663         CDEBUG(D_READA, "sa_entry %.*s rc %d\n",
664                entry->se_qstr.len, entry->se_qstr.name, rc);
665
666         if (rc) {
667                 ll_intent_release(it);
668                 iput(dir);
669                 kfree(minfo);
670         } else {
671                 /*
672                  * release ibits lock ASAP to avoid deadlock when statahead
673                  * thread enqueues lock on parent in readdir and another
674                  * process enqueues lock on child with parent lock held, eg.
675                  * unlink.
676                  */
677                 handle = it->it_lock_handle;
678                 ll_intent_drop_lock(it);
679         }
680
681         spin_lock(&lli->lli_sa_lock);
682         if (rc) {
683                 if (__sa_make_ready(sai, entry, rc))
684                         waitq = &sai->sai_waitq;
685         } else {
686                 entry->se_minfo = minfo;
687                 entry->se_req = ptlrpc_request_addref(req);
688                 /*
689                  * Release the async ibits lock ASAP to avoid deadlock
690                  * when statahead thread tries to enqueue lock on parent
691                  * for readpage and other tries to enqueue lock on child
692                  * with parent's lock held, for example: unlink.
693                  */
694                 entry->se_handle = handle;
695                 if (!sa_has_callback(sai))
696                         waitq = &sai->sai_thread.t_ctl_waitq;
697
698                 list_add_tail(&entry->se_list, &sai->sai_interim_entries);
699         }
700         sai->sai_replied++;
701
702         if (waitq)
703                 wake_up(waitq);
704         spin_unlock(&lli->lli_sa_lock);
705
706         return rc;
707 }
708
709 /* finish async stat RPC arguments */
710 static void sa_fini_data(struct md_enqueue_info *minfo)
711 {
712         iput(minfo->mi_dir);
713         kfree(minfo);
714 }
715
716 /**
717  * prepare arguments for async stat RPC.
718  */
719 static struct md_enqueue_info *
720 sa_prep_data(struct inode *dir, struct inode *child, struct sa_entry *entry)
721 {
722         struct md_enqueue_info   *minfo;
723         struct ldlm_enqueue_info *einfo;
724         struct md_op_data       *op_data;
725
726         minfo = kzalloc(sizeof(*minfo), GFP_NOFS);
727         if (!minfo)
728                 return ERR_PTR(-ENOMEM);
729
730         op_data = ll_prep_md_op_data(&minfo->mi_data, dir, child, NULL, 0, 0,
731                                      LUSTRE_OPC_ANY, NULL);
732         if (IS_ERR(op_data)) {
733                 kfree(minfo);
734                 return (struct md_enqueue_info *)op_data;
735         }
736
737         if (!child)
738                 op_data->op_fid2 = entry->se_fid;
739
740         minfo->mi_it.it_op = IT_GETATTR;
741         minfo->mi_dir = igrab(dir);
742         minfo->mi_cb = ll_statahead_interpret;
743         minfo->mi_cbdata = entry;
744
745         einfo = &minfo->mi_einfo;
746         einfo->ei_type   = LDLM_IBITS;
747         einfo->ei_mode   = it_to_lock_mode(&minfo->mi_it);
748         einfo->ei_cb_bl  = ll_md_blocking_ast;
749         einfo->ei_cb_cp  = ldlm_completion_ast;
750         einfo->ei_cb_gl  = NULL;
751         einfo->ei_cbdata = NULL;
752
753         return minfo;
754 }
755
756 /* async stat for file not found in dcache */
757 static int sa_lookup(struct inode *dir, struct sa_entry *entry)
758 {
759         struct md_enqueue_info   *minfo;
760         int                    rc;
761
762         minfo = sa_prep_data(dir, NULL, entry);
763         if (IS_ERR(minfo))
764                 return PTR_ERR(minfo);
765
766         rc = md_intent_getattr_async(ll_i2mdexp(dir), minfo);
767         if (rc)
768                 sa_fini_data(minfo);
769
770         return rc;
771 }
772
773 /**
774  * async stat for file found in dcache, similar to .revalidate
775  *
776  * \retval      1 dentry valid, no RPC sent
777  * \retval      0 dentry invalid, will send async stat RPC
778  * \retval      negative number upon error
779  */
780 static int sa_revalidate(struct inode *dir, struct sa_entry *entry,
781                          struct dentry *dentry)
782 {
783         struct inode         *inode = d_inode(dentry);
784         struct lookup_intent      it = { .it_op = IT_GETATTR,
785                                          .it_lock_handle = 0 };
786         struct md_enqueue_info   *minfo;
787         int rc;
788
789         if (unlikely(!inode))
790                 return 1;
791
792         if (d_mountpoint(dentry))
793                 return 1;
794
795         entry->se_inode = igrab(inode);
796         rc = md_revalidate_lock(ll_i2mdexp(dir), &it, ll_inode2fid(inode),
797                                 NULL);
798         if (rc == 1) {
799                 entry->se_handle = it.it_lock_handle;
800                 ll_intent_release(&it);
801                 return 1;
802         }
803
804         minfo = sa_prep_data(dir, inode, entry);
805         if (IS_ERR(minfo)) {
806                 entry->se_inode = NULL;
807                 iput(inode);
808                 return PTR_ERR(minfo);
809         }
810
811         rc = md_intent_getattr_async(ll_i2mdexp(dir), minfo);
812         if (rc) {
813                 entry->se_inode = NULL;
814                 iput(inode);
815                 sa_fini_data(minfo);
816         }
817
818         return rc;
819 }
820
821 /* async stat for file with @name */
822 static void sa_statahead(struct dentry *parent, const char *name, int len,
823                          const struct lu_fid *fid)
824 {
825         struct inode         *dir    = d_inode(parent);
826         struct ll_inode_info     *lli    = ll_i2info(dir);
827         struct ll_statahead_info *sai    = lli->lli_sai;
828         struct dentry       *dentry = NULL;
829         struct sa_entry *entry;
830         int                    rc;
831
832         entry = sa_alloc(parent, sai, sai->sai_index, name, len, fid);
833         if (IS_ERR(entry))
834                 return;
835
836         dentry = d_lookup(parent, &entry->se_qstr);
837         if (!dentry) {
838                 rc = sa_lookup(dir, entry);
839         } else {
840                 rc = sa_revalidate(dir, entry, dentry);
841                 if (rc == 1 && agl_should_run(sai, d_inode(dentry)))
842                         ll_agl_add(sai, d_inode(dentry), entry->se_index);
843         }
844
845         if (dentry)
846                 dput(dentry);
847
848         if (rc)
849                 sa_make_ready(sai, entry, rc);
850         else
851                 sai->sai_sent++;
852
853         sai->sai_index++;
854 }
855
856 /* async glimpse (agl) thread main function */
857 static int ll_agl_thread(void *arg)
858 {
859         struct dentry       *parent = arg;
860         struct inode         *dir    = d_inode(parent);
861         struct ll_inode_info     *plli   = ll_i2info(dir);
862         struct ll_inode_info     *clli;
863         struct ll_sb_info       *sbi    = ll_i2sbi(dir);
864         struct ll_statahead_info *sai;
865         struct ptlrpc_thread *thread;
866         struct l_wait_info      lwi    = { 0 };
867
868         sai = ll_sai_get(dir);
869         thread = &sai->sai_agl_thread;
870         thread->t_pid = current_pid();
871         CDEBUG(D_READA, "agl thread started: sai %p, parent %pd\n",
872                sai, parent);
873
874         atomic_inc(&sbi->ll_agl_total);
875         spin_lock(&plli->lli_agl_lock);
876         sai->sai_agl_valid = 1;
877         if (thread_is_init(thread))
878                 /* If someone else has changed the thread state
879                  * (e.g. already changed to SVC_STOPPING), we can't just
880                  * blindly overwrite that setting.
881                  */
882                 thread_set_flags(thread, SVC_RUNNING);
883         spin_unlock(&plli->lli_agl_lock);
884         wake_up(&thread->t_ctl_waitq);
885
886         while (1) {
887                 l_wait_event(thread->t_ctl_waitq,
888                              !list_empty(&sai->sai_agls) ||
889                              !thread_is_running(thread),
890                              &lwi);
891
892                 if (!thread_is_running(thread))
893                         break;
894
895                 spin_lock(&plli->lli_agl_lock);
896                 /* The statahead thread maybe help to process AGL entries,
897                  * so check whether list empty again.
898                  */
899                 if (!list_empty(&sai->sai_agls)) {
900                         clli = list_entry(sai->sai_agls.next,
901                                           struct ll_inode_info, lli_agl_list);
902                         list_del_init(&clli->lli_agl_list);
903                         spin_unlock(&plli->lli_agl_lock);
904                         ll_agl_trigger(&clli->lli_vfs_inode, sai);
905                 } else {
906                         spin_unlock(&plli->lli_agl_lock);
907                 }
908         }
909
910         spin_lock(&plli->lli_agl_lock);
911         sai->sai_agl_valid = 0;
912         while (!list_empty(&sai->sai_agls)) {
913                 clli = list_entry(sai->sai_agls.next,
914                                   struct ll_inode_info, lli_agl_list);
915                 list_del_init(&clli->lli_agl_list);
916                 spin_unlock(&plli->lli_agl_lock);
917                 clli->lli_agl_index = 0;
918                 iput(&clli->lli_vfs_inode);
919                 spin_lock(&plli->lli_agl_lock);
920         }
921         thread_set_flags(thread, SVC_STOPPED);
922         spin_unlock(&plli->lli_agl_lock);
923         wake_up(&thread->t_ctl_waitq);
924         ll_sai_put(sai);
925         CDEBUG(D_READA, "agl thread stopped: sai %p, parent %pd\n",
926                sai, parent);
927         return 0;
928 }
929
930 /* start agl thread */
931 static void ll_start_agl(struct dentry *parent, struct ll_statahead_info *sai)
932 {
933         struct ptlrpc_thread *thread = &sai->sai_agl_thread;
934         struct l_wait_info    lwi    = { 0 };
935         struct ll_inode_info  *plli;
936         struct task_struct *task;
937
938         CDEBUG(D_READA, "start agl thread: sai %p, parent %pd\n",
939                sai, parent);
940
941         plli = ll_i2info(d_inode(parent));
942         task = kthread_run(ll_agl_thread, parent, "ll_agl_%u",
943                            plli->lli_opendir_pid);
944         if (IS_ERR(task)) {
945                 CERROR("can't start ll_agl thread, rc: %ld\n", PTR_ERR(task));
946                 thread_set_flags(thread, SVC_STOPPED);
947                 return;
948         }
949
950         l_wait_event(thread->t_ctl_waitq,
951                      thread_is_running(thread) || thread_is_stopped(thread),
952                      &lwi);
953 }
954
955 /* statahead thread main function */
956 static int ll_statahead_thread(void *arg)
957 {
958         struct dentry       *parent = arg;
959         struct inode         *dir    = d_inode(parent);
960         struct ll_inode_info     *lli   = ll_i2info(dir);
961         struct ll_sb_info       *sbi    = ll_i2sbi(dir);
962         struct ll_statahead_info *sai;
963         struct ptlrpc_thread *sa_thread;
964         struct ptlrpc_thread *agl_thread;
965         struct page           *page = NULL;
966         __u64                pos    = 0;
967         int                    first  = 0;
968         int                    rc     = 0;
969         struct md_op_data *op_data;
970         struct l_wait_info      lwi    = { 0 };
971
972         sai = ll_sai_get(dir);
973         sa_thread = &sai->sai_thread;
974         agl_thread = &sai->sai_agl_thread;
975         sa_thread->t_pid = current_pid();
976         CDEBUG(D_READA, "statahead thread starting: sai %p, parent %pd\n",
977                sai, parent);
978
979         op_data = ll_prep_md_op_data(NULL, dir, dir, NULL, 0, 0,
980                                      LUSTRE_OPC_ANY, dir);
981         if (IS_ERR(op_data)) {
982                 rc = PTR_ERR(op_data);
983                 goto out;
984         }
985
986         op_data->op_max_pages = ll_i2sbi(dir)->ll_md_brw_pages;
987
988         if (sbi->ll_flags & LL_SBI_AGL_ENABLED)
989                 ll_start_agl(parent, sai);
990
991         atomic_inc(&sbi->ll_sa_total);
992         spin_lock(&lli->lli_sa_lock);
993         if (thread_is_init(sa_thread))
994                 /* If someone else has changed the thread state
995                  * (e.g. already changed to SVC_STOPPING), we can't just
996                  * blindly overwrite that setting.
997                  */
998                 thread_set_flags(sa_thread, SVC_RUNNING);
999         spin_unlock(&lli->lli_sa_lock);
1000         wake_up(&sa_thread->t_ctl_waitq);
1001
1002         while (pos != MDS_DIR_END_OFF && thread_is_running(sa_thread)) {
1003                 struct lu_dirpage *dp;
1004                 struct lu_dirent  *ent;
1005
1006                 sai->sai_in_readpage = 1;
1007                 page = ll_get_dir_page(dir, op_data, pos);
1008                 sai->sai_in_readpage = 0;
1009                 if (IS_ERR(page)) {
1010                         rc = PTR_ERR(page);
1011                         CDEBUG(D_READA, "error reading dir " DFID " at %llu/%llu: opendir_pid = %u: rc = %d\n",
1012                                PFID(ll_inode2fid(dir)), pos, sai->sai_index,
1013                                lli->lli_opendir_pid, rc);
1014                         break;
1015                 }
1016
1017                 dp = page_address(page);
1018                 for (ent = lu_dirent_start(dp);
1019                      ent && thread_is_running(sa_thread) && !sa_low_hit(sai);
1020                      ent = lu_dirent_next(ent)) {
1021                         struct lu_fid fid;
1022                         __u64 hash;
1023                         int namelen;
1024                         char *name;
1025
1026                         hash = le64_to_cpu(ent->lde_hash);
1027                         if (unlikely(hash < pos))
1028                                 /*
1029                                  * Skip until we find target hash value.
1030                                  */
1031                                 continue;
1032
1033                         namelen = le16_to_cpu(ent->lde_namelen);
1034                         if (unlikely(namelen == 0))
1035                                 /*
1036                                  * Skip dummy record.
1037                                  */
1038                                 continue;
1039
1040                         name = ent->lde_name;
1041                         if (name[0] == '.') {
1042                                 if (namelen == 1) {
1043                                         /*
1044                                          * skip "."
1045                                          */
1046                                         continue;
1047                                 } else if (name[1] == '.' && namelen == 2) {
1048                                         /*
1049                                          * skip ".."
1050                                          */
1051                                         continue;
1052                                 } else if (!sai->sai_ls_all) {
1053                                         /*
1054                                          * skip hidden files.
1055                                          */
1056                                         sai->sai_skip_hidden++;
1057                                         continue;
1058                                 }
1059                         }
1060
1061                         /*
1062                          * don't stat-ahead first entry.
1063                          */
1064                         if (unlikely(++first == 1))
1065                                 continue;
1066
1067                         fid_le_to_cpu(&fid, &ent->lde_fid);
1068
1069                         /* wait for spare statahead window */
1070                         do {
1071                                 l_wait_event(sa_thread->t_ctl_waitq,
1072                                              !sa_sent_full(sai) ||
1073                                              sa_has_callback(sai) ||
1074                                              !list_empty(&sai->sai_agls) ||
1075                                              !thread_is_running(sa_thread),
1076                                              &lwi);
1077                                 sa_handle_callback(sai);
1078
1079                                 spin_lock(&lli->lli_agl_lock);
1080                                 while (sa_sent_full(sai) &&
1081                                        !agl_list_empty(sai)) {
1082                                         struct ll_inode_info *clli;
1083
1084                                         clli = list_entry(sai->sai_agls.next,
1085                                                           struct ll_inode_info, lli_agl_list);
1086                                         list_del_init(&clli->lli_agl_list);
1087                                         spin_unlock(&lli->lli_agl_lock);
1088
1089                                         ll_agl_trigger(&clli->lli_vfs_inode,
1090                                                        sai);
1091
1092                                         spin_lock(&lli->lli_agl_lock);
1093                                 }
1094                                 spin_unlock(&lli->lli_agl_lock);
1095                         } while (sa_sent_full(sai) &&
1096                                  thread_is_running(sa_thread));
1097
1098                         sa_statahead(parent, name, namelen, &fid);
1099                 }
1100
1101                 pos = le64_to_cpu(dp->ldp_hash_end);
1102                 ll_release_page(dir, page,
1103                                 le32_to_cpu(dp->ldp_flags) & LDF_COLLIDE);
1104
1105                 if (sa_low_hit(sai)) {
1106                         rc = -EFAULT;
1107                         atomic_inc(&sbi->ll_sa_wrong);
1108                         CDEBUG(D_READA, "Statahead for dir " DFID " hit ratio too low: hit/miss %llu/%llu, sent/replied %llu/%llu, stopping statahead thread: pid %d\n",
1109                                PFID(&lli->lli_fid), sai->sai_hit,
1110                                sai->sai_miss, sai->sai_sent,
1111                                sai->sai_replied, current_pid());
1112                         break;
1113                 }
1114         }
1115         ll_finish_md_op_data(op_data);
1116
1117         if (rc < 0) {
1118                 spin_lock(&lli->lli_sa_lock);
1119                 thread_set_flags(sa_thread, SVC_STOPPING);
1120                 lli->lli_sa_enabled = 0;
1121                 spin_unlock(&lli->lli_sa_lock);
1122         }
1123
1124         /*
1125          * statahead is finished, but statahead entries need to be cached, wait
1126          * for file release to stop me.
1127          */
1128         while (thread_is_running(sa_thread)) {
1129                 l_wait_event(sa_thread->t_ctl_waitq,
1130                              sa_has_callback(sai) ||
1131                              !agl_list_empty(sai) ||
1132                              !thread_is_running(sa_thread),
1133                              &lwi);
1134
1135                 sa_handle_callback(sai);
1136         }
1137 out:
1138         if (sai->sai_agl_valid) {
1139                 spin_lock(&lli->lli_agl_lock);
1140                 thread_set_flags(agl_thread, SVC_STOPPING);
1141                 spin_unlock(&lli->lli_agl_lock);
1142                 wake_up(&agl_thread->t_ctl_waitq);
1143
1144                 CDEBUG(D_READA, "stop agl thread: sai %p pid %u\n",
1145                        sai, (unsigned int)agl_thread->t_pid);
1146                 l_wait_event(agl_thread->t_ctl_waitq,
1147                              thread_is_stopped(agl_thread),
1148                              &lwi);
1149         } else {
1150                 /* Set agl_thread flags anyway. */
1151                 thread_set_flags(agl_thread, SVC_STOPPED);
1152         }
1153
1154         /*
1155          * wait for inflight statahead RPCs to finish, and then we can free sai
1156          * safely because statahead RPC will access sai data
1157          */
1158         while (sai->sai_sent != sai->sai_replied) {
1159                 /* in case we're not woken up, timeout wait */
1160                 lwi = LWI_TIMEOUT(msecs_to_jiffies(MSEC_PER_SEC >> 3),
1161                                   NULL, NULL);
1162                 l_wait_event(sa_thread->t_ctl_waitq,
1163                              sai->sai_sent == sai->sai_replied, &lwi);
1164         }
1165
1166         /* release resources held by statahead RPCs */
1167         sa_handle_callback(sai);
1168
1169         spin_lock(&lli->lli_sa_lock);
1170         thread_set_flags(sa_thread, SVC_STOPPED);
1171         spin_unlock(&lli->lli_sa_lock);
1172
1173         CDEBUG(D_READA, "statahead thread stopped: sai %p, parent %pd\n",
1174                sai, parent);
1175
1176         wake_up(&sai->sai_waitq);
1177         wake_up(&sa_thread->t_ctl_waitq);
1178         ll_sai_put(sai);
1179
1180         return rc;
1181 }
1182
1183 /* authorize opened dir handle @key to statahead */
1184 void ll_authorize_statahead(struct inode *dir, void *key)
1185 {
1186         struct ll_inode_info *lli = ll_i2info(dir);
1187
1188         spin_lock(&lli->lli_sa_lock);
1189         if (!lli->lli_opendir_key && !lli->lli_sai) {
1190                 /*
1191                  * if lli_sai is not NULL, it means previous statahead is not
1192                  * finished yet, we'd better not start a new statahead for now.
1193                  */
1194                 LASSERT(!lli->lli_opendir_pid);
1195                 lli->lli_opendir_key = key;
1196                 lli->lli_opendir_pid = current_pid();
1197                 lli->lli_sa_enabled = 1;
1198         }
1199         spin_unlock(&lli->lli_sa_lock);
1200 }
1201
1202 /*
1203  * deauthorize opened dir handle @key to statahead, but statahead thread may
1204  * still be running, notify it to quit.
1205  */
1206 void ll_deauthorize_statahead(struct inode *dir, void *key)
1207 {
1208         struct ll_inode_info *lli = ll_i2info(dir);
1209         struct ll_statahead_info *sai;
1210
1211         LASSERT(lli->lli_opendir_key == key);
1212         LASSERT(lli->lli_opendir_pid);
1213
1214         CDEBUG(D_READA, "deauthorize statahead for " DFID "\n",
1215                PFID(&lli->lli_fid));
1216
1217         spin_lock(&lli->lli_sa_lock);
1218         lli->lli_opendir_key = NULL;
1219         lli->lli_opendir_pid = 0;
1220         lli->lli_sa_enabled = 0;
1221         sai = lli->lli_sai;
1222         if (sai && thread_is_running(&sai->sai_thread)) {
1223                 /*
1224                  * statahead thread may not quit yet because it needs to cache
1225                  * entries, now it's time to tell it to quit.
1226                  */
1227                 thread_set_flags(&sai->sai_thread, SVC_STOPPING);
1228                 wake_up(&sai->sai_thread.t_ctl_waitq);
1229         }
1230         spin_unlock(&lli->lli_sa_lock);
1231 }
1232
1233 enum {
1234         /**
1235          * not first dirent, or is "."
1236          */
1237         LS_NOT_FIRST_DE = 0,
1238         /**
1239          * the first non-hidden dirent
1240          */
1241         LS_FIRST_DE,
1242         /**
1243          * the first hidden dirent, that is "."
1244          */
1245         LS_FIRST_DOT_DE
1246 };
1247
1248 /* file is first dirent under @dir */
1249 static int is_first_dirent(struct inode *dir, struct dentry *dentry)
1250 {
1251         const struct qstr  *target = &dentry->d_name;
1252         struct md_op_data *op_data;
1253         struct page       *page;
1254         __u64            pos    = 0;
1255         int                dot_de;
1256         int rc = LS_NOT_FIRST_DE;
1257
1258         op_data = ll_prep_md_op_data(NULL, dir, dir, NULL, 0, 0,
1259                                      LUSTRE_OPC_ANY, dir);
1260         if (IS_ERR(op_data))
1261                 return PTR_ERR(op_data);
1262         /**
1263          * FIXME choose the start offset of the readdir
1264          */
1265         op_data->op_max_pages = ll_i2sbi(dir)->ll_md_brw_pages;
1266
1267         page = ll_get_dir_page(dir, op_data, pos);
1268
1269         while (1) {
1270                 struct lu_dirpage *dp;
1271                 struct lu_dirent  *ent;
1272
1273                 if (IS_ERR(page)) {
1274                         struct ll_inode_info *lli = ll_i2info(dir);
1275
1276                         rc = PTR_ERR(page);
1277                         CERROR("%s: error reading dir " DFID " at %llu: opendir_pid = %u : rc = %d\n",
1278                                ll_get_fsname(dir->i_sb, NULL, 0),
1279                                PFID(ll_inode2fid(dir)), pos,
1280                                lli->lli_opendir_pid, rc);
1281                         break;
1282                 }
1283
1284                 dp = page_address(page);
1285                 for (ent = lu_dirent_start(dp); ent;
1286                      ent = lu_dirent_next(ent)) {
1287                         __u64 hash;
1288                         int namelen;
1289                         char *name;
1290
1291                         hash = le64_to_cpu(ent->lde_hash);
1292                         /* The ll_get_dir_page() can return any page containing
1293                          * the given hash which may be not the start hash.
1294                          */
1295                         if (unlikely(hash < pos))
1296                                 continue;
1297
1298                         namelen = le16_to_cpu(ent->lde_namelen);
1299                         if (unlikely(namelen == 0))
1300                                 /*
1301                                  * skip dummy record.
1302                                  */
1303                                 continue;
1304
1305                         name = ent->lde_name;
1306                         if (name[0] == '.') {
1307                                 if (namelen == 1)
1308                                         /*
1309                                          * skip "."
1310                                          */
1311                                         continue;
1312                                 else if (name[1] == '.' && namelen == 2)
1313                                         /*
1314                                          * skip ".."
1315                                          */
1316                                         continue;
1317                                 else
1318                                         dot_de = 1;
1319                         } else {
1320                                 dot_de = 0;
1321                         }
1322
1323                         if (dot_de && target->name[0] != '.') {
1324                                 CDEBUG(D_READA, "%.*s skip hidden file %.*s\n",
1325                                        target->len, target->name,
1326                                        namelen, name);
1327                                 continue;
1328                         }
1329
1330                         if (target->len != namelen ||
1331                             memcmp(target->name, name, namelen) != 0)
1332                                 rc = LS_NOT_FIRST_DE;
1333                         else if (!dot_de)
1334                                 rc = LS_FIRST_DE;
1335                         else
1336                                 rc = LS_FIRST_DOT_DE;
1337
1338                         ll_release_page(dir, page, false);
1339                         goto out;
1340                 }
1341                 pos = le64_to_cpu(dp->ldp_hash_end);
1342                 if (pos == MDS_DIR_END_OFF) {
1343                         /*
1344                          * End of directory reached.
1345                          */
1346                         ll_release_page(dir, page, false);
1347                         goto out;
1348                 } else {
1349                         /*
1350                          * chain is exhausted
1351                          * Normal case: continue to the next page.
1352                          */
1353                         ll_release_page(dir, page,
1354                                         le32_to_cpu(dp->ldp_flags) &
1355                                         LDF_COLLIDE);
1356                         page = ll_get_dir_page(dir, op_data, pos);
1357                 }
1358         }
1359 out:
1360         ll_finish_md_op_data(op_data);
1361         return rc;
1362 }
1363
1364 /**
1365  * revalidate @dentryp from statahead cache
1366  *
1367  * \param[in]  dir      parent directory
1368  * \param[in]  sai      sai structure
1369  * \param[out] dentryp  pointer to dentry which will be revalidated
1370  * \param[in]  unplug   unplug statahead window only (normally for negative
1371  *                      dentry)
1372  * \retval              1 on success, dentry is saved in @dentryp
1373  * \retval              0 if revalidation failed (no proper lock on client)
1374  * \retval              negative number upon error
1375  */
1376 static int revalidate_statahead_dentry(struct inode *dir,
1377                                        struct ll_statahead_info *sai,
1378                                        struct dentry **dentryp,
1379                                        bool unplug)
1380 {
1381         struct ll_inode_info *lli = ll_i2info(dir);
1382         struct sa_entry *entry = NULL;
1383         struct l_wait_info lwi = { 0 };
1384         struct ll_dentry_data *ldd;
1385         int rc = 0;
1386
1387         if ((*dentryp)->d_name.name[0] == '.') {
1388                 if (sai->sai_ls_all ||
1389                     sai->sai_miss_hidden >= sai->sai_skip_hidden) {
1390                         /*
1391                          * Hidden dentry is the first one, or statahead
1392                          * thread does not skip so many hidden dentries
1393                          * before "sai_ls_all" enabled as below.
1394                          */
1395                 } else {
1396                         if (!sai->sai_ls_all)
1397                                 /*
1398                                  * It maybe because hidden dentry is not
1399                                  * the first one, "sai_ls_all" was not
1400                                  * set, then "ls -al" missed. Enable
1401                                  * "sai_ls_all" for such case.
1402                                  */
1403                                 sai->sai_ls_all = 1;
1404
1405                         /*
1406                          * Such "getattr" has been skipped before
1407                          * "sai_ls_all" enabled as above.
1408                          */
1409                         sai->sai_miss_hidden++;
1410                         return -EAGAIN;
1411                 }
1412         }
1413
1414         if (unplug) {
1415                 rc = 1;
1416                 goto out_unplug;
1417         }
1418
1419         entry = sa_get(sai, &(*dentryp)->d_name);
1420         if (!entry) {
1421                 rc = -EAGAIN;
1422                 goto out_unplug;
1423         }
1424
1425         /* if statahead is busy in readdir, help it do post-work */
1426         if (!sa_ready(entry) && sai->sai_in_readpage)
1427                 sa_handle_callback(sai);
1428
1429         if (!sa_ready(entry)) {
1430                 spin_lock(&lli->lli_sa_lock);
1431                 sai->sai_index_wait = entry->se_index;
1432                 spin_unlock(&lli->lli_sa_lock);
1433                 lwi = LWI_TIMEOUT_INTR(cfs_time_seconds(30), NULL,
1434                                        LWI_ON_SIGNAL_NOOP, NULL);
1435                 rc = l_wait_event(sai->sai_waitq, sa_ready(entry), &lwi);
1436                 if (rc < 0) {
1437                         /*
1438                          * entry may not be ready, so it may be used by inflight
1439                          * statahead RPC, don't free it.
1440                          */
1441                         entry = NULL;
1442                         rc = -EAGAIN;
1443                         goto out_unplug;
1444                 }
1445         }
1446
1447         if (entry->se_state == SA_ENTRY_SUCC && entry->se_inode) {
1448                 struct inode *inode = entry->se_inode;
1449                 struct lookup_intent it = { .it_op = IT_GETATTR,
1450                                             .it_lock_handle = entry->se_handle };
1451                 __u64 bits;
1452
1453                 rc = md_revalidate_lock(ll_i2mdexp(dir), &it,
1454                                         ll_inode2fid(inode), &bits);
1455                 if (rc == 1) {
1456                         if (!(*dentryp)->d_inode) {
1457                                 struct dentry *alias;
1458
1459                                 alias = ll_splice_alias(inode, *dentryp);
1460                                 if (IS_ERR(alias)) {
1461                                         ll_intent_release(&it);
1462                                         rc = PTR_ERR(alias);
1463                                         goto out_unplug;
1464                                 }
1465                                 *dentryp = alias;
1466                                 /**
1467                                  * statahead prepared this inode, transfer inode
1468                                  * refcount from sa_entry to dentry
1469                                  */
1470                                 entry->se_inode = NULL;
1471                         } else if ((*dentryp)->d_inode != inode) {
1472                                 /* revalidate, but inode is recreated */
1473                                 CDEBUG(D_READA,
1474                                        "%s: stale dentry %pd inode " DFID ", statahead inode " DFID "\n",
1475                                        ll_get_fsname((*dentryp)->d_inode->i_sb,
1476                                                      NULL, 0),
1477                                        *dentryp,
1478                                        PFID(ll_inode2fid((*dentryp)->d_inode)),
1479                                        PFID(ll_inode2fid(inode)));
1480                                 ll_intent_release(&it);
1481                                 rc = -ESTALE;
1482                                 goto out_unplug;
1483                         }
1484
1485                         if ((bits & MDS_INODELOCK_LOOKUP) &&
1486                             d_lustre_invalid(*dentryp))
1487                                 d_lustre_revalidate(*dentryp);
1488                         ll_intent_release(&it);
1489                 }
1490         }
1491 out_unplug:
1492         /*
1493          * statahead cached sa_entry can be used only once, and will be killed
1494          * right after use, so if lookup/revalidate accessed statahead cache,
1495          * set dentry ldd_sa_generation to parent lli_sa_generation, later if we
1496          * stat this file again, we know we've done statahead before, see
1497          * dentry_may_statahead().
1498          */
1499         ldd = ll_d2d(*dentryp);
1500         ldd->lld_sa_generation = lli->lli_sa_generation;
1501         sa_put(sai, entry);
1502         return rc;
1503 }
1504
1505 /**
1506  * start statahead thread
1507  *
1508  * \param[in] dir       parent directory
1509  * \param[in] dentry    dentry that triggers statahead, normally the first
1510  *                      dirent under @dir
1511  * \retval              -EAGAIN on success, because when this function is
1512  *                      called, it's already in lookup call, so client should
1513  *                      do it itself instead of waiting for statahead thread
1514  *                      to do it asynchronously.
1515  * \retval              negative number upon error
1516  */
1517 static int start_statahead_thread(struct inode *dir, struct dentry *dentry)
1518 {
1519         struct ll_inode_info *lli = ll_i2info(dir);
1520         struct ll_statahead_info *sai = NULL;
1521         struct l_wait_info lwi = { 0 };
1522         struct ptlrpc_thread *thread;
1523         struct task_struct *task;
1524         struct dentry *parent = dentry->d_parent;
1525         int rc;
1526
1527         /* I am the "lli_opendir_pid" owner, only me can set "lli_sai". */
1528         rc = is_first_dirent(dir, dentry);
1529         if (rc == LS_NOT_FIRST_DE) {
1530                 /* It is not "ls -{a}l" operation, no need statahead for it. */
1531                 rc = -EFAULT;
1532                 goto out;
1533         }
1534
1535         sai = ll_sai_alloc(parent);
1536         if (!sai) {
1537                 rc = -ENOMEM;
1538                 goto out;
1539         }
1540
1541         sai->sai_ls_all = (rc == LS_FIRST_DOT_DE);
1542         /*
1543          * if current lli_opendir_key was deauthorized, or dir re-opened by
1544          * another process, don't start statahead, otherwise the newly spawned
1545          * statahead thread won't be notified to quit.
1546          */
1547         spin_lock(&lli->lli_sa_lock);
1548         if (unlikely(lli->lli_sai || lli->lli_opendir_key ||
1549                      lli->lli_opendir_pid != current->pid)) {
1550                 spin_unlock(&lli->lli_sa_lock);
1551                 rc = -EPERM;
1552                 goto out;
1553         }
1554         lli->lli_sai = sai;
1555         spin_unlock(&lli->lli_sa_lock);
1556
1557         atomic_inc(&ll_i2sbi(parent->d_inode)->ll_sa_running);
1558
1559         CDEBUG(D_READA, "start statahead thread: [pid %d] [parent %pd]\n",
1560                current_pid(), parent);
1561
1562         task = kthread_run(ll_statahead_thread, parent, "ll_sa_%u",
1563                            lli->lli_opendir_pid);
1564         thread = &sai->sai_thread;
1565         if (IS_ERR(task)) {
1566                 rc = PTR_ERR(task);
1567                 CERROR("can't start ll_sa thread, rc : %d\n", rc);
1568                 goto out;
1569         }
1570
1571         l_wait_event(thread->t_ctl_waitq,
1572                      thread_is_running(thread) || thread_is_stopped(thread),
1573                      &lwi);
1574         ll_sai_put(sai);
1575
1576         /*
1577          * We don't stat-ahead for the first dirent since we are already in
1578          * lookup.
1579          */
1580         return -EAGAIN;
1581
1582 out:
1583         /*
1584          * once we start statahead thread failed, disable statahead so
1585          * that subsequent stat won't waste time to try it.
1586          */
1587         spin_lock(&lli->lli_sa_lock);
1588         lli->lli_sa_enabled = 0;
1589         lli->lli_sai = NULL;
1590         spin_unlock(&lli->lli_sa_lock);
1591         if (sai)
1592                 ll_sai_free(sai);
1593         return rc;
1594 }
1595
1596 /**
1597  * statahead entry function, this is called when client getattr on a file, it
1598  * will start statahead thread if this is the first dir entry, else revalidate
1599  * dentry from statahead cache.
1600  *
1601  * \param[in]  dir      parent directory
1602  * \param[out] dentryp  dentry to getattr
1603  * \param[in]  unplug   unplug statahead window only (normally for negative
1604  *                      dentry)
1605  * \retval              1 on success
1606  * \retval              0 revalidation from statahead cache failed, caller needs
1607  *                      to getattr from server directly
1608  * \retval              negative number on error, caller often ignores this and
1609  *                      then getattr from server
1610  */
1611 int ll_statahead(struct inode *dir, struct dentry **dentryp, bool unplug)
1612 {
1613         struct ll_statahead_info *sai;
1614
1615         sai = ll_sai_get(dir);
1616         if (sai) {
1617                 int rc;
1618
1619                 rc = revalidate_statahead_dentry(dir, sai, dentryp, unplug);
1620                 CDEBUG(D_READA, "revalidate statahead %pd: %d.\n",
1621                        *dentryp, rc);
1622                 ll_sai_put(sai);
1623                 return rc;
1624         }
1625         return start_statahead_thread(dir, *dentryp);
1626 }