probe-rs 0.32.0

A collection of on chip debugging tools to communicate with microchips.
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
//! Low level access to the Xtensa Debug Module (XDM).
use std::{
    fmt::Debug,
    time::{Duration, Instant},
};

use bitvec::{field::BitField, slice::BitSlice};

use crate::{
    architecture::xtensa::arch::instruction::{Instruction, InstructionEncoding},
    probe::{
        CommandResult, JtagAccess, JtagWriteCommand, JtagWriteData, ShiftDrCommand, ShiftDrData,
        queue::{BatchError, DeferredResultIndex, DeferredResultSet, Queue},
    },
};

use super::communication_interface::XtensaError;

const NARADR_OCDID: u8 = 0x40;
const NARADR_DCRSET: u8 = 0x43;
const NARADR_DCRCLR: u8 = 0x42;
const NARADR_DSR: u8 = 0x44;
const NARADR_DDR: u8 = 0x45;
const NARADR_DDREXEC: u8 = 0x46;
// DIR0 that also executes when written
const NARADR_DIR0EXEC: u8 = 0x47;
// Assume we only support 16-24b instructions for now
const NARADR_DIR0: u8 = 0x48;

#[derive(Clone, Copy, PartialEq, Debug)]
enum TapInstruction {
    Nar,
    Ndr,
    PowerControl,
    PowerStatus,
    Idcode,
}

impl TapInstruction {
    fn code(self) -> u32 {
        match self {
            TapInstruction::Nar => 0x1C,
            TapInstruction::Ndr => 0x1C,
            TapInstruction::PowerControl => 0x08,
            TapInstruction::PowerStatus => 0x09,
            TapInstruction::Idcode => 0x1E,
        }
    }

    fn bits(self) -> u32 {
        match self {
            TapInstruction::Nar => 8,
            TapInstruction::Ndr => 32,
            TapInstruction::PowerControl => 8,
            TapInstruction::PowerStatus => 8,
            TapInstruction::Idcode => 32,
        }
    }
}

/// Power registers are separate from the other registers. They are part of the Access Port.
#[derive(Clone, Copy, PartialEq, Debug)]
enum PowerDevice {
    /// Power Control
    PowerControl,
    /// Power status
    PowerStat,
}

impl From<PowerDevice> for TapInstruction {
    fn from(dev: PowerDevice) -> Self {
        match dev {
            PowerDevice::PowerControl => TapInstruction::PowerControl,
            PowerDevice::PowerStat => TapInstruction::PowerStatus,
        }
    }
}

/// Errors that can occur when accessing Xtensa Debug Module registers.
#[derive(thiserror::Error, Debug, Copy, Clone, docsplay::Display)]
pub enum DebugRegisterError {
    /// Register is busy
    Busy,

    /// Register-specific error
    Error,

    /// Unexpected value {0:#04x}
    Unexpected(u8),
}

/// Xtensa Debug Module errors
#[derive(thiserror::Error, Debug, Clone, Copy, docsplay::Display)]
pub enum Error {
    /// Error {access} {print_narsel(narsel)} register
    Xdm {
        /// Nexus Address Register selector. Contains the ID of the register being accessed.
        narsel: u8,

        /// Access type (reading or writing)
        access: &'static str,

        /// The error that occurred.
        source: DebugRegisterError,
    },

    /// The instruction execution has encountered an exception.
    ExecException,

    /// The core is still executing a previous instruction.
    ExecBusy,

    /// Instruction execution overrun.
    ExecOverrun,

    /// The instruction was ignored. Most often this indicates that the core was not halted before
    /// requesting instruction execution.
    InstructionIgnored,

    /// The Xtensa Debug Module is powered off.
    XdmPoweredOff,
}

fn print_narsel(narsel: &u8) -> String {
    let name = match *narsel {
        0x40 => "the OCDID",
        0x42 => "the DCRCLR",
        0x43 => "the DCRSET",
        0x44 => "the DSR",
        0x45 => "the DDR",
        0x46 => "the DDREXEC",
        0x47 => "the DIR0EXEC",
        0x48 => "the DIR0",
        _ => "an unknown",
    };
    format!("{name} ({narsel:#04X})")
}

#[derive(Debug, Default)]
pub(crate) struct XdmState {
    /// The last instruction to be executed.
    // This is used to:
    // - detect incorrect uses of `schedule_write_ddr_and_execute` which expects an instruction to
    //   be loaded
    // - wait for the last instruction to complete before proceeding, as some instructions can be
    //   assumed to complete instantly.
    last_instruction: Option<Instruction>,

