-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkernel.cpp
More file actions
4687 lines (4090 loc) · 134 KB
/
kernel.cpp
File metadata and controls
4687 lines (4090 loc) · 134 KB
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
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
346
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
387
388
389
390
391
392
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <stddef.h>
#include <stdint.h>
extern "C" {
void *malloc(size_t size);
void free(void *ptr);
// Date/Time
struct Time {
uint8_t hour;
uint8_t minute;
uint8_t second;
};
Time get_time();
// C-String und Speicherfunktionen
int string_length(const char *str);
void string_copy(char *dest, const char *src);
bool string_compare(const char *s1, const char *s2);
void memset(void *ptr, uint8_t value, uint32_t size);
void memcpy(void *dest, const void *src, uint32_t size);
}
// Minimal heap implementation (for example only)
// Increased heap size for safety
static uint8_t kernel_heap[4 * 1024 * 1024]; // 4 MB heap
static size_t heap_top = 0;
extern "C" void *malloc(size_t size) {
if (heap_top + size >= sizeof(kernel_heap))
return nullptr;
void *ptr = &kernel_heap[heap_top];
heap_top += size;
return ptr;
}
extern "C" void free(void *) {
// no-op for now
}
// C++ operators
void *operator new(size_t size) { return malloc(size); }
void *operator new[](size_t size) { return malloc(size); }
void operator delete(void *p) noexcept { free(p); }
void operator delete[](void *p) noexcept { free(p); }
// Multiboot-Header-Struktur
struct multiboot_header {
uint32_t magic;
uint32_t flags;
uint32_t checksum;
// Padding/Address fields (must be present to reach offset 32 for graphics
// fields)
uint32_t header_addr;
uint32_t load_addr;
uint32_t load_end_addr;
uint32_t bss_end_addr;
uint32_t entry_addr;
// Graphics fields (Offset 32)
uint32_t mode_type;
uint32_t width;
uint32_t height;
uint32_t depth;
};
const uint32_t MULTIBOOT_MAGIC = 0x1BADB002;
// Flags: Modules aligned (1), Mem info (2), Graphics mode (4)
const uint32_t MULTIBOOT_FLAGS = 0x00000007;
const uint32_t MULTIBOOT_CHECKSUM = -(MULTIBOOT_MAGIC + MULTIBOOT_FLAGS);
__attribute__((section(".multiboot_header"))) struct multiboot_header header = {
.magic = MULTIBOOT_MAGIC,
.flags = MULTIBOOT_FLAGS,
.checksum = MULTIBOOT_CHECKSUM,
.header_addr = 0,
.load_addr = 0,
.load_end_addr = 0,
.bss_end_addr = 0,
.entry_addr = 0,
.mode_type = 0, // 0 = linear graphics mode
.width = 800,
.height = 600,
.depth = 32};
// VBE Info Structures
struct vbe_mode_info {
uint16_t attributes;
uint8_t win_a, win_b;
uint16_t granularity;
uint16_t winsize;
uint16_t segment_a, segment_b;
uint32_t win_funcptr;
uint16_t bytes_per_scanline;
uint16_t x_res, y_res;
uint8_t x_charsize, y_charsize, planes, bpp, banks;
uint8_t memory_model, bank_size, image_pages, reserved0;
uint8_t red_mask, red_position;
uint8_t green_mask, green_position;
uint8_t blue_mask, blue_position;
uint8_t reserved_mask, reserved_position;
uint8_t direct_color_attributes;
uint32_t framebuffer;
uint32_t off_screen_mem_off;
uint16_t off_screen_mem_size;
uint8_t reserved1[206];
} __attribute__((packed));
struct multiboot_info {
uint32_t flags;
uint32_t mem_lower;
uint32_t mem_upper;
uint32_t boot_device;
uint32_t cmdline;
uint32_t mods_count;
uint32_t mods_addr;
uint32_t syms[4];
uint32_t mmap_length;
uint32_t mmap_addr;
uint32_t drives_length;
uint32_t drives_addr;
uint32_t config_table;
uint32_t boot_loader_name;
uint32_t apm_table;
uint32_t vbe_control_info;
uint32_t vbe_mode_info;
uint16_t vbe_mode;
uint16_t vbe_interface_seg;
uint16_t vbe_interface_off;
uint16_t vbe_interface_len;
// Framebuffer info (Bit 12)
uint64_t framebuffer_addr;
uint32_t framebuffer_pitch;
uint32_t framebuffer_width;
uint32_t framebuffer_height;
uint8_t framebuffer_bpp;
uint8_t framebuffer_type;
uint8_t color_info[6];
} __attribute__((packed));
struct Graphics {
uint32_t *framebuffer;
uint32_t width;
uint32_t height;
uint32_t pitch;
bool active;
} screen;
extern "C" void put_pixel(int x, int y, uint32_t color) {
if (!screen.active || x < 0 || (uint32_t)x >= screen.width || y < 0 ||
(uint32_t)y >= screen.height)
return;
screen.framebuffer[y * (screen.pitch / 4) + x] = color;
}
uint32_t system_ram_mb = 0;
extern "C" uint32_t get_total_ram_mb() { return system_ram_mb; }
// ============================================================================
// I/O PORT FUNKTIONEN
// ============================================================================
extern "C" uint8_t inb(uint16_t port) {
uint8_t ret;
asm volatile("inb %1, %0" : "=a"(ret) : "Nd"(port));
return ret;
}
extern "C" uint16_t inw(uint16_t port) {
uint16_t ret;
asm volatile("inw %1, %0" : "=a"(ret) : "Nd"(port));
return ret;
}
extern "C" uint32_t inl(uint16_t port) {
uint32_t ret;
asm volatile("inl %1, %0" : "=a"(ret) : "Nd"(port));
return ret;
}
extern "C" void outb(uint16_t port, uint8_t val) {
asm volatile("outb %0, %1" : : "a"(val), "Nd"(port));
}
extern "C" void outw(uint16_t port, uint16_t val) {
asm volatile("outw %0, %1" : : "a"(val), "Nd"(port));
}
extern "C" void outl(uint16_t port, uint32_t val) {
asm volatile("outl %0, %1" : : "a"(val), "Nd"(port));
}
extern "C" void insl(uint16_t port, void *addr, uint32_t count) {
asm volatile("cld; rep insl"
: "+D"(addr), "+c"(count)
: "d"(port)
: "memory");
}
extern "C" void outsl(uint16_t port, const void *addr, uint32_t count) {
asm volatile("cld; rep outsl"
: "+S"(addr), "+c"(count)
: "d"(port)
: "memory");
}
// Verbesserte Delay-Funktion (wichtig!)
void delay(uint32_t count) {
for (volatile uint32_t i = 0; i < count * 1000000; ++i) {
asm volatile("nop");
}
}
// Kürzere Delay für I/O-Operationen
void io_wait() {
for (volatile int i = 0; i < 4; ++i) {
inb(0x80); // Port 0x80 für I/O-Delay
}
}
// ============================================================================
// GRUNDLEGENDE VGA FUNKTIONEN
// ============================================================================
void print_char(int row, int col, char character, uint16_t color) {
if (row < 0 || row >= 25 || col < 0 || col >= 80)
return;
uint16_t *video_memory = (uint16_t *)0xb8000;
int offset = row * 80 + col;
video_memory[offset] = (color << 8) | character;
}
void print_string(int row, int col, const char *str, uint16_t color);
// Debug Helper
void network_debug_print(const char *msg, int col) {
print_string(24, col, " ", 0x70); // Clear
print_string(24, col, msg, 0x74); // Red on Grey
}
void print_string(int row, int col, const char *str, uint16_t color) {
int i = 0;
while (str[i] != '\0') {
print_char(row, col + i, str[i], color);
i++;
}
}
void print_string_centered(int row, const char *str, uint16_t color) {
int len = string_length(str);
int col = (80 - len) / 2;
print_string(row, col, str, color);
}
// Forward declaration
void network_debug_print(const char *msg, int col);
void clear_screen(uint16_t color) {
uint16_t *video_memory = (uint16_t *)0xb8000;
for (int i = 0; i < 80 * 25; ++i) {
video_memory[i] = (color << 8) | ' ';
}
}
// ============================================================================
// MOUSE DRIVER & WALLPAPER
// ============================================================================
int mouse_x = 40;
int mouse_y = 12;
uint8_t mouse_cycle = 0;
int8_t mouse_byte[3];
bool mouse_left = false;
bool mouse_right = false;
bool mouse_middle = false;
bool show_wallpaper = false;
void mouse_wait(uint8_t type) {
uint32_t timeout = 100000;
if (type == 0) {
while (timeout--) {
if ((inb(0x64) & 1) == 1)
return;
}
} else {
while (timeout--) {
if ((inb(0x64) & 2) == 0)
return;
}
}
}
void mouse_write(uint8_t w) {
mouse_wait(1);
outb(0x64, 0xD4);
mouse_wait(1);
outb(0x60, w);
}
uint8_t mouse_read() {
mouse_wait(0);
return inb(0x60);
}
void init_mouse() {
mouse_wait(1);
outb(0x64, 0xA8);
mouse_wait(1);
outb(0x64, 0x20);
mouse_wait(0);
uint8_t status = inb(0x60) | 2;
mouse_wait(1);
outb(0x64, 0x60);
mouse_wait(1);
outb(0x60, status);
mouse_write(0xF6);
mouse_read();
mouse_write(0xF4);
mouse_read();
}
void handle_mouse_byte(uint8_t b) {
if (mouse_cycle == 0) {
if ((b & 0x08) == 0x08) {
mouse_byte[0] = b;
mouse_cycle++;
}
} else if (mouse_cycle == 1) {
mouse_byte[1] = b;
mouse_cycle++;
} else {
mouse_byte[2] = b;
mouse_cycle = 0;
mouse_left = mouse_byte[0] & 1;
mouse_right = mouse_byte[0] & 2;
mouse_middle = mouse_byte[0] & 4;
int dx = (int8_t)mouse_byte[1];
int dy = (int8_t)mouse_byte[2];
mouse_x += dx / 2; // Sensitivity div 2
mouse_y -= dy / 2; // Invert Y
if (screen.active) {
if (mouse_x < 0)
mouse_x = 0;
if ((uint32_t)mouse_x > screen.width - 1)
mouse_x = screen.width - 1;
if (mouse_y < 0)
mouse_y = 0;
if ((uint32_t)mouse_y > screen.height - 1)
mouse_y = screen.height - 1;
} else {
if (mouse_x < 0)
mouse_x = 0;
if (mouse_x > 79)
mouse_x = 79;
if (mouse_y < 0)
mouse_y = 0;
if (mouse_y > 24)
mouse_y = 24;
}
}
}
void draw_wallpaper_text() {
clear_screen(0x20); // Green bg
// Daisy Field Pattern
for (int y = 0; y < 25; y++) {
for (int x = 0; x < 80; x++) {
int seed = (x * 37 + y * 89);
if (seed % 17 == 0) {
print_char(y, x, 'o', 0x2E); // Yellow center
} else if ((seed % 17) >= 1 && (seed % 17) <= 4) {
print_char(y, x, '*', 0x2F); // White petals
}
}
}
}
// ============================================================================
// C-STRING UND SPEICHER FUNKTIONEN (JETZT EXTERN C)
// ============================================================================
extern "C" {
int string_length(const char *str) {
int len = 0;
while (str[len] != '\0')
len++;
return len;
}
void string_copy(char *dest, const char *src) {
int i = 0;
while (src[i] != '\0') {
dest[i] = src[i];
i++;
}
dest[i] = '\0';
}
bool string_compare(const char *s1, const char *s2) {
int i = 0;
while (s1[i] != '\0' && s2[i] != '\0') {
if (s1[i] != s2[i])
return false;
i++;
}
return s1[i] == s2[i];
}
void memset(void *ptr, uint8_t value, uint32_t size) {
uint8_t *p = (uint8_t *)ptr;
for (uint32_t i = 0; i < size; i++) {
p[i] = value;
}
}
void memcpy(void *dest, const void *src, uint32_t size) {
uint8_t *d = (uint8_t *)dest;
const uint8_t *s = (const uint8_t *)src;
for (uint32_t i = 0; i < size; i++) {
d[i] = s[i];
}
}
} // Ende extern "C"
const char *get_filename_ext(const char *filename) {
const char *dot = nullptr;
while (*filename) {
if (*filename == '.')
dot = filename;
filename++;
}
return dot ? dot + 1 : "";
}
// ============================================================================
// RTC (REAL TIME CLOCK)
// ============================================================================
uint8_t get_rtc_register(int reg) {
outb(0x70, reg);
return inb(0x71);
}
extern "C" Time get_time() {
Time t;
t.second = get_rtc_register(0x00);
t.minute = get_rtc_register(0x02);
t.hour = get_rtc_register(0x04);
// BCD conversion
t.second = (t.second & 0x0F) + ((t.second / 16) * 10);
t.minute = (t.minute & 0x0F) + ((t.minute / 16) * 10);
t.hour = ((t.hour & 0x0F) + ((t.hour & 0x70) / 16) * 10) | (t.hour & 0x80);
return t;
}
// ============================================================================
// NETWORK UTILS & ENDIANNESS
// ============================================================================
uint16_t htons(uint16_t v) { return (v << 8) | (v >> 8); }
uint16_t ntohs(uint16_t v) { return htons(v); }
uint32_t htonl(uint32_t v) {
return ((v & 0xFF) << 24) | ((v & 0xFF00) << 8) | ((v & 0xFF0000) >> 8) |
((v >> 24) & 0xFF);
}
uint32_t ntohl(uint32_t v) { return htonl(v); }
// ============================================================================
// NETWORK PROTOCOL HEADERS
// ============================================================================
struct MacAddress {
uint8_t addr[6];
};
struct EthernetHeader {
uint8_t dest[6];
uint8_t src[6];
uint16_t type;
} __attribute__((packed));
struct ARPHeader {
uint16_t hardware_type;
uint16_t protocol_type;
uint8_t hardware_addr_len;
uint8_t protocol_addr_len;
uint16_t opcode;
uint8_t src_mac[6];
uint32_t src_ip;
uint8_t dest_mac[6];
uint32_t dest_ip;
} __attribute__((packed));
struct IPv4Header {
uint8_t ihl : 4;
uint8_t version : 4;
uint8_t tos;
uint16_t length;
uint16_t id;
uint16_t frag_offset;
uint8_t ttl;
uint8_t protocol;
uint16_t checksum;
uint32_t src_ip;
uint32_t dest_ip;
} __attribute__((packed));
struct UDPHeader {
uint16_t src_port;
uint16_t dest_port;
uint16_t length;
uint16_t checksum;
} __attribute__((packed));
struct TCPHeader {
uint16_t src_port;
uint16_t dest_port;
uint32_t seq_num;
uint32_t ack_num;
uint8_t reserved : 4;
uint8_t data_offset : 4;
uint8_t flags;
uint16_t window_size;
uint16_t checksum;
uint16_t urgent_ptr;
} __attribute__((packed));
struct DNSHeader {
uint16_t id;
uint16_t flags;
uint16_t q_count;
uint16_t ans_count;
uint16_t auth_count;
uint16_t add_count;
} __attribute__((packed));
// Pseudo Header for Checksum calculation
struct PseudoHeader {
uint32_t src_ip;
uint32_t dest_ip;
uint8_t reserved;
uint8_t protocol;
uint16_t tcp_udp_length;
} __attribute__((packed));
// ============================================================================
// PCI & RTL8139 DRIVER
// ============================================================================
uint32_t pci_read_config(uint8_t bus, uint8_t slot, uint8_t func,
uint8_t offset) {
uint32_t address;
uint32_t lbus = (uint32_t)bus;
uint32_t lslot = (uint32_t)slot;
uint32_t lfunc = (uint32_t)func;
uint32_t tmp = 0;
address = (uint32_t)((lbus << 16) | (lslot << 11) | (lfunc << 8) |
(offset & 0xfc) | ((uint32_t)0x80000000));
outl(0xCF8, address);
tmp = (uint32_t)(inl(0xCFC));
return tmp;
}
void pci_write_config(uint8_t bus, uint8_t slot, uint8_t func, uint8_t offset,
uint32_t value) {
uint32_t address;
uint32_t lbus = (uint32_t)bus;
uint32_t lslot = (uint32_t)slot;
uint32_t lfunc = (uint32_t)func;
address = (uint32_t)((lbus << 16) | (lslot << 11) | (lfunc << 8) |
(offset & 0xfc) | ((uint32_t)0x80000000));
outl(0xCF8, address);
outl(0xCFC, value);
}
// RTL8139 Constants
#define RTL8139_VENDOR_ID 0x10EC
#define RTL8139_DEVICE_ID 0x8139
uint16_t rtl8139_io_base = 0;
uint8_t rtl8139_mac[6];
uint8_t *rtl8139_rx_buffer = nullptr;
uint32_t rx_buffer_offset = 0;
uint32_t packet_counter = 0;
uint32_t total_packets_sent = 0;
// TX Buffers
uint8_t *rtl8139_tx_buffers[4];
uint8_t tx_cur = 0;
void find_rtl8139() {
for (uint32_t bus = 0; bus < 256; bus++) {
for (uint32_t slot = 0; slot < 32; slot++) {
uint32_t vendor_device = pci_read_config(bus, slot, 0, 0);
if ((vendor_device & 0xFFFF) != 0xFFFF) {
uint16_t vendor = vendor_device & 0xFFFF;
uint16_t device = (vendor_device >> 16) & 0xFFFF;
if (vendor == RTL8139_VENDOR_ID && device == RTL8139_DEVICE_ID) {
// Found it! Get IO Base (BAR0)
uint32_t bar0 = pci_read_config(bus, slot, 0, 0x10);
rtl8139_io_base = bar0 & (~0x3);
// Enable Bus Mastering (Command Register offset 0x04)
uint32_t command = pci_read_config(bus, slot, 0, 0x04);
if (!(command & 0x04)) {
pci_write_config(bus, slot, 0, 0x04, command | 0x04);
print_string(24, 0, "RTL8139: Bus Mastering Enabled", 0x70);
} else {
print_string(24, 0, "RTL8139: Bus Mastering Already On", 0x70);
}
}
}
}
}
}
void rtl8139_send_packet(const void *data, uint32_t len) {
if (rtl8139_io_base == 0)
return;
// Use current TX buffer
memcpy(rtl8139_tx_buffers[tx_cur], data, len);
// Pad if smaller than 60 bytes (Ethernet min)
if (len < 60) {
memset(rtl8139_tx_buffers[tx_cur] + len, 0, 60 - len);
len = 60;
}
// Write Status (Size) | OWN bit gets cleared by controller later
// TSD0-3 are at 0x10, 0x14, 0x18, 0x1C
outl(rtl8139_io_base + 0x10 + (tx_cur * 4), len); // Write len triggers TX
network_debug_print("TX PKT", 40);
tx_cur = (tx_cur + 1) % 4;
total_packets_sent++;
}
namespace Network {
bool connected = false;
char status_msg[50] = "Searching...";
void init() {
find_rtl8139();
if (rtl8139_io_base != 0) {
connected = true;
string_copy(status_msg, "RTL8139 Init OK");
// Software Reset
outb(rtl8139_io_base + 0x37, 0x10);
while ((inb(rtl8139_io_base + 0x37) & 0x10) != 0) {
asm volatile("nop");
}
// Init RX Buffer
rtl8139_rx_buffer = (uint8_t *)malloc(8192 + 16 + 1500);
outl(rtl8139_io_base + 0x30, (uint32_t)rtl8139_rx_buffer); // RBSTART
// Init TX Buffers
for (int i = 0; i < 4; i++) {
rtl8139_tx_buffers[i] = (uint8_t *)malloc(1536); // Max MTU + padding
outl(rtl8139_io_base + 0x20 + (i * 4),
(uint32_t)rtl8139_tx_buffers[i]); // TSAD0-3
}
// Set IMR + ISR (Enable interrupts - though we poll for now)
outw(rtl8139_io_base + 0x3C, 0x0005); // TOK + ROK
outw(rtl8139_io_base + 0x44, 0x000F); // AB + AM + APM + AAP (Promiscuous)
// Enable RX/TX
outb(rtl8139_io_base + 0x37, 0x0C); // RE + TE
// Read MAC
for (int i = 0; i < 6; i++) {
rtl8139_mac[i] = inb(rtl8139_io_base + i);
}
} else {
string_copy(status_msg, "No NIC Found");
}
}
// ----------------------------------------------------------------------------
// ETHERNET & ARP LAYER
// ----------------------------------------------------------------------------
const uint16_t ETHERTYPE_IPv4 = 0x0800;
const uint16_t ETHERTYPE_ARP = 0x0806;
// Quick IP helper (10.0.2.15)
uint32_t my_ip =
0x0F02000A; // Little Endian representation of 10.0.2.15 (Reverse bytes)
// Actually, let's stick to Network Byte Order for structs: 10.0.2.15 ->
// 0x0A00020F BUT, x86 is Little Endian. If I write 0x0A00020F to memory, it
// becomes 0F 02 00 0A. So:
uint32_t ip_addr_host = 0x0A00020F; // 10.0.2.15
uint32_t gateway_ip = 0x0A000202; // 10.0.2.2 (QEMU default gateway)
// We need a way to set our IP if it's not hardcoded, but static is fine for
// now.
// ARP Cache
struct ArpEntry {
uint32_t ip;
uint8_t mac[6];
bool valid;
};
ArpEntry arp_cache[4];
void arp_update(uint32_t ip, const uint8_t *mac) {
for (int i = 0; i < 4; i++) {
if (arp_cache[i].valid && arp_cache[i].ip == ip) {
memcpy(arp_cache[i].mac, mac, 6);
return;
}
}
// Add new
for (int i = 0; i < 4; i++) {
if (!arp_cache[i].valid) {
arp_cache[i].ip = ip;
memcpy(arp_cache[i].mac, mac, 6);
arp_cache[i].valid = true;
return;
}
}
// Overwrite first
arp_cache[0].ip = ip;
memcpy(arp_cache[0].mac, mac, 6);
arp_cache[0].valid = true;
}
uint8_t *arp_resolve(uint32_t ip) {
for (int i = 0; i < 4; i++) {
if (arp_cache[i].valid && arp_cache[i].ip == ip)
return arp_cache[i].mac;
}
return nullptr;
}
void send_ethernet(const uint8_t *dest_mac, uint16_t type, const void *payload,
uint32_t len) {
uint32_t total_len = sizeof(EthernetHeader) + len;
uint8_t *buffer = (uint8_t *)malloc(total_len);
if (!buffer)
return;
EthernetHeader *eth = (EthernetHeader *)buffer;
memcpy(eth->dest, dest_mac, 6);
memcpy(eth->src, rtl8139_mac, 6);
eth->type = htons(type);
memcpy(buffer + sizeof(EthernetHeader), payload, len);
rtl8139_send_packet(buffer, total_len);
free(buffer);
}
void send_arp_request(uint32_t target_ip) {
ARPHeader arp;
arp.hardware_type = htons(1); // Ethernet
arp.protocol_type = htons(ETHERTYPE_IPv4);
arp.hardware_addr_len = 6;
arp.protocol_addr_len = 4;
arp.opcode = htons(1); // Request
memcpy(arp.src_mac, rtl8139_mac, 6);
arp.src_ip = htonl(ip_addr_host); // My IP
memset(arp.dest_mac, 0,
6); // Target MAC unknown (0) or Broadcast (FF)? ARP Request dest MAC
// in header is Broadcast, here is ignored/0.
arp.dest_ip = htonl(target_ip);
uint8_t broadcast[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
network_debug_print("TX ARP", 40);
send_ethernet(broadcast, ETHERTYPE_ARP, &arp, sizeof(ARPHeader));
}
void handle_arp(const uint8_t *data, uint32_t len) {
if (len < sizeof(ARPHeader))
return;
ARPHeader *arp = (ARPHeader *)data;
if (ntohs(arp->hardware_type) != 1 ||
ntohs(arp->protocol_type) != ETHERTYPE_IPv4)
return;
// Cache the sender
uint32_t sender_ip = ntohl(arp->src_ip);
arp_update(sender_ip, arp->src_mac);
network_debug_print("RX ARP", 60);
if (ntohs(arp->opcode) == 1 && ntohl(arp->dest_ip) == ip_addr_host) {
// ARP Request for me -> Reply
ARPHeader reply;
reply.hardware_type = htons(1);
reply.protocol_type = htons(ETHERTYPE_IPv4);
reply.hardware_addr_len = 6;
reply.protocol_addr_len = 4;
reply.opcode = htons(2); // Reply
memcpy(reply.src_mac, rtl8139_mac, 6);
reply.src_ip = arp->dest_ip;
memcpy(reply.dest_mac, arp->src_mac, 6);
reply.dest_ip = arp->src_ip;
send_ethernet(arp->src_mac, ETHERTYPE_ARP, &reply, sizeof(ARPHeader));
}
}
// Forward declarations
void poll(); // From Network namespace (later in file)
void handle_tcp(const uint8_t *data, uint32_t len, uint32_t src_ip,
uint32_t dest_ip);
// Enum for TCP State
enum TcpState { TCP_CLOSED, TCP_SYN_SENT, TCP_ESTABLISHED };
TcpState tcp_state = TCP_CLOSED;
uint32_t tcp_seq_num = 0;
uint32_t tcp_ack_num = 0;
uint32_t tcp_dest_ip = 0;
uint16_t tcp_dest_port = 0;
uint16_t tcp_src_port = 50000; // Static source port for now
// TCP RX Buffer
#define TCP_RX_BUFFER_SIZE 16384
uint8_t tcp_rx_buffer[TCP_RX_BUFFER_SIZE];
uint32_t tcp_rx_pos = 0;
uint16_t calculate_checksum(const void *data, uint32_t len) {
const uint16_t *ptr = (const uint16_t *)data;
uint32_t sum = 0;
while (len > 1) {
sum += *ptr++;
len -= 2;
}
if (len) {
sum += *(const uint8_t *)ptr;
}
while (sum >> 16) {
sum = (sum & 0xFFFF) + (sum >> 16);
}
return (uint16_t)~sum;
}
void send_ipv4(uint32_t dest_ip, uint8_t protocol, const void *payload,
uint32_t len) {
uint32_t total_len = sizeof(IPv4Header) + len;
uint8_t *buffer = (uint8_t *)malloc(total_len);
if (!buffer)
return;
IPv4Header *ip = (IPv4Header *)buffer;
ip->version = 4;
ip->ihl = 5;
ip->tos = 0;
ip->length = htons(total_len);
ip->id = htons(0); // TODO: Increment ID
ip->frag_offset = htons(0x4000); // Don't fragment
ip->ttl = 64;
ip->protocol = protocol;
ip->src_ip = htonl(ip_addr_host);
ip->dest_ip = htonl(dest_ip);
ip->checksum = 0;
ip->checksum = calculate_checksum(ip, sizeof(IPv4Header));
memcpy(buffer + sizeof(IPv4Header), payload, len);
// ARP Resolve
uint8_t *dest_mac = arp_resolve(dest_ip);
if (!dest_mac) {
send_arp_request(dest_ip);
free(buffer);
return;
}
send_ethernet(dest_mac, ETHERTYPE_IPv4, buffer, total_len);
free(buffer);
}
void tcp_send_packet(uint32_t dest_ip, uint16_t dest_port, uint8_t flags,
const uint8_t *payload, uint32_t len) {
uint32_t total_len = sizeof(TCPHeader) + len;
uint8_t *buffer = (uint8_t *)malloc(total_len);
if (!buffer)
return;
TCPHeader *tcp = (TCPHeader *)buffer;
tcp->src_port = htons(tcp_src_port);
tcp->dest_port = htons(dest_port);
tcp->seq_num = htonl(tcp_seq_num);
tcp->ack_num = htonl(tcp_ack_num);
tcp->reserved = 0;
tcp->data_offset = 5; // 5 * 32-bit words = 20 bytes
tcp->flags = flags;
tcp->window_size = htons(8192);
tcp->checksum = 0;
tcp->urgent_ptr = 0;
if (len > 0) {
memcpy(buffer + sizeof(TCPHeader), payload, len);
}
// Pseudo Header Checksum
PseudoHeader ph;
ph.src_ip = htonl(ip_addr_host);
ph.dest_ip = htonl(dest_ip);
ph.reserved = 0;
ph.protocol = 6; // TCP
ph.tcp_udp_length = htons(total_len);
uint32_t sum = 0;
// Manual sum of PseudoHeader to avoid packed pointer alignment issues
sum += (ph.src_ip & 0xFFFF);
sum += (ph.src_ip >> 16);
sum += (ph.dest_ip & 0xFFFF);
sum += (ph.dest_ip >> 16);
sum += htons(ph.protocol); // Protocol is 8-bit but in 16-bit word 0006
sum += ph.tcp_udp_length;
uint16_t *ptr = (uint16_t *)buffer;
for (int i = 0; i < total_len / 2; i++) {
sum += ptr[i];
}
if (total_len & 1) {
sum += buffer[total_len - 1] & 0xFF;
}
while (sum >> 16)
sum = (sum & 0xFFFF) + (sum >> 16);
tcp->checksum = ~sum;
send_ipv4(dest_ip, 6, buffer, total_len);
free(buffer);
// Increment Sequence Number if SYN or FIN or Data
if ((flags & 0x02) || (flags & 0x01) || len > 0) { // SYN or FIN or payload
tcp_seq_num += (len > 0 ? len : 1);
}
}
void handle_tcp(const uint8_t *data, uint32_t len, uint32_t src_ip,
uint32_t dest_ip) {
if (len < sizeof(TCPHeader))
return;
TCPHeader *tcp = (TCPHeader *)data;
// Very basic check logic
if (ntohs(tcp->dest_port) != tcp_src_port) {
network_debug_print("TCP PORT DROP", 60);
return;
}
uint32_t seq = ntohl(tcp->seq_num);
uint32_t ack = ntohl(tcp->ack_num);
uint8_t flags = tcp->flags;
// Calculate Payload
uint8_t offset = tcp->data_offset * 4;
uint32_t payload_len = len - offset;
const uint8_t *payload = data + offset;
if (tcp_state == TCP_SYN_SENT) {
if ((flags & 0x12) == 0x12) { // SYN + ACK
network_debug_print("RX SYN-ACK", 60);
tcp_ack_num = seq + 1;
tcp_seq_num = ack; // Server ACKed our SYN
tcp_state = TCP_ESTABLISHED;
// Send ACK
tcp_send_packet(src_ip, ntohs(tcp->src_port), 0x10, nullptr, 0); // ACK
}
} else if (tcp_state == TCP_ESTABLISHED) {
// Handle PUSH/DATA
if (payload_len > 0) {
// Store data
if (tcp_rx_pos + payload_len < TCP_RX_BUFFER_SIZE) {
memcpy(tcp_rx_buffer + tcp_rx_pos, payload, payload_len);
tcp_rx_pos += payload_len;
}
tcp_ack_num = seq + payload_len;
// Send ACK (Ack the data)
tcp_send_packet(src_ip, ntohs(tcp->src_port), 0x10, nullptr, 0); // ACK
// If PSH flag is set, maybe we should notify app?
// For now blocking poll handles it.
}
// Handle FIN