1 // Copyright 2016 The Fuchsia Authors
2 // Copyright (c) 2013 Travis Geiselbrecht
3 //
4 // Use of this source code is governed by a MIT-style
5 // license that can be found in the LICENSE file or at
6 // https://opensource.org/licenses/MIT
7
8 /*
9 * Global init hook mechanism. Allows code anywhere in the system to define
10 * a init hook that is called at increasing init levels as the system is
11 * initialized.
12 */
13 #include <arch/ops.h>
14 #include <lk/init.h>
15
16 #include <assert.h>
17 #include <debug.h>
18 #include <trace.h>
19 #include <zircon/compiler.h>
20
21 #define LOCAL_TRACE 0
22 #define TRACE_INIT (LK_DEBUGLEVEL >= 2)
23 #ifndef EARLIEST_TRACE_LEVEL
24 #define EARLIEST_TRACE_LEVEL LK_INIT_LEVEL_TARGET_EARLY
25 #endif
26
27 extern const struct lk_init_struct __start_lk_init[];
28 extern const struct lk_init_struct __stop_lk_init[];
29
lk_init_level(enum lk_init_flags required_flag,uint start_level,uint stop_level)30 void lk_init_level(enum lk_init_flags required_flag, uint start_level, uint stop_level) {
31 LTRACEF("flags %#x, start_level %#x, stop_level %#x\n",
32 (uint)required_flag, start_level, stop_level);
33
34 ASSERT(start_level > 0);
35 uint last_called_level = start_level - 1;
36 const struct lk_init_struct* last = NULL;
37 for (;;) {
38 /* search for the lowest uncalled hook to call */
39 LTRACEF("last %p, last_called_level %#x\n", last, last_called_level);
40
41 const struct lk_init_struct* found = NULL;
42 bool seen_last = false;
43 for (const struct lk_init_struct* ptr = __start_lk_init; ptr != __stop_lk_init; ptr++) {
44 LTRACEF("looking at %p (%s) level %#x, flags %#x, seen_last %d\n", ptr, ptr->name, ptr->level, ptr->flags, seen_last);
45
46 if (ptr == last)
47 seen_last = true;
48
49 /* reject the easy ones */
50 if (!(ptr->flags & required_flag))
51 continue;
52 if (ptr->level > stop_level)
53 continue;
54 if (ptr->level < last_called_level)
55 continue;
56 if (found && found->level <= ptr->level)
57 continue;
58
59 /* keep the lowest one we haven't called yet */
60 if (ptr->level >= start_level && ptr->level > last_called_level) {
61 found = ptr;
62 continue;
63 }
64
65 /* if we're at the same level as the last one we called and we've
66 * already passed over it this time around, we can mark this one
67 * and early terminate the loop.
68 */
69 if (ptr->level == last_called_level && ptr != last && seen_last) {
70 found = ptr;
71 break;
72 }
73 }
74
75 if (!found)
76 break;
77
78 if (TRACE_INIT) {
79 if (found->level >= EARLIEST_TRACE_LEVEL) {
80 printf("INIT: cpu %u, calling hook %p (%s) at level %#x, flags %#x\n",
81 arch_curr_cpu_num(), found->hook, found->name, found->level, found->flags);
82 }
83 }
84
85 found->hook(found->level);
86 last_called_level = found->level;
87 last = found;
88 }
89 }
90