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