    /// The command queue for the current batch. JTAG accesses are batched to reduce the number of
    /// IO operations.
    queue: Queue<Error>,

    /// The results of the reads in the already executed batched JTAG commands.
    jtag_results: DeferredResultSet<CommandResult>,

    /// Read handles for accesses that need to force capturing their bits.
    ///
    /// The batching system tries to minimize the number of captured bits, in order to reduce
    /// the number of JTAG operations. However, some accesses need to capture their bits to
    /// complete correctly, or to - ironically - increase performance. We store their otherwise
    /// ignored handles in this vector and drop them when we're done with the batch.
    status_idxs: Vec<DeferredResultIndex>,
}

/// The lower level functions of the Xtensa Debug Module.
// TODO: this is mostly JTAG-specific, but not specifically. We should probably split this up, e.g.
// move the instruction execution into the current communication_interface module.
#[derive(Debug)]
pub struct Xdm<'probe> {
    /// The JTAG interface.
    pub probe: &'probe mut dyn JtagAccess,

    /// Debug module state.
    state: &'probe mut XdmState,
}

impl<'probe> Xdm<'probe> {
    pub(crate) fn new(probe: &'probe mut dyn JtagAccess, state: &'probe mut XdmState) -> Self {
        // TODO implement openocd's esp32_queue_tdi_idle() to prevent potentially damaging flash ICs

        Self { probe, state }
    }

    #[tracing::instrument(skip(self))]
    pub(crate) fn enter_debug_mode(&mut self) -> Result<(), XtensaError> {
        self.state.queue = Queue::new();
        self.state.jtag_results = DeferredResultSet::new();

        self.probe.tap_reset()?;

        // Reset PCM
        let mut pwr_control = PowerControl(0);
        pwr_control.set_debug_reset(true);
        pwr_control.set_debug_wakeup(true);
        self.pwr_write(PowerDevice::PowerControl, pwr_control.0)?;

        // Reset must be high for 10 CPU clocks.
        std::thread::sleep(Duration::from_millis(1));

        let mut pwr_control = PowerControl(0);
        pwr_control.set_debug_wakeup(true);
        pwr_control.set_mem_wakeup(true);
        pwr_control.set_core_wakeup(true);
        // Wakeup. We enable JTAG in a separate write.
        self.pwr_write(PowerDevice::PowerControl, pwr_control.0)?;

        // Set JTAG_DEBUG_USE separately to ensure it doesn't get reset by a previous write.
        // "any write to PWRCTL when JtagDebugUse is set also clears the bit".
        pwr_control.set_jtag_debug_use(true);
        self.pwr_write(PowerDevice::PowerControl, pwr_control.0)?;

        // After software deasserts this bit (DebugReset), before reading other Debug registers,
        // polling on bit 31 of the Debug Status Register (see Table 5-22) should be performed until
        // it returns 1'b1.
        let now = Instant::now();
        loop {
            let status = self.status()?;
            if status.dbgmod_power_on() {
                break;
            }

            if now.elapsed() > Duration::from_millis(100) {
                return Err(XtensaError::CoreDisabled);
            }
        }

        let mut reset_bits = PowerStatus(0);
        reset_bits.set_core_was_reset(true);
        reset_bits.set_debug_was_reset(true);
        self.pwr_write(PowerDevice::PowerStat, reset_bits.0)?;

        self.check_enabled()?;

        // we might find that an old instruction execution left the core with an exception
        // try to clear problematic bits
        self.write_nexus_register({
            let mut status = DebugStatus(0);

            status.set_exec_exception(true);
            status.set_exec_done(true);
            status.set_exec_overrun(true);
            status.set_debug_pend_break(true);
            status.set_debug_pend_host(true);
            status.set_debug_int_break(true);

            status
        })?;

        // configure the debug module
        self.debug_control({
            let mut reg = DebugControlBits(0);
            reg.set_enable_ocd(true);
            reg
        })?;

        Ok(())
    }

    /// Schedule a write of the Debug Control Register
    pub fn debug_control(&mut self, bits: DebugControlBits) -> Result<(), XtensaError> {
        self.schedule_write_nexus_register(DebugControlSet(bits));
        self.schedule_write_nexus_register(DebugControlClear({
            let mut reg = DebugControlBits(0);

            reg.set_break_in_en(!bits.break_in_en());
            reg.set_break_out_en(!bits.break_out_en());
            reg.set_debug_sw_active(!bits.debug_sw_active());
            reg.set_run_stall_in_en(!bits.run_stall_in_en());
            reg.set_debug_mode_out_en(!bits.debug_mode_out_en());

            reg
        }));
        // Clear pending interrupts that would re-enter us into the Stopped state.
        self.schedule_write_nexus_register({
            let mut status = DebugStatus(0);

            status.set_debug_pend_break(true);
            status.set_debug_int_break(true);

            status
        });

        Ok(())
    }

