arm_adi_v5: Added Cortex-A76 identifiers
[fw/openocd] / src / target / arm_adi_v5.c
1 /***************************************************************************
2  *   Copyright (C) 2006 by Magnus Lundin                                   *
3  *   lundin@mlu.mine.nu                                                    *
4  *                                                                         *
5  *   Copyright (C) 2008 by Spencer Oliver                                  *
6  *   spen@spen-soft.co.uk                                                  *
7  *                                                                         *
8  *   Copyright (C) 2009-2010 by Oyvind Harboe                              *
9  *   oyvind.harboe@zylin.com                                               *
10  *                                                                         *
11  *   Copyright (C) 2009-2010 by David Brownell                             *
12  *                                                                         *
13  *   Copyright (C) 2013 by Andreas Fritiofson                              *
14  *   andreas.fritiofson@gmail.com                                          *
15  *                                                                         *
16  *   Copyright (C) 2019-2021, Ampere Computing LLC                         *
17  *                                                                         *
18  *   This program is free software; you can redistribute it and/or modify  *
19  *   it under the terms of the GNU General Public License as published by  *
20  *   the Free Software Foundation; either version 2 of the License, or     *
21  *   (at your option) any later version.                                   *
22  *                                                                         *
23  *   This program is distributed in the hope that it will be useful,       *
24  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
25  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
26  *   GNU General Public License for more details.                          *
27  *                                                                         *
28  *   You should have received a copy of the GNU General Public License     *
29  *   along with this program.  If not, see <http://www.gnu.org/licenses/>. *
30  ***************************************************************************/
31
32 /**
33  * @file
34  * This file implements support for the ARM Debug Interface version 5 (ADIv5)
35  * debugging architecture.  Compared with previous versions, this includes
36  * a low pin-count Serial Wire Debug (SWD) alternative to JTAG for message
37  * transport, and focuses on memory mapped resources as defined by the
38  * CoreSight architecture.
39  *
40  * A key concept in ADIv5 is the Debug Access Port, or DAP.  A DAP has two
41  * basic components:  a Debug Port (DP) transporting messages to and from a
42  * debugger, and an Access Port (AP) accessing resources.  Three types of DP
43  * are defined.  One uses only JTAG for communication, and is called JTAG-DP.
44  * One uses only SWD for communication, and is called SW-DP.  The third can
45  * use either SWD or JTAG, and is called SWJ-DP.  The most common type of AP
46  * is used to access memory mapped resources and is called a MEM-AP.  Also a
47  * JTAG-AP is also defined, bridging to JTAG resources; those are uncommon.
48  *
49  * This programming interface allows DAP pipelined operations through a
50  * transaction queue.  This primarily affects AP operations (such as using
51  * a MEM-AP to access memory or registers).  If the current transaction has
52  * not finished by the time the next one must begin, and the ORUNDETECT bit
53  * is set in the DP_CTRL_STAT register, the SSTICKYORUN status is set and
54  * further AP operations will fail.  There are two basic methods to avoid
55  * such overrun errors.  One involves polling for status instead of using
56  * transaction pipelining.  The other involves adding delays to ensure the
57  * AP has enough time to complete one operation before starting the next
58  * one.  (For JTAG these delays are controlled by memaccess_tck.)
59  */
60
61 /*
62  * Relevant specifications from ARM include:
63  *
64  * ARM(tm) Debug Interface v5 Architecture Specification    ARM IHI 0031E
65  * CoreSight(tm) v1.0 Architecture Specification            ARM IHI 0029B
66  *
67  * CoreSight(tm) DAP-Lite TRM, ARM DDI 0316D
68  * Cortex-M3(tm) TRM, ARM DDI 0337G
69  */
70
71 #ifdef HAVE_CONFIG_H
72 #include "config.h"
73 #endif
74
75 #include "jtag/interface.h"
76 #include "arm.h"
77 #include "arm_adi_v5.h"
78 #include "jtag/swd.h"
79 #include "transport/transport.h"
80 #include <helper/jep106.h>
81 #include <helper/time_support.h>
82 #include <helper/list.h>
83 #include <helper/jim-nvp.h>
84
85 /* ARM ADI Specification requires at least 10 bits used for TAR autoincrement  */
86
87 /*
88         uint32_t tar_block_size(uint32_t address)
89         Return the largest block starting at address that does not cross a tar block size alignment boundary
90 */
91 static uint32_t max_tar_block_size(uint32_t tar_autoincr_block, target_addr_t address)
92 {
93         return tar_autoincr_block - ((tar_autoincr_block - 1) & address);
94 }
95
96 /***************************************************************************
97  *                                                                         *
98  * DP and MEM-AP  register access  through APACC and DPACC                 *
99  *                                                                         *
100 ***************************************************************************/
101
102 static int mem_ap_setup_csw(struct adiv5_ap *ap, uint32_t csw)
103 {
104         csw |= ap->csw_default;
105
106         if (csw != ap->csw_value) {
107                 /* LOG_DEBUG("DAP: Set CSW %x",csw); */
108                 int retval = dap_queue_ap_write(ap, MEM_AP_REG_CSW, csw);
109                 if (retval != ERROR_OK) {
110                         ap->csw_value = 0;
111                         return retval;
112                 }
113                 ap->csw_value = csw;
114         }
115         return ERROR_OK;
116 }
117
118 static int mem_ap_setup_tar(struct adiv5_ap *ap, target_addr_t tar)
119 {
120         if (!ap->tar_valid || tar != ap->tar_value) {
121                 /* LOG_DEBUG("DAP: Set TAR %x",tar); */
122                 int retval = dap_queue_ap_write(ap, MEM_AP_REG_TAR, (uint32_t)(tar & 0xffffffffUL));
123                 if (retval == ERROR_OK && is_64bit_ap(ap)) {
124                         /* See if bits 63:32 of tar is different from last setting */
125                         if ((ap->tar_value >> 32) != (tar >> 32))
126                                 retval = dap_queue_ap_write(ap, MEM_AP_REG_TAR64, (uint32_t)(tar >> 32));
127                 }
128                 if (retval != ERROR_OK) {
129                         ap->tar_valid = false;
130                         return retval;
131                 }
132                 ap->tar_value = tar;
133                 ap->tar_valid = true;
134         }
135         return ERROR_OK;
136 }
137
138 static int mem_ap_read_tar(struct adiv5_ap *ap, target_addr_t *tar)
139 {
140         uint32_t lower;
141         uint32_t upper = 0;
142
143         int retval = dap_queue_ap_read(ap, MEM_AP_REG_TAR, &lower);
144         if (retval == ERROR_OK && is_64bit_ap(ap))
145                 retval = dap_queue_ap_read(ap, MEM_AP_REG_TAR64, &upper);
146
147         if (retval != ERROR_OK) {
148                 ap->tar_valid = false;
149                 return retval;
150         }
151
152         retval = dap_run(ap->dap);
153         if (retval != ERROR_OK) {
154                 ap->tar_valid = false;
155                 return retval;
156         }
157
158         *tar = (((target_addr_t)upper) << 32) | (target_addr_t)lower;
159
160         ap->tar_value = *tar;
161         ap->tar_valid = true;
162         return ERROR_OK;
163 }
164
165 static uint32_t mem_ap_get_tar_increment(struct adiv5_ap *ap)
166 {
167         switch (ap->csw_value & CSW_ADDRINC_MASK) {
168         case CSW_ADDRINC_SINGLE:
169                 switch (ap->csw_value & CSW_SIZE_MASK) {
170                 case CSW_8BIT:
171                         return 1;
172                 case CSW_16BIT:
173                         return 2;
174                 case CSW_32BIT:
175                         return 4;
176                 default:
177                         return 0;
178                 }
179         case CSW_ADDRINC_PACKED:
180                 return 4;
181         }
182         return 0;
183 }
184
185 /* mem_ap_update_tar_cache is called after an access to MEM_AP_REG_DRW
186  */
187 static void mem_ap_update_tar_cache(struct adiv5_ap *ap)
188 {
189         if (!ap->tar_valid)
190                 return;
191
192         uint32_t inc = mem_ap_get_tar_increment(ap);
193         if (inc >= max_tar_block_size(ap->tar_autoincr_block, ap->tar_value))
194                 ap->tar_valid = false;
195         else
196                 ap->tar_value += inc;
197 }
198
199 /**
200  * Queue transactions setting up transfer parameters for the
201  * currently selected MEM-AP.
202  *
203  * Subsequent transfers using registers like MEM_AP_REG_DRW or MEM_AP_REG_BD2
204  * initiate data reads or writes using memory or peripheral addresses.
205  * If the CSW is configured for it, the TAR may be automatically
206  * incremented after each transfer.
207  *
208  * @param ap The MEM-AP.
209  * @param csw MEM-AP Control/Status Word (CSW) register to assign.  If this
210  *      matches the cached value, the register is not changed.
211  * @param tar MEM-AP Transfer Address Register (TAR) to assign.  If this
212  *      matches the cached address, the register is not changed.
213  *
214  * @return ERROR_OK if the transaction was properly queued, else a fault code.
215  */
216 static int mem_ap_setup_transfer(struct adiv5_ap *ap, uint32_t csw, target_addr_t tar)
217 {
218         int retval;
219         retval = mem_ap_setup_csw(ap, csw);
220         if (retval != ERROR_OK)
221                 return retval;
222         retval = mem_ap_setup_tar(ap, tar);
223         if (retval != ERROR_OK)
224                 return retval;
225         return ERROR_OK;
226 }
227
228 /**
229  * Asynchronous (queued) read of a word from memory or a system register.
230  *
231  * @param ap The MEM-AP to access.
232  * @param address Address of the 32-bit word to read; it must be
233  *      readable by the currently selected MEM-AP.
234  * @param value points to where the word will be stored when the
235  *      transaction queue is flushed (assuming no errors).
236  *
237  * @return ERROR_OK for success.  Otherwise a fault code.
238  */
239 int mem_ap_read_u32(struct adiv5_ap *ap, target_addr_t address,
240                 uint32_t *value)
241 {
242         int retval;
243
244         /* Use banked addressing (REG_BDx) to avoid some link traffic
245          * (updating TAR) when reading several consecutive addresses.
246          */
247         retval = mem_ap_setup_transfer(ap,
248                         CSW_32BIT | (ap->csw_value & CSW_ADDRINC_MASK),
249                         address & 0xFFFFFFFFFFFFFFF0ull);
250         if (retval != ERROR_OK)
251                 return retval;
252
253         return dap_queue_ap_read(ap, MEM_AP_REG_BD0 | (address & 0xC), value);
254 }
255
256 /**
257  * Synchronous read of a word from memory or a system register.
258  * As a side effect, this flushes any queued transactions.
259  *
260  * @param ap The MEM-AP to access.
261  * @param address Address of the 32-bit word to read; it must be
262  *      readable by the currently selected MEM-AP.
263  * @param value points to where the result will be stored.
264  *
265  * @return ERROR_OK for success; *value holds the result.
266  * Otherwise a fault code.
267  */
268 int mem_ap_read_atomic_u32(struct adiv5_ap *ap, target_addr_t address,
269                 uint32_t *value)
270 {
271         int retval;
272
273         retval = mem_ap_read_u32(ap, address, value);
274         if (retval != ERROR_OK)
275                 return retval;
276
277         return dap_run(ap->dap);
278 }
279
280 /**
281  * Asynchronous (queued) write of a word to memory or a system register.
282  *
283  * @param ap The MEM-AP to access.
284  * @param address Address to be written; it must be writable by
285  *      the currently selected MEM-AP.
286  * @param value Word that will be written to the address when transaction
287  *      queue is flushed (assuming no errors).
288  *
289  * @return ERROR_OK for success.  Otherwise a fault code.
290  */
291 int mem_ap_write_u32(struct adiv5_ap *ap, target_addr_t address,
292                 uint32_t value)
293 {
294         int retval;
295
296         /* Use banked addressing (REG_BDx) to avoid some link traffic
297          * (updating TAR) when writing several consecutive addresses.
298          */
299         retval = mem_ap_setup_transfer(ap,
300                         CSW_32BIT | (ap->csw_value & CSW_ADDRINC_MASK),
301                         address & 0xFFFFFFFFFFFFFFF0ull);
302         if (retval != ERROR_OK)
303                 return retval;
304
305         return dap_queue_ap_write(ap, MEM_AP_REG_BD0 | (address & 0xC),
306                         value);
307 }
308
309 /**
310  * Synchronous write of a word to memory or a system register.
311  * As a side effect, this flushes any queued transactions.
312  *
313  * @param ap The MEM-AP to access.
314  * @param address Address to be written; it must be writable by
315  *      the currently selected MEM-AP.
316  * @param value Word that will be written.
317  *
318  * @return ERROR_OK for success; the data was written.  Otherwise a fault code.
319  */
320 int mem_ap_write_atomic_u32(struct adiv5_ap *ap, target_addr_t address,
321                 uint32_t value)
322 {
323         int retval = mem_ap_write_u32(ap, address, value);
324
325         if (retval != ERROR_OK)
326                 return retval;
327
328         return dap_run(ap->dap);
329 }
330
331 /**
332  * Synchronous write of a block of memory, using a specific access size.
333  *
334  * @param ap The MEM-AP to access.
335  * @param buffer The data buffer to write. No particular alignment is assumed.
336  * @param size Which access size to use, in bytes. 1, 2 or 4.
337  * @param count The number of writes to do (in size units, not bytes).
338  * @param address Address to be written; it must be writable by the currently selected MEM-AP.
339  * @param addrinc Whether the target address should be increased for each write or not. This
340  *  should normally be true, except when writing to e.g. a FIFO.
341  * @return ERROR_OK on success, otherwise an error code.
342  */
343 static int mem_ap_write(struct adiv5_ap *ap, const uint8_t *buffer, uint32_t size, uint32_t count,
344                 target_addr_t address, bool addrinc)
345 {
346         struct adiv5_dap *dap = ap->dap;
347         size_t nbytes = size * count;
348         const uint32_t csw_addrincr = addrinc ? CSW_ADDRINC_SINGLE : CSW_ADDRINC_OFF;
349         uint32_t csw_size;
350         target_addr_t addr_xor;
351         int retval = ERROR_OK;
352
353         /* TI BE-32 Quirks mode:
354          * Writes on big-endian TMS570 behave very strangely. Observed behavior:
355          *   size   write address   bytes written in order
356          *   4      TAR ^ 0         (val >> 24), (val >> 16), (val >> 8), (val)
357          *   2      TAR ^ 2         (val >> 8), (val)
358          *   1      TAR ^ 3         (val)
359          * For example, if you attempt to write a single byte to address 0, the processor
360          * will actually write a byte to address 3.
361          *
362          * To make writes of size < 4 work as expected, we xor a value with the address before
363          * setting the TAP, and we set the TAP after every transfer rather then relying on
364          * address increment. */
365
366         if (size == 4) {
367                 csw_size = CSW_32BIT;
368                 addr_xor = 0;
369         } else if (size == 2) {
370                 csw_size = CSW_16BIT;
371                 addr_xor = dap->ti_be_32_quirks ? 2 : 0;
372         } else if (size == 1) {
373                 csw_size = CSW_8BIT;
374                 addr_xor = dap->ti_be_32_quirks ? 3 : 0;
375         } else {
376                 return ERROR_TARGET_UNALIGNED_ACCESS;
377         }
378
379         if (ap->unaligned_access_bad && (address % size != 0))
380                 return ERROR_TARGET_UNALIGNED_ACCESS;
381
382         while (nbytes > 0) {
383                 uint32_t this_size = size;
384
385                 /* Select packed transfer if possible */
386                 if (addrinc && ap->packed_transfers && nbytes >= 4
387                                 && max_tar_block_size(ap->tar_autoincr_block, address) >= 4) {
388                         this_size = 4;
389                         retval = mem_ap_setup_csw(ap, csw_size | CSW_ADDRINC_PACKED);
390                 } else {
391                         retval = mem_ap_setup_csw(ap, csw_size | csw_addrincr);
392                 }
393
394                 if (retval != ERROR_OK)
395                         break;
396
397                 retval = mem_ap_setup_tar(ap, address ^ addr_xor);
398                 if (retval != ERROR_OK)
399                         return retval;
400
401                 /* How many source bytes each transfer will consume, and their location in the DRW,
402                  * depends on the type of transfer and alignment. See ARM document IHI0031C. */
403                 uint32_t outvalue = 0;
404                 uint32_t drw_byte_idx = address;
405                 if (dap->ti_be_32_quirks) {
406                         switch (this_size) {
407                         case 4:
408                                 outvalue |= (uint32_t)*buffer++ << 8 * (3 ^ (drw_byte_idx++ & 3) ^ addr_xor);
409                                 outvalue |= (uint32_t)*buffer++ << 8 * (3 ^ (drw_byte_idx++ & 3) ^ addr_xor);
410                                 outvalue |= (uint32_t)*buffer++ << 8 * (3 ^ (drw_byte_idx++ & 3) ^ addr_xor);
411                                 outvalue |= (uint32_t)*buffer++ << 8 * (3 ^ (drw_byte_idx & 3) ^ addr_xor);
412                                 break;
413                         case 2:
414                                 outvalue |= (uint32_t)*buffer++ << 8 * (1 ^ (drw_byte_idx++ & 3) ^ addr_xor);
415                                 outvalue |= (uint32_t)*buffer++ << 8 * (1 ^ (drw_byte_idx & 3) ^ addr_xor);
416                                 break;
417                         case 1:
418                                 outvalue |= (uint32_t)*buffer++ << 8 * (0 ^ (drw_byte_idx & 3) ^ addr_xor);
419                                 break;
420                         }
421                 } else {
422                         switch (this_size) {
423                         case 4:
424                                 outvalue |= (uint32_t)*buffer++ << 8 * (drw_byte_idx++ & 3);
425                                 outvalue |= (uint32_t)*buffer++ << 8 * (drw_byte_idx++ & 3);
426                                 /* fallthrough */
427                         case 2:
428                                 outvalue |= (uint32_t)*buffer++ << 8 * (drw_byte_idx++ & 3);
429                                 /* fallthrough */
430                         case 1:
431                                 outvalue |= (uint32_t)*buffer++ << 8 * (drw_byte_idx & 3);
432                         }
433                 }
434
435                 nbytes -= this_size;
436
437                 retval = dap_queue_ap_write(ap, MEM_AP_REG_DRW, outvalue);
438                 if (retval != ERROR_OK)
439                         break;
440
441                 mem_ap_update_tar_cache(ap);
442                 if (addrinc)
443                         address += this_size;
444         }
445
446         /* REVISIT: Might want to have a queued version of this function that does not run. */
447         if (retval == ERROR_OK)
448                 retval = dap_run(dap);
449
450         if (retval != ERROR_OK) {
451                 target_addr_t tar;
452                 if (mem_ap_read_tar(ap, &tar) == ERROR_OK)
453                         LOG_ERROR("Failed to write memory at " TARGET_ADDR_FMT, tar);
454                 else
455                         LOG_ERROR("Failed to write memory and, additionally, failed to find out where");
456         }
457
458         return retval;
459 }
460
461 /**
462  * Synchronous read of a block of memory, using a specific access size.
463  *
464  * @param ap The MEM-AP to access.
465  * @param buffer The data buffer to receive the data. No particular alignment is assumed.
466  * @param size Which access size to use, in bytes. 1, 2 or 4.
467  * @param count The number of reads to do (in size units, not bytes).
468  * @param adr Address to be read; it must be readable by the currently selected MEM-AP.
469  * @param addrinc Whether the target address should be increased after each read or not. This
470  *  should normally be true, except when reading from e.g. a FIFO.
471  * @return ERROR_OK on success, otherwise an error code.
472  */
473 static int mem_ap_read(struct adiv5_ap *ap, uint8_t *buffer, uint32_t size, uint32_t count,
474                 target_addr_t adr, bool addrinc)
475 {
476         struct adiv5_dap *dap = ap->dap;
477         size_t nbytes = size * count;
478         const uint32_t csw_addrincr = addrinc ? CSW_ADDRINC_SINGLE : CSW_ADDRINC_OFF;
479         uint32_t csw_size;
480         target_addr_t address = adr;
481         int retval = ERROR_OK;
482
483         /* TI BE-32 Quirks mode:
484          * Reads on big-endian TMS570 behave strangely differently than writes.
485          * They read from the physical address requested, but with DRW byte-reversed.
486          * For example, a byte read from address 0 will place the result in the high bytes of DRW.
487          * Also, packed 8-bit and 16-bit transfers seem to sometimes return garbage in some bytes,
488          * so avoid them. */
489
490         if (size == 4)
491                 csw_size = CSW_32BIT;
492         else if (size == 2)
493                 csw_size = CSW_16BIT;
494         else if (size == 1)
495                 csw_size = CSW_8BIT;
496         else
497                 return ERROR_TARGET_UNALIGNED_ACCESS;
498
499         if (ap->unaligned_access_bad && (adr % size != 0))
500                 return ERROR_TARGET_UNALIGNED_ACCESS;
501
502         /* Allocate buffer to hold the sequence of DRW reads that will be made. This is a significant
503          * over-allocation if packed transfers are going to be used, but determining the real need at
504          * this point would be messy. */
505         uint32_t *read_buf = calloc(count, sizeof(uint32_t));
506         /* Multiplication count * sizeof(uint32_t) may overflow, calloc() is safe */
507         uint32_t *read_ptr = read_buf;
508         if (!read_buf) {
509                 LOG_ERROR("Failed to allocate read buffer");
510                 return ERROR_FAIL;
511         }
512
513         /* Queue up all reads. Each read will store the entire DRW word in the read buffer. How many
514          * useful bytes it contains, and their location in the word, depends on the type of transfer
515          * and alignment. */
516         while (nbytes > 0) {
517                 uint32_t this_size = size;
518
519                 /* Select packed transfer if possible */
520                 if (addrinc && ap->packed_transfers && nbytes >= 4
521                                 && max_tar_block_size(ap->tar_autoincr_block, address) >= 4) {
522                         this_size = 4;
523                         retval = mem_ap_setup_csw(ap, csw_size | CSW_ADDRINC_PACKED);
524                 } else {
525                         retval = mem_ap_setup_csw(ap, csw_size | csw_addrincr);
526                 }
527                 if (retval != ERROR_OK)
528                         break;
529
530                 retval = mem_ap_setup_tar(ap, address);
531                 if (retval != ERROR_OK)
532                         break;
533
534                 retval = dap_queue_ap_read(ap, MEM_AP_REG_DRW, read_ptr++);
535                 if (retval != ERROR_OK)
536                         break;
537
538                 nbytes -= this_size;
539                 if (addrinc)
540                         address += this_size;
541
542                 mem_ap_update_tar_cache(ap);
543         }
544
545         if (retval == ERROR_OK)
546                 retval = dap_run(dap);
547
548         /* Restore state */
549         address = adr;
550         nbytes = size * count;
551         read_ptr = read_buf;
552
553         /* If something failed, read TAR to find out how much data was successfully read, so we can
554          * at least give the caller what we have. */
555         if (retval != ERROR_OK) {
556                 target_addr_t tar;
557                 if (mem_ap_read_tar(ap, &tar) == ERROR_OK) {
558                         /* TAR is incremented after failed transfer on some devices (eg Cortex-M4) */
559                         LOG_ERROR("Failed to read memory at " TARGET_ADDR_FMT, tar);
560                         if (nbytes > tar - address)
561                                 nbytes = tar - address;
562                 } else {
563                         LOG_ERROR("Failed to read memory and, additionally, failed to find out where");
564                         nbytes = 0;
565                 }
566         }
567
568         /* Replay loop to populate caller's buffer from the correct word and byte lane */
569         while (nbytes > 0) {
570                 uint32_t this_size = size;
571
572                 if (addrinc && ap->packed_transfers && nbytes >= 4
573                                 && max_tar_block_size(ap->tar_autoincr_block, address) >= 4) {
574                         this_size = 4;
575                 }
576
577                 if (dap->ti_be_32_quirks) {
578                         switch (this_size) {
579                         case 4:
580                                 *buffer++ = *read_ptr >> 8 * (3 - (address++ & 3));
581                                 *buffer++ = *read_ptr >> 8 * (3 - (address++ & 3));
582                                 /* fallthrough */
583                         case 2:
584                                 *buffer++ = *read_ptr >> 8 * (3 - (address++ & 3));
585                                 /* fallthrough */
586                         case 1:
587                                 *buffer++ = *read_ptr >> 8 * (3 - (address++ & 3));
588                         }
589                 } else {
590                         switch (this_size) {
591                         case 4:
592                                 *buffer++ = *read_ptr >> 8 * (address++ & 3);
593                                 *buffer++ = *read_ptr >> 8 * (address++ & 3);
594                                 /* fallthrough */
595                         case 2:
596                                 *buffer++ = *read_ptr >> 8 * (address++ & 3);
597                                 /* fallthrough */
598                         case 1:
599                                 *buffer++ = *read_ptr >> 8 * (address++ & 3);
600                         }
601                 }
602
603                 read_ptr++;
604                 nbytes -= this_size;
605         }
606
607         free(read_buf);
608         return retval;
609 }
610
611 int mem_ap_read_buf(struct adiv5_ap *ap,
612                 uint8_t *buffer, uint32_t size, uint32_t count, target_addr_t address)
613 {
614         return mem_ap_read(ap, buffer, size, count, address, true);
615 }
616
617 int mem_ap_write_buf(struct adiv5_ap *ap,
618                 const uint8_t *buffer, uint32_t size, uint32_t count, target_addr_t address)
619 {
620         return mem_ap_write(ap, buffer, size, count, address, true);
621 }
622
623 int mem_ap_read_buf_noincr(struct adiv5_ap *ap,
624                 uint8_t *buffer, uint32_t size, uint32_t count, target_addr_t address)
625 {
626         return mem_ap_read(ap, buffer, size, count, address, false);
627 }
628
629 int mem_ap_write_buf_noincr(struct adiv5_ap *ap,
630                 const uint8_t *buffer, uint32_t size, uint32_t count, target_addr_t address)
631 {
632         return mem_ap_write(ap, buffer, size, count, address, false);
633 }
634
635 /*--------------------------------------------------------------------------*/
636
637
638 #define DAP_POWER_DOMAIN_TIMEOUT (10)
639
640 /*--------------------------------------------------------------------------*/
641
642 /**
643  * Invalidate cached DP select and cached TAR and CSW of all APs
644  */
645 void dap_invalidate_cache(struct adiv5_dap *dap)
646 {
647         dap->select = DP_SELECT_INVALID;
648         dap->last_read = NULL;
649
650         int i;
651         for (i = 0; i <= 255; i++) {
652                 /* force csw and tar write on the next mem-ap access */
653                 dap->ap[i].tar_valid = false;
654                 dap->ap[i].csw_value = 0;
655         }
656 }
657
658 /**
659  * Initialize a DAP.  This sets up the power domains, prepares the DP
660  * for further use and activates overrun checking.
661  *
662  * @param dap The DAP being initialized.
663  */
664 int dap_dp_init(struct adiv5_dap *dap)
665 {
666         int retval;
667
668         LOG_DEBUG("%s", adiv5_dap_name(dap));
669
670         dap->do_reconnect = false;
671         dap_invalidate_cache(dap);
672
673         /*
674          * Early initialize dap->dp_ctrl_stat.
675          * In jtag mode only, if the following queue run (in dap_dp_poll_register)
676          * fails and sets the sticky error, it will trigger the clearing
677          * of the sticky. Without this initialization system and debug power
678          * would be disabled while clearing the sticky error bit.
679          */
680         dap->dp_ctrl_stat = CDBGPWRUPREQ | CSYSPWRUPREQ;
681
682         /*
683          * This write operation clears the sticky error bit in jtag mode only and
684          * is ignored in swd mode. It also powers-up system and debug domains in
685          * both jtag and swd modes, if not done before.
686          */
687         retval = dap_queue_dp_write(dap, DP_CTRL_STAT, dap->dp_ctrl_stat | SSTICKYERR);
688         if (retval != ERROR_OK)
689                 return retval;
690
691         retval = dap_queue_dp_read(dap, DP_CTRL_STAT, NULL);
692         if (retval != ERROR_OK)
693                 return retval;
694
695         retval = dap_queue_dp_write(dap, DP_CTRL_STAT, dap->dp_ctrl_stat);
696         if (retval != ERROR_OK)
697                 return retval;
698
699         /* Check that we have debug power domains activated */
700         LOG_DEBUG("DAP: wait CDBGPWRUPACK");
701         retval = dap_dp_poll_register(dap, DP_CTRL_STAT,
702                                       CDBGPWRUPACK, CDBGPWRUPACK,
703                                       DAP_POWER_DOMAIN_TIMEOUT);
704         if (retval != ERROR_OK)
705                 return retval;
706
707         if (!dap->ignore_syspwrupack) {
708                 LOG_DEBUG("DAP: wait CSYSPWRUPACK");
709                 retval = dap_dp_poll_register(dap, DP_CTRL_STAT,
710                                               CSYSPWRUPACK, CSYSPWRUPACK,
711                                               DAP_POWER_DOMAIN_TIMEOUT);
712                 if (retval != ERROR_OK)
713                         return retval;
714         }
715
716         retval = dap_queue_dp_read(dap, DP_CTRL_STAT, NULL);
717         if (retval != ERROR_OK)
718                 return retval;
719
720         /* With debug power on we can activate OVERRUN checking */
721         dap->dp_ctrl_stat = CDBGPWRUPREQ | CSYSPWRUPREQ | CORUNDETECT;
722         retval = dap_queue_dp_write(dap, DP_CTRL_STAT, dap->dp_ctrl_stat);
723         if (retval != ERROR_OK)
724                 return retval;
725         retval = dap_queue_dp_read(dap, DP_CTRL_STAT, NULL);
726         if (retval != ERROR_OK)
727                 return retval;
728
729         retval = dap_run(dap);
730         if (retval != ERROR_OK)
731                 return retval;
732
733         return retval;
734 }
735
736 /**
737  * Initialize a DAP or do reconnect if DAP is not accessible.
738  *
739  * @param dap The DAP being initialized.
740  */
741 int dap_dp_init_or_reconnect(struct adiv5_dap *dap)
742 {
743         LOG_DEBUG("%s", adiv5_dap_name(dap));
744
745         /*
746          * Early initialize dap->dp_ctrl_stat.
747          * In jtag mode only, if the following atomic reads fail and set the
748          * sticky error, it will trigger the clearing of the sticky. Without this
749          * initialization system and debug power would be disabled while clearing
750          * the sticky error bit.
751          */
752         dap->dp_ctrl_stat = CDBGPWRUPREQ | CSYSPWRUPREQ;
753
754         dap->do_reconnect = false;
755
756         dap_dp_read_atomic(dap, DP_CTRL_STAT, NULL);
757         if (dap->do_reconnect) {
758                 /* dap connect calls dap_dp_init() after transport dependent initialization */
759                 return dap->ops->connect(dap);
760         } else {
761                 return dap_dp_init(dap);
762         }
763 }
764
765 /**
766  * Initialize a DAP.  This sets up the power domains, prepares the DP
767  * for further use, and arranges to use AP #0 for all AP operations
768  * until dap_ap-select() changes that policy.
769  *
770  * @param ap The MEM-AP being initialized.
771  */
772 int mem_ap_init(struct adiv5_ap *ap)
773 {
774         /* check that we support packed transfers */
775         uint32_t csw, cfg;
776         int retval;
777         struct adiv5_dap *dap = ap->dap;
778
779         /* Set ap->cfg_reg before calling mem_ap_setup_transfer(). */
780         /* mem_ap_setup_transfer() needs to know if the MEM_AP supports LPAE. */
781         retval = dap_queue_ap_read(ap, MEM_AP_REG_CFG, &cfg);
782         if (retval != ERROR_OK)
783                 return retval;
784
785         retval = dap_run(dap);
786         if (retval != ERROR_OK)
787                 return retval;
788
789         ap->cfg_reg = cfg;
790         ap->tar_valid = false;
791         ap->csw_value = 0;      /* force csw and tar write */
792         retval = mem_ap_setup_transfer(ap, CSW_8BIT | CSW_ADDRINC_PACKED, 0);
793         if (retval != ERROR_OK)
794                 return retval;
795
796         retval = dap_queue_ap_read(ap, MEM_AP_REG_CSW, &csw);
797         if (retval != ERROR_OK)
798                 return retval;
799
800         retval = dap_run(dap);
801         if (retval != ERROR_OK)
802                 return retval;
803
804         if (csw & CSW_ADDRINC_PACKED)
805                 ap->packed_transfers = true;
806         else
807                 ap->packed_transfers = false;
808
809         /* Packed transfers on TI BE-32 processors do not work correctly in
810          * many cases. */
811         if (dap->ti_be_32_quirks)
812                 ap->packed_transfers = false;
813
814         LOG_DEBUG("MEM_AP Packed Transfers: %s",
815                         ap->packed_transfers ? "enabled" : "disabled");
816
817         /* The ARM ADI spec leaves implementation-defined whether unaligned
818          * memory accesses work, only work partially, or cause a sticky error.
819          * On TI BE-32 processors, reads seem to return garbage in some bytes
820          * and unaligned writes seem to cause a sticky error.
821          * TODO: it would be nice to have a way to detect whether unaligned
822          * operations are supported on other processors. */
823         ap->unaligned_access_bad = dap->ti_be_32_quirks;
824
825         LOG_DEBUG("MEM_AP CFG: large data %d, long address %d, big-endian %d",
826                         !!(cfg & MEM_AP_REG_CFG_LD), !!(cfg & MEM_AP_REG_CFG_LA), !!(cfg & MEM_AP_REG_CFG_BE));
827
828         return ERROR_OK;
829 }
830
831 /**
832  * Put the debug link into SWD mode, if the target supports it.
833  * The link's initial mode may be either JTAG (for example,
834  * with SWJ-DP after reset) or SWD.
835  *
836  * Note that targets using the JTAG-DP do not support SWD, and that
837  * some targets which could otherwise support it may have been
838  * configured to disable SWD signaling
839  *
840  * @param dap The DAP used
841  * @return ERROR_OK or else a fault code.
842  */
843 int dap_to_swd(struct adiv5_dap *dap)
844 {
845         LOG_DEBUG("Enter SWD mode");
846
847         return dap_send_sequence(dap, JTAG_TO_SWD);
848 }
849
850 /**
851  * Put the debug link into JTAG mode, if the target supports it.
852  * The link's initial mode may be either SWD or JTAG.
853  *
854  * Note that targets implemented with SW-DP do not support JTAG, and
855  * that some targets which could otherwise support it may have been
856  * configured to disable JTAG signaling
857  *
858  * @param dap The DAP used
859  * @return ERROR_OK or else a fault code.
860  */
861 int dap_to_jtag(struct adiv5_dap *dap)
862 {
863         LOG_DEBUG("Enter JTAG mode");
864
865         return dap_send_sequence(dap, SWD_TO_JTAG);
866 }
867
868 /* CID interpretation -- see ARM IHI 0029B section 3
869  * and ARM IHI 0031A table 13-3.
870  */
871 static const char *class_description[16] = {
872         "Reserved", "ROM table", "Reserved", "Reserved",
873         "Reserved", "Reserved", "Reserved", "Reserved",
874         "Reserved", "CoreSight component", "Reserved", "Peripheral Test Block",
875         "Reserved", "OptimoDE DESS",
876         "Generic IP component", "PrimeCell or System component"
877 };
878
879 static bool is_dap_cid_ok(uint32_t cid)
880 {
881         return (cid & 0xffff0fff) == 0xb105000d;
882 }
883
884 /*
885  * This function checks the ID for each access port to find the requested Access Port type
886  */
887 int dap_find_ap(struct adiv5_dap *dap, enum ap_type type_to_find, struct adiv5_ap **ap_out)
888 {
889         int ap_num;
890
891         /* Maximum AP number is 255 since the SELECT register is 8 bits */
892         for (ap_num = 0; ap_num <= DP_APSEL_MAX; ap_num++) {
893
894                 /* read the IDR register of the Access Port */
895                 uint32_t id_val = 0;
896
897                 int retval = dap_queue_ap_read(dap_ap(dap, ap_num), AP_REG_IDR, &id_val);
898                 if (retval != ERROR_OK)
899                         return retval;
900
901                 retval = dap_run(dap);
902
903                 /* IDR bits:
904                  * 31-28 : Revision
905                  * 27-24 : JEDEC bank (0x4 for ARM)
906                  * 23-17 : JEDEC code (0x3B for ARM)
907                  * 16-13 : Class (0b1000=Mem-AP)
908                  * 12-8  : Reserved
909                  *  7-4  : AP Variant (non-zero for JTAG-AP)
910                  *  3-0  : AP Type (0=JTAG-AP 1=AHB-AP 2=APB-AP 4=AXI-AP)
911                  */
912
913                 /* Reading register for a non-existent AP should not cause an error,
914                  * but just to be sure, try to continue searching if an error does happen.
915                  */
916                 if ((retval == ERROR_OK) &&                  /* Register read success */
917                         ((id_val & IDR_JEP106) == IDR_JEP106_ARM) && /* Jedec codes match */
918                         ((id_val & IDR_TYPE) == type_to_find)) {      /* type matches*/
919
920                         LOG_DEBUG("Found %s at AP index: %d (IDR=0x%08" PRIX32 ")",
921                                                 (type_to_find == AP_TYPE_AHB3_AP)  ? "AHB3-AP"  :
922                                                 (type_to_find == AP_TYPE_AHB5_AP)  ? "AHB5-AP"  :
923                                                 (type_to_find == AP_TYPE_APB_AP)  ? "APB-AP"  :
924                                                 (type_to_find == AP_TYPE_AXI_AP)  ? "AXI-AP"  :
925                                                 (type_to_find == AP_TYPE_JTAG_AP) ? "JTAG-AP" : "Unknown",
926                                                 ap_num, id_val);
927
928                         *ap_out = &dap->ap[ap_num];
929                         return ERROR_OK;
930                 }
931         }
932
933         LOG_DEBUG("No %s found",
934                                 (type_to_find == AP_TYPE_AHB3_AP)  ? "AHB3-AP"  :
935                                 (type_to_find == AP_TYPE_AHB5_AP)  ? "AHB5-AP"  :
936                                 (type_to_find == AP_TYPE_APB_AP)  ? "APB-AP"  :
937                                 (type_to_find == AP_TYPE_AXI_AP)  ? "AXI-AP"  :
938                                 (type_to_find == AP_TYPE_JTAG_AP) ? "JTAG-AP" : "Unknown");
939         return ERROR_FAIL;
940 }
941
942 int dap_get_debugbase(struct adiv5_ap *ap,
943                         target_addr_t *dbgbase, uint32_t *apid)
944 {
945         struct adiv5_dap *dap = ap->dap;
946         int retval;
947         uint32_t baseptr_upper, baseptr_lower;
948
949         baseptr_upper = 0;
950
951         if (is_64bit_ap(ap)) {
952                 /* Read higher order 32-bits of base address */
953                 retval = dap_queue_ap_read(ap, MEM_AP_REG_BASE64, &baseptr_upper);
954                 if (retval != ERROR_OK)
955                         return retval;
956         }
957
958         retval = dap_queue_ap_read(ap, MEM_AP_REG_BASE, &baseptr_lower);
959         if (retval != ERROR_OK)
960                 return retval;
961         retval = dap_queue_ap_read(ap, AP_REG_IDR, apid);
962         if (retval != ERROR_OK)
963                 return retval;
964         retval = dap_run(dap);
965         if (retval != ERROR_OK)
966                 return retval;
967
968         *dbgbase = (((target_addr_t)baseptr_upper) << 32) | baseptr_lower;
969
970         return ERROR_OK;
971 }
972
973 int dap_lookup_cs_component(struct adiv5_ap *ap,
974                         target_addr_t dbgbase, uint8_t type, target_addr_t *addr, int32_t *idx)
975 {
976         uint32_t romentry, entry_offset = 0, devtype;
977         target_addr_t component_base;
978         int retval;
979
980         dbgbase &= 0xFFFFFFFFFFFFF000ull;
981         *addr = 0;
982
983         do {
984                 retval = mem_ap_read_atomic_u32(ap, dbgbase |
985                                                 entry_offset, &romentry);
986                 if (retval != ERROR_OK)
987                         return retval;
988
989                 component_base = dbgbase + (target_addr_t)(romentry & 0xFFFFF000);
990
991                 if (romentry & 0x1) {
992                         uint32_t c_cid1;
993                         retval = mem_ap_read_atomic_u32(ap, component_base | 0xff4, &c_cid1);
994                         if (retval != ERROR_OK) {
995                                 LOG_ERROR("Can't read component with base address " TARGET_ADDR_FMT
996                                           ", the corresponding core might be turned off", component_base);
997                                 return retval;
998                         }
999                         if (((c_cid1 >> 4) & 0x0f) == 1) {
1000                                 retval = dap_lookup_cs_component(ap, component_base,
1001                                                         type, addr, idx);
1002                                 if (retval == ERROR_OK)
1003                                         break;
1004                                 if (retval != ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
1005                                         return retval;
1006                         }
1007
1008                         retval = mem_ap_read_atomic_u32(ap, component_base | 0xfcc, &devtype);
1009                         if (retval != ERROR_OK)
1010                                 return retval;
1011                         if ((devtype & 0xff) == type) {
1012                                 if (!*idx) {
1013                                         *addr = component_base;
1014                                         break;
1015                                 } else
1016                                         (*idx)--;
1017                         }
1018                 }
1019                 entry_offset += 4;
1020         } while ((romentry > 0) && (entry_offset < 0xf00));
1021
1022         if (!*addr)
1023                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1024
1025         return ERROR_OK;
1026 }
1027
1028 static int dap_read_part_id(struct adiv5_ap *ap, target_addr_t component_base, uint32_t *cid, uint64_t *pid)
1029 {
1030         assert((component_base & 0xFFF) == 0);
1031         assert(ap && cid && pid);
1032
1033         uint32_t cid0, cid1, cid2, cid3;
1034         uint32_t pid0, pid1, pid2, pid3, pid4;
1035         int retval;
1036
1037         /* IDs are in last 4K section */
1038         retval = mem_ap_read_u32(ap, component_base + 0xFE0, &pid0);
1039         if (retval != ERROR_OK)
1040                 return retval;
1041         retval = mem_ap_read_u32(ap, component_base + 0xFE4, &pid1);
1042         if (retval != ERROR_OK)
1043                 return retval;
1044         retval = mem_ap_read_u32(ap, component_base + 0xFE8, &pid2);
1045         if (retval != ERROR_OK)
1046                 return retval;
1047         retval = mem_ap_read_u32(ap, component_base + 0xFEC, &pid3);
1048         if (retval != ERROR_OK)
1049                 return retval;
1050         retval = mem_ap_read_u32(ap, component_base + 0xFD0, &pid4);
1051         if (retval != ERROR_OK)
1052                 return retval;
1053         retval = mem_ap_read_u32(ap, component_base + 0xFF0, &cid0);
1054         if (retval != ERROR_OK)
1055                 return retval;
1056         retval = mem_ap_read_u32(ap, component_base + 0xFF4, &cid1);
1057         if (retval != ERROR_OK)
1058                 return retval;
1059         retval = mem_ap_read_u32(ap, component_base + 0xFF8, &cid2);
1060         if (retval != ERROR_OK)
1061                 return retval;
1062         retval = mem_ap_read_u32(ap, component_base + 0xFFC, &cid3);
1063         if (retval != ERROR_OK)
1064                 return retval;
1065
1066         retval = dap_run(ap->dap);
1067         if (retval != ERROR_OK)
1068                 return retval;
1069
1070         *cid = (cid3 & 0xff) << 24
1071                         | (cid2 & 0xff) << 16
1072                         | (cid1 & 0xff) << 8
1073                         | (cid0 & 0xff);
1074         *pid = (uint64_t)(pid4 & 0xff) << 32
1075                         | (pid3 & 0xff) << 24
1076                         | (pid2 & 0xff) << 16
1077                         | (pid1 & 0xff) << 8
1078                         | (pid0 & 0xff);
1079
1080         return ERROR_OK;
1081 }
1082
1083 /* The designer identity code is encoded as:
1084  * bits 11:8 : JEP106 Bank (number of continuation codes), only valid when bit 7 is 1.
1085  * bit 7     : Set when bits 6:0 represent a JEP106 ID and cleared when bits 6:0 represent
1086  *             a legacy ASCII Identity Code.
1087  * bits 6:0  : JEP106 Identity Code (without parity) or legacy ASCII code according to bit 7.
1088  * JEP106 is a standard available from jedec.org
1089  */
1090
1091 /* Part number interpretations are from Cortex
1092  * core specs, the CoreSight components TRM
1093  * (ARM DDI 0314H), CoreSight System Design
1094  * Guide (ARM DGI 0012D) and ETM specs; also
1095  * from chip observation (e.g. TI SDTI).
1096  */
1097
1098 /* The legacy code only used the part number field to identify CoreSight peripherals.
1099  * This meant that the same part number from two different manufacturers looked the same.
1100  * It is desirable for all future additions to identify with both part number and JEP106.
1101  * "ANY_ID" is a wildcard (any JEP106) only to preserve legacy behavior for legacy entries.
1102  */
1103
1104 #define ANY_ID 0x1000
1105
1106 #define ARM_ID 0x4BB
1107
1108 static const struct {
1109         uint16_t designer_id;
1110         uint16_t part_num;
1111         const char *type;
1112         const char *full;
1113 } dap_partnums[] = {
1114         { ARM_ID, 0x000, "Cortex-M3 SCS",              "(System Control Space)", },
1115         { ARM_ID, 0x001, "Cortex-M3 ITM",              "(Instrumentation Trace Module)", },
1116         { ARM_ID, 0x002, "Cortex-M3 DWT",              "(Data Watchpoint and Trace)", },
1117         { ARM_ID, 0x003, "Cortex-M3 FPB",              "(Flash Patch and Breakpoint)", },
1118         { ARM_ID, 0x008, "Cortex-M0 SCS",              "(System Control Space)", },
1119         { ARM_ID, 0x00a, "Cortex-M0 DWT",              "(Data Watchpoint and Trace)", },
1120         { ARM_ID, 0x00b, "Cortex-M0 BPU",              "(Breakpoint Unit)", },
1121         { ARM_ID, 0x00c, "Cortex-M4 SCS",              "(System Control Space)", },
1122         { ARM_ID, 0x00d, "CoreSight ETM11",            "(Embedded Trace)", },
1123         { ARM_ID, 0x00e, "Cortex-M7 FPB",              "(Flash Patch and Breakpoint)", },
1124         { ARM_ID, 0x470, "Cortex-M1 ROM",              "(ROM Table)", },
1125         { ARM_ID, 0x471, "Cortex-M0 ROM",              "(ROM Table)", },
1126         { ARM_ID, 0x490, "Cortex-A15 GIC",             "(Generic Interrupt Controller)", },
1127         { ARM_ID, 0x4a1, "Cortex-A53 ROM",             "(v8 Memory Map ROM Table)", },
1128         { ARM_ID, 0x4a2, "Cortex-A57 ROM",             "(ROM Table)", },
1129         { ARM_ID, 0x4a3, "Cortex-A53 ROM",             "(v7 Memory Map ROM Table)", },
1130         { ARM_ID, 0x4a4, "Cortex-A72 ROM",             "(ROM Table)", },
1131         { ARM_ID, 0x4a9, "Cortex-A9 ROM",              "(ROM Table)", },
1132         { ARM_ID, 0x4aa, "Cortex-A35 ROM",             "(v8 Memory Map ROM Table)", },
1133         { ARM_ID, 0x4af, "Cortex-A15 ROM",             "(ROM Table)", },
1134         { ARM_ID, 0x4b5, "Cortex-R5 ROM",              "(ROM Table)", },
1135         { ARM_ID, 0x4c0, "Cortex-M0+ ROM",             "(ROM Table)", },
1136         { ARM_ID, 0x4c3, "Cortex-M3 ROM",              "(ROM Table)", },
1137         { ARM_ID, 0x4c4, "Cortex-M4 ROM",              "(ROM Table)", },
1138         { ARM_ID, 0x4c7, "Cortex-M7 PPB ROM",          "(Private Peripheral Bus ROM Table)", },
1139         { ARM_ID, 0x4c8, "Cortex-M7 ROM",              "(ROM Table)", },
1140         { ARM_ID, 0x4e0, "Cortex-A35 ROM",             "(v7 Memory Map ROM Table)", },
1141         { ARM_ID, 0x4e4, "Cortex-A76 ROM",             "(ROM Table)", },
1142         { ARM_ID, 0x906, "CoreSight CTI",              "(Cross Trigger)", },
1143         { ARM_ID, 0x907, "CoreSight ETB",              "(Trace Buffer)", },
1144         { ARM_ID, 0x908, "CoreSight CSTF",             "(Trace Funnel)", },
1145         { ARM_ID, 0x909, "CoreSight ATBR",             "(Advanced Trace Bus Replicator)", },
1146         { ARM_ID, 0x910, "CoreSight ETM9",             "(Embedded Trace)", },
1147         { ARM_ID, 0x912, "CoreSight TPIU",             "(Trace Port Interface Unit)", },
1148         { ARM_ID, 0x913, "CoreSight ITM",              "(Instrumentation Trace Macrocell)", },
1149         { ARM_ID, 0x914, "CoreSight SWO",              "(Single Wire Output)", },
1150         { ARM_ID, 0x917, "CoreSight HTM",              "(AHB Trace Macrocell)", },
1151         { ARM_ID, 0x920, "CoreSight ETM11",            "(Embedded Trace)", },
1152         { ARM_ID, 0x921, "Cortex-A8 ETM",              "(Embedded Trace)", },
1153         { ARM_ID, 0x922, "Cortex-A8 CTI",              "(Cross Trigger)", },
1154         { ARM_ID, 0x923, "Cortex-M3 TPIU",             "(Trace Port Interface Unit)", },
1155         { ARM_ID, 0x924, "Cortex-M3 ETM",              "(Embedded Trace)", },
1156         { ARM_ID, 0x925, "Cortex-M4 ETM",              "(Embedded Trace)", },
1157         { ARM_ID, 0x930, "Cortex-R4 ETM",              "(Embedded Trace)", },
1158         { ARM_ID, 0x931, "Cortex-R5 ETM",              "(Embedded Trace)", },
1159         { ARM_ID, 0x932, "CoreSight MTB-M0+",          "(Micro Trace Buffer)", },
1160         { ARM_ID, 0x941, "CoreSight TPIU-Lite",        "(Trace Port Interface Unit)", },
1161         { ARM_ID, 0x950, "Cortex-A9 PTM",              "(Program Trace Macrocell)", },
1162         { ARM_ID, 0x955, "Cortex-A5 ETM",              "(Embedded Trace)", },
1163         { ARM_ID, 0x95a, "Cortex-A72 ETM",             "(Embedded Trace)", },
1164         { ARM_ID, 0x95b, "Cortex-A17 PTM",             "(Program Trace Macrocell)", },
1165         { ARM_ID, 0x95d, "Cortex-A53 ETM",             "(Embedded Trace)", },
1166         { ARM_ID, 0x95e, "Cortex-A57 ETM",             "(Embedded Trace)", },
1167         { ARM_ID, 0x95f, "Cortex-A15 PTM",             "(Program Trace Macrocell)", },
1168         { ARM_ID, 0x961, "CoreSight TMC",              "(Trace Memory Controller)", },
1169         { ARM_ID, 0x962, "CoreSight STM",              "(System Trace Macrocell)", },
1170         { ARM_ID, 0x975, "Cortex-M7 ETM",              "(Embedded Trace)", },
1171         { ARM_ID, 0x9a0, "CoreSight PMU",              "(Performance Monitoring Unit)", },
1172         { ARM_ID, 0x9a1, "Cortex-M4 TPIU",             "(Trace Port Interface Unit)", },
1173         { ARM_ID, 0x9a4, "CoreSight GPR",              "(Granular Power Requester)", },
1174         { ARM_ID, 0x9a5, "Cortex-A5 PMU",              "(Performance Monitor Unit)", },
1175         { ARM_ID, 0x9a7, "Cortex-A7 PMU",              "(Performance Monitor Unit)", },
1176         { ARM_ID, 0x9a8, "Cortex-A53 CTI",             "(Cross Trigger)", },
1177         { ARM_ID, 0x9a9, "Cortex-M7 TPIU",             "(Trace Port Interface Unit)", },
1178         { ARM_ID, 0x9ae, "Cortex-A17 PMU",             "(Performance Monitor Unit)", },
1179         { ARM_ID, 0x9af, "Cortex-A15 PMU",             "(Performance Monitor Unit)", },
1180         { ARM_ID, 0x9b7, "Cortex-R7 PMU",              "(Performance Monitor Unit)", },
1181         { ARM_ID, 0x9d3, "Cortex-A53 PMU",             "(Performance Monitor Unit)", },
1182         { ARM_ID, 0x9d7, "Cortex-A57 PMU",             "(Performance Monitor Unit)", },
1183         { ARM_ID, 0x9d8, "Cortex-A72 PMU",             "(Performance Monitor Unit)", },
1184         { ARM_ID, 0x9da, "Cortex-A35 PMU/CTI/ETM",     "(Performance Monitor Unit/Cross Trigger/ETM)", },
1185         { ARM_ID, 0xc05, "Cortex-A5 Debug",            "(Debug Unit)", },
1186         { ARM_ID, 0xc07, "Cortex-A7 Debug",            "(Debug Unit)", },
1187         { ARM_ID, 0xc08, "Cortex-A8 Debug",            "(Debug Unit)", },
1188         { ARM_ID, 0xc09, "Cortex-A9 Debug",            "(Debug Unit)", },
1189         { ARM_ID, 0xc0e, "Cortex-A17 Debug",           "(Debug Unit)", },
1190         { ARM_ID, 0xc0f, "Cortex-A15 Debug",           "(Debug Unit)", },
1191         { ARM_ID, 0xc14, "Cortex-R4 Debug",            "(Debug Unit)", },
1192         { ARM_ID, 0xc15, "Cortex-R5 Debug",            "(Debug Unit)", },
1193         { ARM_ID, 0xc17, "Cortex-R7 Debug",            "(Debug Unit)", },
1194         { ARM_ID, 0xd03, "Cortex-A53 Debug",           "(Debug Unit)", },
1195         { ARM_ID, 0xd04, "Cortex-A35 Debug",           "(Debug Unit)", },
1196         { ARM_ID, 0xd07, "Cortex-A57 Debug",           "(Debug Unit)", },
1197         { ARM_ID, 0xd08, "Cortex-A72 Debug",           "(Debug Unit)", },
1198         { ARM_ID, 0xd0b, "Cortex-A76 Debug",           "(Debug Unit)", },
1199         { 0x097,  0x9af, "MSP432 ROM",                 "(ROM Table)" },
1200         { 0x09f,  0xcd0, "Atmel CPU with DSU",         "(CPU)" },
1201         { 0x0c1,  0x1db, "XMC4500 ROM",                "(ROM Table)" },
1202         { 0x0c1,  0x1df, "XMC4700/4800 ROM",           "(ROM Table)" },
1203         { 0x0c1,  0x1ed, "XMC1000 ROM",                "(ROM Table)" },
1204         { 0x0E5,  0x000, "SHARC+/Blackfin+",           "", },
1205         { 0x0F0,  0x440, "Qualcomm QDSS Component v1", "(Qualcomm Designed CoreSight Component v1)", },
1206         { 0x1bf,  0x100, "Brahma-B53 Debug",           "(Debug Unit)", },
1207         { 0x1bf,  0x9d3, "Brahma-B53 PMU",             "(Performance Monitor Unit)", },
1208         { 0x1bf,  0x4a1, "Brahma-B53 ROM",             "(ROM Table)", },
1209         { 0x1bf,  0x721, "Brahma-B53 ROM",             "(ROM Table)", },
1210         { 0x3eb,  0x181, "Tegra 186 ROM",              "(ROM Table)", },
1211         { 0x3eb,  0x202, "Denver ETM",                 "(Denver Embedded Trace)", },
1212         { 0x3eb,  0x211, "Tegra 210 ROM",              "(ROM Table)", },
1213         { 0x3eb,  0x302, "Denver Debug",               "(Debug Unit)", },
1214         { 0x3eb,  0x402, "Denver PMU",                 "(Performance Monitor Unit)", },
1215         /* legacy comment: 0x113: what? */
1216         { ANY_ID, 0x120, "TI SDTI",                    "(System Debug Trace Interface)", }, /* from OMAP3 memmap */
1217         { ANY_ID, 0x343, "TI DAPCTL",                  "", }, /* from OMAP3 memmap */
1218 };
1219
1220 static int dap_rom_display(struct command_invocation *cmd,
1221                                 struct adiv5_ap *ap, target_addr_t dbgbase, int depth)
1222 {
1223         int retval;
1224         uint64_t pid;
1225         uint32_t cid;
1226         char tabs[16] = "";
1227
1228         if (depth > 16) {
1229                 command_print(cmd, "\tTables too deep");
1230                 return ERROR_FAIL;
1231         }
1232
1233         if (depth)
1234                 snprintf(tabs, sizeof(tabs), "[L%02d] ", depth);
1235
1236         target_addr_t base_addr = dbgbase & 0xFFFFFFFFFFFFF000ull;
1237         command_print(cmd, "\t\tComponent base address " TARGET_ADDR_FMT, base_addr);
1238
1239         retval = dap_read_part_id(ap, base_addr, &cid, &pid);
1240         if (retval != ERROR_OK) {
1241                 command_print(cmd, "\t\tCan't read component, the corresponding core might be turned off");
1242                 return ERROR_OK; /* Don't abort recursion */
1243         }
1244
1245         if (!is_dap_cid_ok(cid)) {
1246                 command_print(cmd, "\t\tInvalid CID 0x%08" PRIx32, cid);
1247                 return ERROR_OK; /* Don't abort recursion */
1248         }
1249
1250         /* component may take multiple 4K pages */
1251         uint32_t size = (pid >> 36) & 0xf;
1252         if (size > 0)
1253                 command_print(cmd, "\t\tStart address " TARGET_ADDR_FMT, base_addr - 0x1000 * size);
1254
1255         command_print(cmd, "\t\tPeripheral ID 0x%010" PRIx64, pid);
1256
1257         uint8_t class = (cid >> 12) & 0xf;
1258         uint16_t part_num = pid & 0xfff;
1259         uint16_t designer_id = ((pid >> 32) & 0xf) << 8 | ((pid >> 12) & 0xff);
1260
1261         if (designer_id & 0x80) {
1262                 /* JEP106 code */
1263                 command_print(cmd, "\t\tDesigner is 0x%03" PRIx16 ", %s",
1264                                 designer_id, jep106_manufacturer(designer_id >> 8, designer_id & 0x7f));
1265         } else {
1266                 /* Legacy ASCII ID, clear invalid bits */
1267                 designer_id &= 0x7f;
1268                 command_print(cmd, "\t\tDesigner ASCII code 0x%02" PRIx16 ", %s",
1269                                 designer_id, designer_id == 0x41 ? "ARM" : "<unknown>");
1270         }
1271
1272         /* default values to be overwritten upon finding a match */
1273         const char *type = "Unrecognized";
1274         const char *full = "";
1275
1276         /* search dap_partnums[] array for a match */
1277         for (unsigned entry = 0; entry < ARRAY_SIZE(dap_partnums); entry++) {
1278
1279                 if ((dap_partnums[entry].designer_id != designer_id) && (dap_partnums[entry].designer_id != ANY_ID))
1280                         continue;
1281
1282                 if (dap_partnums[entry].part_num != part_num)
1283                         continue;
1284
1285                 type = dap_partnums[entry].type;
1286                 full = dap_partnums[entry].full;
1287                 break;
1288         }
1289
1290         command_print(cmd, "\t\tPart is 0x%" PRIx16", %s %s", part_num, type, full);
1291         command_print(cmd, "\t\tComponent class is 0x%" PRIx8 ", %s", class, class_description[class]);
1292
1293         if (class == 1) { /* ROM Table */
1294                 uint32_t memtype;
1295                 retval = mem_ap_read_atomic_u32(ap, base_addr | 0xFCC, &memtype);
1296                 if (retval != ERROR_OK)
1297                         return retval;
1298
1299                 if (memtype & 0x01)
1300                         command_print(cmd, "\t\tMEMTYPE system memory present on bus");
1301                 else
1302                         command_print(cmd, "\t\tMEMTYPE system memory not present: dedicated debug bus");
1303
1304                 /* Read ROM table entries from base address until we get 0x00000000 or reach the reserved area */
1305                 for (uint16_t entry_offset = 0; entry_offset < 0xF00; entry_offset += 4) {
1306                         uint32_t romentry;
1307                         retval = mem_ap_read_atomic_u32(ap, base_addr | entry_offset, &romentry);
1308                         if (retval != ERROR_OK)
1309                                 return retval;
1310                         command_print(cmd, "\t%sROMTABLE[0x%x] = 0x%" PRIx32 "",
1311                                         tabs, entry_offset, romentry);
1312                         if (romentry & 0x01) {
1313                                 /* Recurse */
1314                                 retval = dap_rom_display(cmd, ap, base_addr + (romentry & 0xFFFFF000), depth + 1);
1315                                 if (retval != ERROR_OK)
1316                                         return retval;
1317                         } else if (romentry != 0) {
1318                                 command_print(cmd, "\t\tComponent not present");
1319                         } else {
1320                                 command_print(cmd, "\t%s\tEnd of ROM table", tabs);
1321                                 break;
1322                         }
1323                 }
1324         } else if (class == 9) { /* CoreSight component */
1325                 const char *major = "Reserved", *subtype = "Reserved";
1326
1327                 uint32_t devtype;
1328                 retval = mem_ap_read_atomic_u32(ap, base_addr | 0xFCC, &devtype);
1329                 if (retval != ERROR_OK)
1330                         return retval;
1331                 unsigned minor = (devtype >> 4) & 0x0f;
1332                 switch (devtype & 0x0f) {
1333                 case 0:
1334                         major = "Miscellaneous";
1335                         switch (minor) {
1336                         case 0:
1337                                 subtype = "other";
1338                                 break;
1339                         case 4:
1340                                 subtype = "Validation component";
1341                                 break;
1342                         }
1343                         break;
1344                 case 1:
1345                         major = "Trace Sink";
1346                         switch (minor) {
1347                         case 0:
1348                                 subtype = "other";
1349                                 break;
1350                         case 1:
1351                                 subtype = "Port";
1352                                 break;
1353                         case 2:
1354                                 subtype = "Buffer";
1355                                 break;
1356                         case 3:
1357                                 subtype = "Router";
1358                                 break;
1359                         }
1360                         break;
1361                 case 2:
1362                         major = "Trace Link";
1363                         switch (minor) {
1364                         case 0:
1365                                 subtype = "other";
1366                                 break;
1367                         case 1:
1368                                 subtype = "Funnel, router";
1369                                 break;
1370                         case 2:
1371                                 subtype = "Filter";
1372                                 break;
1373                         case 3:
1374                                 subtype = "FIFO, buffer";
1375                                 break;
1376                         }
1377                         break;
1378                 case 3:
1379                         major = "Trace Source";
1380                         switch (minor) {
1381                         case 0:
1382                                 subtype = "other";
1383                                 break;
1384                         case 1:
1385                                 subtype = "Processor";
1386                                 break;
1387                         case 2:
1388                                 subtype = "DSP";
1389                                 break;
1390                         case 3:
1391                                 subtype = "Engine/Coprocessor";
1392                                 break;
1393                         case 4:
1394                                 subtype = "Bus";
1395                                 break;
1396                         case 6:
1397                                 subtype = "Software";
1398                                 break;
1399                         }
1400                         break;
1401                 case 4:
1402                         major = "Debug Control";
1403                         switch (minor) {
1404                         case 0:
1405                                 subtype = "other";
1406                                 break;
1407                         case 1:
1408                                 subtype = "Trigger Matrix";
1409                                 break;
1410                         case 2:
1411                                 subtype = "Debug Auth";
1412                                 break;
1413                         case 3:
1414                                 subtype = "Power Requestor";
1415                                 break;
1416                         }
1417                         break;
1418                 case 5:
1419                         major = "Debug Logic";
1420                         switch (minor) {
1421                         case 0:
1422                                 subtype = "other";
1423                                 break;
1424                         case 1:
1425                                 subtype = "Processor";
1426                                 break;
1427                         case 2:
1428                                 subtype = "DSP";
1429                                 break;
1430                         case 3:
1431                                 subtype = "Engine/Coprocessor";
1432                                 break;
1433                         case 4:
1434                                 subtype = "Bus";
1435                                 break;
1436                         case 5:
1437                                 subtype = "Memory";
1438                                 break;
1439                         }
1440                         break;
1441                 case 6:
1442                         major = "Performance Monitor";
1443                         switch (minor) {
1444                         case 0:
1445                                 subtype = "other";
1446                                 break;
1447                         case 1:
1448                                 subtype = "Processor";
1449                                 break;
1450                         case 2:
1451                                 subtype = "DSP";
1452                                 break;
1453                         case 3:
1454                                 subtype = "Engine/Coprocessor";
1455                                 break;
1456                         case 4:
1457                                 subtype = "Bus";
1458                                 break;
1459                         case 5:
1460                                 subtype = "Memory";
1461                                 break;
1462                         }
1463                         break;
1464                 }
1465                 command_print(cmd, "\t\tType is 0x%02" PRIx8 ", %s, %s",
1466                                 (uint8_t)(devtype & 0xff),
1467                                 major, subtype);
1468                 /* REVISIT also show 0xfc8 DevId */
1469         }
1470
1471         return ERROR_OK;
1472 }
1473
1474 int dap_info_command(struct command_invocation *cmd,
1475                 struct adiv5_ap *ap)
1476 {
1477         int retval;
1478         uint32_t apid;
1479         target_addr_t dbgbase;
1480         target_addr_t dbgaddr;
1481         uint8_t mem_ap;
1482
1483         /* Now we read ROM table ID registers, ref. ARM IHI 0029B sec  */
1484         retval = dap_get_debugbase(ap, &dbgbase, &apid);
1485         if (retval != ERROR_OK)
1486                 return retval;
1487
1488         command_print(cmd, "AP ID register 0x%8.8" PRIx32, apid);
1489         if (apid == 0) {
1490                 command_print(cmd, "No AP found at this ap 0x%x", ap->ap_num);
1491                 return ERROR_FAIL;
1492         }
1493
1494         switch (apid & (IDR_JEP106 | IDR_TYPE)) {
1495         case IDR_JEP106_ARM | AP_TYPE_JTAG_AP:
1496                 command_print(cmd, "\tType is JTAG-AP");
1497                 break;
1498         case IDR_JEP106_ARM | AP_TYPE_AHB3_AP:
1499                 command_print(cmd, "\tType is MEM-AP AHB3");
1500                 break;
1501         case IDR_JEP106_ARM | AP_TYPE_AHB5_AP:
1502                 command_print(cmd, "\tType is MEM-AP AHB5");
1503                 break;
1504         case IDR_JEP106_ARM | AP_TYPE_APB_AP:
1505                 command_print(cmd, "\tType is MEM-AP APB");
1506                 break;
1507         case IDR_JEP106_ARM | AP_TYPE_AXI_AP:
1508                 command_print(cmd, "\tType is MEM-AP AXI");
1509                 break;
1510         default:
1511                 command_print(cmd, "\tUnknown AP type");
1512                 break;
1513         }
1514
1515         /* NOTE: a MEM-AP may have a single CoreSight component that's
1516          * not a ROM table ... or have no such components at all.
1517          */
1518         mem_ap = (apid & IDR_CLASS) == AP_CLASS_MEM_AP;
1519         if (mem_ap) {
1520                 if (is_64bit_ap(ap))
1521                         dbgaddr = 0xFFFFFFFFFFFFFFFFull;
1522                 else
1523                         dbgaddr = 0xFFFFFFFFul;
1524
1525                 command_print(cmd, "MEM-AP BASE " TARGET_ADDR_FMT, dbgbase);
1526
1527                 if (dbgbase == dbgaddr || (dbgbase & 0x3) == 0x2) {
1528                         command_print(cmd, "\tNo ROM table present");
1529                 } else {
1530                         if (dbgbase & 0x01)
1531                                 command_print(cmd, "\tValid ROM table present");
1532                         else
1533                                 command_print(cmd, "\tROM table in legacy format");
1534
1535                         dap_rom_display(cmd, ap, dbgbase & 0xFFFFFFFFFFFFF000ull, 0);
1536                 }
1537         }
1538
1539         return ERROR_OK;
1540 }
1541
1542 enum adiv5_cfg_param {
1543         CFG_DAP,
1544         CFG_AP_NUM,
1545         CFG_BASEADDR,
1546         CFG_CTIBASE, /* DEPRECATED */
1547 };
1548
1549 static const struct jim_nvp nvp_config_opts[] = {
1550         { .name = "-dap",       .value = CFG_DAP },
1551         { .name = "-ap-num",    .value = CFG_AP_NUM },
1552         { .name = "-baseaddr",  .value = CFG_BASEADDR },
1553         { .name = "-ctibase",   .value = CFG_CTIBASE }, /* DEPRECATED */
1554         { .name = NULL, .value = -1 }
1555 };
1556
1557 static int adiv5_jim_spot_configure(struct jim_getopt_info *goi,
1558                 struct adiv5_dap **dap_p, int *ap_num_p, uint32_t *base_p)
1559 {
1560         if (!goi->argc)
1561                 return JIM_OK;
1562
1563         Jim_SetEmptyResult(goi->interp);
1564
1565         struct jim_nvp *n;
1566         int e = jim_nvp_name2value_obj(goi->interp, nvp_config_opts,
1567                                 goi->argv[0], &n);
1568         if (e != JIM_OK)
1569                 return JIM_CONTINUE;
1570
1571         /* base_p can be NULL, then '-baseaddr' option is treated as unknown */
1572         if (!base_p && (n->value == CFG_BASEADDR || n->value == CFG_CTIBASE))
1573                 return JIM_CONTINUE;
1574
1575         e = jim_getopt_obj(goi, NULL);
1576         if (e != JIM_OK)
1577                 return e;
1578
1579         switch (n->value) {
1580         case CFG_DAP:
1581                 if (goi->isconfigure) {
1582                         Jim_Obj *o_t;
1583                         struct adiv5_dap *dap;
1584                         e = jim_getopt_obj(goi, &o_t);
1585                         if (e != JIM_OK)
1586                                 return e;
1587                         dap = dap_instance_by_jim_obj(goi->interp, o_t);
1588                         if (!dap) {
1589                                 Jim_SetResultString(goi->interp, "DAP name invalid!", -1);
1590                                 return JIM_ERR;
1591                         }
1592                         if (*dap_p && *dap_p != dap) {
1593                                 Jim_SetResultString(goi->interp,
1594                                         "DAP assignment cannot be changed!", -1);
1595                                 return JIM_ERR;
1596                         }
1597                         *dap_p = dap;
1598                 } else {
1599                         if (goi->argc)
1600                                 goto err_no_param;
1601                         if (!*dap_p) {
1602                                 Jim_SetResultString(goi->interp, "DAP not configured", -1);
1603                                 return JIM_ERR;
1604                         }
1605                         Jim_SetResultString(goi->interp, adiv5_dap_name(*dap_p), -1);
1606                 }
1607                 break;
1608
1609         case CFG_AP_NUM:
1610                 if (goi->isconfigure) {
1611                         jim_wide ap_num;
1612                         e = jim_getopt_wide(goi, &ap_num);
1613                         if (e != JIM_OK)
1614                                 return e;
1615                         if (ap_num < 0 || ap_num > DP_APSEL_MAX) {
1616                                 Jim_SetResultString(goi->interp, "Invalid AP number!", -1);
1617                                 return JIM_ERR;
1618                         }
1619                         *ap_num_p = ap_num;
1620                 } else {
1621                         if (goi->argc)
1622                                 goto err_no_param;
1623                         if (*ap_num_p == DP_APSEL_INVALID) {
1624                                 Jim_SetResultString(goi->interp, "AP number not configured", -1);
1625                                 return JIM_ERR;
1626                         }
1627                         Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, *ap_num_p));
1628                 }
1629                 break;
1630
1631         case CFG_CTIBASE:
1632                 LOG_WARNING("DEPRECATED! use \'-baseaddr' not \'-ctibase\'");
1633                 /* fall through */
1634         case CFG_BASEADDR:
1635                 if (goi->isconfigure) {
1636                         jim_wide base;
1637                         e = jim_getopt_wide(goi, &base);
1638                         if (e != JIM_OK)
1639                                 return e;
1640                         *base_p = (uint32_t)base;
1641                 } else {
1642                         if (goi->argc)
1643                                 goto err_no_param;
1644                         Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, *base_p));
1645                 }
1646                 break;
1647         };
1648
1649         return JIM_OK;
1650
1651 err_no_param:
1652         Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "NO PARAMS");
1653         return JIM_ERR;
1654 }
1655
1656 int adiv5_jim_configure(struct target *target, struct jim_getopt_info *goi)
1657 {
1658         struct adiv5_private_config *pc;
1659         int e;
1660
1661         pc = (struct adiv5_private_config *)target->private_config;
1662         if (!pc) {
1663                 pc = calloc(1, sizeof(struct adiv5_private_config));
1664                 pc->ap_num = DP_APSEL_INVALID;
1665                 target->private_config = pc;
1666         }
1667
1668         target->has_dap = true;
1669
1670         e = adiv5_jim_spot_configure(goi, &pc->dap, &pc->ap_num, NULL);
1671         if (e != JIM_OK)
1672                 return e;
1673
1674         if (pc->dap && !target->dap_configured) {
1675                 if (target->tap_configured) {
1676                         pc->dap = NULL;
1677                         Jim_SetResultString(goi->interp,
1678                                 "-chain-position and -dap configparams are mutually exclusive!", -1);
1679                         return JIM_ERR;
1680                 }
1681                 target->tap = pc->dap->tap;
1682                 target->dap_configured = true;
1683         }
1684
1685         return JIM_OK;
1686 }
1687
1688 int adiv5_verify_config(struct adiv5_private_config *pc)
1689 {
1690         if (!pc)
1691                 return ERROR_FAIL;
1692
1693         if (!pc->dap)
1694                 return ERROR_FAIL;
1695
1696         return ERROR_OK;
1697 }
1698
1699 int adiv5_jim_mem_ap_spot_configure(struct adiv5_mem_ap_spot *cfg,
1700                 struct jim_getopt_info *goi)
1701 {
1702         return adiv5_jim_spot_configure(goi, &cfg->dap, &cfg->ap_num, &cfg->base);
1703 }
1704
1705 int adiv5_mem_ap_spot_init(struct adiv5_mem_ap_spot *p)
1706 {
1707         p->dap = NULL;
1708         p->ap_num = DP_APSEL_INVALID;
1709         p->base = 0;
1710         return ERROR_OK;
1711 }
1712
1713 COMMAND_HANDLER(handle_dap_info_command)
1714 {
1715         struct adiv5_dap *dap = adiv5_get_dap(CMD_DATA);
1716         uint32_t apsel;
1717
1718         switch (CMD_ARGC) {
1719         case 0:
1720                 apsel = dap->apsel;
1721                 break;
1722         case 1:
1723                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], apsel);
1724                 if (apsel > DP_APSEL_MAX) {
1725                         command_print(CMD, "Invalid AP number");
1726                         return ERROR_COMMAND_ARGUMENT_INVALID;
1727                 }
1728                 break;
1729         default:
1730                 return ERROR_COMMAND_SYNTAX_ERROR;
1731         }
1732
1733         return dap_info_command(CMD, &dap->ap[apsel]);
1734 }
1735
1736 COMMAND_HANDLER(dap_baseaddr_command)
1737 {
1738         struct adiv5_dap *dap = adiv5_get_dap(CMD_DATA);
1739         uint32_t apsel, baseaddr_lower, baseaddr_upper;
1740         struct adiv5_ap *ap;
1741         target_addr_t baseaddr;
1742         int retval;
1743
1744         baseaddr_upper = 0;
1745
1746         switch (CMD_ARGC) {
1747         case 0:
1748                 apsel = dap->apsel;
1749                 break;
1750         case 1:
1751                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], apsel);
1752                 /* AP address is in bits 31:24 of DP_SELECT */
1753                 if (apsel > DP_APSEL_MAX) {
1754                         command_print(CMD, "Invalid AP number");
1755                         return ERROR_COMMAND_ARGUMENT_INVALID;
1756                 }
1757                 break;
1758         default:
1759                 return ERROR_COMMAND_SYNTAX_ERROR;
1760         }
1761
1762         /* NOTE:  assumes we're talking to a MEM-AP, which
1763          * has a base address.  There are other kinds of AP,
1764          * though they're not common for now.  This should
1765          * use the ID register to verify it's a MEM-AP.
1766          */
1767
1768         ap = dap_ap(dap, apsel);
1769         retval = dap_queue_ap_read(ap, MEM_AP_REG_BASE, &baseaddr_lower);
1770
1771         if (is_64bit_ap(ap) && retval == ERROR_OK)
1772                 retval = dap_queue_ap_read(ap, MEM_AP_REG_BASE64, &baseaddr_upper);
1773         if (retval != ERROR_OK)
1774                 return retval;
1775         retval = dap_run(dap);
1776         if (retval != ERROR_OK)
1777                 return retval;
1778         if (is_64bit_ap(ap)) {
1779                 baseaddr = (((target_addr_t)baseaddr_upper) << 32) | baseaddr_lower;
1780                 command_print(CMD, "0x%016" PRIx64, baseaddr);
1781         } else
1782                 command_print(CMD, "0x%08" PRIx32, baseaddr_lower);
1783
1784         return retval;
1785 }
1786
1787 COMMAND_HANDLER(dap_memaccess_command)
1788 {
1789         struct adiv5_dap *dap = adiv5_get_dap(CMD_DATA);
1790         uint32_t memaccess_tck;
1791
1792         switch (CMD_ARGC) {
1793         case 0:
1794                 memaccess_tck = dap->ap[dap->apsel].memaccess_tck;
1795                 break;
1796         case 1:
1797                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], memaccess_tck);
1798                 break;
1799         default:
1800                 return ERROR_COMMAND_SYNTAX_ERROR;
1801         }
1802         dap->ap[dap->apsel].memaccess_tck = memaccess_tck;
1803
1804         command_print(CMD, "memory bus access delay set to %" PRIu32 " tck",
1805                         dap->ap[dap->apsel].memaccess_tck);
1806
1807         return ERROR_OK;
1808 }
1809
1810 COMMAND_HANDLER(dap_apsel_command)
1811 {
1812         struct adiv5_dap *dap = adiv5_get_dap(CMD_DATA);
1813         uint32_t apsel;
1814
1815         switch (CMD_ARGC) {
1816         case 0:
1817                 command_print(CMD, "%" PRIu32, dap->apsel);
1818                 return ERROR_OK;
1819         case 1:
1820                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], apsel);
1821                 /* AP address is in bits 31:24 of DP_SELECT */
1822                 if (apsel > DP_APSEL_MAX) {
1823                         command_print(CMD, "Invalid AP number");
1824                         return ERROR_COMMAND_ARGUMENT_INVALID;
1825                 }
1826                 break;
1827         default:
1828                 return ERROR_COMMAND_SYNTAX_ERROR;
1829         }
1830
1831         dap->apsel = apsel;
1832         return ERROR_OK;
1833 }
1834
1835 COMMAND_HANDLER(dap_apcsw_command)
1836 {
1837         struct adiv5_dap *dap = adiv5_get_dap(CMD_DATA);
1838         uint32_t apcsw = dap->ap[dap->apsel].csw_default;
1839         uint32_t csw_val, csw_mask;
1840
1841         switch (CMD_ARGC) {
1842         case 0:
1843                 command_print(CMD, "ap %" PRIu32 " selected, csw 0x%8.8" PRIx32,
1844                         dap->apsel, apcsw);
1845                 return ERROR_OK;
1846         case 1:
1847                 if (strcmp(CMD_ARGV[0], "default") == 0)
1848                         csw_val = CSW_AHB_DEFAULT;
1849                 else
1850                         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], csw_val);
1851
1852                 if (csw_val & (CSW_SIZE_MASK | CSW_ADDRINC_MASK)) {
1853                         LOG_ERROR("CSW value cannot include 'Size' and 'AddrInc' bit-fields");
1854                         return ERROR_COMMAND_ARGUMENT_INVALID;
1855                 }
1856                 apcsw = csw_val;
1857                 break;
1858         case 2:
1859                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], csw_val);
1860                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], csw_mask);
1861                 if (csw_mask & (CSW_SIZE_MASK | CSW_ADDRINC_MASK)) {
1862                         LOG_ERROR("CSW mask cannot include 'Size' and 'AddrInc' bit-fields");
1863                         return ERROR_COMMAND_ARGUMENT_INVALID;
1864                 }
1865                 apcsw = (apcsw & ~csw_mask) | (csw_val & csw_mask);
1866                 break;
1867         default:
1868                 return ERROR_COMMAND_SYNTAX_ERROR;
1869         }
1870         dap->ap[dap->apsel].csw_default = apcsw;
1871
1872         return 0;
1873 }
1874
1875
1876
1877 COMMAND_HANDLER(dap_apid_command)
1878 {
1879         struct adiv5_dap *dap = adiv5_get_dap(CMD_DATA);
1880         uint32_t apsel, apid;
1881         int retval;
1882
1883         switch (CMD_ARGC) {
1884         case 0:
1885                 apsel = dap->apsel;
1886                 break;
1887         case 1:
1888                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], apsel);
1889                 /* AP address is in bits 31:24 of DP_SELECT */
1890                 if (apsel > DP_APSEL_MAX) {
1891                         command_print(CMD, "Invalid AP number");
1892                         return ERROR_COMMAND_ARGUMENT_INVALID;
1893                 }
1894                 break;
1895         default:
1896                 return ERROR_COMMAND_SYNTAX_ERROR;
1897         }
1898
1899         retval = dap_queue_ap_read(dap_ap(dap, apsel), AP_REG_IDR, &apid);
1900         if (retval != ERROR_OK)
1901                 return retval;
1902         retval = dap_run(dap);
1903         if (retval != ERROR_OK)
1904                 return retval;
1905
1906         command_print(CMD, "0x%8.8" PRIx32, apid);
1907
1908         return retval;
1909 }
1910
1911 COMMAND_HANDLER(dap_apreg_command)
1912 {
1913         struct adiv5_dap *dap = adiv5_get_dap(CMD_DATA);
1914         uint32_t apsel, reg, value;
1915         struct adiv5_ap *ap;
1916         int retval;
1917
1918         if (CMD_ARGC < 2 || CMD_ARGC > 3)
1919                 return ERROR_COMMAND_SYNTAX_ERROR;
1920
1921         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], apsel);
1922         /* AP address is in bits 31:24 of DP_SELECT */
1923         if (apsel > DP_APSEL_MAX) {
1924                 command_print(CMD, "Invalid AP number");
1925                 return ERROR_COMMAND_ARGUMENT_INVALID;
1926         }
1927
1928         ap = dap_ap(dap, apsel);
1929
1930         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], reg);
1931         if (reg >= 256 || (reg & 3)) {
1932                 command_print(CMD, "Invalid reg value (should be less than 256 and 4 bytes aligned)");
1933                 return ERROR_COMMAND_ARGUMENT_INVALID;
1934         }
1935
1936         if (CMD_ARGC == 3) {
1937                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], value);
1938                 switch (reg) {
1939                 case MEM_AP_REG_CSW:
1940                         ap->csw_value = 0;  /* invalid, in case write fails */
1941                         retval = dap_queue_ap_write(ap, reg, value);
1942                         if (retval == ERROR_OK)
1943                                 ap->csw_value = value;
1944                         break;
1945                 case MEM_AP_REG_TAR:
1946                         retval = dap_queue_ap_write(ap, reg, value);
1947                         if (retval == ERROR_OK)
1948                                 ap->tar_value = (ap->tar_value & ~0xFFFFFFFFull) | value;
1949                         else {
1950                                 /* To track independent writes to TAR and TAR64, two tar_valid flags */
1951                                 /* should be used. To keep it simple, tar_valid is only invalidated on a */
1952                                 /* write fail. This approach causes a later re-write of the TAR and TAR64 */
1953                                 /* if tar_valid is false. */
1954                                 ap->tar_valid = false;
1955                         }
1956                         break;
1957                 case MEM_AP_REG_TAR64:
1958                         retval = dap_queue_ap_write(ap, reg, value);
1959                         if (retval == ERROR_OK)
1960                                 ap->tar_value = (ap->tar_value & 0xFFFFFFFFull) | (((target_addr_t)value) << 32);
1961                         else {
1962                                 /* See above comment for the MEM_AP_REG_TAR failed write case */
1963                                 ap->tar_valid = false;
1964                         }
1965                         break;
1966                 default:
1967                         retval = dap_queue_ap_write(ap, reg, value);
1968                         break;
1969                 }
1970         } else {
1971                 retval = dap_queue_ap_read(ap, reg, &value);
1972         }
1973         if (retval == ERROR_OK)
1974                 retval = dap_run(dap);
1975
1976         if (retval != ERROR_OK)
1977                 return retval;
1978
1979         if (CMD_ARGC == 2)
1980                 command_print(CMD, "0x%08" PRIx32, value);
1981
1982         return retval;
1983 }
1984
1985 COMMAND_HANDLER(dap_dpreg_command)
1986 {
1987         struct adiv5_dap *dap = adiv5_get_dap(CMD_DATA);
1988         uint32_t reg, value;
1989         int retval;
1990
1991         if (CMD_ARGC < 1 || CMD_ARGC > 2)
1992                 return ERROR_COMMAND_SYNTAX_ERROR;
1993
1994         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], reg);
1995         if (reg >= 256 || (reg & 3)) {
1996                 command_print(CMD, "Invalid reg value (should be less than 256 and 4 bytes aligned)");
1997                 return ERROR_COMMAND_ARGUMENT_INVALID;
1998         }
1999
2000         if (CMD_ARGC == 2) {
2001                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], value);
2002                 retval = dap_queue_dp_write(dap, reg, value);
2003         } else {
2004                 retval = dap_queue_dp_read(dap, reg, &value);
2005         }
2006         if (retval == ERROR_OK)
2007                 retval = dap_run(dap);
2008
2009         if (retval != ERROR_OK)
2010                 return retval;
2011
2012         if (CMD_ARGC == 1)
2013                 command_print(CMD, "0x%08" PRIx32, value);
2014
2015         return retval;
2016 }
2017
2018 COMMAND_HANDLER(dap_ti_be_32_quirks_command)
2019 {
2020         struct adiv5_dap *dap = adiv5_get_dap(CMD_DATA);
2021         return CALL_COMMAND_HANDLER(handle_command_parse_bool, &dap->ti_be_32_quirks,
2022                 "TI BE-32 quirks mode");
2023 }
2024
2025 const struct command_registration dap_instance_commands[] = {
2026         {
2027                 .name = "info",
2028                 .handler = handle_dap_info_command,
2029                 .mode = COMMAND_EXEC,
2030                 .help = "display ROM table for MEM-AP "
2031                         "(default currently selected AP)",
2032                 .usage = "[ap_num]",
2033         },
2034         {
2035                 .name = "apsel",
2036                 .handler = dap_apsel_command,
2037                 .mode = COMMAND_ANY,
2038                 .help = "Set the currently selected AP (default 0) "
2039                         "and display the result",
2040                 .usage = "[ap_num]",
2041         },
2042         {
2043                 .name = "apcsw",
2044                 .handler = dap_apcsw_command,
2045                 .mode = COMMAND_ANY,
2046                 .help = "Set CSW default bits",
2047                 .usage = "[value [mask]]",
2048         },
2049
2050         {
2051                 .name = "apid",
2052                 .handler = dap_apid_command,
2053                 .mode = COMMAND_EXEC,
2054                 .help = "return ID register from AP "
2055                         "(default currently selected AP)",
2056                 .usage = "[ap_num]",
2057         },
2058         {
2059                 .name = "apreg",
2060                 .handler = dap_apreg_command,
2061                 .mode = COMMAND_EXEC,
2062                 .help = "read/write a register from AP "
2063                         "(reg is byte address of a word register, like 0 4 8...)",
2064                 .usage = "ap_num reg [value]",
2065         },
2066         {
2067                 .name = "dpreg",
2068                 .handler = dap_dpreg_command,
2069                 .mode = COMMAND_EXEC,
2070                 .help = "read/write a register from DP "
2071                         "(reg is byte address (bank << 4 | reg) of a word register, like 0 4 8...)",
2072                 .usage = "reg [value]",
2073         },
2074         {
2075                 .name = "baseaddr",
2076                 .handler = dap_baseaddr_command,
2077                 .mode = COMMAND_EXEC,
2078                 .help = "return debug base address from MEM-AP "
2079                         "(default currently selected AP)",
2080                 .usage = "[ap_num]",
2081         },
2082         {
2083                 .name = "memaccess",
2084                 .handler = dap_memaccess_command,
2085                 .mode = COMMAND_EXEC,
2086                 .help = "set/get number of extra tck for MEM-AP memory "
2087                         "bus access [0-255]",
2088                 .usage = "[cycles]",
2089         },
2090         {
2091                 .name = "ti_be_32_quirks",
2092                 .handler = dap_ti_be_32_quirks_command,
2093                 .mode = COMMAND_CONFIG,
2094                 .help = "set/get quirks mode for TI TMS450/TMS570 processors",
2095                 .usage = "[enable]",
2096         },
2097         COMMAND_REGISTRATION_DONE
2098 };