target/riscv: fix dead assignment
[fw/openocd] / src / target / riscv / riscv.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2
3 #include <assert.h>
4 #include <stdlib.h>
5 #include <time.h>
6
7 #ifdef HAVE_CONFIG_H
8 #include "config.h"
9 #endif
10
11 #include <helper/log.h>
12 #include <helper/time_support.h>
13 #include "target/target.h"
14 #include "target/algorithm.h"
15 #include "target/target_type.h"
16 #include <target/smp.h>
17 #include "jtag/jtag.h"
18 #include "target/register.h"
19 #include "target/breakpoints.h"
20 #include "riscv.h"
21 #include "gdb_regs.h"
22 #include "rtos/rtos.h"
23 #include "debug_defines.h"
24 #include <helper/bits.h>
25
26 #define get_field(reg, mask) (((reg) & (mask)) / ((mask) & ~((mask) << 1)))
27 #define set_field(reg, mask, val) (((reg) & ~(mask)) | (((val) * ((mask) & ~((mask) << 1))) & (mask)))
28
29 /* Constants for legacy SiFive hardware breakpoints. */
30 #define CSR_BPCONTROL_X                 (1<<0)
31 #define CSR_BPCONTROL_W                 (1<<1)
32 #define CSR_BPCONTROL_R                 (1<<2)
33 #define CSR_BPCONTROL_U                 (1<<3)
34 #define CSR_BPCONTROL_S                 (1<<4)
35 #define CSR_BPCONTROL_H                 (1<<5)
36 #define CSR_BPCONTROL_M                 (1<<6)
37 #define CSR_BPCONTROL_BPMATCH   (0xf<<7)
38 #define CSR_BPCONTROL_BPACTION  (0xff<<11)
39
40 #define DEBUG_ROM_START         0x800
41 #define DEBUG_ROM_RESUME        (DEBUG_ROM_START + 4)
42 #define DEBUG_ROM_EXCEPTION     (DEBUG_ROM_START + 8)
43 #define DEBUG_RAM_START         0x400
44
45 #define SETHALTNOT                              0x10c
46
47 /*** JTAG registers. ***/
48
49 #define DTMCONTROL                                      0x10
50 #define DTMCONTROL_DBUS_RESET           (1<<16)
51 #define DTMCONTROL_IDLE                         (7<<10)
52 #define DTMCONTROL_ADDRBITS                     (0xf<<4)
53 #define DTMCONTROL_VERSION                      (0xf)
54
55 #define DBUS                                            0x11
56 #define DBUS_OP_START                           0
57 #define DBUS_OP_SIZE                            2
58 typedef enum {
59         DBUS_OP_NOP = 0,
60         DBUS_OP_READ = 1,
61         DBUS_OP_WRITE = 2
62 } dbus_op_t;
63 typedef enum {
64         DBUS_STATUS_SUCCESS = 0,
65         DBUS_STATUS_FAILED = 2,
66         DBUS_STATUS_BUSY = 3
67 } dbus_status_t;
68 #define DBUS_DATA_START                         2
69 #define DBUS_DATA_SIZE                          34
70 #define DBUS_ADDRESS_START                      36
71
72 typedef enum slot {
73         SLOT0,
74         SLOT1,
75         SLOT_LAST,
76 } slot_t;
77
78 /*** Debug Bus registers. ***/
79
80 #define DMCONTROL                               0x10
81 #define DMCONTROL_INTERRUPT             (((uint64_t)1)<<33)
82 #define DMCONTROL_HALTNOT               (((uint64_t)1)<<32)
83 #define DMCONTROL_BUSERROR              (7<<19)
84 #define DMCONTROL_SERIAL                (3<<16)
85 #define DMCONTROL_AUTOINCREMENT (1<<15)
86 #define DMCONTROL_ACCESS                (7<<12)
87 #define DMCONTROL_HARTID                (0x3ff<<2)
88 #define DMCONTROL_NDRESET               (1<<1)
89 #define DMCONTROL_FULLRESET             1
90
91 #define DMINFO                                  0x11
92 #define DMINFO_ABUSSIZE                 (0x7fU<<25)
93 #define DMINFO_SERIALCOUNT              (0xf<<21)
94 #define DMINFO_ACCESS128                (1<<20)
95 #define DMINFO_ACCESS64                 (1<<19)
96 #define DMINFO_ACCESS32                 (1<<18)
97 #define DMINFO_ACCESS16                 (1<<17)
98 #define DMINFO_ACCESS8                  (1<<16)
99 #define DMINFO_DRAMSIZE                 (0x3f<<10)
100 #define DMINFO_AUTHENTICATED    (1<<5)
101 #define DMINFO_AUTHBUSY                 (1<<4)
102 #define DMINFO_AUTHTYPE                 (3<<2)
103 #define DMINFO_VERSION                  3
104
105 /*** Info about the core being debugged. ***/
106
107 #define DBUS_ADDRESS_UNKNOWN    0xffff
108
109 #define MAX_HWBPS                       16
110 #define DRAM_CACHE_SIZE         16
111
112 static uint8_t ir_dtmcontrol[4] = {DTMCONTROL};
113 struct scan_field select_dtmcontrol = {
114         .in_value = NULL,
115         .out_value = ir_dtmcontrol
116 };
117 static uint8_t ir_dbus[4] = {DBUS};
118 struct scan_field select_dbus = {
119         .in_value = NULL,
120         .out_value = ir_dbus
121 };
122 static uint8_t ir_idcode[4] = {0x1};
123 struct scan_field select_idcode = {
124         .in_value = NULL,
125         .out_value = ir_idcode
126 };
127
128 static bscan_tunnel_type_t bscan_tunnel_type;
129 int bscan_tunnel_ir_width; /* if zero, then tunneling is not present/active */
130
131 static const uint8_t bscan_zero[4] = {0};
132 static const uint8_t bscan_one[4] = {1};
133
134 static uint8_t ir_user4[4];
135 static struct scan_field select_user4 = {
136         .in_value = NULL,
137         .out_value = ir_user4
138 };
139
140
141 static uint8_t bscan_tunneled_ir_width[4] = {5};  /* overridden by assignment in riscv_init_target */
142 static struct scan_field _bscan_tunnel_data_register_select_dmi[] = {
143                 {
144                         .num_bits = 3,
145                         .out_value = bscan_zero,
146                         .in_value = NULL,
147                 },
148                 {
149                         .num_bits = 5, /* initialized in riscv_init_target to ir width of DM */
150                         .out_value = ir_dbus,
151                         .in_value = NULL,
152                 },
153                 {
154                         .num_bits = 7,
155                         .out_value = bscan_tunneled_ir_width,
156                         .in_value = NULL,
157                 },
158                 {
159                         .num_bits = 1,
160                         .out_value = bscan_zero,
161                         .in_value = NULL,
162                 }
163 };
164
165 static struct scan_field _bscan_tunnel_nested_tap_select_dmi[] = {
166                 {
167                         .num_bits = 1,
168                         .out_value = bscan_zero,
169                         .in_value = NULL,
170                 },
171                 {
172                         .num_bits = 7,
173                         .out_value = bscan_tunneled_ir_width,
174                         .in_value = NULL,
175                 },
176                 {
177                         .num_bits = 0, /* initialized in riscv_init_target to ir width of DM */
178                         .out_value = ir_dbus,
179                         .in_value = NULL,
180                 },
181                 {
182                         .num_bits = 3,
183                         .out_value = bscan_zero,
184                         .in_value = NULL,
185                 }
186 };
187 static struct scan_field *bscan_tunnel_nested_tap_select_dmi = _bscan_tunnel_nested_tap_select_dmi;
188 static uint32_t bscan_tunnel_nested_tap_select_dmi_num_fields = ARRAY_SIZE(_bscan_tunnel_nested_tap_select_dmi);
189
190 static struct scan_field *bscan_tunnel_data_register_select_dmi = _bscan_tunnel_data_register_select_dmi;
191 static uint32_t bscan_tunnel_data_register_select_dmi_num_fields = ARRAY_SIZE(_bscan_tunnel_data_register_select_dmi);
192
193 struct trigger {
194         uint64_t address;
195         uint32_t length;
196         uint64_t mask;
197         uint64_t value;
198         bool read, write, execute;
199         int unique_id;
200 };
201
202 /* Wall-clock timeout for a command/access. Settable via RISC-V Target commands.*/
203 int riscv_command_timeout_sec = DEFAULT_COMMAND_TIMEOUT_SEC;
204
205 /* Wall-clock timeout after reset. Settable via RISC-V Target commands.*/
206 int riscv_reset_timeout_sec = DEFAULT_RESET_TIMEOUT_SEC;
207
208 static bool riscv_enable_virt2phys = true;
209 bool riscv_ebreakm = true;
210 bool riscv_ebreaks = true;
211 bool riscv_ebreaku = true;
212
213 bool riscv_enable_virtual;
214
215 static enum {
216         RO_NORMAL,
217         RO_REVERSED
218 } resume_order;
219
220 static const virt2phys_info_t sv32 = {
221         .name = "Sv32",
222         .va_bits = 32,
223         .level = 2,
224         .pte_shift = 2,
225         .vpn_shift = {12, 22},
226         .vpn_mask = {0x3ff, 0x3ff},
227         .pte_ppn_shift = {10, 20},
228         .pte_ppn_mask = {0x3ff, 0xfff},
229         .pa_ppn_shift = {12, 22},
230         .pa_ppn_mask = {0x3ff, 0xfff},
231 };
232
233 static const virt2phys_info_t sv39 = {
234         .name = "Sv39",
235         .va_bits = 39,
236         .level = 3,
237         .pte_shift = 3,
238         .vpn_shift = {12, 21, 30},
239         .vpn_mask = {0x1ff, 0x1ff, 0x1ff},
240         .pte_ppn_shift = {10, 19, 28},
241         .pte_ppn_mask = {0x1ff, 0x1ff, 0x3ffffff},
242         .pa_ppn_shift = {12, 21, 30},
243         .pa_ppn_mask = {0x1ff, 0x1ff, 0x3ffffff},
244 };
245
246 static const virt2phys_info_t sv48 = {
247         .name = "Sv48",
248         .va_bits = 48,
249         .level = 4,
250         .pte_shift = 3,
251         .vpn_shift = {12, 21, 30, 39},
252         .vpn_mask = {0x1ff, 0x1ff, 0x1ff, 0x1ff},
253         .pte_ppn_shift = {10, 19, 28, 37},
254         .pte_ppn_mask = {0x1ff, 0x1ff, 0x1ff, 0x1ffff},
255         .pa_ppn_shift = {12, 21, 30, 39},
256         .pa_ppn_mask = {0x1ff, 0x1ff, 0x1ff, 0x1ffff},
257 };
258
259 static enum riscv_halt_reason riscv_halt_reason(struct target *target, int hartid);
260 static void riscv_info_init(struct target *target, struct riscv_info *r);
261 static void riscv_invalidate_register_cache(struct target *target);
262 static int riscv_step_rtos_hart(struct target *target);
263
264 static void riscv_sample_buf_maybe_add_timestamp(struct target *target, bool before)
265 {
266         RISCV_INFO(r);
267         uint32_t now = timeval_ms() & 0xffffffff;
268         if (r->sample_buf.used + 5 < r->sample_buf.size) {
269                 if (before)
270                         r->sample_buf.buf[r->sample_buf.used++] = RISCV_SAMPLE_BUF_TIMESTAMP_BEFORE;
271                 else
272                         r->sample_buf.buf[r->sample_buf.used++] = RISCV_SAMPLE_BUF_TIMESTAMP_AFTER;
273                 r->sample_buf.buf[r->sample_buf.used++] = now & 0xff;
274                 r->sample_buf.buf[r->sample_buf.used++] = (now >> 8) & 0xff;
275                 r->sample_buf.buf[r->sample_buf.used++] = (now >> 16) & 0xff;
276                 r->sample_buf.buf[r->sample_buf.used++] = (now >> 24) & 0xff;
277         }
278 }
279
280 static int riscv_resume_go_all_harts(struct target *target);
281
282 void select_dmi_via_bscan(struct target *target)
283 {
284         jtag_add_ir_scan(target->tap, &select_user4, TAP_IDLE);
285         if (bscan_tunnel_type == BSCAN_TUNNEL_DATA_REGISTER)
286                 jtag_add_dr_scan(target->tap, bscan_tunnel_data_register_select_dmi_num_fields,
287                                                                                 bscan_tunnel_data_register_select_dmi, TAP_IDLE);
288         else /* BSCAN_TUNNEL_NESTED_TAP */
289                 jtag_add_dr_scan(target->tap, bscan_tunnel_nested_tap_select_dmi_num_fields,
290                                                                                 bscan_tunnel_nested_tap_select_dmi, TAP_IDLE);
291 }
292
293 uint32_t dtmcontrol_scan_via_bscan(struct target *target, uint32_t out)
294 {
295         /* On BSCAN TAP: Select IR=USER4, issue tunneled IR scan via BSCAN TAP's DR */
296         uint8_t tunneled_ir_width[4] = {bscan_tunnel_ir_width};
297         uint8_t tunneled_dr_width[4] = {32};
298         uint8_t out_value[5] = {0};
299         uint8_t in_value[5] = {0};
300
301         buf_set_u32(out_value, 0, 32, out);
302         struct scan_field tunneled_ir[4] = {};
303         struct scan_field tunneled_dr[4] = {};
304
305         if (bscan_tunnel_type == BSCAN_TUNNEL_DATA_REGISTER) {
306                 tunneled_ir[0].num_bits = 3;
307                 tunneled_ir[0].out_value = bscan_zero;
308                 tunneled_ir[0].in_value = NULL;
309                 tunneled_ir[1].num_bits = bscan_tunnel_ir_width;
310                 tunneled_ir[1].out_value = ir_dtmcontrol;
311                 tunneled_ir[1].in_value = NULL;
312                 tunneled_ir[2].num_bits = 7;
313                 tunneled_ir[2].out_value = tunneled_ir_width;
314                 tunneled_ir[2].in_value = NULL;
315                 tunneled_ir[3].num_bits = 1;
316                 tunneled_ir[3].out_value = bscan_zero;
317                 tunneled_ir[3].in_value = NULL;
318
319                 tunneled_dr[0].num_bits = 3;
320                 tunneled_dr[0].out_value = bscan_zero;
321                 tunneled_dr[0].in_value = NULL;
322                 tunneled_dr[1].num_bits = 32 + 1;
323                 tunneled_dr[1].out_value = out_value;
324                 tunneled_dr[1].in_value = in_value;
325                 tunneled_dr[2].num_bits = 7;
326                 tunneled_dr[2].out_value = tunneled_dr_width;
327                 tunneled_dr[2].in_value = NULL;
328                 tunneled_dr[3].num_bits = 1;
329                 tunneled_dr[3].out_value = bscan_one;
330                 tunneled_dr[3].in_value = NULL;
331         } else {
332                 /* BSCAN_TUNNEL_NESTED_TAP */
333                 tunneled_ir[3].num_bits = 3;
334                 tunneled_ir[3].out_value = bscan_zero;
335                 tunneled_ir[3].in_value = NULL;
336                 tunneled_ir[2].num_bits = bscan_tunnel_ir_width;
337                 tunneled_ir[2].out_value = ir_dtmcontrol;
338                 tunneled_ir[1].in_value = NULL;
339                 tunneled_ir[1].num_bits = 7;
340                 tunneled_ir[1].out_value = tunneled_ir_width;
341                 tunneled_ir[2].in_value = NULL;
342                 tunneled_ir[0].num_bits = 1;
343                 tunneled_ir[0].out_value = bscan_zero;
344                 tunneled_ir[0].in_value = NULL;
345
346                 tunneled_dr[3].num_bits = 3;
347                 tunneled_dr[3].out_value = bscan_zero;
348                 tunneled_dr[3].in_value = NULL;
349                 tunneled_dr[2].num_bits = 32 + 1;
350                 tunneled_dr[2].out_value = out_value;
351                 tunneled_dr[2].in_value = in_value;
352                 tunneled_dr[1].num_bits = 7;
353                 tunneled_dr[1].out_value = tunneled_dr_width;
354                 tunneled_dr[1].in_value = NULL;
355                 tunneled_dr[0].num_bits = 1;
356                 tunneled_dr[0].out_value = bscan_one;
357                 tunneled_dr[0].in_value = NULL;
358         }
359         jtag_add_ir_scan(target->tap, &select_user4, TAP_IDLE);
360         jtag_add_dr_scan(target->tap, ARRAY_SIZE(tunneled_ir), tunneled_ir, TAP_IDLE);
361         jtag_add_dr_scan(target->tap, ARRAY_SIZE(tunneled_dr), tunneled_dr, TAP_IDLE);
362         select_dmi_via_bscan(target);
363
364         int retval = jtag_execute_queue();
365         if (retval != ERROR_OK) {
366                 LOG_ERROR("failed jtag scan: %d", retval);
367                 return retval;
368         }
369         /* Note the starting offset is bit 1, not bit 0.  In BSCAN tunnel, there is a one-bit TCK skew between
370            output and input */
371         uint32_t in = buf_get_u32(in_value, 1, 32);
372         LOG_DEBUG("DTMCS: 0x%x -> 0x%x", out, in);
373
374         return in;
375 }
376
377 static uint32_t dtmcontrol_scan(struct target *target, uint32_t out)
378 {
379         struct scan_field field;
380         uint8_t in_value[4];
381         uint8_t out_value[4] = { 0 };
382
383         if (bscan_tunnel_ir_width != 0)
384                 return dtmcontrol_scan_via_bscan(target, out);
385
386
387         buf_set_u32(out_value, 0, 32, out);
388
389         jtag_add_ir_scan(target->tap, &select_dtmcontrol, TAP_IDLE);
390
391         field.num_bits = 32;
392         field.out_value = out_value;
393         field.in_value = in_value;
394         jtag_add_dr_scan(target->tap, 1, &field, TAP_IDLE);
395
396         /* Always return to dbus. */
397         jtag_add_ir_scan(target->tap, &select_dbus, TAP_IDLE);
398
399         int retval = jtag_execute_queue();
400         if (retval != ERROR_OK) {
401                 LOG_ERROR("failed jtag scan: %d", retval);
402                 return retval;
403         }
404
405         uint32_t in = buf_get_u32(field.in_value, 0, 32);
406         LOG_DEBUG("DTMCONTROL: 0x%x -> 0x%x", out, in);
407
408         return in;
409 }
410
411 static struct target_type *get_target_type(struct target *target)
412 {
413         if (!target->arch_info) {
414                 LOG_ERROR("Target has not been initialized");
415                 return NULL;
416         }
417
418         RISCV_INFO(info);
419         switch (info->dtm_version) {
420                 case 0:
421                         return &riscv011_target;
422                 case 1:
423                         return &riscv013_target;
424                 default:
425                         LOG_ERROR("Unsupported DTM version: %d", info->dtm_version);
426                         return NULL;
427         }
428 }
429
430 static int riscv_create_target(struct target *target, Jim_Interp *interp)
431 {
432         LOG_DEBUG("riscv_create_target()");
433         target->arch_info = calloc(1, sizeof(struct riscv_info));
434         if (!target->arch_info) {
435                 LOG_ERROR("Failed to allocate RISC-V target structure.");
436                 return ERROR_FAIL;
437         }
438         riscv_info_init(target, target->arch_info);
439         return ERROR_OK;
440 }
441
442 static int riscv_init_target(struct command_context *cmd_ctx,
443                 struct target *target)
444 {
445         LOG_DEBUG("riscv_init_target()");
446         RISCV_INFO(info);
447         info->cmd_ctx = cmd_ctx;
448
449         select_dtmcontrol.num_bits = target->tap->ir_length;
450         select_dbus.num_bits = target->tap->ir_length;
451         select_idcode.num_bits = target->tap->ir_length;
452
453         if (bscan_tunnel_ir_width != 0) {
454                 assert(target->tap->ir_length >= 6);
455                 uint32_t ir_user4_raw = 0x23 << (target->tap->ir_length - 6);
456                 h_u32_to_le(ir_user4, ir_user4_raw);
457                 select_user4.num_bits = target->tap->ir_length;
458                 bscan_tunneled_ir_width[0] = bscan_tunnel_ir_width;
459                 if (bscan_tunnel_type == BSCAN_TUNNEL_DATA_REGISTER)
460                         bscan_tunnel_data_register_select_dmi[1].num_bits = bscan_tunnel_ir_width;
461                 else /* BSCAN_TUNNEL_NESTED_TAP */
462                         bscan_tunnel_nested_tap_select_dmi[2].num_bits = bscan_tunnel_ir_width;
463         }
464
465         riscv_semihosting_init(target);
466
467         target->debug_reason = DBG_REASON_DBGRQ;
468
469         return ERROR_OK;
470 }
471
472 static void riscv_free_registers(struct target *target)
473 {
474         /* Free the shared structure use for most registers. */
475         if (target->reg_cache) {
476                 if (target->reg_cache->reg_list) {
477                         free(target->reg_cache->reg_list[0].arch_info);
478                         /* Free the ones we allocated separately. */
479                         for (unsigned i = GDB_REGNO_COUNT; i < target->reg_cache->num_regs; i++)
480                                 free(target->reg_cache->reg_list[i].arch_info);
481                         for (unsigned int i = 0; i < target->reg_cache->num_regs; i++)
482                                 free(target->reg_cache->reg_list[i].value);
483                         free(target->reg_cache->reg_list);
484                 }
485                 free(target->reg_cache);
486         }
487 }
488
489 static void riscv_deinit_target(struct target *target)
490 {
491         LOG_DEBUG("riscv_deinit_target()");
492
493         struct riscv_info *info = target->arch_info;
494         struct target_type *tt = get_target_type(target);
495
496         if (tt && info && info->version_specific)
497                 tt->deinit_target(target);
498
499         riscv_free_registers(target);
500
501         if (!info)
502                 return;
503
504         range_list_t *entry, *tmp;
505         list_for_each_entry_safe(entry, tmp, &info->expose_csr, list) {
506                 free(entry->name);
507                 free(entry);
508         }
509
510         list_for_each_entry_safe(entry, tmp, &info->expose_custom, list) {
511                 free(entry->name);
512                 free(entry);
513         }
514
515         free(info->reg_names);
516         free(target->arch_info);
517
518         target->arch_info = NULL;
519 }
520
521 static void trigger_from_breakpoint(struct trigger *trigger,
522                 const struct breakpoint *breakpoint)
523 {
524         trigger->address = breakpoint->address;
525         trigger->length = breakpoint->length;
526         trigger->mask = ~0LL;
527         trigger->read = false;
528         trigger->write = false;
529         trigger->execute = true;
530         /* unique_id is unique across both breakpoints and watchpoints. */
531         trigger->unique_id = breakpoint->unique_id;
532 }
533
534 static int maybe_add_trigger_t1(struct target *target,
535                 struct trigger *trigger, uint64_t tdata1)
536 {
537         RISCV_INFO(r);
538
539         const uint32_t bpcontrol_x = 1<<0;
540         const uint32_t bpcontrol_w = 1<<1;
541         const uint32_t bpcontrol_r = 1<<2;
542         const uint32_t bpcontrol_u = 1<<3;
543         const uint32_t bpcontrol_s = 1<<4;
544         const uint32_t bpcontrol_h = 1<<5;
545         const uint32_t bpcontrol_m = 1<<6;
546         const uint32_t bpcontrol_bpmatch = 0xf << 7;
547         const uint32_t bpcontrol_bpaction = 0xff << 11;
548
549         if (tdata1 & (bpcontrol_r | bpcontrol_w | bpcontrol_x)) {
550                 /* Trigger is already in use, presumably by user code. */
551                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
552         }
553
554         tdata1 = set_field(tdata1, bpcontrol_r, trigger->read);
555         tdata1 = set_field(tdata1, bpcontrol_w, trigger->write);
556         tdata1 = set_field(tdata1, bpcontrol_x, trigger->execute);
557         tdata1 = set_field(tdata1, bpcontrol_u,
558                         !!(r->misa & BIT('U' - 'A')));
559         tdata1 = set_field(tdata1, bpcontrol_s,
560                         !!(r->misa & BIT('S' - 'A')));
561         tdata1 = set_field(tdata1, bpcontrol_h,
562                         !!(r->misa & BIT('H' - 'A')));
563         tdata1 |= bpcontrol_m;
564         tdata1 = set_field(tdata1, bpcontrol_bpmatch, 0); /* exact match */
565         tdata1 = set_field(tdata1, bpcontrol_bpaction, 0); /* cause bp exception */
566
567         riscv_set_register(target, GDB_REGNO_TDATA1, tdata1);
568
569         riscv_reg_t tdata1_rb;
570         if (riscv_get_register(target, &tdata1_rb, GDB_REGNO_TDATA1) != ERROR_OK)
571                 return ERROR_FAIL;
572         LOG_DEBUG("tdata1=0x%" PRIx64, tdata1_rb);
573
574         if (tdata1 != tdata1_rb) {
575                 LOG_DEBUG("Trigger doesn't support what we need; After writing 0x%"
576                                 PRIx64 " to tdata1 it contains 0x%" PRIx64,
577                                 tdata1, tdata1_rb);
578                 riscv_set_register(target, GDB_REGNO_TDATA1, 0);
579                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
580         }
581
582         riscv_set_register(target, GDB_REGNO_TDATA2, trigger->address);
583
584         return ERROR_OK;
585 }
586
587 static int maybe_add_trigger_t2(struct target *target,
588                 struct trigger *trigger, uint64_t tdata1)
589 {
590         RISCV_INFO(r);
591
592         /* tselect is already set */
593         if (tdata1 & (MCONTROL_EXECUTE | MCONTROL_STORE | MCONTROL_LOAD)) {
594                 /* Trigger is already in use, presumably by user code. */
595                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
596         }
597
598         /* address/data match trigger */
599         tdata1 |= MCONTROL_DMODE(riscv_xlen(target));
600         tdata1 = set_field(tdata1, MCONTROL_ACTION,
601                         MCONTROL_ACTION_DEBUG_MODE);
602         tdata1 = set_field(tdata1, MCONTROL_MATCH, MCONTROL_MATCH_EQUAL);
603         tdata1 |= MCONTROL_M;
604         if (r->misa & (1 << ('S' - 'A')))
605                 tdata1 |= MCONTROL_S;
606         if (r->misa & (1 << ('U' - 'A')))
607                 tdata1 |= MCONTROL_U;
608
609         if (trigger->execute)
610                 tdata1 |= MCONTROL_EXECUTE;
611         if (trigger->read)
612                 tdata1 |= MCONTROL_LOAD;
613         if (trigger->write)
614                 tdata1 |= MCONTROL_STORE;
615
616         riscv_set_register(target, GDB_REGNO_TDATA1, tdata1);
617
618         uint64_t tdata1_rb;
619         int result = riscv_get_register(target, &tdata1_rb, GDB_REGNO_TDATA1);
620         if (result != ERROR_OK)
621                 return result;
622         LOG_DEBUG("tdata1=0x%" PRIx64, tdata1_rb);
623
624         if (tdata1 != tdata1_rb) {
625                 LOG_DEBUG("Trigger doesn't support what we need; After writing 0x%"
626                                 PRIx64 " to tdata1 it contains 0x%" PRIx64,
627                                 tdata1, tdata1_rb);
628                 riscv_set_register(target, GDB_REGNO_TDATA1, 0);
629                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
630         }
631
632         riscv_set_register(target, GDB_REGNO_TDATA2, trigger->address);
633
634         return ERROR_OK;
635 }
636
637 static int maybe_add_trigger_t6(struct target *target,
638                 struct trigger *trigger, uint64_t tdata1)
639 {
640         RISCV_INFO(r);
641
642         /* tselect is already set */
643         if (tdata1 & (CSR_MCONTROL6_EXECUTE | CSR_MCONTROL6_STORE | CSR_MCONTROL6_LOAD)) {
644                 /* Trigger is already in use, presumably by user code. */
645                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
646         }
647
648         /* address/data match trigger */
649         tdata1 |= MCONTROL_DMODE(riscv_xlen(target));
650         tdata1 = set_field(tdata1, CSR_MCONTROL6_ACTION,
651                         MCONTROL_ACTION_DEBUG_MODE);
652         tdata1 = set_field(tdata1, CSR_MCONTROL6_MATCH, MCONTROL_MATCH_EQUAL);
653         tdata1 |= CSR_MCONTROL6_M;
654         if (r->misa & (1 << ('H' - 'A')))
655                 tdata1 |= CSR_MCONTROL6_VS | CSR_MCONTROL6_VU;
656         if (r->misa & (1 << ('S' - 'A')))
657                 tdata1 |= CSR_MCONTROL6_S;
658         if (r->misa & (1 << ('U' - 'A')))
659                 tdata1 |= CSR_MCONTROL6_U;
660
661         if (trigger->execute)
662                 tdata1 |= CSR_MCONTROL6_EXECUTE;
663         if (trigger->read)
664                 tdata1 |= CSR_MCONTROL6_LOAD;
665         if (trigger->write)
666                 tdata1 |= CSR_MCONTROL6_STORE;
667
668         riscv_set_register(target, GDB_REGNO_TDATA1, tdata1);
669
670         uint64_t tdata1_rb;
671         int result = riscv_get_register(target, &tdata1_rb, GDB_REGNO_TDATA1);
672         if (result != ERROR_OK)
673                 return result;
674         LOG_DEBUG("tdata1=0x%" PRIx64, tdata1_rb);
675
676         if (tdata1 != tdata1_rb) {
677                 LOG_DEBUG("Trigger doesn't support what we need; After writing 0x%"
678                                 PRIx64 " to tdata1 it contains 0x%" PRIx64,
679                                 tdata1, tdata1_rb);
680                 riscv_set_register(target, GDB_REGNO_TDATA1, 0);
681                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
682         }
683
684         riscv_set_register(target, GDB_REGNO_TDATA2, trigger->address);
685
686         return ERROR_OK;
687 }
688
689 static int add_trigger(struct target *target, struct trigger *trigger)
690 {
691         RISCV_INFO(r);
692
693         if (riscv_enumerate_triggers(target) != ERROR_OK)
694                 return ERROR_FAIL;
695
696         riscv_reg_t tselect;
697         if (riscv_get_register(target, &tselect, GDB_REGNO_TSELECT) != ERROR_OK)
698                 return ERROR_FAIL;
699
700         unsigned int i;
701         for (i = 0; i < r->trigger_count; i++) {
702                 if (r->trigger_unique_id[i] != -1)
703                         continue;
704
705                 riscv_set_register(target, GDB_REGNO_TSELECT, i);
706
707                 uint64_t tdata1;
708                 int result = riscv_get_register(target, &tdata1, GDB_REGNO_TDATA1);
709                 if (result != ERROR_OK)
710                         return result;
711                 int type = get_field(tdata1, MCONTROL_TYPE(riscv_xlen(target)));
712
713                 switch (type) {
714                         case 1:
715                                 result = maybe_add_trigger_t1(target, trigger, tdata1);
716                                 break;
717                         case 2:
718                                 result = maybe_add_trigger_t2(target, trigger, tdata1);
719                                 break;
720                         case 6:
721                                 result = maybe_add_trigger_t6(target, trigger, tdata1);
722                                 break;
723                         default:
724                                 LOG_DEBUG("trigger %d has unknown type %d", i, type);
725                                 continue;
726                 }
727
728                 if (result != ERROR_OK)
729                         continue;
730
731                 LOG_DEBUG("[%d] Using trigger %d (type %d) for bp %d", target->coreid,
732                                 i, type, trigger->unique_id);
733                 r->trigger_unique_id[i] = trigger->unique_id;
734                 break;
735         }
736
737         riscv_set_register(target, GDB_REGNO_TSELECT, tselect);
738
739         if (i >= r->trigger_count) {
740                 LOG_ERROR("Couldn't find an available hardware trigger.");
741                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
742         }
743
744         return ERROR_OK;
745 }
746
747 /**
748  * Write one memory item of given "size". Use memory access of given "access_size".
749  * Utilize read-modify-write, if needed.
750  * */
751 static int write_by_given_size(struct target *target, target_addr_t address,
752                 uint32_t size, uint8_t *buffer, uint32_t access_size)
753 {
754         assert(size == 1 || size == 2 || size == 4 || size == 8);
755         assert(access_size == 1 || access_size == 2 || access_size == 4 || access_size == 8);
756
757         if (access_size <= size && address % access_size == 0)
758                 /* Can do the memory access directly without a helper buffer. */
759                 return target_write_memory(target, address, access_size, size / access_size, buffer);
760
761         unsigned int offset_head = address % access_size;
762         unsigned int n_blocks = ((size + offset_head) <= access_size) ? 1 : 2;
763         uint8_t helper_buf[n_blocks * access_size];
764
765         /* Read from memory */
766         if (target_read_memory(target, address - offset_head, access_size, n_blocks, helper_buf) != ERROR_OK)
767                 return ERROR_FAIL;
768
769         /* Modify and write back */
770         memcpy(helper_buf + offset_head, buffer, size);
771         return target_write_memory(target, address - offset_head, access_size, n_blocks, helper_buf);
772 }
773
774 /**
775  * Read one memory item of given "size". Use memory access of given "access_size".
776  * Read larger section of memory and pick out the required portion, if needed.
777  * */
778 static int read_by_given_size(struct target *target, target_addr_t address,
779         uint32_t size, uint8_t *buffer, uint32_t access_size)
780 {
781         assert(size == 1 || size == 2 || size == 4 || size == 8);
782         assert(access_size == 1 || access_size == 2 || access_size == 4 || access_size == 8);
783
784         if (access_size <= size && address % access_size == 0)
785                 /* Can do the memory access directly without a helper buffer. */
786                 return target_read_memory(target, address, access_size, size / access_size, buffer);
787
788         unsigned int offset_head = address % access_size;
789         unsigned int n_blocks = ((size + offset_head) <= access_size) ? 1 : 2;
790         uint8_t helper_buf[n_blocks * access_size];
791
792         /* Read from memory */
793         if (target_read_memory(target, address - offset_head, access_size, n_blocks, helper_buf) != ERROR_OK)
794                 return ERROR_FAIL;
795
796         /* Pick the requested portion from the buffer */
797         memcpy(buffer, helper_buf + offset_head, size);
798         return ERROR_OK;
799 }
800
801 /**
802  * Write one memory item using any memory access size that will work.
803  * Utilize read-modify-write, if needed.
804  * */
805 int riscv_write_by_any_size(struct target *target, target_addr_t address, uint32_t size, uint8_t *buffer)
806 {
807         assert(size == 1 || size == 2 ||  size == 4 || size == 8);
808
809         /* Find access size that correspond to data size and the alignment. */
810         unsigned int preferred_size = size;
811         while (address % preferred_size != 0)
812                 preferred_size /= 2;
813
814         /* First try the preferred (most natural) access size. */
815         if (write_by_given_size(target, address, size, buffer, preferred_size) == ERROR_OK)
816                 return ERROR_OK;
817
818         /* On failure, try other access sizes.
819            Minimize the number of accesses by trying first the largest size. */
820         for (unsigned int access_size = 8; access_size > 0; access_size /= 2) {
821                 if (access_size == preferred_size)
822                         /* Already tried this size. */
823                         continue;
824
825                 if (write_by_given_size(target, address, size, buffer, access_size) == ERROR_OK)
826                         return ERROR_OK;
827         }
828
829         /* No access attempt succeeded. */
830         return ERROR_FAIL;
831 }
832
833 /**
834  * Read one memory item using any memory access size that will work.
835  * Read larger section of memory and pick out the required portion, if needed.
836  * */
837 int riscv_read_by_any_size(struct target *target, target_addr_t address, uint32_t size, uint8_t *buffer)
838 {
839         assert(size == 1 || size == 2 ||  size == 4 || size == 8);
840
841         /* Find access size that correspond to data size and the alignment. */
842         unsigned int preferred_size = size;
843         while (address % preferred_size != 0)
844                 preferred_size /= 2;
845
846         /* First try the preferred (most natural) access size. */
847         if (read_by_given_size(target, address, size, buffer, preferred_size) == ERROR_OK)
848                 return ERROR_OK;
849
850         /* On failure, try other access sizes.
851            Minimize the number of accesses by trying first the largest size. */
852         for (unsigned int access_size = 8; access_size > 0; access_size /= 2) {
853                 if (access_size == preferred_size)
854                         /* Already tried this size. */
855                         continue;
856
857                 if (read_by_given_size(target, address, size, buffer, access_size) == ERROR_OK)
858                         return ERROR_OK;
859         }
860
861         /* No access attempt succeeded. */
862         return ERROR_FAIL;
863 }
864
865 static int riscv_add_breakpoint(struct target *target, struct breakpoint *breakpoint)
866 {
867         LOG_DEBUG("[%d] @0x%" TARGET_PRIxADDR, target->coreid, breakpoint->address);
868         assert(breakpoint);
869         if (breakpoint->type == BKPT_SOFT) {
870                 /** @todo check RVC for size/alignment */
871                 if (!(breakpoint->length == 4 || breakpoint->length == 2)) {
872                         LOG_ERROR("Invalid breakpoint length %d", breakpoint->length);
873                         return ERROR_FAIL;
874                 }
875
876                 if (0 != (breakpoint->address % 2)) {
877                         LOG_ERROR("Invalid breakpoint alignment for address 0x%" TARGET_PRIxADDR, breakpoint->address);
878                         return ERROR_FAIL;
879                 }
880
881                 /* Read the original instruction. */
882                 if (riscv_read_by_any_size(
883                                 target, breakpoint->address, breakpoint->length, breakpoint->orig_instr) != ERROR_OK) {
884                         LOG_ERROR("Failed to read original instruction at 0x%" TARGET_PRIxADDR,
885                                         breakpoint->address);
886                         return ERROR_FAIL;
887                 }
888
889                 uint8_t buff[4] = { 0 };
890                 buf_set_u32(buff, 0, breakpoint->length * CHAR_BIT, breakpoint->length == 4 ? ebreak() : ebreak_c());
891                 /* Write the ebreak instruction. */
892                 if (riscv_write_by_any_size(target, breakpoint->address, breakpoint->length, buff) != ERROR_OK) {
893                         LOG_ERROR("Failed to write %d-byte breakpoint instruction at 0x%"
894                                         TARGET_PRIxADDR, breakpoint->length, breakpoint->address);
895                         return ERROR_FAIL;
896                 }
897
898         } else if (breakpoint->type == BKPT_HARD) {
899                 struct trigger trigger;
900                 trigger_from_breakpoint(&trigger, breakpoint);
901                 int const result = add_trigger(target, &trigger);
902                 if (result != ERROR_OK)
903                         return result;
904         } else {
905                 LOG_INFO("OpenOCD only supports hardware and software breakpoints.");
906                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
907         }
908
909         breakpoint->is_set = true;
910         return ERROR_OK;
911 }
912
913 static int remove_trigger(struct target *target, struct trigger *trigger)
914 {
915         RISCV_INFO(r);
916
917         if (riscv_enumerate_triggers(target) != ERROR_OK)
918                 return ERROR_FAIL;
919
920         unsigned int i;
921         for (i = 0; i < r->trigger_count; i++) {
922                 if (r->trigger_unique_id[i] == trigger->unique_id)
923                         break;
924         }
925         if (i >= r->trigger_count) {
926                 LOG_ERROR("Couldn't find the hardware resources used by hardware "
927                                 "trigger.");
928                 return ERROR_FAIL;
929         }
930         LOG_DEBUG("[%d] Stop using resource %d for bp %d", target->coreid, i,
931                         trigger->unique_id);
932
933         riscv_reg_t tselect;
934         int result = riscv_get_register(target, &tselect, GDB_REGNO_TSELECT);
935         if (result != ERROR_OK)
936                 return result;
937         riscv_set_register(target, GDB_REGNO_TSELECT, i);
938         riscv_set_register(target, GDB_REGNO_TDATA1, 0);
939         riscv_set_register(target, GDB_REGNO_TSELECT, tselect);
940         r->trigger_unique_id[i] = -1;
941
942         return ERROR_OK;
943 }
944
945 static int riscv_remove_breakpoint(struct target *target,
946                 struct breakpoint *breakpoint)
947 {
948         if (breakpoint->type == BKPT_SOFT) {
949                 /* Write the original instruction. */
950                 if (riscv_write_by_any_size(
951                                 target, breakpoint->address, breakpoint->length, breakpoint->orig_instr) != ERROR_OK) {
952                         LOG_ERROR("Failed to restore instruction for %d-byte breakpoint at "
953                                         "0x%" TARGET_PRIxADDR, breakpoint->length, breakpoint->address);
954                         return ERROR_FAIL;
955                 }
956
957         } else if (breakpoint->type == BKPT_HARD) {
958                 struct trigger trigger;
959                 trigger_from_breakpoint(&trigger, breakpoint);
960                 int result = remove_trigger(target, &trigger);
961                 if (result != ERROR_OK)
962                         return result;
963
964         } else {
965                 LOG_INFO("OpenOCD only supports hardware and software breakpoints.");
966                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
967         }
968
969         breakpoint->is_set = false;
970
971         return ERROR_OK;
972 }
973
974 static void trigger_from_watchpoint(struct trigger *trigger,
975                 const struct watchpoint *watchpoint)
976 {
977         trigger->address = watchpoint->address;
978         trigger->length = watchpoint->length;
979         trigger->mask = watchpoint->mask;
980         trigger->value = watchpoint->value;
981         trigger->read = (watchpoint->rw == WPT_READ || watchpoint->rw == WPT_ACCESS);
982         trigger->write = (watchpoint->rw == WPT_WRITE || watchpoint->rw == WPT_ACCESS);
983         trigger->execute = false;
984         /* unique_id is unique across both breakpoints and watchpoints. */
985         trigger->unique_id = watchpoint->unique_id;
986 }
987
988 int riscv_add_watchpoint(struct target *target, struct watchpoint *watchpoint)
989 {
990         struct trigger trigger;
991         trigger_from_watchpoint(&trigger, watchpoint);
992
993         int result = add_trigger(target, &trigger);
994         if (result != ERROR_OK)
995                 return result;
996         watchpoint->is_set = true;
997
998         return ERROR_OK;
999 }
1000
1001 int riscv_remove_watchpoint(struct target *target,
1002                 struct watchpoint *watchpoint)
1003 {
1004         LOG_DEBUG("[%d] @0x%" TARGET_PRIxADDR, target->coreid, watchpoint->address);
1005
1006         struct trigger trigger;
1007         trigger_from_watchpoint(&trigger, watchpoint);
1008
1009         int result = remove_trigger(target, &trigger);
1010         if (result != ERROR_OK)
1011                 return result;
1012         watchpoint->is_set = false;
1013
1014         return ERROR_OK;
1015 }
1016
1017 /* Sets *hit_watchpoint to the first watchpoint identified as causing the
1018  * current halt.
1019  *
1020  * The GDB server uses this information to tell GDB what data address has
1021  * been hit, which enables GDB to print the hit variable along with its old
1022  * and new value. */
1023 static int riscv_hit_watchpoint(struct target *target, struct watchpoint **hit_watchpoint)
1024 {
1025         struct watchpoint *wp = target->watchpoints;
1026
1027         LOG_DEBUG("Current hartid = %d", riscv_current_hartid(target));
1028
1029         /*TODO instead of disassembling the instruction that we think caused the
1030          * trigger, check the hit bit of each watchpoint first. The hit bit is
1031          * simpler and more reliable to check but as it is optional and relatively
1032          * new, not all hardware will implement it  */
1033         riscv_reg_t dpc;
1034         riscv_get_register(target, &dpc, GDB_REGNO_DPC);
1035         const uint8_t length = 4;
1036         LOG_DEBUG("dpc is 0x%" PRIx64, dpc);
1037
1038         /* fetch the instruction at dpc */
1039         uint8_t buffer[length];
1040         if (target_read_buffer(target, dpc, length, buffer) != ERROR_OK) {
1041                 LOG_ERROR("Failed to read instruction at dpc 0x%" PRIx64, dpc);
1042                 return ERROR_FAIL;
1043         }
1044
1045         uint32_t instruction = 0;
1046
1047         for (int i = 0; i < length; i++) {
1048                 LOG_DEBUG("Next byte is %x", buffer[i]);
1049                 instruction += (buffer[i] << 8 * i);
1050         }
1051         LOG_DEBUG("Full instruction is %x", instruction);
1052
1053         /* find out which memory address is accessed by the instruction at dpc */
1054         /* opcode is first 7 bits of the instruction */
1055         uint8_t opcode = instruction & 0x7F;
1056         uint32_t rs1;
1057         int16_t imm;
1058         riscv_reg_t mem_addr;
1059
1060         if (opcode == MATCH_LB || opcode == MATCH_SB) {
1061                 rs1 = (instruction & 0xf8000) >> 15;
1062                 riscv_get_register(target, &mem_addr, rs1);
1063
1064                 if (opcode == MATCH_SB) {
1065                         LOG_DEBUG("%x is store instruction", instruction);
1066                         imm = ((instruction & 0xf80) >> 7) | ((instruction & 0xfe000000) >> 20);
1067                 } else {
1068                         LOG_DEBUG("%x is load instruction", instruction);
1069                         imm = (instruction & 0xfff00000) >> 20;
1070                 }
1071                 /* sign extend 12-bit imm to 16-bits */
1072                 if (imm & (1 << 11))
1073                         imm |= 0xf000;
1074                 mem_addr += imm;
1075                 LOG_DEBUG("memory address=0x%" PRIx64, mem_addr);
1076         } else {
1077                 LOG_DEBUG("%x is not a RV32I load or store", instruction);
1078                 return ERROR_FAIL;
1079         }
1080
1081         while (wp) {
1082                 /*TODO support length/mask */
1083                 if (wp->address == mem_addr) {
1084                         *hit_watchpoint = wp;
1085                         LOG_DEBUG("Hit address=%" TARGET_PRIxADDR, wp->address);
1086                         return ERROR_OK;
1087                 }
1088                 wp = wp->next;
1089         }
1090
1091         /* No match found - either we hit a watchpoint caused by an instruction that
1092          * this function does not yet disassemble, or we hit a breakpoint.
1093          *
1094          * OpenOCD will behave as if this function had never been implemented i.e.
1095          * report the halt to GDB with no address information. */
1096         return ERROR_FAIL;
1097 }
1098
1099
1100 static int oldriscv_step(struct target *target, int current, uint32_t address,
1101                 int handle_breakpoints)
1102 {
1103         struct target_type *tt = get_target_type(target);
1104         return tt->step(target, current, address, handle_breakpoints);
1105 }
1106
1107 static int old_or_new_riscv_step(struct target *target, int current,
1108                 target_addr_t address, int handle_breakpoints)
1109 {
1110         RISCV_INFO(r);
1111         LOG_DEBUG("handle_breakpoints=%d", handle_breakpoints);
1112         if (!r->is_halted)
1113                 return oldriscv_step(target, current, address, handle_breakpoints);
1114         else
1115                 return riscv_openocd_step(target, current, address, handle_breakpoints);
1116 }
1117
1118
1119 static int riscv_examine(struct target *target)
1120 {
1121         LOG_DEBUG("riscv_examine()");
1122         if (target_was_examined(target)) {
1123                 LOG_DEBUG("Target was already examined.");
1124                 return ERROR_OK;
1125         }
1126
1127         /* Don't need to select dbus, since the first thing we do is read dtmcontrol. */
1128
1129         RISCV_INFO(info);
1130         uint32_t dtmcontrol = dtmcontrol_scan(target, 0);
1131         LOG_DEBUG("dtmcontrol=0x%x", dtmcontrol);
1132         info->dtm_version = get_field(dtmcontrol, DTMCONTROL_VERSION);
1133         LOG_DEBUG("  version=0x%x", info->dtm_version);
1134
1135         struct target_type *tt = get_target_type(target);
1136         if (!tt)
1137                 return ERROR_FAIL;
1138
1139         int result = tt->init_target(info->cmd_ctx, target);
1140         if (result != ERROR_OK)
1141                 return result;
1142
1143         return tt->examine(target);
1144 }
1145
1146 static int oldriscv_poll(struct target *target)
1147 {
1148         struct target_type *tt = get_target_type(target);
1149         return tt->poll(target);
1150 }
1151
1152 static int old_or_new_riscv_poll(struct target *target)
1153 {
1154         RISCV_INFO(r);
1155         if (!r->is_halted)
1156                 return oldriscv_poll(target);
1157         else
1158                 return riscv_openocd_poll(target);
1159 }
1160
1161 int riscv_select_current_hart(struct target *target)
1162 {
1163         return riscv_set_current_hartid(target, target->coreid);
1164 }
1165
1166 static int halt_prep(struct target *target)
1167 {
1168         RISCV_INFO(r);
1169
1170         LOG_DEBUG("[%s] prep hart, debug_reason=%d", target_name(target),
1171                                 target->debug_reason);
1172         if (riscv_select_current_hart(target) != ERROR_OK)
1173                 return ERROR_FAIL;
1174         if (riscv_is_halted(target)) {
1175                 LOG_DEBUG("[%s] Hart is already halted (reason=%d).",
1176                                 target_name(target), target->debug_reason);
1177         } else {
1178                 if (r->halt_prep(target) != ERROR_OK)
1179                         return ERROR_FAIL;
1180                 r->prepped = true;
1181         }
1182
1183         return ERROR_OK;
1184 }
1185
1186 static int riscv_halt_go_all_harts(struct target *target)
1187 {
1188         RISCV_INFO(r);
1189
1190         if (riscv_select_current_hart(target) != ERROR_OK)
1191                 return ERROR_FAIL;
1192         if (riscv_is_halted(target)) {
1193                 LOG_DEBUG("[%s] Hart is already halted.", target_name(target));
1194         } else {
1195                 if (r->halt_go(target) != ERROR_OK)
1196                         return ERROR_FAIL;
1197         }
1198
1199         riscv_invalidate_register_cache(target);
1200
1201         return ERROR_OK;
1202 }
1203
1204 static int halt_go(struct target *target)
1205 {
1206         RISCV_INFO(r);
1207         int result;
1208         if (!r->is_halted) {
1209                 struct target_type *tt = get_target_type(target);
1210                 result = tt->halt(target);
1211         } else {
1212                 result = riscv_halt_go_all_harts(target);
1213         }
1214         target->state = TARGET_HALTED;
1215         if (target->debug_reason == DBG_REASON_NOTHALTED)
1216                 target->debug_reason = DBG_REASON_DBGRQ;
1217
1218         return result;
1219 }
1220
1221 static int halt_finish(struct target *target)
1222 {
1223         return target_call_event_callbacks(target, TARGET_EVENT_HALTED);
1224 }
1225
1226 int riscv_halt(struct target *target)
1227 {
1228         RISCV_INFO(r);
1229
1230         if (!r->is_halted) {
1231                 struct target_type *tt = get_target_type(target);
1232                 return tt->halt(target);
1233         }
1234
1235         LOG_DEBUG("[%d] halting all harts", target->coreid);
1236
1237         int result = ERROR_OK;
1238         if (target->smp) {
1239                 struct target_list *tlist;
1240                 foreach_smp_target(tlist, target->smp_targets) {
1241                         struct target *t = tlist->target;
1242                         if (halt_prep(t) != ERROR_OK)
1243                                 result = ERROR_FAIL;
1244                 }
1245
1246                 foreach_smp_target(tlist, target->smp_targets) {
1247                         struct target *t = tlist->target;
1248                         struct riscv_info *i = riscv_info(t);
1249                         if (i->prepped) {
1250                                 if (halt_go(t) != ERROR_OK)
1251                                         result = ERROR_FAIL;
1252                         }
1253                 }
1254
1255                 foreach_smp_target(tlist, target->smp_targets) {
1256                         struct target *t = tlist->target;
1257                         if (halt_finish(t) != ERROR_OK)
1258                                 return ERROR_FAIL;
1259                 }
1260
1261         } else {
1262                 if (halt_prep(target) != ERROR_OK)
1263                         result = ERROR_FAIL;
1264                 if (halt_go(target) != ERROR_OK)
1265                         result = ERROR_FAIL;
1266                 if (halt_finish(target) != ERROR_OK)
1267                         return ERROR_FAIL;
1268         }
1269
1270         return result;
1271 }
1272
1273 static int riscv_assert_reset(struct target *target)
1274 {
1275         LOG_DEBUG("[%d]", target->coreid);
1276         struct target_type *tt = get_target_type(target);
1277         riscv_invalidate_register_cache(target);
1278         return tt->assert_reset(target);
1279 }
1280
1281 static int riscv_deassert_reset(struct target *target)
1282 {
1283         LOG_DEBUG("[%d]", target->coreid);
1284         struct target_type *tt = get_target_type(target);
1285         return tt->deassert_reset(target);
1286 }
1287
1288 static int riscv_resume_prep_all_harts(struct target *target)
1289 {
1290         RISCV_INFO(r);
1291
1292         LOG_DEBUG("[%s] prep hart", target_name(target));
1293         if (riscv_select_current_hart(target) != ERROR_OK)
1294                 return ERROR_FAIL;
1295         if (riscv_is_halted(target)) {
1296                 if (r->resume_prep(target) != ERROR_OK)
1297                         return ERROR_FAIL;
1298         } else {
1299                 LOG_DEBUG("[%s] hart requested resume, but was already resumed",
1300                                 target_name(target));
1301         }
1302
1303         LOG_DEBUG("[%s] mark as prepped", target_name(target));
1304         r->prepped = true;
1305
1306         return ERROR_OK;
1307 }
1308
1309 /* state must be riscv_reg_t state[RISCV_MAX_HWBPS] = {0}; */
1310 static int disable_triggers(struct target *target, riscv_reg_t *state)
1311 {
1312         RISCV_INFO(r);
1313
1314         LOG_DEBUG("deal with triggers");
1315
1316         if (riscv_enumerate_triggers(target) != ERROR_OK)
1317                 return ERROR_FAIL;
1318
1319         if (r->manual_hwbp_set) {
1320                 /* Look at every trigger that may have been set. */
1321                 riscv_reg_t tselect;
1322                 if (riscv_get_register(target, &tselect, GDB_REGNO_TSELECT) != ERROR_OK)
1323                         return ERROR_FAIL;
1324                 for (unsigned int t = 0; t < r->trigger_count; t++) {
1325                         if (riscv_set_register(target, GDB_REGNO_TSELECT, t) != ERROR_OK)
1326                                 return ERROR_FAIL;
1327                         riscv_reg_t tdata1;
1328                         if (riscv_get_register(target, &tdata1, GDB_REGNO_TDATA1) != ERROR_OK)
1329                                 return ERROR_FAIL;
1330                         if (tdata1 & MCONTROL_DMODE(riscv_xlen(target))) {
1331                                 state[t] = tdata1;
1332                                 if (riscv_set_register(target, GDB_REGNO_TDATA1, 0) != ERROR_OK)
1333                                         return ERROR_FAIL;
1334                         }
1335                 }
1336                 if (riscv_set_register(target, GDB_REGNO_TSELECT, tselect) != ERROR_OK)
1337                         return ERROR_FAIL;
1338
1339         } else {
1340                 /* Just go through the triggers we manage. */
1341                 struct watchpoint *watchpoint = target->watchpoints;
1342                 int i = 0;
1343                 while (watchpoint) {
1344                         LOG_DEBUG("watchpoint %d: set=%d", i, watchpoint->is_set);
1345                         state[i] = watchpoint->is_set;
1346                         if (watchpoint->is_set) {
1347                                 if (riscv_remove_watchpoint(target, watchpoint) != ERROR_OK)
1348                                         return ERROR_FAIL;
1349                         }
1350                         watchpoint = watchpoint->next;
1351                         i++;
1352                 }
1353         }
1354
1355         return ERROR_OK;
1356 }
1357
1358 static int enable_triggers(struct target *target, riscv_reg_t *state)
1359 {
1360         RISCV_INFO(r);
1361
1362         if (r->manual_hwbp_set) {
1363                 /* Look at every trigger that may have been set. */
1364                 riscv_reg_t tselect;
1365                 if (riscv_get_register(target, &tselect, GDB_REGNO_TSELECT) != ERROR_OK)
1366                         return ERROR_FAIL;
1367                 for (unsigned int t = 0; t < r->trigger_count; t++) {
1368                         if (state[t] != 0) {
1369                                 if (riscv_set_register(target, GDB_REGNO_TSELECT, t) != ERROR_OK)
1370                                         return ERROR_FAIL;
1371                                 if (riscv_set_register(target, GDB_REGNO_TDATA1, state[t]) != ERROR_OK)
1372                                         return ERROR_FAIL;
1373                         }
1374                 }
1375                 if (riscv_set_register(target, GDB_REGNO_TSELECT, tselect) != ERROR_OK)
1376                         return ERROR_FAIL;
1377
1378         } else {
1379                 struct watchpoint *watchpoint = target->watchpoints;
1380                 int i = 0;
1381                 while (watchpoint) {
1382                         LOG_DEBUG("watchpoint %d: cleared=%" PRId64, i, state[i]);
1383                         if (state[i]) {
1384                                 if (riscv_add_watchpoint(target, watchpoint) != ERROR_OK)
1385                                         return ERROR_FAIL;
1386                         }
1387                         watchpoint = watchpoint->next;
1388                         i++;
1389                 }
1390         }
1391
1392         return ERROR_OK;
1393 }
1394
1395 /**
1396  * Get everything ready to resume.
1397  */
1398 static int resume_prep(struct target *target, int current,
1399                 target_addr_t address, int handle_breakpoints, int debug_execution)
1400 {
1401         RISCV_INFO(r);
1402         LOG_DEBUG("[%d]", target->coreid);
1403
1404         if (!current)
1405                 riscv_set_register(target, GDB_REGNO_PC, address);
1406
1407         if (target->debug_reason == DBG_REASON_WATCHPOINT) {
1408                 /* To be able to run off a trigger, disable all the triggers, step, and
1409                  * then resume as usual. */
1410                 riscv_reg_t trigger_state[RISCV_MAX_HWBPS] = {0};
1411
1412                 if (disable_triggers(target, trigger_state) != ERROR_OK)
1413                         return ERROR_FAIL;
1414
1415                 if (old_or_new_riscv_step(target, true, 0, false) != ERROR_OK)
1416                         return ERROR_FAIL;
1417
1418                 if (enable_triggers(target, trigger_state) != ERROR_OK)
1419                         return ERROR_FAIL;
1420         }
1421
1422         if (r->is_halted) {
1423                 if (riscv_resume_prep_all_harts(target) != ERROR_OK)
1424                         return ERROR_FAIL;
1425         }
1426
1427         LOG_DEBUG("[%d] mark as prepped", target->coreid);
1428         r->prepped = true;
1429
1430         return ERROR_OK;
1431 }
1432
1433 /**
1434  * Resume all the harts that have been prepped, as close to instantaneous as
1435  * possible.
1436  */
1437 static int resume_go(struct target *target, int current,
1438                 target_addr_t address, int handle_breakpoints, int debug_execution)
1439 {
1440         RISCV_INFO(r);
1441         int result;
1442         if (!r->is_halted) {
1443                 struct target_type *tt = get_target_type(target);
1444                 result = tt->resume(target, current, address, handle_breakpoints,
1445                                 debug_execution);
1446         } else {
1447                 result = riscv_resume_go_all_harts(target);
1448         }
1449
1450         return result;
1451 }
1452
1453 static int resume_finish(struct target *target)
1454 {
1455         register_cache_invalidate(target->reg_cache);
1456
1457         target->state = TARGET_RUNNING;
1458         target->debug_reason = DBG_REASON_NOTHALTED;
1459         return target_call_event_callbacks(target, TARGET_EVENT_RESUMED);
1460 }
1461
1462 /**
1463  * @par single_hart When true, only resume a single hart even if SMP is
1464  * configured.  This is used to run algorithms on just one hart.
1465  */
1466 static int riscv_resume(
1467                 struct target *target,
1468                 int current,
1469                 target_addr_t address,
1470                 int handle_breakpoints,
1471                 int debug_execution,
1472                 bool single_hart)
1473 {
1474         LOG_DEBUG("handle_breakpoints=%d", handle_breakpoints);
1475         int result = ERROR_OK;
1476         if (target->smp && !single_hart) {
1477                 struct target_list *tlist;
1478                 foreach_smp_target_direction(resume_order == RO_NORMAL,
1479                                                                          tlist, target->smp_targets) {
1480                         struct target *t = tlist->target;
1481                         if (resume_prep(t, current, address, handle_breakpoints,
1482                                                 debug_execution) != ERROR_OK)
1483                                 result = ERROR_FAIL;
1484                 }
1485
1486                 foreach_smp_target_direction(resume_order == RO_NORMAL,
1487                                                                          tlist, target->smp_targets) {
1488                         struct target *t = tlist->target;
1489                         struct riscv_info *i = riscv_info(t);
1490                         if (i->prepped) {
1491                                 if (resume_go(t, current, address, handle_breakpoints,
1492                                                         debug_execution) != ERROR_OK)
1493                                         result = ERROR_FAIL;
1494                         }
1495                 }
1496
1497                 foreach_smp_target_direction(resume_order == RO_NORMAL,
1498                                                                          tlist, target->smp_targets) {
1499                         struct target *t = tlist->target;
1500                         if (resume_finish(t) != ERROR_OK)
1501                                 return ERROR_FAIL;
1502                 }
1503
1504         } else {
1505                 if (resume_prep(target, current, address, handle_breakpoints,
1506                                         debug_execution) != ERROR_OK)
1507                         result = ERROR_FAIL;
1508                 if (resume_go(target, current, address, handle_breakpoints,
1509                                         debug_execution) != ERROR_OK)
1510                         result = ERROR_FAIL;
1511                 if (resume_finish(target) != ERROR_OK)
1512                         return ERROR_FAIL;
1513         }
1514
1515         return result;
1516 }
1517
1518 static int riscv_target_resume(struct target *target, int current, target_addr_t address,
1519                 int handle_breakpoints, int debug_execution)
1520 {
1521         return riscv_resume(target, current, address, handle_breakpoints,
1522                         debug_execution, false);
1523 }
1524
1525 static int riscv_mmu(struct target *target, int *enabled)
1526 {
1527         if (!riscv_enable_virt2phys) {
1528                 *enabled = 0;
1529                 return ERROR_OK;
1530         }
1531
1532         /* Don't use MMU in explicit or effective M (machine) mode */
1533         riscv_reg_t priv;
1534         if (riscv_get_register(target, &priv, GDB_REGNO_PRIV) != ERROR_OK) {
1535                 LOG_ERROR("Failed to read priv register.");
1536                 return ERROR_FAIL;
1537         }
1538
1539         riscv_reg_t mstatus;
1540         if (riscv_get_register(target, &mstatus, GDB_REGNO_MSTATUS) != ERROR_OK) {
1541                 LOG_ERROR("Failed to read mstatus register.");
1542                 return ERROR_FAIL;
1543         }
1544
1545         if ((get_field(mstatus, MSTATUS_MPRV) ? get_field(mstatus, MSTATUS_MPP) : priv) == PRV_M) {
1546                 LOG_DEBUG("SATP/MMU ignored in Machine mode (mstatus=0x%" PRIx64 ").", mstatus);
1547                 *enabled = 0;
1548                 return ERROR_OK;
1549         }
1550
1551         riscv_reg_t satp;
1552         if (riscv_get_register(target, &satp, GDB_REGNO_SATP) != ERROR_OK) {
1553                 LOG_DEBUG("Couldn't read SATP.");
1554                 /* If we can't read SATP, then there must not be an MMU. */
1555                 *enabled = 0;
1556                 return ERROR_OK;
1557         }
1558
1559         if (get_field(satp, RISCV_SATP_MODE(riscv_xlen(target))) == SATP_MODE_OFF) {
1560                 LOG_DEBUG("MMU is disabled.");
1561                 *enabled = 0;
1562         } else {
1563                 LOG_DEBUG("MMU is enabled.");
1564                 *enabled = 1;
1565         }
1566
1567         return ERROR_OK;
1568 }
1569
1570 static int riscv_address_translate(struct target *target,
1571                 target_addr_t virtual, target_addr_t *physical)
1572 {
1573         RISCV_INFO(r);
1574         riscv_reg_t satp_value;
1575         int mode;
1576         uint64_t ppn_value;
1577         target_addr_t table_address;
1578         const virt2phys_info_t *info;
1579         uint64_t pte = 0;
1580         int i;
1581
1582         int result = riscv_get_register(target, &satp_value, GDB_REGNO_SATP);
1583         if (result != ERROR_OK)
1584                 return result;
1585
1586         unsigned xlen = riscv_xlen(target);
1587         mode = get_field(satp_value, RISCV_SATP_MODE(xlen));
1588         switch (mode) {
1589                 case SATP_MODE_SV32:
1590                         info = &sv32;
1591                         break;
1592                 case SATP_MODE_SV39:
1593                         info = &sv39;
1594                         break;
1595                 case SATP_MODE_SV48:
1596                         info = &sv48;
1597                         break;
1598                 case SATP_MODE_OFF:
1599                         LOG_ERROR("No translation or protection." \
1600                                       " (satp: 0x%" PRIx64 ")", satp_value);
1601                         return ERROR_FAIL;
1602                 default:
1603                         LOG_ERROR("The translation mode is not supported." \
1604                                       " (satp: 0x%" PRIx64 ")", satp_value);
1605                         return ERROR_FAIL;
1606         }
1607         LOG_DEBUG("virtual=0x%" TARGET_PRIxADDR "; mode=%s", virtual, info->name);
1608
1609         /* verify bits xlen-1:va_bits-1 are all equal */
1610         target_addr_t mask = ((target_addr_t)1 << (xlen - (info->va_bits - 1))) - 1;
1611         target_addr_t masked_msbs = (virtual >> (info->va_bits - 1)) & mask;
1612         if (masked_msbs != 0 && masked_msbs != mask) {
1613                 LOG_ERROR("Virtual address 0x%" TARGET_PRIxADDR " is not sign-extended "
1614                                 "for %s mode.", virtual, info->name);
1615                 return ERROR_FAIL;
1616         }
1617
1618         ppn_value = get_field(satp_value, RISCV_SATP_PPN(xlen));
1619         table_address = ppn_value << RISCV_PGSHIFT;
1620         i = info->level - 1;
1621         while (i >= 0) {
1622                 uint64_t vpn = virtual >> info->vpn_shift[i];
1623                 vpn &= info->vpn_mask[i];
1624                 target_addr_t pte_address = table_address +
1625                                                                         (vpn << info->pte_shift);
1626                 uint8_t buffer[8];
1627                 assert(info->pte_shift <= 3);
1628                 int retval = r->read_memory(target, pte_address,
1629                                 4, (1 << info->pte_shift) / 4, buffer, 4);
1630                 if (retval != ERROR_OK)
1631                         return ERROR_FAIL;
1632
1633                 if (info->pte_shift == 2)
1634                         pte = buf_get_u32(buffer, 0, 32);
1635                 else
1636                         pte = buf_get_u64(buffer, 0, 64);
1637
1638                 LOG_DEBUG("i=%d; PTE @0x%" TARGET_PRIxADDR " = 0x%" PRIx64, i,
1639                                 pte_address, pte);
1640
1641                 if (!(pte & PTE_V) || (!(pte & PTE_R) && (pte & PTE_W)))
1642                         return ERROR_FAIL;
1643
1644                 if ((pte & PTE_R) || (pte & PTE_X)) /* Found leaf PTE. */
1645                         break;
1646
1647                 i--;
1648                 if (i < 0)
1649                         break;
1650                 ppn_value = pte >> PTE_PPN_SHIFT;
1651                 table_address = ppn_value << RISCV_PGSHIFT;
1652         }
1653
1654         if (i < 0) {
1655                 LOG_ERROR("Couldn't find the PTE.");
1656                 return ERROR_FAIL;
1657         }
1658
1659         /* Make sure to clear out the high bits that may be set. */
1660         *physical = virtual & (((target_addr_t)1 << info->va_bits) - 1);
1661
1662         while (i < info->level) {
1663                 ppn_value = pte >> info->pte_ppn_shift[i];
1664                 ppn_value &= info->pte_ppn_mask[i];
1665                 *physical &= ~(((target_addr_t)info->pa_ppn_mask[i]) <<
1666                                 info->pa_ppn_shift[i]);
1667                 *physical |= (ppn_value << info->pa_ppn_shift[i]);
1668                 i++;
1669         }
1670         LOG_DEBUG("0x%" TARGET_PRIxADDR " -> 0x%" TARGET_PRIxADDR, virtual,
1671                         *physical);
1672
1673         return ERROR_OK;
1674 }
1675
1676 static int riscv_virt2phys(struct target *target, target_addr_t virtual, target_addr_t *physical)
1677 {
1678         int enabled;
1679         if (riscv_mmu(target, &enabled) == ERROR_OK) {
1680                 if (!enabled)
1681                         return ERROR_FAIL;
1682
1683                 if (riscv_address_translate(target, virtual, physical) == ERROR_OK)
1684                         return ERROR_OK;
1685         }
1686
1687         return ERROR_FAIL;
1688 }
1689
1690 static int riscv_read_phys_memory(struct target *target, target_addr_t phys_address,
1691                         uint32_t size, uint32_t count, uint8_t *buffer)
1692 {
1693         RISCV_INFO(r);
1694         if (riscv_select_current_hart(target) != ERROR_OK)
1695                 return ERROR_FAIL;
1696         return r->read_memory(target, phys_address, size, count, buffer, size);
1697 }
1698
1699 static int riscv_read_memory(struct target *target, target_addr_t address,
1700                 uint32_t size, uint32_t count, uint8_t *buffer)
1701 {
1702         if (count == 0) {
1703                 LOG_WARNING("0-length read from 0x%" TARGET_PRIxADDR, address);
1704                 return ERROR_OK;
1705         }
1706
1707         if (riscv_select_current_hart(target) != ERROR_OK)
1708                 return ERROR_FAIL;
1709
1710         target_addr_t physical_addr;
1711         if (target->type->virt2phys(target, address, &physical_addr) == ERROR_OK)
1712                 address = physical_addr;
1713
1714         RISCV_INFO(r);
1715         return r->read_memory(target, address, size, count, buffer, size);
1716 }
1717
1718 static int riscv_write_phys_memory(struct target *target, target_addr_t phys_address,
1719                         uint32_t size, uint32_t count, const uint8_t *buffer)
1720 {
1721         if (riscv_select_current_hart(target) != ERROR_OK)
1722                 return ERROR_FAIL;
1723         struct target_type *tt = get_target_type(target);
1724         return tt->write_memory(target, phys_address, size, count, buffer);
1725 }
1726
1727 static int riscv_write_memory(struct target *target, target_addr_t address,
1728                 uint32_t size, uint32_t count, const uint8_t *buffer)
1729 {
1730         if (count == 0) {
1731                 LOG_WARNING("0-length write to 0x%" TARGET_PRIxADDR, address);
1732                 return ERROR_OK;
1733         }
1734
1735         if (riscv_select_current_hart(target) != ERROR_OK)
1736                 return ERROR_FAIL;
1737
1738         target_addr_t physical_addr;
1739         if (target->type->virt2phys(target, address, &physical_addr) == ERROR_OK)
1740                 address = physical_addr;
1741
1742         struct target_type *tt = get_target_type(target);
1743         return tt->write_memory(target, address, size, count, buffer);
1744 }
1745
1746 static const char *riscv_get_gdb_arch(struct target *target)
1747 {
1748         switch (riscv_xlen(target)) {
1749                 case 32:
1750                         return "riscv:rv32";
1751                 case 64:
1752                         return "riscv:rv64";
1753         }
1754         LOG_ERROR("Unsupported xlen: %d", riscv_xlen(target));
1755         return NULL;
1756 }
1757
1758 static int riscv_get_gdb_reg_list_internal(struct target *target,
1759                 struct reg **reg_list[], int *reg_list_size,
1760                 enum target_register_class reg_class, bool read)
1761 {
1762         RISCV_INFO(r);
1763         LOG_DEBUG("[%s] {%d} reg_class=%d, read=%d",
1764                         target_name(target), r->current_hartid, reg_class, read);
1765
1766         if (!target->reg_cache) {
1767                 LOG_ERROR("Target not initialized. Return ERROR_FAIL.");
1768                 return ERROR_FAIL;
1769         }
1770
1771         if (riscv_select_current_hart(target) != ERROR_OK)
1772                 return ERROR_FAIL;
1773
1774         switch (reg_class) {
1775                 case REG_CLASS_GENERAL:
1776                         *reg_list_size = 33;
1777                         break;
1778                 case REG_CLASS_ALL:
1779                         *reg_list_size = target->reg_cache->num_regs;
1780                         break;
1781                 default:
1782                         LOG_ERROR("Unsupported reg_class: %d", reg_class);
1783                         return ERROR_FAIL;
1784         }
1785
1786         *reg_list = calloc(*reg_list_size, sizeof(struct reg *));
1787         if (!*reg_list)
1788                 return ERROR_FAIL;
1789
1790         for (int i = 0; i < *reg_list_size; i++) {
1791                 assert(!target->reg_cache->reg_list[i].valid ||
1792                                 target->reg_cache->reg_list[i].size > 0);
1793                 (*reg_list)[i] = &target->reg_cache->reg_list[i];
1794                 if (read &&
1795                                 target->reg_cache->reg_list[i].exist &&
1796                                 !target->reg_cache->reg_list[i].valid) {
1797                         if (target->reg_cache->reg_list[i].type->get(
1798                                                 &target->reg_cache->reg_list[i]) != ERROR_OK)
1799                                 return ERROR_FAIL;
1800                 }
1801         }
1802
1803         return ERROR_OK;
1804 }
1805
1806 static int riscv_get_gdb_reg_list_noread(struct target *target,
1807                 struct reg **reg_list[], int *reg_list_size,
1808                 enum target_register_class reg_class)
1809 {
1810         return riscv_get_gdb_reg_list_internal(target, reg_list, reg_list_size,
1811                         reg_class, false);
1812 }
1813
1814 static int riscv_get_gdb_reg_list(struct target *target,
1815                 struct reg **reg_list[], int *reg_list_size,
1816                 enum target_register_class reg_class)
1817 {
1818         return riscv_get_gdb_reg_list_internal(target, reg_list, reg_list_size,
1819                         reg_class, true);
1820 }
1821
1822 static int riscv_arch_state(struct target *target)
1823 {
1824         struct target_type *tt = get_target_type(target);
1825         return tt->arch_state(target);
1826 }
1827
1828 /* Algorithm must end with a software breakpoint instruction. */
1829 static int riscv_run_algorithm(struct target *target, int num_mem_params,
1830                 struct mem_param *mem_params, int num_reg_params,
1831                 struct reg_param *reg_params, target_addr_t entry_point,
1832                 target_addr_t exit_point, int timeout_ms, void *arch_info)
1833 {
1834         RISCV_INFO(info);
1835
1836         if (num_mem_params > 0) {
1837                 LOG_ERROR("Memory parameters are not supported for RISC-V algorithms.");
1838                 return ERROR_FAIL;
1839         }
1840
1841         if (target->state != TARGET_HALTED) {
1842                 LOG_WARNING("target not halted");
1843                 return ERROR_TARGET_NOT_HALTED;
1844         }
1845
1846         /* Save registers */
1847         struct reg *reg_pc = register_get_by_name(target->reg_cache, "pc", true);
1848         if (!reg_pc || reg_pc->type->get(reg_pc) != ERROR_OK)
1849                 return ERROR_FAIL;
1850         uint64_t saved_pc = buf_get_u64(reg_pc->value, 0, reg_pc->size);
1851         LOG_DEBUG("saved_pc=0x%" PRIx64, saved_pc);
1852
1853         uint64_t saved_regs[32];
1854         for (int i = 0; i < num_reg_params; i++) {
1855                 LOG_DEBUG("save %s", reg_params[i].reg_name);
1856                 struct reg *r = register_get_by_name(target->reg_cache, reg_params[i].reg_name, false);
1857                 if (!r) {
1858                         LOG_ERROR("Couldn't find register named '%s'", reg_params[i].reg_name);
1859                         return ERROR_FAIL;
1860                 }
1861
1862                 if (r->size != reg_params[i].size) {
1863                         LOG_ERROR("Register %s is %d bits instead of %d bits.",
1864                                         reg_params[i].reg_name, r->size, reg_params[i].size);
1865                         return ERROR_FAIL;
1866                 }
1867
1868                 if (r->number > GDB_REGNO_XPR31) {
1869                         LOG_ERROR("Only GPRs can be use as argument registers.");
1870                         return ERROR_FAIL;
1871                 }
1872
1873                 if (r->type->get(r) != ERROR_OK)
1874                         return ERROR_FAIL;
1875                 saved_regs[r->number] = buf_get_u64(r->value, 0, r->size);
1876
1877                 if (reg_params[i].direction == PARAM_OUT || reg_params[i].direction == PARAM_IN_OUT) {
1878                         if (r->type->set(r, reg_params[i].value) != ERROR_OK)
1879                                 return ERROR_FAIL;
1880                 }
1881         }
1882
1883
1884         /* Disable Interrupts before attempting to run the algorithm. */
1885         uint64_t current_mstatus;
1886         uint8_t mstatus_bytes[8] = { 0 };
1887
1888         LOG_DEBUG("Disabling Interrupts");
1889         struct reg *reg_mstatus = register_get_by_name(target->reg_cache,
1890                         "mstatus", true);
1891         if (!reg_mstatus) {
1892                 LOG_ERROR("Couldn't find mstatus!");
1893                 return ERROR_FAIL;
1894         }
1895
1896         reg_mstatus->type->get(reg_mstatus);
1897         current_mstatus = buf_get_u64(reg_mstatus->value, 0, reg_mstatus->size);
1898         uint64_t ie_mask = MSTATUS_MIE | MSTATUS_HIE | MSTATUS_SIE | MSTATUS_UIE;
1899         buf_set_u64(mstatus_bytes, 0, info->xlen, set_field(current_mstatus,
1900                                 ie_mask, 0));
1901
1902         reg_mstatus->type->set(reg_mstatus, mstatus_bytes);
1903
1904         /* Run algorithm */
1905         LOG_DEBUG("resume at 0x%" TARGET_PRIxADDR, entry_point);
1906         if (riscv_resume(target, 0, entry_point, 0, 0, true) != ERROR_OK)
1907                 return ERROR_FAIL;
1908
1909         int64_t start = timeval_ms();
1910         while (target->state != TARGET_HALTED) {
1911                 LOG_DEBUG("poll()");
1912                 int64_t now = timeval_ms();
1913                 if (now - start > timeout_ms) {
1914                         LOG_ERROR("Algorithm timed out after %" PRId64 " ms.", now - start);
1915                         riscv_halt(target);
1916                         old_or_new_riscv_poll(target);
1917                         enum gdb_regno regnums[] = {
1918                                 GDB_REGNO_RA, GDB_REGNO_SP, GDB_REGNO_GP, GDB_REGNO_TP,
1919                                 GDB_REGNO_T0, GDB_REGNO_T1, GDB_REGNO_T2, GDB_REGNO_FP,
1920                                 GDB_REGNO_S1, GDB_REGNO_A0, GDB_REGNO_A1, GDB_REGNO_A2,
1921                                 GDB_REGNO_A3, GDB_REGNO_A4, GDB_REGNO_A5, GDB_REGNO_A6,
1922                                 GDB_REGNO_A7, GDB_REGNO_S2, GDB_REGNO_S3, GDB_REGNO_S4,
1923                                 GDB_REGNO_S5, GDB_REGNO_S6, GDB_REGNO_S7, GDB_REGNO_S8,
1924                                 GDB_REGNO_S9, GDB_REGNO_S10, GDB_REGNO_S11, GDB_REGNO_T3,
1925                                 GDB_REGNO_T4, GDB_REGNO_T5, GDB_REGNO_T6,
1926                                 GDB_REGNO_PC,
1927                                 GDB_REGNO_MSTATUS, GDB_REGNO_MEPC, GDB_REGNO_MCAUSE,
1928                         };
1929                         for (unsigned i = 0; i < ARRAY_SIZE(regnums); i++) {
1930                                 enum gdb_regno regno = regnums[i];
1931                                 riscv_reg_t reg_value;
1932                                 if (riscv_get_register(target, &reg_value, regno) != ERROR_OK)
1933                                         break;
1934                                 LOG_ERROR("%s = 0x%" PRIx64, gdb_regno_name(regno), reg_value);
1935                         }
1936                         return ERROR_TARGET_TIMEOUT;
1937                 }
1938
1939                 int result = old_or_new_riscv_poll(target);
1940                 if (result != ERROR_OK)
1941                         return result;
1942         }
1943
1944         /* The current hart id might have been changed in poll(). */
1945         if (riscv_select_current_hart(target) != ERROR_OK)
1946                 return ERROR_FAIL;
1947
1948         if (reg_pc->type->get(reg_pc) != ERROR_OK)
1949                 return ERROR_FAIL;
1950         uint64_t final_pc = buf_get_u64(reg_pc->value, 0, reg_pc->size);
1951         if (exit_point && final_pc != exit_point) {
1952                 LOG_ERROR("PC ended up at 0x%" PRIx64 " instead of 0x%"
1953                                 TARGET_PRIxADDR, final_pc, exit_point);
1954                 return ERROR_FAIL;
1955         }
1956
1957         /* Restore Interrupts */
1958         LOG_DEBUG("Restoring Interrupts");
1959         buf_set_u64(mstatus_bytes, 0, info->xlen, current_mstatus);
1960         reg_mstatus->type->set(reg_mstatus, mstatus_bytes);
1961
1962         /* Restore registers */
1963         uint8_t buf[8] = { 0 };
1964         buf_set_u64(buf, 0, info->xlen, saved_pc);
1965         if (reg_pc->type->set(reg_pc, buf) != ERROR_OK)
1966                 return ERROR_FAIL;
1967
1968         for (int i = 0; i < num_reg_params; i++) {
1969                 if (reg_params[i].direction == PARAM_IN ||
1970                                 reg_params[i].direction == PARAM_IN_OUT) {
1971                         struct reg *r = register_get_by_name(target->reg_cache, reg_params[i].reg_name, false);
1972                         if (r->type->get(r) != ERROR_OK) {
1973                                 LOG_ERROR("get(%s) failed", r->name);
1974                                 return ERROR_FAIL;
1975                         }
1976                         buf_cpy(r->value, reg_params[i].value, reg_params[i].size);
1977                 }
1978                 LOG_DEBUG("restore %s", reg_params[i].reg_name);
1979                 struct reg *r = register_get_by_name(target->reg_cache, reg_params[i].reg_name, false);
1980                 buf_set_u64(buf, 0, info->xlen, saved_regs[r->number]);
1981                 if (r->type->set(r, buf) != ERROR_OK) {
1982                         LOG_ERROR("set(%s) failed", r->name);
1983                         return ERROR_FAIL;
1984                 }
1985         }
1986
1987         return ERROR_OK;
1988 }
1989
1990 static int riscv_checksum_memory(struct target *target,
1991                 target_addr_t address, uint32_t count,
1992                 uint32_t *checksum)
1993 {
1994         struct working_area *crc_algorithm;
1995         struct reg_param reg_params[2];
1996         int retval;
1997
1998         LOG_DEBUG("address=0x%" TARGET_PRIxADDR "; count=0x%" PRIx32, address, count);
1999
2000         static const uint8_t riscv32_crc_code[] = {
2001 #include "../../../contrib/loaders/checksum/riscv32_crc.inc"
2002         };
2003         static const uint8_t riscv64_crc_code[] = {
2004 #include "../../../contrib/loaders/checksum/riscv64_crc.inc"
2005         };
2006
2007         static const uint8_t *crc_code;
2008
2009         unsigned xlen = riscv_xlen(target);
2010         unsigned crc_code_size;
2011         if (xlen == 32) {
2012                 crc_code = riscv32_crc_code;
2013                 crc_code_size = sizeof(riscv32_crc_code);
2014         } else {
2015                 crc_code = riscv64_crc_code;
2016                 crc_code_size = sizeof(riscv64_crc_code);
2017         }
2018
2019         if (count < crc_code_size * 4) {
2020                 /* Don't use the algorithm for relatively small buffers. It's faster
2021                  * just to read the memory.  target_checksum_memory() will take care of
2022                  * that if we fail. */
2023                 return ERROR_FAIL;
2024         }
2025
2026         retval = target_alloc_working_area(target, crc_code_size, &crc_algorithm);
2027         if (retval != ERROR_OK)
2028                 return retval;
2029
2030         if (crc_algorithm->address + crc_algorithm->size > address &&
2031                         crc_algorithm->address < address + count) {
2032                 /* Region to checksum overlaps with the work area we've been assigned.
2033                  * Bail. (Would be better to manually checksum what we read there, and
2034                  * use the algorithm for the rest.) */
2035                 target_free_working_area(target, crc_algorithm);
2036                 return ERROR_FAIL;
2037         }
2038
2039         retval = target_write_buffer(target, crc_algorithm->address, crc_code_size,
2040                         crc_code);
2041         if (retval != ERROR_OK) {
2042                 LOG_ERROR("Failed to write code to " TARGET_ADDR_FMT ": %d",
2043                                 crc_algorithm->address, retval);
2044                 target_free_working_area(target, crc_algorithm);
2045                 return retval;
2046         }
2047
2048         init_reg_param(&reg_params[0], "a0", xlen, PARAM_IN_OUT);
2049         init_reg_param(&reg_params[1], "a1", xlen, PARAM_OUT);
2050         buf_set_u64(reg_params[0].value, 0, xlen, address);
2051         buf_set_u64(reg_params[1].value, 0, xlen, count);
2052
2053         /* 20 second timeout/megabyte */
2054         int timeout = 20000 * (1 + (count / (1024 * 1024)));
2055
2056         retval = target_run_algorithm(target, 0, NULL, 2, reg_params,
2057                         crc_algorithm->address,
2058                         0,      /* Leave exit point unspecified because we don't know. */
2059                         timeout, NULL);
2060
2061         if (retval == ERROR_OK)
2062                 *checksum = buf_get_u32(reg_params[0].value, 0, 32);
2063         else
2064                 LOG_ERROR("error executing RISC-V CRC algorithm");
2065
2066         destroy_reg_param(&reg_params[0]);
2067         destroy_reg_param(&reg_params[1]);
2068
2069         target_free_working_area(target, crc_algorithm);
2070
2071         LOG_DEBUG("checksum=0x%" PRIx32 ", result=%d", *checksum, retval);
2072
2073         return retval;
2074 }
2075
2076 /*** OpenOCD Helper Functions ***/
2077
2078 enum riscv_poll_hart {
2079         RPH_NO_CHANGE,
2080         RPH_DISCOVERED_HALTED,
2081         RPH_DISCOVERED_RUNNING,
2082         RPH_ERROR
2083 };
2084 static enum riscv_poll_hart riscv_poll_hart(struct target *target, int hartid)
2085 {
2086         RISCV_INFO(r);
2087         if (riscv_set_current_hartid(target, hartid) != ERROR_OK)
2088                 return RPH_ERROR;
2089
2090         LOG_DEBUG("polling hart %d, target->state=%d", hartid, target->state);
2091
2092         /* If OpenOCD thinks we're running but this hart is halted then it's time
2093          * to raise an event. */
2094         bool halted = riscv_is_halted(target);
2095         if (target->state != TARGET_HALTED && halted) {
2096                 LOG_DEBUG("  triggered a halt");
2097                 r->on_halt(target);
2098                 return RPH_DISCOVERED_HALTED;
2099         } else if (target->state != TARGET_RUNNING && !halted) {
2100                 LOG_DEBUG("  triggered running");
2101                 target->state = TARGET_RUNNING;
2102                 target->debug_reason = DBG_REASON_NOTHALTED;
2103                 return RPH_DISCOVERED_RUNNING;
2104         }
2105
2106         return RPH_NO_CHANGE;
2107 }
2108
2109 static int set_debug_reason(struct target *target, enum riscv_halt_reason halt_reason)
2110 {
2111         switch (halt_reason) {
2112                 case RISCV_HALT_BREAKPOINT:
2113                         target->debug_reason = DBG_REASON_BREAKPOINT;
2114                         break;
2115                 case RISCV_HALT_TRIGGER:
2116                         target->debug_reason = DBG_REASON_WATCHPOINT;
2117                         break;
2118                 case RISCV_HALT_INTERRUPT:
2119                 case RISCV_HALT_GROUP:
2120                         target->debug_reason = DBG_REASON_DBGRQ;
2121                         break;
2122                 case RISCV_HALT_SINGLESTEP:
2123                         target->debug_reason = DBG_REASON_SINGLESTEP;
2124                         break;
2125                 case RISCV_HALT_UNKNOWN:
2126                         target->debug_reason = DBG_REASON_UNDEFINED;
2127                         break;
2128                 case RISCV_HALT_ERROR:
2129                         return ERROR_FAIL;
2130         }
2131         LOG_DEBUG("[%s] debug_reason=%d", target_name(target), target->debug_reason);
2132         return ERROR_OK;
2133 }
2134
2135 static int sample_memory(struct target *target)
2136 {
2137         RISCV_INFO(r);
2138
2139         if (!r->sample_buf.buf || !r->sample_config.enabled)
2140                 return ERROR_OK;
2141
2142         LOG_DEBUG("buf used/size: %d/%d", r->sample_buf.used, r->sample_buf.size);
2143
2144         uint64_t start = timeval_ms();
2145         riscv_sample_buf_maybe_add_timestamp(target, true);
2146         int result = ERROR_OK;
2147         if (r->sample_memory) {
2148                 result = r->sample_memory(target, &r->sample_buf, &r->sample_config,
2149                                                                           start + TARGET_DEFAULT_POLLING_INTERVAL);
2150                 if (result != ERROR_NOT_IMPLEMENTED)
2151                         goto exit;
2152         }
2153
2154         /* Default slow path. */
2155         while (timeval_ms() - start < TARGET_DEFAULT_POLLING_INTERVAL) {
2156                 for (unsigned int i = 0; i < ARRAY_SIZE(r->sample_config.bucket); i++) {
2157                         if (r->sample_config.bucket[i].enabled &&
2158                                         r->sample_buf.used + 1 + r->sample_config.bucket[i].size_bytes < r->sample_buf.size) {
2159                                 assert(i < RISCV_SAMPLE_BUF_TIMESTAMP_BEFORE);
2160                                 r->sample_buf.buf[r->sample_buf.used] = i;
2161                                 result = riscv_read_phys_memory(
2162                                         target, r->sample_config.bucket[i].address,
2163                                         r->sample_config.bucket[i].size_bytes, 1,
2164                                         r->sample_buf.buf + r->sample_buf.used + 1);
2165                                 if (result == ERROR_OK)
2166                                         r->sample_buf.used += 1 + r->sample_config.bucket[i].size_bytes;
2167                                 else
2168                                         goto exit;
2169                         }
2170                 }
2171         }
2172
2173 exit:
2174         riscv_sample_buf_maybe_add_timestamp(target, false);
2175         if (result != ERROR_OK) {
2176                 LOG_INFO("Turning off memory sampling because it failed.");
2177                 r->sample_config.enabled = false;
2178         }
2179         return result;
2180 }
2181
2182 /*** OpenOCD Interface ***/
2183 int riscv_openocd_poll(struct target *target)
2184 {
2185         LOG_DEBUG("polling all harts");
2186         int halted_hart = -1;
2187
2188         if (target->smp) {
2189                 unsigned halts_discovered = 0;
2190                 unsigned should_remain_halted = 0;
2191                 unsigned should_resume = 0;
2192                 struct target_list *list;
2193                 foreach_smp_target(list, target->smp_targets) {
2194                         struct target *t = list->target;
2195                         struct riscv_info *r = riscv_info(t);
2196                         enum riscv_poll_hart out = riscv_poll_hart(t, r->current_hartid);
2197                         switch (out) {
2198                         case RPH_NO_CHANGE:
2199                                 break;
2200                         case RPH_DISCOVERED_RUNNING:
2201                                 t->state = TARGET_RUNNING;
2202                                 t->debug_reason = DBG_REASON_NOTHALTED;
2203                                 break;
2204                         case RPH_DISCOVERED_HALTED:
2205                                 halts_discovered++;
2206                                 t->state = TARGET_HALTED;
2207                                 enum riscv_halt_reason halt_reason =
2208                                         riscv_halt_reason(t, r->current_hartid);
2209                                 if (set_debug_reason(t, halt_reason) != ERROR_OK)
2210                                         return ERROR_FAIL;
2211
2212                                 if (halt_reason == RISCV_HALT_BREAKPOINT) {
2213                                         int retval;
2214                                         switch (riscv_semihosting(t, &retval)) {
2215                                         case SEMIHOSTING_NONE:
2216                                         case SEMIHOSTING_WAITING:
2217                                                 /* This hart should remain halted. */
2218                                                 should_remain_halted++;
2219                                                 break;
2220                                         case SEMIHOSTING_HANDLED:
2221                                                 /* This hart should be resumed, along with any other
2222                                                          * harts that halted due to haltgroups. */
2223                                                 should_resume++;
2224                                                 break;
2225                                         case SEMIHOSTING_ERROR:
2226                                                 return retval;
2227                                         }
2228                                 } else if (halt_reason != RISCV_HALT_GROUP) {
2229                                         should_remain_halted++;
2230                                 }
2231                                 break;
2232
2233                         case RPH_ERROR:
2234                                 return ERROR_FAIL;
2235                         }
2236                 }
2237
2238                 LOG_DEBUG("should_remain_halted=%d, should_resume=%d",
2239                                   should_remain_halted, should_resume);
2240                 if (should_remain_halted && should_resume) {
2241                         LOG_WARNING("%d harts should remain halted, and %d should resume.",
2242                                                 should_remain_halted, should_resume);
2243                 }
2244                 if (should_remain_halted) {
2245                         LOG_DEBUG("halt all");
2246                         riscv_halt(target);
2247                 } else if (should_resume) {
2248                         LOG_DEBUG("resume all");
2249                         riscv_resume(target, true, 0, 0, 0, false);
2250                 }
2251
2252                 /* Sample memory if any target is running. */
2253                 foreach_smp_target(list, target->smp_targets) {
2254                         struct target *t = list->target;
2255                         if (t->state == TARGET_RUNNING) {
2256                                 sample_memory(target);
2257                                 break;
2258                         }
2259                 }
2260
2261                 return ERROR_OK;
2262
2263         } else {
2264                 enum riscv_poll_hart out = riscv_poll_hart(target,
2265                                 riscv_current_hartid(target));
2266                 if (out == RPH_NO_CHANGE || out == RPH_DISCOVERED_RUNNING) {
2267                         if (target->state == TARGET_RUNNING)
2268                                 sample_memory(target);
2269                         return ERROR_OK;
2270                 } else if (out == RPH_ERROR) {
2271                         return ERROR_FAIL;
2272                 }
2273
2274                 halted_hart = riscv_current_hartid(target);
2275                 LOG_DEBUG("  hart %d halted", halted_hart);
2276
2277                 enum riscv_halt_reason halt_reason = riscv_halt_reason(target, halted_hart);
2278                 if (set_debug_reason(target, halt_reason) != ERROR_OK)
2279                         return ERROR_FAIL;
2280                 target->state = TARGET_HALTED;
2281         }
2282
2283         if (target->debug_reason == DBG_REASON_BREAKPOINT) {
2284                 int retval;
2285                 switch (riscv_semihosting(target, &retval)) {
2286                         case SEMIHOSTING_NONE:
2287                         case SEMIHOSTING_WAITING:
2288                                 target_call_event_callbacks(target, TARGET_EVENT_HALTED);
2289                                 break;
2290                         case SEMIHOSTING_HANDLED:
2291                                 if (riscv_resume(target, true, 0, 0, 0, false) != ERROR_OK)
2292                                         return ERROR_FAIL;
2293                                 break;
2294                         case SEMIHOSTING_ERROR:
2295                                 return retval;
2296                 }
2297         } else {
2298                 target_call_event_callbacks(target, TARGET_EVENT_HALTED);
2299         }
2300
2301         return ERROR_OK;
2302 }
2303
2304 int riscv_openocd_step(struct target *target, int current,
2305                 target_addr_t address, int handle_breakpoints)
2306 {
2307         LOG_DEBUG("stepping rtos hart");
2308
2309         if (!current)
2310                 riscv_set_register(target, GDB_REGNO_PC, address);
2311
2312         riscv_reg_t trigger_state[RISCV_MAX_HWBPS] = {0};
2313         if (disable_triggers(target, trigger_state) != ERROR_OK)
2314                 return ERROR_FAIL;
2315
2316         int out = riscv_step_rtos_hart(target);
2317         if (out != ERROR_OK) {
2318                 LOG_ERROR("unable to step rtos hart");
2319                 return out;
2320         }
2321
2322         register_cache_invalidate(target->reg_cache);
2323
2324         if (enable_triggers(target, trigger_state) != ERROR_OK)
2325                 return ERROR_FAIL;
2326
2327         target->state = TARGET_RUNNING;
2328         target_call_event_callbacks(target, TARGET_EVENT_RESUMED);
2329         target->state = TARGET_HALTED;
2330         target->debug_reason = DBG_REASON_SINGLESTEP;
2331         target_call_event_callbacks(target, TARGET_EVENT_HALTED);
2332         return out;
2333 }
2334
2335 /* Command Handlers */
2336 COMMAND_HANDLER(riscv_set_command_timeout_sec)
2337 {
2338         if (CMD_ARGC != 1) {
2339                 LOG_ERROR("Command takes exactly 1 parameter");
2340                 return ERROR_COMMAND_SYNTAX_ERROR;
2341         }
2342         int timeout = atoi(CMD_ARGV[0]);
2343         if (timeout <= 0) {
2344                 LOG_ERROR("%s is not a valid integer argument for command.", CMD_ARGV[0]);
2345                 return ERROR_FAIL;
2346         }
2347
2348         riscv_command_timeout_sec = timeout;
2349
2350         return ERROR_OK;
2351 }
2352
2353 COMMAND_HANDLER(riscv_set_reset_timeout_sec)
2354 {
2355         if (CMD_ARGC != 1) {
2356                 LOG_ERROR("Command takes exactly 1 parameter");
2357                 return ERROR_COMMAND_SYNTAX_ERROR;
2358         }
2359         int timeout = atoi(CMD_ARGV[0]);
2360         if (timeout <= 0) {
2361                 LOG_ERROR("%s is not a valid integer argument for command.", CMD_ARGV[0]);
2362                 return ERROR_FAIL;
2363         }
2364
2365         riscv_reset_timeout_sec = timeout;
2366         return ERROR_OK;
2367 }
2368
2369 COMMAND_HANDLER(riscv_set_prefer_sba)
2370 {
2371         struct target *target = get_current_target(CMD_CTX);
2372         RISCV_INFO(r);
2373         bool prefer_sba;
2374         LOG_WARNING("`riscv set_prefer_sba` is deprecated. Please use `riscv set_mem_access` instead.");
2375         if (CMD_ARGC != 1) {
2376                 LOG_ERROR("Command takes exactly 1 parameter");
2377                 return ERROR_COMMAND_SYNTAX_ERROR;
2378         }
2379         COMMAND_PARSE_ON_OFF(CMD_ARGV[0], prefer_sba);
2380         if (prefer_sba) {
2381                 /* Use system bus with highest priority */
2382                 r->mem_access_methods[0] = RISCV_MEM_ACCESS_SYSBUS;
2383                 r->mem_access_methods[1] = RISCV_MEM_ACCESS_PROGBUF;
2384                 r->mem_access_methods[2] = RISCV_MEM_ACCESS_ABSTRACT;
2385         } else {
2386                 /* Use progbuf with highest priority */
2387                 r->mem_access_methods[0] = RISCV_MEM_ACCESS_PROGBUF;
2388                 r->mem_access_methods[1] = RISCV_MEM_ACCESS_SYSBUS;
2389                 r->mem_access_methods[2] = RISCV_MEM_ACCESS_ABSTRACT;
2390         }
2391
2392         /* Reset warning flags */
2393         r->mem_access_progbuf_warn = true;
2394         r->mem_access_sysbus_warn = true;
2395         r->mem_access_abstract_warn = true;
2396
2397         return ERROR_OK;
2398 }
2399
2400 COMMAND_HANDLER(riscv_set_mem_access)
2401 {
2402         struct target *target = get_current_target(CMD_CTX);
2403         RISCV_INFO(r);
2404         int progbuf_cnt = 0;
2405         int sysbus_cnt = 0;
2406         int abstract_cnt = 0;
2407
2408         if (CMD_ARGC < 1 || CMD_ARGC > RISCV_NUM_MEM_ACCESS_METHODS) {
2409                 LOG_ERROR("Command takes 1 to %d parameters", RISCV_NUM_MEM_ACCESS_METHODS);
2410                 return ERROR_COMMAND_SYNTAX_ERROR;
2411         }
2412
2413         /* Check argument validity */
2414         for (unsigned int i = 0; i < CMD_ARGC; i++) {
2415                 if (strcmp("progbuf", CMD_ARGV[i]) == 0) {
2416                         progbuf_cnt++;
2417                 } else if (strcmp("sysbus", CMD_ARGV[i]) == 0) {
2418                         sysbus_cnt++;
2419                 } else if (strcmp("abstract", CMD_ARGV[i]) == 0) {
2420                         abstract_cnt++;
2421                 } else {
2422                         LOG_ERROR("Unknown argument '%s'. "
2423                                 "Must be one of: 'progbuf', 'sysbus' or 'abstract'.", CMD_ARGV[i]);
2424                         return ERROR_COMMAND_SYNTAX_ERROR;
2425                 }
2426         }
2427         if (progbuf_cnt > 1 || sysbus_cnt > 1 || abstract_cnt > 1) {
2428                 LOG_ERROR("Syntax error - duplicate arguments to `riscv set_mem_access`.");
2429                 return ERROR_COMMAND_SYNTAX_ERROR;
2430         }
2431
2432         /* Args are valid, store them */
2433         for (unsigned int i = 0; i < RISCV_NUM_MEM_ACCESS_METHODS; i++)
2434                 r->mem_access_methods[i] = RISCV_MEM_ACCESS_UNSPECIFIED;
2435         for (unsigned int i = 0; i < CMD_ARGC; i++) {
2436                 if (strcmp("progbuf", CMD_ARGV[i]) == 0)
2437                         r->mem_access_methods[i] = RISCV_MEM_ACCESS_PROGBUF;
2438                 else if (strcmp("sysbus", CMD_ARGV[i]) == 0)
2439                         r->mem_access_methods[i] = RISCV_MEM_ACCESS_SYSBUS;
2440                 else if (strcmp("abstract", CMD_ARGV[i]) == 0)
2441                         r->mem_access_methods[i] = RISCV_MEM_ACCESS_ABSTRACT;
2442         }
2443
2444         /* Reset warning flags */
2445         r->mem_access_progbuf_warn = true;
2446         r->mem_access_sysbus_warn = true;
2447         r->mem_access_abstract_warn = true;
2448
2449         return ERROR_OK;
2450 }
2451
2452 COMMAND_HANDLER(riscv_set_enable_virtual)
2453 {
2454         if (CMD_ARGC != 1) {
2455                 LOG_ERROR("Command takes exactly 1 parameter");
2456                 return ERROR_COMMAND_SYNTAX_ERROR;
2457         }
2458         COMMAND_PARSE_ON_OFF(CMD_ARGV[0], riscv_enable_virtual);
2459         return ERROR_OK;
2460 }
2461
2462 static int parse_ranges(struct list_head *ranges, const char *tcl_arg, const char *reg_type, unsigned int max_val)
2463 {
2464         char *args = strdup(tcl_arg);
2465         if (!args)
2466                 return ERROR_FAIL;
2467
2468         /* For backward compatibility, allow multiple parameters within one TCL argument, separated by ',' */
2469         char *arg = strtok(args, ",");
2470         while (arg) {
2471                 unsigned low = 0;
2472                 unsigned high = 0;
2473                 char *name = NULL;
2474
2475                 char *dash = strchr(arg, '-');
2476                 char *equals = strchr(arg, '=');
2477                 unsigned int pos;
2478
2479                 if (!dash && !equals) {
2480                         /* Expecting single register number. */
2481                         if (sscanf(arg, "%u%n", &low, &pos) != 1 || pos != strlen(arg)) {
2482                                 LOG_ERROR("Failed to parse single register number from '%s'.", arg);
2483                                 free(args);
2484                                 return ERROR_COMMAND_SYNTAX_ERROR;
2485                         }
2486                 } else if (dash && !equals) {
2487                         /* Expecting register range - two numbers separated by a dash: ##-## */
2488                         *dash = 0;
2489                         dash++;
2490                         if (sscanf(arg, "%u%n", &low, &pos) != 1 || pos != strlen(arg)) {
2491                                 LOG_ERROR("Failed to parse single register number from '%s'.", arg);
2492                                 free(args);
2493                                 return ERROR_COMMAND_SYNTAX_ERROR;
2494                         }
2495                         if (sscanf(dash, "%u%n", &high, &pos) != 1 || pos != strlen(dash)) {
2496                                 LOG_ERROR("Failed to parse single register number from '%s'.", dash);
2497                                 free(args);
2498                                 return ERROR_COMMAND_SYNTAX_ERROR;
2499                         }
2500                         if (high < low) {
2501                                 LOG_ERROR("Incorrect range encountered [%u, %u].", low, high);
2502                                 free(args);
2503                                 return ERROR_FAIL;
2504                         }
2505                 } else if (!dash && equals) {
2506                         /* Expecting single register number with textual name specified: ##=name */
2507                         *equals = 0;
2508                         equals++;
2509                         if (sscanf(arg, "%u%n", &low, &pos) != 1 || pos != strlen(arg)) {
2510                                 LOG_ERROR("Failed to parse single register number from '%s'.", arg);
2511                                 free(args);
2512                                 return ERROR_COMMAND_SYNTAX_ERROR;
2513                         }
2514
2515                         name = calloc(1, strlen(equals) + strlen(reg_type) + 2);
2516                         if (!name) {
2517                                 LOG_ERROR("Failed to allocate register name.");
2518                                 free(args);
2519                                 return ERROR_FAIL;
2520                         }
2521
2522                         /* Register prefix: "csr_" or "custom_" */
2523                         strcpy(name, reg_type);
2524                         name[strlen(reg_type)] = '_';
2525
2526                         if (sscanf(equals, "%[_a-zA-Z0-9]%n", name + strlen(reg_type) + 1, &pos) != 1 || pos != strlen(equals)) {
2527                                 LOG_ERROR("Failed to parse register name from '%s'.", equals);
2528                                 free(args);
2529                                 free(name);
2530                                 return ERROR_COMMAND_SYNTAX_ERROR;
2531                         }
2532                 } else {
2533                         LOG_ERROR("Invalid argument '%s'.", arg);
2534                         free(args);
2535                         return ERROR_COMMAND_SYNTAX_ERROR;
2536                 }
2537
2538                 high = high > low ? high : low;
2539
2540                 if (high > max_val) {
2541                         LOG_ERROR("Cannot expose %s register number %u, maximum allowed value is %u.", reg_type, high, max_val);
2542                         free(name);
2543                         free(args);
2544                         return ERROR_FAIL;
2545                 }
2546
2547                 /* Check for overlap, name uniqueness. */
2548                 range_list_t *entry;
2549                 list_for_each_entry(entry, ranges, list) {
2550                         if ((entry->low <= high) && (low <= entry->high)) {
2551                                 if (low == high)
2552                                         LOG_WARNING("Duplicate %s register number - "
2553                                                         "Register %u has already been exposed previously", reg_type, low);
2554                                 else
2555                                         LOG_WARNING("Overlapping register ranges - Register range starting from %u overlaps "
2556                                                         "with already exposed register/range at %u.", low, entry->low);
2557                         }
2558
2559                         if (entry->name && name && (strcasecmp(entry->name, name) == 0)) {
2560                                 LOG_ERROR("Duplicate register name \"%s\" found.", name);
2561                                 free(name);
2562                                 free(args);
2563                                 return ERROR_FAIL;
2564                         }
2565                 }
2566
2567                 range_list_t *range = calloc(1, sizeof(range_list_t));
2568                 if (!range) {
2569                         LOG_ERROR("Failed to allocate range list.");
2570                         free(name);
2571                         free(args);
2572                         return ERROR_FAIL;
2573                 }
2574
2575                 range->low = low;
2576                 range->high = high;
2577                 range->name = name;
2578                 list_add(&range->list, ranges);
2579
2580                 arg = strtok(NULL, ",");
2581         }
2582
2583         free(args);
2584         return ERROR_OK;
2585 }
2586
2587 COMMAND_HANDLER(riscv_set_expose_csrs)
2588 {
2589         if (CMD_ARGC == 0) {
2590                 LOG_ERROR("Command expects parameters");
2591                 return ERROR_COMMAND_SYNTAX_ERROR;
2592         }
2593
2594         struct target *target = get_current_target(CMD_CTX);
2595         RISCV_INFO(info);
2596         int ret = ERROR_OK;
2597
2598         for (unsigned int i = 0; i < CMD_ARGC; i++) {
2599                 ret = parse_ranges(&info->expose_csr, CMD_ARGV[i], "csr", 0xfff);
2600                 if (ret != ERROR_OK)
2601                         break;
2602         }
2603
2604         return ret;
2605 }
2606
2607 COMMAND_HANDLER(riscv_set_expose_custom)
2608 {
2609         if (CMD_ARGC == 0) {
2610                 LOG_ERROR("Command expects parameters");
2611                 return ERROR_COMMAND_SYNTAX_ERROR;
2612         }
2613
2614         struct target *target = get_current_target(CMD_CTX);
2615         RISCV_INFO(info);
2616         int ret = ERROR_OK;
2617
2618         for (unsigned int i = 0; i < CMD_ARGC; i++) {
2619                 ret = parse_ranges(&info->expose_custom, CMD_ARGV[i], "custom", 0x3fff);
2620                 if (ret != ERROR_OK)
2621                         break;
2622         }
2623
2624         return ret;
2625 }
2626
2627 COMMAND_HANDLER(riscv_authdata_read)
2628 {
2629         unsigned int index = 0;
2630         if (CMD_ARGC == 0) {
2631                 /* nop */
2632         } else if (CMD_ARGC == 1) {
2633                 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], index);
2634         } else {
2635                 LOG_ERROR("Command takes at most one parameter");
2636                 return ERROR_COMMAND_SYNTAX_ERROR;
2637         }
2638
2639         struct target *target = get_current_target(CMD_CTX);
2640         if (!target) {
2641                 LOG_ERROR("target is NULL!");
2642                 return ERROR_FAIL;
2643         }
2644
2645         RISCV_INFO(r);
2646         if (!r) {
2647                 LOG_ERROR("riscv_info is NULL!");
2648                 return ERROR_FAIL;
2649         }
2650
2651         if (r->authdata_read) {
2652                 uint32_t value;
2653                 if (r->authdata_read(target, &value, index) != ERROR_OK)
2654                         return ERROR_FAIL;
2655                 command_print_sameline(CMD, "0x%08" PRIx32, value);
2656                 return ERROR_OK;
2657         } else {
2658                 LOG_ERROR("authdata_read is not implemented for this target.");
2659                 return ERROR_FAIL;
2660         }
2661 }
2662
2663 COMMAND_HANDLER(riscv_authdata_write)
2664 {
2665         uint32_t value;
2666         unsigned int index = 0;
2667
2668         if (CMD_ARGC == 0) {
2669                 /* nop */
2670         } else if (CMD_ARGC == 1) {
2671                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], value);
2672         } else if (CMD_ARGC == 2) {
2673                 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], index);
2674                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
2675         } else {
2676                 LOG_ERROR("Command takes at most 2 arguments");
2677                 return ERROR_COMMAND_SYNTAX_ERROR;
2678         }
2679
2680         struct target *target = get_current_target(CMD_CTX);
2681         RISCV_INFO(r);
2682
2683         if (r->authdata_write) {
2684                 return r->authdata_write(target, value, index);
2685         } else {
2686                 LOG_ERROR("authdata_write is not implemented for this target.");
2687                 return ERROR_FAIL;
2688         }
2689 }
2690
2691 COMMAND_HANDLER(riscv_dmi_read)
2692 {
2693         if (CMD_ARGC != 1) {
2694                 LOG_ERROR("Command takes 1 parameter");
2695                 return ERROR_COMMAND_SYNTAX_ERROR;
2696         }
2697
2698         struct target *target = get_current_target(CMD_CTX);
2699         if (!target) {
2700                 LOG_ERROR("target is NULL!");
2701                 return ERROR_FAIL;
2702         }
2703
2704         RISCV_INFO(r);
2705         if (!r) {
2706                 LOG_ERROR("riscv_info is NULL!");
2707                 return ERROR_FAIL;
2708         }
2709
2710         if (r->dmi_read) {
2711                 uint32_t address, value;
2712                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2713                 if (r->dmi_read(target, &value, address) != ERROR_OK)
2714                         return ERROR_FAIL;
2715                 command_print(CMD, "0x%" PRIx32, value);
2716                 return ERROR_OK;
2717         } else {
2718                 LOG_ERROR("dmi_read is not implemented for this target.");
2719                 return ERROR_FAIL;
2720         }
2721 }
2722
2723
2724 COMMAND_HANDLER(riscv_dmi_write)
2725 {
2726         if (CMD_ARGC != 2) {
2727                 LOG_ERROR("Command takes exactly 2 arguments");
2728                 return ERROR_COMMAND_SYNTAX_ERROR;
2729         }
2730
2731         struct target *target = get_current_target(CMD_CTX);
2732         RISCV_INFO(r);
2733
2734         uint32_t address, value;
2735         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
2736         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
2737
2738         if (r->dmi_write) {
2739                 return r->dmi_write(target, address, value);
2740         } else {
2741                 LOG_ERROR("dmi_write is not implemented for this target.");
2742                 return ERROR_FAIL;
2743         }
2744 }
2745
2746 COMMAND_HANDLER(riscv_test_sba_config_reg)
2747 {
2748         if (CMD_ARGC != 4) {
2749                 LOG_ERROR("Command takes exactly 4 arguments");
2750                 return ERROR_COMMAND_SYNTAX_ERROR;
2751         }
2752
2753         struct target *target = get_current_target(CMD_CTX);
2754         RISCV_INFO(r);
2755
2756         target_addr_t legal_address;
2757         uint32_t num_words;
2758         target_addr_t illegal_address;
2759         bool run_sbbusyerror_test;
2760
2761         COMMAND_PARSE_NUMBER(target_addr, CMD_ARGV[0], legal_address);
2762         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], num_words);
2763         COMMAND_PARSE_NUMBER(target_addr, CMD_ARGV[2], illegal_address);
2764         COMMAND_PARSE_ON_OFF(CMD_ARGV[3], run_sbbusyerror_test);
2765
2766         if (r->test_sba_config_reg) {
2767                 return r->test_sba_config_reg(target, legal_address, num_words,
2768                                 illegal_address, run_sbbusyerror_test);
2769         } else {
2770                 LOG_ERROR("test_sba_config_reg is not implemented for this target.");
2771                 return ERROR_FAIL;
2772         }
2773 }
2774
2775 COMMAND_HANDLER(riscv_reset_delays)
2776 {
2777         int wait = 0;
2778
2779         if (CMD_ARGC > 1) {
2780                 LOG_ERROR("Command takes at most one argument");
2781                 return ERROR_COMMAND_SYNTAX_ERROR;
2782         }
2783
2784         if (CMD_ARGC == 1)
2785                 COMMAND_PARSE_NUMBER(int, CMD_ARGV[0], wait);
2786
2787         struct target *target = get_current_target(CMD_CTX);
2788         RISCV_INFO(r);
2789         r->reset_delays_wait = wait;
2790         return ERROR_OK;
2791 }
2792
2793 COMMAND_HANDLER(riscv_set_ir)
2794 {
2795         if (CMD_ARGC != 2) {
2796                 LOG_ERROR("Command takes exactly 2 arguments");
2797                 return ERROR_COMMAND_SYNTAX_ERROR;
2798         }
2799
2800         uint32_t value;
2801         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
2802
2803         if (!strcmp(CMD_ARGV[0], "idcode"))
2804                 buf_set_u32(ir_idcode, 0, 32, value);
2805         else if (!strcmp(CMD_ARGV[0], "dtmcs"))
2806                 buf_set_u32(ir_dtmcontrol, 0, 32, value);
2807         else if (!strcmp(CMD_ARGV[0], "dmi"))
2808                 buf_set_u32(ir_dbus, 0, 32, value);
2809         else
2810                 return ERROR_FAIL;
2811
2812         return ERROR_OK;
2813 }
2814
2815 COMMAND_HANDLER(riscv_resume_order)
2816 {
2817         if (CMD_ARGC > 1) {
2818                 LOG_ERROR("Command takes at most one argument");
2819                 return ERROR_COMMAND_SYNTAX_ERROR;
2820         }
2821
2822         if (!strcmp(CMD_ARGV[0], "normal")) {
2823                 resume_order = RO_NORMAL;
2824         } else if (!strcmp(CMD_ARGV[0], "reversed")) {
2825                 resume_order = RO_REVERSED;
2826         } else {
2827                 LOG_ERROR("Unsupported resume order: %s", CMD_ARGV[0]);
2828                 return ERROR_FAIL;
2829         }
2830
2831         return ERROR_OK;
2832 }
2833
2834 COMMAND_HANDLER(riscv_use_bscan_tunnel)
2835 {
2836         int irwidth = 0;
2837         int tunnel_type = BSCAN_TUNNEL_NESTED_TAP;
2838
2839         if (CMD_ARGC > 2) {
2840                 LOG_ERROR("Command takes at most two arguments");
2841                 return ERROR_COMMAND_SYNTAX_ERROR;
2842         } else if (CMD_ARGC == 1) {
2843                 COMMAND_PARSE_NUMBER(int, CMD_ARGV[0], irwidth);
2844         } else if (CMD_ARGC == 2) {
2845                 COMMAND_PARSE_NUMBER(int, CMD_ARGV[0], irwidth);
2846                 COMMAND_PARSE_NUMBER(int, CMD_ARGV[1], tunnel_type);
2847         }
2848         if (tunnel_type == BSCAN_TUNNEL_NESTED_TAP)
2849                 LOG_INFO("Nested Tap based Bscan Tunnel Selected");
2850         else if (tunnel_type == BSCAN_TUNNEL_DATA_REGISTER)
2851                 LOG_INFO("Simple Register based Bscan Tunnel Selected");
2852         else
2853                 LOG_INFO("Invalid Tunnel type selected ! : selecting default Nested Tap Type");
2854
2855         bscan_tunnel_type = tunnel_type;
2856         bscan_tunnel_ir_width = irwidth;
2857         return ERROR_OK;
2858 }
2859
2860 COMMAND_HANDLER(riscv_set_enable_virt2phys)
2861 {
2862         if (CMD_ARGC != 1) {
2863                 LOG_ERROR("Command takes exactly 1 parameter");
2864                 return ERROR_COMMAND_SYNTAX_ERROR;
2865         }
2866         COMMAND_PARSE_ON_OFF(CMD_ARGV[0], riscv_enable_virt2phys);
2867         return ERROR_OK;
2868 }
2869
2870 COMMAND_HANDLER(riscv_set_ebreakm)
2871 {
2872         if (CMD_ARGC != 1) {
2873                 LOG_ERROR("Command takes exactly 1 parameter");
2874                 return ERROR_COMMAND_SYNTAX_ERROR;
2875         }
2876         COMMAND_PARSE_ON_OFF(CMD_ARGV[0], riscv_ebreakm);
2877         return ERROR_OK;
2878 }
2879
2880 COMMAND_HANDLER(riscv_set_ebreaks)
2881 {
2882         if (CMD_ARGC != 1) {
2883                 LOG_ERROR("Command takes exactly 1 parameter");
2884                 return ERROR_COMMAND_SYNTAX_ERROR;
2885         }
2886         COMMAND_PARSE_ON_OFF(CMD_ARGV[0], riscv_ebreaks);
2887         return ERROR_OK;
2888 }
2889
2890 COMMAND_HANDLER(riscv_set_ebreaku)
2891 {
2892         if (CMD_ARGC != 1) {
2893                 LOG_ERROR("Command takes exactly 1 parameter");
2894                 return ERROR_COMMAND_SYNTAX_ERROR;
2895         }
2896         COMMAND_PARSE_ON_OFF(CMD_ARGV[0], riscv_ebreaku);
2897         return ERROR_OK;
2898 }
2899
2900 COMMAND_HELPER(riscv_print_info_line, const char *section, const char *key,
2901                            unsigned int value)
2902 {
2903         char full_key[80];
2904         snprintf(full_key, sizeof(full_key), "%s.%s", section, key);
2905         command_print(CMD, "%-21s %3d", full_key, value);
2906         return 0;
2907 }
2908
2909 COMMAND_HANDLER(handle_info)
2910 {
2911         struct target *target = get_current_target(CMD_CTX);
2912         RISCV_INFO(r);
2913
2914         /* This output format can be fed directly into TCL's "array set". */
2915
2916         riscv_print_info_line(CMD, "hart", "xlen", riscv_xlen(target));
2917         riscv_enumerate_triggers(target);
2918         riscv_print_info_line(CMD, "hart", "trigger_count",
2919                                                   r->trigger_count);
2920
2921         if (r->print_info)
2922                 return CALL_COMMAND_HANDLER(r->print_info, target);
2923
2924         return 0;
2925 }
2926
2927 static const struct command_registration riscv_exec_command_handlers[] = {
2928         {
2929                 .name = "info",
2930                 .handler = handle_info,
2931                 .mode = COMMAND_EXEC,
2932                 .usage = "",
2933                 .help = "Displays some information OpenOCD detected about the target."
2934         },
2935         {
2936                 .name = "set_command_timeout_sec",
2937                 .handler = riscv_set_command_timeout_sec,
2938                 .mode = COMMAND_ANY,
2939                 .usage = "[sec]",
2940                 .help = "Set the wall-clock timeout (in seconds) for individual commands"
2941         },
2942         {
2943                 .name = "set_reset_timeout_sec",
2944                 .handler = riscv_set_reset_timeout_sec,
2945                 .mode = COMMAND_ANY,
2946                 .usage = "[sec]",
2947                 .help = "Set the wall-clock timeout (in seconds) after reset is deasserted"
2948         },
2949         {
2950                 .name = "set_prefer_sba",
2951                 .handler = riscv_set_prefer_sba,
2952                 .mode = COMMAND_ANY,
2953                 .usage = "on|off",
2954                 .help = "When on, prefer to use System Bus Access to access memory. "
2955                         "When off (default), prefer to use the Program Buffer to access memory."
2956         },
2957         {
2958                 .name = "set_mem_access",
2959                 .handler = riscv_set_mem_access,
2960                 .mode = COMMAND_ANY,
2961                 .usage = "method1 [method2] [method3]",
2962                 .help = "Set which memory access methods shall be used and in which order "
2963                         "of priority. Method can be one of: 'progbuf', 'sysbus' or 'abstract'."
2964         },
2965         {
2966                 .name = "set_enable_virtual",
2967                 .handler = riscv_set_enable_virtual,
2968                 .mode = COMMAND_ANY,
2969                 .usage = "on|off",
2970                 .help = "When on, memory accesses are performed on physical or virtual "
2971                                 "memory depending on the current system configuration. "
2972                                 "When off (default), all memory accessses are performed on physical memory."
2973         },
2974         {
2975                 .name = "expose_csrs",
2976                 .handler = riscv_set_expose_csrs,
2977                 .mode = COMMAND_CONFIG,
2978                 .usage = "n0[-m0|=name0][,n1[-m1|=name1]]...",
2979                 .help = "Configure a list of inclusive ranges for CSRs to expose in "
2980                                 "addition to the standard ones. This must be executed before "
2981                                 "`init`."
2982         },
2983         {
2984                 .name = "expose_custom",
2985                 .handler = riscv_set_expose_custom,
2986                 .mode = COMMAND_CONFIG,
2987                 .usage = "n0[-m0|=name0][,n1[-m1|=name1]]...",
2988                 .help = "Configure a list of inclusive ranges for custom registers to "
2989                         "expose. custom0 is accessed as abstract register number 0xc000, "
2990                         "etc. This must be executed before `init`."
2991         },
2992         {
2993                 .name = "authdata_read",
2994                 .handler = riscv_authdata_read,
2995                 .usage = "[index]",
2996                 .mode = COMMAND_ANY,
2997                 .help = "Return the 32-bit value read from authdata or authdata0 "
2998                                 "(index=0), or authdata1 (index=1)."
2999         },
3000         {
3001                 .name = "authdata_write",
3002                 .handler = riscv_authdata_write,
3003                 .mode = COMMAND_ANY,
3004                 .usage = "[index] value",
3005                 .help = "Write the 32-bit value to authdata or authdata0 (index=0), "
3006                                 "or authdata1 (index=1)."
3007         },
3008         {
3009                 .name = "dmi_read",
3010                 .handler = riscv_dmi_read,
3011                 .mode = COMMAND_ANY,
3012                 .usage = "address",
3013                 .help = "Perform a 32-bit DMI read at address, returning the value."
3014         },
3015         {
3016                 .name = "dmi_write",
3017                 .handler = riscv_dmi_write,
3018                 .mode = COMMAND_ANY,
3019                 .usage = "address value",
3020                 .help = "Perform a 32-bit DMI write of value at address."
3021         },
3022         {
3023                 .name = "test_sba_config_reg",
3024                 .handler = riscv_test_sba_config_reg,
3025                 .mode = COMMAND_ANY,
3026                 .usage = "legal_address num_words "
3027                         "illegal_address run_sbbusyerror_test[on/off]",
3028                 .help = "Perform a series of tests on the SBCS register. "
3029                         "Inputs are a legal, 128-byte aligned address and a number of words to "
3030                         "read/write starting at that address (i.e., address range [legal address, "
3031                         "legal_address+word_size*num_words) must be legally readable/writable), "
3032                         "an illegal, 128-byte aligned address for error flag/handling cases, "
3033                         "and whether sbbusyerror test should be run."
3034         },
3035         {
3036                 .name = "reset_delays",
3037                 .handler = riscv_reset_delays,
3038                 .mode = COMMAND_ANY,
3039                 .usage = "[wait]",
3040                 .help = "OpenOCD learns how many Run-Test/Idle cycles are required "
3041                         "between scans to avoid encountering the target being busy. This "
3042                         "command resets those learned values after `wait` scans. It's only "
3043                         "useful for testing OpenOCD itself."
3044         },
3045         {
3046                 .name = "resume_order",
3047                 .handler = riscv_resume_order,
3048                 .mode = COMMAND_ANY,
3049                 .usage = "normal|reversed",
3050                 .help = "Choose the order that harts are resumed in when `hasel` is not "
3051                         "supported. Normal order is from lowest hart index to highest. "
3052                         "Reversed order is from highest hart index to lowest."
3053         },
3054         {
3055                 .name = "set_ir",
3056                 .handler = riscv_set_ir,
3057                 .mode = COMMAND_ANY,
3058                 .usage = "[idcode|dtmcs|dmi] value",
3059                 .help = "Set IR value for specified JTAG register."
3060         },
3061         {
3062                 .name = "use_bscan_tunnel",
3063                 .handler = riscv_use_bscan_tunnel,
3064                 .mode = COMMAND_ANY,
3065                 .usage = "value [type]",
3066                 .help = "Enable or disable use of a BSCAN tunnel to reach DM.  Supply "
3067                         "the width of the DM transport TAP's instruction register to "
3068                         "enable.  Supply a value of 0 to disable. Pass A second argument "
3069                         "(optional) to indicate Bscan Tunnel Type {0:(default) NESTED_TAP , "
3070                         "1: DATA_REGISTER}"
3071         },
3072         {
3073                 .name = "set_enable_virt2phys",
3074                 .handler = riscv_set_enable_virt2phys,
3075                 .mode = COMMAND_ANY,
3076                 .usage = "on|off",
3077                 .help = "When on (default), enable translation from virtual address to "
3078                         "physical address."
3079         },
3080         {
3081                 .name = "set_ebreakm",
3082                 .handler = riscv_set_ebreakm,
3083                 .mode = COMMAND_ANY,
3084                 .usage = "on|off",
3085                 .help = "Control dcsr.ebreakm. When off, M-mode ebreak instructions "
3086                         "don't trap to OpenOCD. Defaults to on."
3087         },
3088         {
3089                 .name = "set_ebreaks",
3090                 .handler = riscv_set_ebreaks,
3091                 .mode = COMMAND_ANY,
3092                 .usage = "on|off",
3093                 .help = "Control dcsr.ebreaks. When off, S-mode ebreak instructions "
3094                         "don't trap to OpenOCD. Defaults to on."
3095         },
3096         {
3097                 .name = "set_ebreaku",
3098                 .handler = riscv_set_ebreaku,
3099                 .mode = COMMAND_ANY,
3100                 .usage = "on|off",
3101                 .help = "Control dcsr.ebreaku. When off, U-mode ebreak instructions "
3102                         "don't trap to OpenOCD. Defaults to on."
3103         },
3104         COMMAND_REGISTRATION_DONE
3105 };
3106
3107 /*
3108  * To be noted that RISC-V targets use the same semihosting commands as
3109  * ARM targets.
3110  *
3111  * The main reason is compatibility with existing tools. For example the
3112  * Eclipse OpenOCD/SEGGER J-Link/QEMU plug-ins have several widgets to
3113  * configure semihosting, which generate commands like `arm semihosting
3114  * enable`.
3115  * A secondary reason is the fact that the protocol used is exactly the
3116  * one specified by ARM. If RISC-V will ever define its own semihosting
3117  * protocol, then a command like `riscv semihosting enable` will make
3118  * sense, but for now all semihosting commands are prefixed with `arm`.
3119  */
3120
3121 static const struct command_registration riscv_command_handlers[] = {
3122         {
3123                 .name = "riscv",
3124                 .mode = COMMAND_ANY,
3125                 .help = "RISC-V Command Group",
3126                 .usage = "",
3127                 .chain = riscv_exec_command_handlers
3128         },
3129         {
3130                 .name = "arm",
3131                 .mode = COMMAND_ANY,
3132                 .help = "ARM Command Group",
3133                 .usage = "",
3134                 .chain = semihosting_common_handlers
3135         },
3136         COMMAND_REGISTRATION_DONE
3137 };
3138
3139 static unsigned riscv_xlen_nonconst(struct target *target)
3140 {
3141         return riscv_xlen(target);
3142 }
3143
3144 static unsigned int riscv_data_bits(struct target *target)
3145 {
3146         RISCV_INFO(r);
3147         if (r->data_bits)
3148                 return r->data_bits(target);
3149         return riscv_xlen(target);
3150 }
3151
3152 struct target_type riscv_target = {
3153         .name = "riscv",
3154
3155         .target_create = riscv_create_target,
3156         .init_target = riscv_init_target,
3157         .deinit_target = riscv_deinit_target,
3158         .examine = riscv_examine,
3159
3160         /* poll current target status */
3161         .poll = old_or_new_riscv_poll,
3162
3163         .halt = riscv_halt,
3164         .resume = riscv_target_resume,
3165         .step = old_or_new_riscv_step,
3166
3167         .assert_reset = riscv_assert_reset,
3168         .deassert_reset = riscv_deassert_reset,
3169
3170         .read_memory = riscv_read_memory,
3171         .write_memory = riscv_write_memory,
3172         .read_phys_memory = riscv_read_phys_memory,
3173         .write_phys_memory = riscv_write_phys_memory,
3174
3175         .checksum_memory = riscv_checksum_memory,
3176
3177         .mmu = riscv_mmu,
3178         .virt2phys = riscv_virt2phys,
3179
3180         .get_gdb_arch = riscv_get_gdb_arch,
3181         .get_gdb_reg_list = riscv_get_gdb_reg_list,
3182         .get_gdb_reg_list_noread = riscv_get_gdb_reg_list_noread,
3183
3184         .add_breakpoint = riscv_add_breakpoint,
3185         .remove_breakpoint = riscv_remove_breakpoint,
3186
3187         .add_watchpoint = riscv_add_watchpoint,
3188         .remove_watchpoint = riscv_remove_watchpoint,
3189         .hit_watchpoint = riscv_hit_watchpoint,
3190
3191         .arch_state = riscv_arch_state,
3192
3193         .run_algorithm = riscv_run_algorithm,
3194
3195         .commands = riscv_command_handlers,
3196
3197         .address_bits = riscv_xlen_nonconst,
3198         .data_bits = riscv_data_bits
3199 };
3200
3201 /*** RISC-V Interface ***/
3202
3203 /* Initializes the shared RISC-V structure. */
3204 static void riscv_info_init(struct target *target, struct riscv_info *r)
3205 {
3206         memset(r, 0, sizeof(*r));
3207
3208         r->common_magic = RISCV_COMMON_MAGIC;
3209
3210         r->dtm_version = 1;
3211         r->current_hartid = target->coreid;
3212         r->version_specific = NULL;
3213
3214         memset(r->trigger_unique_id, 0xff, sizeof(r->trigger_unique_id));
3215
3216         r->xlen = -1;
3217
3218         r->mem_access_methods[0] = RISCV_MEM_ACCESS_PROGBUF;
3219         r->mem_access_methods[1] = RISCV_MEM_ACCESS_SYSBUS;
3220         r->mem_access_methods[2] = RISCV_MEM_ACCESS_ABSTRACT;
3221
3222         r->mem_access_progbuf_warn = true;
3223         r->mem_access_sysbus_warn = true;
3224         r->mem_access_abstract_warn = true;
3225
3226         INIT_LIST_HEAD(&r->expose_csr);
3227         INIT_LIST_HEAD(&r->expose_custom);
3228 }
3229
3230 static int riscv_resume_go_all_harts(struct target *target)
3231 {
3232         RISCV_INFO(r);
3233
3234         LOG_DEBUG("[%s] resuming hart", target_name(target));
3235         if (riscv_select_current_hart(target) != ERROR_OK)
3236                 return ERROR_FAIL;
3237         if (riscv_is_halted(target)) {
3238                 if (r->resume_go(target) != ERROR_OK)
3239                         return ERROR_FAIL;
3240         } else {
3241                 LOG_DEBUG("[%s] hart requested resume, but was already resumed",
3242                                 target_name(target));
3243         }
3244
3245         riscv_invalidate_register_cache(target);
3246         return ERROR_OK;
3247 }
3248
3249 /* Steps the hart that's currently selected in the RTOS, or if there is no RTOS
3250  * then the only hart. */
3251 static int riscv_step_rtos_hart(struct target *target)
3252 {
3253         RISCV_INFO(r);
3254         if (riscv_select_current_hart(target) != ERROR_OK)
3255                 return ERROR_FAIL;
3256         LOG_DEBUG("[%s] stepping", target_name(target));
3257
3258         if (!riscv_is_halted(target)) {
3259                 LOG_ERROR("Hart isn't halted before single step!");
3260                 return ERROR_FAIL;
3261         }
3262         riscv_invalidate_register_cache(target);
3263         r->on_step(target);
3264         if (r->step_current_hart(target) != ERROR_OK)
3265                 return ERROR_FAIL;
3266         riscv_invalidate_register_cache(target);
3267         r->on_halt(target);
3268         if (!riscv_is_halted(target)) {
3269                 LOG_ERROR("Hart was not halted after single step!");
3270                 return ERROR_FAIL;
3271         }
3272         return ERROR_OK;
3273 }
3274
3275 bool riscv_supports_extension(struct target *target, char letter)
3276 {
3277         RISCV_INFO(r);
3278         unsigned num;
3279         if (letter >= 'a' && letter <= 'z')
3280                 num = letter - 'a';
3281         else if (letter >= 'A' && letter <= 'Z')
3282                 num = letter - 'A';
3283         else
3284                 return false;
3285         return r->misa & BIT(num);
3286 }
3287
3288 unsigned riscv_xlen(const struct target *target)
3289 {
3290         RISCV_INFO(r);
3291         return r->xlen;
3292 }
3293
3294 int riscv_set_current_hartid(struct target *target, int hartid)
3295 {
3296         RISCV_INFO(r);
3297         if (!r->select_current_hart)
3298                 return ERROR_OK;
3299
3300         int previous_hartid = riscv_current_hartid(target);
3301         r->current_hartid = hartid;
3302         LOG_DEBUG("setting hartid to %d, was %d", hartid, previous_hartid);
3303         if (r->select_current_hart(target) != ERROR_OK)
3304                 return ERROR_FAIL;
3305
3306         return ERROR_OK;
3307 }
3308
3309 /* Invalidates the register cache. */
3310 static void riscv_invalidate_register_cache(struct target *target)
3311 {
3312         LOG_DEBUG("[%d]", target->coreid);
3313         register_cache_invalidate(target->reg_cache);
3314         for (size_t i = 0; i < target->reg_cache->num_regs; ++i) {
3315                 struct reg *reg = &target->reg_cache->reg_list[i];
3316                 reg->valid = false;
3317         }
3318 }
3319
3320 int riscv_current_hartid(const struct target *target)
3321 {
3322         RISCV_INFO(r);
3323         return r->current_hartid;
3324 }
3325
3326 int riscv_count_harts(struct target *target)
3327 {
3328         if (!target)
3329                 return 1;
3330         RISCV_INFO(r);
3331         if (!r || !r->hart_count)
3332                 return 1;
3333         return r->hart_count(target);
3334 }
3335
3336 /**
3337  * If write is true:
3338  *   return true iff we are guaranteed that the register will contain exactly
3339  *       the value we just wrote when it's read.
3340  * If write is false:
3341  *   return true iff we are guaranteed that the register will read the same
3342  *       value in the future as the value we just read.
3343  */
3344 static bool gdb_regno_cacheable(enum gdb_regno regno, bool write)
3345 {
3346         /* GPRs, FPRs, vector registers are just normal data stores. */
3347         if (regno <= GDB_REGNO_XPR31 ||
3348                         (regno >= GDB_REGNO_FPR0 && regno <= GDB_REGNO_FPR31) ||
3349                         (regno >= GDB_REGNO_V0 && regno <= GDB_REGNO_V31))
3350                 return true;
3351
3352         /* Most CSRs won't change value on us, but we can't assume it about arbitrary
3353          * CSRs. */
3354         switch (regno) {
3355                 case GDB_REGNO_DPC:
3356                         return true;
3357
3358                 case GDB_REGNO_VSTART:
3359                 case GDB_REGNO_VXSAT:
3360                 case GDB_REGNO_VXRM:
3361                 case GDB_REGNO_VLENB:
3362                 case GDB_REGNO_VL:
3363                 case GDB_REGNO_VTYPE:
3364                 case GDB_REGNO_MISA:
3365                 case GDB_REGNO_DCSR:
3366                 case GDB_REGNO_DSCRATCH0:
3367                 case GDB_REGNO_MSTATUS:
3368                 case GDB_REGNO_MEPC:
3369                 case GDB_REGNO_MCAUSE:
3370                 case GDB_REGNO_SATP:
3371                         /*
3372                          * WARL registers might not contain the value we just wrote, but
3373                          * these ones won't spontaneously change their value either. *
3374                          */
3375                         return !write;
3376
3377                 case GDB_REGNO_TSELECT: /* I think this should be above, but then it doesn't work. */
3378                 case GDB_REGNO_TDATA1:  /* Changes value when tselect is changed. */
3379                 case GDB_REGNO_TDATA2:  /* Changse value when tselect is changed. */
3380                 default:
3381                         return false;
3382         }
3383 }
3384
3385 /**
3386  * This function is called when the debug user wants to change the value of a
3387  * register. The new value may be cached, and may not be written until the hart
3388  * is resumed. */
3389 int riscv_set_register(struct target *target, enum gdb_regno regid, riscv_reg_t value)
3390 {
3391         RISCV_INFO(r);
3392         LOG_DEBUG("[%s] %s <- %" PRIx64, target_name(target), gdb_regno_name(regid), value);
3393         assert(r->set_register);
3394
3395         keep_alive();
3396
3397         /* TODO: Hack to deal with gdb that thinks these registers still exist. */
3398         if (regid > GDB_REGNO_XPR15 && regid <= GDB_REGNO_XPR31 && value == 0 &&
3399                         riscv_supports_extension(target, 'E'))
3400                 return ERROR_OK;
3401
3402         struct reg *reg = &target->reg_cache->reg_list[regid];
3403         buf_set_u64(reg->value, 0, reg->size, value);
3404
3405         int result = r->set_register(target, regid, value);
3406         if (result == ERROR_OK)
3407                 reg->valid = gdb_regno_cacheable(regid, true);
3408         else
3409                 reg->valid = false;
3410         LOG_DEBUG("[%s] wrote 0x%" PRIx64 " to %s valid=%d",
3411                           target_name(target), value, reg->name, reg->valid);
3412         return result;
3413 }
3414
3415 int riscv_get_register(struct target *target, riscv_reg_t *value,
3416                 enum gdb_regno regid)
3417 {
3418         RISCV_INFO(r);
3419
3420         keep_alive();
3421
3422         struct reg *reg = &target->reg_cache->reg_list[regid];
3423         if (!reg->exist) {
3424                 LOG_DEBUG("[%s] %s does not exist.",
3425                                   target_name(target), gdb_regno_name(regid));
3426                 return ERROR_FAIL;
3427         }
3428
3429         if (reg && reg->valid) {
3430                 *value = buf_get_u64(reg->value, 0, reg->size);
3431                 LOG_DEBUG("[%s] %s: %" PRIx64 " (cached)", target_name(target),
3432                                   gdb_regno_name(regid), *value);
3433                 return ERROR_OK;
3434         }
3435
3436         /* TODO: Hack to deal with gdb that thinks these registers still exist. */
3437         if (regid > GDB_REGNO_XPR15 && regid <= GDB_REGNO_XPR31 &&
3438                         riscv_supports_extension(target, 'E')) {
3439                 *value = 0;
3440                 return ERROR_OK;
3441         }
3442
3443         int result = r->get_register(target, value, regid);
3444
3445         if (result == ERROR_OK)
3446                 reg->valid = gdb_regno_cacheable(regid, false);
3447
3448         LOG_DEBUG("[%s] %s: %" PRIx64, target_name(target),
3449                         gdb_regno_name(regid), *value);
3450         return result;
3451 }
3452
3453 bool riscv_is_halted(struct target *target)
3454 {
3455         RISCV_INFO(r);
3456         assert(r->is_halted);
3457         return r->is_halted(target);
3458 }
3459
3460 static enum riscv_halt_reason riscv_halt_reason(struct target *target, int hartid)
3461 {
3462         RISCV_INFO(r);
3463         if (riscv_set_current_hartid(target, hartid) != ERROR_OK)
3464                 return RISCV_HALT_ERROR;
3465         if (!riscv_is_halted(target)) {
3466                 LOG_ERROR("Hart is not halted!");
3467                 return RISCV_HALT_UNKNOWN;
3468         }
3469         return r->halt_reason(target);
3470 }
3471
3472 size_t riscv_debug_buffer_size(struct target *target)
3473 {
3474         RISCV_INFO(r);
3475         return r->debug_buffer_size;
3476 }
3477
3478 int riscv_write_debug_buffer(struct target *target, int index, riscv_insn_t insn)
3479 {
3480         RISCV_INFO(r);
3481         r->write_debug_buffer(target, index, insn);
3482         return ERROR_OK;
3483 }
3484
3485 riscv_insn_t riscv_read_debug_buffer(struct target *target, int index)
3486 {
3487         RISCV_INFO(r);
3488         return r->read_debug_buffer(target, index);
3489 }
3490
3491 int riscv_execute_debug_buffer(struct target *target)
3492 {
3493         RISCV_INFO(r);
3494         return r->execute_debug_buffer(target);
3495 }
3496
3497 void riscv_fill_dmi_write_u64(struct target *target, char *buf, int a, uint64_t d)
3498 {
3499         RISCV_INFO(r);
3500         r->fill_dmi_write_u64(target, buf, a, d);
3501 }
3502
3503 void riscv_fill_dmi_read_u64(struct target *target, char *buf, int a)
3504 {
3505         RISCV_INFO(r);
3506         r->fill_dmi_read_u64(target, buf, a);
3507 }
3508
3509 void riscv_fill_dmi_nop_u64(struct target *target, char *buf)
3510 {
3511         RISCV_INFO(r);
3512         r->fill_dmi_nop_u64(target, buf);
3513 }
3514
3515 int riscv_dmi_write_u64_bits(struct target *target)
3516 {
3517         RISCV_INFO(r);
3518         return r->dmi_write_u64_bits(target);
3519 }
3520
3521 /**
3522  * Count triggers, and initialize trigger_count for each hart.
3523  * trigger_count is initialized even if this function fails to discover
3524  * something.
3525  * Disable any hardware triggers that have dmode set. We can't have set them
3526  * ourselves. Maybe they're left over from some killed debug session.
3527  * */
3528 int riscv_enumerate_triggers(struct target *target)
3529 {
3530         RISCV_INFO(r);
3531
3532         if (r->triggers_enumerated)
3533                 return ERROR_OK;
3534
3535         r->triggers_enumerated = true;  /* At the very least we tried. */
3536
3537         riscv_reg_t tselect;
3538         int result = riscv_get_register(target, &tselect, GDB_REGNO_TSELECT);
3539         /* If tselect is not readable, the trigger module is likely not
3540                 * implemented. There are no triggers to enumerate then and no error
3541                 * should be thrown. */
3542         if (result != ERROR_OK) {
3543                 LOG_DEBUG("[%s] Cannot access tselect register. "
3544                                 "Assuming that triggers are not implemented.", target_name(target));
3545                 r->trigger_count = 0;
3546                 return ERROR_OK;
3547         }
3548
3549         for (unsigned int t = 0; t < RISCV_MAX_TRIGGERS; ++t) {
3550                 r->trigger_count = t;
3551
3552                 /* If we can't write tselect, then this hart does not support triggers. */
3553                 if (riscv_set_register(target, GDB_REGNO_TSELECT, t) != ERROR_OK)
3554                         break;
3555                 uint64_t tselect_rb;
3556                 result = riscv_get_register(target, &tselect_rb, GDB_REGNO_TSELECT);
3557                 if (result != ERROR_OK)
3558                         return result;
3559                 /* Mask off the top bit, which is used as tdrmode in old
3560                         * implementations. */
3561                 tselect_rb &= ~(1ULL << (riscv_xlen(target) - 1));
3562                 if (tselect_rb != t)
3563                         break;
3564                 uint64_t tdata1;
3565                 result = riscv_get_register(target, &tdata1, GDB_REGNO_TDATA1);
3566                 if (result != ERROR_OK)
3567                         return result;
3568
3569                 int type = get_field(tdata1, MCONTROL_TYPE(riscv_xlen(target)));
3570                 if (type == 0)
3571                         break;
3572                 switch (type) {
3573                         case 1:
3574                                 /* On these older cores we don't support software using
3575                                         * triggers. */
3576                                 riscv_set_register(target, GDB_REGNO_TDATA1, 0);
3577                                 break;
3578                         case 2:
3579                                 if (tdata1 & MCONTROL_DMODE(riscv_xlen(target)))
3580                                         riscv_set_register(target, GDB_REGNO_TDATA1, 0);
3581                                 break;
3582                         case 6:
3583                                 if (tdata1 & MCONTROL_DMODE(riscv_xlen(target)))
3584                                         riscv_set_register(target, GDB_REGNO_TDATA1, 0);
3585                                 break;
3586                 }
3587         }
3588
3589         riscv_set_register(target, GDB_REGNO_TSELECT, tselect);
3590
3591         LOG_INFO("[%s] Found %d triggers", target_name(target), r->trigger_count);
3592
3593         return ERROR_OK;
3594 }
3595
3596 const char *gdb_regno_name(enum gdb_regno regno)
3597 {
3598         static char buf[32];
3599
3600         switch (regno) {
3601                 case GDB_REGNO_ZERO:
3602                         return "zero";
3603                 case GDB_REGNO_RA:
3604                         return "ra";
3605                 case GDB_REGNO_SP:
3606                         return "sp";
3607                 case GDB_REGNO_GP:
3608                         return "gp";
3609                 case GDB_REGNO_TP:
3610                         return "tp";
3611                 case GDB_REGNO_T0:
3612                         return "t0";
3613                 case GDB_REGNO_T1:
3614                         return "t1";
3615                 case GDB_REGNO_T2:
3616                         return "t2";
3617                 case GDB_REGNO_S0:
3618                         return "s0";
3619                 case GDB_REGNO_S1:
3620                         return "s1";
3621                 case GDB_REGNO_A0:
3622                         return "a0";
3623                 case GDB_REGNO_A1:
3624                         return "a1";
3625                 case GDB_REGNO_A2:
3626                         return "a2";
3627                 case GDB_REGNO_A3:
3628                         return "a3";
3629                 case GDB_REGNO_A4:
3630                         return "a4";
3631                 case GDB_REGNO_A5:
3632                         return "a5";
3633                 case GDB_REGNO_A6:
3634                         return "a6";
3635                 case GDB_REGNO_A7:
3636                         return "a7";
3637                 case GDB_REGNO_S2:
3638                         return "s2";
3639                 case GDB_REGNO_S3:
3640                         return "s3";
3641                 case GDB_REGNO_S4:
3642                         return "s4";
3643                 case GDB_REGNO_S5:
3644                         return "s5";
3645                 case GDB_REGNO_S6:
3646                         return "s6";
3647                 case GDB_REGNO_S7:
3648                         return "s7";
3649                 case GDB_REGNO_S8:
3650                         return "s8";
3651                 case GDB_REGNO_S9:
3652                         return "s9";
3653                 case GDB_REGNO_S10:
3654                         return "s10";
3655                 case GDB_REGNO_S11:
3656                         return "s11";
3657                 case GDB_REGNO_T3:
3658                         return "t3";
3659                 case GDB_REGNO_T4:
3660                         return "t4";
3661                 case GDB_REGNO_T5:
3662                         return "t5";
3663                 case GDB_REGNO_T6:
3664                         return "t6";
3665                 case GDB_REGNO_PC:
3666                         return "pc";
3667                 case GDB_REGNO_FPR0:
3668                         return "fpr0";
3669                 case GDB_REGNO_FPR31:
3670                         return "fpr31";
3671                 case GDB_REGNO_CSR0:
3672                         return "csr0";
3673                 case GDB_REGNO_TSELECT:
3674                         return "tselect";
3675                 case GDB_REGNO_TDATA1:
3676                         return "tdata1";
3677                 case GDB_REGNO_TDATA2:
3678                         return "tdata2";
3679                 case GDB_REGNO_MISA:
3680                         return "misa";
3681                 case GDB_REGNO_DPC:
3682                         return "dpc";
3683                 case GDB_REGNO_DCSR:
3684                         return "dcsr";
3685                 case GDB_REGNO_DSCRATCH0:
3686                         return "dscratch0";
3687                 case GDB_REGNO_MSTATUS:
3688                         return "mstatus";
3689                 case GDB_REGNO_MEPC:
3690                         return "mepc";
3691                 case GDB_REGNO_MCAUSE:
3692                         return "mcause";
3693                 case GDB_REGNO_PRIV:
3694                         return "priv";
3695                 case GDB_REGNO_SATP:
3696                         return "satp";
3697                 case GDB_REGNO_VTYPE:
3698                         return "vtype";
3699                 case GDB_REGNO_VL:
3700                         return "vl";
3701                 case GDB_REGNO_V0:
3702                         return "v0";
3703                 case GDB_REGNO_V1:
3704                         return "v1";
3705                 case GDB_REGNO_V2:
3706                         return "v2";
3707                 case GDB_REGNO_V3:
3708                         return "v3";
3709                 case GDB_REGNO_V4:
3710                         return "v4";
3711                 case GDB_REGNO_V5:
3712                         return "v5";
3713                 case GDB_REGNO_V6:
3714                         return "v6";
3715                 case GDB_REGNO_V7:
3716                         return "v7";
3717                 case GDB_REGNO_V8:
3718                         return "v8";
3719                 case GDB_REGNO_V9:
3720                         return "v9";
3721                 case GDB_REGNO_V10:
3722                         return "v10";
3723                 case GDB_REGNO_V11:
3724                         return "v11";
3725                 case GDB_REGNO_V12:
3726                         return "v12";
3727                 case GDB_REGNO_V13:
3728                         return "v13";
3729                 case GDB_REGNO_V14:
3730                         return "v14";
3731                 case GDB_REGNO_V15:
3732                         return "v15";
3733                 case GDB_REGNO_V16:
3734                         return "v16";
3735                 case GDB_REGNO_V17:
3736                         return "v17";
3737                 case GDB_REGNO_V18:
3738                         return "v18";
3739                 case GDB_REGNO_V19:
3740                         return "v19";
3741                 case GDB_REGNO_V20:
3742                         return "v20";
3743                 case GDB_REGNO_V21:
3744                         return "v21";
3745                 case GDB_REGNO_V22:
3746                         return "v22";
3747                 case GDB_REGNO_V23:
3748                         return "v23";
3749                 case GDB_REGNO_V24:
3750                         return "v24";
3751                 case GDB_REGNO_V25:
3752                         return "v25";
3753                 case GDB_REGNO_V26:
3754                         return "v26";
3755                 case GDB_REGNO_V27:
3756                         return "v27";
3757                 case GDB_REGNO_V28:
3758                         return "v28";
3759                 case GDB_REGNO_V29:
3760                         return "v29";
3761                 case GDB_REGNO_V30:
3762                         return "v30";
3763                 case GDB_REGNO_V31:
3764                         return "v31";
3765                 default:
3766                         if (regno <= GDB_REGNO_XPR31)
3767                                 sprintf(buf, "x%d", regno - GDB_REGNO_ZERO);
3768                         else if (regno >= GDB_REGNO_CSR0 && regno <= GDB_REGNO_CSR4095)
3769                                 sprintf(buf, "csr%d", regno - GDB_REGNO_CSR0);
3770                         else if (regno >= GDB_REGNO_FPR0 && regno <= GDB_REGNO_FPR31)
3771                                 sprintf(buf, "f%d", regno - GDB_REGNO_FPR0);
3772                         else
3773                                 sprintf(buf, "gdb_regno_%d", regno);
3774                         return buf;
3775         }
3776 }
3777
3778 static int register_get(struct reg *reg)
3779 {
3780         riscv_reg_info_t *reg_info = reg->arch_info;
3781         struct target *target = reg_info->target;
3782         RISCV_INFO(r);
3783
3784         if (reg->number >= GDB_REGNO_V0 && reg->number <= GDB_REGNO_V31) {
3785                 if (!r->get_register_buf) {
3786                         LOG_ERROR("Reading register %s not supported on this RISC-V target.",
3787                                         gdb_regno_name(reg->number));
3788                         return ERROR_FAIL;
3789                 }
3790
3791                 if (r->get_register_buf(target, reg->value, reg->number) != ERROR_OK)
3792                         return ERROR_FAIL;
3793         } else {
3794                 uint64_t value;
3795                 int result = riscv_get_register(target, &value, reg->number);
3796                 if (result != ERROR_OK)
3797                         return result;
3798                 buf_set_u64(reg->value, 0, reg->size, value);
3799         }
3800         reg->valid = gdb_regno_cacheable(reg->number, false);
3801         char *str = buf_to_hex_str(reg->value, reg->size);
3802         LOG_DEBUG("[%s] read 0x%s from %s (valid=%d)", target_name(target),
3803                         str, reg->name, reg->valid);
3804         free(str);
3805         return ERROR_OK;
3806 }
3807
3808 static int register_set(struct reg *reg, uint8_t *buf)
3809 {
3810         riscv_reg_info_t *reg_info = reg->arch_info;
3811         struct target *target = reg_info->target;
3812         RISCV_INFO(r);
3813
3814         char *str = buf_to_hex_str(buf, reg->size);
3815         LOG_DEBUG("[%s] write 0x%s to %s (valid=%d)", target_name(target),
3816                         str, reg->name, reg->valid);
3817         free(str);
3818
3819         /* Exit early for writing x0, which on the hardware would be ignored, and we
3820          * don't want to update our cache. */
3821         if (reg->number == GDB_REGNO_ZERO)
3822                 return ERROR_OK;
3823
3824         memcpy(reg->value, buf, DIV_ROUND_UP(reg->size, 8));
3825         reg->valid = gdb_regno_cacheable(reg->number, true);
3826
3827         if (reg->number == GDB_REGNO_TDATA1 ||
3828                         reg->number == GDB_REGNO_TDATA2) {
3829                 r->manual_hwbp_set = true;
3830                 /* When enumerating triggers, we clear any triggers with DMODE set,
3831                  * assuming they were left over from a previous debug session. So make
3832                  * sure that is done before a user might be setting their own triggers.
3833                  */
3834                 if (riscv_enumerate_triggers(target) != ERROR_OK)
3835                         return ERROR_FAIL;
3836         }
3837
3838         if (reg->number >= GDB_REGNO_V0 && reg->number <= GDB_REGNO_V31) {
3839                 if (!r->set_register_buf) {
3840                         LOG_ERROR("Writing register %s not supported on this RISC-V target.",
3841                                         gdb_regno_name(reg->number));
3842                         return ERROR_FAIL;
3843                 }
3844
3845                 if (r->set_register_buf(target, reg->number, reg->value) != ERROR_OK)
3846                         return ERROR_FAIL;
3847         } else {
3848                 uint64_t value = buf_get_u64(buf, 0, reg->size);
3849                 if (riscv_set_register(target, reg->number, value) != ERROR_OK)
3850                         return ERROR_FAIL;
3851         }
3852
3853         return ERROR_OK;
3854 }
3855
3856 static struct reg_arch_type riscv_reg_arch_type = {
3857         .get = register_get,
3858         .set = register_set
3859 };
3860
3861 struct csr_info {
3862         unsigned number;
3863         const char *name;
3864 };
3865
3866 static int cmp_csr_info(const void *p1, const void *p2)
3867 {
3868         return (int) (((struct csr_info *)p1)->number) - (int) (((struct csr_info *)p2)->number);
3869 }
3870
3871 int riscv_init_registers(struct target *target)
3872 {
3873         RISCV_INFO(info);
3874
3875         riscv_free_registers(target);
3876
3877         target->reg_cache = calloc(1, sizeof(*target->reg_cache));
3878         if (!target->reg_cache)
3879                 return ERROR_FAIL;
3880         target->reg_cache->name = "RISC-V Registers";
3881         target->reg_cache->num_regs = GDB_REGNO_COUNT;
3882
3883         if (!list_empty(&info->expose_custom)) {
3884                 range_list_t *entry;
3885                 list_for_each_entry(entry, &info->expose_custom, list)
3886                         target->reg_cache->num_regs += entry->high - entry->low + 1;
3887         }
3888
3889         LOG_DEBUG("create register cache for %d registers",
3890                         target->reg_cache->num_regs);
3891
3892         target->reg_cache->reg_list =
3893                 calloc(target->reg_cache->num_regs, sizeof(struct reg));
3894         if (!target->reg_cache->reg_list)
3895                 return ERROR_FAIL;
3896
3897         const unsigned int max_reg_name_len = 12;
3898         free(info->reg_names);
3899         info->reg_names =
3900                 calloc(target->reg_cache->num_regs, max_reg_name_len);
3901         if (!info->reg_names)
3902                 return ERROR_FAIL;
3903         char *reg_name = info->reg_names;
3904
3905         static struct reg_feature feature_cpu = {
3906                 .name = "org.gnu.gdb.riscv.cpu"
3907         };
3908         static struct reg_feature feature_fpu = {
3909                 .name = "org.gnu.gdb.riscv.fpu"
3910         };
3911         static struct reg_feature feature_csr = {
3912                 .name = "org.gnu.gdb.riscv.csr"
3913         };
3914         static struct reg_feature feature_vector = {
3915                 .name = "org.gnu.gdb.riscv.vector"
3916         };
3917         static struct reg_feature feature_virtual = {
3918                 .name = "org.gnu.gdb.riscv.virtual"
3919         };
3920         static struct reg_feature feature_custom = {
3921                 .name = "org.gnu.gdb.riscv.custom"
3922         };
3923
3924         /* These types are built into gdb. */
3925         static struct reg_data_type type_ieee_single = { .type = REG_TYPE_IEEE_SINGLE, .id = "ieee_single" };
3926         static struct reg_data_type type_ieee_double = { .type = REG_TYPE_IEEE_DOUBLE, .id = "ieee_double" };
3927         static struct reg_data_type_union_field single_double_fields[] = {
3928                 {"float", &type_ieee_single, single_double_fields + 1},
3929                 {"double", &type_ieee_double, NULL},
3930         };
3931         static struct reg_data_type_union single_double_union = {
3932                 .fields = single_double_fields
3933         };
3934         static struct reg_data_type type_ieee_single_double = {
3935                 .type = REG_TYPE_ARCH_DEFINED,
3936                 .id = "FPU_FD",
3937                 .type_class = REG_TYPE_CLASS_UNION,
3938                 .reg_type_union = &single_double_union
3939         };
3940         static struct reg_data_type type_uint8 = { .type = REG_TYPE_UINT8, .id = "uint8" };
3941         static struct reg_data_type type_uint16 = { .type = REG_TYPE_UINT16, .id = "uint16" };
3942         static struct reg_data_type type_uint32 = { .type = REG_TYPE_UINT32, .id = "uint32" };
3943         static struct reg_data_type type_uint64 = { .type = REG_TYPE_UINT64, .id = "uint64" };
3944         static struct reg_data_type type_uint128 = { .type = REG_TYPE_UINT128, .id = "uint128" };
3945
3946         /* This is roughly the XML we want:
3947          * <vector id="bytes" type="uint8" count="16"/>
3948          * <vector id="shorts" type="uint16" count="8"/>
3949          * <vector id="words" type="uint32" count="4"/>
3950          * <vector id="longs" type="uint64" count="2"/>
3951          * <vector id="quads" type="uint128" count="1"/>
3952          * <union id="riscv_vector_type">
3953          *   <field name="b" type="bytes"/>
3954          *   <field name="s" type="shorts"/>
3955          *   <field name="w" type="words"/>
3956          *   <field name="l" type="longs"/>
3957          *   <field name="q" type="quads"/>
3958          * </union>
3959          */
3960
3961         info->vector_uint8.type = &type_uint8;
3962         info->vector_uint8.count = info->vlenb;
3963         info->type_uint8_vector.type = REG_TYPE_ARCH_DEFINED;
3964         info->type_uint8_vector.id = "bytes";
3965         info->type_uint8_vector.type_class = REG_TYPE_CLASS_VECTOR;
3966         info->type_uint8_vector.reg_type_vector = &info->vector_uint8;
3967
3968         info->vector_uint16.type = &type_uint16;
3969         info->vector_uint16.count = info->vlenb / 2;
3970         info->type_uint16_vector.type = REG_TYPE_ARCH_DEFINED;
3971         info->type_uint16_vector.id = "shorts";
3972         info->type_uint16_vector.type_class = REG_TYPE_CLASS_VECTOR;
3973         info->type_uint16_vector.reg_type_vector = &info->vector_uint16;
3974
3975         info->vector_uint32.type = &type_uint32;
3976         info->vector_uint32.count = info->vlenb / 4;
3977         info->type_uint32_vector.type = REG_TYPE_ARCH_DEFINED;
3978         info->type_uint32_vector.id = "words";
3979         info->type_uint32_vector.type_class = REG_TYPE_CLASS_VECTOR;
3980         info->type_uint32_vector.reg_type_vector = &info->vector_uint32;
3981
3982         info->vector_uint64.type = &type_uint64;
3983         info->vector_uint64.count = info->vlenb / 8;
3984         info->type_uint64_vector.type = REG_TYPE_ARCH_DEFINED;
3985         info->type_uint64_vector.id = "longs";
3986         info->type_uint64_vector.type_class = REG_TYPE_CLASS_VECTOR;
3987         info->type_uint64_vector.reg_type_vector = &info->vector_uint64;
3988
3989         info->vector_uint128.type = &type_uint128;
3990         info->vector_uint128.count = info->vlenb / 16;
3991         info->type_uint128_vector.type = REG_TYPE_ARCH_DEFINED;
3992         info->type_uint128_vector.id = "quads";
3993         info->type_uint128_vector.type_class = REG_TYPE_CLASS_VECTOR;
3994         info->type_uint128_vector.reg_type_vector = &info->vector_uint128;
3995
3996         info->vector_fields[0].name = "b";
3997         info->vector_fields[0].type = &info->type_uint8_vector;
3998         if (info->vlenb >= 2) {
3999                 info->vector_fields[0].next = info->vector_fields + 1;
4000                 info->vector_fields[1].name = "s";
4001                 info->vector_fields[1].type = &info->type_uint16_vector;
4002         } else {
4003                 info->vector_fields[0].next = NULL;
4004         }
4005         if (info->vlenb >= 4) {
4006                 info->vector_fields[1].next = info->vector_fields + 2;
4007                 info->vector_fields[2].name = "w";
4008                 info->vector_fields[2].type = &info->type_uint32_vector;
4009         } else {
4010                 info->vector_fields[1].next = NULL;
4011         }
4012         if (info->vlenb >= 8) {
4013                 info->vector_fields[2].next = info->vector_fields + 3;
4014                 info->vector_fields[3].name = "l";
4015                 info->vector_fields[3].type = &info->type_uint64_vector;
4016         } else {
4017                 info->vector_fields[2].next = NULL;
4018         }
4019         if (info->vlenb >= 16) {
4020                 info->vector_fields[3].next = info->vector_fields + 4;
4021                 info->vector_fields[4].name = "q";
4022                 info->vector_fields[4].type = &info->type_uint128_vector;
4023         } else {
4024                 info->vector_fields[3].next = NULL;
4025         }
4026         info->vector_fields[4].next = NULL;
4027
4028         info->vector_union.fields = info->vector_fields;
4029
4030         info->type_vector.type = REG_TYPE_ARCH_DEFINED;
4031         info->type_vector.id = "riscv_vector";
4032         info->type_vector.type_class = REG_TYPE_CLASS_UNION;
4033         info->type_vector.reg_type_union = &info->vector_union;
4034
4035         struct csr_info csr_info[] = {
4036 #define DECLARE_CSR(name, number) { number, #name },
4037 #include "encoding.h"
4038 #undef DECLARE_CSR
4039         };
4040         /* encoding.h does not contain the registers in sorted order. */
4041         qsort(csr_info, ARRAY_SIZE(csr_info), sizeof(*csr_info), cmp_csr_info);
4042         unsigned csr_info_index = 0;
4043
4044         int custom_within_range = 0;
4045
4046         riscv_reg_info_t *shared_reg_info = calloc(1, sizeof(riscv_reg_info_t));
4047         if (!shared_reg_info)
4048                 return ERROR_FAIL;
4049         shared_reg_info->target = target;
4050
4051         /* When gdb requests register N, gdb_get_register_packet() assumes that this
4052          * is register at index N in reg_list. So if there are certain registers
4053          * that don't exist, we need to leave holes in the list (or renumber, but
4054          * it would be nice not to have yet another set of numbers to translate
4055          * between). */
4056         for (uint32_t number = 0; number < target->reg_cache->num_regs; number++) {
4057                 struct reg *r = &target->reg_cache->reg_list[number];
4058                 r->dirty = false;
4059                 r->valid = false;
4060                 r->exist = true;
4061                 r->type = &riscv_reg_arch_type;
4062                 r->arch_info = shared_reg_info;
4063                 r->number = number;
4064                 r->size = riscv_xlen(target);
4065                 /* r->size is set in riscv_invalidate_register_cache, maybe because the
4066                  * target is in theory allowed to change XLEN on us. But I expect a lot
4067                  * of other things to break in that case as well. */
4068                 if (number <= GDB_REGNO_XPR31) {
4069                         r->exist = number <= GDB_REGNO_XPR15 ||
4070                                 !riscv_supports_extension(target, 'E');
4071                         /* TODO: For now we fake that all GPRs exist because otherwise gdb
4072                          * doesn't work. */
4073                         r->exist = true;
4074                         r->caller_save = true;
4075                         switch (number) {
4076                                 case GDB_REGNO_ZERO:
4077                                         r->name = "zero";
4078                                         break;
4079                                 case GDB_REGNO_RA:
4080                                         r->name = "ra";
4081                                         break;
4082                                 case GDB_REGNO_SP:
4083                                         r->name = "sp";
4084                                         break;
4085                                 case GDB_REGNO_GP:
4086                                         r->name = "gp";
4087                                         break;
4088                                 case GDB_REGNO_TP:
4089                                         r->name = "tp";
4090                                         break;
4091                                 case GDB_REGNO_T0:
4092                                         r->name = "t0";
4093                                         break;
4094                                 case GDB_REGNO_T1:
4095                                         r->name = "t1";
4096                                         break;
4097                                 case GDB_REGNO_T2:
4098                                         r->name = "t2";
4099                                         break;
4100                                 case GDB_REGNO_FP:
4101                                         r->name = "fp";
4102                                         break;
4103                                 case GDB_REGNO_S1:
4104                                         r->name = "s1";
4105                                         break;
4106                                 case GDB_REGNO_A0:
4107                                         r->name = "a0";
4108                                         break;
4109                                 case GDB_REGNO_A1:
4110                                         r->name = "a1";
4111                                         break;
4112                                 case GDB_REGNO_A2:
4113                                         r->name = "a2";
4114                                         break;
4115                                 case GDB_REGNO_A3:
4116                                         r->name = "a3";
4117                                         break;
4118                                 case GDB_REGNO_A4:
4119                                         r->name = "a4";
4120                                         break;
4121                                 case GDB_REGNO_A5:
4122                                         r->name = "a5";
4123                                         break;
4124                                 case GDB_REGNO_A6:
4125                                         r->name = "a6";
4126                                         break;
4127                                 case GDB_REGNO_A7:
4128                                         r->name = "a7";
4129                                         break;
4130                                 case GDB_REGNO_S2:
4131                                         r->name = "s2";
4132                                         break;
4133                                 case GDB_REGNO_S3:
4134                                         r->name = "s3";
4135                                         break;
4136                                 case GDB_REGNO_S4:
4137                                         r->name = "s4";
4138                                         break;
4139                                 case GDB_REGNO_S5:
4140                                         r->name = "s5";
4141                                         break;
4142                                 case GDB_REGNO_S6:
4143                                         r->name = "s6";
4144                                         break;
4145                                 case GDB_REGNO_S7:
4146                                         r->name = "s7";
4147                                         break;
4148                                 case GDB_REGNO_S8:
4149                                         r->name = "s8";
4150                                         break;
4151                                 case GDB_REGNO_S9:
4152                                         r->name = "s9";
4153                                         break;
4154                                 case GDB_REGNO_S10:
4155                                         r->name = "s10";
4156                                         break;
4157                                 case GDB_REGNO_S11:
4158                                         r->name = "s11";
4159                                         break;
4160                                 case GDB_REGNO_T3:
4161                                         r->name = "t3";
4162                                         break;
4163                                 case GDB_REGNO_T4:
4164                                         r->name = "t4";
4165                                         break;
4166                                 case GDB_REGNO_T5:
4167                                         r->name = "t5";
4168                                         break;
4169                                 case GDB_REGNO_T6:
4170                                         r->name = "t6";
4171                                         break;
4172                         }
4173                         r->group = "general";
4174                         r->feature = &feature_cpu;
4175                 } else if (number == GDB_REGNO_PC) {
4176                         r->caller_save = true;
4177                         sprintf(reg_name, "pc");
4178                         r->group = "general";
4179                         r->feature = &feature_cpu;
4180                 } else if (number >= GDB_REGNO_FPR0 && number <= GDB_REGNO_FPR31) {
4181                         r->caller_save = true;
4182                         if (riscv_supports_extension(target, 'D')) {
4183                                 r->size = 64;
4184                                 if (riscv_supports_extension(target, 'F'))
4185                                         r->reg_data_type = &type_ieee_single_double;
4186                                 else
4187                                         r->reg_data_type = &type_ieee_double;
4188                         } else if (riscv_supports_extension(target, 'F')) {
4189                                 r->reg_data_type = &type_ieee_single;
4190                                 r->size = 32;
4191                         } else {
4192                                 r->exist = false;
4193                         }
4194                         switch (number) {
4195                                 case GDB_REGNO_FT0:
4196                                         r->name = "ft0";
4197                                         break;
4198                                 case GDB_REGNO_FT1:
4199                                         r->name = "ft1";
4200                                         break;
4201                                 case GDB_REGNO_FT2:
4202                                         r->name = "ft2";
4203                                         break;
4204                                 case GDB_REGNO_FT3:
4205                                         r->name = "ft3";
4206                                         break;
4207                                 case GDB_REGNO_FT4:
4208                                         r->name = "ft4";
4209                                         break;
4210                                 case GDB_REGNO_FT5:
4211                                         r->name = "ft5";
4212                                         break;
4213                                 case GDB_REGNO_FT6:
4214                                         r->name = "ft6";
4215                                         break;
4216                                 case GDB_REGNO_FT7:
4217                                         r->name = "ft7";
4218                                         break;
4219                                 case GDB_REGNO_FS0:
4220                                         r->name = "fs0";
4221                                         break;
4222                                 case GDB_REGNO_FS1:
4223                                         r->name = "fs1";
4224                                         break;
4225                                 case GDB_REGNO_FA0:
4226                                         r->name = "fa0";
4227                                         break;
4228                                 case GDB_REGNO_FA1:
4229                                         r->name = "fa1";
4230                                         break;
4231                                 case GDB_REGNO_FA2:
4232                                         r->name = "fa2";
4233                                         break;
4234                                 case GDB_REGNO_FA3:
4235                                         r->name = "fa3";
4236                                         break;
4237                                 case GDB_REGNO_FA4:
4238                                         r->name = "fa4";
4239                                         break;
4240                                 case GDB_REGNO_FA5:
4241                                         r->name = "fa5";
4242                                         break;
4243                                 case GDB_REGNO_FA6:
4244                                         r->name = "fa6";
4245                                         break;
4246                                 case GDB_REGNO_FA7:
4247                                         r->name = "fa7";
4248                                         break;
4249                                 case GDB_REGNO_FS2:
4250                                         r->name = "fs2";
4251                                         break;
4252                                 case GDB_REGNO_FS3:
4253                                         r->name = "fs3";
4254                                         break;
4255                                 case GDB_REGNO_FS4:
4256                                         r->name = "fs4";
4257                                         break;
4258                                 case GDB_REGNO_FS5:
4259                                         r->name = "fs5";
4260                                         break;
4261                                 case GDB_REGNO_FS6:
4262                                         r->name = "fs6";
4263                                         break;
4264                                 case GDB_REGNO_FS7:
4265                                         r->name = "fs7";
4266                                         break;
4267                                 case GDB_REGNO_FS8:
4268                                         r->name = "fs8";
4269                                         break;
4270                                 case GDB_REGNO_FS9:
4271                                         r->name = "fs9";
4272                                         break;
4273                                 case GDB_REGNO_FS10:
4274                                         r->name = "fs10";
4275                                         break;
4276                                 case GDB_REGNO_FS11:
4277                                         r->name = "fs11";
4278                                         break;
4279                                 case GDB_REGNO_FT8:
4280                                         r->name = "ft8";
4281                                         break;
4282                                 case GDB_REGNO_FT9:
4283                                         r->name = "ft9";
4284                                         break;
4285                                 case GDB_REGNO_FT10:
4286                                         r->name = "ft10";
4287                                         break;
4288                                 case GDB_REGNO_FT11:
4289                                         r->name = "ft11";
4290                                         break;
4291                         }
4292                         r->group = "float";
4293                         r->feature = &feature_fpu;
4294                 } else if (number >= GDB_REGNO_CSR0 && number <= GDB_REGNO_CSR4095) {
4295                         r->group = "csr";
4296                         r->feature = &feature_csr;
4297                         unsigned csr_number = number - GDB_REGNO_CSR0;
4298
4299                         while (csr_info[csr_info_index].number < csr_number &&
4300                                         csr_info_index < ARRAY_SIZE(csr_info) - 1) {
4301                                 csr_info_index++;
4302                         }
4303                         if (csr_info[csr_info_index].number == csr_number) {
4304                                 r->name = csr_info[csr_info_index].name;
4305                         } else {
4306                                 sprintf(reg_name, "csr%d", csr_number);
4307                                 /* Assume unnamed registers don't exist, unless we have some
4308                                  * configuration that tells us otherwise. That's important
4309                                  * because eg. Eclipse crashes if a target has too many
4310                                  * registers, and apparently has no way of only showing a
4311                                  * subset of registers in any case. */
4312                                 r->exist = false;
4313                         }
4314
4315                         switch (csr_number) {
4316                                 case CSR_FFLAGS:
4317                                 case CSR_FRM:
4318                                 case CSR_FCSR:
4319                                         r->exist = riscv_supports_extension(target, 'F');
4320                                         r->group = "float";
4321                                         r->feature = &feature_fpu;
4322                                         break;
4323                                 case CSR_SSTATUS:
4324                                 case CSR_STVEC:
4325                                 case CSR_SIP:
4326                                 case CSR_SIE:
4327                                 case CSR_SCOUNTEREN:
4328                                 case CSR_SSCRATCH:
4329                                 case CSR_SEPC:
4330                                 case CSR_SCAUSE:
4331                                 case CSR_STVAL:
4332                                 case CSR_SATP:
4333                                         r->exist = riscv_supports_extension(target, 'S');
4334                                         break;
4335                                 case CSR_MEDELEG:
4336                                 case CSR_MIDELEG:
4337                                         /* "In systems with only M-mode, or with both M-mode and
4338                                          * U-mode but without U-mode trap support, the medeleg and
4339                                          * mideleg registers should not exist." */
4340                                         r->exist = riscv_supports_extension(target, 'S') ||
4341                                                 riscv_supports_extension(target, 'N');
4342                                         break;
4343
4344                                 case CSR_PMPCFG1:
4345                                 case CSR_PMPCFG3:
4346                                 case CSR_CYCLEH:
4347                                 case CSR_TIMEH:
4348                                 case CSR_INSTRETH:
4349                                 case CSR_HPMCOUNTER3H:
4350                                 case CSR_HPMCOUNTER4H:
4351                                 case CSR_HPMCOUNTER5H:
4352                                 case CSR_HPMCOUNTER6H:
4353                                 case CSR_HPMCOUNTER7H:
4354                                 case CSR_HPMCOUNTER8H:
4355                                 case CSR_HPMCOUNTER9H:
4356                                 case CSR_HPMCOUNTER10H:
4357                                 case CSR_HPMCOUNTER11H:
4358                                 case CSR_HPMCOUNTER12H:
4359                                 case CSR_HPMCOUNTER13H:
4360                                 case CSR_HPMCOUNTER14H:
4361                                 case CSR_HPMCOUNTER15H:
4362                                 case CSR_HPMCOUNTER16H:
4363                                 case CSR_HPMCOUNTER17H:
4364                                 case CSR_HPMCOUNTER18H:
4365                                 case CSR_HPMCOUNTER19H:
4366                                 case CSR_HPMCOUNTER20H:
4367                                 case CSR_HPMCOUNTER21H:
4368                                 case CSR_HPMCOUNTER22H:
4369                                 case CSR_HPMCOUNTER23H:
4370                                 case CSR_HPMCOUNTER24H:
4371                                 case CSR_HPMCOUNTER25H:
4372                                 case CSR_HPMCOUNTER26H:
4373                                 case CSR_HPMCOUNTER27H:
4374                                 case CSR_HPMCOUNTER28H:
4375                                 case CSR_HPMCOUNTER29H:
4376                                 case CSR_HPMCOUNTER30H:
4377                                 case CSR_HPMCOUNTER31H:
4378                                 case CSR_MCYCLEH:
4379                                 case CSR_MINSTRETH:
4380                                 case CSR_MHPMCOUNTER3H:
4381                                 case CSR_MHPMCOUNTER4H:
4382                                 case CSR_MHPMCOUNTER5H:
4383                                 case CSR_MHPMCOUNTER6H:
4384                                 case CSR_MHPMCOUNTER7H:
4385                                 case CSR_MHPMCOUNTER8H:
4386                                 case CSR_MHPMCOUNTER9H:
4387                                 case CSR_MHPMCOUNTER10H:
4388                                 case CSR_MHPMCOUNTER11H:
4389                                 case CSR_MHPMCOUNTER12H:
4390                                 case CSR_MHPMCOUNTER13H:
4391                                 case CSR_MHPMCOUNTER14H:
4392                                 case CSR_MHPMCOUNTER15H:
4393                                 case CSR_MHPMCOUNTER16H:
4394                                 case CSR_MHPMCOUNTER17H:
4395                                 case CSR_MHPMCOUNTER18H:
4396                                 case CSR_MHPMCOUNTER19H:
4397                                 case CSR_MHPMCOUNTER20H:
4398                                 case CSR_MHPMCOUNTER21H:
4399                                 case CSR_MHPMCOUNTER22H:
4400                                 case CSR_MHPMCOUNTER23H:
4401                                 case CSR_MHPMCOUNTER24H:
4402                                 case CSR_MHPMCOUNTER25H:
4403                                 case CSR_MHPMCOUNTER26H:
4404                                 case CSR_MHPMCOUNTER27H:
4405                                 case CSR_MHPMCOUNTER28H:
4406                                 case CSR_MHPMCOUNTER29H:
4407                                 case CSR_MHPMCOUNTER30H:
4408                                 case CSR_MHPMCOUNTER31H:
4409                                         r->exist = riscv_xlen(target) == 32;
4410                                         break;
4411
4412                                 case CSR_VSTART:
4413                                 case CSR_VXSAT:
4414                                 case CSR_VXRM:
4415                                 case CSR_VL:
4416                                 case CSR_VTYPE:
4417                                 case CSR_VLENB:
4418                                         r->exist = riscv_supports_extension(target, 'V');
4419                                         break;
4420                         }
4421
4422                         if (!r->exist && !list_empty(&info->expose_csr)) {
4423                                 range_list_t *entry;
4424                                 list_for_each_entry(entry, &info->expose_csr, list)
4425                                         if ((entry->low <= csr_number) && (csr_number <= entry->high)) {
4426                                                 if (entry->name) {
4427                                                         *reg_name = 0;
4428                                                         r->name = entry->name;
4429                                                 }
4430
4431                                                 LOG_DEBUG("Exposing additional CSR %d (name=%s)",
4432                                                                 csr_number, entry->name ? entry->name : reg_name);
4433
4434                                                 r->exist = true;
4435                                                 break;
4436                                         }
4437                         }
4438
4439                 } else if (number == GDB_REGNO_PRIV) {
4440                         sprintf(reg_name, "priv");
4441                         r->group = "general";
4442                         r->feature = &feature_virtual;
4443                         r->size = 8;
4444
4445                 } else if (number >= GDB_REGNO_V0 && number <= GDB_REGNO_V31) {
4446                         r->caller_save = false;
4447                         r->exist = riscv_supports_extension(target, 'V') && info->vlenb;
4448                         r->size = info->vlenb * 8;
4449                         sprintf(reg_name, "v%d", number - GDB_REGNO_V0);
4450                         r->group = "vector";
4451                         r->feature = &feature_vector;
4452                         r->reg_data_type = &info->type_vector;
4453
4454                 } else if (number >= GDB_REGNO_COUNT) {
4455                         /* Custom registers. */
4456                         assert(!list_empty(&info->expose_custom));
4457
4458                         range_list_t *range = list_first_entry(&info->expose_custom, range_list_t, list);
4459
4460                         unsigned custom_number = range->low + custom_within_range;
4461
4462                         r->group = "custom";
4463                         r->feature = &feature_custom;
4464                         r->arch_info = calloc(1, sizeof(riscv_reg_info_t));
4465                         if (!r->arch_info)
4466                                 return ERROR_FAIL;
4467                         ((riscv_reg_info_t *) r->arch_info)->target = target;
4468                         ((riscv_reg_info_t *) r->arch_info)->custom_number = custom_number;
4469                         sprintf(reg_name, "custom%d", custom_number);
4470
4471                         if (range->name) {
4472                                 *reg_name = 0;
4473                                 r->name = range->name;
4474                         }
4475
4476                         LOG_DEBUG("Exposing additional custom register %d (name=%s)",
4477                                         number, range->name ? range->name : reg_name);
4478
4479                         custom_within_range++;
4480                         if (custom_within_range > range->high - range->low) {
4481                                 custom_within_range = 0;
4482                                 list_rotate_left(&info->expose_custom);
4483                         }
4484                 }
4485
4486                 if (reg_name[0]) {
4487                         r->name = reg_name;
4488                         reg_name += strlen(reg_name) + 1;
4489                         assert(reg_name < info->reg_names + target->reg_cache->num_regs *
4490                                         max_reg_name_len);
4491                 }
4492                 r->value = calloc(1, DIV_ROUND_UP(r->size, 8));
4493         }
4494
4495         return ERROR_OK;
4496 }
4497
4498
4499 void riscv_add_bscan_tunneled_scan(struct target *target, struct scan_field *field,
4500                                         riscv_bscan_tunneled_scan_context_t *ctxt)
4501 {
4502         jtag_add_ir_scan(target->tap, &select_user4, TAP_IDLE);
4503
4504         memset(ctxt->tunneled_dr, 0, sizeof(ctxt->tunneled_dr));
4505         if (bscan_tunnel_type == BSCAN_TUNNEL_DATA_REGISTER) {
4506                 ctxt->tunneled_dr[3].num_bits = 1;
4507                 ctxt->tunneled_dr[3].out_value = bscan_one;
4508                 ctxt->tunneled_dr[2].num_bits = 7;
4509                 ctxt->tunneled_dr_width = field->num_bits;
4510                 ctxt->tunneled_dr[2].out_value = &ctxt->tunneled_dr_width;
4511                 /* for BSCAN tunnel, there is a one-TCK skew between shift in and shift out, so
4512                    scanning num_bits + 1, and then will right shift the input field after executing the queues */
4513
4514                 ctxt->tunneled_dr[1].num_bits = field->num_bits + 1;
4515                 ctxt->tunneled_dr[1].out_value = field->out_value;
4516                 ctxt->tunneled_dr[1].in_value = field->in_value;
4517
4518                 ctxt->tunneled_dr[0].num_bits = 3;
4519                 ctxt->tunneled_dr[0].out_value = bscan_zero;
4520         } else {
4521                 /* BSCAN_TUNNEL_NESTED_TAP */
4522                 ctxt->tunneled_dr[0].num_bits = 1;
4523                 ctxt->tunneled_dr[0].out_value = bscan_one;
4524                 ctxt->tunneled_dr[1].num_bits = 7;
4525                 ctxt->tunneled_dr_width = field->num_bits;
4526                 ctxt->tunneled_dr[1].out_value = &ctxt->tunneled_dr_width;
4527                 /* for BSCAN tunnel, there is a one-TCK skew between shift in and shift out, so
4528                    scanning num_bits + 1, and then will right shift the input field after executing the queues */
4529                 ctxt->tunneled_dr[2].num_bits = field->num_bits + 1;
4530                 ctxt->tunneled_dr[2].out_value = field->out_value;
4531                 ctxt->tunneled_dr[2].in_value = field->in_value;
4532                 ctxt->tunneled_dr[3].num_bits = 3;
4533                 ctxt->tunneled_dr[3].out_value = bscan_zero;
4534         }
4535         jtag_add_dr_scan(target->tap, ARRAY_SIZE(ctxt->tunneled_dr), ctxt->tunneled_dr, TAP_IDLE);
4536 }