    fn check_enabled(&mut self) -> Result<(), XtensaError> {
        let Ok(device_id) = self.read_nexus_register::<OcdId>() else {
            return Err(XtensaError::CoreDisabled);
        };
        let device_id = device_id.0;
        tracing::debug!("Read OCDID: {:#010X}", device_id);

        if device_id == 0 || device_id == u32::MAX {
            // Disable the debug module if we can't work with it.
            self.pwr_write(PowerDevice::PowerControl, 0)?;
            return Err(XtensaError::CoreDisabled);
        }
        tracing::info!("Found Xtensa device with OCDID: {:#010X}", device_id);
        Ok(())
    }

    /// Read and clear the `PowerStatus` flags.
    pub fn power_status(&mut self, clear: PowerStatus) -> Result<PowerStatus, XtensaError> {
        let bits = self.pwr_write(PowerDevice::PowerStat, clear.0)?;
        Ok(PowerStatus(bits))
    }

    /// Read and clear the `core_was_reset` flag.
    pub fn read_power_status(&mut self) -> Result<PowerStatus, XtensaError> {
        let bits = self.pwr_write(PowerDevice::PowerStat, 0)?;
        Ok(PowerStatus(bits))
    }

    /// Execute the queued commands.
    pub fn execute(&mut self) -> Result<(), XtensaError> {
        let mut queue = std::mem::take(&mut self.state.queue);

        tracing::debug!("Executing {} commands", queue.len());

        // Drop the status readers when we're done.
        // We take now to avoid a possibly recursive call to clear before it's time.
        let _idxs = std::mem::take(&mut self.state.status_idxs);

        let mut started = Instant::now();
        let mut previous_queue_len = queue.len();
        while !queue.is_empty() {
            match queue.execute(|queue| self.probe.write_register_batch(queue)) {
                Ok(result) => {
                    self.state.jtag_results.merge_from(result);
                    return Ok(());
                }
                Err(e) => {
                    // Consume the successful commands.
                    queue.consume(e.results.len());

                    match e.error {
                        BatchError::Specific(err) => {
                            // err is now ProbeRsError, not Box<dyn Error>
                            match err {
                                Error::Xdm {
                                    source: DebugRegisterError::Busy,
                                    ..
                                } => {
                                    // The specific nexus register may need some longer delay. For now we just
                                    // retry, but we should probably add some no-ops later.
                                }
                                Error::ExecBusy => {
                                    // The instruction is still executing. Retry the Debug Status read.
                                    // Do not rewind the queue, it will not include the failed command.
                                    // Retrying the failed command will just shift the DSR out of the
                                    // JTAG DR again, re-attempting the read.
                                }
                                Error::ExecOverrun => {
                                    // Clear exception/overrun to allow executing further instructions.
                                    self.clear_exception_state()?;
                                    // This state is reported by a DebugStatus read. We need to rewind this read and
                                    // the previous commands that attempted to execute an instruction. Commands come in NAR-NDR
                                    // pairs, and we don't have to rewind the last NDR, because the failed instruction is not
                                    // part of the returned results, hence it is not consumed.
                                    if !queue.rewind(3) {
                                        return Err(XtensaError::XdmError(Error::ExecOverrun));
                                    }
                                }
                                Error::ExecException => {
                                    // Clear exception to allow executing further instructions.
                                    self.clear_exception_state()?;
                                    // TODO: in the future, we might want to bubble up the exception cause.
                                    // We might also want to store this error for each result that has not
                                    // yet been read.
                                    return Err(XtensaError::XdmError(Error::ExecException));
                                }

                                error => return Err(XtensaError::XdmError(error)),
                            }
                        }
                        BatchError::Probe(debug_probe_error) => {
                            return Err(debug_probe_error.into());
                        }
                    };

                    self.state.jtag_results.merge_from(e.results);
                }
            }

            // If progress was made, reset the timeout.
            if queue.len() < previous_queue_len {
                started = Instant::now();
                previous_queue_len = queue.len();
            }

            if started.elapsed() > Duration::from_millis(500) {
                return Err(XtensaError::Timeout);
            }
        }

        Ok(())
    }

