-
Notifications
You must be signed in to change notification settings - Fork 174
Expand file tree
/
Copy pathcortex_m.zig
More file actions
1209 lines (1079 loc) · 43.3 KB
/
cortex_m.zig
File metadata and controls
1209 lines (1079 loc) · 43.3 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
const std = @import("std");
const builtin = @import("builtin");
const microzig = @import("microzig");
const mmio = microzig.mmio;
const app = microzig.app;
const shared = @import("cortex_m/shared_types.zig");
const VectorTable = microzig.chip.VectorTable;
const Core = enum {
cortex_m0,
cortex_m0plus,
cortex_m3,
cortex_m33,
cortex_m4,
cortex_m55,
cortex_m7,
};
const cortex_m = std.meta.stringToEnum(Core, microzig.config.cpu_name) orelse
@compileError(std.fmt.comptimePrint("Unrecognized Cortex-M core name: {s}", .{microzig.config.cpu_name}));
/// Segger's RTT support
pub const rtt = @import("rtt");
/// Complete list of interrupt values based on the chip's `interrupts` array.
pub const Interrupt = microzig.utilities.GenerateInterruptEnum(i32);
/// Used to set interrupt handlers.
pub const Handler = microzig.interrupt.Handler;
/// Allowable `interrupt` options for microzig.options.
pub const InterruptOptions = microzig.utilities.GenerateInterruptOptions(&.{
.{ .InterruptEnum = Interrupt, .HandlerFn = Handler },
});
/// Allowable `cpu` options for microzig.options.
pub const CPU_Options = struct {
/// If true, interrupt vectors are moved to RAM so handlers can be set at runtime.
///
/// NOTE: Not supported on cortex_m0.
ram_vector_table: bool = false,
/// If true, the Cortex-M interrupts will be initialized with a more verbose variant
/// of the interrupt handlers which print the interrupt name.
///
/// NOTE: This option is enabled in debug builds by default.
verbose_unhandled_irq: bool = (builtin.mode == .Debug),
/// If true, the FPU will be enabled in the startup code.
///
/// NOTE: This option is enabled by default if hard float is enabled.
/// NOTE: Not supported on cortex_m0, cortex_m0plus and cortex_m3.
enable_fpu: bool = builtin.abi.float() == .hard,
};
/// External Interrupts
/// These are the interrupts generated by the NVIC.
pub const ExternalInterrupt = blk: {
// Note: The value of each field is the interrupt number (VTOR offset),
// not the offset into the whole vector table.
const vector_info = @typeInfo(Interrupt).@"enum";
const vector_fields = vector_info.fields;
var result_len: usize = 0;
for (vector_fields) |field| {
if (field.value >= 0) result_len += 1;
}
if (result_len == 0) break :blk enum {};
var field_names: [result_len][]const u8 = undefined;
var field_values: [result_len]u8 = undefined;
var field_index: usize = 0;
for (microzig.chip.interrupts) |intr| {
if (intr.index >= 0) {
field_names[field_index] = intr.name;
field_values[field_index] = intr.index;
field_index += 1;
}
}
break :blk @Enum(u8, .exhaustive, field_names, field_values);
};
/// Machine exceptions.
pub const Exception = blk: {
// Note: The value of each field is the index into the whole
// vector table, not the negative offset from VTOR.
const vector_info = @typeInfo(Interrupt).@"enum";
const vector_fields = vector_info.fields;
var result_len: usize = 0;
for (vector_fields) |field| {
if (field.value < 0) result_len += 1;
}
if (result_len == 0) break :blk enum {};
var field_names: [result_len][]const u8 = undefined;
var field_values: [result_len]u4 = undefined;
var field_index: usize = 0;
for (microzig.chip.interrupts) |intr| {
if (intr.index < 0) {
field_names[field_index] = intr.name;
field_values[field_index] = 16 + intr.index; // Cortex-M exceptions are mapped to vector table slots 0 - 15
field_index += 1;
}
}
break :blk @Enum(u4, .exhaustive, field_names, field_values);
};
pub const interrupt = struct {
/// The priority of an interrupt.
/// Cortex-M uses a reversed priority scheme so the lowest priority is 15 and the highest is 0.
///
/// Note: Some platforms may only use the most significant bits of the priority register.
pub const Priority = enum(u8) {
lowest = 15,
highest = 0,
_,
};
pub fn globally_enabled() bool {
var mrs: u32 = undefined;
asm volatile ("mrs %[mrs], 16"
: [mrs] "+r" (mrs),
);
return mrs & 0x1 == 0;
}
pub fn enable_interrupts() void {
asm volatile ("cpsie i");
}
pub fn disable_interrupts() void {
asm volatile ("cpsid i");
}
fn assert_not_exception(comptime int: Interrupt) void {
if (@intFromEnum(int) < 0) {
@compileError("expected interrupt, got exception: " ++ @tagName(int));
}
}
pub const exception = struct {
const ppb = switch (cortex_m) {
.cortex_m7 => microzig.chip.peripherals.SCB,
else => microzig.cpu.peripherals.ppb,
};
pub fn is_enabled(comptime excpt: Exception) bool {
switch (cortex_m) {
.cortex_m3, .cortex_m4, .cortex_m7 => {
const raw = ppb.SHCSR.raw;
switch (excpt) {
.UsageFault => return (raw & 0x0004_0000) != 0,
.BusFault => return (raw & 0x0002_0000) != 0,
.MemManageFault => return (raw & 0x0001_0000) != 0,
else => @compileError("not supported on this platform"),
}
},
.cortex_m33,
.cortex_m55,
=> {
const raw = ppb.SHCSR.raw;
switch (excpt) {
.SecureFault => return (raw & 0x0008_0000) != 0,
.UsageFault => return (raw & 0x0004_0000) != 0,
.BusFault => return (raw & 0x0002_0000) != 0,
.MemManageFault => return (raw & 0x0001_0000) != 0,
else => @compileError("not supported on this platform"),
}
},
else => @compileError("not supported on this platform"),
}
}
pub fn enable(comptime excpt: Exception) void {
switch (cortex_m) {
.cortex_m3, .cortex_m4, .cortex_m7 => {
switch (excpt) {
.UsageFault => ppb.SHCSR.raw |= 0x0004_0000,
.BusFault => ppb.SHCSR.raw |= 0x0002_0000,
.MemManageFault => ppb.SHCSR.raw |= 0x0001_0000,
else => @compileError("not supported on this platform"),
}
},
.cortex_m33,
.cortex_m55,
=> {
switch (excpt) {
.SecureFault => ppb.SHCSR.raw |= 0x0008_0000,
.UsageFault => ppb.SHCSR.raw |= 0x0004_0000,
.BusFault => ppb.SHCSR.raw |= 0x0002_0000,
.MemManageFault => ppb.SHCSR.raw |= 0x0001_0000,
else => @compileError("not supported on this platform"),
}
},
else => @compileError("not supported on this platform"),
}
}
pub fn disable(comptime excpt: Exception) void {
switch (cortex_m) {
.cortex_m3, .cortex_m4, .cortex_m7 => {
switch (excpt) {
.UsageFault => ppb.SHCSR.raw &= ~@as(u32, 0x0004_0000),
.BusFault => ppb.SHCSR.raw &= ~@as(u32, 0x0002_0000),
.MemManageFault => ppb.SHCSR.raw &= ~@as(u32, 0x0001_0000),
else => @compileError("not supported on this platform"),
}
},
.cortex_m33,
.cortex_m55,
=> {
switch (excpt) {
.SecureFault => ppb.SHCSR.raw &= ~@as(u32, 0x0008_0000),
.UsageFault => ppb.SHCSR.raw &= ~@as(u32, 0x0004_0000),
.BusFault => ppb.SHCSR.raw &= ~@as(u32, 0x0002_0000),
.MemManageFault => ppb.SHCSR.raw &= ~@as(u32, 0x0001_0000),
else => @compileError("not supported on this platform"),
}
},
else => @compileError("not supported on this platform"),
}
}
pub fn is_pending(comptime excpt: Exception) bool {
switch (cortex_m) {
.cortex_m0plus,
=> {
if (excpt == .SVCALL) return (ppb.SHCSR.raw & 0x0000_8000) != 0;
@compileError("not supported on this platform");
},
.cortex_m3, .cortex_m4, .cortex_m7 => {
const raw = ppb.SHCSR.raw;
switch (excpt) {
.SVCall => return (raw & 0x0000_8000) != 0,
.BusFault => return (raw & 0x0000_4000) != 0,
.MemManageFault => return (raw & 0x0000_2000) != 0,
.UsageFault => return (raw & 0x0000_1000) != 0,
else => @compileError("not supported on this platform"),
}
},
.cortex_m33,
.cortex_m55,
=> {
const raw = ppb.SHCSR.raw;
switch (excpt) {
.HardFault => return (raw & 0x0020_0000) != 0,
.SecureFault => return (raw & 0x0010_0000) != 0,
.SVCall => return (raw & 0x0000_8000) != 0,
.BusFault => return (raw & 0x0000_4000) != 0,
.MemManageFault => return (raw & 0x0000_2000) != 0,
.UsageFault => return (raw & 0x0000_1000) != 0,
else => @compileError("not supported on this platform"),
}
},
else => @compileError("not supported on this platform"),
}
}
pub fn set_pending(comptime excpt: Exception) void {
switch (cortex_m) {
.cortex_m0plus,
=> {
if (excpt == .SVCALL) ppb.SHCSR.raw |= 0x0000_8000;
@compileError("not supported on this platform");
},
.cortex_m3, .cortex_m4, .cortex_m7 => {
switch (excpt) {
.SVCall => ppb.SHCSR.raw |= 0x0000_8000,
.BusFault => ppb.SHCSR.raw |= 0x0000_4000,
.MemManageFault => ppb.SHCSR.raw |= 0x0000_2000,
.UsageFault => ppb.SHCSR.raw |= 0x0000_1000,
else => @compileError("not supported on this platform"),
}
},
.cortex_m33,
.cortex_m55,
=> {
switch (excpt) {
.HardFault => ppb.SHCSR.raw |= 0x0020_0000,
.SecureFault => ppb.SHCSR.raw |= 0x0010_0000,
.SVCall => ppb.SHCSR.raw |= 0x0000_8000,
.BusFault => ppb.SHCSR.raw |= 0x0000_4000,
.MemManageFault => ppb.SHCSR.raw |= 0x0000_2000,
.UsageFault => ppb.SHCSR.raw |= 0x0000_1000,
else => @compileError("not supported on this platform"),
}
},
else => @compileError("not supported on this platform"),
}
}
pub fn clear_pending(comptime excpt: Exception) void {
switch (cortex_m) {
.cortex_m0plus,
=> {
if (excpt == .SVCALL) ppb.SHCSR.raw &= ~@as(u32, 0x0000_8000);
@compileError("not supported on this platform");
},
.cortex_m3, .cortex_m4, .cortex_m7 => {
switch (excpt) {
.SVCall => ppb.SHCSR.raw &= ~@as(u32, 0x0000_8000),
.BusFault => ppb.SHCSR.raw &= ~@as(u32, 0x0000_4000),
.MemManageFault => ppb.SHCSR.raw &= ~@as(u32, 0x0000_2000),
.UsageFault => ppb.SHCSR.raw &= ~@as(u32, 0x0000_1000),
else => @compileError("not supported on this platform"),
}
},
.cortex_m33,
.cortex_m55,
=> {
switch (excpt) {
.HardFault => ppb.SHCSR.raw &= ~@as(u32, 0x0020_0000),
.SecureFault => ppb.SHCSR.raw &= ~@as(u32, 0x0010_0000),
.SVCall => ppb.SHCSR.raw &= ~@as(u32, 0x0000_8000),
.BusFault => ppb.SHCSR.raw &= ~@as(u32, 0x0000_4000),
.MemManageFault => ppb.SHCSR.raw &= ~@as(u32, 0x0000_2000),
.UsageFault => ppb.SHCSR.raw &= ~@as(u32, 0x0000_1000),
else => @compileError("not supported on this platform"),
}
},
else => @compileError("not supported on this platform"),
}
}
/// Note: Although the Priority values are 0 - 15, some platforms may
/// only use the most significant bits.
pub fn set_priority(comptime excpt: Exception, priority: Priority) void {
const num: u2 = @intCast(@intFromEnum(excpt) / 4);
const shift: u5 = @as(u5, @intCast(@intFromEnum(excpt))) % 4 * 8;
// The code below is safe since the switch is compile-time resolved.
// The any SHPRn register which is unavailable on a platform will
// not be accessed as no matching `Exception` will be exist.
switch (num) {
0 => {
@compileError("Cannot set the priority for the exception");
},
1 => {
ppb.SHPR1.raw &= ~(@as(u32, 0xFF) << shift);
ppb.SHPR1.raw |= @as(u32, @intFromEnum(priority)) << shift;
},
2 => {
ppb.SHPR2.raw &= ~(@as(u32, 0xFF) << shift);
ppb.SHPR2.raw |= @as(u32, @intFromEnum(priority)) << shift;
},
3 => {
ppb.SHPR3.raw &= ~(@as(u32, 0xFF) << shift);
ppb.SHPR3.raw |= @as(u32, @intFromEnum(priority)) << shift;
},
}
}
pub fn get_priority(comptime excpt: Exception) Priority {
const num: u2 = @intCast(@intFromEnum(excpt) / 4);
const shift: u5 = @as(u5, @intCast(@intFromEnum(excpt))) % 4 * 8;
const raw: u8 = (switch (num) {
0 => @compileError("Cannot get the priority for the exception"),
1 => ppb.SHPR1.raw,
2 => ppb.SHPR2.raw,
3 => ppb.SHPR3.raw,
} >> shift) & 0xFF;
return @enumFromInt(raw);
}
};
const nvic = peripherals.nvic;
pub fn is_enabled(comptime int: ExternalInterrupt) bool {
const num: comptime_int = @intFromEnum(int);
switch (cortex_m) {
.cortex_m0,
.cortex_m0plus,
=> {
return nvic.ISER & (1 << num) != 0;
},
.cortex_m3,
.cortex_m33,
.cortex_m4,
.cortex_m55,
.cortex_m7,
=> {
const bank = num / 32;
const index = num % 32;
return nvic.ISER[bank] & (1 << index) != 0;
},
}
}
pub fn enable(comptime int: ExternalInterrupt) void {
const num: comptime_int = @intFromEnum(int);
switch (cortex_m) {
.cortex_m0,
.cortex_m0plus,
=> {
nvic.ISER |= 1 << num;
},
.cortex_m3,
.cortex_m33,
.cortex_m4,
.cortex_m55,
.cortex_m7,
=> {
const bank = num / 32;
const index = num % 32;
nvic.ISER[bank] |= 1 << index;
},
}
}
pub fn disable(comptime int: ExternalInterrupt) void {
const num: comptime_int = @intFromEnum(int);
switch (cortex_m) {
.cortex_m0,
.cortex_m0plus,
=> {
nvic.ICER |= 1 << num;
},
.cortex_m3,
.cortex_m33,
.cortex_m4,
.cortex_m55,
.cortex_m7,
=> {
const bank = num / 32;
const index = num % 32;
nvic.ICER[bank] |= 1 << index;
},
}
}
pub fn is_pending(comptime int: ExternalInterrupt) bool {
const num: comptime_int = @intFromEnum(int);
switch (cortex_m) {
.cortex_m0,
.cortex_m0plus,
=> {
return nvic.ISPR & (1 << num) != 0;
},
.cortex_m3,
.cortex_m33,
.cortex_m4,
.cortex_m55,
.cortex_m7,
=> {
const bank = num / 32;
const index = num % 32;
return nvic.ISPR[bank] & (1 << index) != 0;
},
}
}
pub fn set_pending(comptime int: ExternalInterrupt) void {
const num: comptime_int = @intFromEnum(int);
switch (cortex_m) {
.cortex_m0,
.cortex_m0plus,
=> {
nvic.ISPR |= 1 << num;
},
.cortex_m3,
.cortex_m33,
.cortex_m4,
.cortex_m55,
.cortex_m7,
=> {
const bank = num / 32;
const index = num % 32;
nvic.ISPR[bank] |= 1 << index;
},
}
}
pub fn clear_pending(comptime int: ExternalInterrupt) void {
const num: comptime_int = @intFromEnum(int);
switch (cortex_m) {
.cortex_m0,
.cortex_m0plus,
=> {
nvic.ICPR |= 1 << num;
},
.cortex_m3,
.cortex_m33,
.cortex_m4,
.cortex_m55,
.cortex_m7,
=> {
const bank = num / 32;
const index = num % 32;
nvic.ICPR[bank] |= 1 << index;
},
}
}
pub fn set_priority(comptime int: ExternalInterrupt, priority: Priority) void {
nvic.IPR[@intFromEnum(int)] = @intFromEnum(priority);
}
pub fn get_priority(comptime int: ExternalInterrupt) Priority {
return @enumFromInt(peripherals.nvic.IPR[@intFromEnum(int)]);
}
};
pub fn executing_isr() bool {
return peripherals.scb.ICSR.read().VECTACTIVE != 0;
}
pub fn enable_fault_irq() void {
asm volatile ("cpsie f");
}
pub fn disable_fault_irq() void {
asm volatile ("cpsid f");
}
pub fn nop() void {
asm volatile ("nop");
}
pub fn wfi() void {
asm volatile ("wfi");
}
pub fn wfe() void {
asm volatile ("wfe");
}
pub fn sev() void {
asm volatile ("sev");
}
pub fn isb() void {
asm volatile ("isb");
}
pub fn dsb() void {
asm volatile ("dsb");
}
pub fn dmb() void {
asm volatile ("dmb");
}
pub fn clrex() void {
asm volatile ("clrex");
}
/// Atomic operations with fallback to critical sections for Cortex-M0/M0+
pub const atomic = struct {
pub const has_native_atomics = switch (cortex_m) {
.cortex_m0, .cortex_m0plus => false,
else => true,
};
/// Atomic add
pub fn add(comptime T: type, ptr: *T, delta: T) T {
if (has_native_atomics) {
return @atomicRmw(T, ptr, .Add, delta, .monotonic);
} else {
const cs = microzig.interrupt.enter_critical_section();
defer cs.leave();
const old_value = ptr.*;
ptr.* = old_value +% delta;
return old_value;
}
}
/// Atomic load
pub fn load(comptime T: type, ptr: *const T, comptime ordering: std.builtin.AtomicOrder) T {
if (has_native_atomics) {
return @atomicLoad(T, ptr, ordering);
} else {
const cs = microzig.interrupt.enter_critical_section();
defer cs.leave();
return ptr.*;
}
}
/// Atomic store
pub fn store(comptime T: type, ptr: *T, value: T, comptime ordering: std.builtin.AtomicOrder) void {
if (has_native_atomics) {
@atomicStore(T, ptr, value, ordering);
} else {
const cs = microzig.interrupt.enter_critical_section();
defer cs.leave();
ptr.* = value;
}
}
/// Atomic compare and swap
pub fn cmpxchg(
comptime T: type,
ptr: *T,
expected_value: T,
new_value: T,
comptime success_ordering: std.builtin.AtomicOrder,
comptime failure_ordering: std.builtin.AtomicOrder,
) ?T {
if (has_native_atomics) {
return @cmpxchgWeak(T, ptr, expected_value, new_value, success_ordering, failure_ordering);
} else {
const cs = microzig.interrupt.enter_critical_section();
defer cs.leave();
const current = ptr.*;
if (current == expected_value) {
ptr.* = new_value;
return null;
}
return current;
}
}
/// Atomic read-modify-write
pub fn rmw(
comptime T: type,
ptr: *T,
comptime op: std.builtin.AtomicRmwOp,
operand: T,
comptime ordering: std.builtin.AtomicOrder,
) T {
if (has_native_atomics) {
return @atomicRmw(T, ptr, op, operand, ordering);
} else {
const cs = microzig.interrupt.enter_critical_section();
defer cs.leave();
const old_value = ptr.*;
ptr.* = switch (op) {
.Xchg => operand,
.Add => old_value +% operand,
.Sub => old_value -% operand,
.And => old_value & operand,
.Nand => ~(old_value & operand),
.Or => old_value | operand,
.Xor => old_value ^ operand,
.Max => @max(old_value, operand),
.Min => @min(old_value, operand),
};
return old_value;
}
}
};
/// Enables the FPU.
///
/// NOTE: This function is automatically called on cpu startup if the cpu has
/// an fpu and hard float is enabled. HALs also call this in the startup of
/// other cores.
pub inline fn enable_fpu() void {
switch (cortex_m) {
inline .cortex_m0,
.cortex_m0plus,
.cortex_m3,
=> |flavour| @compileError("FPU not supported on " ++ @tagName(flavour)),
else => {},
}
// Taken from the rust crate cortex-m-rt.
asm volatile (
\\ldr r0, =0xE000ED88
\\ldr r1, =(0b1111 << 20)
\\ldr r2, [r0]
\\orr r2, r2, r1
\\str r2, [r0]
\\dsb
\\isb
::: .{
.r0 = true,
.r1 = true,
.r2 = true,
.memory = true,
});
}
/// The RAM vector table used. You can swap interrupt handlers at runtime here.
/// Available when using a RAM vector table or a RAM image.
pub var ram_vector_table: VectorTable align(256) = if (using_ram_vector_table or is_ram_image)
startup_logic.generate_vector_table()
else
@compileError("`ram_vector_table` is not available. Consider adding .cpu = .{ .ram_vector_table = true }" ++
" to your microzig_options or using a RAM image");
pub const startup_logic = struct {
extern fn microzig_main() noreturn;
pub fn ram_image_start() linksection("microzig_ram_start") callconv(.naked) noreturn {
const eos = comptime microzig.utilities.get_end_of_stack();
asm volatile (
\\
// Set up stack and jump to _start
\\msr msp, %[eos]
// using bx instead of b because the _start function might be too far away
\\bx %[start_fn]
:
: [eos] "r" (@as(u32, @intFromPtr(eos))),
[start_fn] "r" (@as(u32, @intFromPtr(&_start))),
);
}
pub fn _start() callconv(.c) noreturn {
microzig.utilities.initialize_system_memories(.auto);
if (using_ram_vector_table or is_ram_image) {
switch (cortex_m) {
.cortex_m0 => @compileError("RAM image and RAM vector table are not supported on cortex_m0"),
else => {},
}
asm volatile (
\\
// Set VTOR to point to ram table
\\mov r0, %[_vector_table]
\\mov r1, %[_VTOR_ADDRESS]
\\str r0, [r1]
:
: [_vector_table] "r" (&ram_vector_table),
[_VTOR_ADDRESS] "r" (&peripherals.scb.VTOR),
: .{ .memory = true, .r0 = true, .r1 = true });
}
if (microzig.options.cpu.enable_fpu and has_fpu) {
enable_fpu();
} else if (microzig.options.cpu.enable_fpu and !has_fpu) {
@compileError(
\\FPU enable requested though the chip doesn't appear to have an FPU.
\\
++ fpu_error_helper_message);
}
if (@hasField(types.peripherals.SystemControlBlock, "SHCSR")) {
// Enable distinction between MemFault, BusFault and UsageFault:
peripherals.scb.SHCSR.modify(.{
.MEMFAULTENA = 1,
.BUSFAULTENA = 1,
.USGFAULTENA = 1,
});
enable_fault_irq();
}
// If the compiler gets too aggressive with inlining we might get some
// floating point operations before the FPU is enabled.
@call(.never_inline, microzig_main, .{});
}
// Validate that the VectorTable type has all the fault handlers that the CPU expects
comptime {
if (@hasDecl(core, "cpu_flags")) {
const flags = core.cpu_flags;
if ((flags.has_hard_fault and !@hasField(VectorTable, HardFault_name)) or
(flags.has_bus_fault and !@hasField(VectorTable, BusFault_name)) or
(flags.has_mem_manage_fault and !@hasField(VectorTable, MemManageFault_name)) or
(flags.has_usage_fault and !@hasField(VectorTable, UsageFault_name)))
@compileError("The CPU configures a fault vector, but it is not present in the VectorTable type!");
}
}
// If we are using a RAM vector table, we can use a dummy one (only 8 bytes) that only provides
// the reset vector and the initial stack pointer.
const FlashVectorTable = if (using_ram_vector_table)
extern struct {
initial_stack_pointer: usize,
Reset: Handler,
}
else
VectorTable;
// The vector table in flash must be aligned to 256 as VTOR ignores the lower 8 bits of the
// address.
const _vector_table: FlashVectorTable align(256) = if (is_ram_image) {
@compileError("`_vector_table` is not available in a RAM image. Use `ram_vector_table` instead.");
} else if (using_ram_vector_table)
.{
.initial_stack_pointer = microzig.config.end_of_stack.address orelse @panic("EndOfStack is not define"),
.Reset = .{ .c = microzig.cpu.startup_logic._start },
}
else
generate_vector_table();
fn generate_vector_table() VectorTable {
var tmp: VectorTable = .{
.initial_stack_pointer = microzig.utilities.get_end_of_stack(),
.Reset = .{ .c = microzig.cpu.startup_logic._start },
};
// Apply interrupts
for (@typeInfo(@TypeOf(microzig.options.interrupts)).@"struct".fields) |field| {
const maybe_handler = @field(microzig.options.interrupts, field.name);
const maybe_default = get_hal_default_handler(field.name);
@field(tmp, field.name) = blk: {
if (maybe_handler) |handler| {
if (!microzig.options.overwrite_hal_interrupts and maybe_default != null)
@compileError(std.fmt.comptimePrint(
\\Interrupt {s} is used internally by the HAL; overriding it may cause malfunction.
\\If you are sure of what you are doing, set "overwrite_hal_interrupts" to true in: "microzig_options".
\\
, .{field.name}));
break :blk handler;
} else break :blk maybe_default orelse default_exception_handler(field.name);
};
}
return tmp;
}
fn get_hal_default_handler(comptime handler_name: []const u8) ?microzig.interrupt.Handler {
if (microzig.config.has_hal) {
if (@hasDecl(microzig.hal, "default_interrupts")) {
return @field(microzig.hal.default_interrupts, handler_name);
}
}
return null;
}
fn default_exception_handler(comptime name: []const u8) microzig.interrupt.Handler {
return switch (builtin.mode) {
.Debug => .{ .c = DebugExceptionHandler(name).handle },
else => .{ .c = ReleaseExceptionHandler.handle },
};
}
fn DebugExceptionHandler(comptime name: []const u8) type {
if (microzig.options.cpu.verbose_unhandled_irq) {
return struct {
pub const handle = debug_exception_handler(name);
};
}
return ReleaseExceptionHandler;
}
const IrqHandlerFn = *const fn () callconv(.c) void;
fn debug_exception_handler(comptime name: []const u8) IrqHandlerFn {
// Only use verbose fault handlers on cores that have the required registers
const has_hfsr = @hasField(types.peripherals.SystemControlBlock, "HFSR");
const has_cfsr = @hasField(types.peripherals.SystemControlBlock, "CFSR");
if (comptime std.mem.eql(u8, name, HardFault_name) and has_hfsr)
return debug.hard_fault_handler;
if (comptime std.mem.eql(u8, name, BusFault_name) and has_cfsr)
return debug.bus_fault_handler;
if (comptime std.mem.eql(u8, name, MemManageFault_name))
return debug.mem_manage_fault_handler;
if (comptime std.mem.eql(u8, name, UsageFault_name) and has_cfsr)
return debug.usage_fault_handler;
return struct {
fn handle() callconv(.c) void {
@panic("Unhandled exception: " ++ name);
}
}.handle;
}
const ReleaseExceptionHandler = struct {
fn handle() callconv(.c) void {
@panic("Unhandled exception");
}
};
const HardFault_name = "HardFault";
const BusFault_name = "BusFault";
const MemManageFault_name = "MemManageFault";
const UsageFault_name = "UsageFault";
};
/// Implements several mechanisms to easy debugging with Cortex-M cpus.
///
/// Read more here:
/// https://interrupt.memfault.com/blog/cortex-m-hardfault-debug
pub const debug = struct {
const logger = std.log.scoped(.cortex_m_debug);
/// This frame is pushed mostly by the CPU itself, and we move it into
/// the parameter register, so we can inspect it.
pub const ContextStateFrame = extern struct {
r0: u32,
r1: u32,
r2: u32,
r3: u32,
r12: u32,
lr: u32,
return_address: u32,
xpsr: u32,
};
/// Wraps `handler` in a small asm block that ensures that it is a regular interrupt handler
/// function, but also provides us with a ContextStateFrame fetched from the system status:
pub fn make_fault_handler(comptime handler: *const fn (context: *ContextStateFrame) callconv(.c) void) *const fn () callconv(.c) void {
return struct {
fn invoke() callconv(.c) void {
// See this article on how we use that:
// https://interrupt.memfault.com/blog/cortex-m-hardfault-debug
asm volatile (
\\
// Check 2th bit of LR.
\\tst lr, #4
// Do "if then else" equal
\\ite eq
// if equals, we use the MSP
\\mrseq r0, msp
// otherwise, we use the PSP
\\mrsne r0, psp
// Then we branch to our handler:
\\b %[handler]
:
: [handler] "s" (handler),
);
}
}.invoke;
}
pub fn hard_fault_handler() callconv(.c) void {
const hfsr = peripherals.scb.HFSR.read();
logger.err("Hard Fault:", .{});
logger.err(" VECTTBL: {}", .{hfsr.VECTTBL});
logger.err(" FORCED: {}", .{hfsr.FORCED});
logger.err(" DEBUGEVT: {}", .{hfsr.DEBUGEVT});
@panic("Hard fault");
}
pub fn mem_manage_fault_handler() callconv(.c) void {
@panic("Memory fault");
}
pub const bus_fault_handler = make_fault_handler(handle_bus_fault_wrapped);
fn handle_bus_fault_wrapped(context: *const ContextStateFrame) callconv(.c) void {
const bfsr = peripherals.scb.CFSR.read().BFSR;
logger.err("Bus Fault:", .{});
logger.err(" context = r0:0x{X:0>8} r1:0x{X:0>8} r2:0x{X:0>8} r3:0x{X:0>8}", .{
context.r0,
context.r1,
context.r2,
context.r3,
});
logger.err(" r12:0x{X:0>8} lr:0x{X:0>8} ra:0x{X:0>8} xpsr:0x{X:0>8}", .{
context.r12,
context.lr,
context.return_address,
context.xpsr,
});
logger.err(" instruction bus error = {}", .{bfsr.instruction_bus_error});
logger.err(" precice data bus error = {}", .{bfsr.precice_data_bus_error});
logger.err(" imprecice data bus error = {}", .{bfsr.imprecice_data_bus_error});
logger.err(" unstacking exception error = {}", .{bfsr.unstacking_exception_error});
logger.err(" exception stacking error = {}", .{bfsr.exception_stacking_error});
if (has_fpu)
logger.err(" fpu lazy state preservation fault = {}", .{bfsr.fpu_lazy_state_preservation_fault});
logger.err(" busfault address register valid = {}", .{bfsr.busfault_address_register_valid});
if (bfsr.busfault_address_register_valid) {
const address = peripherals.scb.BFAR;
logger.err(" busfault address register = 0x{X:0>8}", .{address});
}
@panic("Bus fault");
}
pub const usage_fault_handler = make_fault_handler(handle_usage_fault_wrapped);
fn handle_usage_fault_wrapped(context: *const ContextStateFrame) callconv(.c) void {
const ufsr = peripherals.scb.CFSR.read().UFSR;
logger.err("Usage Fault:", .{});
logger.err(
" context = r0:0x{X:0>8} r1:0x{X:0>8} r2:0x{X:0>8} r3:0x{X:0>8}",
.{ context.r0, context.r1, context.r2, context.r3 },
);
logger.err(
" r12:0x{X:0>8} lr:0x{X:0>8} ra:0x{X:0>8} xpsr:0x{X:0>8}",
.{ context.r12, context.lr, context.return_address, context.xpsr },
);
logger.err(" undefined instruction = {}", .{ufsr.undefined_instruction});
logger.err(" invalid state = {}", .{ufsr.invalid_state});
logger.err(" invalid pc load = {}", .{ufsr.invalid_pc_load});
logger.err(" missing coprocessor usage = {}", .{ufsr.missing_coprocessor_usage});
logger.err(" unaligned memory access = {}", .{ufsr.unaligned_memory_access});
logger.err(" divide by zero = {}", .{ufsr.divide_by_zero});
@panic("Usage fault");
}
};
const is_ram_image = microzig.config.ram_image;
pub const using_ram_vector_table = @hasField(CPU_Options, "ram_vector_table") and microzig.options.cpu.ram_vector_table;
pub fn export_startup_logic() void {
if (is_ram_image) {
@export(&startup_logic.ram_image_start, .{
.name = "_entry_point",
.linkage = .strong,