Lots of RISC-V improvements.
[fw/openocd] / src / target / riscv / riscv.c
1 #include <assert.h>
2 #include <stdlib.h>
3 #include <time.h>
4
5 #ifdef HAVE_CONFIG_H
6 #include "config.h"
7 #endif
8
9 #include "target/target.h"
10 #include "target/algorithm.h"
11 #include "target/target_type.h"
12 #include "log.h"
13 #include "jtag/jtag.h"
14 #include "target/register.h"
15 #include "target/breakpoints.h"
16 #include "helper/time_support.h"
17 #include "riscv.h"
18 #include "gdb_regs.h"
19 #include "rtos/rtos.h"
20
21 /**
22  * Since almost everything can be accomplish by scanning the dbus register, all
23  * functions here assume dbus is already selected. The exception are functions
24  * called directly by OpenOCD, which can't assume anything about what's
25  * currently in IR. They should set IR to dbus explicitly.
26  */
27
28 /**
29  * Code structure
30  *
31  * At the bottom of the stack are the OpenOCD JTAG functions:
32  *              jtag_add_[id]r_scan
33  *              jtag_execute_query
34  *              jtag_add_runtest
35  *
36  * There are a few functions to just instantly shift a register and get its
37  * value:
38  *              dtmcontrol_scan
39  *              idcode_scan
40  *              dbus_scan
41  *
42  * Because doing one scan and waiting for the result is slow, most functions
43  * batch up a bunch of dbus writes and then execute them all at once. They use
44  * the scans "class" for this:
45  *              scans_new
46  *              scans_delete
47  *              scans_execute
48  *              scans_add_...
49  * Usually you new(), call a bunch of add functions, then execute() and look
50  * at the results by calling scans_get...()
51  *
52  * Optimized functions will directly use the scans class above, but slightly
53  * lazier code will use the cache functions that in turn use the scans
54  * functions:
55  *              cache_get...
56  *              cache_set...
57  *              cache_write
58  * cache_set... update a local structure, which is then synced to the target
59  * with cache_write(). Only Debug RAM words that are actually changed are sent
60  * to the target. Afterwards use cache_get... to read results.
61  */
62
63 #define get_field(reg, mask) (((reg) & (mask)) / ((mask) & ~((mask) << 1)))
64 #define set_field(reg, mask, val) (((reg) & ~(mask)) | (((val) * ((mask) & ~((mask) << 1))) & (mask)))
65
66 #define DIM(x)          (sizeof(x)/sizeof(*x))
67
68 /* Constants for legacy SiFive hardware breakpoints. */
69 #define CSR_BPCONTROL_X                 (1<<0)
70 #define CSR_BPCONTROL_W                 (1<<1)
71 #define CSR_BPCONTROL_R                 (1<<2)
72 #define CSR_BPCONTROL_U                 (1<<3)
73 #define CSR_BPCONTROL_S                 (1<<4)
74 #define CSR_BPCONTROL_H                 (1<<5)
75 #define CSR_BPCONTROL_M                 (1<<6)
76 #define CSR_BPCONTROL_BPMATCH   (0xf<<7)
77 #define CSR_BPCONTROL_BPACTION  (0xff<<11)
78
79 #define DEBUG_ROM_START         0x800
80 #define DEBUG_ROM_RESUME        (DEBUG_ROM_START + 4)
81 #define DEBUG_ROM_EXCEPTION     (DEBUG_ROM_START + 8)
82 #define DEBUG_RAM_START         0x400
83
84 #define SETHALTNOT                              0x10c
85
86 /*** JTAG registers. ***/
87
88 #define DTMCONTROL                                      0x10
89 #define DTMCONTROL_DBUS_RESET           (1<<16)
90 #define DTMCONTROL_IDLE                         (7<<10)
91 #define DTMCONTROL_ADDRBITS                     (0xf<<4)
92 #define DTMCONTROL_VERSION                      (0xf)
93
94 #define DBUS                                            0x11
95 #define DBUS_OP_START                           0
96 #define DBUS_OP_SIZE                            2
97 typedef enum {
98         DBUS_OP_NOP = 0,
99         DBUS_OP_READ = 1,
100         DBUS_OP_WRITE = 2
101 } dbus_op_t;
102 typedef enum {
103         DBUS_STATUS_SUCCESS = 0,
104         DBUS_STATUS_FAILED = 2,
105         DBUS_STATUS_BUSY = 3
106 } dbus_status_t;
107 #define DBUS_DATA_START                         2
108 #define DBUS_DATA_SIZE                          34
109 #define DBUS_ADDRESS_START                      36
110
111 typedef enum {
112         RE_OK,
113         RE_FAIL,
114         RE_AGAIN
115 } riscv_error_t;
116
117 typedef enum slot {
118         SLOT0,
119         SLOT1,
120         SLOT_LAST,
121 } slot_t;
122
123 /*** Debug Bus registers. ***/
124
125 #define DMCONTROL                               0x10
126 #define DMCONTROL_INTERRUPT             (((uint64_t)1)<<33)
127 #define DMCONTROL_HALTNOT               (((uint64_t)1)<<32)
128 #define DMCONTROL_BUSERROR              (7<<19)
129 #define DMCONTROL_SERIAL                (3<<16)
130 #define DMCONTROL_AUTOINCREMENT (1<<15)
131 #define DMCONTROL_ACCESS                (7<<12)
132 #define DMCONTROL_HARTID                (0x3ff<<2)
133 #define DMCONTROL_NDRESET               (1<<1)
134 #define DMCONTROL_FULLRESET             1
135
136 #define DMINFO                                  0x11
137 #define DMINFO_ABUSSIZE                 (0x7fU<<25)
138 #define DMINFO_SERIALCOUNT              (0xf<<21)
139 #define DMINFO_ACCESS128                (1<<20)
140 #define DMINFO_ACCESS64                 (1<<19)
141 #define DMINFO_ACCESS32                 (1<<18)
142 #define DMINFO_ACCESS16                 (1<<17)
143 #define DMINFO_ACCESS8                  (1<<16)
144 #define DMINFO_DRAMSIZE                 (0x3f<<10)
145 #define DMINFO_AUTHENTICATED    (1<<5)
146 #define DMINFO_AUTHBUSY                 (1<<4)
147 #define DMINFO_AUTHTYPE                 (3<<2)
148 #define DMINFO_VERSION                  3
149
150 /*** Info about the core being debugged. ***/
151
152 #define DBUS_ADDRESS_UNKNOWN    0xffff
153
154 #define MAX_HWBPS                       16
155 #define DRAM_CACHE_SIZE         16
156
157 uint8_t ir_dtmcontrol[4] = {DTMCONTROL};
158 struct scan_field select_dtmcontrol = {
159         .in_value = NULL,
160         .out_value = ir_dtmcontrol
161 };
162 uint8_t ir_dbus[4] = {DBUS};
163 struct scan_field select_dbus = {
164         .in_value = NULL,
165         .out_value = ir_dbus
166 };
167 uint8_t ir_idcode[4] = {0x1};
168 struct scan_field select_idcode = {
169         .in_value = NULL,
170         .out_value = ir_idcode
171 };
172
173 struct trigger {
174         uint64_t address;
175         uint32_t length;
176         uint64_t mask;
177         uint64_t value;
178         bool read, write, execute;
179         int unique_id;
180 };
181
182 /* Wall-clock timeout for a command/access. Settable via RISC-V Target commands.*/
183 int riscv_command_timeout_sec = DEFAULT_COMMAND_TIMEOUT_SEC;
184
185 /* Wall-clock timeout after reset. Settable via RISC-V Target commands.*/
186 int riscv_reset_timeout_sec = DEFAULT_RESET_TIMEOUT_SEC;
187
188 bool riscv_prefer_sba;
189
190 typedef struct {
191         uint16_t low, high;
192 } range_t;
193
194 /* In addition to the ones in the standard spec, we'll also expose additional
195  * CSRs in this list.
196  * The list is either NULL, or a series of ranges (inclusive), terminated with
197  * 1,0. */
198 range_t *expose_csr;
199 /* Same, but for custom registers. */
200 range_t *expose_custom;
201
202 static uint32_t dtmcontrol_scan(struct target *target, uint32_t out)
203 {
204         struct scan_field field;
205         uint8_t in_value[4];
206         uint8_t out_value[4];
207
208         buf_set_u32(out_value, 0, 32, out);
209
210         jtag_add_ir_scan(target->tap, &select_dtmcontrol, TAP_IDLE);
211
212         field.num_bits = 32;
213         field.out_value = out_value;
214         field.in_value = in_value;
215         jtag_add_dr_scan(target->tap, 1, &field, TAP_IDLE);
216
217         /* Always return to dbus. */
218         jtag_add_ir_scan(target->tap, &select_dbus, TAP_IDLE);
219
220         int retval = jtag_execute_queue();
221         if (retval != ERROR_OK) {
222                 LOG_ERROR("failed jtag scan: %d", retval);
223                 return retval;
224         }
225
226         uint32_t in = buf_get_u32(field.in_value, 0, 32);
227         LOG_DEBUG("DTMCONTROL: 0x%x -> 0x%x", out, in);
228
229         return in;
230 }
231
232 static struct target_type *get_target_type(struct target *target)
233 {
234         riscv_info_t *info = (riscv_info_t *) target->arch_info;
235
236         if (!info) {
237                 LOG_ERROR("Target has not been initialized");
238                 return NULL;
239         }
240
241         switch (info->dtm_version) {
242                 case 0:
243                         return &riscv011_target;
244                 case 1:
245                         return &riscv013_target;
246                 default:
247                         LOG_ERROR("Unsupported DTM version: %d", info->dtm_version);
248                         return NULL;
249         }
250 }
251
252 static int riscv_init_target(struct command_context *cmd_ctx,
253                 struct target *target)
254 {
255         LOG_DEBUG("riscv_init_target()");
256         target->arch_info = calloc(1, sizeof(riscv_info_t));
257         if (!target->arch_info)
258                 return ERROR_FAIL;
259         riscv_info_t *info = (riscv_info_t *) target->arch_info;
260         riscv_info_init(target, info);
261         info->cmd_ctx = cmd_ctx;
262
263         select_dtmcontrol.num_bits = target->tap->ir_length;
264         select_dbus.num_bits = target->tap->ir_length;
265         select_idcode.num_bits = target->tap->ir_length;
266
267         riscv_semihosting_init(target);
268
269         target->debug_reason = DBG_REASON_DBGRQ;
270
271         return ERROR_OK;
272 }
273
274 static void riscv_deinit_target(struct target *target)
275 {
276         LOG_DEBUG("riscv_deinit_target()");
277         struct target_type *tt = get_target_type(target);
278         if (tt) {
279                 tt->deinit_target(target);
280                 riscv_info_t *info = (riscv_info_t *) target->arch_info;
281                 free(info->reg_names);
282                 free(info);
283         }
284         /* Free the shared structure use for most registers. */
285         if (target->reg_cache) {
286                 if (target->reg_cache->reg_list) {
287                         if (target->reg_cache->reg_list[0].arch_info)
288                                 free(target->reg_cache->reg_list[0].arch_info);
289                         /* Free the ones we allocated separately. */
290                         for (unsigned i = GDB_REGNO_COUNT; i < target->reg_cache->num_regs; i++)
291                                 free(target->reg_cache->reg_list[i].arch_info);
292                         free(target->reg_cache->reg_list);
293                 }
294                 free(target->reg_cache);
295         }
296         target->arch_info = NULL;
297 }
298
299 static int oldriscv_halt(struct target *target)
300 {
301         struct target_type *tt = get_target_type(target);
302         return tt->halt(target);
303 }
304
305 static void trigger_from_breakpoint(struct trigger *trigger,
306                 const struct breakpoint *breakpoint)
307 {
308         trigger->address = breakpoint->address;
309         trigger->length = breakpoint->length;
310         trigger->mask = ~0LL;
311         trigger->read = false;
312         trigger->write = false;
313         trigger->execute = true;
314         /* unique_id is unique across both breakpoints and watchpoints. */
315         trigger->unique_id = breakpoint->unique_id;
316 }
317
318 static int maybe_add_trigger_t1(struct target *target, unsigned hartid,
319                 struct trigger *trigger, uint64_t tdata1)
320 {
321         RISCV_INFO(r);
322
323         const uint32_t bpcontrol_x = 1<<0;
324         const uint32_t bpcontrol_w = 1<<1;
325         const uint32_t bpcontrol_r = 1<<2;
326         const uint32_t bpcontrol_u = 1<<3;
327         const uint32_t bpcontrol_s = 1<<4;
328         const uint32_t bpcontrol_h = 1<<5;
329         const uint32_t bpcontrol_m = 1<<6;
330         const uint32_t bpcontrol_bpmatch = 0xf << 7;
331         const uint32_t bpcontrol_bpaction = 0xff << 11;
332
333         if (tdata1 & (bpcontrol_r | bpcontrol_w | bpcontrol_x)) {
334                 /* Trigger is already in use, presumably by user code. */
335                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
336         }
337
338         tdata1 = set_field(tdata1, bpcontrol_r, trigger->read);
339         tdata1 = set_field(tdata1, bpcontrol_w, trigger->write);
340         tdata1 = set_field(tdata1, bpcontrol_x, trigger->execute);
341         tdata1 = set_field(tdata1, bpcontrol_u,
342                         !!(r->misa[hartid] & (1 << ('U' - 'A'))));
343         tdata1 = set_field(tdata1, bpcontrol_s,
344                         !!(r->misa[hartid] & (1 << ('S' - 'A'))));
345         tdata1 = set_field(tdata1, bpcontrol_h,
346                         !!(r->misa[hartid] & (1 << ('H' - 'A'))));
347         tdata1 |= bpcontrol_m;
348         tdata1 = set_field(tdata1, bpcontrol_bpmatch, 0); /* exact match */
349         tdata1 = set_field(tdata1, bpcontrol_bpaction, 0); /* cause bp exception */
350
351         riscv_set_register_on_hart(target, hartid, GDB_REGNO_TDATA1, tdata1);
352
353         riscv_reg_t tdata1_rb;
354         if (riscv_get_register_on_hart(target, &tdata1_rb, hartid,
355                                 GDB_REGNO_TDATA1) != ERROR_OK)
356                 return ERROR_FAIL;
357         LOG_DEBUG("tdata1=0x%" PRIx64, tdata1_rb);
358
359         if (tdata1 != tdata1_rb) {
360                 LOG_DEBUG("Trigger doesn't support what we need; After writing 0x%"
361                                 PRIx64 " to tdata1 it contains 0x%" PRIx64,
362                                 tdata1, tdata1_rb);
363                 riscv_set_register_on_hart(target, hartid, GDB_REGNO_TDATA1, 0);
364                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
365         }
366
367         riscv_set_register_on_hart(target, hartid, GDB_REGNO_TDATA2, trigger->address);
368
369         return ERROR_OK;
370 }
371
372 static int maybe_add_trigger_t2(struct target *target, unsigned hartid,
373                 struct trigger *trigger, uint64_t tdata1)
374 {
375         RISCV_INFO(r);
376
377         /* tselect is already set */
378         if (tdata1 & (MCONTROL_EXECUTE | MCONTROL_STORE | MCONTROL_LOAD)) {
379                 /* Trigger is already in use, presumably by user code. */
380                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
381         }
382
383         /* address/data match trigger */
384         tdata1 |= MCONTROL_DMODE(riscv_xlen(target));
385         tdata1 = set_field(tdata1, MCONTROL_ACTION,
386                         MCONTROL_ACTION_DEBUG_MODE);
387         tdata1 = set_field(tdata1, MCONTROL_MATCH, MCONTROL_MATCH_EQUAL);
388         tdata1 |= MCONTROL_M;
389         if (r->misa[hartid] & (1 << ('H' - 'A')))
390                 tdata1 |= MCONTROL_H;
391         if (r->misa[hartid] & (1 << ('S' - 'A')))
392                 tdata1 |= MCONTROL_S;
393         if (r->misa[hartid] & (1 << ('U' - 'A')))
394                 tdata1 |= MCONTROL_U;
395
396         if (trigger->execute)
397                 tdata1 |= MCONTROL_EXECUTE;
398         if (trigger->read)
399                 tdata1 |= MCONTROL_LOAD;
400         if (trigger->write)
401                 tdata1 |= MCONTROL_STORE;
402
403         riscv_set_register_on_hart(target, hartid, GDB_REGNO_TDATA1, tdata1);
404
405         uint64_t tdata1_rb;
406         int result = riscv_get_register_on_hart(target, &tdata1_rb, hartid, GDB_REGNO_TDATA1);
407         if (result != ERROR_OK)
408                 return result;
409         LOG_DEBUG("tdata1=0x%" PRIx64, tdata1_rb);
410
411         if (tdata1 != tdata1_rb) {
412                 LOG_DEBUG("Trigger doesn't support what we need; After writing 0x%"
413                                 PRIx64 " to tdata1 it contains 0x%" PRIx64,
414                                 tdata1, tdata1_rb);
415                 riscv_set_register_on_hart(target, hartid, GDB_REGNO_TDATA1, 0);
416                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
417         }
418
419         riscv_set_register_on_hart(target, hartid, GDB_REGNO_TDATA2, trigger->address);
420
421         return ERROR_OK;
422 }
423
424 static int add_trigger(struct target *target, struct trigger *trigger)
425 {
426         RISCV_INFO(r);
427
428         if (riscv_enumerate_triggers(target) != ERROR_OK)
429                 return ERROR_FAIL;
430
431         /* In RTOS mode, we need to set the same trigger in the same slot on every
432          * hart, to keep up the illusion that each hart is a thread running on the
433          * same core. */
434
435         /* Otherwise, we just set the trigger on the one hart this target deals
436          * with. */
437
438         riscv_reg_t tselect[RISCV_MAX_HARTS];
439
440         int first_hart = -1;
441         for (int hartid = 0; hartid < riscv_count_harts(target); ++hartid) {
442                 if (!riscv_hart_enabled(target, hartid))
443                         continue;
444                 if (first_hart < 0)
445                         first_hart = hartid;
446                 int result = riscv_get_register_on_hart(target, &tselect[hartid],
447                                 hartid, GDB_REGNO_TSELECT);
448                 if (result != ERROR_OK)
449                         return result;
450         }
451         assert(first_hart >= 0);
452
453         unsigned int i;
454         for (i = 0; i < r->trigger_count[first_hart]; i++) {
455                 if (r->trigger_unique_id[i] != -1)
456                         continue;
457
458                 riscv_set_register_on_hart(target, first_hart, GDB_REGNO_TSELECT, i);
459
460                 uint64_t tdata1;
461                 int result = riscv_get_register_on_hart(target, &tdata1, first_hart,
462                                 GDB_REGNO_TDATA1);
463                 if (result != ERROR_OK)
464                         return result;
465                 int type = get_field(tdata1, MCONTROL_TYPE(riscv_xlen(target)));
466
467                 result = ERROR_OK;
468                 for (int hartid = first_hart; hartid < riscv_count_harts(target); ++hartid) {
469                         if (!riscv_hart_enabled(target, hartid))
470                                 continue;
471                         if (hartid > first_hart)
472                                 riscv_set_register_on_hart(target, hartid, GDB_REGNO_TSELECT, i);
473                         switch (type) {
474                                 case 1:
475                                         result = maybe_add_trigger_t1(target, hartid, trigger, tdata1);
476                                         break;
477                                 case 2:
478                                         result = maybe_add_trigger_t2(target, hartid, trigger, tdata1);
479                                         break;
480                                 default:
481                                         LOG_DEBUG("trigger %d has unknown type %d", i, type);
482                                         continue;
483                         }
484
485                         if (result != ERROR_OK)
486                                 continue;
487                 }
488
489                 if (result != ERROR_OK)
490                         continue;
491
492                 LOG_DEBUG("[%d] Using trigger %d (type %d) for bp %d", target->coreid,
493                                 i, type, trigger->unique_id);
494                 r->trigger_unique_id[i] = trigger->unique_id;
495                 break;
496         }
497
498         for (int hartid = first_hart; hartid < riscv_count_harts(target); ++hartid) {
499                 if (!riscv_hart_enabled(target, hartid))
500                         continue;
501                 riscv_set_register_on_hart(target, hartid, GDB_REGNO_TSELECT,
502                                 tselect[hartid]);
503         }
504
505         if (i >= r->trigger_count[first_hart]) {
506                 LOG_ERROR("Couldn't find an available hardware trigger.");
507                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
508         }
509
510         return ERROR_OK;
511 }
512
513 int riscv_add_breakpoint(struct target *target, struct breakpoint *breakpoint)
514 {
515         LOG_DEBUG("[%d] @0x%" TARGET_PRIxADDR, target->coreid, breakpoint->address);
516         assert(breakpoint);
517         if (breakpoint->type == BKPT_SOFT) {
518                 /** @todo check RVC for size/alignment */
519                 if (!(breakpoint->length == 4 || breakpoint->length == 2)) {
520                         LOG_ERROR("Invalid breakpoint length %d", breakpoint->length);
521                         return ERROR_FAIL;
522                 }
523
524                 if (0 != (breakpoint->address % 2)) {
525                         LOG_ERROR("Invalid breakpoint alignment for address 0x%" TARGET_PRIxADDR, breakpoint->address);
526                         return ERROR_FAIL;
527                 }
528
529                 if (target_read_memory(target, breakpoint->address, 2, breakpoint->length / 2,
530                                         breakpoint->orig_instr) != ERROR_OK) {
531                         LOG_ERROR("Failed to read original instruction at 0x%" TARGET_PRIxADDR,
532                                         breakpoint->address);
533                         return ERROR_FAIL;
534                 }
535
536                 uint8_t buff[4];
537                 buf_set_u32(buff, 0, breakpoint->length * CHAR_BIT, breakpoint->length == 4 ? ebreak() : ebreak_c());
538                 int const retval = target_write_memory(target, breakpoint->address, 2, breakpoint->length / 2, buff);
539
540                 if (retval != ERROR_OK) {
541                         LOG_ERROR("Failed to write %d-byte breakpoint instruction at 0x%"
542                                         TARGET_PRIxADDR, breakpoint->length, breakpoint->address);
543                         return ERROR_FAIL;
544                 }
545
546         } else if (breakpoint->type == BKPT_HARD) {
547                 struct trigger trigger;
548                 trigger_from_breakpoint(&trigger, breakpoint);
549                 int const result = add_trigger(target, &trigger);
550                 if (result != ERROR_OK)
551                         return result;
552         } else {
553                 LOG_INFO("OpenOCD only supports hardware and software breakpoints.");
554                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
555         }
556
557         breakpoint->set = true;
558         return ERROR_OK;
559 }
560
561 static int remove_trigger(struct target *target, struct trigger *trigger)
562 {
563         RISCV_INFO(r);
564
565         if (riscv_enumerate_triggers(target) != ERROR_OK)
566                 return ERROR_FAIL;
567
568         int first_hart = -1;
569         for (int hartid = 0; hartid < riscv_count_harts(target); ++hartid) {
570                 if (!riscv_hart_enabled(target, hartid))
571                         continue;
572                 if (first_hart < 0) {
573                         first_hart = hartid;
574                         break;
575                 }
576         }
577         assert(first_hart >= 0);
578
579         unsigned int i;
580         for (i = 0; i < r->trigger_count[first_hart]; i++) {
581                 if (r->trigger_unique_id[i] == trigger->unique_id)
582                         break;
583         }
584         if (i >= r->trigger_count[first_hart]) {
585                 LOG_ERROR("Couldn't find the hardware resources used by hardware "
586                                 "trigger.");
587                 return ERROR_FAIL;
588         }
589         LOG_DEBUG("[%d] Stop using resource %d for bp %d", target->coreid, i,
590                         trigger->unique_id);
591         for (int hartid = first_hart; hartid < riscv_count_harts(target); ++hartid) {
592                 if (!riscv_hart_enabled(target, hartid))
593                         continue;
594                 riscv_reg_t tselect;
595                 int result = riscv_get_register_on_hart(target, &tselect, hartid, GDB_REGNO_TSELECT);
596                 if (result != ERROR_OK)
597                         return result;
598                 riscv_set_register_on_hart(target, hartid, GDB_REGNO_TSELECT, i);
599                 riscv_set_register_on_hart(target, hartid, GDB_REGNO_TDATA1, 0);
600                 riscv_set_register_on_hart(target, hartid, GDB_REGNO_TSELECT, tselect);
601         }
602         r->trigger_unique_id[i] = -1;
603
604         return ERROR_OK;
605 }
606
607 int riscv_remove_breakpoint(struct target *target,
608                 struct breakpoint *breakpoint)
609 {
610         if (breakpoint->type == BKPT_SOFT) {
611                 if (target_write_memory(target, breakpoint->address, 2, breakpoint->length / 2,
612                                         breakpoint->orig_instr) != ERROR_OK) {
613                         LOG_ERROR("Failed to restore instruction for %d-byte breakpoint at "
614                                         "0x%" TARGET_PRIxADDR, breakpoint->length, breakpoint->address);
615                         return ERROR_FAIL;
616                 }
617
618         } else if (breakpoint->type == BKPT_HARD) {
619                 struct trigger trigger;
620                 trigger_from_breakpoint(&trigger, breakpoint);
621                 int result = remove_trigger(target, &trigger);
622                 if (result != ERROR_OK)
623                         return result;
624
625         } else {
626                 LOG_INFO("OpenOCD only supports hardware and software breakpoints.");
627                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
628         }
629
630         breakpoint->set = false;
631
632         return ERROR_OK;
633 }
634
635 static void trigger_from_watchpoint(struct trigger *trigger,
636                 const struct watchpoint *watchpoint)
637 {
638         trigger->address = watchpoint->address;
639         trigger->length = watchpoint->length;
640         trigger->mask = watchpoint->mask;
641         trigger->value = watchpoint->value;
642         trigger->read = (watchpoint->rw == WPT_READ || watchpoint->rw == WPT_ACCESS);
643         trigger->write = (watchpoint->rw == WPT_WRITE || watchpoint->rw == WPT_ACCESS);
644         trigger->execute = false;
645         /* unique_id is unique across both breakpoints and watchpoints. */
646         trigger->unique_id = watchpoint->unique_id;
647 }
648
649 int riscv_add_watchpoint(struct target *target, struct watchpoint *watchpoint)
650 {
651         struct trigger trigger;
652         trigger_from_watchpoint(&trigger, watchpoint);
653
654         int result = add_trigger(target, &trigger);
655         if (result != ERROR_OK)
656                 return result;
657         watchpoint->set = true;
658
659         return ERROR_OK;
660 }
661
662 int riscv_remove_watchpoint(struct target *target,
663                 struct watchpoint *watchpoint)
664 {
665         LOG_DEBUG("[%d] @0x%" TARGET_PRIxADDR, target->coreid, watchpoint->address);
666
667         struct trigger trigger;
668         trigger_from_watchpoint(&trigger, watchpoint);
669
670         int result = remove_trigger(target, &trigger);
671         if (result != ERROR_OK)
672                 return result;
673         watchpoint->set = false;
674
675         return ERROR_OK;
676 }
677
678 /* Sets *hit_watchpoint to the first watchpoint identified as causing the
679  * current halt.
680  *
681  * The GDB server uses this information to tell GDB what data address has
682  * been hit, which enables GDB to print the hit variable along with its old
683  * and new value. */
684 int riscv_hit_watchpoint(struct target *target, struct watchpoint **hit_watchpoint)
685 {
686         struct watchpoint *wp = target->watchpoints;
687
688         LOG_DEBUG("Current hartid = %d", riscv_current_hartid(target));
689
690         /*TODO instead of disassembling the instruction that we think caused the
691          * trigger, check the hit bit of each watchpoint first. The hit bit is
692          * simpler and more reliable to check but as it is optional and relatively
693          * new, not all hardware will implement it  */
694         riscv_reg_t dpc;
695         riscv_get_register(target, &dpc, GDB_REGNO_DPC);
696         const uint8_t length = 4;
697         LOG_DEBUG("dpc is 0x%" PRIx64, dpc);
698
699         /* fetch the instruction at dpc */
700         uint8_t buffer[length];
701         if (target_read_buffer(target, dpc, length, buffer) != ERROR_OK) {
702                 LOG_ERROR("Failed to read instruction at dpc 0x%" PRIx64, dpc);
703                 return ERROR_FAIL;
704         }
705
706         uint32_t instruction = 0;
707
708         for (int i = 0; i < length; i++) {
709                 LOG_DEBUG("Next byte is %x", buffer[i]);
710                 instruction += (buffer[i] << 8 * i);
711         }
712         LOG_DEBUG("Full instruction is %x", instruction);
713
714         /* find out which memory address is accessed by the instruction at dpc */
715         /* opcode is first 7 bits of the instruction */
716         uint8_t opcode = instruction & 0x7F;
717         uint32_t rs1;
718         int16_t imm;
719         riscv_reg_t mem_addr;
720
721         if (opcode == MATCH_LB || opcode == MATCH_SB) {
722                 rs1 = (instruction & 0xf8000) >> 15;
723                 riscv_get_register(target, &mem_addr, rs1);
724
725                 if (opcode == MATCH_SB) {
726                         LOG_DEBUG("%x is store instruction", instruction);
727                         imm = ((instruction & 0xf80) >> 7) | ((instruction & 0xfe000000) >> 20);
728                 } else {
729                         LOG_DEBUG("%x is load instruction", instruction);
730                         imm = (instruction & 0xfff00000) >> 20;
731                 }
732                 /* sign extend 12-bit imm to 16-bits */
733                 if (imm & (1 << 11))
734                         imm |= 0xf000;
735                 mem_addr += imm;
736                 LOG_DEBUG("memory address=0x%" PRIx64, mem_addr);
737         } else {
738                 LOG_DEBUG("%x is not a RV32I load or store", instruction);
739                 return ERROR_FAIL;
740         }
741
742         while (wp) {
743                 /*TODO support length/mask */
744                 if (wp->address == mem_addr) {
745                         *hit_watchpoint = wp;
746                         LOG_DEBUG("Hit address=%" TARGET_PRIxADDR, wp->address);
747                         return ERROR_OK;
748                 }
749                 wp = wp->next;
750         }
751
752         /* No match found - either we hit a watchpoint caused by an instruction that
753          * this function does not yet disassemble, or we hit a breakpoint.
754          *
755          * OpenOCD will behave as if this function had never been implemented i.e.
756          * report the halt to GDB with no address information. */
757         return ERROR_FAIL;
758 }
759
760
761 static int oldriscv_step(struct target *target, int current, uint32_t address,
762                 int handle_breakpoints)
763 {
764         struct target_type *tt = get_target_type(target);
765         return tt->step(target, current, address, handle_breakpoints);
766 }
767
768 static int old_or_new_riscv_step(
769                 struct target *target,
770                 int current,
771                 target_addr_t address,
772                 int handle_breakpoints
773 ){
774         RISCV_INFO(r);
775         LOG_DEBUG("handle_breakpoints=%d", handle_breakpoints);
776         if (r->is_halted == NULL)
777                 return oldriscv_step(target, current, address, handle_breakpoints);
778         else
779                 return riscv_openocd_step(target, current, address, handle_breakpoints);
780 }
781
782
783 static int riscv_examine(struct target *target)
784 {
785         LOG_DEBUG("riscv_examine()");
786         if (target_was_examined(target)) {
787                 LOG_DEBUG("Target was already examined.");
788                 return ERROR_OK;
789         }
790
791         /* Don't need to select dbus, since the first thing we do is read dtmcontrol. */
792
793         riscv_info_t *info = (riscv_info_t *) target->arch_info;
794         uint32_t dtmcontrol = dtmcontrol_scan(target, 0);
795         LOG_DEBUG("dtmcontrol=0x%x", dtmcontrol);
796         info->dtm_version = get_field(dtmcontrol, DTMCONTROL_VERSION);
797         LOG_DEBUG("  version=0x%x", info->dtm_version);
798
799         struct target_type *tt = get_target_type(target);
800         if (tt == NULL)
801                 return ERROR_FAIL;
802
803         int result = tt->init_target(info->cmd_ctx, target);
804         if (result != ERROR_OK)
805                 return result;
806
807         return tt->examine(target);
808 }
809
810 static int oldriscv_poll(struct target *target)
811 {
812         struct target_type *tt = get_target_type(target);
813         return tt->poll(target);
814 }
815
816 static int old_or_new_riscv_poll(struct target *target)
817 {
818         RISCV_INFO(r);
819         if (r->is_halted == NULL)
820                 return oldriscv_poll(target);
821         else
822                 return riscv_openocd_poll(target);
823 }
824
825 static int old_or_new_riscv_halt(struct target *target)
826 {
827         RISCV_INFO(r);
828         if (r->is_halted == NULL)
829                 return oldriscv_halt(target);
830         else
831                 return riscv_openocd_halt(target);
832 }
833
834 static int riscv_assert_reset(struct target *target)
835 {
836         LOG_DEBUG("[%d]", target->coreid);
837         struct target_type *tt = get_target_type(target);
838         riscv_invalidate_register_cache(target);
839         return tt->assert_reset(target);
840 }
841
842 static int riscv_deassert_reset(struct target *target)
843 {
844         LOG_DEBUG("[%d]", target->coreid);
845         struct target_type *tt = get_target_type(target);
846         return tt->deassert_reset(target);
847 }
848
849
850 static int oldriscv_resume(struct target *target, int current, uint32_t address,
851                 int handle_breakpoints, int debug_execution)
852 {
853         struct target_type *tt = get_target_type(target);
854         return tt->resume(target, current, address, handle_breakpoints,
855                         debug_execution);
856 }
857
858 static int old_or_new_riscv_resume(
859                 struct target *target,
860                 int current,
861                 target_addr_t address,
862                 int handle_breakpoints,
863                 int debug_execution
864 ){
865         LOG_DEBUG("handle_breakpoints=%d", handle_breakpoints);
866         if (target->smp) {
867                 struct target_list *targets = target->head;
868                 int result = ERROR_OK;
869                 while (targets) {
870                         struct target *t = targets->target;
871                         riscv_info_t *r = riscv_info(t);
872                         if (r->is_halted == NULL) {
873                                 if (oldriscv_resume(t, current, address, handle_breakpoints,
874                                                         debug_execution) != ERROR_OK)
875                                         result = ERROR_FAIL;
876                         } else {
877                                 if (riscv_openocd_resume(t, current, address,
878                                                         handle_breakpoints, debug_execution) != ERROR_OK)
879                                         result = ERROR_FAIL;
880                         }
881                         targets = targets->next;
882                 }
883                 return result;
884         }
885
886         RISCV_INFO(r);
887         if (r->is_halted == NULL)
888                 return oldriscv_resume(target, current, address, handle_breakpoints, debug_execution);
889         else
890                 return riscv_openocd_resume(target, current, address, handle_breakpoints, debug_execution);
891 }
892
893 static int riscv_select_current_hart(struct target *target)
894 {
895         RISCV_INFO(r);
896         if (riscv_rtos_enabled(target)) {
897                 if (r->rtos_hartid == -1)
898                         r->rtos_hartid = target->rtos->current_threadid - 1;
899                 return riscv_set_current_hartid(target, r->rtos_hartid);
900         } else
901                 return riscv_set_current_hartid(target, target->coreid);
902 }
903
904 static int riscv_read_memory(struct target *target, target_addr_t address,
905                 uint32_t size, uint32_t count, uint8_t *buffer)
906 {
907         if (riscv_select_current_hart(target) != ERROR_OK)
908                 return ERROR_FAIL;
909         struct target_type *tt = get_target_type(target);
910         return tt->read_memory(target, address, size, count, buffer);
911 }
912
913 static int riscv_write_memory(struct target *target, target_addr_t address,
914                 uint32_t size, uint32_t count, const uint8_t *buffer)
915 {
916         if (riscv_select_current_hart(target) != ERROR_OK)
917                 return ERROR_FAIL;
918         struct target_type *tt = get_target_type(target);
919         return tt->write_memory(target, address, size, count, buffer);
920 }
921
922 static int riscv_get_gdb_reg_list_internal(struct target *target,
923                 struct reg **reg_list[], int *reg_list_size,
924                 enum target_register_class reg_class, bool read)
925 {
926         RISCV_INFO(r);
927         LOG_DEBUG("rtos_hartid=%d, current_hartid=%d, reg_class=%d, read=%d",
928                         r->rtos_hartid, r->current_hartid, reg_class, read);
929
930         if (!target->reg_cache) {
931                 LOG_ERROR("Target not initialized. Return ERROR_FAIL.");
932                 return ERROR_FAIL;
933         }
934
935         if (riscv_select_current_hart(target) != ERROR_OK)
936                 return ERROR_FAIL;
937
938         switch (reg_class) {
939                 case REG_CLASS_GENERAL:
940                         *reg_list_size = 33;
941                         break;
942                 case REG_CLASS_ALL:
943                         *reg_list_size = target->reg_cache->num_regs;
944                         break;
945                 default:
946                         LOG_ERROR("Unsupported reg_class: %d", reg_class);
947                         return ERROR_FAIL;
948         }
949
950         *reg_list = calloc(*reg_list_size, sizeof(struct reg *));
951         if (!*reg_list)
952                 return ERROR_FAIL;
953
954         for (int i = 0; i < *reg_list_size; i++) {
955                 assert(!target->reg_cache->reg_list[i].valid ||
956                                 target->reg_cache->reg_list[i].size > 0);
957                 (*reg_list)[i] = &target->reg_cache->reg_list[i];
958                 if (read && !target->reg_cache->reg_list[i].valid) {
959                         if (target->reg_cache->reg_list[i].type->get(
960                                                 &target->reg_cache->reg_list[i]) != ERROR_OK)
961                                 /* This function is called when first connecting to gdb,
962                                  * resulting in an attempt to read all kinds of registers which
963                                  * probably will fail. Ignore these failures, and when
964                                  * encountered stop reading to save time. */
965                                 read = false;
966                 }
967         }
968
969         return ERROR_OK;
970 }
971
972 static int riscv_get_gdb_reg_list(struct target *target,
973                 struct reg **reg_list[], int *reg_list_size,
974                 enum target_register_class reg_class)
975 {
976         return riscv_get_gdb_reg_list_internal(target, reg_list, reg_list_size,
977                         reg_class, true);
978 }
979
980 static int riscv_arch_state(struct target *target)
981 {
982         struct target_type *tt = get_target_type(target);
983         return tt->arch_state(target);
984 }
985
986 /* Algorithm must end with a software breakpoint instruction. */
987 static int riscv_run_algorithm(struct target *target, int num_mem_params,
988                 struct mem_param *mem_params, int num_reg_params,
989                 struct reg_param *reg_params, target_addr_t entry_point,
990                 target_addr_t exit_point, int timeout_ms, void *arch_info)
991 {
992         riscv_info_t *info = (riscv_info_t *) target->arch_info;
993
994         if (num_mem_params > 0) {
995                 LOG_ERROR("Memory parameters are not supported for RISC-V algorithms.");
996                 return ERROR_FAIL;
997         }
998
999         if (target->state != TARGET_HALTED) {
1000                 LOG_WARNING("target not halted");
1001                 return ERROR_TARGET_NOT_HALTED;
1002         }
1003
1004         /* Save registers */
1005         struct reg *reg_pc = register_get_by_name(target->reg_cache, "pc", 1);
1006         if (!reg_pc || reg_pc->type->get(reg_pc) != ERROR_OK)
1007                 return ERROR_FAIL;
1008         uint64_t saved_pc = buf_get_u64(reg_pc->value, 0, reg_pc->size);
1009
1010         uint64_t saved_regs[32];
1011         for (int i = 0; i < num_reg_params; i++) {
1012                 if (reg_params[i].direction == PARAM_IN)
1013                         continue;
1014
1015                 LOG_DEBUG("save %s", reg_params[i].reg_name);
1016                 struct reg *r = register_get_by_name(target->reg_cache, reg_params[i].reg_name, 0);
1017                 if (!r) {
1018                         LOG_ERROR("Couldn't find register named '%s'", reg_params[i].reg_name);
1019                         return ERROR_FAIL;
1020                 }
1021
1022                 if (r->size != reg_params[i].size) {
1023                         LOG_ERROR("Register %s is %d bits instead of %d bits.",
1024                                         reg_params[i].reg_name, r->size, reg_params[i].size);
1025                         return ERROR_FAIL;
1026                 }
1027
1028                 if (r->number > GDB_REGNO_XPR31) {
1029                         LOG_ERROR("Only GPRs can be use as argument registers.");
1030                         return ERROR_FAIL;
1031                 }
1032
1033                 if (r->type->get(r) != ERROR_OK)
1034                         return ERROR_FAIL;
1035                 saved_regs[r->number] = buf_get_u64(r->value, 0, r->size);
1036                 if (r->type->set(r, reg_params[i].value) != ERROR_OK)
1037                         return ERROR_FAIL;
1038         }
1039
1040
1041         /* Disable Interrupts before attempting to run the algorithm. */
1042         uint64_t current_mstatus;
1043         uint8_t mstatus_bytes[8];
1044
1045         LOG_DEBUG("Disabling Interrupts");
1046         struct reg *reg_mstatus = register_get_by_name(target->reg_cache,
1047                         "mstatus", 1);
1048         if (!reg_mstatus) {
1049                 LOG_ERROR("Couldn't find mstatus!");
1050                 return ERROR_FAIL;
1051         }
1052
1053         reg_mstatus->type->get(reg_mstatus);
1054         current_mstatus = buf_get_u64(reg_mstatus->value, 0, reg_mstatus->size);
1055         uint64_t ie_mask = MSTATUS_MIE | MSTATUS_HIE | MSTATUS_SIE | MSTATUS_UIE;
1056         buf_set_u64(mstatus_bytes, 0, info->xlen[0], set_field(current_mstatus,
1057                                 ie_mask, 0));
1058
1059         reg_mstatus->type->set(reg_mstatus, mstatus_bytes);
1060
1061         /* Run algorithm */
1062         LOG_DEBUG("resume at 0x%" TARGET_PRIxADDR, entry_point);
1063         if (oldriscv_resume(target, 0, entry_point, 0, 0) != ERROR_OK)
1064                 return ERROR_FAIL;
1065
1066         int64_t start = timeval_ms();
1067         while (target->state != TARGET_HALTED) {
1068                 LOG_DEBUG("poll()");
1069                 int64_t now = timeval_ms();
1070                 if (now - start > timeout_ms) {
1071                         LOG_ERROR("Algorithm timed out after %d ms.", timeout_ms);
1072                         LOG_ERROR("  now   = 0x%08x", (uint32_t) now);
1073                         LOG_ERROR("  start = 0x%08x", (uint32_t) start);
1074                         oldriscv_halt(target);
1075                         old_or_new_riscv_poll(target);
1076                         return ERROR_TARGET_TIMEOUT;
1077                 }
1078
1079                 int result = old_or_new_riscv_poll(target);
1080                 if (result != ERROR_OK)
1081                         return result;
1082         }
1083
1084         if (reg_pc->type->get(reg_pc) != ERROR_OK)
1085                 return ERROR_FAIL;
1086         uint64_t final_pc = buf_get_u64(reg_pc->value, 0, reg_pc->size);
1087         if (final_pc != exit_point) {
1088                 LOG_ERROR("PC ended up at 0x%" PRIx64 " instead of 0x%"
1089                                 TARGET_PRIxADDR, final_pc, exit_point);
1090                 return ERROR_FAIL;
1091         }
1092
1093         /* Restore Interrupts */
1094         LOG_DEBUG("Restoring Interrupts");
1095         buf_set_u64(mstatus_bytes, 0, info->xlen[0], current_mstatus);
1096         reg_mstatus->type->set(reg_mstatus, mstatus_bytes);
1097
1098         /* Restore registers */
1099         uint8_t buf[8];
1100         buf_set_u64(buf, 0, info->xlen[0], saved_pc);
1101         if (reg_pc->type->set(reg_pc, buf) != ERROR_OK)
1102                 return ERROR_FAIL;
1103
1104         for (int i = 0; i < num_reg_params; i++) {
1105                 LOG_DEBUG("restore %s", reg_params[i].reg_name);
1106                 struct reg *r = register_get_by_name(target->reg_cache, reg_params[i].reg_name, 0);
1107                 buf_set_u64(buf, 0, info->xlen[0], saved_regs[r->number]);
1108                 if (r->type->set(r, buf) != ERROR_OK)
1109                         return ERROR_FAIL;
1110         }
1111
1112         return ERROR_OK;
1113 }
1114
1115 /* Should run code on the target to perform CRC of
1116 memory. Not yet implemented.
1117 */
1118
1119 static int riscv_checksum_memory(struct target *target,
1120                 target_addr_t address, uint32_t count,
1121                 uint32_t *checksum)
1122 {
1123         *checksum = 0xFFFFFFFF;
1124         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1125 }
1126
1127 /*** OpenOCD Helper Functions ***/
1128
1129 enum riscv_poll_hart {
1130         RPH_NO_CHANGE,
1131         RPH_DISCOVERED_HALTED,
1132         RPH_DISCOVERED_RUNNING,
1133         RPH_ERROR
1134 };
1135 static enum riscv_poll_hart riscv_poll_hart(struct target *target, int hartid)
1136 {
1137         RISCV_INFO(r);
1138         if (riscv_set_current_hartid(target, hartid) != ERROR_OK)
1139                 return RPH_ERROR;
1140
1141         LOG_DEBUG("polling hart %d, target->state=%d", hartid, target->state);
1142
1143         /* If OpenOCD thinks we're running but this hart is halted then it's time
1144          * to raise an event. */
1145         bool halted = riscv_is_halted(target);
1146         if (target->state != TARGET_HALTED && halted) {
1147                 LOG_DEBUG("  triggered a halt");
1148                 r->on_halt(target);
1149                 return RPH_DISCOVERED_HALTED;
1150         } else if (target->state != TARGET_RUNNING && !halted) {
1151                 LOG_DEBUG("  triggered running");
1152                 target->state = TARGET_RUNNING;
1153                 return RPH_DISCOVERED_RUNNING;
1154         }
1155
1156         return RPH_NO_CHANGE;
1157 }
1158
1159 int set_debug_reason(struct target *target, int hartid)
1160 {
1161         switch (riscv_halt_reason(target, hartid)) {
1162                 case RISCV_HALT_BREAKPOINT:
1163                         target->debug_reason = DBG_REASON_BREAKPOINT;
1164                         break;
1165                 case RISCV_HALT_TRIGGER:
1166                         target->debug_reason = DBG_REASON_WATCHPOINT;
1167                         break;
1168                 case RISCV_HALT_INTERRUPT:
1169                         target->debug_reason = DBG_REASON_DBGRQ;
1170                         break;
1171                 case RISCV_HALT_SINGLESTEP:
1172                         target->debug_reason = DBG_REASON_SINGLESTEP;
1173                         break;
1174                 case RISCV_HALT_UNKNOWN:
1175                         target->debug_reason = DBG_REASON_UNDEFINED;
1176                         break;
1177                 case RISCV_HALT_ERROR:
1178                         return ERROR_FAIL;
1179         }
1180         return ERROR_OK;
1181 }
1182
1183 /*** OpenOCD Interface ***/
1184 int riscv_openocd_poll(struct target *target)
1185 {
1186         LOG_DEBUG("polling all harts");
1187         int halted_hart = -1;
1188         if (riscv_rtos_enabled(target)) {
1189                 /* Check every hart for an event. */
1190                 for (int i = 0; i < riscv_count_harts(target); ++i) {
1191                         enum riscv_poll_hart out = riscv_poll_hart(target, i);
1192                         switch (out) {
1193                         case RPH_NO_CHANGE:
1194                         case RPH_DISCOVERED_RUNNING:
1195                                 continue;
1196                         case RPH_DISCOVERED_HALTED:
1197                                 halted_hart = i;
1198                                 break;
1199                         case RPH_ERROR:
1200                                 return ERROR_FAIL;
1201                         }
1202                 }
1203                 if (halted_hart == -1) {
1204                         LOG_DEBUG("  no harts just halted, target->state=%d", target->state);
1205                         return ERROR_OK;
1206                 }
1207                 LOG_DEBUG("  hart %d halted", halted_hart);
1208
1209                 /* If we're here then at least one hart triggered.  That means
1210                  * we want to go and halt _every_ hart in the system, as that's
1211                  * the invariant we hold here.  Some harts might have already
1212                  * halted (as we're either in single-step mode or they also
1213                  * triggered a breakpoint), so don't attempt to halt those
1214                  * harts. */
1215                 for (int i = 0; i < riscv_count_harts(target); ++i)
1216                         riscv_halt_one_hart(target, i);
1217
1218         } else if (target->smp) {
1219                 bool halt_discovered = false;
1220                 bool newly_halted[128] = {0};
1221                 unsigned i = 0;
1222                 for (struct target_list *list = target->head; list != NULL;
1223                                 list = list->next, i++) {
1224                         struct target *t = list->target;
1225                         riscv_info_t *r = riscv_info(t);
1226                         assert(i < DIM(newly_halted));
1227                         enum riscv_poll_hart out = riscv_poll_hart(t, r->current_hartid);
1228                         switch (out) {
1229                                 case RPH_NO_CHANGE:
1230                                         break;
1231                                 case RPH_DISCOVERED_RUNNING:
1232                                         t->state = TARGET_RUNNING;
1233                                         break;
1234                                 case RPH_DISCOVERED_HALTED:
1235                                         halt_discovered = true;
1236                                         newly_halted[i] = true;
1237                                         t->state = TARGET_HALTED;
1238                                         if (set_debug_reason(t, r->current_hartid) != ERROR_OK)
1239                                                 return ERROR_FAIL;
1240                                         break;
1241                                 case RPH_ERROR:
1242                                         return ERROR_FAIL;
1243                         }
1244                 }
1245
1246                 if (halt_discovered) {
1247                         LOG_DEBUG("Halt other targets in this SMP group.");
1248                         i = 0;
1249                         for (struct target_list *list = target->head; list != NULL;
1250                                         list = list->next, i++) {
1251                                 struct target *t = list->target;
1252                                 riscv_info_t *r = riscv_info(t);
1253                                 if (t->state != TARGET_HALTED) {
1254                                         if (riscv_halt_one_hart(t, r->current_hartid) != ERROR_OK)
1255                                                 return ERROR_FAIL;
1256                                         t->state = TARGET_HALTED;
1257                                         if (set_debug_reason(t, r->current_hartid) != ERROR_OK)
1258                                                 return ERROR_FAIL;
1259                                         newly_halted[i] = true;
1260                                 }
1261                         }
1262
1263                         /* Now that we have all our ducks in a row, tell the higher layers
1264                          * what just happened. */
1265                         i = 0;
1266                         for (struct target_list *list = target->head; list != NULL;
1267                                         list = list->next, i++) {
1268                                 struct target *t = list->target;
1269                                 if (newly_halted[i])
1270                                         target_call_event_callbacks(t, TARGET_EVENT_HALTED);
1271                         }
1272                 }
1273                 return ERROR_OK;
1274
1275         } else {
1276                 enum riscv_poll_hart out = riscv_poll_hart(target,
1277                                 riscv_current_hartid(target));
1278                 if (out == RPH_NO_CHANGE || out == RPH_DISCOVERED_RUNNING)
1279                         return ERROR_OK;
1280                 else if (out == RPH_ERROR)
1281                         return ERROR_FAIL;
1282
1283                 halted_hart = riscv_current_hartid(target);
1284                 LOG_DEBUG("  hart %d halted", halted_hart);
1285         }
1286
1287         target->state = TARGET_HALTED;
1288         if (set_debug_reason(target, halted_hart) != ERROR_OK)
1289                 return ERROR_FAIL;
1290
1291         if (riscv_rtos_enabled(target)) {
1292                 target->rtos->current_threadid = halted_hart + 1;
1293                 target->rtos->current_thread = halted_hart + 1;
1294                 riscv_set_rtos_hartid(target, halted_hart);
1295         }
1296
1297         target->state = TARGET_HALTED;
1298
1299         if (target->debug_reason == DBG_REASON_BREAKPOINT) {
1300                 int retval;
1301                 if (riscv_semihosting(target, &retval) != 0)
1302                         return retval;
1303         }
1304
1305         target_call_event_callbacks(target, TARGET_EVENT_HALTED);
1306         return ERROR_OK;
1307 }
1308
1309 int riscv_openocd_halt(struct target *target)
1310 {
1311         RISCV_INFO(r);
1312         int result;
1313
1314         LOG_DEBUG("[%d] halting all harts", target->coreid);
1315
1316         if (target->smp) {
1317                 LOG_DEBUG("Halt other targets in this SMP group.");
1318                 struct target_list *targets = target->head;
1319                 result = ERROR_OK;
1320                 while (targets) {
1321                         struct target *t = targets->target;
1322                         targets = targets->next;
1323                         if (t->state != TARGET_HALTED) {
1324                                 if (riscv_halt_all_harts(t) != ERROR_OK)
1325                                         result = ERROR_FAIL;
1326                         }
1327                 }
1328         } else {
1329                 result = riscv_halt_all_harts(target);
1330         }
1331
1332         if (riscv_rtos_enabled(target)) {
1333                 if (r->rtos_hartid != -1) {
1334                         LOG_DEBUG("halt requested on RTOS hartid %d", r->rtos_hartid);
1335                         target->rtos->current_threadid = r->rtos_hartid + 1;
1336                         target->rtos->current_thread = r->rtos_hartid + 1;
1337                 } else
1338                         LOG_DEBUG("halt requested, but no known RTOS hartid");
1339         }
1340
1341         target->state = TARGET_HALTED;
1342         target->debug_reason = DBG_REASON_DBGRQ;
1343         target_call_event_callbacks(target, TARGET_EVENT_HALTED);
1344         return result;
1345 }
1346
1347 int riscv_openocd_resume(
1348                 struct target *target,
1349                 int current,
1350                 target_addr_t address,
1351                 int handle_breakpoints,
1352                 int debug_execution)
1353 {
1354         LOG_DEBUG("debug_reason=%d", target->debug_reason);
1355
1356         if (!current)
1357                 riscv_set_register(target, GDB_REGNO_PC, address);
1358
1359         if (target->debug_reason == DBG_REASON_WATCHPOINT) {
1360                 /* To be able to run off a trigger, disable all the triggers, step, and
1361                  * then resume as usual. */
1362                 struct watchpoint *watchpoint = target->watchpoints;
1363                 bool trigger_temporarily_cleared[RISCV_MAX_HWBPS] = {0};
1364
1365                 int i = 0;
1366                 int result = ERROR_OK;
1367                 while (watchpoint && result == ERROR_OK) {
1368                         LOG_DEBUG("watchpoint %d: set=%d", i, watchpoint->set);
1369                         trigger_temporarily_cleared[i] = watchpoint->set;
1370                         if (watchpoint->set)
1371                                 result = riscv_remove_watchpoint(target, watchpoint);
1372                         watchpoint = watchpoint->next;
1373                         i++;
1374                 }
1375
1376                 if (result == ERROR_OK)
1377                         result = riscv_step_rtos_hart(target);
1378
1379                 watchpoint = target->watchpoints;
1380                 i = 0;
1381                 while (watchpoint) {
1382                         LOG_DEBUG("watchpoint %d: cleared=%d", i, trigger_temporarily_cleared[i]);
1383                         if (trigger_temporarily_cleared[i]) {
1384                                 if (result == ERROR_OK)
1385                                         result = riscv_add_watchpoint(target, watchpoint);
1386                                 else
1387                                         riscv_add_watchpoint(target, watchpoint);
1388                         }
1389                         watchpoint = watchpoint->next;
1390                         i++;
1391                 }
1392
1393                 if (result != ERROR_OK)
1394                         return result;
1395         }
1396
1397         int out = riscv_resume_all_harts(target);
1398         if (out != ERROR_OK) {
1399                 LOG_ERROR("unable to resume all harts");
1400                 return out;
1401         }
1402
1403         register_cache_invalidate(target->reg_cache);
1404         target->state = TARGET_RUNNING;
1405         target_call_event_callbacks(target, TARGET_EVENT_RESUMED);
1406         return out;
1407 }
1408
1409 int riscv_openocd_step(
1410                 struct target *target,
1411                 int current,
1412                 target_addr_t address,
1413                 int handle_breakpoints
1414 ) {
1415         LOG_DEBUG("stepping rtos hart");
1416
1417         if (!current)
1418                 riscv_set_register(target, GDB_REGNO_PC, address);
1419
1420         int out = riscv_step_rtos_hart(target);
1421         if (out != ERROR_OK) {
1422                 LOG_ERROR("unable to step rtos hart");
1423                 return out;
1424         }
1425
1426         register_cache_invalidate(target->reg_cache);
1427         target->state = TARGET_RUNNING;
1428         target_call_event_callbacks(target, TARGET_EVENT_RESUMED);
1429         target->state = TARGET_HALTED;
1430         target->debug_reason = DBG_REASON_SINGLESTEP;
1431         target_call_event_callbacks(target, TARGET_EVENT_HALTED);
1432         return out;
1433 }
1434
1435 /* Command Handlers */
1436 COMMAND_HANDLER(riscv_set_command_timeout_sec)
1437 {
1438         if (CMD_ARGC != 1) {
1439                 LOG_ERROR("Command takes exactly 1 parameter");
1440                 return ERROR_COMMAND_SYNTAX_ERROR;
1441         }
1442         int timeout = atoi(CMD_ARGV[0]);
1443         if (timeout <= 0) {
1444                 LOG_ERROR("%s is not a valid integer argument for command.", CMD_ARGV[0]);
1445                 return ERROR_FAIL;
1446         }
1447
1448         riscv_command_timeout_sec = timeout;
1449
1450         return ERROR_OK;
1451 }
1452
1453 COMMAND_HANDLER(riscv_set_reset_timeout_sec)
1454 {
1455         if (CMD_ARGC != 1) {
1456                 LOG_ERROR("Command takes exactly 1 parameter");
1457                 return ERROR_COMMAND_SYNTAX_ERROR;
1458         }
1459         int timeout = atoi(CMD_ARGV[0]);
1460         if (timeout <= 0) {
1461                 LOG_ERROR("%s is not a valid integer argument for command.", CMD_ARGV[0]);
1462                 return ERROR_FAIL;
1463         }
1464
1465         riscv_reset_timeout_sec = timeout;
1466         return ERROR_OK;
1467 }
1468
1469 COMMAND_HANDLER(riscv_test_compliance) {
1470
1471         struct target *target = get_current_target(CMD_CTX);
1472
1473         RISCV_INFO(r);
1474
1475         if (CMD_ARGC > 0) {
1476                 LOG_ERROR("Command does not take any parameters.");
1477                 return ERROR_COMMAND_SYNTAX_ERROR;
1478         }
1479
1480         if (r->test_compliance) {
1481                 return r->test_compliance(target);
1482         } else {
1483                 LOG_ERROR("This target does not support this command (may implement an older version of the spec).");
1484                 return ERROR_FAIL;
1485         }
1486 }
1487
1488 COMMAND_HANDLER(riscv_set_prefer_sba)
1489 {
1490         if (CMD_ARGC != 1) {
1491                 LOG_ERROR("Command takes exactly 1 parameter");
1492                 return ERROR_COMMAND_SYNTAX_ERROR;
1493         }
1494         COMMAND_PARSE_ON_OFF(CMD_ARGV[0], riscv_prefer_sba);
1495         return ERROR_OK;
1496 }
1497
1498 void parse_error(const char *string, char c, unsigned position)
1499 {
1500         char buf[position+2];
1501         for (unsigned i = 0; i < position; i++)
1502                 buf[i] = ' ';
1503         buf[position] = '^';
1504         buf[position + 1] = 0;
1505
1506         LOG_ERROR("Parse error at character %c in:", c);
1507         LOG_ERROR("%s", string);
1508         LOG_ERROR("%s", buf);
1509 }
1510
1511 int parse_ranges(range_t **ranges, const char **argv)
1512 {
1513         for (unsigned pass = 0; pass < 2; pass++) {
1514                 unsigned range = 0;
1515                 unsigned low = 0;
1516                 bool parse_low = true;
1517                 unsigned high = 0;
1518                 for (unsigned i = 0; i == 0 || argv[0][i-1]; i++) {
1519                         char c = argv[0][i];
1520                         if (isspace(c)) {
1521                                 /* Ignore whitespace. */
1522                                 continue;
1523                         }
1524
1525                         if (parse_low) {
1526                                 if (isdigit(c)) {
1527                                         low *= 10;
1528                                         low += c - '0';
1529                                 } else if (c == '-') {
1530                                         parse_low = false;
1531                                 } else if (c == ',' || c == 0) {
1532                                         if (pass == 1) {
1533                                                 (*ranges)[range].low = low;
1534                                                 (*ranges)[range].high = low;
1535                                         }
1536                                         low = 0;
1537                                         range++;
1538                                 } else {
1539                                         parse_error(argv[0], c, i);
1540                                         return ERROR_COMMAND_SYNTAX_ERROR;
1541                                 }
1542
1543                         } else {
1544                                 if (isdigit(c)) {
1545                                         high *= 10;
1546                                         high += c - '0';
1547                                 } else if (c == ',' || c == 0) {
1548                                         parse_low = true;
1549                                         if (pass == 1) {
1550                                                 (*ranges)[range].low = low;
1551                                                 (*ranges)[range].high = high;
1552                                         }
1553                                         low = 0;
1554                                         high = 0;
1555                                         range++;
1556                                 } else {
1557                                         parse_error(argv[0], c, i);
1558                                         return ERROR_COMMAND_SYNTAX_ERROR;
1559                                 }
1560                         }
1561                 }
1562
1563                 if (pass == 0) {
1564                         if (*ranges)
1565                                 free(*ranges);
1566                         *ranges = calloc(range + 2, sizeof(range_t));
1567                 } else {
1568                         (*ranges)[range].low = 1;
1569                         (*ranges)[range].high = 0;
1570                 }
1571         }
1572
1573         return ERROR_OK;
1574 }
1575
1576 COMMAND_HANDLER(riscv_set_expose_csrs)
1577 {
1578         if (CMD_ARGC != 1) {
1579                 LOG_ERROR("Command takes exactly 1 parameter");
1580                 return ERROR_COMMAND_SYNTAX_ERROR;
1581         }
1582
1583         return parse_ranges(&expose_csr, CMD_ARGV);
1584 }
1585
1586 COMMAND_HANDLER(riscv_set_expose_custom)
1587 {
1588         if (CMD_ARGC != 1) {
1589                 LOG_ERROR("Command takes exactly 1 parameter");
1590                 return ERROR_COMMAND_SYNTAX_ERROR;
1591         }
1592
1593         return parse_ranges(&expose_custom, CMD_ARGV);
1594 }
1595
1596 COMMAND_HANDLER(riscv_authdata_read)
1597 {
1598         if (CMD_ARGC != 0) {
1599                 LOG_ERROR("Command takes no parameters");
1600                 return ERROR_COMMAND_SYNTAX_ERROR;
1601         }
1602
1603         struct target *target = get_current_target(CMD_CTX);
1604         if (!target) {
1605                 LOG_ERROR("target is NULL!");
1606                 return ERROR_FAIL;
1607         }
1608
1609         RISCV_INFO(r);
1610         if (!r) {
1611                 LOG_ERROR("riscv_info is NULL!");
1612                 return ERROR_FAIL;
1613         }
1614
1615         if (r->authdata_read) {
1616                 uint32_t value;
1617                 if (r->authdata_read(target, &value) != ERROR_OK)
1618                         return ERROR_FAIL;
1619                 command_print(CMD_CTX, "0x%" PRIx32, value);
1620                 return ERROR_OK;
1621         } else {
1622                 LOG_ERROR("authdata_read is not implemented for this target.");
1623                 return ERROR_FAIL;
1624         }
1625 }
1626
1627 COMMAND_HANDLER(riscv_authdata_write)
1628 {
1629         if (CMD_ARGC != 1) {
1630                 LOG_ERROR("Command takes exactly 1 argument");
1631                 return ERROR_COMMAND_SYNTAX_ERROR;
1632         }
1633
1634         struct target *target = get_current_target(CMD_CTX);
1635         RISCV_INFO(r);
1636
1637         uint32_t value;
1638         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], value);
1639
1640         if (r->authdata_write) {
1641                 return r->authdata_write(target, value);
1642         } else {
1643                 LOG_ERROR("authdata_write is not implemented for this target.");
1644                 return ERROR_FAIL;
1645         }
1646 }
1647
1648 COMMAND_HANDLER(riscv_dmi_read)
1649 {
1650         if (CMD_ARGC != 1) {
1651                 LOG_ERROR("Command takes 1 parameter");
1652                 return ERROR_COMMAND_SYNTAX_ERROR;
1653         }
1654
1655         struct target *target = get_current_target(CMD_CTX);
1656         if (!target) {
1657                 LOG_ERROR("target is NULL!");
1658                 return ERROR_FAIL;
1659         }
1660
1661         RISCV_INFO(r);
1662         if (!r) {
1663                 LOG_ERROR("riscv_info is NULL!");
1664                 return ERROR_FAIL;
1665         }
1666
1667         if (r->dmi_read) {
1668                 uint32_t address, value;
1669                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
1670                 if (r->dmi_read(target, &value, address) != ERROR_OK)
1671                         return ERROR_FAIL;
1672                 command_print(CMD_CTX, "0x%" PRIx32, value);
1673                 return ERROR_OK;
1674         } else {
1675                 LOG_ERROR("dmi_read is not implemented for this target.");
1676                 return ERROR_FAIL;
1677         }
1678 }
1679
1680
1681 COMMAND_HANDLER(riscv_dmi_write)
1682 {
1683         if (CMD_ARGC != 2) {
1684                 LOG_ERROR("Command takes exactly 2 arguments");
1685                 return ERROR_COMMAND_SYNTAX_ERROR;
1686         }
1687
1688         struct target *target = get_current_target(CMD_CTX);
1689         RISCV_INFO(r);
1690
1691         uint32_t address, value;
1692         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
1693         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
1694
1695         if (r->dmi_write) {
1696                 return r->dmi_write(target, address, value);
1697         } else {
1698                 LOG_ERROR("dmi_write is not implemented for this target.");
1699                 return ERROR_FAIL;
1700         }
1701 }
1702
1703 COMMAND_HANDLER(riscv_test_sba_config_reg)
1704 {
1705         if (CMD_ARGC != 4) {
1706                 LOG_ERROR("Command takes exactly 4 arguments");
1707                 return ERROR_COMMAND_SYNTAX_ERROR;
1708         }
1709
1710         struct target *target = get_current_target(CMD_CTX);
1711         RISCV_INFO(r);
1712
1713         target_addr_t legal_address;
1714         uint32_t num_words;
1715         target_addr_t illegal_address;
1716         bool run_sbbusyerror_test;
1717
1718         COMMAND_PARSE_NUMBER(target_addr, CMD_ARGV[0], legal_address);
1719         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], num_words);
1720         COMMAND_PARSE_NUMBER(target_addr, CMD_ARGV[2], illegal_address);
1721         COMMAND_PARSE_ON_OFF(CMD_ARGV[3], run_sbbusyerror_test);
1722
1723         if (r->test_sba_config_reg) {
1724                 return r->test_sba_config_reg(target, legal_address, num_words,
1725                                 illegal_address, run_sbbusyerror_test);
1726         } else {
1727                 LOG_ERROR("test_sba_config_reg is not implemented for this target.");
1728                 return ERROR_FAIL;
1729         }
1730 }
1731
1732 COMMAND_HANDLER(riscv_reset_delays)
1733 {
1734         int wait = 0;
1735
1736         if (CMD_ARGC > 1) {
1737                 LOG_ERROR("Command takes at most one argument");
1738                 return ERROR_COMMAND_SYNTAX_ERROR;
1739         }
1740
1741         if (CMD_ARGC == 1)
1742                 COMMAND_PARSE_NUMBER(int, CMD_ARGV[0], wait);
1743
1744         struct target *target = get_current_target(CMD_CTX);
1745         RISCV_INFO(r);
1746         r->reset_delays_wait = wait;
1747         return ERROR_OK;
1748 }
1749
1750 COMMAND_HANDLER(riscv_set_ir)
1751 {
1752         if (CMD_ARGC != 2) {
1753                 LOG_ERROR("Command takes exactly 2 arguments");
1754                 return ERROR_COMMAND_SYNTAX_ERROR;
1755         }
1756
1757         uint32_t value;
1758         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
1759
1760         if (!strcmp(CMD_ARGV[0], "idcode")) {
1761                 buf_set_u32(ir_idcode, 0, 32, value);
1762                 return ERROR_OK;
1763         } else if (!strcmp(CMD_ARGV[0], "dtmcs")) {
1764                 buf_set_u32(ir_dtmcontrol, 0, 32, value);
1765                 return ERROR_OK;
1766         } else if (!strcmp(CMD_ARGV[0], "dmi")) {
1767                 buf_set_u32(ir_dbus, 0, 32, value);
1768                 return ERROR_OK;
1769         } else {
1770                 return ERROR_FAIL;
1771         }
1772 }
1773
1774 static const struct command_registration riscv_exec_command_handlers[] = {
1775         {
1776                 .name = "test_compliance",
1777                 .handler = riscv_test_compliance,
1778                 .mode = COMMAND_EXEC,
1779                 .usage = "riscv test_compliance",
1780                 .help = "Runs a basic compliance test suite against the RISC-V Debug Spec."
1781         },
1782         {
1783                 .name = "set_command_timeout_sec",
1784                 .handler = riscv_set_command_timeout_sec,
1785                 .mode = COMMAND_ANY,
1786                 .usage = "riscv set_command_timeout_sec [sec]",
1787                 .help = "Set the wall-clock timeout (in seconds) for individual commands"
1788         },
1789         {
1790                 .name = "set_reset_timeout_sec",
1791                 .handler = riscv_set_reset_timeout_sec,
1792                 .mode = COMMAND_ANY,
1793                 .usage = "riscv set_reset_timeout_sec [sec]",
1794                 .help = "Set the wall-clock timeout (in seconds) after reset is deasserted"
1795         },
1796         {
1797                 .name = "set_prefer_sba",
1798                 .handler = riscv_set_prefer_sba,
1799                 .mode = COMMAND_ANY,
1800                 .usage = "riscv set_prefer_sba on|off",
1801                 .help = "When on, prefer to use System Bus Access to access memory. "
1802                         "When off, prefer to use the Program Buffer to access memory."
1803         },
1804         {
1805                 .name = "expose_csrs",
1806                 .handler = riscv_set_expose_csrs,
1807                 .mode = COMMAND_ANY,
1808                 .usage = "riscv expose_csrs n0[-m0][,n1[-m1]]...",
1809                 .help = "Configure a list of inclusive ranges for CSRs to expose in "
1810                                 "addition to the standard ones. This must be executed before "
1811                                 "`init`."
1812         },
1813         {
1814                 .name = "expose_custom",
1815                 .handler = riscv_set_expose_custom,
1816                 .mode = COMMAND_ANY,
1817                 .usage = "riscv expose_custom n0[-m0][,n1[-m1]]...",
1818                 .help = "Configure a list of inclusive ranges for custom registers to "
1819                         "expose. custom0 is accessed as abstract register number 0xc000, "
1820                         "etc. This must be executed before `init`."
1821         },
1822         {
1823                 .name = "authdata_read",
1824                 .handler = riscv_authdata_read,
1825                 .mode = COMMAND_ANY,
1826                 .usage = "riscv authdata_read",
1827                 .help = "Return the 32-bit value read from authdata."
1828         },
1829         {
1830                 .name = "authdata_write",
1831                 .handler = riscv_authdata_write,
1832                 .mode = COMMAND_ANY,
1833                 .usage = "riscv authdata_write value",
1834                 .help = "Write the 32-bit value to authdata."
1835         },
1836         {
1837                 .name = "dmi_read",
1838                 .handler = riscv_dmi_read,
1839                 .mode = COMMAND_ANY,
1840                 .usage = "riscv dmi_read address",
1841                 .help = "Perform a 32-bit DMI read at address, returning the value."
1842         },
1843         {
1844                 .name = "dmi_write",
1845                 .handler = riscv_dmi_write,
1846                 .mode = COMMAND_ANY,
1847                 .usage = "riscv dmi_write address value",
1848                 .help = "Perform a 32-bit DMI write of value at address."
1849         },
1850         {
1851                 .name = "test_sba_config_reg",
1852                 .handler = riscv_test_sba_config_reg,
1853                 .mode = COMMAND_ANY,
1854                 .usage = "riscv test_sba_config_reg legal_address num_words"
1855                         "illegal_address run_sbbusyerror_test[on/off]",
1856                 .help = "Perform a series of tests on the SBCS register."
1857                         "Inputs are a legal, 128-byte aligned address and a number of words to"
1858                         "read/write starting at that address (i.e., address range [legal address,"
1859                         "legal_address+word_size*num_words) must be legally readable/writable)"
1860                         ", an illegal, 128-byte aligned address for error flag/handling cases,"
1861                         "and whether sbbusyerror test should be run."
1862         },
1863         {
1864                 .name = "reset_delays",
1865                 .handler = riscv_reset_delays,
1866                 .mode = COMMAND_ANY,
1867                 .usage = "reset_delays [wait]",
1868                 .help = "OpenOCD learns how many Run-Test/Idle cycles are required "
1869                         "between scans to avoid encountering the target being busy. This "
1870                         "command resets those learned values after `wait` scans. It's only "
1871                         "useful for testing OpenOCD itself."
1872         },
1873         {
1874                 .name = "set_ir",
1875                 .handler = riscv_set_ir,
1876                 .mode = COMMAND_ANY,
1877                 .usage = "riscv set_ir_idcode [idcode|dtmcs|dmi] value",
1878                 .help = "Set IR value for specified JTAG register."
1879         },
1880         COMMAND_REGISTRATION_DONE
1881 };
1882
1883 extern __COMMAND_HANDLER(handle_common_semihosting_command);
1884 extern __COMMAND_HANDLER(handle_common_semihosting_fileio_command);
1885 extern __COMMAND_HANDLER(handle_common_semihosting_resumable_exit_command);
1886 extern __COMMAND_HANDLER(handle_common_semihosting_cmdline);
1887
1888 /*
1889  * To be noted that RISC-V targets use the same semihosting commands as
1890  * ARM targets.
1891  *
1892  * The main reason is compatibility with existing tools. For example the
1893  * Eclipse OpenOCD/SEGGER J-Link/QEMU plug-ins have several widgets to
1894  * configure semihosting, which generate commands like `arm semihosting
1895  * enable`.
1896  * A secondary reason is the fact that the protocol used is exactly the
1897  * one specified by ARM. If RISC-V will ever define its own semihosting
1898  * protocol, then a command like `riscv semihosting enable` will make
1899  * sense, but for now all semihosting commands are prefixed with `arm`.
1900  */
1901 static const struct command_registration arm_exec_command_handlers[] = {
1902         {
1903                 "semihosting",
1904                 .handler = handle_common_semihosting_command,
1905                 .mode = COMMAND_EXEC,
1906                 .usage = "['enable'|'disable']",
1907                 .help = "activate support for semihosting operations",
1908         },
1909         {
1910                 "semihosting_cmdline",
1911                 .handler = handle_common_semihosting_cmdline,
1912                 .mode = COMMAND_EXEC,
1913                 .usage = "arguments",
1914                 .help = "command line arguments to be passed to program",
1915         },
1916         {
1917                 "semihosting_fileio",
1918                 .handler = handle_common_semihosting_fileio_command,
1919                 .mode = COMMAND_EXEC,
1920                 .usage = "['enable'|'disable']",
1921                 .help = "activate support for semihosting fileio operations",
1922         },
1923         {
1924                 "semihosting_resexit",
1925                 .handler = handle_common_semihosting_resumable_exit_command,
1926                 .mode = COMMAND_EXEC,
1927                 .usage = "['enable'|'disable']",
1928                 .help = "activate support for semihosting resumable exit",
1929         },
1930         COMMAND_REGISTRATION_DONE
1931 };
1932
1933 const struct command_registration riscv_command_handlers[] = {
1934         {
1935                 .name = "riscv",
1936                 .mode = COMMAND_ANY,
1937                 .help = "RISC-V Command Group",
1938                 .usage = "",
1939                 .chain = riscv_exec_command_handlers
1940         },
1941         {
1942                 .name = "arm",
1943                 .mode = COMMAND_ANY,
1944                 .help = "ARM Command Group",
1945                 .usage = "",
1946                 .chain = arm_exec_command_handlers
1947         },
1948         COMMAND_REGISTRATION_DONE
1949 };
1950
1951 unsigned riscv_address_bits(struct target *target)
1952 {
1953         return riscv_xlen(target);
1954 }
1955
1956 struct target_type riscv_target = {
1957         .name = "riscv",
1958
1959         .init_target = riscv_init_target,
1960         .deinit_target = riscv_deinit_target,
1961         .examine = riscv_examine,
1962
1963         /* poll current target status */
1964         .poll = old_or_new_riscv_poll,
1965
1966         .halt = old_or_new_riscv_halt,
1967         .resume = old_or_new_riscv_resume,
1968         .step = old_or_new_riscv_step,
1969
1970         .assert_reset = riscv_assert_reset,
1971         .deassert_reset = riscv_deassert_reset,
1972
1973         .read_memory = riscv_read_memory,
1974         .write_memory = riscv_write_memory,
1975
1976         .checksum_memory = riscv_checksum_memory,
1977
1978         .get_gdb_reg_list = riscv_get_gdb_reg_list,
1979
1980         .add_breakpoint = riscv_add_breakpoint,
1981         .remove_breakpoint = riscv_remove_breakpoint,
1982
1983         .add_watchpoint = riscv_add_watchpoint,
1984         .remove_watchpoint = riscv_remove_watchpoint,
1985         .hit_watchpoint = riscv_hit_watchpoint,
1986
1987         .arch_state = riscv_arch_state,
1988
1989         .run_algorithm = riscv_run_algorithm,
1990
1991         .commands = riscv_command_handlers,
1992
1993         .address_bits = riscv_address_bits
1994 };
1995
1996 /*** RISC-V Interface ***/
1997
1998 void riscv_info_init(struct target *target, riscv_info_t *r)
1999 {
2000         memset(r, 0, sizeof(*r));
2001         r->dtm_version = 1;
2002         r->registers_initialized = false;
2003         r->current_hartid = target->coreid;
2004
2005         memset(r->trigger_unique_id, 0xff, sizeof(r->trigger_unique_id));
2006
2007         for (size_t h = 0; h < RISCV_MAX_HARTS; ++h) {
2008                 r->xlen[h] = -1;
2009
2010                 for (size_t e = 0; e < RISCV_MAX_REGISTERS; ++e)
2011                         r->valid_saved_registers[h][e] = false;
2012         }
2013 }
2014
2015 int riscv_halt_all_harts(struct target *target)
2016 {
2017         for (int i = 0; i < riscv_count_harts(target); ++i) {
2018                 if (!riscv_hart_enabled(target, i))
2019                         continue;
2020
2021                 riscv_halt_one_hart(target, i);
2022         }
2023
2024         riscv_invalidate_register_cache(target);
2025
2026         return ERROR_OK;
2027 }
2028
2029 int riscv_halt_one_hart(struct target *target, int hartid)
2030 {
2031         RISCV_INFO(r);
2032         LOG_DEBUG("halting hart %d", hartid);
2033         if (riscv_set_current_hartid(target, hartid) != ERROR_OK)
2034                 return ERROR_FAIL;
2035         if (riscv_is_halted(target)) {
2036                 LOG_DEBUG("  hart %d requested halt, but was already halted", hartid);
2037                 return ERROR_OK;
2038         }
2039
2040         int result = r->halt_current_hart(target);
2041         register_cache_invalidate(target->reg_cache);
2042         return result;
2043 }
2044
2045 int riscv_resume_all_harts(struct target *target)
2046 {
2047         for (int i = 0; i < riscv_count_harts(target); ++i) {
2048                 if (!riscv_hart_enabled(target, i))
2049                         continue;
2050
2051                 riscv_resume_one_hart(target, i);
2052         }
2053
2054         riscv_invalidate_register_cache(target);
2055         return ERROR_OK;
2056 }
2057
2058 int riscv_resume_one_hart(struct target *target, int hartid)
2059 {
2060         RISCV_INFO(r);
2061         LOG_DEBUG("resuming hart %d", hartid);
2062         if (riscv_set_current_hartid(target, hartid) != ERROR_OK)
2063                 return ERROR_FAIL;
2064         if (!riscv_is_halted(target)) {
2065                 LOG_DEBUG("  hart %d requested resume, but was already resumed", hartid);
2066                 return ERROR_OK;
2067         }
2068
2069         r->on_resume(target);
2070         return r->resume_current_hart(target);
2071 }
2072
2073 int riscv_step_rtos_hart(struct target *target)
2074 {
2075         RISCV_INFO(r);
2076         int hartid = r->current_hartid;
2077         if (riscv_rtos_enabled(target)) {
2078                 hartid = r->rtos_hartid;
2079                 if (hartid == -1) {
2080                         LOG_DEBUG("GDB has asked me to step \"any\" thread, so I'm stepping hart 0.");
2081                         hartid = 0;
2082                 }
2083         }
2084         if (riscv_set_current_hartid(target, hartid) != ERROR_OK)
2085                 return ERROR_FAIL;
2086         LOG_DEBUG("stepping hart %d", hartid);
2087
2088         if (!riscv_is_halted(target)) {
2089                 LOG_ERROR("Hart isn't halted before single step!");
2090                 return ERROR_FAIL;
2091         }
2092         riscv_invalidate_register_cache(target);
2093         r->on_step(target);
2094         if (r->step_current_hart(target) != ERROR_OK)
2095                 return ERROR_FAIL;
2096         riscv_invalidate_register_cache(target);
2097         r->on_halt(target);
2098         if (!riscv_is_halted(target)) {
2099                 LOG_ERROR("Hart was not halted after single step!");
2100                 return ERROR_FAIL;
2101         }
2102         return ERROR_OK;
2103 }
2104
2105 bool riscv_supports_extension(struct target *target, int hartid, char letter)
2106 {
2107         RISCV_INFO(r);
2108         unsigned num;
2109         if (letter >= 'a' && letter <= 'z')
2110                 num = letter - 'a';
2111         else if (letter >= 'A' && letter <= 'Z')
2112                 num = letter - 'A';
2113         else
2114                 return false;
2115         return r->misa[hartid] & (1 << num);
2116 }
2117
2118 int riscv_xlen(const struct target *target)
2119 {
2120         return riscv_xlen_of_hart(target, riscv_current_hartid(target));
2121 }
2122
2123 int riscv_xlen_of_hart(const struct target *target, int hartid)
2124 {
2125         RISCV_INFO(r);
2126         assert(r->xlen[hartid] != -1);
2127         return r->xlen[hartid];
2128 }
2129
2130 extern struct rtos_type riscv_rtos;
2131 bool riscv_rtos_enabled(const struct target *target)
2132 {
2133         return false;
2134 }
2135
2136 int riscv_set_current_hartid(struct target *target, int hartid)
2137 {
2138         RISCV_INFO(r);
2139         if (!r->select_current_hart)
2140                 return ERROR_OK;
2141
2142         int previous_hartid = riscv_current_hartid(target);
2143         r->current_hartid = hartid;
2144         assert(riscv_hart_enabled(target, hartid));
2145         LOG_DEBUG("setting hartid to %d, was %d", hartid, previous_hartid);
2146         if (r->select_current_hart(target) != ERROR_OK)
2147                 return ERROR_FAIL;
2148
2149         /* This might get called during init, in which case we shouldn't be
2150          * setting up the register cache. */
2151         if (target_was_examined(target) && riscv_rtos_enabled(target))
2152                 riscv_invalidate_register_cache(target);
2153
2154         return ERROR_OK;
2155 }
2156
2157 void riscv_invalidate_register_cache(struct target *target)
2158 {
2159         RISCV_INFO(r);
2160
2161         LOG_DEBUG("[%d]", target->coreid);
2162         register_cache_invalidate(target->reg_cache);
2163         for (size_t i = 0; i < target->reg_cache->num_regs; ++i) {
2164                 struct reg *reg = &target->reg_cache->reg_list[i];
2165                 reg->valid = false;
2166         }
2167
2168         r->registers_initialized = true;
2169 }
2170
2171 int riscv_current_hartid(const struct target *target)
2172 {
2173         RISCV_INFO(r);
2174         return r->current_hartid;
2175 }
2176
2177 void riscv_set_all_rtos_harts(struct target *target)
2178 {
2179         RISCV_INFO(r);
2180         r->rtos_hartid = -1;
2181 }
2182
2183 void riscv_set_rtos_hartid(struct target *target, int hartid)
2184 {
2185         LOG_DEBUG("setting RTOS hartid %d", hartid);
2186         RISCV_INFO(r);
2187         r->rtos_hartid = hartid;
2188 }
2189
2190 int riscv_count_harts(struct target *target)
2191 {
2192         if (target == NULL)
2193                 return 1;
2194         RISCV_INFO(r);
2195         if (r == NULL)
2196                 return 1;
2197         return r->hart_count;
2198 }
2199
2200 bool riscv_has_register(struct target *target, int hartid, int regid)
2201 {
2202         return 1;
2203 }
2204
2205 /**
2206  * This function is called when the debug user wants to change the value of a
2207  * register. The new value may be cached, and may not be written until the hart
2208  * is resumed. */
2209 int riscv_set_register(struct target *target, enum gdb_regno r, riscv_reg_t v)
2210 {
2211         return riscv_set_register_on_hart(target, riscv_current_hartid(target), r, v);
2212 }
2213
2214 int riscv_set_register_on_hart(struct target *target, int hartid,
2215                 enum gdb_regno regid, uint64_t value)
2216 {
2217         RISCV_INFO(r);
2218         LOG_DEBUG("{%d} %s <- %" PRIx64, hartid, gdb_regno_name(regid), value);
2219         assert(r->set_register);
2220         return r->set_register(target, hartid, regid, value);
2221 }
2222
2223 int riscv_get_register(struct target *target, riscv_reg_t *value,
2224                 enum gdb_regno r)
2225 {
2226         return riscv_get_register_on_hart(target, value,
2227                         riscv_current_hartid(target), r);
2228 }
2229
2230 int riscv_get_register_on_hart(struct target *target, riscv_reg_t *value,
2231                 int hartid, enum gdb_regno regid)
2232 {
2233         RISCV_INFO(r);
2234
2235         struct reg *reg = &target->reg_cache->reg_list[regid];
2236
2237         if (reg && reg->valid && hartid == riscv_current_hartid(target)) {
2238                 *value = buf_get_u64(reg->value, 0, reg->size);
2239                 return ERROR_OK;
2240         }
2241
2242         int result = r->get_register(target, value, hartid, regid);
2243
2244         LOG_DEBUG("{%d} %s: %" PRIx64, hartid, gdb_regno_name(regid), *value);
2245         return result;
2246 }
2247
2248 bool riscv_is_halted(struct target *target)
2249 {
2250         RISCV_INFO(r);
2251         assert(r->is_halted);
2252         return r->is_halted(target);
2253 }
2254
2255 enum riscv_halt_reason riscv_halt_reason(struct target *target, int hartid)
2256 {
2257         RISCV_INFO(r);
2258         if (riscv_set_current_hartid(target, hartid) != ERROR_OK)
2259                 return RISCV_HALT_ERROR;
2260         if (!riscv_is_halted(target)) {
2261                 LOG_ERROR("Hart is not halted!");
2262                 return RISCV_HALT_UNKNOWN;
2263         }
2264         return r->halt_reason(target);
2265 }
2266
2267 size_t riscv_debug_buffer_size(struct target *target)
2268 {
2269         RISCV_INFO(r);
2270         return r->debug_buffer_size[riscv_current_hartid(target)];
2271 }
2272
2273 int riscv_write_debug_buffer(struct target *target, int index, riscv_insn_t insn)
2274 {
2275         RISCV_INFO(r);
2276         r->write_debug_buffer(target, index, insn);
2277         return ERROR_OK;
2278 }
2279
2280 riscv_insn_t riscv_read_debug_buffer(struct target *target, int index)
2281 {
2282         RISCV_INFO(r);
2283         return r->read_debug_buffer(target, index);
2284 }
2285
2286 int riscv_execute_debug_buffer(struct target *target)
2287 {
2288         RISCV_INFO(r);
2289         return r->execute_debug_buffer(target);
2290 }
2291
2292 void riscv_fill_dmi_write_u64(struct target *target, char *buf, int a, uint64_t d)
2293 {
2294         RISCV_INFO(r);
2295         r->fill_dmi_write_u64(target, buf, a, d);
2296 }
2297
2298 void riscv_fill_dmi_read_u64(struct target *target, char *buf, int a)
2299 {
2300         RISCV_INFO(r);
2301         r->fill_dmi_read_u64(target, buf, a);
2302 }
2303
2304 void riscv_fill_dmi_nop_u64(struct target *target, char *buf)
2305 {
2306         RISCV_INFO(r);
2307         r->fill_dmi_nop_u64(target, buf);
2308 }
2309
2310 int riscv_dmi_write_u64_bits(struct target *target)
2311 {
2312         RISCV_INFO(r);
2313         return r->dmi_write_u64_bits(target);
2314 }
2315
2316 bool riscv_hart_enabled(struct target *target, int hartid)
2317 {
2318         /* FIXME: Add a hart mask to the RTOS. */
2319         if (riscv_rtos_enabled(target))
2320                 return hartid < riscv_count_harts(target);
2321
2322         return hartid == target->coreid;
2323 }
2324
2325 /**
2326  * Count triggers, and initialize trigger_count for each hart.
2327  * trigger_count is initialized even if this function fails to discover
2328  * something.
2329  * Disable any hardware triggers that have dmode set. We can't have set them
2330  * ourselves. Maybe they're left over from some killed debug session.
2331  * */
2332 int riscv_enumerate_triggers(struct target *target)
2333 {
2334         RISCV_INFO(r);
2335
2336         if (r->triggers_enumerated)
2337                 return ERROR_OK;
2338
2339         r->triggers_enumerated = true;  /* At the very least we tried. */
2340
2341         for (int hartid = 0; hartid < riscv_count_harts(target); ++hartid) {
2342                 if (!riscv_hart_enabled(target, hartid))
2343                         continue;
2344
2345                 riscv_reg_t tselect;
2346                 int result = riscv_get_register_on_hart(target, &tselect, hartid,
2347                                 GDB_REGNO_TSELECT);
2348                 if (result != ERROR_OK)
2349                         return result;
2350
2351                 for (unsigned t = 0; t < RISCV_MAX_TRIGGERS; ++t) {
2352                         r->trigger_count[hartid] = t;
2353
2354                         riscv_set_register_on_hart(target, hartid, GDB_REGNO_TSELECT, t);
2355                         uint64_t tselect_rb;
2356                         result = riscv_get_register_on_hart(target, &tselect_rb, hartid,
2357                                         GDB_REGNO_TSELECT);
2358                         if (result != ERROR_OK)
2359                                 return result;
2360                         /* Mask off the top bit, which is used as tdrmode in old
2361                          * implementations. */
2362                         tselect_rb &= ~(1ULL << (riscv_xlen(target)-1));
2363                         if (tselect_rb != t)
2364                                 break;
2365                         uint64_t tdata1;
2366                         result = riscv_get_register_on_hart(target, &tdata1, hartid,
2367                                         GDB_REGNO_TDATA1);
2368                         if (result != ERROR_OK)
2369                                 return result;
2370
2371                         int type = get_field(tdata1, MCONTROL_TYPE(riscv_xlen(target)));
2372                         switch (type) {
2373                                 case 1:
2374                                         /* On these older cores we don't support software using
2375                                          * triggers. */
2376                                         riscv_set_register_on_hart(target, hartid, GDB_REGNO_TDATA1, 0);
2377                                         break;
2378                                 case 2:
2379                                         if (tdata1 & MCONTROL_DMODE(riscv_xlen(target)))
2380                                                 riscv_set_register_on_hart(target, hartid, GDB_REGNO_TDATA1, 0);
2381                                         break;
2382                         }
2383                 }
2384
2385                 riscv_set_register_on_hart(target, hartid, GDB_REGNO_TSELECT, tselect);
2386
2387                 LOG_INFO("[%d] Found %d triggers", hartid, r->trigger_count[hartid]);
2388         }
2389
2390         return ERROR_OK;
2391 }
2392
2393 const char *gdb_regno_name(enum gdb_regno regno)
2394 {
2395         static char buf[32];
2396
2397         switch (regno) {
2398                 case GDB_REGNO_ZERO:
2399                         return "zero";
2400                 case GDB_REGNO_S0:
2401                         return "s0";
2402                 case GDB_REGNO_S1:
2403                         return "s1";
2404                 case GDB_REGNO_PC:
2405                         return "pc";
2406                 case GDB_REGNO_FPR0:
2407                         return "fpr0";
2408                 case GDB_REGNO_FPR31:
2409                         return "fpr31";
2410                 case GDB_REGNO_CSR0:
2411                         return "csr0";
2412                 case GDB_REGNO_TSELECT:
2413                         return "tselect";
2414                 case GDB_REGNO_TDATA1:
2415                         return "tdata1";
2416                 case GDB_REGNO_TDATA2:
2417                         return "tdata2";
2418                 case GDB_REGNO_MISA:
2419                         return "misa";
2420                 case GDB_REGNO_DPC:
2421                         return "dpc";
2422                 case GDB_REGNO_DCSR:
2423                         return "dcsr";
2424                 case GDB_REGNO_DSCRATCH:
2425                         return "dscratch";
2426                 case GDB_REGNO_MSTATUS:
2427                         return "mstatus";
2428                 case GDB_REGNO_PRIV:
2429                         return "priv";
2430                 default:
2431                         if (regno <= GDB_REGNO_XPR31)
2432                                 sprintf(buf, "x%d", regno - GDB_REGNO_ZERO);
2433                         else if (regno >= GDB_REGNO_CSR0 && regno <= GDB_REGNO_CSR4095)
2434                                 sprintf(buf, "csr%d", regno - GDB_REGNO_CSR0);
2435                         else if (regno >= GDB_REGNO_FPR0 && regno <= GDB_REGNO_FPR31)
2436                                 sprintf(buf, "f%d", regno - GDB_REGNO_FPR0);
2437                         else
2438                                 sprintf(buf, "gdb_regno_%d", regno);
2439                         return buf;
2440         }
2441 }
2442
2443 static int register_get(struct reg *reg)
2444 {
2445         riscv_reg_info_t *reg_info = reg->arch_info;
2446         struct target *target = reg_info->target;
2447         uint64_t value;
2448         int result = riscv_get_register(target, &value, reg->number);
2449         if (result != ERROR_OK)
2450                 return result;
2451         buf_set_u64(reg->value, 0, reg->size, value);
2452         /* CSRs (and possibly other extension) registers may change value at any
2453          * time. */
2454         if (reg->number <= GDB_REGNO_XPR31 ||
2455                         (reg->number >= GDB_REGNO_FPR0 && reg->number <= GDB_REGNO_FPR31) ||
2456                         reg->number == GDB_REGNO_PC)
2457                 reg->valid = true;
2458         LOG_DEBUG("[%d]{%d} read 0x%" PRIx64 " from %s (valid=%d)",
2459                         target->coreid, riscv_current_hartid(target), value, reg->name,
2460                         reg->valid);
2461         return ERROR_OK;
2462 }
2463
2464 static int register_set(struct reg *reg, uint8_t *buf)
2465 {
2466         riscv_reg_info_t *reg_info = reg->arch_info;
2467         struct target *target = reg_info->target;
2468
2469         uint64_t value = buf_get_u64(buf, 0, reg->size);
2470
2471         LOG_DEBUG("[%d]{%d} write 0x%" PRIx64 " to %s (valid=%d)",
2472                         target->coreid, riscv_current_hartid(target), value, reg->name,
2473                         reg->valid);
2474         struct reg *r = &target->reg_cache->reg_list[reg->number];
2475         /* CSRs (and possibly other extension) registers may change value at any
2476          * time. */
2477         if (reg->number <= GDB_REGNO_XPR31 ||
2478                         (reg->number >= GDB_REGNO_FPR0 && reg->number <= GDB_REGNO_FPR31) ||
2479                         reg->number == GDB_REGNO_PC)
2480                 r->valid = true;
2481         memcpy(r->value, buf, (r->size + 7) / 8);
2482
2483         riscv_set_register(target, reg->number, value);
2484         return ERROR_OK;
2485 }
2486
2487 static struct reg_arch_type riscv_reg_arch_type = {
2488         .get = register_get,
2489         .set = register_set
2490 };
2491
2492 struct csr_info {
2493         unsigned number;
2494         const char *name;
2495 };
2496
2497 static int cmp_csr_info(const void *p1, const void *p2)
2498 {
2499         return (int) (((struct csr_info *)p1)->number) - (int) (((struct csr_info *)p2)->number);
2500 }
2501
2502 int riscv_init_registers(struct target *target)
2503 {
2504         RISCV_INFO(info);
2505
2506         if (target->reg_cache) {
2507                 if (target->reg_cache->reg_list)
2508                         free(target->reg_cache->reg_list);
2509                 free(target->reg_cache);
2510         }
2511
2512         target->reg_cache = calloc(1, sizeof(*target->reg_cache));
2513         target->reg_cache->name = "RISC-V Registers";
2514         target->reg_cache->num_regs = GDB_REGNO_COUNT;
2515
2516         if (expose_custom) {
2517                 for (unsigned i = 0; expose_custom[i].low <= expose_custom[i].high; i++) {
2518                         for (unsigned number = expose_custom[i].low;
2519                                         number <= expose_custom[i].high;
2520                                         number++)
2521                                 target->reg_cache->num_regs++;
2522                 }
2523         }
2524
2525         LOG_DEBUG("create register cache for %d registers",
2526                         target->reg_cache->num_regs);
2527
2528         target->reg_cache->reg_list =
2529                 calloc(target->reg_cache->num_regs, sizeof(struct reg));
2530
2531         const unsigned int max_reg_name_len = 12;
2532         if (info->reg_names)
2533                 free(info->reg_names);
2534         info->reg_names =
2535                 calloc(target->reg_cache->num_regs, max_reg_name_len);
2536         char *reg_name = info->reg_names;
2537
2538         static struct reg_feature feature_cpu = {
2539                 .name = "org.gnu.gdb.riscv.cpu"
2540         };
2541         static struct reg_feature feature_fpu = {
2542                 .name = "org.gnu.gdb.riscv.fpu"
2543         };
2544         static struct reg_feature feature_csr = {
2545                 .name = "org.gnu.gdb.riscv.csr"
2546         };
2547         static struct reg_feature feature_virtual = {
2548                 .name = "org.gnu.gdb.riscv.virtual"
2549         };
2550         static struct reg_feature feature_custom = {
2551                 .name = "org.gnu.gdb.riscv.custom"
2552         };
2553
2554         static struct reg_data_type type_ieee_single = {
2555                 .type = REG_TYPE_IEEE_SINGLE,
2556                 .id = "ieee_single"
2557         };
2558         static struct reg_data_type type_ieee_double = {
2559                 .type = REG_TYPE_IEEE_DOUBLE,
2560                 .id = "ieee_double"
2561         };
2562         struct csr_info csr_info[] = {
2563 #define DECLARE_CSR(name, number) { number, #name },
2564 #include "encoding.h"
2565 #undef DECLARE_CSR
2566         };
2567         /* encoding.h does not contain the registers in sorted order. */
2568         qsort(csr_info, DIM(csr_info), sizeof(*csr_info), cmp_csr_info);
2569         unsigned csr_info_index = 0;
2570
2571         unsigned custom_range_index = 0;
2572         int custom_within_range = 0;
2573
2574         riscv_reg_info_t *shared_reg_info = calloc(1, sizeof(riscv_reg_info_t));
2575         shared_reg_info->target = target;
2576
2577         /* When gdb requests register N, gdb_get_register_packet() assumes that this
2578          * is register at index N in reg_list. So if there are certain registers
2579          * that don't exist, we need to leave holes in the list (or renumber, but
2580          * it would be nice not to have yet another set of numbers to translate
2581          * between). */
2582         for (uint32_t number = 0; number < target->reg_cache->num_regs; number++) {
2583                 struct reg *r = &target->reg_cache->reg_list[number];
2584                 r->dirty = false;
2585                 r->valid = false;
2586                 r->exist = true;
2587                 r->type = &riscv_reg_arch_type;
2588                 r->arch_info = shared_reg_info;
2589                 r->number = number;
2590                 r->size = riscv_xlen(target);
2591                 /* r->size is set in riscv_invalidate_register_cache, maybe because the
2592                  * target is in theory allowed to change XLEN on us. But I expect a lot
2593                  * of other things to break in that case as well. */
2594                 if (number <= GDB_REGNO_XPR31) {
2595                         r->caller_save = true;
2596                         switch (number) {
2597                                 case GDB_REGNO_ZERO:
2598                                         r->name = "zero";
2599                                         break;
2600                                 case GDB_REGNO_RA:
2601                                         r->name = "ra";
2602                                         break;
2603                                 case GDB_REGNO_SP:
2604                                         r->name = "sp";
2605                                         break;
2606                                 case GDB_REGNO_GP:
2607                                         r->name = "gp";
2608                                         break;
2609                                 case GDB_REGNO_TP:
2610                                         r->name = "tp";
2611                                         break;
2612                                 case GDB_REGNO_T0:
2613                                         r->name = "t0";
2614                                         break;
2615                                 case GDB_REGNO_T1:
2616                                         r->name = "t1";
2617                                         break;
2618                                 case GDB_REGNO_T2:
2619                                         r->name = "t2";
2620                                         break;
2621                                 case GDB_REGNO_FP:
2622                                         r->name = "fp";
2623                                         break;
2624                                 case GDB_REGNO_S1:
2625                                         r->name = "s1";
2626                                         break;
2627                                 case GDB_REGNO_A0:
2628                                         r->name = "a0";
2629                                         break;
2630                                 case GDB_REGNO_A1:
2631                                         r->name = "a1";
2632                                         break;
2633                                 case GDB_REGNO_A2:
2634                                         r->name = "a2";
2635                                         break;
2636                                 case GDB_REGNO_A3:
2637                                         r->name = "a3";
2638                                         break;
2639                                 case GDB_REGNO_A4:
2640                                         r->name = "a4";
2641                                         break;
2642                                 case GDB_REGNO_A5:
2643                                         r->name = "a5";
2644                                         break;
2645                                 case GDB_REGNO_A6:
2646                                         r->name = "a6";
2647                                         break;
2648                                 case GDB_REGNO_A7:
2649                                         r->name = "a7";
2650                                         break;
2651                                 case GDB_REGNO_S2:
2652                                         r->name = "s2";
2653                                         break;
2654                                 case GDB_REGNO_S3:
2655                                         r->name = "s3";
2656                                         break;
2657                                 case GDB_REGNO_S4:
2658                                         r->name = "s4";
2659                                         break;
2660                                 case GDB_REGNO_S5:
2661                                         r->name = "s5";
2662                                         break;
2663                                 case GDB_REGNO_S6:
2664                                         r->name = "s6";
2665                                         break;
2666                                 case GDB_REGNO_S7:
2667                                         r->name = "s7";
2668                                         break;
2669                                 case GDB_REGNO_S8:
2670                                         r->name = "s8";
2671                                         break;
2672                                 case GDB_REGNO_S9:
2673                                         r->name = "s9";
2674                                         break;
2675                                 case GDB_REGNO_S10:
2676                                         r->name = "s10";
2677                                         break;
2678                                 case GDB_REGNO_S11:
2679                                         r->name = "s11";
2680                                         break;
2681                                 case GDB_REGNO_T3:
2682                                         r->name = "t3";
2683                                         break;
2684                                 case GDB_REGNO_T4:
2685                                         r->name = "t4";
2686                                         break;
2687                                 case GDB_REGNO_T5:
2688                                         r->name = "t5";
2689                                         break;
2690                                 case GDB_REGNO_T6:
2691                                         r->name = "t6";
2692                                         break;
2693                         }
2694                         r->group = "general";
2695                         r->feature = &feature_cpu;
2696                 } else if (number == GDB_REGNO_PC) {
2697                         r->caller_save = true;
2698                         sprintf(reg_name, "pc");
2699                         r->group = "general";
2700                         r->feature = &feature_cpu;
2701                 } else if (number >= GDB_REGNO_FPR0 && number <= GDB_REGNO_FPR31) {
2702                         r->caller_save = true;
2703                         if (riscv_supports_extension(target, riscv_current_hartid(target),
2704                                                 'D')) {
2705                                 r->reg_data_type = &type_ieee_double;
2706                                 r->size = 64;
2707                         } else if (riscv_supports_extension(target,
2708                                                 riscv_current_hartid(target), 'F')) {
2709                                 r->reg_data_type = &type_ieee_single;
2710                                 r->size = 32;
2711                         } else {
2712                                 r->exist = false;
2713                         }
2714                         switch (number) {
2715                                 case GDB_REGNO_FT0:
2716                                         r->name = "ft0";
2717                                         break;
2718                                 case GDB_REGNO_FT1:
2719                                         r->name = "ft1";
2720                                         break;
2721                                 case GDB_REGNO_FT2:
2722                                         r->name = "ft2";
2723                                         break;
2724                                 case GDB_REGNO_FT3:
2725                                         r->name = "ft3";
2726                                         break;
2727                                 case GDB_REGNO_FT4:
2728                                         r->name = "ft4";
2729                                         break;
2730                                 case GDB_REGNO_FT5:
2731                                         r->name = "ft5";
2732                                         break;
2733                                 case GDB_REGNO_FT6:
2734                                         r->name = "ft6";
2735                                         break;
2736                                 case GDB_REGNO_FT7:
2737                                         r->name = "ft7";
2738                                         break;
2739                                 case GDB_REGNO_FS0:
2740                                         r->name = "fs0";
2741                                         break;
2742                                 case GDB_REGNO_FS1:
2743                                         r->name = "fs1";
2744                                         break;
2745                                 case GDB_REGNO_FA0:
2746                                         r->name = "fa0";
2747                                         break;
2748                                 case GDB_REGNO_FA1:
2749                                         r->name = "fa1";
2750                                         break;
2751                                 case GDB_REGNO_FA2:
2752                                         r->name = "fa2";
2753                                         break;
2754                                 case GDB_REGNO_FA3:
2755                                         r->name = "fa3";
2756                                         break;
2757                                 case GDB_REGNO_FA4:
2758                                         r->name = "fa4";
2759                                         break;
2760                                 case GDB_REGNO_FA5:
2761                                         r->name = "fa5";
2762                                         break;
2763                                 case GDB_REGNO_FA6:
2764                                         r->name = "fa6";
2765                                         break;
2766                                 case GDB_REGNO_FA7:
2767                                         r->name = "fa7";
2768                                         break;
2769                                 case GDB_REGNO_FS2:
2770                                         r->name = "fs2";
2771                                         break;
2772                                 case GDB_REGNO_FS3:
2773                                         r->name = "fs3";
2774                                         break;
2775                                 case GDB_REGNO_FS4:
2776                                         r->name = "fs4";
2777                                         break;
2778                                 case GDB_REGNO_FS5:
2779                                         r->name = "fs5";
2780                                         break;
2781                                 case GDB_REGNO_FS6:
2782                                         r->name = "fs6";
2783                                         break;
2784                                 case GDB_REGNO_FS7:
2785                                         r->name = "fs7";
2786                                         break;
2787                                 case GDB_REGNO_FS8:
2788                                         r->name = "fs8";
2789                                         break;
2790                                 case GDB_REGNO_FS9:
2791                                         r->name = "fs9";
2792                                         break;
2793                                 case GDB_REGNO_FS10:
2794                                         r->name = "fs10";
2795                                         break;
2796                                 case GDB_REGNO_FS11:
2797                                         r->name = "fs11";
2798                                         break;
2799                                 case GDB_REGNO_FT8:
2800                                         r->name = "ft8";
2801                                         break;
2802                                 case GDB_REGNO_FT9:
2803                                         r->name = "ft9";
2804                                         break;
2805                                 case GDB_REGNO_FT10:
2806                                         r->name = "ft10";
2807                                         break;
2808                                 case GDB_REGNO_FT11:
2809                                         r->name = "ft11";
2810                                         break;
2811                         }
2812                         r->group = "float";
2813                         r->feature = &feature_fpu;
2814                 } else if (number >= GDB_REGNO_CSR0 && number <= GDB_REGNO_CSR4095) {
2815                         r->group = "csr";
2816                         r->feature = &feature_csr;
2817                         unsigned csr_number = number - GDB_REGNO_CSR0;
2818
2819                         while (csr_info[csr_info_index].number < csr_number &&
2820                                         csr_info_index < DIM(csr_info) - 1) {
2821                                 csr_info_index++;
2822                         }
2823                         if (csr_info[csr_info_index].number == csr_number) {
2824                                 r->name = csr_info[csr_info_index].name;
2825                         } else {
2826                                 sprintf(reg_name, "csr%d", csr_number);
2827                                 /* Assume unnamed registers don't exist, unless we have some
2828                                  * configuration that tells us otherwise. That's important
2829                                  * because eg. Eclipse crashes if a target has too many
2830                                  * registers, and apparently has no way of only showing a
2831                                  * subset of registers in any case. */
2832                                 r->exist = false;
2833                         }
2834
2835                         switch (csr_number) {
2836                                 case CSR_FFLAGS:
2837                                 case CSR_FRM:
2838                                 case CSR_FCSR:
2839                                         r->exist = riscv_supports_extension(target,
2840                                                         riscv_current_hartid(target), 'F');
2841                                         r->group = "float";
2842                                         r->feature = &feature_fpu;
2843                                         break;
2844                                 case CSR_SSTATUS:
2845                                 case CSR_STVEC:
2846                                 case CSR_SIP:
2847                                 case CSR_SIE:
2848                                 case CSR_SCOUNTEREN:
2849                                 case CSR_SSCRATCH:
2850                                 case CSR_SEPC:
2851                                 case CSR_SCAUSE:
2852                                 case CSR_STVAL:
2853                                 case CSR_SATP:
2854                                         r->exist = riscv_supports_extension(target,
2855                                                         riscv_current_hartid(target), 'S');
2856                                         break;
2857                                 case CSR_MEDELEG:
2858                                 case CSR_MIDELEG:
2859                                         /* "In systems with only M-mode, or with both M-mode and
2860                                          * U-mode but without U-mode trap support, the medeleg and
2861                                          * mideleg registers should not exist." */
2862                                         r->exist = riscv_supports_extension(target, riscv_current_hartid(target), 'S') ||
2863                                                 riscv_supports_extension(target, riscv_current_hartid(target), 'N');
2864                                         break;
2865
2866                                 case CSR_CYCLEH:
2867                                 case CSR_TIMEH:
2868                                 case CSR_INSTRETH:
2869                                 case CSR_HPMCOUNTER3H:
2870                                 case CSR_HPMCOUNTER4H:
2871                                 case CSR_HPMCOUNTER5H:
2872                                 case CSR_HPMCOUNTER6H:
2873                                 case CSR_HPMCOUNTER7H:
2874                                 case CSR_HPMCOUNTER8H:
2875                                 case CSR_HPMCOUNTER9H:
2876                                 case CSR_HPMCOUNTER10H:
2877                                 case CSR_HPMCOUNTER11H:
2878                                 case CSR_HPMCOUNTER12H:
2879                                 case CSR_HPMCOUNTER13H:
2880                                 case CSR_HPMCOUNTER14H:
2881                                 case CSR_HPMCOUNTER15H:
2882                                 case CSR_HPMCOUNTER16H:
2883                                 case CSR_HPMCOUNTER17H:
2884                                 case CSR_HPMCOUNTER18H:
2885                                 case CSR_HPMCOUNTER19H:
2886                                 case CSR_HPMCOUNTER20H:
2887                                 case CSR_HPMCOUNTER21H:
2888                                 case CSR_HPMCOUNTER22H:
2889                                 case CSR_HPMCOUNTER23H:
2890                                 case CSR_HPMCOUNTER24H:
2891                                 case CSR_HPMCOUNTER25H:
2892                                 case CSR_HPMCOUNTER26H:
2893                                 case CSR_HPMCOUNTER27H:
2894                                 case CSR_HPMCOUNTER28H:
2895                                 case CSR_HPMCOUNTER29H:
2896                                 case CSR_HPMCOUNTER30H:
2897                                 case CSR_HPMCOUNTER31H:
2898                                 case CSR_MCYCLEH:
2899                                 case CSR_MINSTRETH:
2900                                 case CSR_MHPMCOUNTER3H:
2901                                 case CSR_MHPMCOUNTER4H:
2902                                 case CSR_MHPMCOUNTER5H:
2903                                 case CSR_MHPMCOUNTER6H:
2904                                 case CSR_MHPMCOUNTER7H:
2905                                 case CSR_MHPMCOUNTER8H:
2906                                 case CSR_MHPMCOUNTER9H:
2907                                 case CSR_MHPMCOUNTER10H:
2908                                 case CSR_MHPMCOUNTER11H:
2909                                 case CSR_MHPMCOUNTER12H:
2910                                 case CSR_MHPMCOUNTER13H:
2911                                 case CSR_MHPMCOUNTER14H:
2912                                 case CSR_MHPMCOUNTER15H:
2913                                 case CSR_MHPMCOUNTER16H:
2914                                 case CSR_MHPMCOUNTER17H:
2915                                 case CSR_MHPMCOUNTER18H:
2916                                 case CSR_MHPMCOUNTER19H:
2917                                 case CSR_MHPMCOUNTER20H:
2918                                 case CSR_MHPMCOUNTER21H:
2919                                 case CSR_MHPMCOUNTER22H:
2920                                 case CSR_MHPMCOUNTER23H:
2921                                 case CSR_MHPMCOUNTER24H:
2922                                 case CSR_MHPMCOUNTER25H:
2923                                 case CSR_MHPMCOUNTER26H:
2924                                 case CSR_MHPMCOUNTER27H:
2925                                 case CSR_MHPMCOUNTER28H:
2926                                 case CSR_MHPMCOUNTER29H:
2927                                 case CSR_MHPMCOUNTER30H:
2928                                 case CSR_MHPMCOUNTER31H:
2929                                         r->exist = riscv_xlen(target) == 32;
2930                                         break;
2931                         }
2932
2933                         if (!r->exist && expose_csr) {
2934                                 for (unsigned i = 0; expose_csr[i].low <= expose_csr[i].high; i++) {
2935                                         if (csr_number >= expose_csr[i].low && csr_number <= expose_csr[i].high) {
2936                                                 LOG_INFO("Exposing additional CSR %d", csr_number);
2937                                                 r->exist = true;
2938                                                 break;
2939                                         }
2940                                 }
2941                         }
2942
2943                 } else if (number == GDB_REGNO_PRIV) {
2944                         sprintf(reg_name, "priv");
2945                         r->group = "general";
2946                         r->feature = &feature_virtual;
2947                         r->size = 8;
2948
2949                 } else {
2950                         /* Custom registers. */
2951                         assert(expose_custom);
2952
2953                         range_t *range = &expose_custom[custom_range_index];
2954                         assert(range->low <= range->high);
2955                         unsigned custom_number = range->low + custom_within_range;
2956
2957                         r->group = "custom";
2958                         r->feature = &feature_custom;
2959                         r->arch_info = calloc(1, sizeof(riscv_reg_info_t));
2960                         assert(r->arch_info);
2961                         ((riscv_reg_info_t *) r->arch_info)->target = target;
2962                         ((riscv_reg_info_t *) r->arch_info)->custom_number = custom_number;
2963                         sprintf(reg_name, "custom%d", custom_number);
2964
2965                         custom_within_range++;
2966                         if (custom_within_range > range->high - range->low) {
2967                                 custom_within_range = 0;
2968                                 custom_range_index++;
2969                         }
2970                 }
2971
2972                 if (reg_name[0])
2973                         r->name = reg_name;
2974                 reg_name += strlen(reg_name) + 1;
2975                 assert(reg_name < info->reg_names + target->reg_cache->num_regs *
2976                                 max_reg_name_len);
2977                 r->value = &info->reg_cache_values[number];
2978         }
2979
2980         return ERROR_OK;
2981 }