    pub(crate) fn read_deferred_result(
        &mut self,
        index: DeferredResultIndex,
    ) -> Result<CommandResult, XtensaError> {
        match self.state.jtag_results.take(index) {
            Ok(result) => Ok(result),
            Err(index) => {
                self.execute()?;
                // We can lose data if `execute` fails.
                self.state
                    .jtag_results
                    .take(index)
                    .map_err(|_| XtensaError::BatchedResultNotAvailable)
            }
        }
    }

    fn do_nexus_op(&mut self, nar: u8, ndr: u32, transform: TransformFn) -> DeferredResultIndex {
        let nar_idx = self.state.queue.schedule(JtagWriteCommand {
            data: JtagWriteData {
                address: TapInstruction::Nar.code(),
                data: nar.to_le_bytes().to_vec(),
                len: TapInstruction::Nar.bits(),
            },
            transform: |write, capture| {
                let capture = capture.load_le::<u8>();
                let nar = write.data[0] >> 1;
                let is_write = write.data[0] & 1 == 1;

                Err(Error::Xdm {
                    narsel: nar,
                    access: if is_write { "writing" } else { "reading" },
                    source: match capture & 0b00000011 {
                        0 => return Ok(CommandResult::None),
                        1 => DebugRegisterError::Error,
                        2 => DebugRegisterError::Busy,
                        _ => DebugRegisterError::Unexpected(capture),
                    },
                })
            },
        });

        // We save the nar reader because we want to capture the previous status.
        self.state.status_idxs.push(nar_idx);

        self.state.queue.schedule(ShiftDrCommand {
            inner: ShiftDrData {
                data: ndr.to_le_bytes().to_vec(),
                len: TapInstruction::Ndr.bits(),
            },
            transform,
        })
    }

    /// Perform an access to a register
    fn schedule_dbg_read_and_transform(
        &mut self,
        address: u8,
        transform: TransformFn,
    ) -> DeferredResultIndex {
        let regdata = address << 1;

        self.do_nexus_op(regdata, 0, transform)
    }

    /// Perform an access to a register
    fn schedule_dbg_read(&mut self, address: u8) -> DeferredResultIndex {
        self.schedule_dbg_read_and_transform(address, transform_u32)
    }

    /// Perform an access to a register
    fn schedule_dbg_write(&mut self, address: u8, value: u32) -> DeferredResultIndex {
        let regdata = (address << 1) | 1;

        self.do_nexus_op(regdata, value, transform_noop)
    }

    fn pwr_write(&mut self, dev: PowerDevice, value: u8) -> Result<u8, XtensaError> {
        let instr = TapInstruction::from(dev);

        let capture = self
            .probe
            .write_register(instr.code(), &[value], instr.bits())?;

        let res = capture.load_le::<u8>();
        tracing::trace!("pwr_write response: {:?}", res);

        Ok(res)
    }

    pub(super) fn read_idcode(&mut self) -> Result<u32, XtensaError> {
        self.probe.tap_reset()?;
        let instr = TapInstruction::Idcode;

        let capture = self
            .probe
            .write_register(instr.code(), &[0, 0, 0, 0], instr.bits())?;

        let res = capture.load_le::<u32>();

        tracing::debug!("idcode response: {:x?}", res);

        Ok(res)
    }

    pub(super) fn schedule_read_nexus_register<R: NexusRegister>(&mut self) -> DeferredResultIndex {
        tracing::debug!("Reading from {}", R::NAME);
        self.schedule_dbg_read(R::ADDRESS)
    }

    fn read_nexus_register<R: NexusRegister>(&mut self) -> Result<R, XtensaError> {
        let bits_reader = self.schedule_read_nexus_register::<R>();

        let bits = self.read_deferred_result(bits_reader)?.into_u32();
        let reg = R::from_bits(bits)?;
        tracing::trace!("Read: {:?}", reg);
        Ok(reg)
    }

    pub(crate) fn schedule_write_nexus_register<R: NexusRegister>(&mut self, register: R) {
        tracing::debug!("Writing {}: {:08x}", R::NAME, register.bits());
        self.schedule_dbg_write(R::ADDRESS, register.bits());
    }

    pub(crate) fn write_nexus_register<R: NexusRegister>(
        &mut self,
        register: R,
    ) -> Result<(), XtensaError> {
        self.schedule_write_nexus_register(register);
        self.execute()
    }

