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