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