k-hardware.cc 12.3 KB
Newer Older
Eddie Kohler's avatar
Eddie Kohler committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include "kernel.hh"
#include "k-apic.hh"
#include "k-devices.hh"
#include "k-pci.hh"
#include "k-vmiter.hh"
#include "elf.h"


// k-hardware.cc
//
//    Functions for interacting with x86 hardware.

pcistate pcistate::state;


// kalloc_pagetable
Eddie Kohler's avatar
Eddie Kohler committed
17
18
19
//    Allocate, initialize, and return a new, empty page table. Memory is
//    allocated using `kalloc()`. The page table's high memory is copied
//    from `early_pagetable`.
Eddie Kohler's avatar
Eddie Kohler committed
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

x86_64_pagetable* kalloc_pagetable() {
    x86_64_pagetable* pt = knew<x86_64_pagetable>();
    if (pt) {
        memset(&pt->entry[0], 0, sizeof(x86_64_pageentry_t) * 256);
        memcpy(&pt->entry[256], &early_pagetable->entry[256],
               sizeof(x86_64_pageentry_t) * 256);
    }
    return pt;
}


// set_pagetable(pagetable)
//    Change page table using wrcr3(), a hardware instruction. set_pagetable()
//    additionally checks that important kernel procedures are mapped in the
//    new page table, and calls panic() if they aren't.

void set_pagetable(x86_64_pagetable* pagetable) {
Eddie Kohler's avatar
Eddie Kohler committed
38
    assert(pagetable != nullptr);          // must not be nullptr
Eddie Kohler's avatar
Eddie Kohler committed
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
    assert(vmiter(pagetable, HIGHMEM_BASE).pa() == 0);
    assert(vmiter(pagetable, HIGHMEM_BASE).writable());
    assert(!vmiter(pagetable, HIGHMEM_BASE).user());
    assert(vmiter(pagetable, KTEXT_BASE).pa() == 0);
    assert(vmiter(pagetable, KTEXT_BASE).writable());
    assert(!vmiter(pagetable, KTEXT_BASE).user());
    auto pa = is_ktext(pagetable) ? ktext2pa(pagetable) : ka2pa(pagetable);
    wrcr3(pa);
}


// pcistate::next(addr)
//    Return the next valid PCI function after `addr`, or -1 if there
//    is none.
int pcistate::next(int addr) const {
    uint32_t x = readl(addr + config_lthb);
    while (true) {
        if (addr_func(addr) == 0
            && (x == uint32_t(-1) || !(x & 0x800000))) {
            addr += make_addr(0, 1, 0);
        } else {
            addr += make_addr(0, 0, 1);
        }
        if (addr >= addr_end) {
            return -1;
        }
        x = readl(addr + config_lthb);
        if (x != uint32_t(-1)) {
            return addr;
        }
    }
}

void pcistate::enable(int addr) {
    // enable I/O (0x01), memory (0x02), and bus master (0x04)
    writew(addr + config_command, 0x0007);
}


// poweroff
//    Turn off the virtual machine. This requires finding a PCI device
//    that speaks ACPI.

void poweroff() {
    auto& pci = pcistate::get();
    int addr = pci.find([&] (int a) {
            uint32_t vd = pci.readl(a + pci.config_vendor);
            return vd == 0x71138086U /* PIIX4 Power Management Controller */
                || vd == 0x29188086U /* ICH9 LPC Interface Controller */;
        });
    if (addr >= 0) {
        // Read I/O base register from controller's PCI configuration space.
        int pm_io_base = pci.readl(addr + 0x40) & 0xFFC0;
        // Write `suspend enable` to the power management control register.
        outw(pm_io_base + 4, 0x2000);
    }
    // No known ACPI controller; spin.
    console_printf(CPOS(24, 0), 0xC000, "Cannot power off!\n");
    while (true) {
    }
}


// reboot
//    Reboot the virtual machine.

void reboot() {
    outb(0x92, 3); // does not return
    while (true) {
    }
}


// process_halt
//    Called when the last user process exits. This will turn off the virtual
//    machine if `HALT=1` was specified during kernel build.

