-
Notifications
You must be signed in to change notification settings - Fork 141
/
main.cpp
316 lines (260 loc) · 8.76 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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
117
118
119
120
121
122
123
124
125
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
178
179
180
181
182
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
/**
* @file main.cpp
*
* カーネル本体のプログラムを書いたファイル.
*/
#include <cstdint>
#include <cstddef>
#include <cstdio>
#include <numeric>
#include <vector>
#include "frame_buffer_config.hpp"
#include "memory_map.hpp"
#include "graphics.hpp"
#include "mouse.hpp"
#include "font.hpp"
#include "console.hpp"
#include "pci.hpp"
#include "logger.hpp"
#include "usb/memory.hpp"
#include "usb/device.hpp"
#include "usb/classdriver/mouse.hpp"
#include "usb/xhci/xhci.hpp"
#include "usb/xhci/trb.hpp"
#include "interrupt.hpp"
#include "asmfunc.h"
#include "queue.hpp"
#include "segment.hpp"
#include "paging.hpp"
#include "memory_manager.hpp"
#include "window.hpp"
#include "layer.hpp"
char pixel_writer_buf[sizeof(RGBResv8BitPerColorPixelWriter)];
PixelWriter* pixel_writer;
char console_buf[sizeof(Console)];
Console* console;
int printk(const char* format, ...) {
va_list ap;
int result;
char s[1024];
va_start(ap, format);
result = vsprintf(s, format, ap);
va_end(ap);
console->PutString(s);
return result;
}
char memory_manager_buf[sizeof(BitmapMemoryManager)];
BitmapMemoryManager* memory_manager;
// #@@range_begin(layermgr_mousehandler)
unsigned int mouse_layer_id;
void MouseObserver(int8_t displacement_x, int8_t displacement_y) {
layer_manager->MoveRelative(mouse_layer_id, {displacement_x, displacement_y});
layer_manager->Draw();
}
// #@@range_end(layermgr_mousehandler)
void SwitchEhci2Xhci(const pci::Device& xhc_dev) {
bool intel_ehc_exist = false;
for (int i = 0; i < pci::num_device; ++i) {
if (pci::devices[i].class_code.Match(0x0cu, 0x03u, 0x20u) /* EHCI */ &&
0x8086 == pci::ReadVendorId(pci::devices[i])) {
intel_ehc_exist = true;
break;
}
}
if (!intel_ehc_exist) {
return;
}
uint32_t superspeed_ports = pci::ReadConfReg(xhc_dev, 0xdc); // USB3PRM
pci::WriteConfReg(xhc_dev, 0xd8, superspeed_ports); // USB3_PSSEN
uint32_t ehci2xhci_ports = pci::ReadConfReg(xhc_dev, 0xd4); // XUSB2PRM
pci::WriteConfReg(xhc_dev, 0xd0, ehci2xhci_ports); // XUSB2PR
Log(kDebug, "SwitchEhci2Xhci: SS = %02, xHCI = %02x\n",
superspeed_ports, ehci2xhci_ports);
}
usb::xhci::Controller* xhc;
struct Message {
enum Type {
kInterruptXHCI,
} type;
};
ArrayQueue<Message>* main_queue;
__attribute__((interrupt))
void IntHandlerXHCI(InterruptFrame* frame) {
main_queue->Push(Message{Message::kInterruptXHCI});
NotifyEndOfInterrupt();
}
alignas(16) uint8_t kernel_main_stack[1024 * 1024];
extern "C" void KernelMainNewStack(
const FrameBufferConfig& frame_buffer_config_ref,
const MemoryMap& memory_map_ref) {
FrameBufferConfig frame_buffer_config{frame_buffer_config_ref};
MemoryMap memory_map{memory_map_ref};
switch (frame_buffer_config.pixel_format) {
case kPixelRGBResv8BitPerColor:
pixel_writer = new(pixel_writer_buf)
RGBResv8BitPerColorPixelWriter{frame_buffer_config};
break;
case kPixelBGRResv8BitPerColor:
pixel_writer = new(pixel_writer_buf)
BGRResv8BitPerColorPixelWriter{frame_buffer_config};
break;
}
// #@@range_begin(new_console)
DrawDesktop(*pixel_writer);
console = new(console_buf) Console{
kDesktopFGColor, kDesktopBGColor
};
console->SetWriter(pixel_writer);
printk("Welcome to MikanOS!\n");
SetLogLevel(kWarn);
// #@@range_end(new_console)
SetupSegments();
const uint16_t kernel_cs = 1 << 3;
const uint16_t kernel_ss = 2 << 3;
SetDSAll(0);
SetCSSS(kernel_cs, kernel_ss);
SetupIdentityPageTable();
::memory_manager = new(memory_manager_buf) BitmapMemoryManager;
const auto memory_map_base = reinterpret_cast<uintptr_t>(memory_map.buffer);
uintptr_t available_end = 0;
for (uintptr_t iter = memory_map_base;
iter < memory_map_base + memory_map.map_size;
iter += memory_map.descriptor_size) {
auto desc = reinterpret_cast<const MemoryDescriptor*>(iter);
if (available_end < desc->physical_start) {
memory_manager->MarkAllocated(
FrameID{available_end / kBytesPerFrame},
(desc->physical_start - available_end) / kBytesPerFrame);
}
const auto physical_end =
desc->physical_start + desc->number_of_pages * kUEFIPageSize;
if (IsAvailable(static_cast<MemoryType>(desc->type))) {
available_end = physical_end;
} else {
memory_manager->MarkAllocated(
FrameID{desc->physical_start / kBytesPerFrame},
desc->number_of_pages * kUEFIPageSize / kBytesPerFrame);
}
}
// #@@range_begin(initialize_heap)
memory_manager->SetMemoryRange(FrameID{1}, FrameID{available_end / kBytesPerFrame});
if (auto err = InitializeHeap(*memory_manager)) {
Log(kError, "failed to allocate pages: %s at %s:%d\n",
err.Name(), err.File(), err.Line());
exit(1);
}
// #@@range_end(initialize_heap)
std::array<Message, 32> main_queue_data;
ArrayQueue<Message> main_queue{main_queue_data};
::main_queue = &main_queue;
auto err = pci::ScanAllBus();
Log(kDebug, "ScanAllBus: %s\n", err.Name());
for (int i = 0; i < pci::num_device; ++i) {
const auto& dev = pci::devices[i];
auto vendor_id = pci::ReadVendorId(dev);
auto class_code = pci::ReadClassCode(dev.bus, dev.device, dev.function);
Log(kDebug, "%d.%d.%d: vend %04x, class %08x, head %02x\n",
dev.bus, dev.device, dev.function,
vendor_id, class_code, dev.header_type);
}
// Intel 製を優先して xHC を探す
pci::Device* xhc_dev = nullptr;
for (int i = 0; i < pci::num_device; ++i) {
if (pci::devices[i].class_code.Match(0x0cu, 0x03u, 0x30u)) {
xhc_dev = &pci::devices[i];
if (0x8086 == pci::ReadVendorId(*xhc_dev)) {
break;
}
}
}
if (xhc_dev) {
Log(kInfo, "xHC has been found: %d.%d.%d\n",
xhc_dev->bus, xhc_dev->device, xhc_dev->function);
}
SetIDTEntry(idt[InterruptVector::kXHCI], MakeIDTAttr(DescriptorType::kInterruptGate, 0),
reinterpret_cast<uint64_t>(IntHandlerXHCI), kernel_cs);
LoadIDT(sizeof(idt) - 1, reinterpret_cast<uintptr_t>(&idt[0]));
const uint8_t bsp_local_apic_id =
*reinterpret_cast<const uint32_t*>(0xfee00020) >> 24;
pci::ConfigureMSIFixedDestination(
*xhc_dev, bsp_local_apic_id,
pci::MSITriggerMode::kLevel, pci::MSIDeliveryMode::kFixed,
InterruptVector::kXHCI, 0);
const WithError<uint64_t> xhc_bar = pci::ReadBar(*xhc_dev, 0);
Log(kDebug, "ReadBar: %s\n", xhc_bar.error.Name());
const uint64_t xhc_mmio_base = xhc_bar.value & ~static_cast<uint64_t>(0xf);
Log(kDebug, "xHC mmio_base = %08lx\n", xhc_mmio_base);
usb::xhci::Controller xhc{xhc_mmio_base};
if (0x8086 == pci::ReadVendorId(*xhc_dev)) {
SwitchEhci2Xhci(*xhc_dev);
}
{
auto err = xhc.Initialize();
Log(kDebug, "xhc.Initialize: %s\n", err.Name());
}
Log(kInfo, "xHC starting\n");
xhc.Run();
::xhc = &xhc;
usb::HIDMouseDriver::default_observer = MouseObserver;
for (int i = 1; i <= xhc.MaxPorts(); ++i) {
auto port = xhc.PortAt(i);
Log(kDebug, "Port %d: IsConnected=%d\n", i, port.IsConnected());
if (port.IsConnected()) {
if (auto err = ConfigurePort(xhc, port)) {
Log(kError, "failed to configure port: %s at %s:%d\n",
err.Name(), err.File(), err.Line());
continue;
}
}
}
// #@@range_begin(main_window)
const int kFrameWidth = frame_buffer_config.horizontal_resolution;
const int kFrameHeight = frame_buffer_config.vertical_resolution;
auto bgwindow = std::make_shared<Window>(kFrameWidth, kFrameHeight);
auto bgwriter = bgwindow->Writer();
DrawDesktop(*bgwriter);
console->SetWriter(bgwriter);
auto mouse_window = std::make_shared<Window>(
kMouseCursorWidth, kMouseCursorHeight);
mouse_window->SetTransparentColor(kMouseTransparentColor);
DrawMouseCursor(mouse_window->Writer(), {0, 0});
layer_manager = new LayerManager;
layer_manager->SetWriter(pixel_writer);
auto bglayer_id = layer_manager->NewLayer()
.SetWindow(bgwindow)
.Move({0, 0})
.ID();
mouse_layer_id = layer_manager->NewLayer()
.SetWindow(mouse_window)
.Move({200, 200})
.ID();
layer_manager->UpDown(bglayer_id, 0);
layer_manager->UpDown(mouse_layer_id, 1);
layer_manager->Draw();
// #@@range_end(main_window)
while (true) {
__asm__("cli");
if (main_queue.Count() == 0) {
__asm__("sti\n\thlt");
continue;
}
Message msg = main_queue.Front();
main_queue.Pop();
__asm__("sti");
switch (msg.type) {
case Message::kInterruptXHCI:
while (xhc.PrimaryEventRing()->HasFront()) {
if (auto err = ProcessEvent(xhc)) {
Log(kError, "Error while ProcessEvent: %s at %s:%d\n",
err.Name(), err.File(), err.Line());
}
}
break;
default:
Log(kError, "Unknown message type: %d\n", msg.type);
}
}
}
extern "C" void __cxa_pure_virtual() {
while (1) __asm__("hlt");
}