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