    pub(super) fn status(&mut self) -> Result<DebugStatus, XtensaError> {
        self.read_nexus_register::<DebugStatus>()
    }

    pub(super) fn schedule_wait_for_exec_done(&mut self) {
        let status_reader = self
            .schedule_dbg_read_and_transform(DebugStatus::ADDRESS, transform_instruction_status);

        self.state.status_idxs.push(status_reader);
    }

    /// Instructs Core to enter Core Stopped state instead of vectoring on a Debug Exception/Interrupt.
    pub(super) fn halt(&mut self) -> Result<(), XtensaError> {
        self.schedule_halt();
        self.execute()
    }

    /// Instructs Core to enter Core Stopped state instead of vectoring on a Debug Exception/Interrupt.
    pub(super) fn schedule_halt(&mut self) {
        self.schedule_write_nexus_register(DebugControlSet({
            let mut control = DebugControlBits(0);

            control.set_enable_ocd(true);
            control.set_debug_interrupt(true);

            control
        }));
        self.schedule_write_nexus_register({
            let mut status = DebugStatus(0);

            status.set_debug_pend_break(true);
            status.set_debug_int_break(true);
            status.set_exec_overrun(true);
            status.set_exec_exception(true);

            status
        });
    }

    pub(super) fn leave_ocd_mode(&mut self) -> Result<(), XtensaError> {
        // clear all clearable status bits
        self.write_nexus_register({
            let mut clear_status = DebugStatus(0);

            clear_status.set_exec_done(true);
            clear_status.set_exec_exception(true);
            clear_status.set_exec_overrun(true);
            clear_status.set_core_wrote_ddr(true);
            clear_status.set_core_read_ddr(true);
            clear_status.set_host_wrote_ddr(true);
            clear_status.set_host_read_ddr(true);
            clear_status.set_debug_pend_break(true);
            clear_status.set_debug_pend_host(true);
            clear_status.set_debug_pend_trax(true);
            clear_status.set_debug_int_break(true);
            clear_status.set_debug_int_host(true);
            clear_status.set_debug_int_trax(true);
            clear_status.set_run_stall_toggle(true);

            clear_status
        })?;

        self.write_nexus_register(DebugControlClear({
            let mut control = DebugControlBits(0);

            control.set_enable_ocd(true);
            control.set_break_in_en(true);
            control.set_break_out_en(true);

            control
        }))?;

        Ok(())
    }

    pub(super) fn resume(&mut self) -> Result<(), XtensaError> {
        tracing::debug!("resuming...");
        // Clear pending interrupts first that would re-enter us into the Stopped state
        self.schedule_write_nexus_register({
            let mut clear_status = DebugStatus(0);

            clear_status.set_debug_pend_host(true);
            clear_status.set_debug_pend_break(true);

            clear_status
        });

        self.schedule_execute_instruction(Instruction::Rfdo(0));
        match self.execute() {
            Ok(_) => Ok(()),
            // Core may just have resumed into a `waiti`
            Err(XtensaError::XdmError(_)) => Ok(()),
            Err(e) => Err(e),
        }
    }

    pub(super) fn schedule_write_instruction(&mut self, instruction: Instruction) {
        tracing::debug!("Preparing instruction: {:?}", instruction);
        self.state.last_instruction = Some(instruction);

        match instruction.encode() {
            InstructionEncoding::Narrow(inst) => {
                self.schedule_write_nexus_register(DebugInstructionRegister(inst));
            }
        }
    }

    pub(super) fn schedule_execute_instruction(&mut self, instruction: Instruction) {
        tracing::debug!("Executing instruction: {:?}", instruction);
        self.state.last_instruction = Some(instruction);

        match instruction.encode() {
            InstructionEncoding::Narrow(inst) => {
                self.schedule_write_nexus_register(DebugInstructionAndExecRegister(inst));
            }
        }

        self.schedule_wait_for_last_instruction();
    }

    pub(super) fn schedule_read_ddr(&mut self) -> DeferredResultIndex {
        self.schedule_read_nexus_register::<DebugDataRegister>()
    }

    pub(super) fn schedule_read_ddr_and_execute(&mut self) -> DeferredResultIndex {
        let reader = self.schedule_read_nexus_register::<DebugDataAndExecRegister>();
        self.schedule_wait_for_last_instruction();

        reader
    }

    pub(super) fn schedule_write_ddr(&mut self, ddr: u32) {
        self.schedule_write_nexus_register(DebugDataRegister(ddr))
    }