void process_halt() {
Eddie Kohler's avatar
Eddie Kohler committed
117
    // change keyboard state, hide cursor
Eddie Kohler's avatar
Eddie Kohler committed
118
119
    auto& kbd = keyboardstate::get();
    kbd.state_ = keyboardstate::boot;
Eddie Kohler's avatar
Eddie Kohler committed
120
121
    consolestate::get().cursor(false);
    // maybe halt machine
Eddie Kohler's avatar
Eddie Kohler committed
122
123
124
    if (memfile::initfs_lookup(".halt") >= 0) {
        poweroff();
    }
Eddie Kohler's avatar
Eddie Kohler committed
125
    // otherwise yield forever
Eddie Kohler's avatar
Eddie Kohler committed
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
    while (true) {
        current()->yield();
    }
}


// log_printf, log_vprintf
//    Print debugging messages to the host's `log.txt` file. We run QEMU
//    so that messages written to the QEMU "parallel port" end up in `log.txt`.

#define IO_PARALLEL1_DATA       0x378
#define IO_PARALLEL1_STATUS     0x379
# define IO_PARALLEL_STATUS_BUSY        0x80
#define IO_PARALLEL1_CONTROL    0x37A
# define IO_PARALLEL_CONTROL_SELECT     0x08
# define IO_PARALLEL_CONTROL_INIT       0x04
# define IO_PARALLEL_CONTROL_STROBE     0x01

static void delay() {
    (void) inb(0x84);
    (void) inb(0x84);
    (void) inb(0x84);
    (void) inb(0x84);
}

static void parallel_port_putc(unsigned char c) {
    static int initialized;
    if (!initialized) {
        outb(IO_PARALLEL1_CONTROL, 0);
        initialized = 1;
    }

    for (int i = 0;
         i < 12800 && (inb(IO_PARALLEL1_STATUS) & IO_PARALLEL_STATUS_BUSY) == 0;
         ++i) {
        delay();
    }
    outb(IO_PARALLEL1_DATA, c);
    outb(IO_PARALLEL1_CONTROL, IO_PARALLEL_CONTROL_SELECT
         | IO_PARALLEL_CONTROL_INIT | IO_PARALLEL_CONTROL_STROBE);
    outb(IO_PARALLEL1_CONTROL, IO_PARALLEL_CONTROL_SELECT
         | IO_PARALLEL_CONTROL_INIT);
}

namespace {
struct log_printer : public printer {
    void putc(unsigned char c, int) override {
        parallel_port_putc(c);
    }
};
}

James Foster's avatar
James Foster committed
178
179
180
// things get ugly when multiple processes output at the same time!
static spinlock printLock;

Eddie Kohler's avatar
Eddie Kohler committed
181
void log_vprintf(const char* format, va_list val) {
James Foster's avatar
James Foster committed
182
    spinlock_guard guard(printLock);
Eddie Kohler's avatar
Eddie Kohler committed
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
    log_printer p;
    p.vprintf(0, format, val);
}

void log_printf(const char* format, ...) {
    va_list val;
    va_start(val, format);
    log_vprintf(format, val);
    va_end(val);
}


// lookup_symbol(addr, name, start)
//    Use the debugging symbol table to look up `addr`. Return the
//    corresponding symbol name (usually a function name) in `*name`
//    and the first address in that symbol in `*start`.

__no_asan
bool lookup_symbol(uintptr_t addr, const char** name, uintptr_t* start) {
    extern elf_symtabref symtab;
    size_t l = 0;
    size_t r = symtab.nsym;
    while (l < r) {
        size_t m = l + ((r - l) >> 1);
        auto& sym = symtab.sym[m];
        if (sym.st_value <= addr
            && (m + 1 == symtab.nsym || addr < (&sym)[1].st_value)
            && (sym.st_size == 0 || addr <= sym.st_value + sym.st_size)) {
            if (!sym.st_value) {
                return false;
            }
            if (name) {
                *name = symtab.strtab + sym.st_name;
            }
            if (start) {
                *start = sym.st_value;
            }
            return true;
        } else if (sym.st_value < addr) {
            l = m + 1;
        } else {
            r = m;
        }
    }
    return false;
}


