OpenOCD
riscv.c
Go to the documentation of this file.
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 
3 #include <assert.h>
4 #include <stdlib.h>
5 #include <time.h>
6 
7 #ifdef HAVE_CONFIG_H
8 #include "config.h"
9 #endif
10 
11 #include <helper/log.h>
12 #include <helper/time_support.h>
13 #include "target/target.h"
14 #include "target/algorithm.h"
15 #include "target/target_type.h"
16 #include <target/smp.h>
17 #include "jtag/jtag.h"
18 #include "target/register.h"
19 #include "target/breakpoints.h"
20 #include "helper/base64.h"
21 #include "helper/time_support.h"
22 #include "riscv.h"
23 #include "riscv_reg.h"
24 #include "program.h"
25 #include "gdb_regs.h"
26 #include "rtos/rtos.h"
27 #include "debug_defines.h"
28 #include <helper/bits.h>
29 #include "field_helpers.h"
30 
31 /*** JTAG registers. ***/
32 
33 #define DTMCONTROL 0x10
34 #define DTMCONTROL_VERSION (0xf)
35 
36 #define DBUS 0x11
37 
38 #define RISCV_TRIGGER_HIT_NOT_FOUND ((int64_t)-1)
39 
40 #define RISCV_HALT_GROUP_REPOLL_LIMIT 5
41 
42 static uint8_t ir_dtmcontrol[4] = {DTMCONTROL};
44  .in_value = NULL,
45  .out_value = ir_dtmcontrol
46 };
47 static uint8_t ir_dbus[4] = {DBUS};
48 struct scan_field select_dbus = {
49  .in_value = NULL,
50  .out_value = ir_dbus
51 };
52 static uint8_t ir_idcode[4] = {0x1};
53 struct scan_field select_idcode = {
54  .in_value = NULL,
55  .out_value = ir_idcode
56 };
57 
59 #define BSCAN_TUNNEL_IR_WIDTH_NBITS 7
60 uint8_t bscan_tunnel_ir_width; /* if zero, then tunneling is not present/active */
61 static int bscan_tunnel_ir_id; /* IR ID of the JTAG TAP to access the tunnel. Valid when not 0 */
62 
63 static const uint8_t bscan_zero[4] = {0};
64 static const uint8_t bscan_one[4] = {1};
65 
66 static uint8_t ir_user4[4];
67 static struct scan_field select_user4 = {
68  .in_value = NULL,
69  .out_value = ir_user4
70 };
71 
72 
74  {
75  .num_bits = 3,
76  .out_value = bscan_zero,
77  .in_value = NULL,
78  },
79  {
80  .num_bits = 5, /* initialized in riscv_init_target to ir width of DM */
81  .out_value = ir_dbus,
82  .in_value = NULL,
83  },
84  {
85  .num_bits = BSCAN_TUNNEL_IR_WIDTH_NBITS,
86  .out_value = &bscan_tunnel_ir_width,
87  .in_value = NULL,
88  },
89  {
90  .num_bits = 1,
91  .out_value = bscan_zero,
92  .in_value = NULL,
93  }
94 };
95 
97  {
98  .num_bits = 1,
99  .out_value = bscan_zero,
100  .in_value = NULL,
101  },
102  {
103  .num_bits = BSCAN_TUNNEL_IR_WIDTH_NBITS,
104  .out_value = &bscan_tunnel_ir_width,
105  .in_value = NULL,
106  },
107  {
108  .num_bits = 0, /* initialized in riscv_init_target to ir width of DM */
109  .out_value = ir_dbus,
110  .in_value = NULL,
111  },
112  {
113  .num_bits = 3,
114  .out_value = bscan_zero,
115  .in_value = NULL,
116  }
117 };
120 
123 
124 struct trigger {
125  uint64_t address;
126  uint32_t length;
127  uint64_t mask;
128  uint64_t value;
131 };
132 
133 struct tdata2_cache {
134  struct list_head elem_tdata2;
136 };
137 
138 struct tdata1_cache {
141  struct list_head elem_tdata1;
142 };
143 
145 {
146  assert(target);
147  RISCV_INFO(r);
148  return r->virt2phys_mode == RISCV_VIRT2PHYS_MODE_HW;
149 }
150 
152 {
153  assert(target);
154  RISCV_INFO(r);
155  return r->virt2phys_mode == RISCV_VIRT2PHYS_MODE_SW;
156 }
157 
159 {
163 
164  static const char *const names[] = {
165  [RISCV_VIRT2PHYS_MODE_HW] = "hw",
166  [RISCV_VIRT2PHYS_MODE_SW] = "sw",
167  [RISCV_VIRT2PHYS_MODE_OFF] = "off",
168  };
169 
170  return names[mode];
171 }
172 
173 /* Wall-clock timeout for a command/access. Settable via RISC-V Target commands.*/
175 
176 /* DEPRECATED Wall-clock timeout after reset. Settable via RISC-V Target commands.*/
178 
180 {
182 }
183 
184 static enum {
188 
189 static const virt2phys_info_t sv32 = {
190  .name = "Sv32",
191  .va_bits = 32,
192  .level = 2,
193  .pte_shift = 2,
194  .vpn_shift = {12, 22},
195  .vpn_mask = {0x3ff, 0x3ff},
196  .pte_ppn_shift = {10, 20},
197  .pte_ppn_mask = {0x3ff, 0xfff},
198  .pa_ppn_shift = {12, 22},
199  .pa_ppn_mask = {0x3ff, 0xfff},
200 };
201 
202 static const virt2phys_info_t sv32x4 = {
203  .name = "Sv32x4",
204  .va_bits = 34,
205  .level = 2,
206  .pte_shift = 2,
207  .vpn_shift = {12, 22},
208  .vpn_mask = {0x3ff, 0xfff},
209  .pte_ppn_shift = {10, 20},
210  .pte_ppn_mask = {0x3ff, 0xfff},
211  .pa_ppn_shift = {12, 22},
212  .pa_ppn_mask = {0x3ff, 0xfff},
213 };
214 
215 static const virt2phys_info_t sv39 = {
216  .name = "Sv39",
217  .va_bits = 39,
218  .level = 3,
219  .pte_shift = 3,
220  .vpn_shift = {12, 21, 30},
221  .vpn_mask = {0x1ff, 0x1ff, 0x1ff},
222  .pte_ppn_shift = {10, 19, 28},
223  .pte_ppn_mask = {0x1ff, 0x1ff, 0x3ffffff},
224  .pa_ppn_shift = {12, 21, 30},
225  .pa_ppn_mask = {0x1ff, 0x1ff, 0x3ffffff},
226 };
227 
228 static const virt2phys_info_t sv39x4 = {
229  .name = "Sv39x4",
230  .va_bits = 41,
231  .level = 3,
232  .pte_shift = 3,
233  .vpn_shift = {12, 21, 30},
234  .vpn_mask = {0x1ff, 0x1ff, 0x7ff},
235  .pte_ppn_shift = {10, 19, 28},
236  .pte_ppn_mask = {0x1ff, 0x1ff, 0x3ffffff},
237  .pa_ppn_shift = {12, 21, 30},
238  .pa_ppn_mask = {0x1ff, 0x1ff, 0x3ffffff},
239 };
240 
241 static const virt2phys_info_t sv48 = {
242  .name = "Sv48",
243  .va_bits = 48,
244  .level = 4,
245  .pte_shift = 3,
246  .vpn_shift = {12, 21, 30, 39},
247  .vpn_mask = {0x1ff, 0x1ff, 0x1ff, 0x1ff},
248  .pte_ppn_shift = {10, 19, 28, 37},
249  .pte_ppn_mask = {0x1ff, 0x1ff, 0x1ff, 0x1ffff},
250  .pa_ppn_shift = {12, 21, 30, 39},
251  .pa_ppn_mask = {0x1ff, 0x1ff, 0x1ff, 0x1ffff},
252 };
253 
254 static const virt2phys_info_t sv48x4 = {
255  .name = "Sv48x4",
256  .va_bits = 50,
257  .level = 4,
258  .pte_shift = 3,
259  .vpn_shift = {12, 21, 30, 39},
260  .vpn_mask = {0x1ff, 0x1ff, 0x1ff, 0x7ff},
261  .pte_ppn_shift = {10, 19, 28, 37},
262  .pte_ppn_mask = {0x1ff, 0x1ff, 0x1ff, 0x1ffff},
263  .pa_ppn_shift = {12, 21, 30, 39},
264  .pa_ppn_mask = {0x1ff, 0x1ff, 0x1ff, 0x1ffff},
265 };
266 
267 static const virt2phys_info_t sv57 = {
268  .name = "Sv57",
269  .va_bits = 57,
270  .level = 5,
271  .pte_shift = 3,
272  .vpn_shift = {12, 21, 30, 39, 48},
273  .vpn_mask = {0x1ff, 0x1ff, 0x1ff, 0x1ff, 0x1ff},
274  .pte_ppn_shift = {10, 19, 28, 37, 46},
275  .pte_ppn_mask = {0x1ff, 0x1ff, 0x1ff, 0x1ff, 0xff},
276  .pa_ppn_shift = {12, 21, 30, 39, 48},
277  .pa_ppn_mask = {0x1ff, 0x1ff, 0x1ff, 0x1ff, 0x1ff},
278 };
279 
280 static const virt2phys_info_t sv57x4 = {
281  .name = "Sv57x4",
282  .va_bits = 59,
283  .level = 5,
284  .pte_shift = 3,
285  .vpn_shift = {12, 21, 30, 39, 48},
286  .vpn_mask = {0x1ff, 0x1ff, 0x1ff, 0x1ff, 0x7ff},
287  .pte_ppn_shift = {10, 19, 28, 37, 46},
288  .pte_ppn_mask = {0x1ff, 0x1ff, 0x1ff, 0x1ff, 0xff},
289  .pa_ppn_shift = {12, 21, 30, 39, 48},
290  .pa_ppn_mask = {0x1ff, 0x1ff, 0x1ff, 0x1ff, 0xff},
291 };
292 
293 static enum riscv_halt_reason riscv_halt_reason(struct target *target);
294 static void riscv_info_init(struct target *target, struct riscv_info *r);
295 static int riscv_step_rtos_hart(struct target *target);
296 
298 static int riscv_interrupts_disable(struct target *target, riscv_reg_t *old_mstatus);
299 static int riscv_interrupts_restore(struct target *target, riscv_reg_t old_mstatus);
300 
301 static void riscv_sample_buf_maybe_add_timestamp(struct target *target, bool before)
302 {
303  RISCV_INFO(r);
304  uint32_t now = timeval_ms() & 0xffffffff;
305  if (r->sample_buf.used + 5 < r->sample_buf.size) {
306  if (before)
307  r->sample_buf.buf[r->sample_buf.used++] = RISCV_SAMPLE_BUF_TIMESTAMP_BEFORE;
308  else
309  r->sample_buf.buf[r->sample_buf.used++] = RISCV_SAMPLE_BUF_TIMESTAMP_AFTER;
310  r->sample_buf.buf[r->sample_buf.used++] = now & 0xff;
311  r->sample_buf.buf[r->sample_buf.used++] = (now >> 8) & 0xff;
312  r->sample_buf.buf[r->sample_buf.used++] = (now >> 16) & 0xff;
313  r->sample_buf.buf[r->sample_buf.used++] = (now >> 24) & 0xff;
314  }
315 }
316 
317 static int riscv_resume_go_all_harts(struct target *target);
318 
320 {
325  else /* BSCAN_TUNNEL_NESTED_TAP */
328 }
329 
330 static int dtmcs_scan_via_bscan(struct jtag_tap *tap, uint32_t out, uint32_t *in_ptr)
331 {
332  /* On BSCAN TAP: Select IR=USER4, issue tunneled IR scan via BSCAN TAP's DR */
333  uint8_t tunneled_dr_width[4] = {32};
334  uint8_t out_value[5] = {0};
335  uint8_t in_value[5] = {0};
336 
337  buf_set_u32(out_value, 0, 32, out);
338  struct scan_field tunneled_ir[4] = {};
339  struct scan_field tunneled_dr[4] = {};
340 
342  tunneled_ir[0].num_bits = 3;
343  tunneled_ir[0].out_value = bscan_zero;
344  tunneled_ir[0].in_value = NULL;
345  tunneled_ir[1].num_bits = bscan_tunnel_ir_width;
346  tunneled_ir[1].out_value = ir_dtmcontrol;
347  tunneled_ir[1].in_value = NULL;
348  tunneled_ir[2].num_bits = BSCAN_TUNNEL_IR_WIDTH_NBITS;
349  tunneled_ir[2].out_value = &bscan_tunnel_ir_width;
350  tunneled_ir[2].in_value = NULL;
351  tunneled_ir[3].num_bits = 1;
352  tunneled_ir[3].out_value = bscan_zero;
353  tunneled_ir[3].in_value = NULL;
354 
355  tunneled_dr[0].num_bits = 3;
356  tunneled_dr[0].out_value = bscan_zero;
357  tunneled_dr[0].in_value = NULL;
358  tunneled_dr[1].num_bits = 32 + 1;
359  tunneled_dr[1].out_value = out_value;
360  tunneled_dr[1].in_value = in_value;
361  tunneled_dr[2].num_bits = BSCAN_TUNNEL_IR_WIDTH_NBITS;
362  tunneled_dr[2].out_value = tunneled_dr_width;
363  tunneled_dr[2].in_value = NULL;
364  tunneled_dr[3].num_bits = 1;
365  tunneled_dr[3].out_value = bscan_one;
366  tunneled_dr[3].in_value = NULL;
367  } else {
368  /* BSCAN_TUNNEL_NESTED_TAP */
369  tunneled_ir[3].num_bits = 3;
370  tunneled_ir[3].out_value = bscan_zero;
371  tunneled_ir[3].in_value = NULL;
372  tunneled_ir[2].num_bits = bscan_tunnel_ir_width;
373  tunneled_ir[2].out_value = ir_dtmcontrol;
374  tunneled_ir[1].in_value = NULL;
375  tunneled_ir[1].num_bits = BSCAN_TUNNEL_IR_WIDTH_NBITS;
376  tunneled_ir[1].out_value = &bscan_tunnel_ir_width;
377  tunneled_ir[2].in_value = NULL;
378  tunneled_ir[0].num_bits = 1;
379  tunneled_ir[0].out_value = bscan_zero;
380  tunneled_ir[0].in_value = NULL;
381 
382  tunneled_dr[3].num_bits = 3;
383  tunneled_dr[3].out_value = bscan_zero;
384  tunneled_dr[3].in_value = NULL;
385  tunneled_dr[2].num_bits = 32 + 1;
386  tunneled_dr[2].out_value = out_value;
387  tunneled_dr[2].in_value = in_value;
388  tunneled_dr[1].num_bits = 7;
389  tunneled_dr[1].out_value = tunneled_dr_width;
390  tunneled_dr[1].in_value = NULL;
391  tunneled_dr[0].num_bits = 1;
392  tunneled_dr[0].out_value = bscan_one;
393  tunneled_dr[0].in_value = NULL;
394  }
396  jtag_add_dr_scan(tap, ARRAY_SIZE(tunneled_ir), tunneled_ir, TAP_IDLE);
397  jtag_add_dr_scan(tap, ARRAY_SIZE(tunneled_dr), tunneled_dr, TAP_IDLE);
399 
400  int retval = jtag_execute_queue();
401  if (retval != ERROR_OK) {
402  LOG_ERROR("failed jtag scan: %d", retval);
403  return retval;
404  }
405  /* Note the starting offset is bit 1, not bit 0. In BSCAN tunnel, there is a one-bit TCK skew between
406  output and input */
407  uint32_t in = buf_get_u32(in_value, 1, 32);
408  LOG_DEBUG("DTMCS: 0x%x -> 0x%x", out, in);
409 
410  if (in_ptr)
411  *in_ptr = in;
412  return ERROR_OK;
413 }
414 
415 /* TODO: rename "dtmcontrol"-> "dtmcs" */
416 int dtmcs_scan(struct jtag_tap *tap, uint32_t out, uint32_t *in_ptr)
417 {
418  uint8_t value[4];
419 
420  if (bscan_tunnel_ir_width != 0)
421  return dtmcs_scan_via_bscan(tap, out, in_ptr);
422 
423  buf_set_u32(value, 0, 32, out);
424 
426 
427  struct scan_field field = {
428  .num_bits = 32,
429  .out_value = value,
430  .in_value = in_ptr ? value : NULL
431  };
432  jtag_add_dr_scan(tap, 1, &field, TAP_IDLE);
433 
434  /* Always return to dbus. */
436 
437  int retval = jtag_execute_queue();
438  if (retval != ERROR_OK) {
439  LOG_ERROR("'dtmcs' scan failed on TAP %s, error code = %d",
440  jtag_tap_name(tap), retval);
441  return retval;
442  }
443 
444  if (in_ptr) {
445  assert(field.in_value);
446  uint32_t in = buf_get_u32(field.in_value, 0, 32);
447  LOG_DEBUG("TAP %s: DTMCS: 0x%" PRIx32 " -> 0x%" PRIx32,
448  jtag_tap_name(tap), out, in);
449  *in_ptr = in;
450  } else {
451  LOG_DEBUG("TAP %s: DTMCS: 0x%" PRIx32 " -> ?", jtag_tap_name(tap), out);
452  }
453  return ERROR_OK;
454 }
455 
456 static struct target_type *get_target_type(struct target *target)
457 {
458  if (!target->arch_info) {
459  LOG_TARGET_ERROR(target, "Target has not been initialized.");
460  return NULL;
461  }
462 
463  RISCV_INFO(info);
464  switch (info->dtm_version) {
466  return &riscv011_target;
468  return &riscv013_target;
469  default:
470  /* TODO: once we have proper support for non-examined targets
471  * we should have an assert here */
472  LOG_TARGET_ERROR(target, "Unsupported DTM version: %d",
473  info->dtm_version);
474  return NULL;
475  }
476 }
477 
479 {
480  struct riscv_private_config * const config = malloc(sizeof(*config));
481  if (!config) {
482  LOG_ERROR("Out of memory!");
483  return NULL;
484  }
485 
486  for (unsigned int i = 0; i < ARRAY_SIZE(config->dcsr_ebreak_fields); ++i)
487  config->dcsr_ebreak_fields[i] = true;
488 
489  return config;
490 }
491 
492 static int riscv_create_target(struct target *target)
493 {
494  LOG_TARGET_DEBUG(target, "riscv_create_target()");
496  if (!config) {
498  if (!config)
499  return ERROR_FAIL;
501  }
502  target->arch_info = calloc(1, sizeof(struct riscv_info));
503  if (!target->arch_info) {
504  LOG_TARGET_ERROR(target, "Failed to allocate RISC-V target structure.");
505  return ERROR_FAIL;
506  }
508  return ERROR_OK;
509 }
510 
511 static struct jim_nvp nvp_ebreak_config_opts[] = {
512  { .name = "m", .value = RISCV_MODE_M },
513  { .name = "s", .value = RISCV_MODE_S },
514  { .name = "u", .value = RISCV_MODE_U },
515  { .name = "vs", .value = RISCV_MODE_VS },
516  { .name = "vu", .value = RISCV_MODE_VU },
517  { .name = NULL, .value = N_RISCV_MODE }
518 };
519 
520 #define RISCV_EBREAK_MODE_INVALID -1
521 
522 static struct jim_nvp nvp_ebreak_mode_opts[] = {
523  { .name = "exception", .value = false },
524  { .name = "halt", .value = true },
525  { .name = NULL, .value = RISCV_EBREAK_MODE_INVALID }
526 };
527 
529 {
530  if (goi->argc == 0) {
531  Jim_WrongNumArgs(goi->interp, 1, goi->argv - 1,
532  "[?execution_mode?] ?ebreak_action?");
533  return JIM_ERR;
534  }
535  struct jim_nvp *common_mode_nvp;
537  &common_mode_nvp) == JIM_OK) {
538  /* Here a common "ebreak" action is processed, e.g:
539  * "riscv.cpu configure -ebreak halt"
540  */
541  int res = jim_getopt_obj(goi, NULL);
542  if (res != JIM_OK)
543  return res;
544  for (int ebreak_ctl_i = 0; ebreak_ctl_i < N_RISCV_MODE; ++ebreak_ctl_i)
545  config->dcsr_ebreak_fields[ebreak_ctl_i] = common_mode_nvp->value;
546  return JIM_OK;
547  }
548 
549  /* Here a "ebreak" action for a specific execution mode is processed, e.g:
550  * "riscv.cpu configure -ebreak m halt"
551  */
552  if (goi->argc < 2) {
553  Jim_WrongNumArgs(goi->interp, 2, goi->argv - 2,
554  "?ebreak_action?");
555  return JIM_ERR;
556  }
557  struct jim_nvp *ctrl_nvp;
558  if (jim_getopt_nvp(goi, nvp_ebreak_config_opts, &ctrl_nvp) != JIM_OK) {
559  jim_getopt_nvp_unknown(goi, nvp_ebreak_config_opts, /*hadprefix*/ true);
560  return JIM_ERR;
561  }
562  struct jim_nvp *mode_nvp;
563  if (jim_getopt_nvp(goi, nvp_ebreak_mode_opts, &mode_nvp) != JIM_OK) {
564  jim_getopt_nvp_unknown(goi, nvp_ebreak_mode_opts, /*hadprefix*/ true);
565  return JIM_ERR;
566  }
567  config->dcsr_ebreak_fields[ctrl_nvp->value] = mode_nvp->value;
568  return JIM_OK;
569 }
570 
578  char *buffer)
579 {
580  int len = 0;
581  const char *separator = "";
582  for (int ebreak_ctl_i = 0; ebreak_ctl_i < N_RISCV_MODE;
583  ++ebreak_ctl_i) {
584  const char * const format = "%s%s %s";
585  const char * const priv_mode =
588  config->dcsr_ebreak_fields[ebreak_ctl_i])->name;
589  if (!buffer)
590  len += snprintf(NULL, 0, format, separator, priv_mode, mode);
591  else
592  len += sprintf(buffer + len, format, separator, priv_mode, mode);
593 
594  separator = "\n";
595  }
596  return len;
597 }
598 
600  Jim_Interp *interp)
601 {
602  const int len = ebreak_config_to_tcl_dict(config, NULL);
603  char *str = malloc(len + 1);
604  if (!str) {
605  LOG_ERROR("Unable to allocate a string of %d bytes.", len + 1);
606  return JIM_ERR;
607  }
609  Jim_SetResultString(interp, str, len);
610  free(str);
611  return JIM_OK;
612 }
613 
616  RISCV_CFG_INVALID = -1
617 };
618 
619 static struct jim_nvp nvp_config_opts[] = {
620  { .name = "-ebreak", .value = RISCV_CFG_EBREAK },
621  { .name = NULL, .value = RISCV_CFG_INVALID }
622 };
623 
624 static int riscv_jim_configure(struct target *target,
625  struct jim_getopt_info *goi)
626 {
628  if (!config) {
630  if (!config)
631  return JIM_ERR;
633  }
634  if (!goi->argc)
635  return JIM_OK;
636 
637  struct jim_nvp *n;
639  goi->argv[0], &n);
640  if (e != JIM_OK)
641  return JIM_CONTINUE;
642 
643  e = jim_getopt_obj(goi, NULL);
644  if (e != JIM_OK)
645  return e;
646 
647  if (!goi->is_configure && goi->argc > 0) {
648  /* Expecting no arguments */
649  Jim_WrongNumArgs(goi->interp, 2, goi->argv - 2, "");
650  return JIM_ERR;
651  }
652  switch (n->value) {
653  case RISCV_CFG_EBREAK:
654  return goi->is_configure
657  default:
658  assert(false && "'jim_getopt_nvp' should have returned an error.");
659  }
660  return JIM_ERR;
661 }
662 
663 static int riscv_init_target(struct command_context *cmd_ctx,
664  struct target *target)
665 {
666  LOG_TARGET_DEBUG(target, "riscv_init_target()");
667  RISCV_INFO(info);
668  info->cmd_ctx = cmd_ctx;
669  info->reset_delays_wait = -1;
670 
674 
675  if (bscan_tunnel_ir_width != 0) {
676  uint32_t ir_user4_raw = bscan_tunnel_ir_id;
677  /* Provide a default value which target some Xilinx FPGA USER4 IR */
678  if (ir_user4_raw == 0) {
679  assert(target->tap->ir_length >= 6);
680  ir_user4_raw = 0x23 << (target->tap->ir_length - 6);
681  }
682  h_u32_to_le(ir_user4, ir_user4_raw);
686  else /* BSCAN_TUNNEL_NESTED_TAP */
688  }
689 
691 
693 
694  return ERROR_OK;
695 }
696 
698 {
699  RISCV_INFO(r);
700 
701  for (unsigned int i = 0; i < r->trigger_count; ++i) {
702  struct tdata1_cache *elem_1, *tmp_1;
703  list_for_each_entry_safe(elem_1, tmp_1, &r->wp_triggers_negative_cache[i], elem_tdata1) {
704  struct tdata2_cache *elem_2, *tmp_2;
705  list_for_each_entry_safe(elem_2, tmp_2, &elem_1->tdata2_cache_head, elem_tdata2) {
706  list_del(&elem_2->elem_tdata2);
707  free(elem_2);
708  }
709  list_del(&elem_1->elem_tdata1);
710  free(elem_1);
711  }
712  }
713  free(r->wp_triggers_negative_cache);
714 }
715 
716 static void riscv_deinit_target(struct target *target)
717 {
718  LOG_TARGET_DEBUG(target, "riscv_deinit_target()");
719 
720  free(target->private_config);
721 
722  struct riscv_info *info = target->arch_info;
723  struct target_type *tt = get_target_type(target);
724  if (!tt)
725  LOG_TARGET_ERROR(target, "Could not identify target type.");
726 
728  LOG_TARGET_ERROR(target, "Failed to flush registers. Ignoring this error.");
729 
730  if (tt && info && info->version_specific)
731  tt->deinit_target(target);
732 
735 
736  if (!info)
737  return;
738 
739  free(info->reserved_triggers);
740 
741  range_list_t *entry, *tmp;
742  list_for_each_entry_safe(entry, tmp, &info->hide_csr, list) {
743  free(entry->name);
744  free(entry);
745  }
746 
747  list_for_each_entry_safe(entry, tmp, &info->expose_csr, list) {
748  free(entry->name);
749  free(entry);
750  }
751 
752  list_for_each_entry_safe(entry, tmp, &info->expose_custom, list) {
753  free(entry->name);
754  free(entry);
755  }
756 
757  free(target->arch_info);
758 
759  target->arch_info = NULL;
760 }
761 
763  const struct breakpoint *breakpoint)
764 {
767  trigger->mask = ~0LL;
768  trigger->is_read = false;
769  trigger->is_write = false;
770  trigger->is_execute = true;
771  /* unique_id is unique across both breakpoints and watchpoints. */
773 }
774 
775 static bool can_use_napot_match(struct trigger *trigger)
776 {
779  bool size_power_of_2 = (size & (size - 1)) == 0;
780  bool addr_aligned = (addr & (size - 1)) == 0;
781  return size > 1 && size_power_of_2 && addr_aligned;
782 }
783 
784 /* Find the next free trigger of the given type, without talking to the target. */
785 static int find_next_free_trigger(struct target *target, int type, bool chained,
786  unsigned int *idx)
787 {
788  assert(idx);
789  RISCV_INFO(r);
790 
791  unsigned int num_found = 0;
792  unsigned int num_required = chained ? 2 : 1;
793 
794  for (unsigned int i = *idx; i < r->trigger_count; i++) {
795  if (r->trigger_unique_id[i] == -1) {
796  if (r->trigger_tinfo[i] & (1 << type)) {
797  num_found++;
798  if (num_required == num_found) {
799  /* Found num_required consecutive free triggers - success, done. */
800  *idx = i - (num_required - 1);
802  "%d trigger(s) of type %d found on index %u, "
803  "chained == %s",
804  num_required, type, *idx,
805  chained ? "true" : "false");
806  return ERROR_OK;
807  }
808  /* Found a trigger but need more consecutive ones */
809  continue;
810  }
811  }
812  /* Trigger already occupied or incompatible type.
813  * Reset the counter of found consecutive triggers */
814  num_found = 0;
815  }
816 
817  return ERROR_FAIL;
818 }
819 
820 static int find_first_trigger_by_id(struct target *target, int unique_id)
821 {
822  RISCV_INFO(r);
823 
824  for (unsigned int i = 0; i < r->trigger_count; i++) {
825  if (r->trigger_unique_id[i] == unique_id)
826  return i;
827  }
828  return -1;
829 }
830 
831 static unsigned int count_trailing_ones(riscv_reg_t reg)
832 {
833  const unsigned int riscv_reg_bits = sizeof(riscv_reg_t) * CHAR_BIT;
834  for (unsigned int i = 0; i < riscv_reg_bits; i++) {
835  if ((1 & (reg >> i)) == 0)
836  return i;
837  }
838  return riscv_reg_bits;
839 }
840 
841 static int set_trigger(struct target *target, unsigned int idx, riscv_reg_t tdata1, riscv_reg_t tdata2)
842 {
843  RISCV_INFO(r);
844  assert(r->reserved_triggers);
845  assert(idx < r->trigger_count);
846  if (r->reserved_triggers[idx]) {
848  "Trigger %u is reserved by 'reserve_trigger' command.", idx);
850  }
851 
852  riscv_reg_t tdata1_rb, tdata2_rb;
853  // Select which trigger to use
855  return ERROR_FAIL;
856 
857  // Disable the trigger by writing 0 to it
859  return ERROR_FAIL;
860 
861  // Set trigger data for tdata2 (and tdata3 if it was supported)
863  return ERROR_FAIL;
864 
865  // Set trigger data for tdata1
867  return ERROR_FAIL;
868 
869  // Read back tdata1, tdata2, (tdata3), and check if the configuration is supported
870  if (riscv_reg_get(target, &tdata1_rb, GDB_REGNO_TDATA1) != ERROR_OK)
871  return ERROR_FAIL;
872  if (riscv_reg_get(target, &tdata2_rb, GDB_REGNO_TDATA2) != ERROR_OK)
873  return ERROR_FAIL;
874 
875  const uint32_t type = get_field(tdata1, CSR_TDATA1_TYPE(riscv_xlen(target)));
876  const bool is_mcontrol = type == CSR_TDATA1_TYPE_MCONTROL;
877 
878  /* Determine if tdata1 supports what we need.
879  * For mcontrol triggers, we don't care about
880  * the value in the read-only "maskmax" field.
881  */
882  const riscv_reg_t tdata1_ignore_mask = is_mcontrol ? CSR_MCONTROL_MASKMAX(riscv_xlen(target)) : 0;
883  const bool tdata1_config_denied = (tdata1 & ~tdata1_ignore_mask) != (tdata1_rb & ~tdata1_ignore_mask);
884 
885  /* Determine if tdata1.maxmask is sufficient
886  * (only relevant for mcontrol triggers and NAPOT match type)
887  */
888  bool unsupported_napot_range = false;
889  riscv_reg_t maskmax_value = 0;
890  if (!tdata1_config_denied) {
891  const bool is_napot_match = get_field(tdata1_rb, CSR_MCONTROL_MATCH) == CSR_MCONTROL_MATCH_NAPOT;
892  if (is_mcontrol && is_napot_match) {
893  maskmax_value = get_field(tdata1_rb, CSR_MCONTROL_MASKMAX(riscv_xlen(target)));
894  const unsigned int napot_size = count_trailing_ones(tdata2) + 1;
895  if (maskmax_value < napot_size)
896  unsupported_napot_range = true;
897  }
898  }
899 
900  const bool tdata2_config_denied = tdata2 != tdata2_rb;
901  if (tdata1_config_denied || tdata2_config_denied || unsupported_napot_range) {
902  LOG_TARGET_DEBUG(target, "Trigger %u doesn't support what we need.", idx);
903 
904  if (tdata1_config_denied)
906  "After writing 0x%" PRIx64 " to tdata1 it contains 0x%" PRIx64,
907  tdata1, tdata1_rb);
908 
909  if (tdata2_config_denied)
911  "After writing 0x%" PRIx64 " to tdata2 it contains 0x%" PRIx64,
912  tdata2, tdata2_rb);
913 
914  if (unsupported_napot_range)
916  "The requested NAPOT match range (tdata2=0x%" PRIx64 ") exceeds maskmax_value=0x%" PRIx64,
917  tdata2, maskmax_value);
918 
920  return ERROR_FAIL;
922  }
923 
924  return ERROR_OK;
925 }
926 
927 static int maybe_add_trigger_t1(struct target *target, struct trigger *trigger)
928 {
929  int ret;
930  riscv_reg_t tdata1, tdata2;
931 
932  RISCV_INFO(r);
933 
934  const uint32_t bpcontrol_x = 1<<0;
935  const uint32_t bpcontrol_w = 1<<1;
936  const uint32_t bpcontrol_r = 1<<2;
937  const uint32_t bpcontrol_u = 1<<3;
938  const uint32_t bpcontrol_s = 1<<4;
939  const uint32_t bpcontrol_h = 1<<5;
940  const uint32_t bpcontrol_m = 1<<6;
941  const uint32_t bpcontrol_bpmatch = 0xf << 7;
942  const uint32_t bpcontrol_bpaction = 0xff << 11;
943 
944  unsigned int idx = 0;
946  if (ret != ERROR_OK)
947  return ret;
948 
949  if (riscv_reg_get(target, &tdata1, GDB_REGNO_TDATA1) != ERROR_OK)
950  return ERROR_FAIL;
951  if (tdata1 & (bpcontrol_r | bpcontrol_w | bpcontrol_x)) {
952  /* Trigger is already in use, presumably by user code. */
954  }
955 
956  tdata1 = 0;
957  tdata1 = set_field(tdata1, bpcontrol_r, trigger->is_read);
958  tdata1 = set_field(tdata1, bpcontrol_w, trigger->is_write);
959  tdata1 = set_field(tdata1, bpcontrol_x, trigger->is_execute);
960  tdata1 = set_field(tdata1, bpcontrol_u, !!(r->misa & BIT('U' - 'A')));
961  tdata1 = set_field(tdata1, bpcontrol_s, !!(r->misa & BIT('S' - 'A')));
962  tdata1 = set_field(tdata1, bpcontrol_h, !!(r->misa & BIT('H' - 'A')));
963  tdata1 = set_field(tdata1, bpcontrol_m, 1);
964  tdata1 = set_field(tdata1, bpcontrol_bpaction, 0); /* cause bp exception */
965  tdata1 = set_field(tdata1, bpcontrol_bpmatch, 0); /* exact match */
966  tdata2 = trigger->address;
967  ret = set_trigger(target, idx, tdata1, tdata2);
968  if (ret != ERROR_OK)
969  return ret;
970  r->trigger_unique_id[idx] = trigger->unique_id;
971  return ERROR_OK;
972 }
973 
977 };
978 
979 static void log_trigger_request_info(struct trigger_request_info trig_info)
980 {
981  LOG_DEBUG("tdata1=%" PRIx64 ", tdata2=%" PRIx64, trig_info.tdata1, trig_info.tdata2);
982 };
983 
984 static struct tdata1_cache *tdata1_cache_alloc(struct list_head *tdata1_cache_head, riscv_reg_t tdata1)
985 {
986  struct tdata1_cache *elem = (struct tdata1_cache *)calloc(1, sizeof(struct tdata1_cache));
987  elem->tdata1 = tdata1;
989  list_add_tail(&elem->elem_tdata1, tdata1_cache_head);
990  return elem;
991 }
992 
994 {
995  struct tdata2_cache * const elem = calloc(1, sizeof(struct tdata2_cache));
996  elem->tdata2 = tdata2;
997  list_add(&elem->elem_tdata2, tdata2_cache_head);
998 }
999 
1000 struct tdata2_cache *tdata2_cache_search(struct list_head *tdata2_cache_head, riscv_reg_t find_tdata2)
1001 {
1002  struct tdata2_cache *elem_2;
1003  list_for_each_entry(elem_2, tdata2_cache_head, elem_tdata2) {
1004  if (elem_2->tdata2 == find_tdata2)
1005  return elem_2;
1006  }
1007  return NULL;
1008 }
1009 
1010 struct tdata1_cache *tdata1_cache_search(struct list_head *tdata1_cache_head, riscv_reg_t find_tdata1)
1011 {
1012  struct tdata1_cache *elem_1;
1013  list_for_each_entry(elem_1, tdata1_cache_head, elem_tdata1) {
1014  if (elem_1->tdata1 == find_tdata1)
1015  return elem_1;
1016  }
1017  return NULL;
1018 }
1019 
1021 {
1022  RISCV_INFO(r);
1023 
1024  r->wp_triggers_negative_cache = (struct list_head *)calloc(r->trigger_count,
1025  sizeof(struct list_head));
1026  for (unsigned int i = 0; i < r->trigger_count; ++i)
1027  INIT_LIST_HEAD(&r->wp_triggers_negative_cache[i]);
1028 }
1029 
1030 static void wp_triggers_cache_add(struct target *target, unsigned int idx, riscv_reg_t tdata1,
1031  riscv_reg_t tdata2, int error_code)
1032 {
1033  RISCV_INFO(r);
1034 
1035  struct tdata1_cache *tdata1_cache = tdata1_cache_search(&r->wp_triggers_negative_cache[idx], tdata1);
1036  if (!tdata1_cache) {
1037  tdata1_cache = tdata1_cache_alloc(&r->wp_triggers_negative_cache[idx], tdata1);
1038  } else {
1040  if (tdata2_cache) {
1042  return;
1043  }
1044  }
1046 }
1047 
1048 static bool wp_triggers_cache_search(struct target *target, unsigned int idx,
1049  riscv_reg_t tdata1, riscv_reg_t tdata2)
1050 {
1051  RISCV_INFO(r);
1052 
1053  struct tdata1_cache *tdata1_cache = tdata1_cache_search(&r->wp_triggers_negative_cache[idx], tdata1);
1054  if (!tdata1_cache)
1055  return false;
1057  if (!tdata2_cache)
1058  return false;
1059  assert(tdata1_cache->tdata1 == tdata1 && tdata2_cache->tdata2 == tdata2);
1060  return true;
1061 }
1062 
1063 static int try_use_trigger_and_cache_result(struct target *target, unsigned int idx, riscv_reg_t tdata1,
1065 {
1066  if (wp_triggers_cache_search(target, idx, tdata1, tdata2))
1068 
1069  int ret = set_trigger(target, idx, tdata1, tdata2);
1070 
1071  /* Add these values to the cache to remember that they are not supported. */
1073  wp_triggers_cache_add(target, idx, tdata1, tdata2, ret);
1074  return ret;
1075 }
1076 
1078  struct trigger *trigger, struct trigger_request_info trig_info)
1079 {
1080  LOG_TARGET_DEBUG(target, "trying to set up a match trigger");
1081  log_trigger_request_info(trig_info);
1082 
1083  int trigger_type =
1086  RISCV_INFO(r);
1087 
1088  /* Find the first trigger, supporting required tdata1 value */
1089  for (unsigned int idx = 0;
1090  find_next_free_trigger(target, trigger_type, false, &idx) == ERROR_OK;
1091  ++idx) {
1092  ret = try_use_trigger_and_cache_result(target, idx, trig_info.tdata1, trig_info.tdata2);
1093 
1094  if (ret == ERROR_OK) {
1095  r->trigger_unique_id[idx] = trigger->unique_id;
1096  return ERROR_OK;
1097  }
1099  return ret;
1100  }
1101  return ret;
1102 }
1103 
1105  struct trigger *trigger, struct trigger_request_info t1,
1106  struct trigger_request_info t2)
1107 {
1108  LOG_TARGET_DEBUG(target, "trying to set up a chain of match triggers");
1111  int trigger_type =
1114  RISCV_INFO(r);
1115 
1116  /* Find the first 2 consecutive triggers, supporting required tdata1 values */
1117  for (unsigned int idx = 0;
1118  find_next_free_trigger(target, trigger_type, true, &idx) == ERROR_OK;
1119  ++idx) {
1120  ret = try_use_trigger_and_cache_result(target, idx, t1.tdata1, t1.tdata2);
1121 
1123  continue;
1124  else if (ret != ERROR_OK)
1125  return ret;
1126 
1127  ret = try_use_trigger_and_cache_result(target, idx + 1, t2.tdata1, t2.tdata2);
1128 
1129  if (ret == ERROR_OK) {
1130  r->trigger_unique_id[idx] = trigger->unique_id;
1131  r->trigger_unique_id[idx + 1] = trigger->unique_id;
1132  return ERROR_OK;
1133  }
1134  /* Undo the setting of the previous trigger */
1135  int ret_undo = set_trigger(target, idx, 0, 0);
1136  if (ret_undo != ERROR_OK)
1137  return ret_undo;
1138 
1140  return ret;
1141  }
1142  return ret;
1143 }
1144 
1147  struct {
1148  /* Other values are available for this field,
1149  * but currently only `any` is needed.
1150  */
1152  } size;
1153  struct {
1157  struct {
1163 };
1164 
1166  struct trigger *trigger)
1167 {
1168  RISCV_INFO(r);
1169 
1170  struct match_triggers_tdata1_fields result = {
1171  .common =
1176  field_value(CSR_MCONTROL_S, !!(r->misa & BIT('S' - 'A'))) |
1177  field_value(CSR_MCONTROL_U, !!(r->misa & BIT('U' - 'A'))) |
1181  .size = {
1182  .any =
1185  },
1186  .chain = {
1189  },
1190  .match = {
1195  }
1196  };
1197  return result;
1198 }
1199 
1201  struct trigger *trigger)
1202 {
1203  bool misa_s = riscv_supports_extension(target, 'S');
1204  bool misa_u = riscv_supports_extension(target, 'U');
1205  bool misa_h = riscv_supports_extension(target, 'H');
1206 
1207  struct match_triggers_tdata1_fields result = {
1208  .common =
1213  field_value(CSR_MCONTROL6_S, misa_s) |
1214  field_value(CSR_MCONTROL6_U, misa_u) |
1215  field_value(CSR_MCONTROL6_VS, misa_h && misa_s) |
1216  field_value(CSR_MCONTROL6_VU, misa_h && misa_u) |
1220  .size = {
1222  },
1223  .chain = {
1226  },
1227  .match = {
1232  }
1233  };
1234  return result;
1235 }
1236 
1238  struct trigger *trigger, struct match_triggers_tdata1_fields fields)
1239 {
1240  RISCV_INFO(r);
1242 
1243  if (trigger->length > 0) {
1244  /* Setting a load/store trigger ("watchpoint") on a range of addresses */
1246  if (r->wp_allow_napot_trigger) {
1247  LOG_TARGET_DEBUG(target, "trying to setup NAPOT match trigger");
1248  struct trigger_request_info napot = {
1249  .tdata1 = fields.common | fields.size.any |
1250  fields.chain.disable | fields.match.napot,
1251  .tdata2 = trigger->address | ((trigger->length - 1) >> 1)
1252  };
1255  return ret;
1256  } else {
1257  LOG_TARGET_DEBUG(target, "NAPOT match triggers are disabled for watchpoints. "
1258  "Use 'riscv set_enable_trigger_feature napot wp' to enable it.");
1259  }
1260  }
1261 
1262  if (r->wp_allow_ge_lt_trigger) {
1263  LOG_TARGET_DEBUG(target, "trying to setup GE+LT chained match trigger pair");
1264  struct trigger_request_info ge_1 = {
1265  .tdata1 = fields.common | fields.size.any | fields.chain.enable |
1266  fields.match.ge,
1267  .tdata2 = trigger->address
1268  };
1269  struct trigger_request_info lt_2 = {
1270  .tdata1 = fields.common | fields.size.any | fields.chain.disable |
1271  fields.match.lt,
1272  .tdata2 = trigger->address + trigger->length
1273  };
1274  ret = try_setup_chained_match_triggers(target, trigger, ge_1, lt_2);
1276  return ret;
1277 
1278  LOG_TARGET_DEBUG(target, "trying to setup LT+GE chained match trigger pair");
1279  struct trigger_request_info lt_1 = {
1280  .tdata1 = fields.common | fields.size.any | fields.chain.enable |
1281  fields.match.lt,
1282  .tdata2 = trigger->address + trigger->length
1283  };
1284  struct trigger_request_info ge_2 = {
1285  .tdata1 = fields.common | fields.size.any | fields.chain.disable |
1286  fields.match.ge,
1287  .tdata2 = trigger->address
1288  };
1289  ret = try_setup_chained_match_triggers(target, trigger, lt_1, ge_2);
1291  return ret;
1292  } else {
1293  LOG_TARGET_DEBUG(target, "LT+GE chained match triggers are disabled for watchpoints. "
1294  "Use 'riscv set_enable_trigger_feature ge_lt wp' to enable it.");
1295  }
1296  }
1297 
1298  if (r->wp_allow_equality_match_trigger) {
1299  LOG_TARGET_DEBUG(target, "trying to setup equality match trigger");
1300  struct trigger_request_info eq = {
1301  .tdata1 = fields.common | fields.size.any | fields.chain.disable |
1302  fields.match.eq,
1303  .tdata2 = trigger->address
1304  };
1306  if (ret != ERROR_OK)
1307  return ret;
1308  } else {
1309  LOG_TARGET_DEBUG(target, "equality match triggers are disabled for watchpoints. "
1310  "Use 'riscv set_enable_trigger_feature eq wp' to enable it.");
1311  }
1312 
1313  if (ret == ERROR_OK && trigger->length > 1) {
1314  LOG_TARGET_DEBUG(target, "Trigger will match accesses at address 0x%" TARGET_PRIxADDR
1315  ", but may not match accesses at addresses in the inclusive range from 0x%"
1317  trigger->address + 1, trigger->address + trigger->length - 1);
1318  RISCV_INFO(info);
1319  if (!info->range_trigger_fallback_encountered)
1320  /* This message is displayed only once per target to avoid
1321  * overwhelming the user with such messages on resume.
1322  */
1324  "Could not set a trigger that will match a whole address range. "
1325  "As a fallback, this trigger (and maybe others) will only match "
1326  "against the first address of the range.");
1327  info->range_trigger_fallback_encountered = true;
1328  }
1329 
1330  return ret;
1331 }
1332 
1334  struct trigger *trigger, struct match_triggers_tdata1_fields fields)
1335 {
1336  LOG_TARGET_DEBUG(target, "trying to setup equality match trigger");
1337  struct trigger_request_info eq = {
1338  .tdata1 = fields.common | fields.size.any | fields.chain.disable |
1339  fields.match.eq,
1340  .tdata2 = trigger->address
1341  };
1342 
1344 }
1345 
1347  struct trigger *trigger, struct match_triggers_tdata1_fields fields)
1348 {
1349  if (trigger->is_execute) {
1350  assert(!trigger->is_read && !trigger->is_write);
1352  }
1353 
1354  assert(trigger->is_read || trigger->is_write);
1356 }
1357 
1358 static int maybe_add_trigger_t3(struct target *target, bool vs, bool vu,
1359  bool m, bool s, bool u, bool pending, unsigned int count,
1360  int unique_id)
1361 {
1362  int ret;
1364 
1365  RISCV_INFO(r);
1366 
1367  tdata1 = 0;
1378 
1379  unsigned int idx = 0;
1381  if (ret != ERROR_OK)
1382  return ret;
1383  ret = set_trigger(target, idx, tdata1, 0);
1384  if (ret != ERROR_OK)
1385  return ret;
1386  r->trigger_unique_id[idx] = unique_id;
1387  return ERROR_OK;
1388 }
1389 
1390 static int maybe_add_trigger_t4(struct target *target, bool vs, bool vu,
1391  bool nmi, bool m, bool s, bool u, riscv_reg_t interrupts,
1392  int unique_id)
1393 {
1394  int ret;
1396 
1397  RISCV_INFO(r);
1398 
1399  tdata1 = 0;
1409 
1410  tdata2 = interrupts;
1411 
1412  unsigned int idx = 0;
1414  if (ret != ERROR_OK)
1415  return ret;
1416  ret = set_trigger(target, idx, tdata1, tdata2);
1417  if (ret != ERROR_OK)
1418  return ret;
1419  r->trigger_unique_id[idx] = unique_id;
1420  return ERROR_OK;
1421 }
1422 
1423 static int maybe_add_trigger_t5(struct target *target, bool vs, bool vu,
1424  bool m, bool s, bool u, riscv_reg_t exception_codes,
1425  int unique_id)
1426 {
1427  int ret;
1429 
1430  RISCV_INFO(r);
1431 
1432  tdata1 = 0;
1441 
1442  tdata2 = exception_codes;
1443 
1444  unsigned int idx = 0;
1446  if (ret != ERROR_OK)
1447  return ret;
1448  ret = set_trigger(target, idx, tdata1, tdata2);
1449  if (ret != ERROR_OK)
1450  return ret;
1451  r->trigger_unique_id[idx] = unique_id;
1452  return ERROR_OK;
1453 }
1454 
1455 static int add_trigger(struct target *target, struct trigger *trigger)
1456 {
1457  int ret;
1458  riscv_reg_t tselect;
1459 
1461  if (ret != ERROR_OK)
1462  return ret;
1463 
1464  ret = riscv_reg_get(target, &tselect, GDB_REGNO_TSELECT);
1465  if (ret != ERROR_OK)
1466  return ret;
1467 
1468  do {
1470  if (ret == ERROR_OK)
1471  break;
1474  if (ret == ERROR_OK)
1475  break;
1478  if (ret == ERROR_OK)
1479  break;
1480  } while (0);
1481 
1482  if (riscv_reg_set(target, GDB_REGNO_TSELECT, tselect) != ERROR_OK &&
1483  ret == ERROR_OK)
1484  return ERROR_FAIL;
1485 
1486  return ret;
1487 }
1488 
1494  uint32_t size, uint8_t *buffer, uint32_t access_size)
1495 {
1496  assert(size == 1 || size == 2 || size == 4 || size == 8);
1497  assert(access_size == 1 || access_size == 2 || access_size == 4 || access_size == 8);
1498 
1499  if (access_size <= size && address % access_size == 0)
1500  /* Can do the memory access directly without a helper buffer. */
1501  return target_write_memory(target, address, access_size, size / access_size, buffer);
1502 
1503  unsigned int offset_head = address % access_size;
1504  unsigned int n_blocks = ((size + offset_head) <= access_size) ? 1 : 2;
1505  uint8_t helper_buf[n_blocks * access_size];
1506 
1507  /* Read from memory */
1508  if (target_read_memory(target, address - offset_head, access_size, n_blocks, helper_buf) != ERROR_OK)
1509  return ERROR_FAIL;
1510 
1511  /* Modify and write back */
1512  memcpy(helper_buf + offset_head, buffer, size);
1513  return target_write_memory(target, address - offset_head, access_size, n_blocks, helper_buf);
1514 }
1515 
1521  uint32_t size, uint8_t *buffer, uint32_t access_size)
1522 {
1523  assert(size == 1 || size == 2 || size == 4 || size == 8);
1524  assert(access_size == 1 || access_size == 2 || access_size == 4 || access_size == 8);
1525 
1526  if (access_size <= size && address % access_size == 0)
1527  /* Can do the memory access directly without a helper buffer. */
1528  return target_read_memory(target, address, access_size, size / access_size, buffer);
1529 
1530  unsigned int offset_head = address % access_size;
1531  unsigned int n_blocks = ((size + offset_head) <= access_size) ? 1 : 2;
1532  uint8_t helper_buf[n_blocks * access_size];
1533 
1534  /* Read from memory */
1535  if (target_read_memory(target, address - offset_head, access_size, n_blocks, helper_buf) != ERROR_OK)
1536  return ERROR_FAIL;
1537 
1538  /* Pick the requested portion from the buffer */
1539  memcpy(buffer, helper_buf + offset_head, size);
1540  return ERROR_OK;
1541 }
1542 
1548 {
1549  assert(size == 1 || size == 2 || size == 4 || size == 8);
1550 
1551  /* Find access size that correspond to data size and the alignment. */
1552  unsigned int preferred_size = size;
1553  while (address % preferred_size != 0)
1554  preferred_size /= 2;
1555 
1556  /* First try the preferred (most natural) access size. */
1557  if (write_by_given_size(target, address, size, buffer, preferred_size) == ERROR_OK)
1558  return ERROR_OK;
1559 
1560  /* On failure, try other access sizes.
1561  Minimize the number of accesses by trying first the largest size. */
1562  for (unsigned int access_size = 8; access_size > 0; access_size /= 2) {
1563  if (access_size == preferred_size)
1564  /* Already tried this size. */
1565  continue;
1566 
1567  if (write_by_given_size(target, address, size, buffer, access_size) == ERROR_OK)
1568  return ERROR_OK;
1569  }
1570 
1571  /* No access attempt succeeded. */
1572  return ERROR_FAIL;
1573 }
1574 
1580 {
1581  assert(size == 1 || size == 2 || size == 4 || size == 8);
1582 
1583  /* Find access size that correspond to data size and the alignment. */
1584  unsigned int preferred_size = size;
1585  while (address % preferred_size != 0)
1586  preferred_size /= 2;
1587 
1588  /* First try the preferred (most natural) access size. */
1589  if (read_by_given_size(target, address, size, buffer, preferred_size) == ERROR_OK)
1590  return ERROR_OK;
1591 
1592  /* On failure, try other access sizes.
1593  Minimize the number of accesses by trying first the largest size. */
1594  for (unsigned int access_size = 8; access_size > 0; access_size /= 2) {
1595  if (access_size == preferred_size)
1596  /* Already tried this size. */
1597  continue;
1598 
1599  if (read_by_given_size(target, address, size, buffer, access_size) == ERROR_OK)
1600  return ERROR_OK;
1601  }
1602 
1603  /* No access attempt succeeded. */
1604  return ERROR_FAIL;
1605 }
1606 
1608 {
1610  assert(breakpoint);
1611  if (breakpoint->type == BKPT_SOFT) {
1613  if (!(breakpoint->length == 4 || breakpoint->length == 2)) {
1614  LOG_TARGET_ERROR(target, "Invalid breakpoint length %d", breakpoint->length);
1615  return ERROR_FAIL;
1616  }
1617 
1618  if (0 != (breakpoint->address % 2)) {
1619  LOG_TARGET_ERROR(target, "Invalid breakpoint alignment for address 0x%" TARGET_PRIxADDR,
1620  breakpoint->address);
1621  return ERROR_FAIL;
1622  }
1623 
1624  /* Read the original instruction. */
1627  LOG_TARGET_ERROR(target, "Failed to read original instruction at 0x%" TARGET_PRIxADDR,
1628  breakpoint->address);
1629  return ERROR_FAIL;
1630  }
1631 
1632  uint8_t buff[4] = { 0 };
1633  buf_set_u32(buff, 0, breakpoint->length * CHAR_BIT, breakpoint->length == 4 ? ebreak() : ebreak_c());
1634  /* Write the ebreak instruction. */
1636  LOG_TARGET_ERROR(target, "Failed to write %d-byte breakpoint instruction at 0x%"
1638  return ERROR_FAIL;
1639  }
1640  breakpoint->is_set = true;
1641 
1642  } else if (breakpoint->type == BKPT_HARD) {
1643  struct trigger trigger;
1645  int const result = add_trigger(target, &trigger);
1646  if (result != ERROR_OK)
1647  return result;
1648 
1649  int trigger_idx = find_first_trigger_by_id(target, breakpoint->unique_id);
1650  breakpoint_hw_set(breakpoint, trigger_idx);
1651  } else {
1652  LOG_TARGET_INFO(target, "OpenOCD only supports hardware and software breakpoints.");
1654  }
1655  return ERROR_OK;
1656 }
1657 
1658 static int remove_trigger(struct target *target, int unique_id)
1659 {
1660  RISCV_INFO(r);
1661 
1663  return ERROR_FAIL;
1664 
1665  riscv_reg_t tselect;
1666  int result = riscv_reg_get(target, &tselect, GDB_REGNO_TSELECT);
1667  if (result != ERROR_OK)
1668  return result;
1669 
1670  bool done = false;
1671  for (unsigned int i = 0; i < r->trigger_count; i++) {
1672  if (r->trigger_unique_id[i] == unique_id) {
1675  r->trigger_unique_id[i] = -1;
1676  LOG_TARGET_DEBUG(target, "Stop using resource %d for bp %d",
1677  i, unique_id);
1678  done = true;
1679  }
1680  }
1681  if (!done) {
1683  "Couldn't find the hardware resources used by hardware trigger.");
1685  }
1686 
1688 
1689  return ERROR_OK;
1690 }
1691 
1693  struct breakpoint *breakpoint)
1694 {
1695  if (breakpoint->type == BKPT_SOFT) {
1696  /* Write the original instruction. */
1699  LOG_TARGET_ERROR(target, "Failed to restore instruction for %d-byte breakpoint at "
1701  return ERROR_FAIL;
1702  }
1703 
1704  } else if (breakpoint->type == BKPT_HARD) {
1705  struct trigger trigger;
1707  int result = remove_trigger(target, trigger.unique_id);
1708  if (result != ERROR_OK)
1709  return result;
1710 
1711  } else {
1712  LOG_TARGET_INFO(target, "OpenOCD only supports hardware and software breakpoints.");
1714  }
1715 
1716  breakpoint->is_set = false;
1717 
1718  return ERROR_OK;
1719 }
1720 
1722  const struct watchpoint *watchpoint)
1723 {
1730  trigger->is_execute = false;
1731  /* unique_id is unique across both breakpoints and watchpoints. */
1733 }
1734 
1736 {
1738  LOG_TARGET_ERROR(target, "Watchpoints on data values are not implemented");
1740  }
1741 
1742  struct trigger trigger;
1744 
1745  int result = add_trigger(target, &trigger);
1746  if (result != ERROR_OK)
1747  return result;
1748 
1749  int trigger_idx = find_first_trigger_by_id(target, watchpoint->unique_id);
1750  watchpoint_set(watchpoint, trigger_idx);
1751 
1752  return ERROR_OK;
1753 }
1754 
1756  struct watchpoint *watchpoint)
1757 {
1758  LOG_TARGET_DEBUG(target, "Removing watchpoint @0x%" TARGET_PRIxADDR, watchpoint->address);
1759 
1760  struct trigger trigger;
1762 
1763  int result = remove_trigger(target, trigger.unique_id);
1764  if (result != ERROR_OK)
1765  return result;
1766  watchpoint->is_set = false;
1767 
1768  return ERROR_OK;
1769 }
1770 
1778 };
1779 
1781  riscv_reg_t tdata1, uint64_t hit_mask)
1782 {
1783  const uint32_t hit0 = get_field(tdata1, CSR_MCONTROL6_HIT0);
1784  const uint32_t hit1 = get_field(tdata1, CSR_MCONTROL6_HIT1);
1785  const uint32_t hit_info = (hit1 << 1) | hit0;
1786  if (hit_info == CSR_MCONTROL6_HIT0_BEFORE)
1787  return M6_HIT_BEFORE;
1788 
1789  if (hit_info == CSR_MCONTROL6_HIT0_AFTER)
1790  return M6_HIT_AFTER;
1791 
1792  if (hit_info == CSR_MCONTROL6_HIT0_IMMEDIATELY_AFTER)
1793  return M6_HIT_IMM_AFTER;
1794 
1795  if (hit_info == CSR_MCONTROL6_HIT0_FALSE) {
1796  /* hit[1..0] equals 0, which can mean one of the following:
1797  * - "hit" bits are supported and this trigger has not fired
1798  * - "hit" bits are not supported on this trigger
1799  * To distinguish these two cases, try writing all non-zero bit
1800  * patterns to hit[1..0] to determine if the "hit" bits are supported:
1801  */
1802  riscv_reg_t tdata1_tests[] = {
1803  set_field(tdata1, CSR_MCONTROL6_HIT0, 1),
1804  set_field(tdata1, CSR_MCONTROL6_HIT1, 1),
1806  };
1807  riscv_reg_t tdata1_test_rb;
1808  for (uint64_t i = 0; i < ARRAY_SIZE(tdata1_tests); ++i) {
1809  if (riscv_reg_set(target, GDB_REGNO_TDATA1, tdata1_tests[i]) != ERROR_OK)
1810  return M6_HIT_ERROR;
1811  if (riscv_reg_get(target, &tdata1_test_rb, GDB_REGNO_TDATA1) != ERROR_OK)
1812  return M6_HIT_ERROR;
1813  if (tdata1_test_rb == tdata1_tests[i]) {
1814  if (riscv_reg_set(target, GDB_REGNO_TDATA1, tdata1_test_rb & ~hit_mask) != ERROR_OK)
1815  return M6_HIT_ERROR;
1816  return M6_NOT_HIT;
1817  }
1818  }
1819  }
1820  return M6_HIT_NOT_SUPPORTED;
1821 }
1822 
1830  bool *need_single_step)
1831 {
1832  /* FIXME: this function assumes that we have only one trigger that can
1833  * have hit bit set. Debug spec allows hit bit to bit set if a trigger has
1834  * matched but did not fire. Such targets will receive erroneous results.
1835  */
1836 
1837  RISCV_INFO(r);
1838  assert(need_single_step);
1839  *need_single_step = false;
1840 
1841  riscv_reg_t tselect;
1842  if (riscv_reg_get(target, &tselect, GDB_REGNO_TSELECT) != ERROR_OK)
1843  return ERROR_FAIL;
1844 
1846  for (unsigned int i = 0; i < r->trigger_count; i++) {
1847  if (r->trigger_unique_id[i] == -1)
1848  continue;
1849 
1851  return ERROR_FAIL;
1852 
1853  uint64_t tdata1;
1854  if (riscv_reg_get(target, &tdata1, GDB_REGNO_TDATA1) != ERROR_OK)
1855  return ERROR_FAIL;
1856  int type = get_field(tdata1, CSR_TDATA1_TYPE(riscv_xlen(target)));
1857 
1858  uint64_t hit_mask = 0;
1859  switch (type) {
1861  /* Doesn't support hit bit. */
1862  break;
1864  hit_mask = CSR_MCONTROL_HIT;
1865  *need_single_step = true;
1866  break;
1869  if (r->tinfo_version == CSR_TINFO_VERSION_0) {
1870  *need_single_step = true;
1871  } else if (r->tinfo_version == RISCV_TINFO_VERSION_UNKNOWN
1872  || r->tinfo_version == CSR_TINFO_VERSION_1) {
1874  tdata1, hit_mask);
1875  if (hits_status == M6_HIT_ERROR)
1876  return ERROR_FAIL;
1877  if (hits_status == M6_HIT_BEFORE || hits_status == M6_HIT_NOT_SUPPORTED)
1878  *need_single_step = true;
1879  }
1880  break;
1882  hit_mask = CSR_ICOUNT_HIT;
1883  break;
1885  hit_mask = CSR_ITRIGGER_HIT(riscv_xlen(target));
1886  break;
1888  hit_mask = CSR_ETRIGGER_HIT(riscv_xlen(target));
1889  break;
1890  default:
1891  LOG_TARGET_DEBUG(target, "Trigger %u has unknown type %d", i, type);
1892  continue;
1893  }
1894 
1895  /* FIXME: this logic needs to be changed to ignore triggers that are not
1896  * the last one in the chain. */
1897  if (tdata1 & hit_mask) {
1898  LOG_TARGET_DEBUG(target, "Trigger %u (unique_id=%" PRIi64
1899  ") has hit bit set. (need_single_step=%s)",
1900  i, r->trigger_unique_id[i], (*need_single_step) ? "yes" : "no");
1901  if (riscv_reg_set(target, GDB_REGNO_TDATA1, tdata1 & ~hit_mask) != ERROR_OK)
1902  return ERROR_FAIL;
1903 
1904  *unique_id = r->trigger_unique_id[i];
1905  break;
1906  }
1907  }
1908 
1909  if (riscv_reg_set(target, GDB_REGNO_TSELECT, tselect) != ERROR_OK)
1910  return ERROR_FAIL;
1911 
1912  return ERROR_OK;
1913 }
1914 
1919 // c.lwsp rd_n0 c_uimm8sphi c_uimm8splo - offset[5] offset[4:2|7:6]
1920 static uint16_t get_offset_clwsp(riscv_insn_t instruction)
1921 {
1922  uint16_t offset_4to2and7to6_bits =
1923  get_field32(instruction, INSN_FIELD_C_UIMM8SPLO);
1924  uint16_t offset_4to2_bits = offset_4to2and7to6_bits >> 2;
1925  uint16_t offset_7to6_bits = offset_4to2and7to6_bits & 0x3;
1926  uint16_t offset_5_bit = get_field32(instruction, INSN_FIELD_C_UIMM8SPHI);
1927  return (offset_4to2_bits << 2) + (offset_5_bit << 5)
1928  + (offset_7to6_bits << 6);
1929 }
1930 
1931 // c.ldsp rd_n0 c_uimm9sphi c_uimm9splo - offset[5] offset[4:3|8:6]
1932 static uint16_t get_offset_cldsp(riscv_insn_t instruction)
1933 {
1934  uint16_t offset_4to3and8to6_bits =
1935  get_field32(instruction, INSN_FIELD_C_UIMM9SPLO);
1936  uint16_t offset_4to3_bits = offset_4to3and8to6_bits >> 3;
1937  uint16_t offset_8to6_bits = offset_4to3and8to6_bits & 0x7;
1938  uint16_t offset_5_bit = get_field32(instruction, INSN_FIELD_C_UIMM9SPHI);
1939  return (offset_4to3_bits << 3) + (offset_5_bit << 5)
1940  + (offset_8to6_bits << 6);
1941 }
1942 
1943 // c.swsp c_rs2 c_uimm8sp_s - offset[5:2|7:6]
1944 static uint16_t get_offset_cswsp(riscv_insn_t instruction)
1945 {
1946  uint16_t offset_5to2and7to6_bits =
1947  get_field32(instruction, INSN_FIELD_C_UIMM8SP_S);
1948  uint16_t offset_5to2_bits = offset_5to2and7to6_bits >> 2;
1949  uint16_t offset_7to6_bits = offset_5to2and7to6_bits & 0x3;
1950  return (offset_5to2_bits << 2) + (offset_7to6_bits << 6);
1951 }
1952 
1953 // c.sdsp c_rs2 c_uimm9sp_s - offset[5:3|8:6]
1954 static uint16_t get_offset_csdsp(riscv_insn_t instruction)
1955 {
1956  uint16_t offset_5to3and8to6_bits =
1957  get_field32(instruction, INSN_FIELD_C_UIMM9SP_S);
1958  uint16_t offset_5to3_bits = offset_5to3and8to6_bits >> 3;
1959  uint16_t offset_8to6_bits = offset_5to3and8to6_bits & 0x7;
1960  return (offset_5to3_bits << 3) + (offset_8to6_bits << 6);
1961 }
1962 
1963 // c.lw rd_p rs1_p c_uimm7lo c_uimm7hi - offset[2|6] offset[5:3]
1964 static uint16_t get_offset_clw(riscv_insn_t instruction)
1965 {
1966  uint16_t offset_2and6_bits = get_field32(instruction, INSN_FIELD_C_UIMM7LO);
1967  uint16_t offset_2_bit = offset_2and6_bits >> 1;
1968  uint16_t offset_6_bit = offset_2and6_bits & 0x1;
1969  uint16_t offset_5to3_bits = get_field32(instruction, INSN_FIELD_C_UIMM7HI);
1970  return (offset_2_bit << 2) + (offset_5to3_bits << 3) + (offset_6_bit << 6);
1971 }
1972 
1973 // c.ld rd_p rs1_p c_uimm8lo c_uimm8hi - offset[7:6] offset[5:3]
1974 static uint16_t get_offset_cld(riscv_insn_t instruction)
1975 {
1976  uint16_t offset_7to6_bits = get_field32(instruction, INSN_FIELD_C_UIMM8LO);
1977  uint16_t offset_5to3_bits = get_field32(instruction, INSN_FIELD_C_UIMM8HI);
1978  return (offset_5to3_bits << 3) + (offset_7to6_bits << 6);
1979 }
1980 
1981 // c.lq rd_p rs1_p c_uimm9lo c_uimm9hi - offset[7:6] offset[5|4|8]
1982 static uint16_t get_offset_clq(riscv_insn_t instruction)
1983 {
1984  uint16_t offset_7to6_bits = get_field32(instruction, INSN_FIELD_C_UIMM9LO);
1985  uint16_t offset_5to4and8_bits =
1986  get_field32(instruction, INSN_FIELD_C_UIMM9HI);
1987  uint16_t offset_5to4_bits = offset_5to4and8_bits >> 1;
1988  uint16_t offset_8_bit = offset_5to4and8_bits & 0x1;
1989  return (offset_5to4_bits << 4) + (offset_7to6_bits << 6)
1990  + (offset_8_bit << 8);
1991 }
1992 
1993 // c.lqsp rd_n0 c_uimm10sphi c_uimm10splo - offset[5] offset[4|9:6]
1994 static uint16_t get_offset_clqsp(riscv_insn_t instruction)
1995 {
1996  uint16_t offset_4and9to6_bits =
1997  get_field32(instruction, INSN_FIELD_C_UIMM10SPLO);
1998  uint16_t offset_4_bit = offset_4and9to6_bits >> 4;
1999  uint16_t offset_9to6_bits = offset_4and9to6_bits & 0xf;
2000  uint16_t offset_5_bit = get_field32(instruction, INSN_FIELD_C_UIMM10SPHI);
2001  return (offset_4_bit << 4) + (offset_5_bit << 5) + (offset_9to6_bits << 6);
2002 }
2003 
2004 // c.sqsp c_rs2 c_uimm10sp_s - offset[5:4|9:6]
2005 static uint16_t get_offset_csqsp(riscv_insn_t instruction)
2006 {
2007  uint16_t offset_5to4and9to6_bits =
2008  get_field32(instruction, INSN_FIELD_C_UIMM10SP_S);
2009  uint16_t offset_5to4_biits = offset_5to4and9to6_bits >> 4;
2010  uint16_t offset_9to6_bits = offset_5to4and9to6_bits & 0xf;
2011  return (offset_5to4_biits << 4) + (offset_9to6_bits << 6);
2012 }
2013 
2020 static uint32_t get_rs1_c(riscv_insn_t instruction)
2021 {
2022  return GDB_REGNO_S0 + get_field32(instruction, INSN_FIELD_C_SREG1);
2023 }
2024 
2025 static uint32_t get_opcode(const riscv_insn_t instruction)
2026 {
2027  // opcode is first 7 bits of the instruction
2028  uint32_t opcode = instruction & INSN_FIELD_OPCODE;
2029  if ((instruction & 0x03) < 0x03) { // opcode size RVC
2030  // RVC MASK_C = 0xe003 for load/store instructions
2031  opcode = instruction & MASK_C_LD;
2032  }
2033  return opcode;
2034 }
2035 
2037  const riscv_insn_t instruction, int *regid)
2038 {
2039  uint32_t opcode = get_opcode(instruction);
2040  int rs;
2041 
2042  switch (opcode) {
2043  case MATCH_LB:
2044  case MATCH_FLH & ~INSN_FIELD_FUNCT3:
2045  case MATCH_SB:
2046  case MATCH_FSH & ~INSN_FIELD_FUNCT3:
2047  rs = get_field32(instruction, INSN_FIELD_RS1);
2048  break;
2049 
2050  case MATCH_C_LWSP:
2051  case MATCH_C_LDSP: // if xlen >= 64 or MATCH_C_FLWSP:
2052  case MATCH_C_FLDSP: // or MATCH_C_LQSP if xlen == 128
2053  case MATCH_C_SWSP:
2054  case MATCH_C_SDSP: // if xlen >= 64 or MATCH_C_FSWSP:
2055  case MATCH_C_FSDSP: // or MATCH_C_SQSP if xlen == 128
2056  rs = GDB_REGNO_SP;
2057  break;
2058 
2059  case MATCH_C_LW:
2060  case MATCH_C_FLW: // or MATCH_C_LD if xlen >= 64
2061  case MATCH_C_FLD: // or MATCH_C_LQ if xlen == 128
2062  case MATCH_C_SW:
2063  case MATCH_C_FSW: // or MATCH_C_SD if xlen >= 64
2064  case MATCH_C_FSD: // or MATCH_C_SQ if xlen == 128
2065  rs = get_rs1_c(instruction);
2066  break;
2067 
2068  default:
2069  LOG_TARGET_DEBUG(target, "0x%" PRIx32 " is not a RV32I or \"C\" load or"
2070  " store", instruction);
2071  return ERROR_FAIL;
2072  }
2073  *regid = rs;
2074  return ERROR_OK;
2075 }
2076 
2078  const riscv_insn_t instruction, int16_t *memoffset)
2079 {
2080  uint32_t opcode = get_opcode(instruction);
2081  int16_t offset = 0;
2082 
2083  switch (opcode) {
2084  case MATCH_LB:
2085  case MATCH_FLH & ~INSN_FIELD_FUNCT3:
2086  case MATCH_SB:
2087  case MATCH_FSH & ~INSN_FIELD_FUNCT3:
2088  if (opcode == MATCH_SB || opcode == (MATCH_FSH & ~INSN_FIELD_FUNCT3)) {
2089  offset = get_field32(instruction, INSN_FIELD_IMM12LO) |
2090  (get_field32(instruction, INSN_FIELD_IMM12HI) << 5);
2091  } else if (opcode == MATCH_LB ||
2092  opcode == (MATCH_FLH & ~INSN_FIELD_FUNCT3)) {
2093  offset = get_field32(instruction, INSN_FIELD_IMM12);
2094  } else {
2095  assert(false);
2096  }
2097  /* sign extend 12-bit imm to 16-bits */
2098  if (offset & (1 << 11))
2099  offset |= 0xf000;
2100  break;
2101 
2102  case MATCH_C_LWSP:
2103  offset = get_offset_clwsp(instruction);
2104  break;
2105 
2106  case MATCH_C_LDSP: // if xlen >= 64 or MATCH_C_FLWSP:
2107  if (riscv_xlen(target) > 32) { // MATCH_C_LDSP
2108  offset = get_offset_cldsp(instruction);
2109  } else { // MATCH_C_FLWSP
2110  offset = get_offset_clwsp(instruction);
2111  }
2112  break;
2113 
2114  case MATCH_C_FLDSP: // or MATCH_C_LQSP if xlen == 128
2115  if (riscv_xlen(target) == 128) { // MATCH_C_LQSP
2116  offset = get_offset_clqsp(instruction);
2117  } else { // MATCH_C_FLDSP
2118  offset = get_offset_cldsp(instruction);
2119  }
2120  break;
2121 
2122  case MATCH_C_SWSP:
2123  offset = get_offset_cswsp(instruction);
2124  break;
2125 
2126  case MATCH_C_SDSP: // if xlen >= 64 or MATCH_C_FSWSP:
2127  if (riscv_xlen(target) > 32) { // MATCH_C_SDSP
2128  offset = get_offset_csdsp(instruction);
2129  } else { // MATCH_C_FSWSP
2130  offset = get_offset_cswsp(instruction);
2131  }
2132  break;
2133 
2134  case MATCH_C_FSDSP: // or MATCH_C_SQSP if xlen == 128
2135  if (riscv_xlen(target) == 128) { // MATCH_C_SQSP
2136  offset = get_offset_csqsp(instruction);
2137  } else { // MATCH_C_FSDSP
2138  offset = get_offset_csdsp(instruction); // same as C.SDSP
2139  }
2140  break;
2141 
2142  case MATCH_C_LW:
2143  offset = get_offset_clw(instruction);
2144  break;
2145 
2146  case MATCH_C_FLW: // or MATCH_C_LD if xlen >= 64
2147  if (riscv_xlen(target) > 32) { // MATCH_C_LD
2148  offset = get_offset_cld(instruction);
2149  } else { // MATCH_C_FLW
2150  offset = get_offset_clw(instruction); // same as C.FLW
2151  }
2152  break;
2153 
2154  case MATCH_C_FLD: // or MATCH_C_LQ if xlen == 128
2155  if (riscv_xlen(target) == 128) { // MATCH_C_LQ
2156  offset = get_offset_clq(instruction);
2157  } else { // MATCH_C_FLD
2158  offset = get_offset_cld(instruction); // same as C.LD
2159  }
2160  break;
2161 
2162  case MATCH_C_SW:
2163  offset = get_offset_clw(instruction); // same as C.LW
2164  break;
2165 
2166  case MATCH_C_FSW: // or MATCH_C_SD if xlen >= 64
2167  if (riscv_xlen(target) > 32) { // MATCH_C_SD
2168  offset = get_offset_cld(instruction); // same as C.LD
2169  } else { // MATCH_C_FSW
2170  offset = get_offset_clw(instruction); // same as C.LW
2171  }
2172  break;
2173 
2174  case MATCH_C_FSD: // or MATCH_C_SQ if xlen == 128
2175  if (riscv_xlen(target) == 128) { // MATCH_C_SQ
2176  offset = get_offset_clq(instruction); // same as C.LQ
2177  } else { // MATCH_C_FSD
2178  offset = get_offset_cld(instruction); // same as C.LD
2179  }
2180  break;
2181 
2182  default:
2183  LOG_TARGET_DEBUG(target, "0x%" PRIx32 " is not a RV32I or \"C\" load or"
2184  " store", instruction);
2185  return ERROR_FAIL;
2186  }
2187  *memoffset = offset;
2188  return ERROR_OK;
2189 }
2190 
2191 static int verify_loadstore(struct target *target,
2192  const riscv_insn_t instruction, bool *is_read)
2193 {
2194  uint32_t opcode = get_opcode(instruction);
2195  bool misa_f = riscv_supports_extension(target, 'F');
2196  bool misa_d = riscv_supports_extension(target, 'D');
2197  enum watchpoint_rw rw;
2198 
2199  switch (opcode) {
2200  case MATCH_LB:
2201  case MATCH_FLH & ~INSN_FIELD_FUNCT3:
2202  rw = WPT_READ;
2203  break;
2204 
2205  case MATCH_SB:
2206  case MATCH_FSH & ~INSN_FIELD_FUNCT3:
2207  rw = WPT_WRITE;
2208  break;
2209 
2210  case MATCH_C_LWSP:
2211  if (get_field32(instruction, INSN_FIELD_RD) == 0) {
2213  "The code points with rd = x0 are reserved for C.LWSP");
2214  return ERROR_FAIL;
2215  }
2216  rw = WPT_READ;
2217  break;
2218 
2219  case MATCH_C_LDSP: // if xlen >= 64 or MATCH_C_FLWSP:
2220  if (riscv_xlen(target) > 32) { // MATCH_C_LDSP
2221  if (get_field32(instruction, INSN_FIELD_RD) == 0) {
2223  "The code points with rd = x0 are reserved for C.LDSP");
2224  return ERROR_FAIL;
2225  }
2226  } else { // MATCH_C_FLWSP
2227  if (!misa_f) {
2228  LOG_TARGET_DEBUG(target, "Matched C.FLWSP but target doesn\'t "
2229  "have the \"F\" extension");
2230  return ERROR_FAIL;
2231  }
2232  }
2233  rw = WPT_READ;
2234  break;
2235 
2236  case MATCH_C_FLDSP: // or MATCH_C_LQSP if xlen == 128
2237  if (riscv_xlen(target) == 128) { // MATCH_C_LQSP
2238  if (get_field32(instruction, INSN_FIELD_RD) == 0) {
2240  "The code points with rd = x0 are reserved for C.LQSP");
2241  return ERROR_FAIL;
2242  }
2243  } else { // MATCH_C_FLDSP
2244  if (!misa_d) {
2245  LOG_TARGET_DEBUG(target, "Matched C.FLDSP but target doesn\'t "
2246  "have the \"D\" extension");
2247  return ERROR_FAIL;
2248  }
2249  }
2250  rw = WPT_READ;
2251  break;
2252 
2253  case MATCH_C_SWSP:
2254  rw = WPT_WRITE;
2255  break;
2256 
2257  case MATCH_C_SDSP: // if xlen >= 64 or MATCH_C_FSWSP:
2258  if (riscv_xlen(target) == 32) { // MATCH_C_FSWSP
2259  if (!misa_f) {
2260  LOG_TARGET_DEBUG(target, "Matched C.FSWSP but target doesn\'t "
2261  "have the \"F\" extension");
2262  return ERROR_FAIL;
2263  }
2264  }
2265  rw = WPT_WRITE;
2266  break;
2267 
2268  case MATCH_C_FSDSP: // or MATCH_C_SQSP if xlen == 128
2269  if (riscv_xlen(target) != 128) { // MATCH_C_SQSP
2270  if (!misa_d) {
2271  LOG_TARGET_DEBUG(target, "Matched C.FSDSP but target doesn\'t "
2272  "have the \"D\" extension");
2273  return ERROR_FAIL;
2274  }
2275  }
2276  rw = WPT_WRITE;
2277  break;
2278 
2279  case MATCH_C_LW:
2280  rw = WPT_READ;
2281  break;
2282 
2283  case MATCH_C_FLW: // or MATCH_C_LD if xlen >= 64
2284  if (riscv_xlen(target) == 32) { // MATCH_C_FLW
2285  if (!misa_f) {
2286  LOG_TARGET_DEBUG(target, "Matched C.FLW but target doesn\'t "
2287  "have the \"F\" extension");
2288  return ERROR_FAIL;
2289  }
2290  }
2291  rw = WPT_READ;
2292  break;
2293 
2294  case MATCH_C_FLD: // or MATCH_C_LQ if xlen == 128
2295  if (riscv_xlen(target) != 128) { // MATCH_C_FLD
2296  if (!misa_d) {
2297  LOG_TARGET_DEBUG(target, "Matched C.FLD but target doesn\'t "
2298  "have the \"D\" extension");
2299  return ERROR_FAIL;
2300  }
2301  }
2302  rw = WPT_READ;
2303  break;
2304 
2305  case MATCH_C_SW:
2306  rw = WPT_WRITE;
2307  break;
2308 
2309  case MATCH_C_FSW: // or MATCH_C_SD if xlen >= 64
2310  if (riscv_xlen(target) == 32) { // MATCH_C_FSW
2311  if (!misa_f) {
2312  LOG_TARGET_DEBUG(target, "Matched C.FSW but target doesn\'t "
2313  "have the \"F\" extension");
2314  return ERROR_FAIL;
2315  }
2316  }
2317  rw = WPT_WRITE;
2318  break;
2319 
2320  case MATCH_C_FSD: // or MATCH_C_SQ if xlen == 128
2321  if (riscv_xlen(target) != 128) { // MATCH_C_FSD
2322  if (!misa_d) {
2323  LOG_TARGET_DEBUG(target, "Matched C.FSD but target doesn\'t "
2324  "have the \"D\" extension");
2325  return ERROR_FAIL;
2326  }
2327  }
2328  rw = WPT_WRITE;
2329  break;
2330 
2331  default:
2332  LOG_TARGET_DEBUG(target, "0x%" PRIx32 " is not a RV32I or \"C\" load or"
2333  " store", instruction);
2334  return ERROR_FAIL;
2335  }
2336 
2337  if (rw == WPT_WRITE) {
2338  *is_read = false;
2339  LOG_TARGET_DEBUG(target, "0x%" PRIx32 " is store instruction",
2340  instruction);
2341  } else {
2342  *is_read = true;
2343  LOG_TARGET_DEBUG(target, "0x%" PRIx32 " is load instruction",
2344  instruction);
2345  }
2346  return ERROR_OK;
2347 }
2348 
2349 /* Sets *hit_watchpoint to the first watchpoint identified as causing the
2350  * current halt.
2351  *
2352  * The GDB server uses this information to tell GDB what data address has
2353  * been hit, which enables GDB to print the hit variable along with its old
2354  * and new value. */
2355 static int riscv_hit_watchpoint(struct target *target, struct watchpoint **hit_watchpoint)
2356 {
2357  RISCV_INFO(r);
2358 
2359  LOG_TARGET_DEBUG(target, "Hit Watchpoint");
2360 
2361  /* If we identified which trigger caused the halt earlier, then just use
2362  * that. */
2363  for (struct watchpoint *wp = target->watchpoints; wp; wp = wp->next) {
2364  if (wp->unique_id == r->trigger_hit) {
2365  *hit_watchpoint = wp;
2366  return ERROR_OK;
2367  }
2368  }
2369 
2370  riscv_reg_t dpc;
2371  if (riscv_reg_get(target, &dpc, GDB_REGNO_DPC) != ERROR_OK)
2372  return ERROR_FAIL;
2373  const uint8_t length = 4;
2374  LOG_TARGET_DEBUG(target, "dpc is 0x%" PRIx64, dpc);
2375 
2376  /* fetch the instruction at dpc */
2377  uint8_t buffer[length];
2378  if (target_read_buffer(target, dpc, length, buffer) != ERROR_OK) {
2379  LOG_TARGET_ERROR(target, "Failed to read instruction at dpc 0x%" PRIx64,
2380  dpc);
2381  return ERROR_FAIL;
2382  }
2383 
2384  riscv_insn_t instruction = 0;
2385 
2386  for (int i = 0; i < length; i++) {
2387  LOG_TARGET_DEBUG(target, "Next byte is %x", buffer[i]);
2388  instruction += (buffer[i] << 8 * i);
2389  }
2390  LOG_TARGET_DEBUG(target, "Full instruction is %x", instruction);
2391 
2392  int rs;
2393  target_addr_t mem_addr;
2394  int16_t memoffset;
2395 
2396  if (get_loadstore_membase_regno(target, instruction, &rs) != ERROR_OK)
2397  return ERROR_FAIL;
2398  if (riscv_reg_get(target, &mem_addr, rs) != ERROR_OK)
2399  return ERROR_FAIL;
2400  if (get_loadstore_memoffset(target, instruction, &memoffset) != ERROR_OK)
2401  return ERROR_FAIL;
2402 
2403  mem_addr += memoffset;
2404  bool is_load;
2405 
2406  if (verify_loadstore(target, instruction, &is_load) != ERROR_OK)
2407  return ERROR_FAIL;
2408 
2409  struct watchpoint *wp = target->watchpoints;
2410  while (wp) {
2411  /* TODO support mask and check read/write/access */
2412  /* TODO check for intersection of the access range and watchpoint range
2413  Recommended matching:
2414  if (intersects(mem_addr, mem_addr + ref_size, wp->address, wp->address + wp->length))
2415  */
2416  if (mem_addr >= wp->address &&
2417  mem_addr < (wp->address + wp->length)) {
2418  *hit_watchpoint = wp;
2419  LOG_TARGET_DEBUG(target, "WP hit found: %s 0x%" TARGET_PRIxADDR
2420  " covered by %s wp at address 0x%" TARGET_PRIxADDR,
2421  is_load ? "Load from" : "Store to", mem_addr,
2422  (wp->rw == WPT_READ ?
2423  "read" : (wp->rw == WPT_WRITE ? "write" : "access")),
2424  wp->address);
2425  return ERROR_OK;
2426  }
2427  wp = wp->next;
2428  }
2429 
2430  /* No match found - either we hit a watchpoint caused by an instruction that
2431  * this function does not yet disassemble, or we hit a breakpoint.
2432  *
2433  * OpenOCD will behave as if this function had never been implemented i.e.
2434  * report the halt to GDB with no address information. */
2435  LOG_TARGET_DEBUG(target, "No watchpoint found that would cover %s 0x%"
2436  TARGET_PRIxADDR, is_load ? "load from" : "store to", mem_addr);
2437  return ERROR_FAIL;
2438 }
2439 
2440 static int oldriscv_step(struct target *target, bool current, uint32_t address,
2441  bool handle_breakpoints)
2442 {
2443  struct target_type *tt = get_target_type(target);
2444  if (!tt)
2445  return ERROR_FAIL;
2446  return tt->step(target, current, address, handle_breakpoints);
2447 }
2448 
2449 static int riscv_openocd_step_impl(struct target *target, bool current,
2450  target_addr_t address, bool handle_breakpoints, int handle_callbacks);
2451 
2452 static int old_or_new_riscv_step_impl(struct target *target, bool current,
2453  target_addr_t address, bool handle_breakpoints, int handle_callbacks)
2454 {
2455  RISCV_INFO(r);
2456  LOG_TARGET_DEBUG(target, "handle_breakpoints=%s",
2457  handle_breakpoints ? "true" : "false");
2458  if (!r->get_hart_state)
2459  return oldriscv_step(target, current, address, handle_breakpoints);
2460  else
2461  return riscv_openocd_step_impl(target, current, address, handle_breakpoints,
2462  handle_callbacks);
2463 }
2464 
2465 static int old_or_new_riscv_step(struct target *target, bool current,
2466  target_addr_t address, bool handle_breakpoints)
2467 {
2468  return old_or_new_riscv_step_impl(target, current, address,
2469  handle_breakpoints, true /* handle callbacks*/);
2470 }
2471 
2472 static int riscv_examine(struct target *target)
2473 {
2474  LOG_TARGET_DEBUG(target, "Starting examination");
2475  if (target_was_examined(target)) {
2476  LOG_TARGET_DEBUG(target, "Target was already examined.");
2477  return ERROR_OK;
2478  }
2479 
2480  /* Don't need to select dbus, since the first thing we do is read dtmcontrol. */
2481 
2482  RISCV_INFO(info);
2483  uint32_t dtmcontrol;
2484  if (dtmcs_scan(target->tap, 0, &dtmcontrol) != ERROR_OK || dtmcontrol == 0) {
2485  LOG_TARGET_ERROR(target, "Could not read dtmcontrol. Check JTAG connectivity/board power.");
2486  return ERROR_FAIL;
2487  }
2488  LOG_TARGET_DEBUG(target, "dtmcontrol=0x%x", dtmcontrol);
2489  info->dtm_version = get_field(dtmcontrol, DTMCONTROL_VERSION);
2490  LOG_TARGET_DEBUG(target, "version=0x%x", info->dtm_version);
2491 
2492  int examine_status = ERROR_FAIL;
2493  struct target_type *tt = get_target_type(target);
2494  if (!tt)
2495  goto examine_fail;
2496 
2497  examine_status = tt->init_target(info->cmd_ctx, target);
2498  if (examine_status != ERROR_OK)
2499  goto examine_fail;
2500 
2501  examine_status = tt->examine(target);
2502  if (examine_status != ERROR_OK)
2503  goto examine_fail;
2504 
2505  return ERROR_OK;
2506 
2507 examine_fail:
2508  info->dtm_version = DTM_DTMCS_VERSION_UNKNOWN;
2509  return examine_status;
2510 }
2511 
2512 static int oldriscv_poll(struct target *target)
2513 {
2514  struct target_type *tt = get_target_type(target);
2515  if (!tt)
2516  return ERROR_FAIL;
2517  return tt->poll(target);
2518 }
2519 
2521 {
2522  RISCV_INFO(r);
2523  if (!r->get_hart_state)
2524  return oldriscv_poll(target);
2525  else
2526  return riscv_openocd_poll(target);
2527 }
2528 
2529 static enum target_debug_reason
2531 {
2532  /* TODO: if we detect that etrigger/itrigger/icount is set, we should
2533  * just report DBG_REASON_UNKNOWN, since we can't disctiguish these
2534  * triggers from BP/WP or from other triggers of such type. However,
2535  * currently this renders existing testsuite as failing. We need to
2536  * fix the testsuite first
2537  */
2538  // TODO: the code below does not handle context-aware trigger types
2539  for (const struct breakpoint *bp = target->breakpoints; bp; bp = bp->next) {
2540  // TODO: investigate if we need to handle bp length
2541  if (bp->type == BKPT_HARD && bp->is_set && bp->address == dpc) {
2542  // FIXME: bp->linked_brp is uninitialized
2543  if (bp->asid) {
2545  "can't derive debug reason for context-aware breakpoint: "
2546  "unique_id = %" PRIu32 ", address = %" TARGET_PRIxADDR
2547  ", asid = %" PRIx32 ", linked = %d",
2548  bp->unique_id, bp->address, bp->asid, bp->linked_brp);
2549  return DBG_REASON_UNDEFINED;
2550  }
2551  return DBG_REASON_BREAKPOINT;
2552  }
2553  }
2554  return DBG_REASON_WATCHPOINT;
2555 }
2559 static int set_debug_reason(struct target *target, enum riscv_halt_reason halt_reason)
2560 {
2561  RISCV_INFO(r);
2562  r->trigger_hit = -1;
2563  r->need_single_step = false;
2564  switch (halt_reason) {
2565  case RISCV_HALT_EBREAK:
2567  break;
2568  case RISCV_HALT_TRIGGER:
2570  if (riscv_trigger_detect_hit_bits(target, &r->trigger_hit,
2571  &r->need_single_step) != ERROR_OK)
2572  return ERROR_FAIL;
2573  // FIXME: handle multiple hit bits
2574  if (r->trigger_hit != RISCV_TRIGGER_HIT_NOT_FOUND) {
2575  /* We scan for breakpoints first. If no breakpoints are found we still
2576  * assume that debug reason is DBG_REASON_BREAKPOINT, unless
2577  * there is a watchpoint match - This is to take
2578  * ETrigger/ITrigger/ICount into account
2579  */
2581  "Active hit bit is detected, trying to find trigger owner.");
2582  for (struct breakpoint *bp = target->breakpoints; bp; bp = bp->next) {
2583  if (bp->unique_id == r->trigger_hit) {
2586  "Breakpoint with unique_id = %" PRIu32 " owns the trigger.",
2587  bp->unique_id);
2588  }
2589  }
2591  // by default we report all triggers as breakpoints
2593  for (struct watchpoint *wp = target->watchpoints; wp; wp = wp->next) {
2594  if (wp->unique_id == r->trigger_hit) {
2597  "Watchpoint with unique_id = %" PRIu32 " owns the trigger.",
2598  wp->unique_id);
2599  }
2600  }
2601  }
2602  } else {
2604  "No trigger hit found, deriving debug reason without it.");
2605  riscv_reg_t dpc;
2606  if (riscv_reg_get(target, &dpc, GDB_REGNO_DPC) != ERROR_OK)
2607  return ERROR_FAIL;
2608  /* Here we don't have the hit bit set (likely, HW does not support it).
2609  * We are trying to guess the state. But here comes the problem:
2610  * if we have etrigger/itrigger/icount raised - we can't really
2611  * distinguish it from the breakpoint or watchpoint. There is not
2612  * much we can do here, except for checking current PC against pending
2613  * breakpoints and hope for the best)
2614  */
2616  }
2617  break;
2618  case RISCV_HALT_INTERRUPT:
2619  case RISCV_HALT_GROUP:
2621  break;
2622  case RISCV_HALT_SINGLESTEP:
2624  break;
2625  case RISCV_HALT_UNKNOWN:
2627  break;
2628  case RISCV_HALT_ERROR:
2629  return ERROR_FAIL;
2630  }
2631  LOG_TARGET_DEBUG(target, "debug_reason=%d", target->debug_reason);
2632 
2633  return ERROR_OK;
2634 }
2635 
2636 static int halt_prep(struct target *target)
2637 {
2638  RISCV_INFO(r);
2639 
2640  LOG_TARGET_DEBUG(target, "prep hart, debug_reason=%d", target->debug_reason);
2641  r->prepped = false;
2642  if (target->state == TARGET_HALTED) {
2643  LOG_TARGET_DEBUG(target, "Hart is already halted.");
2644  } else if (target->state == TARGET_UNAVAILABLE) {
2645  LOG_TARGET_DEBUG(target, "Hart is unavailable.");
2646  } else {
2647  if (r->halt_prep(target) != ERROR_OK)
2648  return ERROR_FAIL;
2649  r->prepped = true;
2650  }
2651 
2652  return ERROR_OK;
2653 }
2654 
2656 {
2657  RISCV_INFO(r);
2658 
2659  enum riscv_hart_state state;
2661  return ERROR_FAIL;
2662  if (state == RISCV_STATE_HALTED) {
2663  LOG_TARGET_DEBUG(target, "Hart is already halted.");
2664  if (target->state != TARGET_HALTED) {
2666  enum riscv_halt_reason halt_reason = riscv_halt_reason(target);
2667  if (set_debug_reason(target, halt_reason) != ERROR_OK)
2668  return ERROR_FAIL;
2669  }
2670  } else {
2671  // Safety check:
2673  LOG_TARGET_INFO(target, "BUG: Registers should not be dirty while "
2674  "the target is not halted!");
2675 
2677 
2678  if (r->halt_go(target) != ERROR_OK)
2679  return ERROR_FAIL;
2680  }
2681 
2682  return ERROR_OK;
2683 }
2684 
2685 static int halt_go(struct target *target)
2686 {
2687  RISCV_INFO(r);
2688  int result;
2689  if (!r->get_hart_state) {
2690  struct target_type *tt = get_target_type(target);
2691  if (!tt)
2692  return ERROR_FAIL;
2693  result = tt->halt(target);
2694  } else {
2695  result = riscv_halt_go_all_harts(target);
2696  }
2699 
2700  return result;
2701 }
2702 
2703 static int halt_finish(struct target *target)
2704 {
2706 }
2707 
2709 {
2710  RISCV_INFO(r);
2711 
2712  if (!r->get_hart_state) {
2713  struct target_type *tt = get_target_type(target);
2714  if (!tt)
2715  return ERROR_FAIL;
2716  return tt->halt(target);
2717  }
2718 
2719  LOG_TARGET_DEBUG(target, "halting all harts");
2720 
2721  int result = ERROR_OK;
2722  if (target->smp) {
2723  struct target_list *tlist;
2725  struct target *t = tlist->target;
2726  if (halt_prep(t) != ERROR_OK)
2727  result = ERROR_FAIL;
2728  }
2729 
2731  struct target *t = tlist->target;
2732  struct riscv_info *i = riscv_info(t);
2733  if (i->prepped) {
2734  if (halt_go(t) != ERROR_OK)
2735  result = ERROR_FAIL;
2736  }
2737  }
2738 
2740  struct target *t = tlist->target;
2741  if (halt_finish(t) != ERROR_OK)
2742  return ERROR_FAIL;
2743  }
2744 
2745  } else {
2746  if (halt_prep(target) != ERROR_OK)
2747  result = ERROR_FAIL;
2748  if (halt_go(target) != ERROR_OK)
2749  result = ERROR_FAIL;
2750  if (halt_finish(target) != ERROR_OK)
2751  return ERROR_FAIL;
2752  }
2753 
2754  return result;
2755 }
2756 
2757 static int riscv_assert_reset(struct target *target)
2758 {
2759  LOG_TARGET_DEBUG(target, "");
2760  struct target_type *tt = get_target_type(target);
2761  if (!tt)
2762  return ERROR_FAIL;
2763 
2765  LOG_TARGET_INFO(target, "Discarding values of dirty registers.");
2766 
2768  return tt->assert_reset(target);
2769 }
2770 
2772 {
2773  LOG_TARGET_DEBUG(target, "");
2774  struct target_type *tt = get_target_type(target);
2775  if (!tt)
2776  return ERROR_FAIL;
2777  return tt->deassert_reset(target);
2778 }
2779 
2780 /* "wp_is_set" array must have at least "r->trigger_count" items. */
2781 static int disable_watchpoints(struct target *target, bool *wp_is_set)
2782 {
2783  RISCV_INFO(r);
2784  LOG_TARGET_DEBUG(target, "Disabling triggers.");
2785 
2786  /* TODO: The algorithm is flawed and may result in a situation described in
2787  * https://github.com/riscv-collab/riscv-openocd/issues/1108
2788  */
2789  memset(wp_is_set, false, r->trigger_count);
2791  int i = 0;
2792  while (watchpoint) {
2793  LOG_TARGET_DEBUG(target, "Watchpoint %" PRIu32 ": set=%s",
2795  wp_is_set[i] ? "true" : "false");
2796  wp_is_set[i] = watchpoint->is_set;
2797  if (watchpoint->is_set) {
2799  return ERROR_FAIL;
2800  }
2802  i++;
2803  }
2804 
2805  return ERROR_OK;
2806 }
2807 
2808 static int enable_watchpoints(struct target *target, bool *wp_is_set)
2809 {
2811  int i = 0;
2812  while (watchpoint) {
2813  LOG_TARGET_DEBUG(target, "Watchpoint %" PRIu32
2814  ": %s to be re-enabled.", watchpoint->unique_id,
2815  wp_is_set[i] ? "needs " : "does not need");
2816  if (wp_is_set[i]) {
2818  return ERROR_FAIL;
2819  }
2821  i++;
2822  }
2823 
2824  return ERROR_OK;
2825 }
2826 
2830 static int resume_prep(struct target *target, bool current,
2831  target_addr_t address, bool handle_breakpoints, bool debug_execution)
2832 {
2833  assert(target->state == TARGET_HALTED);
2834  RISCV_INFO(r);
2835 
2836  if (!current && riscv_reg_set(target, GDB_REGNO_PC, address) != ERROR_OK)
2837  return ERROR_FAIL;
2838 
2839  if (handle_breakpoints) {
2840  /* To be able to run off a trigger, we perform a step operation and then
2841  * resume. If handle_breakpoints is true then step temporarily disables
2842  * pending breakpoints so we can safely perform the step.
2843  *
2844  * Two cases where single step is needed before resuming:
2845  * 1. ebreak used in software breakpoint;
2846  * 2. a trigger that is taken just before the instruction that triggered it is retired.
2847  */
2850  && r->need_single_step)) {
2851  if (old_or_new_riscv_step_impl(target, current, address, handle_breakpoints,
2852  false /* callbacks are not called */) != ERROR_OK)
2853  return ERROR_FAIL;
2854  }
2855  }
2856 
2857  if (r->get_hart_state) {
2858  if (r->resume_prep(target) != ERROR_OK)
2859  return ERROR_FAIL;
2860  }
2861 
2862  LOG_TARGET_DEBUG(target, "Mark as prepped.");
2863  r->prepped = true;
2864 
2865  return ERROR_OK;
2866 }
2867 
2872 static int resume_go(struct target *target, bool current,
2873  target_addr_t address, bool handle_breakpoints, bool debug_execution)
2874 {
2875  assert(target->state == TARGET_HALTED);
2876  RISCV_INFO(r);
2877  int result;
2878  if (!r->get_hart_state) {
2879  struct target_type *tt = get_target_type(target);
2880  if (!tt)
2881  return ERROR_FAIL;
2882  result = tt->resume(target, current, address, handle_breakpoints,
2883  debug_execution);
2884  } else {
2886  }
2887 
2888  return result;
2889 }
2890 
2891 static int resume_finish(struct target *target, bool debug_execution)
2892 {
2893  assert(target->state == TARGET_HALTED);
2895  /* If this happens, it means there is a bug in the previous
2896  * register-flushing algorithm: not all registers were flushed
2897  * back to the target in preparation for the resume.*/
2899  "BUG: registers should have been flushed by this point.");
2900  }
2901 
2903 
2904  target->state = debug_execution ? TARGET_DEBUG_RUNNING : TARGET_RUNNING;
2907  debug_execution ? TARGET_EVENT_DEBUG_RESUMED : TARGET_EVENT_RESUMED);
2908 }
2909 
2914 static int riscv_resume(struct target *target,
2915  bool current,
2917  bool handle_breakpoints,
2918  bool debug_execution,
2919  bool single_hart)
2920 {
2921  int result = ERROR_OK;
2922 
2923  struct list_head *targets;
2924 
2925  OOCD_LIST_HEAD(single_target_list);
2926  struct target_list single_target_entry = {
2927  .lh = {NULL, NULL},
2928  .target = target
2929  };
2930 
2931  if (target->smp && !single_hart) {
2932  targets = target->smp_targets;
2933  } else {
2934  /* Make a list that just contains a single target, so we can
2935  * share code below. */
2936  list_add(&single_target_entry.lh, &single_target_list);
2937  targets = &single_target_list;
2938  }
2939 
2940  LOG_TARGET_DEBUG(target, "current=%s, address=0x%"
2941  TARGET_PRIxADDR ", handle_breakpoints=%s, debug_exec=%s",
2942  current ? "true" : "false",
2943  address,
2944  handle_breakpoints ? "true" : "false",
2945  debug_execution ? "true" : "false");
2946 
2947  struct target_list *tlist;
2949  struct target *t = tlist->target;
2950  LOG_TARGET_DEBUG(t, "target->state=%s", target_state_name(t));
2951  if (t->state != TARGET_HALTED)
2952  LOG_TARGET_DEBUG(t, "skipping this target: target not halted");
2953  else if (resume_prep(t, current, address, handle_breakpoints,
2954  debug_execution) != ERROR_OK)
2955  result = ERROR_FAIL;
2956  }
2957 
2959  struct target *t = tlist->target;
2960  struct riscv_info *i = riscv_info(t);
2961  if (i->prepped) {
2962  if (resume_go(t, current, address, handle_breakpoints,
2963  debug_execution) != ERROR_OK)
2964  result = ERROR_FAIL;
2965  }
2966  }
2967 
2969  struct target *t = tlist->target;
2970  if (t->state == TARGET_HALTED) {
2971  if (resume_finish(t, debug_execution) != ERROR_OK)
2972  result = ERROR_FAIL;
2973  }
2974  }
2975 
2976  return result;
2977 }
2978 
2979 static int riscv_target_resume(struct target *target, bool current,
2980  target_addr_t address, bool handle_breakpoints, bool debug_execution)
2981 {
2982  if (target->state != TARGET_HALTED) {
2983  LOG_TARGET_ERROR(target, "Not halted.");
2984  return ERROR_TARGET_NOT_HALTED;
2985  }
2986  return riscv_resume(target, current, address, handle_breakpoints,
2987  debug_execution, false);
2988 }
2989 
2990 static int riscv_effective_privilege_mode(struct target *target, int *v_mode, int *effective_mode)
2991 {
2992  riscv_reg_t priv;
2994  LOG_TARGET_ERROR(target, "Failed to read priv register.");
2995  return ERROR_FAIL;
2996  }
2997  *v_mode = get_field(priv, VIRT_PRIV_V);
2998 
2999  riscv_reg_t mstatus;
3000  if (riscv_reg_get(target, &mstatus, GDB_REGNO_MSTATUS) != ERROR_OK) {
3001  LOG_TARGET_ERROR(target, "Failed to read mstatus register.");
3002  return ERROR_FAIL;
3003  }
3004 
3005  if (get_field(mstatus, MSTATUS_MPRV))
3006  *effective_mode = get_field(mstatus, MSTATUS_MPP);
3007  else
3008  *effective_mode = get_field(priv, VIRT_PRIV_PRV);
3009 
3010  LOG_TARGET_DEBUG(target, "Effective mode=%d; v=%d", *effective_mode, *v_mode);
3011 
3012  return ERROR_OK;
3013 }
3014 
3015 static int riscv_mmu(struct target *target, bool *enabled)
3016 {
3017  *enabled = false;
3018 
3020  return ERROR_OK;
3021 
3022  /* Don't use MMU in explicit or effective M (machine) mode */
3023  riscv_reg_t priv;
3025  LOG_TARGET_ERROR(target, "Failed to read priv register.");
3026  return ERROR_FAIL;
3027  }
3028 
3029  int effective_mode;
3030  int v_mode;
3031  if (riscv_effective_privilege_mode(target, &v_mode, &effective_mode) != ERROR_OK)
3032  return ERROR_FAIL;
3033 
3034  unsigned int xlen = riscv_xlen(target);
3035 
3036  if (v_mode) {
3037  /* In VU or VS mode, MMU is considered enabled when
3038  * either hgatp or vsatp mode is not OFF */
3039  riscv_reg_t vsatp;
3040  if (riscv_reg_get(target, &vsatp, GDB_REGNO_VSATP) != ERROR_OK) {
3041  LOG_TARGET_ERROR(target, "Failed to read vsatp register; priv=0x%" PRIx64,
3042  priv);
3043  return ERROR_FAIL;
3044  }
3045  /* vsatp is identical to satp, so we can use the satp macros. */
3046  if (get_field(vsatp, RISCV_SATP_MODE(xlen)) != SATP_MODE_OFF) {
3047  LOG_TARGET_DEBUG(target, "VS-stage translation is enabled.");
3048  *enabled = true;
3049  return ERROR_OK;
3050  }
3051 
3052  riscv_reg_t hgatp;
3053  if (riscv_reg_get(target, &hgatp, GDB_REGNO_HGATP) != ERROR_OK) {
3054  LOG_TARGET_ERROR(target, "Failed to read hgatp register; priv=0x%" PRIx64,
3055  priv);
3056  return ERROR_FAIL;
3057  }
3058  if (get_field(hgatp, RISCV_HGATP_MODE(xlen)) != HGATP_MODE_OFF) {
3059  LOG_TARGET_DEBUG(target, "G-stage address translation is enabled.");
3060  *enabled = true;
3061  } else {
3062  LOG_TARGET_DEBUG(target, "No V-mode address translation enabled.");
3063  }
3064 
3065  return ERROR_OK;
3066  }
3067 
3068  /* Don't use MMU in explicit or effective M (machine) mode */
3069  if (effective_mode == PRV_M) {
3070  LOG_TARGET_DEBUG(target, "SATP/MMU ignored in Machine mode.");
3071  return ERROR_OK;
3072  }
3073 
3074  riscv_reg_t satp;
3075  if (riscv_reg_get(target, &satp, GDB_REGNO_SATP) != ERROR_OK) {
3076  LOG_TARGET_DEBUG(target, "Couldn't read SATP.");
3077  /* If we can't read SATP, then there must not be an MMU. */
3078  return ERROR_OK;
3079  }
3080 
3081  if (get_field(satp, RISCV_SATP_MODE(xlen)) == SATP_MODE_OFF) {
3082  LOG_TARGET_DEBUG(target, "MMU is disabled.");
3083  } else {
3084  LOG_TARGET_DEBUG(target, "MMU is enabled.");
3085  *enabled = true;
3086  }
3087 
3088  return ERROR_OK;
3089 }
3090 
3091 /* Translate address from virtual to physical, using info and ppn.
3092  * If extra_info is non-NULL, then translate page table accesses for the primary
3093  * translation using extra_info and extra_ppn. */
3095  const virt2phys_info_t *info, target_addr_t ppn,
3096  const virt2phys_info_t *extra_info, target_addr_t extra_ppn,
3097  target_addr_t virtual, target_addr_t *physical)
3098 {
3099  RISCV_INFO(r);
3100  unsigned int xlen = riscv_xlen(target);
3101 
3102  LOG_TARGET_DEBUG(target, "mode=%s; ppn=0x%" TARGET_PRIxADDR "; virtual=0x%" TARGET_PRIxADDR,
3103  info->name, ppn, virtual);
3104 
3105  /* verify bits xlen-1:va_bits-1 are all equal */
3106  assert(xlen >= info->va_bits);
3107  target_addr_t mask = ((target_addr_t)1 << (xlen - (info->va_bits - 1))) - 1;
3108  target_addr_t masked_msbs = (virtual >> (info->va_bits - 1)) & mask;
3109  if (masked_msbs != 0 && masked_msbs != mask) {
3110  LOG_TARGET_ERROR(target, "Virtual address 0x%" TARGET_PRIxADDR " is not sign-extended "
3111  "for %s mode.", virtual, info->name);
3112  return ERROR_FAIL;
3113  }
3114 
3115  uint64_t pte = 0;
3116  target_addr_t table_address = ppn << RISCV_PGSHIFT;
3117  int i = info->level - 1;
3118  while (i >= 0) {
3119  uint64_t vpn = virtual >> info->vpn_shift[i];
3120  vpn &= info->vpn_mask[i];
3121  target_addr_t pte_address = table_address + (vpn << info->pte_shift);
3122 
3123  if (extra_info) {
3124  /* Perform extra stage translation. */
3125  if (riscv_address_translate(target, extra_info, extra_ppn,
3126  NULL, 0, pte_address, &pte_address) != ERROR_OK)
3127  return ERROR_FAIL;
3128  }
3129 
3130  uint8_t buffer[8];
3131  assert(info->pte_shift <= 3);
3132  const struct riscv_mem_access_args args = {
3133  .address = pte_address,
3134  .read_buffer = buffer,
3135  .size = 4,
3136  .increment = 4,
3137  .count = (1 << info->pte_shift) / 4,
3138  };
3139  int retval = r->access_memory(target, args);
3140  if (retval != ERROR_OK)
3141  return ERROR_FAIL;
3142 
3143  if (info->pte_shift == 2)
3144  pte = buf_get_u32(buffer, 0, 32);
3145  else
3146  pte = buf_get_u64(buffer, 0, 64);
3147 
3148  LOG_TARGET_DEBUG(target, "i=%d; PTE @0x%" TARGET_PRIxADDR " = 0x%" PRIx64, i,
3149  pte_address, pte);
3150 
3151  if (!(pte & PTE_V) || (!(pte & PTE_R) && (pte & PTE_W))) {
3152  LOG_TARGET_ERROR(target, "invalid PTE @0x%" TARGET_PRIxADDR ": 0x%" PRIx64
3153  "; mode=%s; i=%d", pte_address, pte, info->name, i);
3154  return ERROR_FAIL;
3155  }
3156 
3157  if ((pte & PTE_R) || (pte & PTE_W) || (pte & PTE_X)) /* Found leaf PTE. */
3158  break;
3159 
3160  i--;
3161  if (i < 0)
3162  break;
3163  ppn = pte >> PTE_PPN_SHIFT;
3164  table_address = ppn << RISCV_PGSHIFT;
3165  }
3166 
3167  if (i < 0) {
3168  LOG_TARGET_ERROR(target, "Couldn't find the PTE.");
3169  return ERROR_FAIL;
3170  }
3171 
3172  /* Make sure to clear out the high bits that may be set. */
3173  *physical = virtual & (((target_addr_t)1 << info->va_bits) - 1);
3174 
3175  while (i < info->level) {
3176  ppn = pte >> info->pte_ppn_shift[i];
3177  ppn &= info->pte_ppn_mask[i];
3178  *physical &= ~(((target_addr_t)info->pa_ppn_mask[i]) <<
3179  info->pa_ppn_shift[i]);
3180  *physical |= (ppn << info->pa_ppn_shift[i]);
3181  i++;
3182  }
3183  LOG_TARGET_DEBUG(target, "mode=%s; 0x%" TARGET_PRIxADDR " -> 0x%" TARGET_PRIxADDR,
3184  info->name, virtual, *physical);
3185  return ERROR_OK;
3186 }
3187 
3188 /* Virtual to physical translation for hypervisor mode. */
3189 static int riscv_virt2phys_v(struct target *target, target_addr_t virtual, target_addr_t *physical)
3190 {
3191  riscv_reg_t vsatp;
3192  if (riscv_reg_get(target, &vsatp, GDB_REGNO_VSATP) != ERROR_OK) {
3193  LOG_TARGET_ERROR(target, "Failed to read vsatp register.");
3194  return ERROR_FAIL;
3195  }
3196  /* vsatp is identical to satp, so we can use the satp macros. */
3197  unsigned int xlen = riscv_xlen(target);
3198  int vsatp_mode = get_field(vsatp, RISCV_SATP_MODE(xlen));
3199  LOG_TARGET_DEBUG(target, "VS-stage translation mode: %d", vsatp_mode);
3200  riscv_reg_t hgatp;
3201  if (riscv_reg_get(target, &hgatp, GDB_REGNO_HGATP) != ERROR_OK) {
3202  LOG_TARGET_ERROR(target, "Failed to read hgatp register.");
3203  return ERROR_FAIL;
3204  }
3205  int hgatp_mode = get_field(hgatp, RISCV_HGATP_MODE(xlen));
3206  LOG_TARGET_DEBUG(target, "G-stage translation mode: %d", hgatp_mode);
3207 
3208  const virt2phys_info_t *vsatp_info;
3209  /* VS-stage address translation. */
3210  switch (vsatp_mode) {
3211  case SATP_MODE_SV32:
3212  vsatp_info = &sv32;
3213  break;
3214  case SATP_MODE_SV39:
3215  vsatp_info = &sv39;
3216  break;
3217  case SATP_MODE_SV48:
3218  vsatp_info = &sv48;
3219  break;
3220  case SATP_MODE_SV57:
3221  vsatp_info = &sv57;
3222  break;
3223  case SATP_MODE_OFF:
3224  vsatp_info = NULL;
3225  LOG_TARGET_DEBUG(target, "vsatp mode is %d. No VS-stage translation. (vsatp: 0x%" PRIx64 ")",
3226  vsatp_mode, vsatp);
3227  break;
3228  default:
3230  "vsatp mode %d is not supported. (vsatp: 0x%" PRIx64 ")",
3231  vsatp_mode, vsatp);
3232  return ERROR_FAIL;
3233  }
3234 
3235  const virt2phys_info_t *hgatp_info;
3236  /* G-stage address translation. */
3237  switch (hgatp_mode) {
3238  case HGATP_MODE_SV32X4:
3239  hgatp_info = &sv32x4;
3240  break;
3241  case HGATP_MODE_SV39X4:
3242  hgatp_info = &sv39x4;
3243  break;
3244  case HGATP_MODE_SV48X4:
3245  hgatp_info = &sv48x4;
3246  break;
3247  case HGATP_MODE_SV57X4:
3248  hgatp_info = &sv57x4;
3249  break;
3250  case HGATP_MODE_OFF:
3251  hgatp_info = NULL;
3252  LOG_TARGET_DEBUG(target, "hgatp mode is %d. No G-stage translation. (hgatp: 0x%" PRIx64 ")",
3253  hgatp_mode, hgatp);
3254  break;
3255  default:
3257  "hgatp mode %d is not supported. (hgatp: 0x%" PRIx64 ")",
3258  hgatp_mode, hgatp);
3259  return ERROR_FAIL;
3260  }
3261 
3262  /* For any virtual memory access, the original virtual address is
3263  * converted in the first stage by VS-level address translation,
3264  * as controlled by the vsatp register, into a guest physical
3265  * address. */
3266  target_addr_t guest_physical;
3267  if (vsatp_info) {
3268  /* When V=1, memory accesses that would normally bypass
3269  * address translation are subject to G- stage address
3270  * translation alone. This includes memory accesses made
3271  * in support of VS-stage address translation, such as
3272  * reads and writes of VS-level page tables. */
3273 
3275  vsatp_info, get_field(vsatp, RISCV_SATP_PPN(xlen)),
3276  hgatp_info, get_field(hgatp, RISCV_SATP_PPN(xlen)),
3277  virtual, &guest_physical) != ERROR_OK)
3278  return ERROR_FAIL;
3279  } else {
3280  guest_physical = virtual;
3281  }
3282 
3283  /* The guest physical address is then converted in the second
3284  * stage by guest physical address translation, as controlled by
3285  * the hgatp register, into a supervisor physical address. */
3286  if (hgatp_info) {
3288  hgatp_info, get_field(hgatp, RISCV_HGATP_PPN(xlen)),
3289  NULL, 0,
3290  guest_physical, physical) != ERROR_OK)
3291  return ERROR_FAIL;
3292  } else {
3293  *physical = guest_physical;
3294  }
3295 
3296  return ERROR_OK;
3297 }
3298 
3299 static int riscv_virt2phys(struct target *target, target_addr_t virtual, target_addr_t *physical)
3300 {
3301  bool enabled;
3302  if (riscv_mmu(target, &enabled) != ERROR_OK)
3303  return ERROR_FAIL;
3304  if (!enabled) {
3305  *physical = virtual;
3306  LOG_TARGET_DEBUG(target, "MMU is disabled. 0x%" TARGET_PRIxADDR " -> 0x%" TARGET_PRIxADDR, virtual, *physical);
3307  return ERROR_OK;
3308  }
3309 
3310  riscv_reg_t priv;
3312  LOG_TARGET_ERROR(target, "Failed to read priv register.");
3313  return ERROR_FAIL;
3314  }
3315 
3316  if (priv & VIRT_PRIV_V)
3317  return riscv_virt2phys_v(target, virtual, physical);
3318 
3319  riscv_reg_t satp_value;
3320  if (riscv_reg_get(target, &satp_value, GDB_REGNO_SATP) != ERROR_OK) {
3321  LOG_TARGET_ERROR(target, "Failed to read SATP register.");
3322  return ERROR_FAIL;
3323  }
3324 
3325  unsigned int xlen = riscv_xlen(target);
3326  int satp_mode = get_field(satp_value, RISCV_SATP_MODE(xlen));
3327  const virt2phys_info_t *satp_info;
3328  switch (satp_mode) {
3329  case SATP_MODE_SV32:
3330  satp_info = &sv32;
3331  break;
3332  case SATP_MODE_SV39:
3333  satp_info = &sv39;
3334  break;
3335  case SATP_MODE_SV48:
3336  satp_info = &sv48;
3337  break;
3338  case SATP_MODE_SV57:
3339  satp_info = &sv57;
3340  break;
3341  case SATP_MODE_OFF:
3342  LOG_TARGET_ERROR(target, "No translation or protection."
3343  " (satp: 0x%" PRIx64 ")", satp_value);
3344  return ERROR_FAIL;
3345  default:
3346  LOG_TARGET_ERROR(target, "The translation mode is not supported."
3347  " (satp: 0x%" PRIx64 ")", satp_value);
3348  return ERROR_FAIL;
3349  }
3350 
3352  satp_info, get_field(satp_value, RISCV_SATP_PPN(xlen)),
3353  NULL, 0,
3354  virtual, physical);
3355 }
3356 
3358  uint32_t size, uint32_t count, bool is_write)
3359 {
3360  const bool is_misaligned = address % size != 0;
3361  // TODO: This assumes that size of each page is 4 KiB, which is not necessarily the case.
3362  const bool crosses_page_boundary = RISCV_PGBASE(address + size * count - 1) != RISCV_PGBASE(address);
3363  if (is_misaligned && crosses_page_boundary) {
3364  LOG_TARGET_ERROR(target, "Mis-aligned memory %s (address=0x%" TARGET_PRIxADDR ", size=%d, count=%d)"
3365  " would access an element across page boundary. This is not supported.",
3366  is_write ? "write" : "read", address, size, count);
3367  return ERROR_FAIL;
3368  }
3369  return ERROR_OK;
3370 }
3371 
3372 static int riscv_read_phys_memory(struct target *target, target_addr_t phys_address,
3373  uint32_t size, uint32_t count, uint8_t *buffer)
3374 {
3375  const struct riscv_mem_access_args args = {
3376  .address = phys_address,
3377  .read_buffer = buffer,
3378  .size = size,
3379  .count = count,
3380  .increment = size,
3381  };
3382  RISCV_INFO(r);
3383  return r->access_memory(target, args);
3384 }
3385 
3386 static int riscv_write_phys_memory(struct target *target, target_addr_t phys_address,
3387  uint32_t size, uint32_t count, const uint8_t *buffer)
3388 {
3389  const struct riscv_mem_access_args args = {
3390  .address = phys_address,
3391  .write_buffer = buffer,
3392  .size = size,
3393  .count = count,
3394  .increment = size,
3395  };
3396 
3397  RISCV_INFO(r);
3398  return r->access_memory(target, args);
3399 }
3400 
3401 static int riscv_rw_memory(struct target *target, const struct riscv_mem_access_args args)
3402 {
3403  assert(riscv_mem_access_is_valid(args));
3404 
3405  const bool is_write = riscv_mem_access_is_write(args);
3406  if (args.count == 0) {
3407  LOG_TARGET_WARNING(target, "0-length %s 0x%" TARGET_PRIxADDR,
3408  is_write ? "write to" : "read from", args.address);
3409  return ERROR_OK;
3410  }
3411 
3412  bool mmu_enabled;
3413  int result = riscv_mmu(target, &mmu_enabled);
3414  if (result != ERROR_OK)
3415  return result;
3416 
3417  RISCV_INFO(r);
3418  if (!mmu_enabled)
3419  return r->access_memory(target, args);
3420 
3421  result = check_virt_memory_access(target, args.address,
3422  args.size, args.count, is_write);
3423  if (result != ERROR_OK)
3424  return result;
3425 
3426  uint32_t current_count = 0;
3427  target_addr_t current_address = args.address;
3428  while (current_count < args.count) {
3429  target_addr_t physical_addr;
3430  result = target->type->virt2phys(target, current_address, &physical_addr);
3431  if (result != ERROR_OK) {
3432  LOG_TARGET_ERROR(target, "Address translation failed.");
3433  return result;
3434  }
3435 
3436  /* TODO: For simplicity, this algorithm assumes the worst case - the smallest possible page size,
3437  * which is 4 KiB. The algorithm can be improved to detect the real page size, and allow to use larger
3438  * memory transfers and avoid extra unnecessary virt2phys address translations. */
3439  uint32_t chunk_count = MIN(args.count - current_count,
3440  (RISCV_PGSIZE - RISCV_PGOFFSET(current_address))
3441  / args.size);
3442 
3443  struct riscv_mem_access_args current_access = args;
3444  current_access.address = physical_addr;
3445  current_access.count = chunk_count;
3446  if (is_write)
3447  current_access.write_buffer += current_count * args.size;
3448  else
3449  current_access.read_buffer += current_count * args.size;
3450 
3451  result = r->access_memory(target, current_access);
3452  if (result != ERROR_OK)
3453  return result;
3454 
3455  current_count += chunk_count;
3456  current_address += chunk_count * args.size;
3457  }
3458  return ERROR_OK;
3459 }
3460 
3462  uint32_t size, uint32_t count, uint8_t *buffer)
3463 {
3464  const struct riscv_mem_access_args args = {
3465  .address = address,
3466  .read_buffer = buffer,
3467  .size = size,
3468  .count = count,
3469  .increment = size,
3470  };
3471 
3472  return riscv_rw_memory(target, args);
3473 }
3474 
3476  uint32_t size, uint32_t count, const uint8_t *buffer)
3477 {
3478  const struct riscv_mem_access_args args = {
3479  .address = address,
3480  .write_buffer = buffer,
3481  .size = size,
3482  .count = count,
3483  .increment = size,
3484  };
3485 
3486  return riscv_rw_memory(target, args);
3487 }
3488 
3489 static const char *riscv_get_gdb_arch(const struct target *target)
3490 {
3491  switch (riscv_xlen(target)) {
3492  case 32:
3493  return "riscv:rv32";
3494  case 64:
3495  return "riscv:rv64";
3496  }
3497  LOG_TARGET_ERROR(target, "Unsupported xlen: %d", riscv_xlen(target));
3498  return NULL;
3499 }
3500 
3502  struct reg **reg_list[], int *reg_list_size,
3503  enum target_register_class reg_class, bool is_read)
3504 {
3505  LOG_TARGET_DEBUG(target, "reg_class=%d, read=%d", reg_class, is_read);
3506 
3507  if (!target->reg_cache) {
3508  LOG_TARGET_ERROR(target, "Target not initialized. Return ERROR_FAIL.");
3509  return ERROR_FAIL;
3510  }
3511 
3512  switch (reg_class) {
3513  case REG_CLASS_GENERAL:
3514  *reg_list_size = 33;
3515  break;
3516  case REG_CLASS_ALL:
3517  *reg_list_size = target->reg_cache->num_regs;
3518  break;
3519  default:
3520  LOG_TARGET_ERROR(target, "Unsupported reg_class: %d", reg_class);
3521  return ERROR_FAIL;
3522  }
3523 
3524  *reg_list = calloc(*reg_list_size, sizeof(struct reg *));
3525  if (!*reg_list)
3526  return ERROR_FAIL;
3527 
3528  for (int i = 0; i < *reg_list_size; i++) {
3529  assert(!target->reg_cache->reg_list[i].valid ||
3530  target->reg_cache->reg_list[i].size > 0);
3531  (*reg_list)[i] = &target->reg_cache->reg_list[i];
3532  if (is_read &&
3533  target->reg_cache->reg_list[i].exist &&
3534  !target->reg_cache->reg_list[i].valid) {
3536  return ERROR_FAIL;
3537  }
3538  }
3539 
3540  return ERROR_OK;
3541 }
3542 
3544  struct reg **reg_list[], int *reg_list_size,
3545  enum target_register_class reg_class)
3546 {
3547  return riscv_get_gdb_reg_list_internal(target, reg_list, reg_list_size,
3548  reg_class, false);
3549 }
3550 
3552  struct reg **reg_list[], int *reg_list_size,
3553  enum target_register_class reg_class)
3554 {
3555  return riscv_get_gdb_reg_list_internal(target, reg_list, reg_list_size,
3556  reg_class, true);
3557 }
3558 
3559 static int riscv_arch_state(struct target *target)
3560 {
3561  assert(target->state == TARGET_HALTED);
3562  const bool semihosting_active = target->semihosting &&
3564  LOG_USER("%s halted due to %s.%s",
3567  semihosting_active ? " Semihosting is active." : "");
3568  struct target_type *tt = get_target_type(target);
3569  if (!tt)
3570  return ERROR_FAIL;
3571  assert(tt->arch_state);
3572  return tt->arch_state(target);
3573 }
3574 
3575 /* Algorithm must end with a software breakpoint instruction. */
3576 static int riscv_run_algorithm(struct target *target, int num_mem_params,
3577  struct mem_param *mem_params, int num_reg_params,
3578  struct reg_param *reg_params, target_addr_t entry_point,
3579  target_addr_t exit_point, unsigned int timeout_ms, void *arch_info)
3580 {
3581  RISCV_INFO(info);
3582 
3583  if (target->state != TARGET_HALTED) {
3584  LOG_TARGET_ERROR(target, "not halted (run target algo)");
3585  return ERROR_TARGET_NOT_HALTED;
3586  }
3587 
3588  /* Write memory parameters to the target memory */
3589  for (int i = 0; i < num_mem_params; i++) {
3590  if (mem_params[i].direction == PARAM_OUT ||
3591  mem_params[i].direction == PARAM_IN_OUT) {
3592  int retval = target_write_buffer(target, mem_params[i].address, mem_params[i].size, mem_params[i].value);
3593  if (retval != ERROR_OK) {
3594  LOG_TARGET_ERROR(target, "Couldn't write input mem param into the memory, addr=0x%" TARGET_PRIxADDR
3595  " size=0x%" PRIx32, mem_params[i].address, mem_params[i].size);
3596  return retval;
3597  }
3598  }
3599  }
3600 
3601  /* Save registers */
3602  struct reg *reg_pc = register_get_by_name(target->reg_cache, "pc", true);
3603  if (!reg_pc || reg_pc->type->get(reg_pc) != ERROR_OK)
3604  return ERROR_FAIL;
3605  uint64_t saved_pc = buf_get_u64(reg_pc->value, 0, reg_pc->size);
3606  LOG_TARGET_DEBUG(target, "saved_pc=0x%" PRIx64, saved_pc);
3607 
3608  uint64_t saved_regs[32];
3609  for (int i = 0; i < num_reg_params; i++) {
3610  LOG_TARGET_DEBUG(target, "save %s", reg_params[i].reg_name);
3611  struct reg *r = register_get_by_name(target->reg_cache, reg_params[i].reg_name, false);
3612  if (!r) {
3613  LOG_TARGET_ERROR(target, "Couldn't find register named '%s'", reg_params[i].reg_name);
3614  return ERROR_FAIL;
3615  }
3616 
3617  if (r->size != reg_params[i].size) {
3618  LOG_TARGET_ERROR(target, "Register %s is %d bits instead of %d bits.",
3619  reg_params[i].reg_name, r->size, reg_params[i].size);
3620  return ERROR_FAIL;
3621  }
3622 
3623  if (r->number > GDB_REGNO_XPR31) {
3624  LOG_TARGET_ERROR(target, "Only GPRs can be use as argument registers.");
3625  return ERROR_FAIL;
3626  }
3627 
3628  if (r->type->get(r) != ERROR_OK)
3629  return ERROR_FAIL;
3630  saved_regs[r->number] = buf_get_u64(r->value, 0, r->size);
3631 
3632  if (reg_params[i].direction == PARAM_OUT || reg_params[i].direction == PARAM_IN_OUT) {
3633  if (r->type->set(r, reg_params[i].value) != ERROR_OK)
3634  return ERROR_FAIL;
3635  }
3636  }
3637 
3638  /* Disable Interrupts before attempting to run the algorithm. */
3639  riscv_reg_t current_mstatus;
3640  if (riscv_interrupts_disable(target, &current_mstatus) != ERROR_OK)
3641  return ERROR_FAIL;
3642 
3643  /* Run algorithm */
3644  LOG_TARGET_DEBUG(target, "resume at 0x%" TARGET_PRIxADDR, entry_point);
3645  if (riscv_resume(target, false, entry_point, false, true, true) != ERROR_OK)
3646  return ERROR_FAIL;
3647 
3648  int64_t start = timeval_ms();
3649  while (target->state != TARGET_HALTED) {
3650  LOG_TARGET_DEBUG(target, "poll()");
3651  int64_t now = timeval_ms();
3652  if (now - start > timeout_ms) {
3653  LOG_TARGET_ERROR(target, "Algorithm timed out after %" PRId64 " ms.", now - start);
3654  riscv_halt(target);
3656  enum gdb_regno regnums[] = {
3665  GDB_REGNO_PC,
3667  };
3668  for (unsigned int i = 0; i < ARRAY_SIZE(regnums); i++) {
3669  enum gdb_regno regno = regnums[i];
3670  riscv_reg_t reg_value;
3671  if (riscv_reg_get(target, &reg_value, regno) != ERROR_OK)
3672  break;
3673 
3674  LOG_TARGET_ERROR(target, "%s = 0x%" PRIx64, riscv_reg_gdb_regno_name(target, regno), reg_value);
3675  }
3676  return ERROR_TARGET_TIMEOUT;
3677  }
3678 
3679  int result = old_or_new_riscv_poll(target);
3680  if (result != ERROR_OK)
3681  return result;
3682  }
3683 
3684  /* TODO: The current hart id might have been changed in poll(). */
3685  /* if (riscv_select_current_hart(target) != ERROR_OK)
3686  return ERROR_FAIL; */
3687 
3688  if (reg_pc->type->get(reg_pc) != ERROR_OK)
3689  return ERROR_FAIL;
3690  uint64_t final_pc = buf_get_u64(reg_pc->value, 0, reg_pc->size);
3691  if (exit_point && final_pc != exit_point) {
3692  LOG_TARGET_ERROR(target, "PC ended up at 0x%" PRIx64 " instead of 0x%"
3693  TARGET_PRIxADDR, final_pc, exit_point);
3694  return ERROR_FAIL;
3695  }
3696 
3697  /* Restore Interrupts */
3698  if (riscv_interrupts_restore(target, current_mstatus) != ERROR_OK)
3699  return ERROR_FAIL;
3700 
3701  /* Restore registers */
3702  uint8_t buf[8] = { 0 };
3703  buf_set_u64(buf, 0, info->xlen, saved_pc);
3704  if (reg_pc->type->set(reg_pc, buf) != ERROR_OK)
3705  return ERROR_FAIL;
3706 
3707  for (int i = 0; i < num_reg_params; i++) {
3708  if (reg_params[i].direction == PARAM_IN ||
3709  reg_params[i].direction == PARAM_IN_OUT) {
3710  struct reg *r = register_get_by_name(target->reg_cache, reg_params[i].reg_name, false);
3711  if (r->type->get(r) != ERROR_OK) {
3712  LOG_TARGET_ERROR(target, "get(%s) failed", r->name);
3713  return ERROR_FAIL;
3714  }
3715  buf_cpy(r->value, reg_params[i].value, reg_params[i].size);
3716  }
3717  LOG_TARGET_DEBUG(target, "restore %s", reg_params[i].reg_name);
3718  struct reg *r = register_get_by_name(target->reg_cache, reg_params[i].reg_name, false);
3719  buf_set_u64(buf, 0, info->xlen, saved_regs[r->number]);
3720  if (r->type->set(r, buf) != ERROR_OK) {
3721  LOG_TARGET_ERROR(target, "set(%s) failed", r->name);
3722  return ERROR_FAIL;
3723  }
3724  }
3725 
3726  /* Read memory parameters from the target memory */
3727  for (int i = 0; i < num_mem_params; i++) {
3728  if (mem_params[i].direction == PARAM_IN ||
3729  mem_params[i].direction == PARAM_IN_OUT) {
3730  int retval = target_read_buffer(target, mem_params[i].address, mem_params[i].size,
3731  mem_params[i].value);
3732  if (retval != ERROR_OK) {
3733  LOG_TARGET_ERROR(target, "Couldn't read output mem param from the memory, "
3734  "addr=0x%" TARGET_PRIxADDR " size=0x%" PRIx32,
3735  mem_params[i].address, mem_params[i].size);
3736  return retval;
3737  }
3738  }
3739  }
3740 
3741  return ERROR_OK;
3742 }
3743 
3745  target_addr_t address, uint32_t count,
3746  uint32_t *checksum)
3747 {
3748  struct working_area *crc_algorithm;
3749  struct reg_param reg_params[2];
3750  int retval;
3751 
3752  LOG_TARGET_DEBUG(target, "address=0x%" TARGET_PRIxADDR "; count=0x%" PRIx32, address, count);
3753 
3754  static const uint8_t riscv32_crc_code[] = {
3755 #include "../../../contrib/loaders/checksum/riscv32_crc.inc"
3756  };
3757  static const uint8_t riscv64_crc_code[] = {
3758 #include "../../../contrib/loaders/checksum/riscv64_crc.inc"
3759  };
3760 
3761  static const uint8_t *crc_code;
3762 
3763  unsigned int xlen = riscv_xlen(target);
3764  unsigned int crc_code_size;
3765  if (xlen == 32) {
3766  crc_code = riscv32_crc_code;
3767  crc_code_size = sizeof(riscv32_crc_code);
3768  } else {
3769  crc_code = riscv64_crc_code;
3770  crc_code_size = sizeof(riscv64_crc_code);
3771  }
3772 
3773  if (count < crc_code_size * 4) {
3774  /* Don't use the algorithm for relatively small buffers. It's faster
3775  * just to read the memory. target_checksum_memory() will take care of
3776  * that if we fail. */
3777  return ERROR_FAIL;
3778  }
3779 
3780  retval = target_alloc_working_area(target, crc_code_size, &crc_algorithm);
3781  if (retval != ERROR_OK)
3782  return retval;
3783 
3784  if (crc_algorithm->address + crc_algorithm->size > address &&
3785  crc_algorithm->address < address + count) {
3786  /* Region to checksum overlaps with the work area we've been assigned.
3787  * Bail. (Would be better to manually checksum what we read there, and
3788  * use the algorithm for the rest.) */
3789  target_free_working_area(target, crc_algorithm);
3790  return ERROR_FAIL;
3791  }
3792 
3793  retval = target_write_buffer(target, crc_algorithm->address, crc_code_size,
3794  crc_code);
3795  if (retval != ERROR_OK) {
3796  LOG_TARGET_ERROR(target, "Failed to write code to " TARGET_ADDR_FMT ": %d",
3797  crc_algorithm->address, retval);
3798  target_free_working_area(target, crc_algorithm);
3799  return retval;
3800  }
3801 
3802  init_reg_param(&reg_params[0], "a0", xlen, PARAM_IN_OUT);
3803  init_reg_param(&reg_params[1], "a1", xlen, PARAM_OUT);
3804  buf_set_u64(reg_params[0].value, 0, xlen, address);
3805  buf_set_u64(reg_params[1].value, 0, xlen, count);
3806 
3807  /* 20 second timeout/megabyte */
3808  unsigned int timeout = 20000 * (1 + (count / (1024 * 1024)));
3809 
3810  retval = target_run_algorithm(target, 0, NULL, 2, reg_params,
3811  crc_algorithm->address,
3812  0, /* Leave exit point unspecified because we don't know. */
3813  timeout, NULL);
3814 
3815  if (retval == ERROR_OK)
3816  *checksum = buf_get_u32(reg_params[0].value, 0, 32);
3817  else
3818  LOG_TARGET_ERROR(target, "Error executing RISC-V CRC algorithm.");
3819 
3820  destroy_reg_param(&reg_params[0]);
3821  destroy_reg_param(&reg_params[1]);
3822 
3823  target_free_working_area(target, crc_algorithm);
3824 
3825  LOG_TARGET_DEBUG(target, "checksum=0x%" PRIx32 ", result=%d", *checksum, retval);
3826 
3827  return retval;
3828 }
3829 
3830 /*** OpenOCD Helper Functions ***/
3831 
3836 };
3837 static int riscv_poll_hart(struct target *target, enum riscv_next_action *next_action)
3838 {
3839  RISCV_INFO(r);
3840 
3841  LOG_TARGET_DEBUG(target, "polling, target->state=%d", target->state);
3842 
3843  *next_action = RPH_NONE;
3844 
3845  enum riscv_hart_state previous_riscv_state = 0;
3846  enum target_state previous_target_state = target->state;
3847  switch (target->state) {
3848  case TARGET_UNKNOWN:
3849  /* Special case, handled further down. */
3850  previous_riscv_state = RISCV_STATE_UNAVAILABLE; /* Need to assign something. */
3851  break;
3852  case TARGET_RUNNING:
3853  previous_riscv_state = RISCV_STATE_RUNNING;
3854  break;
3855  case TARGET_HALTED:
3856  previous_riscv_state = RISCV_STATE_HALTED;
3857  break;
3858  case TARGET_RESET:
3859  previous_riscv_state = RISCV_STATE_HALTED;
3860  break;
3861  case TARGET_DEBUG_RUNNING:
3862  previous_riscv_state = RISCV_STATE_RUNNING;
3863  break;
3864  case TARGET_UNAVAILABLE:
3865  previous_riscv_state = RISCV_STATE_UNAVAILABLE;
3866  break;
3867  }
3868 
3869  /* If OpenOCD thinks we're running but this hart is halted then it's time
3870  * to raise an event. */
3871  enum riscv_hart_state state;
3873  return ERROR_FAIL;
3874 
3876  LOG_TARGET_ERROR(target, "Hart is non-existent!");
3877  return ERROR_FAIL;
3878  }
3879 
3880  if (state == RISCV_STATE_HALTED && timeval_ms() - r->last_activity > 100) {
3881  /* If we've been idle for a while, flush the register cache. Just in case
3882  * OpenOCD is going to be disconnected without shutting down cleanly. */
3884  return ERROR_FAIL;
3885  }
3886 
3887  if (target->state == TARGET_UNKNOWN || state != previous_riscv_state) {
3888  switch (state) {
3889  case RISCV_STATE_HALTED:
3890  if (previous_riscv_state == RISCV_STATE_UNAVAILABLE)
3891  LOG_TARGET_INFO(target, "became available (halted)");
3892 
3893  LOG_TARGET_DEBUG(target, " triggered a halt; previous_target_state=%d",
3894  previous_target_state);
3896  enum riscv_halt_reason halt_reason = riscv_halt_reason(target);
3897  if (set_debug_reason(target, halt_reason) != ERROR_OK)
3898  return ERROR_FAIL;
3899 
3900  if (halt_reason == RISCV_HALT_EBREAK) {
3901  int retval;
3902  /* Detect if this EBREAK is a semihosting request. If so, handle it. */
3903  switch (riscv_semihosting(target, &retval)) {
3904  case SEMIHOSTING_NONE:
3905  break;
3906  case SEMIHOSTING_WAITING:
3907  /* This hart should remain halted. */
3908  *next_action = RPH_REMAIN_HALTED;
3909  break;
3910  case SEMIHOSTING_HANDLED:
3911  /* This hart should be resumed, along with any other
3912  * harts that halted due to haltgroups. */
3913  *next_action = RPH_RESUME;
3914  return ERROR_OK;
3915  case SEMIHOSTING_ERROR:
3916  return retval;
3917  }
3918  }
3919 
3920  if (r->handle_became_halted &&
3921  r->handle_became_halted(target, previous_riscv_state) != ERROR_OK)
3922  return ERROR_FAIL;
3923 
3924  /* We shouldn't do the callbacks yet. What if
3925  * there are multiple harts that halted at the
3926  * same time? We need to set debug reason on each
3927  * of them before calling a callback, which is
3928  * going to figure out the "current thread". */
3929 
3930  r->halted_needs_event_callback = true;
3931  if (previous_target_state == TARGET_DEBUG_RUNNING)
3932  r->halted_callback_event = TARGET_EVENT_DEBUG_HALTED;
3933  else
3934  r->halted_callback_event = TARGET_EVENT_HALTED;
3935  break;
3936 
3937  case RISCV_STATE_RUNNING:
3938  if (previous_riscv_state == RISCV_STATE_UNAVAILABLE)
3939  LOG_TARGET_INFO(target, "became available (running)");
3940 
3941  LOG_TARGET_DEBUG(target, " triggered running");
3944  if (r->handle_became_running &&
3945  r->handle_became_running(target, previous_riscv_state) != ERROR_OK)
3946  return ERROR_FAIL;
3947  break;
3948 
3950  LOG_TARGET_DEBUG(target, " became unavailable");
3951  LOG_TARGET_INFO(target, "became unavailable.");
3953  if (r->handle_became_unavailable &&
3954  r->handle_became_unavailable(target, previous_riscv_state) != ERROR_OK)
3955  return ERROR_FAIL;
3956  break;
3957 
3959  LOG_TARGET_ERROR(target, "Hart is non-existent!");
3961  break;
3962  }
3963  }
3964 
3965  return ERROR_OK;
3966 }
3967 
3968 static int sample_memory(struct target *target)
3969 {
3970  RISCV_INFO(r);
3971 
3972  if (!r->sample_buf.buf || !r->sample_config.enabled)
3973  return ERROR_OK;
3974 
3975  LOG_TARGET_DEBUG(target, "buf used/size: %d/%d", r->sample_buf.used, r->sample_buf.size);
3976 
3977  uint64_t start = timeval_ms();
3979  int result = ERROR_OK;
3980  if (r->sample_memory) {
3981  result = r->sample_memory(target, &r->sample_buf, &r->sample_config,
3983  if (result != ERROR_NOT_IMPLEMENTED)
3984  goto exit;
3985  }
3986 
3987  /* Default slow path. */
3989  for (unsigned int i = 0; i < ARRAY_SIZE(r->sample_config.bucket); i++) {
3990  if (r->sample_config.bucket[i].enabled &&
3991  r->sample_buf.used + 1 + r->sample_config.bucket[i].size_bytes < r->sample_buf.size) {
3993  r->sample_buf.buf[r->sample_buf.used] = i;
3994  result = riscv_read_phys_memory(target,
3995  r->sample_config.bucket[i].address,
3996  r->sample_config.bucket[i].size_bytes, 1,
3997  r->sample_buf.buf + r->sample_buf.used + 1);
3998  if (result == ERROR_OK)
3999  r->sample_buf.used += 1 + r->sample_config.bucket[i].size_bytes;
4000  else
4001  goto exit;
4002  }
4003  }
4004  }
4005 
4006 exit:
4008  if (result != ERROR_OK) {
4009  LOG_TARGET_INFO(target, "Turning off memory sampling because it failed.");
4010  r->sample_config.enabled = false;
4011  }
4012  return result;
4013 }
4014 
4015 /*** OpenOCD Interface ***/
4017 {
4018  LOG_TARGET_DEBUG(target, "Polling all harts.");
4019 
4020  struct riscv_info *i = riscv_info(target);
4021 
4022  struct list_head *targets;
4023 
4024  OOCD_LIST_HEAD(single_target_list);
4025  struct target_list single_target_entry = {
4026  .lh = {NULL, NULL},
4027  .target = target
4028  };
4029 
4030  if (target->smp) {
4031  targets = target->smp_targets;
4032  } else {
4033  /* Make a list that just contains a single target, so we can
4034  * share code below. */
4035  list_add(&single_target_entry.lh, &single_target_list);
4036  targets = &single_target_list;
4037  }
4038 
4039  unsigned int should_remain_halted = 0;
4040  unsigned int should_resume = 0;
4041  unsigned int halted = 0;
4042  unsigned int running = 0;
4043  unsigned int cause_groups = 0;
4044  struct target_list *entry;
4045  foreach_smp_target(entry, targets) {
4046  struct target *t = entry->target;
4047  struct riscv_info *info = riscv_info(t);
4048 
4049  /* Clear here just in case there were errors and we never got to
4050  * check this flag further down. */
4051  info->halted_needs_event_callback = false;
4052 
4053  if (!target_was_examined(t))
4054  continue;
4055 
4056  enum riscv_next_action next_action;
4057  if (riscv_poll_hart(t, &next_action) != ERROR_OK)
4058  return ERROR_FAIL;
4059 
4060  switch (next_action) {
4061  case RPH_NONE:
4062  if (t->state == TARGET_HALTED)
4063  halted++;
4064  if (t->state == TARGET_RUNNING ||
4066  running++;
4067  break;
4068  case RPH_REMAIN_HALTED:
4069  should_remain_halted++;
4070  break;
4071  case RPH_RESUME:
4072  should_resume++;
4073  break;
4074  }
4075  }
4076 
4077  LOG_TARGET_DEBUG(target, "should_remain_halted=%d, should_resume=%d",
4078  should_remain_halted, should_resume);
4079  if (should_remain_halted && should_resume) {
4080  LOG_TARGET_WARNING(target, "%d harts should remain halted, and %d should resume.",
4081  should_remain_halted, should_resume);
4082  }
4083  if (should_remain_halted) {
4084  LOG_TARGET_DEBUG(target, "halt all; should_remain_halted=%d",
4085  should_remain_halted);
4086  riscv_halt(target);
4087  } else if (should_resume) {
4088  LOG_TARGET_DEBUG(target, "resume all");
4089  riscv_resume(target, true, 0, 0, 0, false);
4090  } else if (halted && running) {
4091  LOG_TARGET_DEBUG(target, "SMP group is in inconsistent state: %u halted, %u running",
4092  halted, running);
4093 
4094  /* The SMP group is in an inconsistent state - some harts in the group have halted
4095  * whereas others are running. The reasons for that (and corresponding
4096  * OpenOCD actions) could be:
4097  * 1) The targets are in the process of halting due to halt groups
4098  * but not all of them halted --> poll again so that the halt reason of every
4099  * hart can be accurately determined (e.g. semihosting).
4100  * 2) The targets do not support halt groups --> OpenOCD must halt
4101  * the remaining harts by a standard halt request.
4102  * 3) The hart states got out of sync for some other unknown reason (problem?). -->
4103  * Same as previous - try to halt the harts by a standard halt request
4104  * to get them back in sync. */
4105 
4106  /* Detect if the harts are just in the process of halting due to a halt group */
4107  foreach_smp_target(entry, targets)
4108  {
4109  struct target *t = entry->target;
4110  if (t->state == TARGET_HALTED) {
4111  riscv_reg_t dcsr;
4112  if (riscv_reg_get(t, &dcsr, GDB_REGNO_DCSR) != ERROR_OK)
4113  return ERROR_FAIL;
4115  cause_groups++;
4116  else
4117  /* This hart has halted due to something else than a halt group.
4118  * Don't continue checking the rest - exit early. */
4119  break;
4120  }
4121  }
4122  /* Condition: halted == cause_groups
4123  *
4124  * This condition indicates a paradox where:
4125  * - All currently halted harts show CSR_DCSR_CAUSE_GROUP
4126  * - However, no individual hart can be identified as the actual initiator of the halt condition
4127  *
4128  * Poll again so that the true halt reason can be discovered (e.g. CSR_DCSR_CAUSE_EBREAK) */
4129  if (halted == cause_groups) {
4130  LOG_TARGET_DEBUG(target, "The harts appear to just be in the process of halting due to a halt group.");
4132  /* Wait a little, then re-poll. */
4134  alive_sleep(10);
4135  LOG_TARGET_DEBUG(target, "Re-polling the state of the SMP group.");
4136  return riscv_openocd_poll(target);
4137  }
4138  /* We have already re-polled multiple times but the halt group is still inconsistent. */
4139  LOG_TARGET_DEBUG(target, "Re-polled the SMP group %d times it is still not in a consistent state.",
4141  }
4142 
4143  /* Halting the whole SMP group to bring it in sync. */
4144  LOG_TARGET_DEBUG(target, "halt all; halted=%d",
4145  halted);
4146  riscv_halt(target);
4147  } else {
4148  /* For targets that were discovered to be halted, call the
4149  * appropriate callback. */
4150  foreach_smp_target(entry, targets)
4151  {
4152  struct target *t = entry->target;
4153  struct riscv_info *info = riscv_info(t);
4154  if (info->halted_needs_event_callback) {
4155  target_call_event_callbacks(t, info->halted_callback_event);
4156  info->halted_needs_event_callback = false;
4157  }
4158  }
4159  }
4160 
4161  i->halt_group_repoll_count = 0;
4162 
4163  /* Call tick() for every hart. What happens in tick() is opaque to this
4164  * layer. The reason it's outside the previous loop is that at this point
4165  * the state of every hart has settled, so any side effects happening in
4166  * tick() won't affect the delicate poll() code. */
4167  foreach_smp_target(entry, targets) {
4168  struct target *t = entry->target;
4169  struct riscv_info *info = riscv_info(t);
4170  if (info->tick && info->tick(t) != ERROR_OK)
4171  return ERROR_FAIL;
4172  }
4173 
4174  /* Sample memory if any target is running. */
4175  foreach_smp_target(entry, targets) {
4176  struct target *t = entry->target;
4177  if (t->state == TARGET_RUNNING) {
4179  break;
4180  }
4181  }
4182 
4183  return ERROR_OK;
4184 }
4185 
4186 static int riscv_openocd_step_impl(struct target *target, bool current,
4187  target_addr_t address, bool handle_breakpoints, int handle_callbacks)
4188 {
4189  LOG_TARGET_DEBUG(target, "stepping hart");
4190 
4191  if (!current) {
4193  return ERROR_FAIL;
4194  }
4195 
4196  struct breakpoint *breakpoint = NULL;
4197  /* the front-end may request us not to handle breakpoints */
4198  if (handle_breakpoints) {
4199  if (current) {
4201  return ERROR_FAIL;
4202  }
4205  return ERROR_FAIL;
4206  }
4207 
4209  return ERROR_FAIL;
4210 
4211  RISCV_INFO(r);
4212  bool *wps_to_enable = calloc(r->trigger_count, sizeof(*wps_to_enable));
4213  if (!wps_to_enable) {
4214  LOG_ERROR("Out of memory");
4215  return ERROR_FAIL;
4216  }
4217 
4218  if (disable_watchpoints(target, wps_to_enable) != ERROR_OK) {
4219  LOG_TARGET_ERROR(target, "Failed to temporarily disable "
4220  "watchpoints before single-step.");
4221  free(wps_to_enable);
4222  return ERROR_FAIL;
4223  }
4224 
4225  bool success = true;
4226  riscv_reg_t current_mstatus;
4227  RISCV_INFO(info);
4228 
4229  if (info->isrmask_mode == RISCV_ISRMASK_STEPONLY) {
4230  /* Disable Interrupts before stepping. */
4231  if (riscv_interrupts_disable(target, &current_mstatus) != ERROR_OK) {
4232  success = false;
4233  LOG_TARGET_ERROR(target, "Unable to disable interrupts.");
4234  goto _exit;
4235  }
4236  }
4237 
4239  success = false;
4240  LOG_TARGET_ERROR(target, "Unable to step rtos hart.");
4241  }
4242 
4244  /* If this happens, it means there is a bug in the previous
4245  * register-flushing algorithm: not all registers were flushed
4246  * back to the target prior to single-step. */
4248  "BUG: registers should have been flushed by this point.");
4249  }
4250 
4252 
4253  if (info->isrmask_mode == RISCV_ISRMASK_STEPONLY)
4254  if (riscv_interrupts_restore(target, current_mstatus) != ERROR_OK) {
4255  success = false;
4256  LOG_TARGET_ERROR(target, "Unable to restore interrupts.");
4257  }
4258 
4259 _exit:
4260  if (enable_watchpoints(target, wps_to_enable) != ERROR_OK) {
4261  success = false;
4262  LOG_TARGET_ERROR(target, "Failed to re-enable watchpoints "
4263  "after single-step.");
4264  }
4265 
4266  free(wps_to_enable);
4267 
4269  success = false;
4270  LOG_TARGET_ERROR(target, "Unable to restore the disabled breakpoint.");
4271  }
4272 
4273  if (success) {
4275  if (handle_callbacks)
4277 
4280  if (handle_callbacks)
4282  }
4283 
4284  return success ? ERROR_OK : ERROR_FAIL;
4285 }
4286 
4287 int riscv_openocd_step(struct target *target, bool current,
4288  target_addr_t address, bool handle_breakpoints)
4289 {
4290  return riscv_openocd_step_impl(target, current, address, handle_breakpoints,
4291  true /* handle_callbacks */);
4292 }
4293 
4294 /* Command Handlers */
4295 COMMAND_HANDLER(riscv_set_command_timeout_sec)
4296 {
4297  if (CMD_ARGC != 1)
4299 
4300  int timeout = atoi(CMD_ARGV[0]);
4301  if (timeout <= 0) {
4302  LOG_ERROR("%s is not a valid integer argument for command.", CMD_ARGV[0]);
4303  return ERROR_FAIL;
4304  }
4305 
4307 
4308  return ERROR_OK;
4309 }
4310 
4311 COMMAND_HANDLER(riscv_set_reset_timeout_sec)
4312 {
4313  LOG_WARNING("The command 'riscv set_reset_timeout_sec' is deprecated! Please, use 'riscv set_command_timeout_sec'.");
4314  if (CMD_ARGC != 1)
4316 
4317  int timeout = atoi(CMD_ARGV[0]);
4318  if (timeout <= 0) {
4319  LOG_ERROR("%s is not a valid integer argument for command.", CMD_ARGV[0]);
4320  return ERROR_FAIL;
4321  }
4322 
4324  return ERROR_OK;
4325 }
4326 
4327 COMMAND_HANDLER(riscv_set_mem_access)
4328 {
4330  RISCV_INFO(r);
4331  int progbuf_cnt = 0;
4332  int sysbus_cnt = 0;
4333  int abstract_cnt = 0;
4334 
4335  if (CMD_ARGC < 1 || CMD_ARGC > RISCV_MEM_ACCESS_MAX_METHODS_NUM) {
4336  command_print(CMD, "Command takes 1 to %d parameters",
4339  }
4340 
4341  /* Check argument validity */
4342  for (unsigned int i = 0; i < CMD_ARGC; i++) {
4343  if (strcmp("progbuf", CMD_ARGV[i]) == 0) {
4344  progbuf_cnt++;
4345  } else if (strcmp("sysbus", CMD_ARGV[i]) == 0) {
4346  sysbus_cnt++;
4347  } else if (strcmp("abstract", CMD_ARGV[i]) == 0) {
4348  abstract_cnt++;
4349  } else {
4350  LOG_ERROR("Unknown argument '%s'. "
4351  "Must be one of: 'progbuf', 'sysbus' or 'abstract'.", CMD_ARGV[i]);
4353  }
4354  }
4355  if (progbuf_cnt > 1 || sysbus_cnt > 1 || abstract_cnt > 1) {
4356  LOG_ERROR("Syntax error - duplicate arguments to `riscv set_mem_access`.");
4358  }
4359 
4360  /* Args are valid, store them */
4361  r->num_enabled_mem_access_methods = CMD_ARGC;
4362  for (unsigned int i = 0; i < CMD_ARGC; i++) {
4363  if (strcmp("progbuf", CMD_ARGV[i]) == 0)
4364  r->mem_access_methods[i] = RISCV_MEM_ACCESS_PROGBUF;
4365  else if (strcmp("sysbus", CMD_ARGV[i]) == 0)
4366  r->mem_access_methods[i] = RISCV_MEM_ACCESS_SYSBUS;
4367  else if (strcmp("abstract", CMD_ARGV[i]) == 0)
4368  r->mem_access_methods[i] = RISCV_MEM_ACCESS_ABSTRACT;
4369  }
4370 
4371  /* Reset warning flags */
4372  for (size_t i = 0; i < RISCV_MEM_ACCESS_MAX_METHODS_NUM; ++i)
4373  r->mem_access_warn[i] = true;
4374 
4375  return ERROR_OK;
4376 }
4377 
4378 
4379 static bool parse_csr_address(const char *reg_address_str, unsigned int *reg_addr)
4380 {
4381  *reg_addr = -1;
4382  /* skip initial spaces */
4383  while (isspace(reg_address_str[0]))
4384  ++reg_address_str;
4385  /* try to detect if string starts with 0x or 0X */
4386  bool is_hex_address = strncmp(reg_address_str, "0x", 2) == 0 ||
4387  strncmp(reg_address_str, "0X", 2) == 0;
4388 
4389  unsigned int scanned_chars;
4390  if (is_hex_address) {
4391  reg_address_str += 2;
4392  if (sscanf(reg_address_str, "%x%n", reg_addr, &scanned_chars) != 1)
4393  return false;
4394  } else {
4395  /* If we are here and register address string starts with zero, this is
4396  * an indication that most likely user has an incorrect input because:
4397  * - decimal numbers typically do not start with "0"
4398  * - octals are not supported by our interface
4399  * - hexadecimal numbers should have "0x" prefix
4400  * Thus such input is rejected. */
4401  if (reg_address_str[0] == '0' && strlen(reg_address_str) > 1)
4402  return false;
4403  if (sscanf(reg_address_str, "%u%n", reg_addr, &scanned_chars) != 1)
4404  return false;
4405  }
4406  return scanned_chars == strlen(reg_address_str);
4407 }
4408 
4409 static int parse_reg_ranges_impl(struct list_head *ranges, char *args,
4410  const char *reg_type, unsigned int max_val, char ** const name_buffer)
4411 {
4412  /* For backward compatibility, allow multiple parameters within one TCL
4413  * argument, separated by ',' */
4414  for (char *arg = strtok(args, ","); arg; arg = strtok(NULL, ",")) {
4415  unsigned int low = 0;
4416  unsigned int high = 0;
4417  char *name = NULL;
4418 
4419  char *dash = strchr(arg, '-');
4420  char *equals = strchr(arg, '=');
4421 
4422  if (!dash && !equals) {
4423  /* Expecting single register number. */
4424  if (!parse_csr_address(arg, &low)) {
4425  LOG_ERROR("Failed to parse single register number from '%s'.", arg);
4427  }
4428  } else if (dash && !equals) {
4429  /* Expecting register range - two numbers separated by a dash: ##-## */
4430  *dash = '\0';
4431  if (!parse_csr_address(arg, &low)) {
4432  LOG_ERROR("Failed to parse '%s' - not a valid decimal or hexadecimal number.",
4433  arg);
4435  }
4436  const char *high_num_in = dash + 1;
4437  if (!parse_csr_address(high_num_in, &high)) {
4438  LOG_ERROR("Failed to parse '%s' - not a valid decimal or hexadecimal number.",
4439  high_num_in);
4441  }
4442  if (high < low) {
4443  LOG_ERROR("Incorrect range encountered [%u, %u].", low, high);
4444  return ERROR_FAIL;
4445  }
4446  } else if (!dash && equals) {
4447  /* Expecting single register number with textual name specified: ##=name */
4448  *equals = '\0';
4449  if (!parse_csr_address(arg, &low)) {
4450  LOG_ERROR("Failed to parse '%s' - not a valid decimal or hexadecimal number.",
4451  arg);
4453  }
4454 
4455  const char * const reg_name_in = equals + 1;
4456  const size_t reg_type_len = strlen(reg_type);
4457  /* format is: <reg_type>_<reg_name_in>\0 */
4458  *name_buffer = calloc(1, strlen(reg_name_in) + reg_type_len + 2);
4459  name = *name_buffer;
4460  if (!name) {
4461  LOG_ERROR("Out of memory");
4462  return ERROR_FAIL;
4463  }
4464  strcpy(name, reg_type);
4465  name[reg_type_len] = '_';
4466 
4467  unsigned int scanned_chars;
4468  char *scan_dst = name + strlen(reg_type) + 1;
4469  if (sscanf(reg_name_in, "%[_a-zA-Z0-9]%n", scan_dst, &scanned_chars) != 1 ||
4470  scanned_chars != strlen(reg_name_in)) {
4471  LOG_ERROR("Invalid characters in register name '%s'.", reg_name_in);
4473  }
4474  } else {
4475  LOG_ERROR("Invalid argument '%s'.", arg);
4477  }
4478 
4479  high = MAX(high, low);
4480 
4481  if (high > max_val) {
4482  LOG_ERROR("Cannot expose %s register number 0x%x, maximum allowed value is 0x%x.",
4483  reg_type, high, max_val);
4484  return ERROR_FAIL;
4485  }
4486 
4487  /* Check for overlap, name uniqueness. */
4488  range_list_t *entry;
4489  list_for_each_entry(entry, ranges, list) {
4490  if (entry->low <= high && low <= entry->high) {
4491  if (low == high)
4492  LOG_WARNING("Duplicate %s register number - "
4493  "Register %u has already been exposed previously", reg_type, low);
4494  else
4495  LOG_WARNING("Overlapping register ranges - Register range starting from %u overlaps "
4496  "with already exposed register/range at %u.", low, entry->low);
4497  }
4498 
4499  if (entry->name && name && (strcasecmp(entry->name, name) == 0)) {
4500  LOG_ERROR("Duplicate register name \"%s\" found.", name);
4501  return ERROR_FAIL;
4502  }
4503  }
4504 
4505  range_list_t *range = calloc(1, sizeof(range_list_t));
4506  if (!range) {
4507  LOG_ERROR("Out of memory");
4508  return ERROR_FAIL;
4509  }
4510 
4511  range->low = low;
4512  range->high = high;
4513  range->name = name;
4514  /* ownership over name_buffer contents is transferred to list item here */
4515  *name_buffer = NULL;
4516  list_add(&range->list, ranges);
4517  }
4518 
4519  return ERROR_OK;
4520 }
4521 
4522 static int parse_reg_ranges(struct list_head *ranges, const char *tcl_arg,
4523  const char *reg_type, unsigned int max_val)
4524 {
4525  char *args = strdup(tcl_arg);
4526  if (!args) {
4527  LOG_ERROR("Out of memory");
4528  return ERROR_FAIL;
4529  }
4530  char *name_buffer = NULL;
4531  int result = parse_reg_ranges_impl(ranges, args, reg_type, max_val, &name_buffer);
4532  free(name_buffer);
4533  free(args);
4534  return result;
4535 }
4536 
4537 COMMAND_HANDLER(riscv_set_expose_csrs)
4538 {
4539  if (CMD_ARGC == 0)
4541 
4543  RISCV_INFO(info);
4544  int ret = ERROR_OK;
4545 
4546  for (unsigned int i = 0; i < CMD_ARGC; i++) {
4547  ret = parse_reg_ranges(&info->expose_csr, CMD_ARGV[i], "csr", 0xfff);
4548  if (ret != ERROR_OK)
4549  break;
4550  }
4551 
4552  return ret;
4553 }
4554 
4555 COMMAND_HANDLER(riscv_set_expose_custom)
4556 {
4557  if (CMD_ARGC == 0)
4559 
4561  RISCV_INFO(info);
4562  int ret = ERROR_OK;
4563 
4564  for (unsigned int i = 0; i < CMD_ARGC; i++) {
4565  ret = parse_reg_ranges(&info->expose_custom, CMD_ARGV[i], "custom", 0x3fff);
4566  if (ret != ERROR_OK)
4567  break;
4568  }
4569 
4570  return ret;
4571 }
4572 
4573 COMMAND_HANDLER(riscv_hide_csrs)
4574 {
4575  if (CMD_ARGC == 0)
4577 
4579  RISCV_INFO(info);
4580  int ret = ERROR_OK;
4581 
4582  for (unsigned int i = 0; i < CMD_ARGC; i++) {
4583  ret = parse_reg_ranges(&info->hide_csr, CMD_ARGV[i], "csr", 0xfff);
4584  if (ret != ERROR_OK)
4585  break;
4586  }
4587 
4588  return ret;
4589 }
4590 
4591 COMMAND_HANDLER(riscv_authdata_read)
4592 {
4593  unsigned int index = 0;
4594  if (CMD_ARGC == 1)
4595  COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], index);
4596  else if (CMD_ARGC != 0)
4598 
4600  if (!target) {
4601  LOG_ERROR("target is NULL!");
4602  return ERROR_FAIL;
4603  }
4604 
4605  RISCV_INFO(r);
4606  if (!r) {
4607  LOG_TARGET_ERROR(target, "riscv_info is NULL!");
4608  return ERROR_FAIL;
4609  }
4610 
4611  if (r->authdata_read) {
4612  uint32_t value;
4613  if (r->authdata_read(target, &value, index) != ERROR_OK)
4614  return ERROR_FAIL;
4615  command_print_sameline(CMD, "0x%08" PRIx32, value);
4616  return ERROR_OK;
4617  }
4618 
4619  LOG_TARGET_ERROR(target, "authdata_read is not implemented for this target.");
4620  return ERROR_FAIL;
4621 }
4622 
4623 COMMAND_HANDLER(riscv_authdata_write)
4624 {
4625  uint32_t value;
4626  unsigned int index = 0;
4627 
4628  if (CMD_ARGC == 0 || CMD_ARGC > 2)
4630 
4631  if (CMD_ARGC == 1) {
4632  COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], value);
4633  } else {
4634  COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], index);
4635  COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
4636  }
4637 
4639  RISCV_INFO(r);
4640 
4641  if (!r->authdata_write) {
4642  LOG_TARGET_ERROR(target, "authdata_write is not implemented for this target.");
4643  return ERROR_FAIL;
4644  }
4645 
4646  return r->authdata_write(target, value, index);
4647 }
4648 
4649 uint32_t riscv_get_dmi_address(const struct target *target, uint32_t dm_address)
4650 {
4651  assert(target);
4652  RISCV_INFO(r);
4653  if (!r || !r->get_dmi_address)
4654  return dm_address;
4655  return r->get_dmi_address(target, dm_address);
4656 }
4657 
4658 static int riscv_dmi_read(struct target *target, uint32_t *value, uint32_t address)
4659 {
4660  if (!target) {
4661  LOG_ERROR("target is NULL!");
4662  return ERROR_FAIL;
4663  }
4664  RISCV_INFO(r);
4665  if (!r) {
4666  LOG_TARGET_ERROR(target, "riscv_info is NULL!");
4667  return ERROR_FAIL;
4668  }
4669  if (!r->dmi_read) {
4670  LOG_TARGET_ERROR(target, "dmi_read is not implemented.");
4671  return ERROR_FAIL;
4672  }
4673  return r->dmi_read(target, value, address);
4674 }
4675 
4676 static int riscv_dmi_write(struct target *target, uint32_t dmi_address, uint32_t value)
4677 {
4678  if (!target) {
4679  LOG_ERROR("target is NULL!");
4680  return ERROR_FAIL;
4681  }
4682  RISCV_INFO(r);
4683  if (!r) {
4684  LOG_TARGET_ERROR(target, "riscv_info is NULL!");
4685  return ERROR_FAIL;
4686  }
4687  if (!r->dmi_write) {
4688  LOG_TARGET_ERROR(target, "dmi_write is not implemented.");
4689  return ERROR_FAIL;
4690  }
4691  const int result = r->dmi_write(target, dmi_address, value);
4692  /* Invalidate our cached progbuf copy:
4693  * - if the user tinkered directly with a progbuf register
4694  * - if debug module was reset, in which case progbuf registers
4695  * may not retain their value.
4696  * FIXME: If there are multiple DMs on a single TAP, it is possible to
4697  * clobber progbuf or reset the DM of another target.
4698  */
4699  const bool progbuf_touched =
4700  (dmi_address >= riscv_get_dmi_address(target, DM_PROGBUF0) &&
4701  dmi_address <= riscv_get_dmi_address(target, DM_PROGBUF15));
4702  const bool dm_deactivated =
4703  (dmi_address == riscv_get_dmi_address(target, DM_DMCONTROL) &&
4704  (value & DM_DMCONTROL_DMACTIVE) == 0);
4705  if (progbuf_touched || dm_deactivated) {
4706  if (r->invalidate_cached_progbuf) {
4707  /* Here the return value of invalidate_cached_progbuf()
4708  * is ignored. It is okay to do so for now, since the
4709  * only case an error is returned is a failure to
4710  * assign a DM to the target, which would have already
4711  * caused an error during dmi_write().
4712  * FIXME: invalidate_cached_progbuf() should be void.
4713  */
4714  r->invalidate_cached_progbuf(target);
4715  } else {
4717  "invalidate_cached_progbuf() is not implemented.");
4718  }
4719  }
4720  return result;
4721 }
4722 
4723 COMMAND_HANDLER(handle_riscv_dmi_read)
4724 {
4725  if (CMD_ARGC != 1)
4727 
4728  uint32_t dmi_address;
4729  COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], dmi_address);
4730 
4731  struct target * const target = get_current_target(CMD_CTX);
4732  uint32_t value;
4733  const int result = riscv_dmi_read(target, &value, dmi_address);
4734  if (result == ERROR_OK)
4735  command_print(CMD, "0x%" PRIx32, value);
4736  return result;
4737 }
4738 
4739 COMMAND_HANDLER(handle_riscv_dmi_write)
4740 {
4741  if (CMD_ARGC != 2)
4743 
4744  uint32_t dmi_address, value;
4745  COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], dmi_address);
4746  COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
4747 
4748  struct target * const target = get_current_target(CMD_CTX);
4749  return riscv_dmi_write(target, dmi_address, value);
4750 }
4751 
4752 COMMAND_HANDLER(handle_riscv_dm_read)
4753 {
4754  if (CMD_ARGC != 1)
4756 
4757  uint32_t dm_address;
4758  COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], dm_address);
4759 
4760  struct target * const target = get_current_target(CMD_CTX);
4761  uint32_t value;
4762  const int result = riscv_dmi_read(target, &value,
4763  riscv_get_dmi_address(target, dm_address));
4764  if (result == ERROR_OK)
4765  command_print(CMD, "0x%" PRIx32, value);
4766  return result;
4767 }
4768 
4769 COMMAND_HANDLER(handle_riscv_dm_write)
4770 {
4771  if (CMD_ARGC != 2)
4773 
4774  uint32_t dm_address, value;
4775  COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], dm_address);
4776  COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
4777 
4778  struct target * const target = get_current_target(CMD_CTX);
4779  return riscv_dmi_write(target, riscv_get_dmi_address(target, dm_address),
4780  value);
4781 }
4782 
4783 COMMAND_HANDLER(riscv_reset_delays)
4784 {
4785  int wait = 0;
4786 
4787  if (CMD_ARGC > 1)
4789 
4790  if (CMD_ARGC == 1)
4791  COMMAND_PARSE_NUMBER(int, CMD_ARGV[0], wait);
4792 
4794  RISCV_INFO(r);
4795  r->reset_delays_wait = wait;
4796  return ERROR_OK;
4797 }
4798 
4799 COMMAND_HANDLER(riscv_set_ir)
4800 {
4801  if (CMD_ARGC != 2)
4803 
4804  uint32_t value;
4805  COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
4806 
4807  if (!strcmp(CMD_ARGV[0], "idcode"))
4808  buf_set_u32(ir_idcode, 0, 32, value);
4809  else if (!strcmp(CMD_ARGV[0], "dtmcs"))
4810  buf_set_u32(ir_dtmcontrol, 0, 32, value);
4811  else if (!strcmp(CMD_ARGV[0], "dmi"))
4812  buf_set_u32(ir_dbus, 0, 32, value);
4813  else
4814  return ERROR_FAIL;
4815 
4816  return ERROR_OK;
4817 }
4818 
4819 COMMAND_HANDLER(riscv_resume_order)
4820 {
4821  if (CMD_ARGC != 1)
4823 
4824  if (!strcmp(CMD_ARGV[0], "normal")) {
4826  } else if (!strcmp(CMD_ARGV[0], "reversed")) {
4828  } else {
4829  LOG_ERROR("Unsupported resume order: %s", CMD_ARGV[0]);
4830  return ERROR_FAIL;
4831  }
4832 
4833  return ERROR_OK;
4834 }
4835 
4836 COMMAND_HANDLER(riscv_use_bscan_tunnel)
4837 {
4838  uint8_t irwidth = 0;
4839  int tunnel_type = BSCAN_TUNNEL_NESTED_TAP;
4840 
4841  if (CMD_ARGC < 1 || CMD_ARGC > 2)
4843 
4844  if (CMD_ARGC >= 1) {
4845  COMMAND_PARSE_NUMBER(u8, CMD_ARGV[0], irwidth);
4846  assert(BSCAN_TUNNEL_IR_WIDTH_NBITS < 8);
4847  if (irwidth >= (uint8_t)1 << BSCAN_TUNNEL_IR_WIDTH_NBITS) {
4848  command_print(CMD, "'value' does not fit into %d bits.",
4851  }
4852  }
4853  if (CMD_ARGC == 2)
4854  COMMAND_PARSE_NUMBER(int, CMD_ARGV[1], tunnel_type);
4855  if (tunnel_type == BSCAN_TUNNEL_NESTED_TAP)
4856  LOG_INFO("Nested Tap based Bscan Tunnel Selected");
4857  else if (tunnel_type == BSCAN_TUNNEL_DATA_REGISTER)
4858  LOG_INFO("Simple Register based Bscan Tunnel Selected");
4859  else
4860  LOG_INFO("Invalid Tunnel type selected ! : selecting default Nested Tap Type");
4861 
4862  bscan_tunnel_type = tunnel_type;
4863  bscan_tunnel_ir_width = irwidth;
4864  return ERROR_OK;
4865 }
4866 
4867 COMMAND_HANDLER(riscv_set_bscan_tunnel_ir)
4868 {
4869  int ir_id = 0;
4870 
4871  if (CMD_ARGC > 1)
4873 
4874  if (CMD_ARGC == 1)
4875  COMMAND_PARSE_NUMBER(int, CMD_ARGV[0], ir_id);
4876 
4877  LOG_INFO("Bscan tunnel IR 0x%x selected", ir_id);
4878 
4879  bscan_tunnel_ir_id = ir_id;
4880  return ERROR_OK;
4881 }
4882 
4883 COMMAND_HANDLER(riscv_set_maskisr)
4884 {
4886  RISCV_INFO(info);
4887 
4888  static const struct jim_nvp nvp_maskisr_modes[] = {
4889  { .name = "off", .value = RISCV_ISRMASK_OFF },
4890  { .name = "steponly", .value = RISCV_ISRMASK_STEPONLY },
4891  { .name = NULL, .value = -1 },
4892  };
4893  const struct jim_nvp *n;
4894 
4895  if (CMD_ARGC > 0) {
4896  n = jim_nvp_name2value_simple(nvp_maskisr_modes, CMD_ARGV[0]);
4897  if (!n->name)
4899  info->isrmask_mode = n->value;
4900  } else {
4901  n = jim_nvp_value2name_simple(nvp_maskisr_modes, info->isrmask_mode);
4902  command_print(CMD, "riscv interrupt mask %s", n->name);
4903  }
4904 
4905  return ERROR_OK;
4906 }
4907 
4908 COMMAND_HANDLER(riscv_set_autofence)
4909 {
4911  RISCV_INFO(r);
4912 
4913  if (CMD_ARGC == 0) {
4914  command_print(CMD, "autofence: %s", r->autofence ? "on" : "off");
4915  return ERROR_OK;
4916  } else if (CMD_ARGC == 1) {
4917  COMMAND_PARSE_ON_OFF(CMD_ARGV[0], r->autofence);
4918  return ERROR_OK;
4919  }
4920 
4922 }
4923 
4924 COMMAND_HELPER(ebreakx_deprecation_helper, enum riscv_priv_mode mode)
4925 {
4926  struct target * const target = get_current_target(CMD_CTX);
4928  const char *mode_str;
4929  switch (mode) {
4930  case RISCV_MODE_M:
4931  mode_str = "m";
4932  break;
4933  case RISCV_MODE_S:
4934  mode_str = "s";
4935  break;
4936  case RISCV_MODE_U:
4937  mode_str = "u";
4938  break;
4939  default:
4940  assert(0 && "Unexpected execution mode");
4941  mode_str = "unexpected";
4942  }
4943  if (CMD_ARGC > 1)
4945  if (CMD_ARGC == 0) {
4946  LOG_WARNING("DEPRECATED! use '%s cget -ebreak' not '%s'",
4948  command_print(CMD, "riscv_ebreak%s enabled: %s", mode_str,
4949  config->dcsr_ebreak_fields[mode] ? "on" : "off");
4950  return ERROR_OK;
4951  }
4952  assert(CMD_ARGC == 1);
4953  command_print(CMD, "DEPRECATED! use '%s configure -ebreak %s' not '%s'",
4954  target_name(target), mode_str, CMD_NAME);
4955  bool ebreak_ctl;
4956  COMMAND_PARSE_ON_OFF(CMD_ARGV[0], ebreak_ctl);
4957  config->dcsr_ebreak_fields[mode] = ebreak_ctl;
4958  switch (mode) {
4959  case RISCV_MODE_S:
4960  config->dcsr_ebreak_fields[RISCV_MODE_VS] = ebreak_ctl;
4961  break;
4962  case RISCV_MODE_U:
4963  config->dcsr_ebreak_fields[RISCV_MODE_VU] = ebreak_ctl;
4964  break;
4965  default:
4966  break;
4967  }
4968  return ERROR_OK;
4969 }
4970 
4971 COMMAND_HANDLER(riscv_set_ebreakm)
4972 {
4973  return CALL_COMMAND_HANDLER(ebreakx_deprecation_helper,
4974  RISCV_MODE_M);
4975 }
4976 
4977 COMMAND_HANDLER(riscv_set_ebreaks)
4978 {
4979  return CALL_COMMAND_HANDLER(ebreakx_deprecation_helper,
4980  RISCV_MODE_S);
4981 }
4982 
4983 COMMAND_HANDLER(riscv_set_ebreaku)
4984 {
4985  return CALL_COMMAND_HANDLER(ebreakx_deprecation_helper,
4986  RISCV_MODE_U);
4987 }
4988 
4989 COMMAND_HELPER(riscv_clear_trigger, int trigger_id, const char *name)
4990 {
4992  if (CMD_ARGC != 1)
4994 
4995  if (find_first_trigger_by_id(target, trigger_id) < 0) {
4996  LOG_TARGET_ERROR(target, "No %s is set. Nothing to clear.", name);
4997  return ERROR_FAIL;
4998  }
4999  return remove_trigger(target, trigger_id);
5000 }
5001 
5002 COMMAND_HANDLER(riscv_itrigger)
5003 {
5004  if (CMD_ARGC < 1)
5006 
5008  const int ITRIGGER_UNIQUE_ID = -CSR_TDATA1_TYPE_ITRIGGER;
5009 
5011  return ERROR_FAIL;
5012 
5013  if (!strcmp(CMD_ARGV[0], "set")) {
5014  if (find_first_trigger_by_id(target, ITRIGGER_UNIQUE_ID) >= 0) {
5015  LOG_TARGET_ERROR(target, "An itrigger is already set, and OpenOCD "
5016  "doesn't support setting more than one at a time.");
5017  return ERROR_FAIL;
5018  }
5019  bool vs = false;
5020  bool vu = false;
5021  bool nmi = false;
5022  bool m = false;
5023  bool s = false;
5024  bool u = false;
5025  riscv_reg_t interrupts = 0;
5026 
5027  for (unsigned int i = 1; i < CMD_ARGC; i++) {
5028  if (!strcmp(CMD_ARGV[i], "vs"))
5029  vs = true;
5030  else if (!strcmp(CMD_ARGV[i], "vu"))
5031  vu = true;
5032  else if (!strcmp(CMD_ARGV[i], "nmi"))
5033  nmi = true;
5034  else if (!strcmp(CMD_ARGV[i], "m"))
5035  m = true;
5036  else if (!strcmp(CMD_ARGV[i], "s"))
5037  s = true;
5038  else if (!strcmp(CMD_ARGV[i], "u"))
5039  u = true;
5040  else
5041  COMMAND_PARSE_NUMBER(u64, CMD_ARGV[i], interrupts);
5042  }
5043  if (!nmi && interrupts == 0) {
5044  LOG_ERROR("Doesn't make sense to set itrigger with "
5045  "mie_bits=0 and without nmi.");
5046  return ERROR_FAIL;
5047  } else if (!vs && !vu && !m && !s && !u) {
5048  LOG_ERROR("Doesn't make sense to set itrigger without at "
5049  "least one of vs, vu, m, s, or u.");
5050  return ERROR_FAIL;
5051  }
5052  int result = maybe_add_trigger_t4(target, vs, vu, nmi, m, s, u, interrupts, ITRIGGER_UNIQUE_ID);
5053  if (result != ERROR_OK)
5054  LOG_TARGET_ERROR(target, "Failed to set requested itrigger.");
5055  return result;
5056 
5057  } else if (!strcmp(CMD_ARGV[0], "clear")) {
5058  return riscv_clear_trigger(CMD, ITRIGGER_UNIQUE_ID, "itrigger");
5059 
5060  } else {
5061  LOG_ERROR("First argument must be either 'set' or 'clear'.");
5063  }
5064  return ERROR_OK;
5065 }
5066 
5067 COMMAND_HANDLER(riscv_icount)
5068 {
5069  if (CMD_ARGC < 1)
5071 
5073  const int ICOUNT_UNIQUE_ID = -CSR_TDATA1_TYPE_ICOUNT;
5074 
5076  return ERROR_FAIL;
5077 
5078  if (!strcmp(CMD_ARGV[0], "set")) {
5079  if (find_first_trigger_by_id(target, ICOUNT_UNIQUE_ID) >= 0) {
5080  LOG_TARGET_ERROR(target, "An icount trigger is already set, and OpenOCD "
5081  "doesn't support setting more than one at a time.");
5082  return ERROR_FAIL;
5083  }
5084  bool vs = false;
5085  bool vu = false;
5086  bool m = false;
5087  bool s = false;
5088  bool u = false;
5089  bool pending = false;
5090  unsigned int count = 0;
5091 
5092  for (unsigned int i = 1; i < CMD_ARGC; i++) {
5093  if (!strcmp(CMD_ARGV[i], "vs"))
5094  vs = true;
5095  else if (!strcmp(CMD_ARGV[i], "vu"))
5096  vu = true;
5097  else if (!strcmp(CMD_ARGV[i], "pending"))
5098  pending = true;
5099  else if (!strcmp(CMD_ARGV[i], "m"))
5100  m = true;
5101  else if (!strcmp(CMD_ARGV[i], "s"))
5102  s = true;
5103  else if (!strcmp(CMD_ARGV[i], "u"))
5104  u = true;
5105  else
5106  COMMAND_PARSE_NUMBER(uint, CMD_ARGV[i], count);
5107  }
5108  if (count == 0) {
5109  LOG_ERROR("Doesn't make sense to set icount trigger with "
5110  "count=0.");
5111  return ERROR_FAIL;
5112  } else if (!vs && !vu && !m && !s && !u) {
5113  LOG_ERROR("Doesn't make sense to set itrigger without at "
5114  "least one of vs, vu, m, s, or u.");
5115  return ERROR_FAIL;
5116  }
5117  int result = maybe_add_trigger_t3(target, vs, vu, m, s, u, pending, count, ICOUNT_UNIQUE_ID);
5118  if (result != ERROR_OK)
5119  LOG_TARGET_ERROR(target, "Failed to set requested icount trigger.");
5120  return result;
5121 
5122  } else if (!strcmp(CMD_ARGV[0], "clear")) {
5123  return riscv_clear_trigger(CMD, ICOUNT_UNIQUE_ID, "icount trigger");
5124 
5125  } else {
5126  LOG_ERROR("First argument must be either 'set' or 'clear'.");
5128  }
5129  return ERROR_OK;
5130 }
5131 
5132 COMMAND_HANDLER(riscv_etrigger)
5133 {
5134  if (CMD_ARGC < 1)
5136 
5138  const int ETRIGGER_UNIQUE_ID = -CSR_TDATA1_TYPE_ETRIGGER;
5139 
5141  return ERROR_FAIL;
5142 
5143  if (!strcmp(CMD_ARGV[0], "set")) {
5144  if (find_first_trigger_by_id(target, ETRIGGER_UNIQUE_ID) >= 0) {
5145  LOG_TARGET_ERROR(target, "An etrigger is already set, and OpenOCD "
5146  "doesn't support setting more than one at a time.");
5147  return ERROR_FAIL;
5148  }
5149  bool vs = false;
5150  bool vu = false;
5151  bool m = false;
5152  bool s = false;
5153  bool u = false;
5154  riscv_reg_t exception_codes = 0;
5155 
5156  for (unsigned int i = 1; i < CMD_ARGC; i++) {
5157  if (!strcmp(CMD_ARGV[i], "vs"))
5158  vs = true;
5159  else if (!strcmp(CMD_ARGV[i], "vu"))
5160  vu = true;
5161  else if (!strcmp(CMD_ARGV[i], "m"))
5162  m = true;
5163  else if (!strcmp(CMD_ARGV[i], "s"))
5164  s = true;
5165  else if (!strcmp(CMD_ARGV[i], "u"))
5166  u = true;
5167  else
5168  COMMAND_PARSE_NUMBER(u64, CMD_ARGV[i], exception_codes);
5169  }
5170  if (exception_codes == 0) {
5171  LOG_ERROR("Doesn't make sense to set etrigger with "
5172  "exception_codes=0.");
5173  return ERROR_FAIL;
5174  } else if (!vs && !vu && !m && !s && !u) {
5175  LOG_ERROR("Doesn't make sense to set etrigger without at "
5176  "least one of vs, vu, m, s, or u.");
5177  return ERROR_FAIL;
5178  }
5179  int result = maybe_add_trigger_t5(target, vs, vu, m, s, u, exception_codes, ETRIGGER_UNIQUE_ID);
5180  if (result != ERROR_OK)
5181  LOG_TARGET_ERROR(target, "Failed to set requested etrigger.");
5182  return result;
5183 
5184  } else if (!strcmp(CMD_ARGV[0], "clear")) {
5185  return riscv_clear_trigger(CMD, ETRIGGER_UNIQUE_ID, "etrigger");
5186 
5187  } else {
5188  LOG_ERROR("First argument must be either 'set' or 'clear'.");
5190  }
5191  return ERROR_OK;
5192 }
5193 
5194 COMMAND_HANDLER(handle_repeat_read)
5195 {
5197  RISCV_INFO(r);
5198 
5199  if (CMD_ARGC < 2 || CMD_ARGC > 3)
5201 
5202  uint32_t count;
5206  uint32_t size = 4;
5207  if (CMD_ARGC > 2)
5209 
5210  if (count == 0)
5211  return ERROR_OK;
5212 
5213  uint8_t *buffer = malloc(size * count);
5214  if (!buffer) {
5215  LOG_ERROR("malloc failed");
5216  return ERROR_FAIL;
5217  }
5218  const struct riscv_mem_access_args args = {
5219  .address = address,
5220  .read_buffer = buffer,
5221  .size = size,
5222  .count = count,
5223  .increment = 0,
5224  };
5225  int result = r->access_memory(target, args);
5226  if (result == ERROR_OK)
5228  free(buffer);
5229  return result;
5230 }
5231 
5232 COMMAND_HANDLER(handle_memory_sample_command)
5233 {
5235  RISCV_INFO(r);
5236 
5237  if (CMD_ARGC == 0) {
5238  command_print(CMD, "Memory sample configuration for %s:", target_name(target));
5239  for (unsigned int i = 0; i < ARRAY_SIZE(r->sample_config.bucket); i++) {
5240  if (r->sample_config.bucket[i].enabled) {
5241  command_print(CMD, "bucket %d; address=0x%" TARGET_PRIxADDR "; size=%d", i,
5242  r->sample_config.bucket[i].address,
5243  r->sample_config.bucket[i].size_bytes);
5244  } else {
5245  command_print(CMD, "bucket %d; disabled", i);
5246  }
5247  }
5248  return ERROR_OK;
5249  }
5250 
5251  if (CMD_ARGC < 2)
5253 
5254  uint32_t bucket;
5255  COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], bucket);
5256  if (bucket > ARRAY_SIZE(r->sample_config.bucket)) {
5257  LOG_TARGET_ERROR(target, "Max bucket number is %zd.", ARRAY_SIZE(r->sample_config.bucket));
5259  }
5260 
5261  if (!strcmp(CMD_ARGV[1], "clear")) {
5262  r->sample_config.bucket[bucket].enabled = false;
5263  } else {
5264  COMMAND_PARSE_ADDRESS(CMD_ARGV[1], r->sample_config.bucket[bucket].address);
5265 
5266  if (CMD_ARGC > 2) {
5267  COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], r->sample_config.bucket[bucket].size_bytes);
5268  if (r->sample_config.bucket[bucket].size_bytes != 4 &&
5269  r->sample_config.bucket[bucket].size_bytes != 8) {
5270  LOG_TARGET_ERROR(target, "Only 4-byte and 8-byte sizes are supported.");
5272  }
5273  } else {
5274  r->sample_config.bucket[bucket].size_bytes = 4;
5275  }
5276 
5277  r->sample_config.bucket[bucket].enabled = true;
5278  }
5279 
5280  if (!r->sample_buf.buf) {
5281  r->sample_buf.size = 1024 * 1024;
5282  r->sample_buf.buf = malloc(r->sample_buf.size);
5283  }
5284 
5285  /* Clear the buffer when the configuration is changed. */
5286  r->sample_buf.used = 0;
5287 
5288  r->sample_config.enabled = true;
5289 
5290  return ERROR_OK;
5291 }
5292 
5293 COMMAND_HANDLER(handle_dump_sample_buf_command)
5294 {
5296  RISCV_INFO(r);
5297 
5298  if (CMD_ARGC > 1)
5300 
5301  bool base64 = false;
5302  if (CMD_ARGC > 0) {
5303  if (!strcmp(CMD_ARGV[0], "base64")) {
5304  base64 = true;
5305  } else {
5306  LOG_ERROR("Unknown argument: %s", CMD_ARGV[0]);
5308  }
5309  }
5310 
5311  int result = ERROR_OK;
5312  if (base64) {
5313  unsigned char *encoded = base64_encode(r->sample_buf.buf,
5314  r->sample_buf.used, NULL);
5315  if (!encoded) {
5316  LOG_TARGET_ERROR(target, "Failed base64 encode!");
5317  result = ERROR_FAIL;
5318  goto error;
5319  }
5320  command_print(CMD, "%s", encoded);
5321  free(encoded);
5322  } else {
5323  unsigned int i = 0;
5324  while (i < r->sample_buf.used) {
5325  uint8_t command = r->sample_buf.buf[i++];
5327  uint32_t timestamp = buf_get_u32(r->sample_buf.buf + i, 0, 32);
5328  i += 4;
5329  command_print(CMD, "timestamp before: %u", timestamp);
5330  } else if (command == RISCV_SAMPLE_BUF_TIMESTAMP_AFTER) {
5331  uint32_t timestamp = buf_get_u32(r->sample_buf.buf + i, 0, 32);
5332  i += 4;
5333  command_print(CMD, "timestamp after: %u", timestamp);
5334  } else if (command < ARRAY_SIZE(r->sample_config.bucket)) {
5336  r->sample_config.bucket[command].address);
5337  if (r->sample_config.bucket[command].size_bytes == 4) {
5338  uint32_t value = buf_get_u32(r->sample_buf.buf + i, 0, 32);
5339  i += 4;
5340  command_print(CMD, "0x%08" PRIx32, value);
5341  } else if (r->sample_config.bucket[command].size_bytes == 8) {
5342  uint64_t value = buf_get_u64(r->sample_buf.buf + i, 0, 64);
5343  i += 8;
5344  command_print(CMD, "0x%016" PRIx64, value);
5345  } else {
5346  LOG_TARGET_ERROR(target, "Found invalid size in bucket %d: %d", command,
5347  r->sample_config.bucket[command].size_bytes);
5348  result = ERROR_FAIL;
5349  goto error;
5350  }
5351  } else {
5352  LOG_TARGET_ERROR(target, "Found invalid command byte in sample buf: 0x%2x at offset 0x%x",
5353  command, i - 1);
5354  result = ERROR_FAIL;
5355  goto error;
5356  }
5357  }
5358  }
5359 
5360 error:
5361  /* Clear the sample buffer even when there was an error. */
5362  r->sample_buf.used = 0;
5363  return result;
5364 }
5365 
5366 static COMMAND_HELPER(riscv_print_info_line_if_available, const char *section,
5367  const char *key, unsigned int value, bool is_available)
5368 {
5369  char full_key[80];
5370  snprintf(full_key, sizeof(full_key), "%s.%s", section, key);
5371  if (is_available)
5372  command_print(CMD, "%-21s %3d", full_key, value);
5373  else
5374  command_print(CMD, "%-21s unavailable", full_key);
5375  return 0;
5376 }
5377 
5378 COMMAND_HELPER(riscv_print_info_line, const char *section, const char *key,
5379  unsigned int value)
5380 {
5381  return CALL_COMMAND_HANDLER(riscv_print_info_line_if_available, section,
5382  key, value, /*is_available*/ true);
5383 }
5384 
5385 COMMAND_HANDLER(handle_info)
5386 {
5388  RISCV_INFO(r);
5389 
5390  /* This output format can be fed directly into TCL's "array set". */
5391 
5392  riscv_print_info_line(CMD, "hart", "xlen", riscv_xlen(target));
5393 
5394  const bool trigger_count_available =
5396  riscv_print_info_line_if_available(CMD, "hart", "trigger_count",
5397  r->trigger_count, trigger_count_available);
5398  if (r->print_info)
5399  return CALL_COMMAND_HANDLER(r->print_info, target);
5400 
5401  return 0;
5402 }
5403 
5404 COMMAND_HANDLER(riscv_exec_progbuf)
5405 {
5406  if (CMD_ARGC < 1 || CMD_ARGC > 16)
5408 
5410 
5411  RISCV_INFO(r);
5412  if (r->dtm_version != DTM_DTMCS_VERSION_1_0) {
5413  LOG_TARGET_ERROR(target, "exec_progbuf: Program buffer is "
5414  "only supported on v0.13 or v1.0 targets.");
5415  return ERROR_FAIL;
5416  }
5417 
5418  if (target->state != TARGET_HALTED) {
5419  LOG_TARGET_ERROR(target, "exec_progbuf: Can't execute "
5420  "program buffer, target not halted.");
5421  return ERROR_TARGET_NOT_HALTED;
5422  }
5423 
5424  if (riscv_progbuf_size(target) == 0) {
5425  LOG_TARGET_ERROR(target, "exec_progbuf: Program buffer not implemented "
5426  "in the target.");
5427  return ERROR_FAIL;
5428  }
5429 
5430  struct riscv_program prog;
5431  riscv_program_init(&prog, target);
5432 
5433  for (unsigned int i = 0; i < CMD_ARGC; i++) {
5434  riscv_insn_t instr;
5435  COMMAND_PARSE_NUMBER(u32, CMD_ARGV[i], instr);
5436  if (riscv_program_insert(&prog, instr) != ERROR_OK)
5437  return ERROR_FAIL;
5438  }
5439 
5441  return ERROR_FAIL;
5442  int error = riscv_program_exec(&prog, target);
5444 
5445  if (error != ERROR_OK) {
5446  LOG_TARGET_ERROR(target, "exec_progbuf: Program buffer execution failed.");
5447  return ERROR_FAIL;
5448  }
5449 
5450  LOG_TARGET_DEBUG(target, "exec_progbuf: Program buffer execution successful.");
5451 
5452  return ERROR_OK;
5453 }
5454 
5455 COMMAND_HANDLER(riscv_set_enable_trigger_feature)
5456 {
5458  RISCV_INFO(r);
5459 
5460  if (CMD_ARGC == 2) {
5461  bool enable_for_wp = true;
5462 
5463  if (!strcmp(CMD_ARGV[1], "wp"))
5464  enable_for_wp = true;
5465  else if (!strcmp(CMD_ARGV[1], "none"))
5466  enable_for_wp = false;
5467  else
5469 
5470  if (!strcmp(CMD_ARGV[0], "all")) {
5471  r->wp_allow_equality_match_trigger = enable_for_wp;
5472  r->wp_allow_napot_trigger = enable_for_wp;
5473  r->wp_allow_ge_lt_trigger = enable_for_wp;
5474  } else if (!strcmp(CMD_ARGV[0], "eq")) {
5475  r->wp_allow_equality_match_trigger = enable_for_wp;
5476  } else if (!strcmp(CMD_ARGV[0], "napot")) {
5477  r->wp_allow_napot_trigger = enable_for_wp;
5478  } else if (!strcmp(CMD_ARGV[0], "ge_lt")) {
5479  r->wp_allow_ge_lt_trigger = enable_for_wp;
5480  } else {
5482  }
5483  } else if (CMD_ARGC != 0) {
5485  }
5486 
5487  command_print(CMD, "Triggers feature configuration:\n"
5488  "Equality match trigger: for wp (%s)\n"
5489  "NAPOT trigger: for wp (%s)\n"
5490  "ge-lt chained triggers: for wp (%s)",
5491  r->wp_allow_equality_match_trigger ? "enabled" : "disabled",
5492  r->wp_allow_napot_trigger ? "enabled" : "disabled",
5493  r->wp_allow_ge_lt_trigger ? "enabled" : "disabled");
5494 
5495  return ERROR_OK;
5496 }
5497 
5498 static COMMAND_HELPER(report_reserved_triggers, struct target *target)
5499 {
5500  RISCV_INFO(r);
5502  return ERROR_FAIL;
5503  const char *separator = "";
5504  for (riscv_reg_t t = 0; t < r->trigger_count; ++t) {
5505  if (r->reserved_triggers[t]) {
5506  command_print_sameline(CMD, "%s%" PRIu64, separator, t);
5507  separator = " ";
5508  }
5509  }
5510  command_print_sameline(CMD, "\n");
5511  return ERROR_OK;
5512 }
5513 
5514 COMMAND_HANDLER(handle_reserve_trigger)
5515 {
5517  if (CMD_ARGC == 0)
5518  return CALL_COMMAND_HANDLER(report_reserved_triggers, target);
5519 
5520  if (CMD_ARGC != 2)
5522 
5523  riscv_reg_t t;
5524  COMMAND_PARSE_NUMBER(u64, CMD_ARGV[0], t);
5525 
5527  return ERROR_FAIL;
5528  RISCV_INFO(r);
5529  if (r->trigger_count == 0) {
5530  command_print(CMD, "Error: There are no triggers on the target.");
5532  }
5533  if (t >= r->trigger_count) {
5534  command_print(CMD, "Error: trigger with index %" PRIu64
5535  " does not exist. There are only %u triggers"
5536  " on the target (with indexes 0 .. %u).",
5537  t, r->trigger_count, r->trigger_count - 1);
5539  }
5540  if (r->trigger_unique_id[t] != -1) {
5541  command_print(CMD, "Error: trigger with index %" PRIu64
5542  " is already in use and can not be reserved.", t);
5544  }
5545  COMMAND_PARSE_ON_OFF(CMD_ARGV[1], r->reserved_triggers[t]);
5546  return ERROR_OK;
5547 }
5548 
5549 COMMAND_HANDLER(handle_riscv_virt2phys_mode)
5550 {
5552  if (CMD_ARGC == 0) {
5553  enum riscv_virt2phys_mode mode = info->virt2phys_mode;
5555  return ERROR_OK;
5556  }
5557 
5558  if (CMD_ARGC != 1)
5560 
5561  // TODO: add auto mode to allow OpenOCD choose translation mode
5562  if (!strcmp(CMD_ARGV[0],
5564  info->virt2phys_mode = RISCV_VIRT2PHYS_MODE_SW;
5565  } else if (!strcmp(CMD_ARGV[0],
5567  info->virt2phys_mode = RISCV_VIRT2PHYS_MODE_HW;
5568  } else if (!strcmp(CMD_ARGV[0],
5570  info->virt2phys_mode = RISCV_VIRT2PHYS_MODE_OFF;
5571  } else {
5572  command_print(CMD, "Unsupported address translation mode: %s", CMD_ARGV[0]);
5574  }
5575 
5576  return ERROR_OK;
5577 }
5578 
5579 static const struct command_registration riscv_exec_command_handlers[] = {
5580  {
5581  .name = "dump_sample_buf",
5582  .handler = handle_dump_sample_buf_command,
5583  .mode = COMMAND_ANY,
5584  .usage = "[base64]",
5585  .help = "Print the contents of the sample buffer, and clear the buffer."
5586  },
5587  {
5588  .name = "info",
5589  .handler = handle_info,
5590  .mode = COMMAND_ANY,
5591  .usage = "",
5592  .help = "Displays some information OpenOCD detected about the target."
5593  },
5594  {
5595  .name = "memory_sample",
5596  .handler = handle_memory_sample_command,
5597  .mode = COMMAND_ANY,
5598  .usage = "bucket address|clear [size=4]",
5599  .help = "Causes OpenOCD to frequently read size bytes at the given address."
5600  },
5601  {
5602  .name = "repeat_read",
5603  .handler = handle_repeat_read,
5604  .mode = COMMAND_ANY,
5605  .usage = "count address [size=4]",
5606  .help = "Repeatedly read the value at address."
5607  },
5608  {
5609  .name = "set_command_timeout_sec",
5610  .handler = riscv_set_command_timeout_sec,
5611  .mode = COMMAND_ANY,
5612  .usage = "sec",
5613  .help = "Set the wall-clock timeout (in seconds) for individual commands"
5614  },
5615  {
5616  .name = "set_reset_timeout_sec",
5617  .handler = riscv_set_reset_timeout_sec,
5618  .mode = COMMAND_ANY,
5619  .usage = "sec",
5620  .help = "DEPRECATED. Use 'riscv set_command_timeout_sec' instead."
5621  },
5622  {
5623  .name = "set_mem_access",
5624  .handler = riscv_set_mem_access,
5625  .mode = COMMAND_ANY,
5626  .usage = "method1 [method2] [method3]",
5627  .help = "Set which memory access methods shall be used and in which order "
5628  "of priority. Method can be one of: 'progbuf', 'sysbus' or 'abstract'."
5629  },
5630  {
5631  .name = "expose_csrs",
5632  .handler = riscv_set_expose_csrs,
5633  .mode = COMMAND_CONFIG,
5634  .usage = "n0[-m0|=name0][,n1[-m1|=name1]]...[,n15[-m15|=name15]]",
5635  .help = "Configure a list of inclusive ranges for CSRs to expose in "
5636  "addition to the standard ones. This must be executed before "
5637  "`init`."
5638  },
5639  {
5640  .name = "expose_custom",
5641  .handler = riscv_set_expose_custom,
5642  .mode = COMMAND_CONFIG,
5643  .usage = "n0[-m0|=name0][,n1[-m1|=name1]]...[,n15[-m15|=name15]]",
5644  .help = "Configure a list of inclusive ranges for custom registers to "
5645  "expose. custom0 is accessed as abstract register number 0xc000, "
5646  "etc. This must be executed before `init`."
5647  },
5648  {
5649  .name = "hide_csrs",
5650  .handler = riscv_hide_csrs,
5651  .mode = COMMAND_CONFIG,
5652  .usage = "{n0|n-m0}[,n1|n-m1]......",
5653  .help = "Configure a list of inclusive ranges for CSRs to hide from gdb. "
5654  "Hidden registers are still available, but are not listed in "
5655  "gdb target description and `reg` command output. "
5656  "This must be executed before `init`."
5657  },
5658  {
5659  .name = "authdata_read",
5660  .handler = riscv_authdata_read,
5661  .usage = "[index]",
5662  .mode = COMMAND_ANY,
5663  .help = "Return the 32-bit value read from authdata or authdata0 "
5664  "(index=0), or authdata1 (index=1)."
5665  },
5666  {
5667  .name = "authdata_write",
5668  .handler = riscv_authdata_write,
5669  .mode = COMMAND_ANY,
5670  .usage = "[index] value",
5671  .help = "Write the 32-bit value to authdata or authdata0 (index=0), "
5672  "or authdata1 (index=1)."
5673  },
5674  {
5675  .name = "dmi_read",
5676  .handler = handle_riscv_dmi_read,
5677  .mode = COMMAND_ANY,
5678  .usage = "address",
5679  .help = "Read and return 32-bit value from the given address on the "
5680  "RISC-V DMI bus."
5681  },
5682  {
5683  .name = "dmi_write",
5684  .handler = handle_riscv_dmi_write,
5685  .mode = COMMAND_ANY,
5686  .usage = "address value",
5687  .help = "Write a 32-bit value to the given address on the RISC-V DMI bus."
5688  },
5689  {
5690  .name = "dm_read",
5691  .handler = handle_riscv_dm_read,
5692  .mode = COMMAND_ANY,
5693  .usage = "reg_address",
5694  .help = "Read and return 32-bit value from a debug module's register "
5695  "at reg_address."
5696  },
5697  {
5698  .name = "dm_write",
5699  .handler = handle_riscv_dm_write,
5700  .mode = COMMAND_ANY,
5701  .usage = "reg_address value",
5702  .help = "Write a 32-bit value to the debug module's register at "
5703  "reg_address."
5704  },
5705  {
5706  .name = "reset_delays",
5707  .handler = riscv_reset_delays,
5708  .mode = COMMAND_ANY,
5709  .usage = "[wait]",
5710  .help = "OpenOCD learns how many Run-Test/Idle cycles are required "
5711  "between scans to avoid encountering the target being busy. This "
5712  "command resets those learned values after `wait` scans. It's only "
5713  "useful for testing OpenOCD itself."
5714  },
5715  {
5716  .name = "resume_order",
5717  .handler = riscv_resume_order,
5718  .mode = COMMAND_ANY,
5719  .usage = "normal|reversed",
5720  .help = "Choose the order that harts are resumed in when `hasel` is not "
5721  "supported. Normal order is from lowest hart index to highest. "
5722  "Reversed order is from highest hart index to lowest."
5723  },
5724  {
5725  .name = "set_ir",
5726  .handler = riscv_set_ir,
5727  .mode = COMMAND_ANY,
5728  .usage = "idcode|dtmcs|dmi value",
5729  .help = "Set IR value for specified JTAG register."
5730  },
5731  {
5732  .name = "use_bscan_tunnel",
5733  .handler = riscv_use_bscan_tunnel,
5734  .mode = COMMAND_CONFIG,
5735  .usage = "value [type]",
5736  .help = "Enable or disable use of a BSCAN tunnel to reach DM."
5737  },
5738  {
5739  .name = "set_bscan_tunnel_ir",
5740  .handler = riscv_set_bscan_tunnel_ir,
5741  .mode = COMMAND_CONFIG,
5742  .usage = "[value]",
5743  .help = "Specify the JTAG TAP IR used to access the bscan tunnel. "
5744  "By default it is 0x23 << (ir_length - 6), which map some "
5745  "Xilinx FPGA (IR USER4)"
5746  },
5747  {
5748  .name = "set_maskisr",
5749  .handler = riscv_set_maskisr,
5750  .mode = COMMAND_EXEC,
5751  .help = "mask riscv interrupts",
5752  .usage = "['off'|'steponly']",
5753  },
5754  {
5755  .name = "set_ebreakm",
5756  .handler = riscv_set_ebreakm,
5757  .mode = COMMAND_ANY,
5758  .usage = "[on|off]",
5759  .help = "DEPRECATED! use '<target_name> configure -ebreak' or "
5760  "'<target_name> cget -ebreak'"
5761  },
5762  {
5763  .name = "set_ebreaks",
5764  .handler = riscv_set_ebreaks,
5765  .mode = COMMAND_ANY,
5766  .usage = "[on|off]",
5767  .help = "DEPRECATED! use '<target_name> configure -ebreak' or "
5768  "'<target_name> cget -ebreak'"
5769  },
5770  {
5771  .name = "set_ebreaku",
5772  .handler = riscv_set_ebreaku,
5773  .mode = COMMAND_ANY,
5774  .usage = "[on|off]",
5775  .help = "DEPRECATED! use '<target_name> configure -ebreak' or "
5776  "'<target_name> cget -ebreak'"
5777  },
5778  {
5779  .name = "etrigger",
5780  .handler = riscv_etrigger,
5781  .mode = COMMAND_EXEC,
5782  .usage = "set [vs] [vu] [m] [s] [u] <exception_codes>|clear",
5783  .help = "Set or clear a single exception trigger."
5784  },
5785  {
5786  .name = "icount",
5787  .handler = riscv_icount,
5788  .mode = COMMAND_EXEC,
5789  .usage = "set [vs] [vu] [m] [s] [u] [pending] <count>|clear",
5790  .help = "Set or clear a single instruction count trigger."
5791  },
5792  {
5793  .name = "itrigger",
5794  .handler = riscv_itrigger,
5795  .mode = COMMAND_EXEC,
5796  .usage = "set [vs] [vu] [nmi] [m] [s] [u] <mie_bits>|clear",
5797  .help = "Set or clear a single interrupt trigger."
5798  },
5799  {
5800  .name = "exec_progbuf",
5801  .handler = riscv_exec_progbuf,
5802  .mode = COMMAND_EXEC,
5803  .usage = "instr1 [instr2 [... instr16]]",
5804  .help = "Execute a sequence of 32-bit instructions using the program buffer. "
5805  "The final ebreak instruction is added automatically, if needed."
5806  },
5807  {
5808  .name = "set_enable_trigger_feature",
5809  .handler = riscv_set_enable_trigger_feature,
5810  .mode = COMMAND_ANY,
5811  .usage = "[('eq'|'napot'|'ge_lt'|'all') ('wp'|'none')]",
5812  .help = "Control whether OpenOCD is allowed to use certain RISC-V trigger features for watchpoints."
5813  },
5814  {
5815  .name = "reserve_trigger",
5816  .handler = handle_reserve_trigger,
5817  /* TODO: Move this to COMMAND_ANY */
5818  .mode = COMMAND_EXEC,
5819  .usage = "[index ('on'|'off')]",
5820  .help = "Controls which RISC-V triggers shall not be touched by OpenOCD.",
5821  },
5822  {
5823  .name = "virt2phys_mode",
5824  .handler = handle_riscv_virt2phys_mode,
5825  .mode = COMMAND_ANY,
5826  .usage = "['sw'|'hw'|'off']",
5827  .help = "Configure the virtual address translation mode: "
5828  "sw - translate vaddr to paddr by manually traversing page tables, "
5829  "hw - translate vaddr to paddr by hardware, "
5830  "off - no address translation."
5831  },
5832  {
5833  .name = "autofence",
5834  .handler = riscv_set_autofence,
5835  .mode = COMMAND_ANY,
5836  .usage = "[on|off]",
5837  .help = "When on (default), OpenOCD will automatically execute fence instructions in some situations. "
5838  "When off, users need to take care of memory coherency themselves, for example by using "
5839  "`riscv exec_progbuf` to execute fence or CMO instructions."
5840  },
5841  {
5842  .chain = smp_command_handlers
5843  },
5845 };
5846 
5847 /*
5848  * To be noted that RISC-V targets use the same semihosting commands as
5849  * ARM targets.
5850  *
5851  * The main reason is compatibility with existing tools. For example the
5852  * Eclipse OpenOCD/SEGGER J-Link/QEMU plug-ins have several widgets to
5853  * configure semihosting, which generate commands like `arm semihosting
5854  * enable`.
5855  * A secondary reason is the fact that the protocol used is exactly the
5856  * one specified by ARM. If RISC-V will ever define its own semihosting
5857  * protocol, then a command like `riscv semihosting enable` will make
5858  * sense, but for now all semihosting commands are prefixed with `arm`.
5859  */
5860 
5861 static const struct command_registration riscv_command_handlers[] = {
5862  {
5863  .name = "riscv",
5864  .mode = COMMAND_ANY,
5865  .help = "RISC-V Command Group",
5866  .usage = "",
5868  },
5869  {
5870  .name = "arm",
5871  .mode = COMMAND_ANY,
5872  .help = "ARM Command Group",
5873  .usage = "",
5875  },
5877 };
5878 
5879 static unsigned int riscv_xlen_nonconst(struct target *target)
5880 {
5881  return riscv_xlen(target);
5882 }
5883 
5884 static unsigned int riscv_data_bits(struct target *target)
5885 {
5886  RISCV_INFO(r);
5887  if (r->data_bits)
5888  return r->data_bits(target);
5889  return riscv_xlen(target);
5890 }
5891 
5892 struct target_type riscv_target = {
5893  .name = "riscv",
5894 
5895  .target_create = riscv_create_target,
5896  .target_jim_configure = riscv_jim_configure,
5897  .init_target = riscv_init_target,
5898  .deinit_target = riscv_deinit_target,
5899  .examine = riscv_examine,
5900 
5901  /* poll current target status */
5902  .poll = old_or_new_riscv_poll,
5903 
5904  .halt = riscv_halt,
5905  .resume = riscv_target_resume,
5906  .step = old_or_new_riscv_step,
5907 
5908  .assert_reset = riscv_assert_reset,
5909  .deassert_reset = riscv_deassert_reset,
5910 
5911  .read_memory = riscv_read_memory,
5912  .write_memory = riscv_write_memory,
5913  .read_phys_memory = riscv_read_phys_memory,
5914  .write_phys_memory = riscv_write_phys_memory,
5915 
5916  .checksum_memory = riscv_checksum_memory,
5917 
5918  .mmu = riscv_mmu,
5919  .virt2phys = riscv_virt2phys,
5920 
5921  .get_gdb_arch = riscv_get_gdb_arch,
5922  .get_gdb_reg_list = riscv_get_gdb_reg_list,
5923  .get_gdb_reg_list_noread = riscv_get_gdb_reg_list_noread,
5924 
5925  .add_breakpoint = riscv_add_breakpoint,
5926  .remove_breakpoint = riscv_remove_breakpoint,
5927 
5928  .add_watchpoint = riscv_add_watchpoint,
5929  .remove_watchpoint = riscv_remove_watchpoint,
5930  .hit_watchpoint = riscv_hit_watchpoint,
5931 
5932  .arch_state = riscv_arch_state,
5933 
5934  .run_algorithm = riscv_run_algorithm,
5935 
5936  .commands = riscv_command_handlers,
5937 
5938  .address_bits = riscv_xlen_nonconst,
5939  .data_bits = riscv_data_bits
5940 };
5941 
5942 /*** RISC-V Interface ***/
5943 
5944 /* Initializes the shared RISC-V structure. */
5945 static void riscv_info_init(struct target *target, struct riscv_info *r)
5946 {
5947  memset(r, 0, sizeof(*r));
5948 
5950 
5952  r->version_specific = NULL;
5953 
5954  memset(r->trigger_unique_id, 0xff, sizeof(r->trigger_unique_id));
5955 
5956  r->xlen = -1;
5957 
5959 
5961 
5965 
5967  for (size_t i = 0; i < RISCV_MEM_ACCESS_MAX_METHODS_NUM; ++i)
5968  r->mem_access_warn[i] = true;
5969 
5972  INIT_LIST_HEAD(&r->hide_csr);
5973 
5975 
5977  r->wp_allow_ge_lt_trigger = true;
5978  r->wp_allow_napot_trigger = true;
5979 
5980  r->autofence = true;
5981 }
5982 
5984 {
5985  RISCV_INFO(r);
5986 
5987  LOG_TARGET_DEBUG(target, "Resuming hart, state=%d.", target->state);
5988  if (target->state == TARGET_HALTED) {
5989  if (r->resume_go(target) != ERROR_OK)
5990  return ERROR_FAIL;
5991  } else {
5992  LOG_TARGET_DEBUG(target, "Hart requested resume, but was already resumed.");
5993  }
5994  return ERROR_OK;
5995 }
5996 
5997 static int riscv_interrupts_disable(struct target *target, riscv_reg_t *old_mstatus)
5998 {
5999  LOG_TARGET_DEBUG(target, "Disabling interrupts.");
6000  riscv_reg_t current_mstatus;
6001  int ret = riscv_reg_get(target, &current_mstatus, GDB_REGNO_MSTATUS);
6002  if (ret != ERROR_OK) {
6003  LOG_TARGET_ERROR(target, "Failed to read mstatus!");
6004  return ret;
6005  }
6006  if (old_mstatus)
6007  *old_mstatus = current_mstatus;
6008  return riscv_reg_set(target, GDB_REGNO_MSTATUS, current_mstatus & ~mstatus_ie_mask);
6009 }
6010 
6011 static int riscv_interrupts_restore(struct target *target, riscv_reg_t old_mstatus)
6012 {
6013  LOG_TARGET_DEBUG(target, "Restoring interrupts.");
6014  riscv_reg_t current_mstatus;
6015  int ret = riscv_reg_get(target, &current_mstatus, GDB_REGNO_MSTATUS);
6016  if (ret != ERROR_OK) {
6017  LOG_TARGET_ERROR(target, "Failed to read mstatus!");
6018  return ret;
6019  }
6020  if ((current_mstatus & mstatus_ie_mask) != 0) {
6021  LOG_TARGET_WARNING(target, "Interrupt enable bits in mstatus changed during single-step.");
6022  LOG_TARGET_WARNING(target, "OpenOCD might have affected the program when it restored the interrupt bits after single-step.");
6023  LOG_TARGET_WARNING(target, "Hint: Use 'riscv set_maskisr off' to prevent OpenOCD from touching mstatus during single-step.");
6024  }
6025  return riscv_reg_set(target, GDB_REGNO_MSTATUS, current_mstatus | (old_mstatus & mstatus_ie_mask));
6026 }
6027 
6029 {
6030  RISCV_INFO(r);
6031  LOG_TARGET_DEBUG(target, "Stepping.");
6032 
6033  if (target->state != TARGET_HALTED) {
6034  LOG_TARGET_ERROR(target, "Hart isn't halted before single step!");
6035  return ERROR_TARGET_NOT_HALTED;
6036  }
6037  r->on_step(target);
6038  if (r->step_current_hart(target) != ERROR_OK)
6039  return ERROR_FAIL;
6040  if (target->state != TARGET_HALTED) {
6041  LOG_TARGET_ERROR(target, "Hart was not halted after single step!");
6042  return ERROR_FAIL;
6043  }
6044  return ERROR_OK;
6045 }
6046 
6047 bool riscv_supports_extension(const struct target *target, char letter)
6048 {
6049  RISCV_INFO(r);
6050  unsigned int num;
6051  if (letter >= 'a' && letter <= 'z')
6052  num = letter - 'a';
6053  else if (letter >= 'A' && letter <= 'Z')
6054  num = letter - 'A';
6055  else
6056  return false;
6057  return r->misa & BIT(num);
6058 }
6059 
6060 unsigned int riscv_xlen(const struct target *target)
6061 {
6062  RISCV_INFO(r);
6063  return r->xlen;
6064 }
6065 
6066 unsigned int riscv_vlenb(const struct target *target)
6067 {
6068  RISCV_INFO(r);
6069  return r->vlenb;
6070 }
6071 
6073 {
6074  RISCV_INFO(r);
6075  assert(r->get_hart_state);
6076  return r->get_hart_state(target, state);
6077 }
6078 
6079 static enum riscv_halt_reason riscv_halt_reason(struct target *target)
6080 {
6081  RISCV_INFO(r);
6082  if (target->state != TARGET_HALTED) {
6083  LOG_TARGET_ERROR(target, "Hart is not halted!");
6084  return RISCV_HALT_UNKNOWN;
6085  }
6086  return r->halt_reason(target);
6087 }
6088 
6089 unsigned int riscv_progbuf_size(struct target *target)
6090 {
6091  RISCV_INFO(r);
6092  return r->get_progbufsize(target);
6093 }
6094 
6095 int riscv_write_progbuf(struct target *target, unsigned int index, riscv_insn_t insn)
6096 {
6097  RISCV_INFO(r);
6098  return r->write_progbuf(target, index, insn);
6099 }
6100 
6102 {
6103  RISCV_INFO(r);
6104  return r->read_progbuf(target, index);
6105 }
6106 
6107 int riscv_execute_progbuf(struct target *target, uint32_t *cmderr)
6108 {
6109  RISCV_INFO(r);
6110  return r->execute_progbuf(target, cmderr);
6111 }
6112 
6113 void riscv_fill_dmi_write(const struct target *target, uint8_t *buf, uint32_t a, uint32_t d)
6114 {
6115  RISCV_INFO(r);
6116  r->fill_dmi_write(target, buf, a, d);
6117 }
6118 
6119 void riscv_fill_dmi_read(const struct target *target, uint8_t *buf, uint32_t a)
6120 {
6121  RISCV_INFO(r);
6122  r->fill_dmi_read(target, buf, a);
6123 }
6124 
6125 void riscv_fill_dm_nop(const struct target *target, uint8_t *buf)
6126 {
6127  RISCV_INFO(r);
6128  r->fill_dm_nop(target, buf);
6129 }
6130 
6131 unsigned int riscv_get_dmi_address_bits(const struct target *target)
6132 {
6133  RISCV_INFO(r);
6134  return r->get_dmi_address_bits(target);
6135 }
6136 
6137 static int check_if_trigger_exists(struct target *target, unsigned int index)
6138 {
6139  /* If we can't write tselect, then this hart does not support triggers. */
6142  riscv_reg_t tselect_rb;
6143  if (riscv_reg_get(target, &tselect_rb, GDB_REGNO_TSELECT) != ERROR_OK)
6144  return ERROR_FAIL;
6145  /* Mask off the top bit, which is used as tdrmode in legacy RISC-V Debug Spec
6146  * (old revisions of v0.11 spec). */
6147  tselect_rb &= ~(1ULL << (riscv_xlen(target) - 1));
6148  if (tselect_rb != index)
6150  return ERROR_OK;
6151 }
6152 
6158 static int get_trigger_types(struct target *target, unsigned int *trigger_tinfo,
6159  riscv_reg_t tdata1)
6160 {
6161  assert(trigger_tinfo);
6162  riscv_reg_t tinfo;
6163  if (riscv_reg_get(target, &tinfo, GDB_REGNO_TINFO) == ERROR_OK) {
6164  /* tinfo.INFO == 1: trigger doesn’t exist
6165  * tinfo == 0 or tinfo.INFO != 1 and tinfo LSB is set: invalid tinfo */
6166  if (tinfo == 0 || tinfo & 0x1)
6168  *trigger_tinfo = tinfo;
6169  return ERROR_OK;
6170  }
6171  const unsigned int type = get_field(tdata1, CSR_TDATA1_TYPE(riscv_xlen(target)));
6172  if (type == 0)
6174  *trigger_tinfo = 1 << type;
6175  return ERROR_OK;
6176 }
6177 
6179 {
6180  bool dmode_is_set = false;
6181  switch (get_field(tdata1, CSR_TDATA1_TYPE(riscv_xlen(target)))) {
6183  /* On these older cores we don't support software using
6184  * triggers. */
6185  dmode_is_set = true;
6186  break;
6188  dmode_is_set = tdata1 & CSR_MCONTROL_DMODE(riscv_xlen(target));
6189  break;
6191  dmode_is_set = tdata1 & CSR_MCONTROL6_DMODE(riscv_xlen(target));
6192  break;
6194  dmode_is_set = tdata1 & CSR_ICOUNT_DMODE(riscv_xlen(target));
6195  break;
6197  dmode_is_set = tdata1 & CSR_ITRIGGER_DMODE(riscv_xlen(target));
6198  break;
6200  dmode_is_set = tdata1 & CSR_ETRIGGER_DMODE(riscv_xlen(target));
6201  break;
6202  }
6203  if (!dmode_is_set)
6204  /* Nothing to do */
6205  return ERROR_OK;
6207 }
6208 
6217 {
6218  RISCV_INFO(r);
6219 
6220  if (r->triggers_enumerated)
6221  return ERROR_OK;
6222 
6223  if (target->state != TARGET_HALTED) {
6224  LOG_TARGET_ERROR(target, "Unable to enumerate triggers: target not halted.");
6225  return ERROR_TARGET_NOT_HALTED;
6226  }
6227 
6228  riscv_reg_t orig_tselect;
6229  int result = riscv_reg_get(target, &orig_tselect, GDB_REGNO_TSELECT);
6230  /* If tselect is not readable, the trigger module is likely not
6231  * implemented. */
6232  if (result != ERROR_OK) {
6233  LOG_TARGET_INFO(target, "Cannot access tselect register. "
6234  "Assuming that triggers are not implemented.");
6235  r->triggers_enumerated = true;
6236  r->trigger_count = 0;
6237  free(r->reserved_triggers);
6238  r->reserved_triggers = NULL;
6239  return ERROR_OK;
6240  }
6241 
6242  /* Obtaining tinfo.version value once.
6243  * No need to enumerate per-trigger.
6244  * See https://github.com/riscv/riscv-debug-spec/pull/1081.
6245  */
6246  riscv_reg_t tinfo;
6247  if (riscv_reg_get(target, &tinfo, GDB_REGNO_TINFO) == ERROR_OK) {
6248  r->tinfo_version = get_field(tinfo, CSR_TINFO_VERSION);
6249  LOG_TARGET_DEBUG(target, "Trigger tinfo.version = %d.", r->tinfo_version);
6250  } else {
6251  r->tinfo_version = RISCV_TINFO_VERSION_UNKNOWN;
6252  LOG_TARGET_DEBUG(target, "Trigger tinfo.version is unknown.");
6253  }
6254 
6255  unsigned int t = 0;
6256  for (; t < ARRAY_SIZE(r->trigger_tinfo); ++t) {
6257  result = check_if_trigger_exists(target, t);
6258  if (result == ERROR_FAIL)
6259  return ERROR_FAIL;
6261  break;
6262 
6263  riscv_reg_t tdata1;
6264  if (riscv_reg_get(target, &tdata1, GDB_REGNO_TDATA1) != ERROR_OK)
6265  return ERROR_FAIL;
6266 
6267  result = get_trigger_types(target, &r->trigger_tinfo[t], tdata1);
6268  if (result == ERROR_FAIL)
6269  return ERROR_FAIL;
6271  break;
6272 
6273  LOG_TARGET_DEBUG(target, "Trigger %u: supported types (mask) = 0x%08x",
6274  t, r->trigger_tinfo[t]);
6275 
6276  if (disable_trigger_if_dmode(target, tdata1) != ERROR_OK)
6277  return ERROR_FAIL;
6278  }
6279 
6280  if (riscv_reg_set(target, GDB_REGNO_TSELECT, orig_tselect) != ERROR_OK)
6281  return ERROR_FAIL;
6282 
6283  r->triggers_enumerated = true;
6284  r->trigger_count = t;
6285  LOG_TARGET_INFO(target, "Found %d triggers", r->trigger_count);
6286  free(r->reserved_triggers);
6287  r->reserved_triggers = calloc(t, sizeof(*r->reserved_triggers));
6289  return ERROR_OK;
6290 }
6291 
6292 void riscv_add_bscan_tunneled_scan(struct jtag_tap *tap, const struct scan_field *field,
6294 {
6296 
6297  memset(ctxt->tunneled_dr, 0, sizeof(ctxt->tunneled_dr));
6299  ctxt->tunneled_dr[3].num_bits = 1;
6300  ctxt->tunneled_dr[3].out_value = bscan_one;
6301  ctxt->tunneled_dr[2].num_bits = 7;
6302  ctxt->tunneled_dr_width = field->num_bits;
6303  ctxt->tunneled_dr[2].out_value = &ctxt->tunneled_dr_width;
6304  /* for BSCAN tunnel, there is a one-TCK skew between shift in and shift out, so
6305  scanning num_bits + 1, and then will right shift the input field after executing the queues */
6306 
6307  ctxt->tunneled_dr[1].num_bits = field->num_bits + 1;
6308  ctxt->tunneled_dr[1].out_value = field->out_value;
6309  ctxt->tunneled_dr[1].in_value = field->in_value;
6310 
6311  ctxt->tunneled_dr[0].num_bits = 3;
6312  ctxt->tunneled_dr[0].out_value = bscan_zero;
6313  } else {
6314  /* BSCAN_TUNNEL_NESTED_TAP */
6315  ctxt->tunneled_dr[0].num_bits = 1;
6316  ctxt->tunneled_dr[0].out_value = bscan_one;
6317  ctxt->tunneled_dr[1].num_bits = 7;
6318  ctxt->tunneled_dr_width = field->num_bits;
6319  ctxt->tunneled_dr[1].out_value = &ctxt->tunneled_dr_width;
6320  /* for BSCAN tunnel, there is a one-TCK skew between shift in and shift out, so
6321  scanning num_bits + 1, and then will right shift the input field after executing the queues */
6322  ctxt->tunneled_dr[2].num_bits = field->num_bits + 1;
6323  ctxt->tunneled_dr[2].out_value = field->out_value;
6324  ctxt->tunneled_dr[2].in_value = field->in_value;
6325  ctxt->tunneled_dr[3].num_bits = 3;
6326  ctxt->tunneled_dr[3].out_value = bscan_zero;
6327  }
6329 }
void init_reg_param(struct reg_param *param, const char *reg_name, uint32_t size, enum param_direction direction)
Definition: algorithm.c:29
void destroy_reg_param(struct reg_param *param)
Definition: algorithm.c:38
@ PARAM_OUT
Definition: algorithm.h:16
@ PARAM_IN
Definition: algorithm.h:15
@ PARAM_IN_OUT
Definition: algorithm.h:17
enum arm_mode mode
Definition: armv4_5.c:281
const char * name
Definition: armv4_5.c:76
unsigned char * base64_encode(const unsigned char *src, size_t len, size_t *out_len)
base64_encode - Base64 encode @src: Data to be encoded @len: Length of the data to be encoded @out_le...
Definition: base64.c:33
void * buf_cpy(const void *from, void *_to, unsigned int size)
Copies size bits out of from and into to.
Definition: binarybuffer.c:43
static uint32_t buf_get_u32(const uint8_t *_buffer, unsigned int first, unsigned int num)
Retrieves num bits from _buffer, starting at the first bit, returning the bits in a 32-bit word.
Definition: binarybuffer.h:104
static void buf_set_u32(uint8_t *_buffer, unsigned int first, unsigned int num, uint32_t value)
Sets num bits in _buffer, starting at the first bit, using the bits in value.
Definition: binarybuffer.h:34
static uint64_t buf_get_u64(const uint8_t *_buffer, unsigned int first, unsigned int num)
Retrieves num bits from _buffer, starting at the first bit, returning the bits in a 64-bit word.
Definition: binarybuffer.h:134
static void buf_set_u64(uint8_t *_buffer, unsigned int first, unsigned int num, uint64_t value)
Sets num bits in _buffer, starting at the first bit, using the bits in value.
Definition: binarybuffer.h:65
struct breakpoint * breakpoint_find(struct target *target, target_addr_t address)
Definition: breakpoints.c:470
@ BKPT_HARD
Definition: breakpoints.h:18
@ BKPT_SOFT
Definition: breakpoints.h:19
static void watchpoint_set(struct watchpoint *watchpoint, unsigned int number)
Definition: breakpoints.h:81
#define WATCHPOINT_IGNORE_DATA_VALUE_MASK
Definition: breakpoints.h:39
static void breakpoint_hw_set(struct breakpoint *breakpoint, unsigned int hw_number)
Definition: breakpoints.h:65
watchpoint_rw
Definition: breakpoints.h:22
@ WPT_ACCESS
Definition: breakpoints.h:23
@ WPT_READ
Definition: breakpoints.h:23
@ WPT_WRITE
Definition: breakpoints.h:23
void command_print_sameline(struct command_invocation *cmd, const char *format,...)
Definition: command.c:348
void command_print(struct command_invocation *cmd, const char *format,...)
Definition: command.c:371
#define CMD
Use this macro to access the command being handled, rather than accessing the variable directly.
Definition: command.h:141
#define CALL_COMMAND_HANDLER(name, extra ...)
Use this to macro to call a command helper (or a nested handler).
Definition: command.h:118
#define CMD_NAME
Use this macro to access the name of the command being handled, rather than accessing the variable di...
Definition: command.h:166
#define CMD_ARGV
Use this macro to access the arguments for the command being handled, rather than accessing the varia...
Definition: command.h:156
#define COMMAND_PARSE_ADDRESS(in, out)
Definition: command.h:450
#define COMMAND_PARSE_ON_OFF(in, out)
parses an on/off command argument
Definition: command.h:528
#define ERROR_COMMAND_SYNTAX_ERROR
Definition: command.h:400
#define CMD_ARGC
Use this macro to access the number of arguments for the command being handled, rather than accessing...
Definition: command.h:151
#define COMMAND_PARSE_NUMBER(type, in, out)
parses the string in into out as a type, or prints a command error and passes the error code to the c...
Definition: command.h:440
#define ERROR_COMMAND_ARGUMENT_OVERFLOW
Definition: command.h:403
#define CMD_CTX
Use this macro to access the context of the command being handled, rather than accessing the variable...
Definition: command.h:146
#define COMMAND_REGISTRATION_DONE
Use this as the last entry in an array of command_registration records.
Definition: command.h:251
#define ERROR_COMMAND_ARGUMENT_INVALID
Definition: command.h:402
@ COMMAND_CONFIG
Definition: command.h:41
@ COMMAND_ANY
Definition: command.h:42
@ COMMAND_EXEC
Definition: command.h:40
static int halted(struct target *target, const char *label)
Definition: davinci.c:58
#define CSR_MCONTROL6_VS
#define CSR_MCONTROL_CHAIN
#define CSR_MCONTROL6_CHAIN
#define CSR_MCONTROL6_MATCH_NAPOT
#define CSR_ETRIGGER_VS
#define CSR_ICOUNT_ACTION_DEBUG_MODE
#define CSR_MCONTROL6_HIT0_AFTER
#define CSR_MCONTROL6_SIZE_ANY
#define CSR_ITRIGGER_HIT(XLEN)
#define CSR_MCONTROL_LOAD
#define CSR_ITRIGGER_ACTION_DEBUG_MODE
#define CSR_ETRIGGER_ACTION
#define CSR_DCSR_CAUSE_GROUP
#define CSR_MCONTROL6_CHAIN_DISABLED
#define CSR_MCONTROL6_TYPE(XLEN)
#define CSR_MCONTROL6_LOAD
#define CSR_TDATA1_TYPE_ICOUNT
#define CSR_MCONTROL6_HIT0_FALSE
#define CSR_ITRIGGER_ACTION
#define CSR_MCONTROL_ACTION_DEBUG_MODE
#define CSR_MCONTROL6_ACTION
#define CSR_MCONTROL6_MATCH_GE
#define DM_DMCONTROL
#define CSR_ETRIGGER_HIT(XLEN)
#define CSR_ETRIGGER_ACTION_DEBUG_MODE
#define CSR_ICOUNT_ACTION
#define CSR_MCONTROL_STORE
#define CSR_MCONTROL_CHAIN_DISABLED
#define CSR_MCONTROL_CHAIN_ENABLED
#define CSR_MCONTROL6_EXECUTE
#define CSR_MCONTROL_MATCH_LT
#define CSR_MCONTROL_MATCH_GE
#define CSR_ICOUNT_PENDING
#define CSR_ITRIGGER_DMODE(XLEN)
#define CSR_TDATA1_TYPE_MCONTROL6
#define CSR_MCONTROL6_STORE
#define CSR_MCONTROL_TYPE(XLEN)
#define VIRT_PRIV_PRV
#define CSR_MCONTROL_M
#define CSR_MCONTROL_EXECUTE
#define CSR_ETRIGGER_DMODE(XLEN)
#define CSR_MCONTROL_ACTION
#define CSR_MCONTROL6_M
#define CSR_MCONTROL6_S
#define CSR_MCONTROL_SIZELO_ANY
#define CSR_TINFO_VERSION_0
#define CSR_MCONTROL_MASKMAX(XLEN)
#define CSR_MCONTROL_U
#define CSR_MCONTROL6_U
#define CSR_MCONTROL6_MATCH_LT
#define CSR_MCONTROL6_VU
#define CSR_TDATA1_TYPE_ETRIGGER
#define CSR_ICOUNT_COUNT
#define CSR_MCONTROL6_MATCH_EQUAL
#define DM_DMCONTROL_DMACTIVE
#define CSR_ITRIGGER_VS
#define CSR_ETRIGGER_TYPE(XLEN)
#define CSR_ETRIGGER_S
#define CSR_TINFO_VERSION_1
#define CSR_MCONTROL_S
#define CSR_ETRIGGER_VU
#define CSR_MCONTROL6_MATCH
#define CSR_ITRIGGER_M
#define CSR_MCONTROL_DMODE(XLEN)
#define CSR_ICOUNT_M
#define CSR_ICOUNT_VU
#define CSR_ITRIGGER_NMI
#define DTM_DTMCS_VERSION_0_11
#define CSR_MCONTROL_SIZELO
#define CSR_ETRIGGER_M
#define CSR_MCONTROL6_DMODE(XLEN)
#define CSR_MCONTROL_MATCH_NAPOT
#define CSR_TDATA1_TYPE_MCONTROL
#define CSR_ICOUNT_TYPE(XLEN)
#define CSR_ITRIGGER_VU
#define CSR_MCONTROL6_HIT1
#define VIRT_PRIV_V
#define CSR_ITRIGGER_S
#define CSR_TDATA1_TYPE_LEGACY
#define CSR_TINFO_VERSION
#define CSR_ICOUNT_DMODE(XLEN)
#define CSR_ITRIGGER_TYPE(XLEN)
#define DTM_DTMCS_VERSION_1_0
#define CSR_MCONTROL6_HIT0
#define CSR_MCONTROL6_SIZE
#define DM_PROGBUF0
#define CSR_ETRIGGER_U
#define CSR_TDATA1_TYPE_ITRIGGER
#define CSR_ICOUNT_HIT
#define CSR_MCONTROL_SIZEHI
#define CSR_ITRIGGER_U
#define CSR_MCONTROL_MATCH
#define CSR_TDATA1_TYPE(XLEN)
#define DM_PROGBUF15
#define CSR_ICOUNT_VS
#define CSR_MCONTROL6_HIT0_BEFORE
#define CSR_ICOUNT_U
#define CSR_ICOUNT_S
#define CSR_MCONTROL6_CHAIN_ENABLED
#define CSR_MCONTROL_HIT
#define CSR_MCONTROL6_HIT0_IMMEDIATELY_AFTER
#define CSR_MCONTROL_MATCH_EQUAL
#define CSR_DCSR_CAUSE
uint64_t buffer
Pointer to data buffer to send over SPI.
Definition: dw-spi-helper.h:0
uint32_t size
Size of dw_spi_transaction::buffer.
Definition: dw-spi-helper.h:4
uint32_t address
Starting address. Sector aligned.
Definition: dw-spi-helper.h:0
const char * rs
Definition: ecos.c:480
#define PTE_W
Definition: encoding.h:298
#define MATCH_C_SDSP
Definition: encoding.h:578
#define INSN_FIELD_C_UIMM9SP_S
Definition: encoding.h:3312
#define INSN_FIELD_C_UIMM9SPLO
Definition: encoding.h:3309
#define INSN_FIELD_C_SREG1
Definition: encoding.h:3330
#define MSTATUS_MIE
Definition: encoding.h:16
#define INSN_FIELD_C_UIMM8LO
Definition: encoding.h:3286
#define INSN_FIELD_IMM12
Definition: encoding.h:3251
#define MATCH_C_LW
Definition: encoding.h:560
#define MSTATUS_SIE
Definition: encoding.h:14
#define MSTATUS_MPP
Definition: encoding.h:23
#define INSN_FIELD_C_UIMM10SP_S
Definition: encoding.h:3311
#define INSN_FIELD_C_UIMM7HI
Definition: encoding.h:3285
#define INSN_FIELD_C_UIMM7LO
Definition: encoding.h:3284
#define INSN_FIELD_C_UIMM8HI
Definition: encoding.h:3287
#define PTE_R
Definition: encoding.h:297
#define MATCH_C_SW
Definition: encoding.h:596
#define MSTATUS_UIE
Definition: encoding.h:13
#define MATCH_C_FSW
Definition: encoding.h:534
#define INSN_FIELD_C_UIMM8SPLO
Definition: encoding.h:3304
#define HGATP_MODE_SV57X4
Definition: encoding.h:266
#define INSN_FIELD_C_UIMM9SPHI
Definition: encoding.h:3310
#define PTE_PPN_SHIFT
Definition: encoding.h:310
#define MATCH_C_FSD
Definition: encoding.h:530
#define MATCH_LB
Definition: encoding.h:1264
#define INSN_FIELD_IMM12HI
Definition: encoding.h:3253
#define HGATP_MODE_SV32X4
Definition: encoding.h:263
#define INSN_FIELD_C_UIMM9HI
Definition: encoding.h:3289
#define SATP_MODE_SV32
Definition: encoding.h:248
#define SATP_MODE_SV39
Definition: encoding.h:249
#define HGATP_MODE_SV39X4
Definition: encoding.h:264
#define MATCH_C_LWSP
Definition: encoding.h:562
#define INSN_FIELD_C_UIMM8SPHI
Definition: encoding.h:3305
#define MATCH_C_LDSP
Definition: encoding.h:550
#define PTE_V
Definition: encoding.h:296
#define MATCH_SB
Definition: encoding.h:1408
#define MATCH_FLH
Definition: encoding.h:856
#define MATCH_C_FSDSP
Definition: encoding.h:532
#define INSN_FIELD_C_UIMM10SPLO
Definition: encoding.h:3307
#define INSN_FIELD_C_UIMM10SPHI
Definition: encoding.h:3308
#define HGATP_MODE_SV48X4
Definition: encoding.h:265
#define SATP_MODE_SV48
Definition: encoding.h:250
#define MSTATUS_HIE
Definition: encoding.h:15
#define MATCH_FSH
Definition: encoding.h:964
#define INSN_FIELD_C_UIMM8SP_S
Definition: encoding.h:3306
#define MATCH_C_FLW
Definition: encoding.h:526
#define INSN_FIELD_OPCODE
Definition: encoding.h:3270
#define HGATP_MODE_OFF
Definition: encoding.h:262
#define INSN_FIELD_C_UIMM9LO
Definition: encoding.h:3288
#define INSN_FIELD_RD
Definition: encoding.h:3235
#define SATP_MODE_OFF
Definition: encoding.h:247
#define SATP_MODE_SV57
Definition: encoding.h:251
#define MASK_C_LD
Definition: encoding.h:549
#define INSN_FIELD_RS1
Definition: encoding.h:3237
#define PTE_X
Definition: encoding.h:299
#define MATCH_C_SWSP
Definition: encoding.h:598
#define INSN_FIELD_IMM12LO
Definition: encoding.h:3255
#define MSTATUS_MPRV
Definition: encoding.h:26
#define INSN_FIELD_FUNCT3
Definition: encoding.h:3247
#define MATCH_C_FLDSP
Definition: encoding.h:524
#define PRV_M
Definition: encoding.h:236
#define MATCH_C_FLD
Definition: encoding.h:522
uint8_t type
Definition: esp_usb_jtag.c:0
static struct esp_usb_jtag * priv
Definition: esp_usb_jtag.c:219
uint8_t length
Definition: esp_usb_jtag.c:1
static uint64_t set_field(uint64_t reg, uint64_t mask, uint64_t val)
Definition: field_helpers.h:21
static uint64_t field_value(uint64_t mask, uint64_t val)
Definition: field_helpers.h:37
static uint32_t get_field32(uint64_t reg, uint64_t mask)
Definition: field_helpers.h:14
static uint64_t get_field(uint64_t reg, uint64_t mask)
Definition: field_helpers.h:9
static uint16_t direction
Definition: ftdi.c:120
gdb_regno
Definition: gdb_regs.h:10
@ GDB_REGNO_DPC
Definition: gdb_regs.h:99
@ GDB_REGNO_S8
Definition: gdb_regs.h:37
@ GDB_REGNO_SATP
Definition: gdb_regs.h:105
@ GDB_REGNO_MSTATUS
Definition: gdb_regs.h:102
@ GDB_REGNO_S4
Definition: gdb_regs.h:33
@ GDB_REGNO_S11
Definition: gdb_regs.h:40
@ GDB_REGNO_S5
Definition: gdb_regs.h:34
@ GDB_REGNO_T5
Definition: gdb_regs.h:43
@ GDB_REGNO_T6
Definition: gdb_regs.h:44
@ GDB_REGNO_A4
Definition: gdb_regs.h:26
@ GDB_REGNO_GP
Definition: gdb_regs.h:14
@ GDB_REGNO_S7
Definition: gdb_regs.h:36
@ GDB_REGNO_A1
Definition: gdb_regs.h:23
@ GDB_REGNO_A5
Definition: gdb_regs.h:27
@ GDB_REGNO_TSELECT
Definition: gdb_regs.h:93
@ GDB_REGNO_T2
Definition: gdb_regs.h:18
@ GDB_REGNO_S1
Definition: gdb_regs.h:21
@ GDB_REGNO_T3
Definition: gdb_regs.h:41
@ GDB_REGNO_SP
Definition: gdb_regs.h:13
@ GDB_REGNO_VSATP
Definition: gdb_regs.h:106
@ GDB_REGNO_A6
Definition: gdb_regs.h:29
@ GDB_REGNO_FP
Definition: gdb_regs.h:20
@ GDB_REGNO_TDATA1
Definition: gdb_regs.h:94
@ GDB_REGNO_XPR31
Definition: gdb_regs.h:45
@ GDB_REGNO_A0
Definition: gdb_regs.h:22
@ GDB_REGNO_MEPC
Definition: gdb_regs.h:103
@ GDB_REGNO_A2
Definition: gdb_regs.h:24
@ GDB_REGNO_A7
Definition: gdb_regs.h:30
@ GDB_REGNO_RA
Definition: gdb_regs.h:12
@ GDB_REGNO_S9
Definition: gdb_regs.h:38
@ GDB_REGNO_PC
Definition: gdb_regs.h:47
@ GDB_REGNO_S0
Definition: gdb_regs.h:19
@ GDB_REGNO_T4
Definition: gdb_regs.h:42
@ GDB_REGNO_S10
Definition: gdb_regs.h:39
@ GDB_REGNO_PRIV
Definition: gdb_regs.h:112
@ GDB_REGNO_S2
Definition: gdb_regs.h:31
@ GDB_REGNO_TP
Definition: gdb_regs.h:15
@ GDB_REGNO_MCAUSE
Definition: gdb_regs.h:104
@ GDB_REGNO_TDATA2
Definition: gdb_regs.h:95
@ GDB_REGNO_T1
Definition: gdb_regs.h:17
@ GDB_REGNO_TINFO
Definition: gdb_regs.h:97
@ GDB_REGNO_S6
Definition: gdb_regs.h:35
@ GDB_REGNO_S3
Definition: gdb_regs.h:32
@ GDB_REGNO_T0
Definition: gdb_regs.h:16
@ GDB_REGNO_DCSR
Definition: gdb_regs.h:100
@ GDB_REGNO_A3
Definition: gdb_regs.h:25
@ GDB_REGNO_HGATP
Definition: gdb_regs.h:107
struct jim_nvp * jim_nvp_name2value_simple(const struct jim_nvp *p, const char *name)
Definition: jim-nvp.c:46
int jim_getopt_nvp(struct jim_getopt_info *goi, const struct jim_nvp *nvp, struct jim_nvp **puthere)
Remove argv[0] as NVP.
Definition: jim-nvp.c:237
void jim_getopt_nvp_unknown(struct jim_getopt_info *goi, const struct jim_nvp *nvptable, int hadprefix)
Create an appropriate error message for an NVP.
Definition: jim-nvp.c:253
int jim_nvp_name2value_obj(Jim_Interp *interp, const struct jim_nvp *p, Jim_Obj *o, struct jim_nvp **result)
Definition: jim-nvp.c:66
int jim_getopt_obj(struct jim_getopt_info *goi, Jim_Obj **puthere)
Remove argv[0] from the list.
Definition: jim-nvp.c:169
struct jim_nvp * jim_nvp_value2name_simple(const struct jim_nvp *p, int value)
Definition: jim-nvp.c:124
int jtag_execute_queue(void)
For software FIFO implementations, the queued commands can be executed during this call or earlier.
Definition: jtag/core.c:1050
const char * jtag_tap_name(const struct jtag_tap *tap)
Definition: jtag/core.c:282
void jtag_add_dr_scan(struct jtag_tap *active, int in_num_fields, const struct scan_field *in_fields, enum tap_state state)
Generate a DR SCAN using the fields passed to the function.
Definition: jtag/core.c:457
void jtag_add_ir_scan(struct jtag_tap *active, struct scan_field *in_fields, enum tap_state state)
Generate an IR SCAN with a list of scan fields with one entry for each enabled TAP.
Definition: jtag/core.c:380
The JTAG interface can be implemented with a software or hardware fifo.
@ TAP_IDLE
Definition: jtag.h:53
static void list_add(struct list_head *new, struct list_head *head)
Definition: list.h:197
#define OOCD_LIST_HEAD(name)
Definition: list.h:50
static void list_add_tail(struct list_head *new, struct list_head *head)
Definition: list.h:203
#define list_for_each_entry_safe(p, n, h, field)
Definition: list.h:159
#define list_for_each_entry(p, h, field)
Definition: list.h:155
static void list_del(struct list_head *entry)
Definition: list.h:88
static void INIT_LIST_HEAD(struct list_head *list)
Definition: list.h:54
static void list_move(struct list_head *list, struct list_head *head)
Definition: list.h:209
void alive_sleep(uint64_t ms)
Definition: log.c:470
static int64_t start
Definition: log.c:54
#define LOG_TARGET_INFO(target, fmt_str,...)
Definition: log.h:154
#define LOG_USER(expr ...)
Definition: log.h:137
#define LOG_TARGET_WARNING(target, fmt_str,...)
Definition: log.h:160
#define ERROR_NOT_IMPLEMENTED
Definition: log.h:179
#define LOG_WARNING(expr ...)
Definition: log.h:131
#define ERROR_FAIL
Definition: log.h:175
#define LOG_TARGET_ERROR(target, fmt_str,...)
Definition: log.h:163
#define LOG_TARGET_DEBUG(target, fmt_str,...)
Definition: log.h:151
#define LOG_ERROR(expr ...)
Definition: log.h:134
#define LOG_INFO(expr ...)
Definition: log.h:128
#define LOG_DEBUG(expr ...)
Definition: log.h:111
#define ERROR_OK
Definition: log.h:169
@ LOG_LVL_INFO
Definition: log.h:47
@ LOG_LVL_ERROR
Definition: log.h:45
#define t1
Definition: mips32.c:193
#define t2
Definition: mips32.c:194
static uint32_t ebreak(void) __attribute__((unused))
Definition: opcodes.h:336
static uint32_t ebreak_c(void) __attribute__((unused))
Definition: opcodes.h:341
uint8_t mask
Definition: parport.c:70
int riscv_program_insert(struct riscv_program *p, riscv_insn_t i)
Definition: program.c:197
int riscv_program_init(struct riscv_program *p, struct target *target)
Definition: program.c:17
int riscv_program_exec(struct riscv_program *p, struct target *t)
Add ebreak and execute the program.
Definition: program.c:42
struct reg * register_get_by_name(struct reg_cache *first, const char *name, bool search_all)
Definition: register.c:50
reg_type
Definition: register.h:19
#define MIN(a, b)
Definition: replacements.h:22
#define MAX(a, b)
Definition: replacements.h:25
struct target_type riscv011_target
Definition: riscv-011.c:2459
struct target_type riscv013_target
Definition: riscv-013.c:5092
static int riscv_reset_timeout_sec
Definition: riscv.c:177
static enum target_debug_reason derive_debug_reason_without_hitbit(const struct target *target, riscv_reg_t dpc)
Definition: riscv.c:2530
static int check_if_trigger_exists(struct target *target, unsigned int index)
Definition: riscv.c:6137
static int halt_finish(struct target *target)
Definition: riscv.c:2703
COMMAND_HELPER(ebreakx_deprecation_helper, enum riscv_priv_mode mode)
Definition: riscv.c:4924
static bool parse_csr_address(const char *reg_address_str, unsigned int *reg_addr)
Definition: riscv.c:4379
static struct scan_field _bscan_tunnel_data_register_select_dmi[]
Definition: riscv.c:73
static const virt2phys_info_t sv57
Definition: riscv.c:267
static int riscv_rw_memory(struct target *target, const struct riscv_mem_access_args args)
Definition: riscv.c:3401
static struct tdata1_cache * tdata1_cache_alloc(struct list_head *tdata1_cache_head, riscv_reg_t tdata1)
Definition: riscv.c:984
struct scan_field select_idcode
Definition: riscv.c:53
static int verify_loadstore(struct target *target, const riscv_insn_t instruction, bool *is_read)
Definition: riscv.c:2191
static const virt2phys_info_t sv48x4
Definition: riscv.c:254
static int set_debug_reason(struct target *target, enum riscv_halt_reason halt_reason)
Set OpenOCD's generic debug reason from the RISC-V halt reason.
Definition: riscv.c:2559
static uint32_t get_opcode(const riscv_insn_t instruction)
Definition: riscv.c:2025
static struct jim_nvp nvp_ebreak_config_opts[]
Definition: riscv.c:511
unsigned int riscv_xlen(const struct target *target)
Definition: riscv.c:6060
static struct scan_field select_user4
Definition: riscv.c:67
static bscan_tunnel_type_t bscan_tunnel_type
Definition: riscv.c:58
static int riscv_halt_go_all_harts(struct target *target)
Definition: riscv.c:2655
struct scan_field select_dbus
Definition: riscv.c:48
static const virt2phys_info_t sv57x4
Definition: riscv.c:280
static int riscv_step_rtos_hart(struct target *target)
Definition: riscv.c:6028
mctrl6hitstatus
Definition: riscv.c:1771
@ M6_HIT_NOT_SUPPORTED
Definition: riscv.c:1773
@ M6_HIT_ERROR
Definition: riscv.c:1772
@ M6_HIT_BEFORE
Definition: riscv.c:1775
@ M6_HIT_AFTER
Definition: riscv.c:1776
@ M6_HIT_IMM_AFTER
Definition: riscv.c:1777
@ M6_NOT_HIT
Definition: riscv.c:1774
void riscv_add_bscan_tunneled_scan(struct jtag_tap *tap, const struct scan_field *field, riscv_bscan_tunneled_scan_context_t *ctxt)
Definition: riscv.c:6292
static int riscv_checksum_memory(struct target *target, target_addr_t address, uint32_t count, uint32_t *checksum)
Definition: riscv.c:3744
static int get_trigger_types(struct target *target, unsigned int *trigger_tinfo, riscv_reg_t tdata1)
This function reads tinfo or tdata1, when reading tinfo fails, to determine trigger types supported b...
Definition: riscv.c:6158
static int maybe_add_trigger_t2_t6_for_bp(struct target *target, struct trigger *trigger, struct match_triggers_tdata1_fields fields)
Definition: riscv.c:1333
static int maybe_add_trigger_t2_t6_for_wp(struct target *target, struct trigger *trigger, struct match_triggers_tdata1_fields fields)
Definition: riscv.c:1237
unsigned int riscv_get_dmi_address_bits(const struct target *target)
Definition: riscv.c:6131
static int riscv_trigger_detect_hit_bits(struct target *target, int64_t *unique_id, bool *need_single_step)
Look at the trigger hit bits to find out which trigger is the reason we're halted.
Definition: riscv.c:1829
static const virt2phys_info_t sv32x4
Definition: riscv.c:202
static uint16_t get_offset_csqsp(riscv_insn_t instruction)
Definition: riscv.c:2005
static int get_loadstore_memoffset(struct target *target, const riscv_insn_t instruction, int16_t *memoffset)
Definition: riscv.c:2077
static uint32_t bscan_tunnel_data_register_select_dmi_num_fields
Definition: riscv.c:122
bool riscv_supports_extension(const struct target *target, char letter)
Definition: riscv.c:6047
static uint16_t get_offset_cswsp(riscv_insn_t instruction)
Definition: riscv.c:1944
static int maybe_add_trigger_t2_t6(struct target *target, struct trigger *trigger, struct match_triggers_tdata1_fields fields)
Definition: riscv.c:1346
static const struct command_registration riscv_command_handlers[]
Definition: riscv.c:5861
static int riscv_command_timeout_sec_value
Definition: riscv.c:174
void select_dmi_via_bscan(struct jtag_tap *tap)
Definition: riscv.c:319
int riscv_read_by_any_size(struct target *target, target_addr_t address, uint32_t size, uint8_t *buffer)
Read one memory item using any memory access size that will work.
Definition: riscv.c:1579
static int riscv_read_phys_memory(struct target *target, target_addr_t phys_address, uint32_t size, uint32_t count, uint8_t *buffer)
Definition: riscv.c:3372
static int riscv_write_phys_memory(struct target *target, target_addr_t phys_address, uint32_t size, uint32_t count, const uint8_t *buffer)
Definition: riscv.c:3386
int riscv_halt(struct target *target)
Definition: riscv.c:2708
static void create_wp_trigger_cache(struct target *target)
Definition: riscv.c:1020
static int riscv_remove_breakpoint(struct target *target, struct breakpoint *breakpoint)
Definition: riscv.c:1692
static void tdata2_cache_alloc(struct list_head *tdata2_cache_head, riscv_reg_t tdata2)
Definition: riscv.c:993
static int riscv_poll_hart(struct target *target, enum riscv_next_action *next_action)
Definition: riscv.c:3837
static int add_trigger(struct target *target, struct trigger *trigger)
Definition: riscv.c:1455
static uint16_t get_offset_cldsp(riscv_insn_t instruction)
Definition: riscv.c:1932
static int remove_trigger(struct target *target, int unique_id)
Definition: riscv.c:1658
static bool can_use_napot_match(struct trigger *trigger)
Definition: riscv.c:775
int riscv_write_by_any_size(struct target *target, target_addr_t address, uint32_t size, uint8_t *buffer)
Write one memory item using any memory access size that will work.
Definition: riscv.c:1547
static uint16_t get_offset_clqsp(riscv_insn_t instruction)
Definition: riscv.c:1994
static void trigger_from_watchpoint(struct trigger *trigger, const struct watchpoint *watchpoint)
Definition: riscv.c:1721
static int riscv_resume(struct target *target, bool current, target_addr_t address, bool handle_breakpoints, bool debug_execution, bool single_hart)
Definition: riscv.c:2914
unsigned int riscv_vlenb(const struct target *target)
Definition: riscv.c:6066
int riscv_get_hart_state(struct target *target, enum riscv_hart_state *state)
Definition: riscv.c:6072
static const virt2phys_info_t sv32
Definition: riscv.c:189
static int riscv_create_target(struct target *target)
Definition: riscv.c:492
static int riscv_init_target(struct command_context *cmd_ctx, struct target *target)
Definition: riscv.c:663
static struct jim_nvp nvp_config_opts[]
Definition: riscv.c:619
static int old_or_new_riscv_poll(struct target *target)
Definition: riscv.c:2520
static int riscv_add_breakpoint(struct target *target, struct breakpoint *breakpoint)
Definition: riscv.c:1607
static int riscv_get_gdb_reg_list(struct target *target, struct reg **reg_list[], int *reg_list_size, enum target_register_class reg_class)
Definition: riscv.c:3551
static void log_trigger_request_info(struct trigger_request_info trig_info)
Definition: riscv.c:979
static const riscv_reg_t mstatus_ie_mask
Definition: riscv.c:297
static int riscv_mmu(struct target *target, bool *enabled)
Definition: riscv.c:3015
static int try_setup_chained_match_triggers(struct target *target, struct trigger *trigger, struct trigger_request_info t1, struct trigger_request_info t2)
Definition: riscv.c:1104
static int jim_report_ebreak_config(const struct riscv_private_config *config, Jim_Interp *interp)
Definition: riscv.c:599
bool riscv_virt2phys_mode_is_hw(const struct target *target)
Definition: riscv.c:144
static int riscv_openocd_step_impl(struct target *target, bool current, target_addr_t address, bool handle_breakpoints, int handle_callbacks)
Definition: riscv.c:4186
static void riscv_sample_buf_maybe_add_timestamp(struct target *target, bool before)
Definition: riscv.c:301
static int old_or_new_riscv_step_impl(struct target *target, bool current, target_addr_t address, bool handle_breakpoints, int handle_callbacks)
Definition: riscv.c:2452
static uint16_t get_offset_clwsp(riscv_insn_t instruction)
These functions are needed to extract individual bits (for offset) from the instruction.
Definition: riscv.c:1920
static int riscv_virt2phys_v(struct target *target, target_addr_t virtual, target_addr_t *physical)
Definition: riscv.c:3189
#define RISCV_EBREAK_MODE_INVALID
Definition: riscv.c:520
unsigned int riscv_progbuf_size(struct target *target)
Definition: riscv.c:6089
static int parse_reg_ranges(struct list_head *ranges, const char *tcl_arg, const char *reg_type, unsigned int max_val)
Definition: riscv.c:4522
static const virt2phys_info_t sv39x4
Definition: riscv.c:228
#define RISCV_TRIGGER_HIT_NOT_FOUND
Definition: riscv.c:38
static int riscv_address_translate(struct target *target, const virt2phys_info_t *info, target_addr_t ppn, const virt2phys_info_t *extra_info, target_addr_t extra_ppn, target_addr_t virtual, target_addr_t *physical)
Definition: riscv.c:3094
struct tdata1_cache * tdata1_cache_search(struct list_head *tdata1_cache_head, riscv_reg_t find_tdata1)
Definition: riscv.c:1010
static const virt2phys_info_t sv48
Definition: riscv.c:241
static int set_trigger(struct target *target, unsigned int idx, riscv_reg_t tdata1, riscv_reg_t tdata2)
Definition: riscv.c:841
static int ebreak_config_to_tcl_dict(const struct riscv_private_config *config, char *buffer)
Obtain dcsr.ebreak* configuration as a Tcl dictionary.
Definition: riscv.c:577
static int jim_configure_ebreak(struct riscv_private_config *config, struct jim_getopt_info *goi)
Definition: riscv.c:528
uint8_t bscan_tunnel_ir_width
Definition: riscv.c:60
static struct scan_field _bscan_tunnel_nested_tap_select_dmi[]
Definition: riscv.c:96
struct tdata2_cache * tdata2_cache_search(struct list_head *tdata2_cache_head, riscv_reg_t find_tdata2)
Definition: riscv.c:1000
static enum mctrl6hitstatus check_mcontrol6_hit_status(struct target *target, riscv_reg_t tdata1, uint64_t hit_mask)
Definition: riscv.c:1780
struct target_type riscv_target
Definition: riscv.c:5892
static int riscv_effective_privilege_mode(struct target *target, int *v_mode, int *effective_mode)
Definition: riscv.c:2990
static struct match_triggers_tdata1_fields fill_match_triggers_tdata1_fields_t6(struct target *target, struct trigger *trigger)
Definition: riscv.c:1200
static int resume_prep(struct target *target, bool current, target_addr_t address, bool handle_breakpoints, bool debug_execution)
Get everything ready to resume.
Definition: riscv.c:2830
static int resume_finish(struct target *target, bool debug_execution)
Definition: riscv.c:2891
struct scan_field select_dtmcontrol
Definition: riscv.c:43
static int check_virt_memory_access(struct target *target, target_addr_t address, uint32_t size, uint32_t count, bool is_write)
Definition: riscv.c:3357
#define DTMCONTROL_VERSION
Definition: riscv.c:34
static int disable_watchpoints(struct target *target, bool *wp_is_set)
Definition: riscv.c:2781
static const struct command_registration riscv_exec_command_handlers[]
Definition: riscv.c:5579
@ RO_REVERSED
Definition: riscv.c:186
@ RO_NORMAL
Definition: riscv.c:185
static void riscv_info_init(struct target *target, struct riscv_info *r)
Definition: riscv.c:5945
static uint8_t ir_dtmcontrol[4]
Definition: riscv.c:42
void riscv_fill_dmi_write(const struct target *target, uint8_t *buf, uint32_t a, uint32_t d)
Definition: riscv.c:6113
static bool wp_triggers_cache_search(struct target *target, unsigned int idx, riscv_reg_t tdata1, riscv_reg_t tdata2)
Definition: riscv.c:1048
int dtmcs_scan(struct jtag_tap *tap, uint32_t out, uint32_t *in_ptr)
Definition: riscv.c:416
static int riscv_get_gdb_reg_list_internal(struct target *target, struct reg **reg_list[], int *reg_list_size, enum target_register_class reg_class, bool is_read)
Definition: riscv.c:3501
static int get_loadstore_membase_regno(struct target *target, const riscv_insn_t instruction, int *regid)
Definition: riscv.c:2036
static int riscv_read_memory(struct target *target, target_addr_t address, uint32_t size, uint32_t count, uint8_t *buffer)
Definition: riscv.c:3461
static void free_wp_triggers_cache(struct target *target)
Definition: riscv.c:697
static int bscan_tunnel_ir_id
Definition: riscv.c:61
static int maybe_add_trigger_t5(struct target *target, bool vs, bool vu, bool m, bool s, bool u, riscv_reg_t exception_codes, int unique_id)
Definition: riscv.c:1423
static uint16_t get_offset_clq(riscv_insn_t instruction)
Definition: riscv.c:1982
const char * riscv_virt2phys_mode_to_str(enum riscv_virt2phys_mode mode)
Definition: riscv.c:158
static uint8_t ir_user4[4]
Definition: riscv.c:66
static int riscv_target_resume(struct target *target, bool current, target_addr_t address, bool handle_breakpoints, bool debug_execution)
Definition: riscv.c:2979
int riscv_openocd_poll(struct target *target)
Definition: riscv.c:4016
static int riscv_dmi_write(struct target *target, uint32_t dmi_address, uint32_t value)
Definition: riscv.c:4676
static unsigned int riscv_xlen_nonconst(struct target *target)
Definition: riscv.c:5879
#define DTMCONTROL
Definition: riscv.c:33
int riscv_add_watchpoint(struct target *target, struct watchpoint *watchpoint)
Definition: riscv.c:1735
static int maybe_add_trigger_t3(struct target *target, bool vs, bool vu, bool m, bool s, bool u, bool pending, unsigned int count, int unique_id)
Definition: riscv.c:1358
static int oldriscv_poll(struct target *target)
Definition: riscv.c:2512
static int riscv_hit_watchpoint(struct target *target, struct watchpoint **hit_watchpoint)
Definition: riscv.c:2355
static int dtmcs_scan_via_bscan(struct jtag_tap *tap, uint32_t out, uint32_t *in_ptr)
Definition: riscv.c:330
uint32_t riscv_get_dmi_address(const struct target *target, uint32_t dm_address)
Definition: riscv.c:4649
int riscv_write_progbuf(struct target *target, unsigned int index, riscv_insn_t insn)
Definition: riscv.c:6095
static int try_setup_single_match_trigger(struct target *target, struct trigger *trigger, struct trigger_request_info trig_info)
Definition: riscv.c:1077
static uint16_t get_offset_cld(riscv_insn_t instruction)
Definition: riscv.c:1974
static int halt_go(struct target *target)
Definition: riscv.c:2685
static int riscv_assert_reset(struct target *target)
Definition: riscv.c:2757
riscv_insn_t riscv_read_progbuf(struct target *target, int index)
Definition: riscv.c:6101
static int read_by_given_size(struct target *target, target_addr_t address, uint32_t size, uint8_t *buffer, uint32_t access_size)
Read one memory item of given "size".
Definition: riscv.c:1520
void riscv_fill_dm_nop(const struct target *target, uint8_t *buf)
Definition: riscv.c:6125
static uint32_t bscan_tunnel_nested_tap_select_dmi_num_fields
Definition: riscv.c:119
static int halt_prep(struct target *target)
Definition: riscv.c:2636
static int riscv_jim_configure(struct target *target, struct jim_getopt_info *goi)
Definition: riscv.c:624
static uint8_t ir_dbus[4]
Definition: riscv.c:47
static unsigned int riscv_data_bits(struct target *target)
Definition: riscv.c:5884
COMMAND_HANDLER(riscv_set_command_timeout_sec)
Definition: riscv.c:4295
#define RISCV_HALT_GROUP_REPOLL_LIMIT
Definition: riscv.c:40
static uint16_t get_offset_csdsp(riscv_insn_t instruction)
Definition: riscv.c:1954
static int riscv_dmi_read(struct target *target, uint32_t *value, uint32_t address)
Definition: riscv.c:4658
static int enable_watchpoints(struct target *target, bool *wp_is_set)
Definition: riscv.c:2808
void riscv_fill_dmi_read(const struct target *target, uint8_t *buf, uint32_t a)
Definition: riscv.c:6119
static struct jim_nvp nvp_ebreak_mode_opts[]
Definition: riscv.c:522
int riscv_execute_progbuf(struct target *target, uint32_t *cmderr)
Definition: riscv.c:6107
static void riscv_deinit_target(struct target *target)
Definition: riscv.c:716
static const char * riscv_get_gdb_arch(const struct target *target)
Definition: riscv.c:3489
#define BSCAN_TUNNEL_IR_WIDTH_NBITS
Definition: riscv.c:59
static int riscv_examine(struct target *target)
Definition: riscv.c:2472
bool riscv_virt2phys_mode_is_sw(const struct target *target)
Definition: riscv.c:151
static int riscv_resume_go_all_harts(struct target *target)
Definition: riscv.c:5983
static int parse_reg_ranges_impl(struct list_head *ranges, char *args, const char *reg_type, unsigned int max_val, char **const name_buffer)
Definition: riscv.c:4409
static int maybe_add_trigger_t1(struct target *target, struct trigger *trigger)
Definition: riscv.c:927
static int maybe_add_trigger_t4(struct target *target, bool vs, bool vu, bool nmi, bool m, bool s, bool u, riscv_reg_t interrupts, int unique_id)
Definition: riscv.c:1390
static int sample_memory(struct target *target)
Definition: riscv.c:3968
static int try_use_trigger_and_cache_result(struct target *target, unsigned int idx, riscv_reg_t tdata1, riscv_reg_t tdata2)
Definition: riscv.c:1063
static int find_next_free_trigger(struct target *target, int type, bool chained, unsigned int *idx)
Definition: riscv.c:785
static uint16_t get_offset_clw(riscv_insn_t instruction)
Definition: riscv.c:1964
static unsigned int count_trailing_ones(riscv_reg_t reg)
Definition: riscv.c:831
static enum @125 resume_order
static int riscv_arch_state(struct target *target)
Definition: riscv.c:3559
static int riscv_run_algorithm(struct target *target, int num_mem_params, struct mem_param *mem_params, int num_reg_params, struct reg_param *reg_params, target_addr_t entry_point, target_addr_t exit_point, unsigned int timeout_ms, void *arch_info)
Definition: riscv.c:3576
static struct scan_field * bscan_tunnel_nested_tap_select_dmi
Definition: riscv.c:118
static int disable_trigger_if_dmode(struct target *target, riscv_reg_t tdata1)
Definition: riscv.c:6178
static void wp_triggers_cache_add(struct target *target, unsigned int idx, riscv_reg_t tdata1, riscv_reg_t tdata2, int error_code)
Definition: riscv.c:1030
int riscv_remove_watchpoint(struct target *target, struct watchpoint *watchpoint)
Definition: riscv.c:1755
static int riscv_interrupts_restore(struct target *target, riscv_reg_t old_mstatus)
Definition: riscv.c:6011
static struct match_triggers_tdata1_fields fill_match_triggers_tdata1_fields_t2(struct target *target, struct trigger *trigger)
Definition: riscv.c:1165
static int riscv_get_gdb_reg_list_noread(struct target *target, struct reg **reg_list[], int *reg_list_size, enum target_register_class reg_class)
Definition: riscv.c:3543
static int oldriscv_step(struct target *target, bool current, uint32_t address, bool handle_breakpoints)
Definition: riscv.c:2440
static struct target_type * get_target_type(struct target *target)
Definition: riscv.c:456
static struct scan_field * bscan_tunnel_data_register_select_dmi
Definition: riscv.c:121
int riscv_get_command_timeout_sec(void)
Definition: riscv.c:179
static int find_first_trigger_by_id(struct target *target, int unique_id)
Definition: riscv.c:820
static void trigger_from_breakpoint(struct trigger *trigger, const struct breakpoint *breakpoint)
Definition: riscv.c:762
static const uint8_t bscan_zero[4]
Definition: riscv.c:63
static int riscv_interrupts_disable(struct target *target, riscv_reg_t *old_mstatus)
Definition: riscv.c:5997
static int riscv_write_memory(struct target *target, target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
Definition: riscv.c:3475
riscv_next_action
Definition: riscv.c:3832
@ RPH_RESUME
Definition: riscv.c:3834
@ RPH_NONE
Definition: riscv.c:3833
@ RPH_REMAIN_HALTED
Definition: riscv.c:3835
static int write_by_given_size(struct target *target, target_addr_t address, uint32_t size, uint8_t *buffer, uint32_t access_size)
Write one memory item of given "size".
Definition: riscv.c:1493
int riscv_enumerate_triggers(struct target *target)
Count triggers, and initialize trigger_count for each hart.
Definition: riscv.c:6216
riscv_cfg_opts
Definition: riscv.c:614
@ RISCV_CFG_EBREAK
Definition: riscv.c:615
@ RISCV_CFG_INVALID
Definition: riscv.c:616
int riscv_openocd_step(struct target *target, bool current, target_addr_t address, bool handle_breakpoints)
Definition: riscv.c:4287
static struct riscv_private_config * alloc_default_riscv_private_config(void)
Definition: riscv.c:478
static int resume_go(struct target *target, bool current, target_addr_t address, bool handle_breakpoints, bool debug_execution)
Resume all the harts that have been prepped, as close to instantaneous as possible.
Definition: riscv.c:2872
static uint8_t ir_idcode[4]
Definition: riscv.c:52
static int riscv_virt2phys(struct target *target, target_addr_t virtual, target_addr_t *physical)
Definition: riscv.c:3299
static int old_or_new_riscv_step(struct target *target, bool current, target_addr_t address, bool handle_breakpoints)
Definition: riscv.c:2465
static enum riscv_halt_reason riscv_halt_reason(struct target *target)
Definition: riscv.c:6079
static const virt2phys_info_t sv39
Definition: riscv.c:215
static int riscv_deassert_reset(struct target *target)
Definition: riscv.c:2771
#define DBUS
Definition: riscv.c:36
static const uint8_t bscan_one[4]
Definition: riscv.c:64
static uint32_t get_rs1_c(riscv_insn_t instruction)
Decode rs1' register num for RVC.
Definition: riscv.c:2020
static bool riscv_mem_access_is_valid(const struct riscv_mem_access_args args)
Definition: riscv.h:148
#define RISCV_SAMPLE_BUF_TIMESTAMP_BEFORE
Definition: riscv.h:102
#define RISCV_PGSHIFT
Definition: riscv.h:31
#define RISCV_INFO(R)
Definition: riscv.h:426
static struct riscv_info * riscv_info(const struct target *target) __attribute__((unused))
Definition: riscv.h:421
void riscv_semihosting_init(struct target *target)
Initialize RISC-V semihosting.
@ RISCV_MEM_ACCESS_MAX_METHODS_NUM
Definition: riscv.h:60
@ RISCV_MEM_ACCESS_SYSBUS
Definition: riscv.h:58
@ RISCV_MEM_ACCESS_PROGBUF
Definition: riscv.h:57
@ RISCV_MEM_ACCESS_ABSTRACT
Definition: riscv.h:59
riscv_hart_state
Definition: riscv.h:88
@ RISCV_STATE_RUNNING
Definition: riscv.h:90
@ RISCV_STATE_UNAVAILABLE
Definition: riscv.h:92
@ RISCV_STATE_NON_EXISTENT
Definition: riscv.h:89
@ RISCV_STATE_HALTED
Definition: riscv.h:91
enum semihosting_result riscv_semihosting(struct target *target, int *retval)
Check for and process a semihosting request using the ARM protocol).
#define RISCV_SATP_PPN(xlen)
Definition: riscv.h:28
#define RISCV_TINFO_VERSION_UNKNOWN
Definition: riscv.h:126
riscv_priv_mode
Definition: riscv.h:370
@ RISCV_MODE_M
Definition: riscv.h:371
@ RISCV_MODE_U
Definition: riscv.h:373
@ N_RISCV_MODE
Definition: riscv.h:376
@ RISCV_MODE_VU
Definition: riscv.h:375
@ RISCV_MODE_VS
Definition: riscv.h:374
@ RISCV_MODE_S
Definition: riscv.h:372
#define RISCV_PGSIZE
Definition: riscv.h:32
#define RISCV_SAMPLE_BUF_TIMESTAMP_AFTER
Definition: riscv.h:103
uint64_t riscv_reg_t
Definition: riscv.h:46
#define RISCV_PGOFFSET(addr)
Definition: riscv.h:34
#define RISCV_PGBASE(addr)
Definition: riscv.h:33
#define RISCV_COMMON_MAGIC
Definition: riscv.h:18
static bool riscv_mem_access_is_write(const struct riscv_mem_access_args args)
Definition: riscv.h:161
#define DEFAULT_COMMAND_TIMEOUT_SEC
Definition: riscv.h:25
bscan_tunnel_type_t
Definition: riscv.h:441
@ BSCAN_TUNNEL_NESTED_TAP
Definition: riscv.h:441
@ BSCAN_TUNNEL_DATA_REGISTER
Definition: riscv.h:441
static struct riscv_private_config * riscv_private_config(const struct target *target)
Definition: riscv.h:384
@ YNM_MAYBE
Definition: riscv.h:51
#define RISCV_SATP_MODE(xlen)
Definition: riscv.h:27
#define RISCV_HGATP_MODE(xlen)
Definition: riscv.h:29
uint32_t riscv_insn_t
Definition: riscv.h:47
riscv_halt_reason
Definition: riscv.h:71
@ RISCV_HALT_INTERRUPT
Definition: riscv.h:72
@ RISCV_HALT_SINGLESTEP
Definition: riscv.h:74
@ RISCV_HALT_EBREAK
Definition: riscv.h:73
@ RISCV_HALT_UNKNOWN
Definition: riscv.h:76
@ RISCV_HALT_ERROR
Definition: riscv.h:78
@ RISCV_HALT_GROUP
Definition: riscv.h:77
@ RISCV_HALT_TRIGGER
Definition: riscv.h:75
#define DTM_DTMCS_VERSION_UNKNOWN
Definition: riscv.h:125
#define RISCV_HGATP_PPN(xlen)
Definition: riscv.h:30
riscv_virt2phys_mode
Definition: riscv.h:63
@ RISCV_VIRT2PHYS_MODE_HW
Definition: riscv.h:64
@ RISCV_VIRT2PHYS_MODE_OFF
Definition: riscv.h:66
@ RISCV_VIRT2PHYS_MODE_SW
Definition: riscv.h:65
@ RISCV_ISRMASK_OFF
Definition: riscv.h:83
@ RISCV_ISRMASK_STEPONLY
Definition: riscv.h:85
int riscv_reg_set(struct target *target, enum gdb_regno regid, riscv_reg_t value)
This function is used to change the value of a register.
Definition: riscv_reg.c:918
void riscv_reg_cache_invalidate_all(struct target *target)
Invalidate all registers - forget their cached register values.
Definition: riscv_reg.c:899
const char * riscv_reg_gdb_regno_name(const struct target *target, enum gdb_regno regno)
This file describes the register cache interface available to the RISC-V target.
Definition: riscv_reg.c:171
int riscv_reg_flush_all(struct target *target)
Write all dirty registers to the target.
Definition: riscv_reg.c:776
int riscv_reg_get(struct target *target, riscv_reg_t *value, enum gdb_regno regid)
This function is used to get the value of a register.
Definition: riscv_reg.c:952
void riscv_reg_free_all(struct target *target)
Free register cache and associated structures.
Definition: riscv_reg.c:759
bool riscv_reg_cache_any_dirty(const struct target *target, int log_level)
Check whether there are any dirty registers in the OpenOCD's register cache.
Definition: riscv_reg.c:880
target_addr_t addr
Start address to search for the control block.
Definition: rtt/rtt.c:28
struct target * target
Definition: rtt/rtt.c:26
const struct command_registration semihosting_common_handlers[]
@ SEMIHOSTING_ERROR
@ SEMIHOSTING_HANDLED
@ SEMIHOSTING_WAITING
@ SEMIHOSTING_NONE
const struct command_registration smp_command_handlers[]
Definition: smp.c:153
#define foreach_smp_target(pos, head)
Definition: smp.h:15
#define foreach_smp_target_direction(forward, pos, head)
Definition: smp.h:18
#define BIT(nr)
Definition: stm32l4x.h:18
struct breakpoint * next
Definition: breakpoints.h:34
unsigned int length
Definition: breakpoints.h:29
uint8_t * orig_instr
Definition: breakpoints.h:33
enum breakpoint_type type
Definition: breakpoints.h:30
uint32_t unique_id
Definition: breakpoints.h:35
bool is_set
Definition: breakpoints.h:31
target_addr_t address
Definition: breakpoints.h:27
const char * name
Definition: command.h:234
A TCL -ish GetOpt like code.
Definition: jim-nvp.h:136
Jim_Interp * interp
Definition: jim-nvp.h:137
bool is_configure
Definition: jim-nvp.h:140
Jim_Obj *const * argv
Definition: jim-nvp.h:139
Name Value Pairs, aka: NVP.
Definition: jim-nvp.h:60
const char * name
Definition: jim-nvp.h:61
int value
Definition: jim-nvp.h:62
Definition: jtag.h:101
unsigned int ir_length
size of instruction register
Definition: jtag.h:110
Definition: list.h:41
struct match_triggers_tdata1_fields::@127 chain
struct match_triggers_tdata1_fields::@128 match
struct match_triggers_tdata1_fields::@126 size
char * name
Definition: riscv.h:122
uint16_t low
Definition: riscv.h:121
int(* get)(struct reg *reg)
Definition: register.h:152
int(* set)(struct reg *reg, uint8_t *buf)
Definition: register.h:153
unsigned int num_regs
Definition: register.h:148
struct reg * reg_list
Definition: register.h:147
uint32_t size
Definition: algorithm.h:29
uint8_t * value
Definition: algorithm.h:30
const char * reg_name
Definition: algorithm.h:28
Definition: register.h:111
bool valid
Definition: register.h:126
bool exist
Definition: register.h:128
uint32_t size
Definition: register.h:132
uint8_t * value
Definition: register.h:122
uint32_t number
Definition: register.h:115
const struct reg_arch_type * type
Definition: register.h:141
const char * name
Definition: register.h:113
struct scan_field tunneled_dr[4]
Definition: riscv.h:395
void * version_specific
Definition: riscv.h:174
enum riscv_virt2phys_mode virt2phys_mode
Definition: riscv.h:226
bool wp_allow_equality_match_trigger
Definition: riscv.h:363
struct list_head expose_custom
Definition: riscv.h:347
int64_t trigger_unique_id[RISCV_MAX_HWBPS]
Definition: riscv.h:219
int xlen
Definition: riscv.h:180
bool prepped
Definition: riscv.h:235
unsigned int num_enabled_mem_access_methods
Definition: riscv.h:335
enum riscv_isrmasking_mode isrmask_mode
Definition: riscv.h:244
unsigned int dtm_version
Definition: riscv.h:171
unsigned int halt_group_repoll_count
Definition: riscv.h:242
struct list_head expose_csr
Definition: riscv.h:343
enum yes_no_maybe vsew64_supported
Definition: riscv.h:359
bool autofence
Definition: riscv.h:367
unsigned int common_magic
Definition: riscv.h:169
bool mem_access_warn[RISCV_MEM_ACCESS_MAX_METHODS_NUM]
Definition: riscv.h:339
bool wp_allow_ge_lt_trigger
Definition: riscv.h:365
enum riscv_mem_access_method mem_access_methods[RISCV_MEM_ACCESS_MAX_METHODS_NUM]
Definition: riscv.h:333
bool wp_allow_napot_trigger
Definition: riscv.h:364
struct list_head hide_csr
Definition: riscv.h:351
uint8_t * read_buffer
Definition: riscv.h:140
const uint8_t * write_buffer
Definition: riscv.h:139
target_addr_t address
Definition: riscv.h:137
uint32_t count
Definition: riscv.h:143
This structure defines a single scan field in the scan.
Definition: jtag.h:87
uint8_t * in_value
A pointer to a 32-bit memory location for data scanned out.
Definition: jtag.h:93
const uint8_t * out_value
A pointer to value to be scanned into the device.
Definition: jtag.h:91
unsigned int num_bits
The number of bits this field specifies.
Definition: jtag.h:89
bool is_active
A flag reporting whether semihosting is active.
struct list_head lh
Definition: target.h:216
struct target * target
Definition: target.h:217
This holds methods shared between all instances of a given target type.
Definition: target_type.h:26
const char * name
Name of this type of target.
Definition: target_type.h:31
int(* deassert_reset)(struct target *target)
The implementation is responsible for polling the target such that target->state reflects the state c...
Definition: target_type.h:76
int(* init_target)(struct command_context *cmd_ctx, struct target *target)
Definition: target_type.h:225
int(* resume)(struct target *target, bool current, target_addr_t address, bool handle_breakpoints, bool debug_execution)
Definition: target_type.h:45
void(* deinit_target)(struct target *target)
Free all the resources allocated by the target.
Definition: target_type.h:243
int(* halt)(struct target *target)
Definition: target_type.h:43
int(* assert_reset)(struct target *target)
Definition: target_type.h:64
int(* arch_state)(struct target *target)
Definition: target_type.h:37
int(* step)(struct target *target, bool current, target_addr_t address, bool handle_breakpoints)
Definition: target_type.h:47
int(* poll)(struct target *target)
Definition: target_type.h:34
int(* examine)(struct target *target)
This method is used to perform target setup that requires JTAG access.
Definition: target_type.h:218
int(* virt2phys)(struct target *target, target_addr_t address, target_addr_t *physical)
Definition: target_type.h:248
Definition: target.h:119
struct semihosting * semihosting
Definition: target.h:212
struct jtag_tap * tap
Definition: target.h:122
enum target_debug_reason debug_reason
Definition: target.h:157
enum target_state state
Definition: target.h:160
void * private_config
Definition: target.h:168
struct reg_cache * reg_cache
Definition: target.h:161
struct list_head * smp_targets
Definition: target.h:191
struct breakpoint * breakpoints
Definition: target.h:162
unsigned int smp
Definition: target.h:190
struct target_type * type
Definition: target.h:120
struct watchpoint * watchpoints
Definition: target.h:163
void * arch_info
Definition: target.h:167
struct list_head elem_tdata1
Definition: riscv.c:141
struct list_head tdata2_cache_head
Definition: riscv.c:140
riscv_reg_t tdata1
Definition: riscv.c:139
struct list_head elem_tdata2
Definition: riscv.c:134
riscv_reg_t tdata2
Definition: riscv.c:135
Definition: psoc6.c:83
riscv_reg_t tdata2
Definition: riscv.c:976
riscv_reg_t tdata1
Definition: riscv.c:975
Definition: riscv.c:124
bool is_write
Definition: riscv.c:129
uint64_t value
Definition: riscv.c:128
uint64_t address
Definition: riscv.c:125
uint32_t length
Definition: riscv.c:126
bool is_read
Definition: riscv.c:129
uint64_t mask
Definition: riscv.c:127
int unique_id
Definition: riscv.c:130
bool is_execute
Definition: riscv.c:129
const char * name
Definition: riscv.h:399
uint64_t mask
Definition: breakpoints.h:44
enum watchpoint_rw rw
Definition: breakpoints.h:46
bool is_set
Definition: breakpoints.h:47
struct watchpoint * next
Definition: breakpoints.h:49
unsigned int length
Definition: breakpoints.h:43
uint64_t value
Definition: breakpoints.h:45
int unique_id
Definition: breakpoints.h:50
target_addr_t address
Definition: breakpoints.h:42
uint32_t size
Definition: target.h:90
target_addr_t address
Definition: target.h:89
int target_call_event_callbacks(struct target *target, enum target_event event)
Definition: target.c:1774
int target_write_buffer(struct target *target, target_addr_t address, uint32_t size, const uint8_t *buffer)
Definition: target.c:2351
int target_read_buffer(struct target *target, target_addr_t address, uint32_t size, uint8_t *buffer)
Definition: target.c:2416
int target_run_algorithm(struct target *target, int num_mem_params, struct mem_param *mem_params, int num_reg_params, struct reg_param *reg_param, target_addr_t entry_point, target_addr_t exit_point, unsigned int timeout_ms, void *arch_info)
Downloads a target-specific native code algorithm to the target, and executes it.
Definition: target.c:783
int target_write_memory(struct target *target, target_addr_t address, uint32_t size, uint32_t count, const uint8_t *buffer)
Write count items of size bytes to the memory of target at the address given.
Definition: target.c:1275
int target_alloc_working_area(struct target *target, uint32_t size, struct working_area **area)
Definition: target.c:2070
const char * target_state_name(const struct target *t)
Return the name of this targets current state.
Definition: target.c:269
int target_free_working_area(struct target *target, struct working_area *area)
Free a working area.
Definition: target.c:2128
int target_read_memory(struct target *target, target_addr_t address, uint32_t size, uint32_t count, uint8_t *buffer)
Read count items of size bytes from the memory of target at the address given.
Definition: target.c:1247
const char * debug_reason_name(const struct target *t)
Definition: target.c:256
struct target * get_current_target(struct command_context *cmd_ctx)
Definition: target.c:467
void target_handle_md_output(struct command_invocation *cmd, struct target *target, target_addr_t address, unsigned int size, unsigned int count, const uint8_t *buffer, bool include_address)
Definition: target.c:3350
target_debug_reason
Definition: target.h:71
@ DBG_REASON_UNDEFINED
Definition: target.h:80
@ DBG_REASON_NOTHALTED
Definition: target.h:77
@ DBG_REASON_DBGRQ
Definition: target.h:72
@ DBG_REASON_SINGLESTEP
Definition: target.h:76
@ DBG_REASON_WATCHPOINT
Definition: target.h:74
@ DBG_REASON_BREAKPOINT
Definition: target.h:73
target_register_class
Definition: target.h:113
@ REG_CLASS_GENERAL
Definition: target.h:115
@ REG_CLASS_ALL
Definition: target.h:114
#define ERROR_TARGET_NOT_HALTED
Definition: target.h:786
static bool target_was_examined(const struct target *target)
Definition: target.h:432
@ TARGET_EVENT_DEBUG_RESUMED
Definition: target.h:275
@ TARGET_EVENT_HALTED
Definition: target.h:255
@ TARGET_EVENT_RESUMED
Definition: target.h:256
@ TARGET_EVENT_DEBUG_HALTED
Definition: target.h:274
static const char * target_name(const struct target *target)
Returns the instance-specific name of the specified target.
Definition: target.h:236
target_state
Definition: target.h:55
@ TARGET_RESET
Definition: target.h:59
@ TARGET_DEBUG_RUNNING
Definition: target.h:60
@ TARGET_UNKNOWN
Definition: target.h:56
@ TARGET_UNAVAILABLE
Definition: target.h:61
@ TARGET_HALTED
Definition: target.h:58
@ TARGET_RUNNING
Definition: target.h:57
#define TARGET_DEFAULT_POLLING_INTERVAL
Definition: target.h:802
#define ERROR_TARGET_TIMEOUT
Definition: target.h:785
#define ERROR_TARGET_RESOURCE_NOT_AVAILABLE
Definition: target.h:790
int64_t timeval_ms(void)
#define TARGET_ADDR_FMT
Definition: types.h:286
static void h_u32_to_le(uint8_t *buf, uint32_t val)
Definition: types.h:178
#define ARRAY_SIZE(x)
Compute the number of elements of a variable length array.
Definition: types.h:57
uint64_t target_addr_t
Definition: types.h:279
#define TARGET_PRIxADDR
Definition: types.h:284
static struct ublast_lowlevel low
static struct ublast_lowlevel_priv info
#define NULL
Definition: usb.h:16
uint8_t cmd
Definition: vdebug.c:1
uint8_t offset[4]
Definition: vdebug.c:9
uint8_t state[4]
Definition: vdebug.c:21
uint8_t count[4]
Definition: vdebug.c:22