    pub(super) fn schedule_write_ddr_and_execute(&mut self, ddr: u32) {
        if let Some(instruction) = self.state.last_instruction {
            tracing::debug!("Executing instruction via DDREXEC write: {:?}", instruction);
        } else {
            tracing::warn!("Writing DDREXEC without instruction");
        }

        self.schedule_write_nexus_register(DebugDataAndExecRegister(ddr));
        self.schedule_wait_for_last_instruction();
    }

    fn schedule_wait_for_last_instruction(&mut self) {
        // Assume some instructions complete practically instantly and don't waste bandwidth
        // checking their results.
        if let Some(last_instruction) = self.state.last_instruction {
            let wait = !matches!(
                last_instruction,
                Instruction::Rsr(_, _)
                    | Instruction::Wsr(_, _)
                    | Instruction::Lddr32P(_)
                    | Instruction::Sddr32P(_)
            );

            if wait {
                self.schedule_wait_for_exec_done();
            }
        }
    }

    pub(crate) fn reset_and_halt(&mut self) -> Result<(), XtensaError> {
        self.execute()?;
        self.pwr_write(PowerDevice::PowerControl, {
            let mut pwr_control = PowerControl(0);

            pwr_control.set_jtag_debug_use(true);
            pwr_control.set_debug_wakeup(true);
            pwr_control.set_mem_wakeup(true);
            pwr_control.set_core_wakeup(true);
            pwr_control.set_core_reset(true);

            pwr_control.0
        })?;
        self.halt()?;

        self.pwr_write(PowerDevice::PowerControl, {
            let mut pwr_control = PowerControl(0);

            pwr_control.set_jtag_debug_use(true);
            pwr_control.set_debug_wakeup(true);
            pwr_control.set_mem_wakeup(true);
            pwr_control.set_core_wakeup(true);

            pwr_control.0
        })?;

        Ok(())
    }

    fn clear_exception_state(&mut self) -> Result<(), XtensaError> {
        self.write_nexus_register({
            let mut status = DebugStatus(0);

            status.set_exec_exception(true);
            status.set_exec_overrun(true);

            status
        })
    }
}

type TransformFn = fn(&ShiftDrData, &BitSlice) -> Result<CommandResult, Error>;

fn transform_u32(_data: &ShiftDrData, capture: &BitSlice) -> Result<CommandResult, Error> {
    Ok(CommandResult::U32(capture.load_le::<u32>()))
}

fn transform_noop(_data: &ShiftDrData, _capture: &BitSlice) -> Result<CommandResult, Error> {
    Ok(CommandResult::None)
}

fn transform_instruction_status(
    _data: &ShiftDrData,
    capture: &BitSlice,
) -> Result<CommandResult, Error> {
    let status = DebugStatus(capture.load_le::<u32>());

    if status.exec_overrun() {
        return Err(Error::ExecOverrun);
    }
    if status.exec_exception() {
        return Err(Error::ExecException);
    }
    if status.exec_busy() {
        return Err(Error::ExecBusy);
    }
    if status.exec_done() {
        return Ok(CommandResult::None);
    }

    Err(Error::InstructionIgnored)
}

bitfield::bitfield! {
    /// Power and Reset Control register
    #[derive(Copy, Clone)]
    pub struct PowerControl(u8);
    impl Debug;

    /// Request power to core
    pub core_wakeup,    set_core_wakeup:    0;

    /// Request power to Memory domain
    pub mem_wakeup,     set_mem_wakeup:     1;

    /// Request power to Debug module
    pub debug_wakeup,   set_debug_wakeup:   2;

    /// Setting to 1 asserts reset to the core
    pub core_reset,     set_core_reset:     4;

    /// Setting to 1 asserts reset to the Xtensa Debug module
    pub debug_reset,    set_debug_reset:    6;

    /// Set to enable JTAG access to Debug
    ///
    /// Tied high in configurations without PSO.
    pub jtag_debug_use, set_jtag_debug_use: 7;
}

bitfield::bitfield! {
    /// Power and Reset Status register
    #[derive(Copy, Clone)]
    pub struct PowerStatus(u8);
    impl Debug;

    /// Set if core is powered on
    pub core_domain_on,    _: 0;

    /// Set if memory domain is powered on
    pub mem_domain_on,     _: 1;

    /// Set if debug domain is powered on
    pub debug_domain_on,   _: 2;

    /// Set if any core wakeup signal is set. Indicates some
    /// agent still requires power to the core.
    pub core_still_needed, _: 3;

    /// Core was reset since last time this bit was cleared
    ///
    /// Clears bit when written as 1
    pub core_was_reset,    set_core_was_reset: 4;

    /// Debug module was reset since last time this bit was cleared
    ///
    /// Clears bit when written as 1
    pub debug_was_reset,   set_debug_was_reset: 6;
}