namespace {
struct backtracer {
    backtracer(uintptr_t rbp, uintptr_t rsp, uintptr_t stack_top)
        : rbp_(rbp), rsp_(rsp), stack_top_(stack_top) {
Eddie Kohler's avatar
Eddie Kohler committed
235
236
        pt_ = pa2kptr<x86_64_pagetable*>(rdcr3());
        check();
Eddie Kohler's avatar
Eddie Kohler committed
237
238
    }
    bool ok() const {
Eddie Kohler's avatar
Eddie Kohler committed
239
        return rsp_ != 0;
Eddie Kohler's avatar
Eddie Kohler committed
240
241
242
243
244
245
246
247
248
    }
    uintptr_t ret_rip() const {
        uintptr_t* rbpx = reinterpret_cast<uintptr_t*>(rbp_);
        return rbpx[1];
    }
    void step() {
        uintptr_t* rbpx = reinterpret_cast<uintptr_t*>(rbp_);
        rsp_ = rbp_ + 16;
        rbp_ = rbpx[0];
Eddie Kohler's avatar
Eddie Kohler committed
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
        check();
    }

private:
    uintptr_t rbp_;
    uintptr_t rsp_;
    uintptr_t stack_top_;
    x86_64_pagetable* pt_;

    void check() {
        if (rbp_ < rsp_
            || stack_top_ - rbp_ < 16
            || ((vmiter(pt_, rbp_).range_perm(16)) & PTE_P) == 0) {
            rbp_ = rsp_ = 0;
        }
Eddie Kohler's avatar
Eddie Kohler committed
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
    }
};
}

// log_backtrace(prefix[, rsp, rbp])
//    Print a backtrace to `log.txt`, each line prefixed by `prefix`.

void log_backtrace(const char* prefix) {
    log_backtrace(prefix, rdrsp(), rdrbp());
}

void log_backtrace(const char* prefix, uintptr_t rsp, uintptr_t rbp) {
    if (rsp != rbp && round_up(rsp, PAGESIZE) == round_down(rbp, PAGESIZE)) {
        log_printf("%s  warning: possible stack overflow (rsp %p, rbp %p)\n",
                   rsp, rbp);
    }
    int frame = 1;
    for (backtracer bt(rbp, rsp, round_up(rsp, PAGESIZE));
         bt.ok();
         bt.step(), ++frame) {
        uintptr_t ret_rip = bt.ret_rip();
        const char* name;
        if (lookup_symbol(ret_rip, &name, nullptr)) {
            log_printf("%s  #%d  %p  <%s>\n", prefix, frame, ret_rip, name);
        } else if (ret_rip) {
            log_printf("%s  #%d  %p\n", prefix, frame, ret_rip);
        }
    }
}


Eddie Kohler's avatar
Eddie Kohler committed
295
// error_vprintf
Eddie Kohler's avatar
Eddie Kohler committed
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
//    Print debugging messages to the console and to the host's
//    `log.txt` file via `log_printf`.

__noinline
int error_vprintf(int cpos, int color, const char* format, va_list val) {
    va_list val2;
    __builtin_va_copy(val2, val);
    log_vprintf(format, val2);
    va_end(val2);
    return console_vprintf(cpos, color, format, val);
}


// fail
//    Loop until user presses Control-C, then poweroff.

[[noreturn]] void fail() {
    auto& kbd = keyboardstate::get();
    kbd.state_ = kbd.fail;
    while (true) {
        kbd.handle_interrupt();
    }
}


// panic, assert_fail
//    Use console_printf() to print a failure message and then wait for
//    control-C. Also write the failure message to the log.

std::atomic<bool> panicking;

static void error_print_backtrace(uintptr_t rsp, uintptr_t rbp) {
    int frame = 1;
    for (backtracer bt(rbp, rsp, round_up(rsp, PAGESIZE));
         bt.ok();
         bt.step(), ++frame) {
        uintptr_t ret_rip = bt.ret_rip();
        const char* name;
        if (lookup_symbol(ret_rip, &name, nullptr)) {
            error_printf("  #%d  %p  <%s>\n", frame, ret_rip, name);
        } else {
            error_printf("  #%d  %p\n", frame, ret_rip);
        }
    }
}

