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