bitfield::bitfield! {
    /// Debug Status register
    ///
    /// The DSR register provides OCD status to host debugger.
    #[derive(Copy, Clone)]
    pub struct DebugStatus(u32);
    impl Debug;

    /// Instruction in DIR completed execution (w/ or w/o exception)
    ///
    /// Cleared by writing 1
    pub exec_done,         set_exec_done: 0;

    /// A previous instruction in DIR completed with an exception
    ///
    /// Cleared by writing 1
    pub exec_exception,    set_exec_exception: 1;

    /// Core is executing DIR (meaningful while Stopped is 1)
    pub exec_busy,         _: 2;

    /// DIR execution attempted while previous execute still busy
    ///
    /// Cleared by writing 1
    pub exec_overrun,      set_exec_overrun: 3;

    /// Core is under OCD debug control, in Stopped or executing DIR
    pub stopped,           _: 4;

    /// Core wrote to DDR, i.e. executed WSR.DDR or XSR.DDR
    ///
    /// Cleared by writing 1
    pub core_wrote_ddr,    set_core_wrote_ddr: 10;

    /// Core read from DDR, i.e. executed RSR.DDR or XSR.DDR
    ///
    /// Cleared by writing 1
    pub core_read_ddr,     set_core_read_ddr: 11;

    /// Host wrote to DDR (via JTAG or APB) (includes DDREXEC)
    ///
    /// Cleared by writing 1
    pub host_wrote_ddr,    set_host_wrote_ddr: 14;

    /// Host read from DDR (via JTAG or APB) (includes DDREXEC)
    ///
    /// Cleared by writing 1
    pub host_read_ddr,     set_host_read_ddr: 15;

    /// Debug interrupt pending due to BreakIn signal
    ///
    /// Cleared by writing 1
    pub debug_pend_break,  set_debug_pend_break: 16;

    /// Debug interrupt pending due to DCR.DebugInterrupt
    ///
    /// Cleared by writing 1
    pub debug_pend_host,   set_debug_pend_host: 17;

    /// Debug interrupt pending due to TRAX PTO
    ///
    /// Cleared by writing 1
    pub debug_pend_trax,   set_debug_pend_trax: 18;

    /// Debug interrupt taken due to BreakIn signal
    ///
    /// Cleared by writing 1
    pub debug_int_break,   set_debug_int_break: 20;

    /// Debug interrupt taken due to DCR.DebugInterrupt signal
    ///
    /// Cleared by writing 1
    pub debug_int_host,    set_debug_int_host: 21;

    /// Debug interrupt taken due to TRAX PTO
    ///
    /// Cleared by writing 1
    pub debug_int_trax,    set_debug_int_trax: 22;

    /// Set when RunStall input to Xtensa changes polarity
    ///
    /// Cleared by writing 1
    pub run_stall_toggle,  set_run_stall_toggle: 23;

    /// Provides the real-time value of the RunStall input to Xtensa
    pub run_stall_sample,  _: 24;

    /// Break-out topology detection status bit (BreakOutAck signal state)
    pub break_out_ack_iti, _: 25;

    /// Break-in topology detection status bit (BreakIn signal state)
    pub break_in_iti,      _: 26;

    /// Always 1 (Read as zero when the Debug module is powered off.)
    pub dbgmod_power_on,   _: 31;

}

/// An abstraction over all registers that can be accessed via the NAR/NDR instruction pair.
pub(crate) trait NexusRegister: Sized + Copy + Debug {
    /// NAR register address
    const ADDRESS: u8;
    const NAME: &'static str;

    fn from_bits(bits: u32) -> Result<Self, XtensaError>;
    fn bits(&self) -> u32;
}

impl NexusRegister for DebugStatus {
    const ADDRESS: u8 = NARADR_DSR;
    const NAME: &'static str = "DebugStatus";

    fn from_bits(bits: u32) -> Result<Self, XtensaError> {
        Ok(Self(bits))
    }

    fn bits(&self) -> u32 {
        self.0
    }
}

/// Writes and executes DIR.
#[derive(Copy, Clone, Debug)]
struct OcdId(u32);

impl NexusRegister for OcdId {
    const ADDRESS: u8 = NARADR_OCDID;
    const NAME: &'static str = "OCDID";