static void vpanic(uintptr_t rsp, uintptr_t rbp, uintptr_t rip,
                   const char* format, va_list val) {
    panicking = true;

Eddie Kohler's avatar
Eddie Kohler committed
346
    cursorpos = CPOS(24, 80);
Eddie Kohler's avatar
Eddie Kohler committed
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
    if (format) {
        // Print panic message to both the screen and the log
        error_printf(-1, COLOR_ERROR, "PANIC: ");
        error_vprintf(-1, COLOR_ERROR, format, val);
        if (CCOL(cursorpos)) {
            error_printf(-1, COLOR_ERROR, "\n");
        }
    } else {
        error_printf(-1, COLOR_ERROR, "PANIC");
        log_printf("\n");
    }

    if (rip) {
        const char* name;
        if (lookup_symbol(rip, &name, nullptr)) {
            error_printf("  #0  %p  <%s>\n", rip, name);
        } else {
            error_printf("  #0  %p\n", rip);
        }
    }
    error_print_backtrace(rsp, rbp);
}

void panic(const char* format, ...) {
    va_list val;
    va_start(val, format);
    vpanic(rdrsp(), rdrbp(), 0, format, val);
    va_end(val);
    fail();
}

void panic_at(uintptr_t rsp, uintptr_t rbp, uintptr_t rip,
              const char* format, ...) {
    va_list val;
    va_start(val, format);
    vpanic(rsp, rbp, rip, format, val);
    va_end(val);
    fail();
}

Eddie Kohler's avatar
Eddie Kohler committed
387
388
void assert_fail(const char* file, int line, const char* msg,
                 const char* description) {
Eddie Kohler's avatar
Eddie Kohler committed
389
    cursorpos = CPOS(23, 0);
Eddie Kohler's avatar
Eddie Kohler committed
390
391
392
    if (description) {
        error_printf("%s:%d: %s\n", file, line, description);
    }
Eddie Kohler's avatar
Eddie Kohler committed
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
    error_printf("%s:%d: kernel assertion '%s' failed\n", file, line, msg);
    error_print_backtrace(rdrsp(), rdrbp());
    fail();
}


// C++ ABI functions

namespace std {
const nothrow_t nothrow;
}

extern "C" {
// The __cxa_guard functions control the initialization of static variables.

// __cxa_guard_acquire(guard)
//    Return 0 if the static variables guarded by `*guard` are already
//    initialized. Otherwise lock `*guard` and return 1. The compiler
//    will initialize the statics, then call `__cxa_guard_release`.
int __cxa_guard_acquire(long long* arg) {
    std::atomic<char>* guard = reinterpret_cast<std::atomic<char>*>(arg);
    if (guard->load(std::memory_order_relaxed) == 2) {
        return 0;
    }
    while (true) {
        char old_value = guard->exchange(1);
        if (old_value == 2) {
            guard->exchange(2);
            return 0;
        } else if (old_value == 1) {
            pause();
        } else {
            return 1;
        }
    }
}

// __cxa_guard_release(guard)
//    Mark `guard` to indicate that the static variables it guards are
//    initialized.
void __cxa_guard_release(long long* arg) {
    std::atomic<char>* guard = reinterpret_cast<std::atomic<char>*>(arg);
    guard->store(2);
}

// __cxa_pure_virtual()
//    Used as a placeholder for pure virtual functions.
void __cxa_pure_virtual() {
James Foster's avatar
James Foster committed
441
442
    // Note that panic() will prouce a page fault if there is no console
    // (https://github.com/CS161/chickadee/issues/14)
Eddie Kohler's avatar
Eddie Kohler committed
443
444
445
446
447
448
449
450
451
452
    panic("pure virtual function called in kernel!\n");
}

// __dso_handle, __cxa_atexit
//    Used to destroy global objects at "program exit". We don't bother.
void* __dso_handle;
void __cxa_atexit(...) {
}

}