    fn from_bits(bits: u32) -> Result<Self, XtensaError> {
        Ok(Self(bits))
    }

    fn bits(&self) -> u32 {
        self.0
    }
}

bitfield::bitfield! {
    /// Debug Control register bits.
    #[derive(Copy, Clone)]
    pub struct DebugControlBits(u32);
    impl Debug;

    /// Set to activate the OCD.
    pub enable_ocd,          set_enable_ocd         : 0;

    /// Set to break the core (same as DSR.DebugPendHost)
    ///
    /// R/set
    pub debug_interrupt,     set_debug_interrupt    : 1;

    /// Set to allow debug interrupts to supersede all conditions
    pub interrupt_all_conds, set_interrupt_all_conds: 2;

    /// Enable BreakIn
    pub break_in_en,         set_break_in_en        : 16;

    /// Enable BreakOut
    pub break_out_en,        set_break_out_en       : 17;

    /// A software-set flag that indicates user-controlled debug mode
    pub debug_sw_active,     set_debug_sw_active    : 20;

    /// Enable the RunStall input
    pub run_stall_in_en,     set_run_stall_in_en    : 21;

    /// Enable the XOCDMode output
    pub debug_mode_out_en,   set_debug_mode_out_en  : 22;

    /// BreakOut topology detection control bit
    pub break_out_ito,       set_break_out_ito      : 24;

    /// BreakInAck topology detection control bit
    pub break_in_ack_ito,    set_break_in_ack_ito   : 25;
}

#[derive(Copy, Clone, Debug)]
/// Bits written as 1 are set to 1 in hardware.
pub struct DebugControlSet(pub(crate) DebugControlBits);

impl NexusRegister for DebugControlSet {
    const ADDRESS: u8 = NARADR_DCRSET;
    const NAME: &'static str = "DebugControlSet";

    fn from_bits(bits: u32) -> Result<Self, XtensaError> {
        Ok(Self(DebugControlBits(bits)))
    }

    fn bits(&self) -> u32 {
        self.0.0
    }
}

#[derive(Copy, Clone, Debug)]
/// Bits written as 1 are set to 0 in hardware.
pub struct DebugControlClear(pub(crate) DebugControlBits);

impl NexusRegister for DebugControlClear {
    const ADDRESS: u8 = NARADR_DCRCLR;
    const NAME: &'static str = "DebugControlClear";

    fn from_bits(bits: u32) -> Result<Self, XtensaError> {
        Ok(Self(DebugControlBits(bits)))
    }

    fn bits(&self) -> u32 {
        self.0.0
    }
}

/// Writes DDR.
#[derive(Copy, Clone, Debug)]
struct DebugDataRegister(u32);

impl NexusRegister for DebugDataRegister {
    const ADDRESS: u8 = NARADR_DDR;
    const NAME: &'static str = "DDR";

    fn from_bits(bits: u32) -> Result<Self, XtensaError> {
        Ok(Self(bits))
    }

    fn bits(&self) -> u32 {
        self.0
    }
}

/// Writes DDR and executes DIR on write AND READ.
#[derive(Copy, Clone, Debug)]
struct DebugDataAndExecRegister(u32);

impl NexusRegister for DebugDataAndExecRegister {
    const ADDRESS: u8 = NARADR_DDREXEC;
    const NAME: &'static str = "DDREXEC";

    fn from_bits(bits: u32) -> Result<Self, XtensaError> {
        Ok(Self(bits))
    }

    fn bits(&self) -> u32 {
        self.0
    }
}

/// Writes DIR.
#[derive(Copy, Clone, Debug)]
struct DebugInstructionRegister(u32);

impl NexusRegister for DebugInstructionRegister {
    const ADDRESS: u8 = NARADR_DIR0;
    const NAME: &'static str = "DIR0";

    fn from_bits(bits: u32) -> Result<Self, XtensaError> {
        Ok(Self(bits))
    }

    fn bits(&self) -> u32 {
        self.0
    }
}

/// Writes and executes DIR.
#[derive(Copy, Clone, Debug)]
struct DebugInstructionAndExecRegister(u32);

impl NexusRegister for DebugInstructionAndExecRegister {
    const ADDRESS: u8 = NARADR_DIR0EXEC;
    const NAME: &'static str = "DIR0EXEC";

    fn from_bits(bits: u32) -> Result<Self, XtensaError> {
        Ok(Self(bits))
    }

    fn bits(&self) -> u32 {
        self.0
    }
}