b17fd410f353453b01519672382bf0040cec3776
[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  *   This program is free software; you can redistribute it and/or modify  *
14  *   it under the terms of the GNU General Public License as published by  *
15  *   the Free Software Foundation; either version 2 of the License, or     *
16  *   (at your option) any later version.                                   *
17  *                                                                         *
18  *   This program is distributed in the hope that it will be useful,       *
19  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
20  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
21  *   GNU General Public License for more details.                          *
22  *                                                                         *
23  *   You should have received a copy of the GNU General Public License     *
24  *   along with this program; if not, write to the                         *
25  *   Free Software Foundation, Inc.,                                       *
26  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
27  ***************************************************************************/
28
29 /**
30  * @file
31  * This file implements support for the ARM Debug Interface version 5 (ADIv5)
32  * debugging architecture.  Compared with previous versions, this includes
33  * a low pin-count Serial Wire Debug (SWD) alternative to JTAG for message
34  * transport, and focusses on memory mapped resources as defined by the
35  * CoreSight architecture.
36  *
37  * A key concept in ADIv5 is the Debug Access Port, or DAP.  A DAP has two
38  * basic components:  a Debug Port (DP) transporting messages to and from a
39  * debugger, and an Access Port (AP) accessing resources.  Three types of DP
40  * are defined.  One uses only JTAG for communication, and is called JTAG-DP.
41  * One uses only SWD for communication, and is called SW-DP.  The third can
42  * use either SWD or JTAG, and is called SWJ-DP.  The most common type of AP
43  * is used to access memory mapped resources and is called a MEM-AP.  Also a
44  * JTAG-AP is also defined, bridging to JTAG resources; those are uncommon.
45  *
46  * This programming interface allows DAP pipelined operations through a
47  * transaction queue.  This primarily affects AP operations (such as using
48  * a MEM-AP to access memory or registers).  If the current transaction has
49  * not finished by the time the next one must begin, and the ORUNDETECT bit
50  * is set in the DP_CTRL_STAT register, the SSTICKYORUN status is set and
51  * further AP operations will fail.  There are two basic methods to avoid
52  * such overrun errors.  One involves polling for status instead of using
53  * transaction piplining.  The other involves adding delays to ensure the
54  * AP has enough time to complete one operation before starting the next
55  * one.  (For JTAG these delays are controlled by memaccess_tck.)
56  */
57
58 /*
59  * Relevant specifications from ARM include:
60  *
61  * ARM(tm) Debug Interface v5 Architecture Specification    ARM IHI 0031A
62  * CoreSight(tm) v1.0 Architecture Specification            ARM IHI 0029B
63  *
64  * CoreSight(tm) DAP-Lite TRM, ARM DDI 0316D
65  * Cortex-M3(tm) TRM, ARM DDI 0337G
66  */
67
68 #ifdef HAVE_CONFIG_H
69 #include "config.h"
70 #endif
71
72 #include "jtag/interface.h"
73 #include "arm.h"
74 #include "arm_adi_v5.h"
75 #include <helper/time_support.h>
76
77 /* ARM ADI Specification requires at least 10 bits used for TAR autoincrement  */
78
79 /*
80         uint32_t tar_block_size(uint32_t address)
81         Return the largest block starting at address that does not cross a tar block size alignment boundary
82 */
83 static uint32_t max_tar_block_size(uint32_t tar_autoincr_block, uint32_t address)
84 {
85         return (tar_autoincr_block - ((tar_autoincr_block - 1) & address)) >> 2;
86 }
87
88 /***************************************************************************
89  *                                                                         *
90  * DP and MEM-AP  register access  through APACC and DPACC                 *
91  *                                                                         *
92 ***************************************************************************/
93
94 /**
95  * Select one of the APs connected to the specified DAP.  The
96  * selection is implicitly used with future AP transactions.
97  * This is a NOP if the specified AP is already selected.
98  *
99  * @param dap The DAP
100  * @param apsel Number of the AP to (implicitly) use with further
101  *      transactions.  This normally identifies a MEM-AP.
102  */
103 void dap_ap_select(struct adiv5_dap *dap, uint8_t ap)
104 {
105         uint32_t new_ap = (ap << 24) & 0xFF000000;
106
107         if (new_ap != dap->ap_current) {
108                 dap->ap_current = new_ap;
109                 /* Switching AP invalidates cached values.
110                  * Values MUST BE UPDATED BEFORE AP ACCESS.
111                  */
112                 dap->ap_bank_value = -1;
113                 dap->ap_csw_value = -1;
114                 dap->ap_tar_value = -1;
115         }
116 }
117
118 /**
119  * Queue transactions setting up transfer parameters for the
120  * currently selected MEM-AP.
121  *
122  * Subsequent transfers using registers like AP_REG_DRW or AP_REG_BD2
123  * initiate data reads or writes using memory or peripheral addresses.
124  * If the CSW is configured for it, the TAR may be automatically
125  * incremented after each transfer.
126  *
127  * @todo Rename to reflect it being specifically a MEM-AP function.
128  *
129  * @param dap The DAP connected to the MEM-AP.
130  * @param csw MEM-AP Control/Status Word (CSW) register to assign.  If this
131  *      matches the cached value, the register is not changed.
132  * @param tar MEM-AP Transfer Address Register (TAR) to assign.  If this
133  *      matches the cached address, the register is not changed.
134  *
135  * @return ERROR_OK if the transaction was properly queued, else a fault code.
136  */
137 int dap_setup_accessport(struct adiv5_dap *dap, uint32_t csw, uint32_t tar)
138 {
139         int retval;
140
141         csw = csw | CSW_DBGSWENABLE | CSW_MASTER_DEBUG | CSW_HPROT;
142         if (csw != dap->ap_csw_value) {
143                 /* LOG_DEBUG("DAP: Set CSW %x",csw); */
144                 retval = dap_queue_ap_write(dap, AP_REG_CSW, csw);
145                 if (retval != ERROR_OK)
146                         return retval;
147                 dap->ap_csw_value = csw;
148         }
149         if (tar != dap->ap_tar_value) {
150                 /* LOG_DEBUG("DAP: Set TAR %x",tar); */
151                 retval = dap_queue_ap_write(dap, AP_REG_TAR, tar);
152                 if (retval != ERROR_OK)
153                         return retval;
154                 dap->ap_tar_value = tar;
155         }
156         /* Disable TAR cache when autoincrementing */
157         if (csw & CSW_ADDRINC_MASK)
158                 dap->ap_tar_value = -1;
159         return ERROR_OK;
160 }
161
162 /**
163  * Asynchronous (queued) read of a word from memory or a system register.
164  *
165  * @param dap The DAP connected to the MEM-AP performing the read.
166  * @param address Address of the 32-bit word to read; it must be
167  *      readable by the currently selected MEM-AP.
168  * @param value points to where the word will be stored when the
169  *      transaction queue is flushed (assuming no errors).
170  *
171  * @return ERROR_OK for success.  Otherwise a fault code.
172  */
173 int mem_ap_read_u32(struct adiv5_dap *dap, uint32_t address,
174                 uint32_t *value)
175 {
176         int retval;
177
178         /* Use banked addressing (REG_BDx) to avoid some link traffic
179          * (updating TAR) when reading several consecutive addresses.
180          */
181         retval = dap_setup_accessport(dap, CSW_32BIT | CSW_ADDRINC_OFF,
182                         address & 0xFFFFFFF0);
183         if (retval != ERROR_OK)
184                 return retval;
185
186         return dap_queue_ap_read(dap, AP_REG_BD0 | (address & 0xC), value);
187 }
188
189 /**
190  * Synchronous read of a word from memory or a system register.
191  * As a side effect, this flushes any queued transactions.
192  *
193  * @param dap The DAP connected to the MEM-AP performing the read.
194  * @param address Address of the 32-bit word to read; it must be
195  *      readable by the currently selected MEM-AP.
196  * @param value points to where the result will be stored.
197  *
198  * @return ERROR_OK for success; *value holds the result.
199  * Otherwise a fault code.
200  */
201 int mem_ap_read_atomic_u32(struct adiv5_dap *dap, uint32_t address,
202                 uint32_t *value)
203 {
204         int retval;
205
206         retval = mem_ap_read_u32(dap, address, value);
207         if (retval != ERROR_OK)
208                 return retval;
209
210         return dap_run(dap);
211 }
212
213 /**
214  * Asynchronous (queued) write of a word to memory or a system register.
215  *
216  * @param dap The DAP connected to the MEM-AP.
217  * @param address Address to be written; it must be writable by
218  *      the currently selected MEM-AP.
219  * @param value Word that will be written to the address when transaction
220  *      queue is flushed (assuming no errors).
221  *
222  * @return ERROR_OK for success.  Otherwise a fault code.
223  */
224 int mem_ap_write_u32(struct adiv5_dap *dap, uint32_t address,
225                 uint32_t value)
226 {
227         int retval;
228
229         /* Use banked addressing (REG_BDx) to avoid some link traffic
230          * (updating TAR) when writing several consecutive addresses.
231          */
232         retval = dap_setup_accessport(dap, CSW_32BIT | CSW_ADDRINC_OFF,
233                         address & 0xFFFFFFF0);
234         if (retval != ERROR_OK)
235                 return retval;
236
237         return dap_queue_ap_write(dap, AP_REG_BD0 | (address & 0xC),
238                         value);
239 }
240
241 /**
242  * Synchronous write of a word to memory or a system register.
243  * As a side effect, this flushes any queued transactions.
244  *
245  * @param dap The DAP connected to the MEM-AP.
246  * @param address Address to be written; it must be writable by
247  *      the currently selected MEM-AP.
248  * @param value Word that will be written.
249  *
250  * @return ERROR_OK for success; the data was written.  Otherwise a fault code.
251  */
252 int mem_ap_write_atomic_u32(struct adiv5_dap *dap, uint32_t address,
253                 uint32_t value)
254 {
255         int retval = mem_ap_write_u32(dap, address, value);
256
257         if (retval != ERROR_OK)
258                 return retval;
259
260         return dap_run(dap);
261 }
262
263 /*****************************************************************************
264 *                                                                            *
265 * mem_ap_write_buf(struct adiv5_dap *dap, uint8_t *buffer, int count, uint32_t address, bool addr_incr) *
266 *                                                                            *
267 * Write a buffer in target order (little endian)                             *
268 *                                                                            *
269 *****************************************************************************/
270 int mem_ap_write_buf_u32(struct adiv5_dap *dap, const uint8_t *buffer, int count, uint32_t address, bool addr_incr)
271 {
272         int wcount, blocksize, writecount, errorcount = 0, retval = ERROR_OK;
273         uint32_t adr = address;
274         const uint8_t *pBuffer = buffer;
275         uint32_t incr_flag = CSW_ADDRINC_OFF;
276
277         count >>= 2;
278         wcount = count;
279
280         /* if we have an unaligned access - reorder data */
281         if (adr & 0x3u) {
282                 for (writecount = 0; writecount < count; writecount++) {
283                         int i;
284                         uint32_t outvalue;
285                         memcpy(&outvalue, pBuffer, sizeof(uint32_t));
286
287                         for (i = 0; i < 4; i++) {
288                                 *((uint8_t *)pBuffer + (adr & 0x3)) = outvalue;
289                                 outvalue >>= 8;
290                                 adr++;
291                         }
292                         pBuffer += sizeof(uint32_t);
293                 }
294         }
295
296         while (wcount > 0) {
297                 /* Adjust to write blocks within boundaries aligned to the TAR autoincremnent size*/
298                 blocksize = max_tar_block_size(dap->tar_autoincr_block, address);
299                 if (wcount < blocksize)
300                         blocksize = wcount;
301
302                 /* handle unaligned data at 4k boundary */
303                 if (blocksize == 0)
304                         blocksize = 1;
305
306                 if (addr_incr)
307                         incr_flag = CSW_ADDRINC_SINGLE;
308
309                 retval = dap_setup_accessport(dap, CSW_32BIT | incr_flag, address);
310                 if (retval != ERROR_OK)
311                         return retval;
312
313                 for (writecount = 0; writecount < blocksize; writecount++) {
314                         uint32_t tmp;
315                         tmp = buf_get_u32(buffer + 4 * writecount, 0, 32);
316                         retval = dap_queue_ap_write(dap, AP_REG_DRW, tmp);
317                         if (retval != ERROR_OK)
318                                 break;
319                 }
320
321                 retval = dap_run(dap);
322                 if (retval == ERROR_OK) {
323                         wcount = wcount - blocksize;
324                         if (addr_incr)
325                                 address = address + 4 * blocksize;
326                         buffer = buffer + 4 * blocksize;
327                 } else
328                         errorcount++;
329
330                 if (errorcount > 1) {
331                         LOG_WARNING("Block write error address 0x%" PRIx32 ", wcount 0x%x", address, wcount);
332                         return retval;
333                 }
334         }
335
336         return retval;
337 }
338
339 static int mem_ap_write_buf_packed_u16(struct adiv5_dap *dap,
340                 const uint8_t *buffer, int count, uint32_t address)
341 {
342         int retval = ERROR_OK;
343         int wcount, blocksize, writecount, i;
344
345         wcount = count >> 1;
346
347         while (wcount > 0) {
348                 int nbytes;
349
350                 /* Adjust to write blocks within boundaries aligned to the TAR autoincremnent size*/
351                 blocksize = max_tar_block_size(dap->tar_autoincr_block, address);
352
353                 if (wcount < blocksize)
354                         blocksize = wcount;
355
356                 /* handle unaligned data at 4k boundary */
357                 if (blocksize == 0)
358                         blocksize = 1;
359
360                 retval = dap_setup_accessport(dap, CSW_16BIT | CSW_ADDRINC_PACKED, address);
361                 if (retval != ERROR_OK)
362                         return retval;
363                 writecount = blocksize;
364
365                 do {
366                         nbytes = MIN((writecount << 1), 4);
367
368                         if (nbytes < 4) {
369                                 retval = mem_ap_write_buf_u16(dap, buffer,
370                                                 nbytes, address);
371                                 if (retval != ERROR_OK) {
372                                         LOG_WARNING("Block write error address "
373                                                 "0x%" PRIx32 ", count 0x%x",
374                                                 address, count);
375                                         return retval;
376                                 }
377
378                                 address += nbytes >> 1;
379                         } else {
380                                 uint32_t outvalue;
381                                 memcpy(&outvalue, buffer, sizeof(uint32_t));
382
383                                 for (i = 0; i < nbytes; i++) {
384                                         *((uint8_t *)buffer + (address & 0x3)) = outvalue;
385                                         outvalue >>= 8;
386                                         address++;
387                                 }
388
389                                 memcpy(&outvalue, buffer, sizeof(uint32_t));
390                                 retval = dap_queue_ap_write(dap,
391                                                 AP_REG_DRW, outvalue);
392                                 if (retval != ERROR_OK)
393                                         break;
394
395                                 retval = dap_run(dap);
396                                 if (retval != ERROR_OK) {
397                                         LOG_WARNING("Block write error address "
398                                                 "0x%" PRIx32 ", count 0x%x",
399                                                 address, count);
400                                         return retval;
401                                 }
402                         }
403
404                         buffer += nbytes >> 1;
405                         writecount -= nbytes >> 1;
406
407                 } while (writecount);
408                 wcount -= blocksize;
409         }
410
411         return retval;
412 }
413
414 int mem_ap_write_buf_u16(struct adiv5_dap *dap, const uint8_t *buffer, int count, uint32_t address)
415 {
416         int retval = ERROR_OK;
417
418         if (count >= 4)
419                 return mem_ap_write_buf_packed_u16(dap, buffer, count, address);
420
421         while (count > 0) {
422                 retval = dap_setup_accessport(dap, CSW_16BIT | CSW_ADDRINC_SINGLE, address);
423                 if (retval != ERROR_OK)
424                         return retval;
425                 uint16_t svalue;
426                 memcpy(&svalue, buffer, sizeof(uint16_t));
427                 uint32_t outvalue = (uint32_t)svalue << 8 * (address & 0x3);
428                 retval = dap_queue_ap_write(dap, AP_REG_DRW, outvalue);
429                 if (retval != ERROR_OK)
430                         break;
431
432                 retval = dap_run(dap);
433                 if (retval != ERROR_OK)
434                         break;
435
436                 count -= 2;
437                 address += 2;
438                 buffer += 2;
439         }
440
441         return retval;
442 }
443
444 static int mem_ap_write_buf_packed_u8(struct adiv5_dap *dap,
445                 const uint8_t *buffer, int count, uint32_t address)
446 {
447         int retval = ERROR_OK;
448         int wcount, blocksize, writecount, i;
449
450         wcount = count;
451
452         while (wcount > 0) {
453                 int nbytes;
454
455                 /* Adjust to write blocks within boundaries aligned to the TAR autoincremnent size*/
456                 blocksize = max_tar_block_size(dap->tar_autoincr_block, address);
457
458                 if (wcount < blocksize)
459                         blocksize = wcount;
460
461                 retval = dap_setup_accessport(dap, CSW_8BIT | CSW_ADDRINC_PACKED, address);
462                 if (retval != ERROR_OK)
463                         return retval;
464                 writecount = blocksize;
465
466                 do {
467                         nbytes = MIN(writecount, 4);
468
469                         if (nbytes < 4) {
470                                 retval = mem_ap_write_buf_u8(dap, buffer, nbytes, address);
471                                 if (retval != ERROR_OK) {
472                                         LOG_WARNING("Block write error address "
473                                                 "0x%" PRIx32 ", count 0x%x",
474                                                 address, count);
475                                         return retval;
476                                 }
477
478                                 address += nbytes;
479                         } else {
480                                 uint32_t outvalue;
481                                 memcpy(&outvalue, buffer, sizeof(uint32_t));
482
483                                 for (i = 0; i < nbytes; i++) {
484                                         *((uint8_t *)buffer + (address & 0x3)) = outvalue;
485                                         outvalue >>= 8;
486                                         address++;
487                                 }
488
489                                 memcpy(&outvalue, buffer, sizeof(uint32_t));
490                                 retval = dap_queue_ap_write(dap,
491                                                 AP_REG_DRW, outvalue);
492                                 if (retval != ERROR_OK)
493                                         break;
494
495                                 retval = dap_run(dap);
496                                 if (retval != ERROR_OK) {
497                                         LOG_WARNING("Block write error address "
498                                                 "0x%" PRIx32 ", count 0x%x",
499                                                 address, count);
500                                         return retval;
501                                 }
502                         }
503
504                         buffer += nbytes;
505                         writecount -= nbytes;
506
507                 } while (writecount);
508                 wcount -= blocksize;
509         }
510
511         return retval;
512 }
513
514 int mem_ap_write_buf_u8(struct adiv5_dap *dap, const uint8_t *buffer, int count, uint32_t address)
515 {
516         int retval = ERROR_OK;
517
518         if (count >= 4)
519                 return mem_ap_write_buf_packed_u8(dap, buffer, count, address);
520
521         while (count > 0) {
522                 retval = dap_setup_accessport(dap, CSW_8BIT | CSW_ADDRINC_SINGLE, address);
523                 if (retval != ERROR_OK)
524                         return retval;
525                 uint32_t outvalue = (uint32_t)*buffer << 8 * (address & 0x3);
526                 retval = dap_queue_ap_write(dap, AP_REG_DRW, outvalue);
527                 if (retval != ERROR_OK)
528                         break;
529
530                 retval = dap_run(dap);
531                 if (retval != ERROR_OK)
532                         break;
533
534                 count--;
535                 address++;
536                 buffer++;
537         }
538
539         return retval;
540 }
541
542 /* FIXME don't import ... this is a temporary workaround for the
543  * mem_ap_read_buf_u32() mess, until it's no longer JTAG-specific.
544  */
545 extern int adi_jtag_dp_scan(struct adiv5_dap *dap,
546                 uint8_t instr, uint8_t reg_addr, uint8_t RnW,
547                 uint8_t *outvalue, uint8_t *invalue, uint8_t *ack);
548
549 /**
550  * Synchronously read a block of 32-bit words into a buffer
551  * @param dap The DAP connected to the MEM-AP.
552  * @param buffer where the words will be stored (in host byte order).
553  * @param count How many words to read.
554  * @param address Memory address from which to read words; all the
555  * @param addr_incr if true, increment the source address for each u32
556  *      words must be readable by the currently selected MEM-AP.
557  */
558 int mem_ap_read_buf_u32(struct adiv5_dap *dap, uint8_t *buffer,
559                 int count, uint32_t address, bool addr_incr)
560 {
561         int wcount, blocksize, readcount, errorcount = 0, retval = ERROR_OK;
562         uint32_t adr = address;
563         uint8_t *pBuffer = buffer;
564         uint32_t incr_flag = CSW_ADDRINC_OFF;
565
566         count >>= 2;
567         wcount = count;
568
569         while (wcount > 0) {
570                 /* Adjust to read blocks within boundaries aligned to the
571                  * TAR autoincrement size (at least 2^10).  Autoincrement
572                  * mode avoids an extra per-word roundtrip to update TAR.
573                  */
574                 blocksize = max_tar_block_size(dap->tar_autoincr_block,
575                                 address);
576                 if (wcount < blocksize)
577                         blocksize = wcount;
578
579                 /* handle unaligned data at 4k boundary */
580                 if (blocksize == 0)
581                         blocksize = 1;
582
583                 if (addr_incr)
584                         incr_flag = CSW_ADDRINC_SINGLE;
585
586                 retval = dap_setup_accessport(dap, CSW_32BIT | incr_flag,
587                                 address);
588                 if (retval != ERROR_OK)
589                         return retval;
590
591                 /* FIXME remove these three calls to adi_jtag_dp_scan(),
592                  * so this routine becomes transport-neutral.  Be careful
593                  * not to cause performance problems with JTAG; would it
594                  * suffice to loop over dap_queue_ap_read(), or would that
595                  * be slower when JTAG is the chosen transport?
596                  */
597
598                 /* Scan out first read */
599                 retval = adi_jtag_dp_scan(dap, JTAG_DP_APACC, AP_REG_DRW,
600                                 DPAP_READ, 0, NULL, NULL);
601                 if (retval != ERROR_OK)
602                         return retval;
603                 for (readcount = 0; readcount < blocksize - 1; readcount++) {
604                         /* Scan out next read; scan in posted value for the
605                          * previous one.  Assumes read is acked "OK/FAULT",
606                          * and CTRL_STAT says that meant "OK".
607                          */
608                         retval = adi_jtag_dp_scan(dap, JTAG_DP_APACC, AP_REG_DRW,
609                                         DPAP_READ, 0, buffer + 4 * readcount,
610                                         &dap->ack);
611                         if (retval != ERROR_OK)
612                                 return retval;
613                 }
614
615                 /* Scan in last posted value; RDBUFF has no other effect,
616                  * assuming ack is OK/FAULT and CTRL_STAT says "OK".
617                  */
618                 retval = adi_jtag_dp_scan(dap, JTAG_DP_DPACC, DP_RDBUFF,
619                                 DPAP_READ, 0, buffer + 4 * readcount,
620                                 &dap->ack);
621                 if (retval != ERROR_OK)
622                         return retval;
623
624                 retval = dap_run(dap);
625                 if (retval != ERROR_OK) {
626                         errorcount++;
627                         if (errorcount <= 1) {
628                                 /* try again */
629                                 continue;
630                         }
631                         LOG_WARNING("Block read error address 0x%" PRIx32, address);
632                         return retval;
633                 }
634                 wcount = wcount - blocksize;
635                 if (addr_incr)
636                         address += 4 * blocksize;
637                 buffer += 4 * blocksize;
638         }
639
640         /* if we have an unaligned access - reorder data */
641         if (adr & 0x3u) {
642                 for (readcount = 0; readcount < count; readcount++) {
643                         int i;
644                         uint32_t data;
645                         memcpy(&data, pBuffer, sizeof(uint32_t));
646
647                         for (i = 0; i < 4; i++) {
648                                 *((uint8_t *)pBuffer) =
649                                                 (data >> 8 * (adr & 0x3));
650                                 pBuffer++;
651                                 adr++;
652                         }
653                 }
654         }
655
656         return retval;
657 }
658
659 static int mem_ap_read_buf_packed_u16(struct adiv5_dap *dap,
660                 uint8_t *buffer, int count, uint32_t address)
661 {
662         uint32_t invalue;
663         int retval = ERROR_OK;
664         int wcount, blocksize, readcount, i;
665
666         wcount = count >> 1;
667
668         while (wcount > 0) {
669                 int nbytes;
670
671                 /* Adjust to read blocks within boundaries aligned to the TAR autoincremnent size*/
672                 blocksize = max_tar_block_size(dap->tar_autoincr_block, address);
673                 if (wcount < blocksize)
674                         blocksize = wcount;
675
676                 retval = dap_setup_accessport(dap, CSW_16BIT | CSW_ADDRINC_PACKED, address);
677                 if (retval != ERROR_OK)
678                         return retval;
679
680                 /* handle unaligned data at 4k boundary */
681                 if (blocksize == 0)
682                         blocksize = 1;
683                 readcount = blocksize;
684
685                 do {
686                         retval = dap_queue_ap_read(dap, AP_REG_DRW, &invalue);
687                         if (retval != ERROR_OK)
688                                 return retval;
689                         retval = dap_run(dap);
690                         if (retval != ERROR_OK) {
691                                 LOG_WARNING("Block read error address 0x%" PRIx32 ", count 0x%x", address, count);
692                                 return retval;
693                         }
694
695                         nbytes = MIN((readcount << 1), 4);
696
697                         for (i = 0; i < nbytes; i++) {
698                                 *((uint8_t *)buffer) = (invalue >> 8 * (address & 0x3));
699                                 buffer++;
700                                 address++;
701                         }
702
703                         readcount -= (nbytes >> 1);
704                 } while (readcount);
705                 wcount -= blocksize;
706         }
707
708         return retval;
709 }
710
711 /**
712  * Synchronously read a block of 16-bit halfwords into a buffer
713  * @param dap The DAP connected to the MEM-AP.
714  * @param buffer where the halfwords will be stored (in host byte order).
715  * @param count How many halfwords to read.
716  * @param address Memory address from which to read words; all the
717  *      words must be readable by the currently selected MEM-AP.
718  */
719 int mem_ap_read_buf_u16(struct adiv5_dap *dap, uint8_t *buffer,
720                 int count, uint32_t address)
721 {
722         uint32_t invalue, i;
723         int retval = ERROR_OK;
724
725         if (count >= 4)
726                 return mem_ap_read_buf_packed_u16(dap, buffer, count, address);
727
728         while (count > 0) {
729                 retval = dap_setup_accessport(dap, CSW_16BIT | CSW_ADDRINC_SINGLE, address);
730                 if (retval != ERROR_OK)
731                         return retval;
732                 retval = dap_queue_ap_read(dap, AP_REG_DRW, &invalue);
733                 if (retval != ERROR_OK)
734                         break;
735
736                 retval = dap_run(dap);
737                 if (retval != ERROR_OK)
738                         break;
739
740                 if (address & 0x1) {
741                         for (i = 0; i < 2; i++) {
742                                 *((uint8_t *)buffer) = (invalue >> 8 * (address & 0x3));
743                                 buffer++;
744                                 address++;
745                         }
746                 } else {
747                         uint16_t svalue = (invalue >> 8 * (address & 0x3));
748                         memcpy(buffer, &svalue, sizeof(uint16_t));
749                         address += 2;
750                         buffer += 2;
751                 }
752                 count -= 2;
753         }
754
755         return retval;
756 }
757
758 /* FIX!!! is this a potential performance bottleneck w.r.t. requiring too many
759  * roundtrips when jtag_execute_queue() has a large overhead(e.g. for USB)s?
760  *
761  * The solution is to arrange for a large out/in scan in this loop and
762  * and convert data afterwards.
763  */
764 static int mem_ap_read_buf_packed_u8(struct adiv5_dap *dap,
765                 uint8_t *buffer, int count, uint32_t address)
766 {
767         uint32_t invalue;
768         int retval = ERROR_OK;
769         int wcount, blocksize, readcount, i;
770
771         wcount = count;
772
773         while (wcount > 0) {
774                 int nbytes;
775
776                 /* Adjust to read blocks within boundaries aligned to the TAR autoincremnent size*/
777                 blocksize = max_tar_block_size(dap->tar_autoincr_block, address);
778
779                 if (wcount < blocksize)
780                         blocksize = wcount;
781
782                 retval = dap_setup_accessport(dap, CSW_8BIT | CSW_ADDRINC_PACKED, address);
783                 if (retval != ERROR_OK)
784                         return retval;
785                 readcount = blocksize;
786
787                 do {
788                         retval = dap_queue_ap_read(dap, AP_REG_DRW, &invalue);
789                         if (retval != ERROR_OK)
790                                 return retval;
791                         retval = dap_run(dap);
792                         if (retval != ERROR_OK) {
793                                 LOG_WARNING("Block read error address 0x%" PRIx32 ", count 0x%x", address, count);
794                                 return retval;
795                         }
796
797                         nbytes = MIN(readcount, 4);
798
799                         for (i = 0; i < nbytes; i++) {
800                                 *((uint8_t *)buffer) = (invalue >> 8 * (address & 0x3));
801                                 buffer++;
802                                 address++;
803                         }
804
805                         readcount -= nbytes;
806                 } while (readcount);
807                 wcount -= blocksize;
808         }
809
810         return retval;
811 }
812
813 /**
814  * Synchronously read a block of bytes into a buffer
815  * @param dap The DAP connected to the MEM-AP.
816  * @param buffer where the bytes will be stored.
817  * @param count How many bytes to read.
818  * @param address Memory address from which to read data; all the
819  *      data must be readable by the currently selected MEM-AP.
820  */
821 int mem_ap_read_buf_u8(struct adiv5_dap *dap, uint8_t *buffer,
822                 int count, uint32_t address)
823 {
824         uint32_t invalue;
825         int retval = ERROR_OK;
826
827         if (count >= 4)
828                 return mem_ap_read_buf_packed_u8(dap, buffer, count, address);
829
830         while (count > 0) {
831                 retval = dap_setup_accessport(dap, CSW_8BIT | CSW_ADDRINC_SINGLE, address);
832                 if (retval != ERROR_OK)
833                         return retval;
834                 retval = dap_queue_ap_read(dap, AP_REG_DRW, &invalue);
835                 if (retval != ERROR_OK)
836                         return retval;
837                 retval = dap_run(dap);
838                 if (retval != ERROR_OK)
839                         break;
840
841                 *((uint8_t *)buffer) = (invalue >> 8 * (address & 0x3));
842                 count--;
843                 address++;
844                 buffer++;
845         }
846
847         return retval;
848 }
849
850 /*--------------------------------------------------------------------*/
851 /*          Wrapping function with selection of AP                    */
852 /*--------------------------------------------------------------------*/
853 int mem_ap_sel_read_u32(struct adiv5_dap *swjdp, uint8_t ap,
854                 uint32_t address, uint32_t *value)
855 {
856         dap_ap_select(swjdp, ap);
857         return mem_ap_read_u32(swjdp, address, value);
858 }
859
860 int mem_ap_sel_write_u32(struct adiv5_dap *swjdp, uint8_t ap,
861                 uint32_t address, uint32_t value)
862 {
863         dap_ap_select(swjdp, ap);
864         return mem_ap_write_u32(swjdp, address, value);
865 }
866
867 int mem_ap_sel_read_atomic_u32(struct adiv5_dap *swjdp, uint8_t ap,
868                 uint32_t address, uint32_t *value)
869 {
870         dap_ap_select(swjdp, ap);
871         return mem_ap_read_atomic_u32(swjdp, address, value);
872 }
873
874 int mem_ap_sel_write_atomic_u32(struct adiv5_dap *swjdp, uint8_t ap,
875                 uint32_t address, uint32_t value)
876 {
877         dap_ap_select(swjdp, ap);
878         return mem_ap_write_atomic_u32(swjdp, address, value);
879 }
880
881 int mem_ap_sel_read_buf_u8(struct adiv5_dap *swjdp, uint8_t ap,
882                 uint8_t *buffer, int count, uint32_t address)
883 {
884         dap_ap_select(swjdp, ap);
885         return mem_ap_read_buf_u8(swjdp, buffer, count, address);
886 }
887
888 int mem_ap_sel_read_buf_u16(struct adiv5_dap *swjdp, uint8_t ap,
889                 uint8_t *buffer, int count, uint32_t address)
890 {
891         dap_ap_select(swjdp, ap);
892         return mem_ap_read_buf_u16(swjdp, buffer, count, address);
893 }
894
895 int mem_ap_sel_read_buf_u32_noincr(struct adiv5_dap *swjdp, uint8_t ap,
896                 uint8_t *buffer, int count, uint32_t address)
897 {
898         dap_ap_select(swjdp, ap);
899         return mem_ap_read_buf_u32(swjdp, buffer, count, address, false);
900 }
901
902 int mem_ap_sel_read_buf_u32(struct adiv5_dap *swjdp, uint8_t ap,
903                 uint8_t *buffer, int count, uint32_t address)
904 {
905         dap_ap_select(swjdp, ap);
906         return mem_ap_read_buf_u32(swjdp, buffer, count, address, true);
907 }
908
909 int mem_ap_sel_write_buf_u8(struct adiv5_dap *swjdp, uint8_t ap,
910                 const uint8_t *buffer, int count, uint32_t address)
911 {
912         dap_ap_select(swjdp, ap);
913         return mem_ap_write_buf_u8(swjdp, buffer, count, address);
914 }
915
916 int mem_ap_sel_write_buf_u16(struct adiv5_dap *swjdp, uint8_t ap,
917                 const uint8_t *buffer, int count, uint32_t address)
918 {
919         dap_ap_select(swjdp, ap);
920         return mem_ap_write_buf_u16(swjdp, buffer, count, address);
921 }
922
923 int mem_ap_sel_write_buf_u32(struct adiv5_dap *swjdp, uint8_t ap,
924                 const uint8_t *buffer, int count, uint32_t address)
925 {
926         dap_ap_select(swjdp, ap);
927         return mem_ap_write_buf_u32(swjdp, buffer, count, address, true);
928 }
929
930 int mem_ap_sel_write_buf_u32_noincr(struct adiv5_dap *swjdp, uint8_t ap,
931                 const uint8_t *buffer, int count, uint32_t address)
932 {
933         dap_ap_select(swjdp, ap);
934         return mem_ap_write_buf_u32(swjdp, buffer, count, address, false);
935 }
936
937 #define MDM_REG_STAT            0x00
938 #define MDM_REG_CTRL            0x04
939 #define MDM_REG_ID              0xfc
940
941 #define MDM_STAT_FMEACK         (1<<0)
942 #define MDM_STAT_FREADY         (1<<1)
943 #define MDM_STAT_SYSSEC         (1<<2)
944 #define MDM_STAT_SYSRES         (1<<3)
945 #define MDM_STAT_FMEEN          (1<<5)
946 #define MDM_STAT_BACKDOOREN     (1<<6)
947 #define MDM_STAT_LPEN           (1<<7)
948 #define MDM_STAT_VLPEN          (1<<8)
949 #define MDM_STAT_LLSMODEXIT     (1<<9)
950 #define MDM_STAT_VLLSXMODEXIT   (1<<10)
951 #define MDM_STAT_CORE_HALTED    (1<<16)
952 #define MDM_STAT_CORE_SLEEPDEEP (1<<17)
953 #define MDM_STAT_CORESLEEPING   (1<<18)
954
955 #define MEM_CTRL_FMEIP          (1<<0)
956 #define MEM_CTRL_DBG_DIS        (1<<1)
957 #define MEM_CTRL_DBG_REQ        (1<<2)
958 #define MEM_CTRL_SYS_RES_REQ    (1<<3)
959 #define MEM_CTRL_CORE_HOLD_RES  (1<<4)
960 #define MEM_CTRL_VLLSX_DBG_REQ  (1<<5)
961 #define MEM_CTRL_VLLSX_DBG_ACK  (1<<6)
962 #define MEM_CTRL_VLLSX_STAT_ACK (1<<7)
963
964 /**
965  *
966  */
967 int dap_syssec_kinetis_mdmap(struct adiv5_dap *dap)
968 {
969         uint32_t val;
970         int retval;
971         enum reset_types jtag_reset_config = jtag_get_reset_config();
972
973         dap_ap_select(dap, 1);
974
975         /* first check mdm-ap id register */
976         retval = dap_queue_ap_read(dap, MDM_REG_ID, &val);
977         if (retval != ERROR_OK)
978                 return retval;
979         dap_run(dap);
980
981         if (val != 0x001C0000) {
982                 LOG_DEBUG("id doesn't match %08X != 0x001C0000", val);
983                 dap_ap_select(dap, 0);
984                 return ERROR_FAIL;
985         }
986
987         /* read and parse status register
988          * it's important that the device is out of
989          * reset here
990          */
991         retval = dap_queue_ap_read(dap, MDM_REG_STAT, &val);
992         if (retval != ERROR_OK)
993                 return retval;
994         dap_run(dap);
995
996         LOG_DEBUG("MDM_REG_STAT %08X", val);
997
998         if ((val & (MDM_STAT_SYSSEC|MDM_STAT_FREADY)) != (MDM_STAT_FREADY)) {
999                 LOG_DEBUG("MDMAP: system is secured, masserase needed");
1000
1001                 if (!(val & MDM_STAT_FMEEN))
1002                         LOG_DEBUG("MDMAP: masserase is disabled");
1003                 else {
1004                         /* we need to assert reset */
1005                         if (jtag_reset_config & RESET_HAS_SRST) {
1006                                 /* default to asserting srst */
1007                                 adapter_assert_reset();
1008                         } else {
1009                                 LOG_DEBUG("SRST not configured");
1010                                 dap_ap_select(dap, 0);
1011                                 return ERROR_FAIL;
1012                         }
1013
1014                         while (1) {
1015                                 retval = dap_queue_ap_write(dap, MDM_REG_CTRL, MEM_CTRL_FMEIP);
1016                                 if (retval != ERROR_OK)
1017                                         return retval;
1018                                 dap_run(dap);
1019                                 /* read status register and wait for ready */
1020                                 retval = dap_queue_ap_read(dap, MDM_REG_STAT, &val);
1021                                 if (retval != ERROR_OK)
1022                                         return retval;
1023                                 dap_run(dap);
1024                                 LOG_DEBUG("MDM_REG_STAT %08X", val);
1025
1026                                 if ((val & 1))
1027                                         break;
1028                         }
1029
1030                         while (1) {
1031                                 retval = dap_queue_ap_write(dap, MDM_REG_CTRL, 0);
1032                                 if (retval != ERROR_OK)
1033                                         return retval;
1034                                 dap_run(dap);
1035                                 /* read status register */
1036                                 retval = dap_queue_ap_read(dap, MDM_REG_STAT, &val);
1037                                 if (retval != ERROR_OK)
1038                                         return retval;
1039                                 dap_run(dap);
1040                                 LOG_DEBUG("MDM_REG_STAT %08X", val);
1041                                 /* read control register and wait for ready */
1042                                 retval = dap_queue_ap_read(dap, MDM_REG_CTRL, &val);
1043                                 if (retval != ERROR_OK)
1044                                         return retval;
1045                                 dap_run(dap);
1046                                 LOG_DEBUG("MDM_REG_CTRL %08X", val);
1047
1048                                 if (val == 0x00)
1049                                         break;
1050                         }
1051                 }
1052         }
1053
1054         dap_ap_select(dap, 0);
1055
1056         return ERROR_OK;
1057 }
1058
1059 /** */
1060 struct dap_syssec_filter {
1061         /** */
1062         uint32_t idcode;
1063         /** */
1064         int (*dap_init)(struct adiv5_dap *dap);
1065 };
1066
1067 /** */
1068 static struct dap_syssec_filter dap_syssec_filter_data[] = {
1069         { 0x4BA00477, dap_syssec_kinetis_mdmap }
1070 };
1071
1072 /**
1073  *
1074  */
1075 int dap_syssec(struct adiv5_dap *dap)
1076 {
1077         unsigned int i;
1078         struct jtag_tap *tap;
1079
1080         for (i = 0; i < sizeof(dap_syssec_filter_data); i++) {
1081                 tap = dap->jtag_info->tap;
1082
1083                 while (tap != NULL) {
1084                         if (tap->hasidcode && (dap_syssec_filter_data[i].idcode == tap->idcode)) {
1085                                 LOG_DEBUG("DAP: mdmap_init for idcode: %08x", tap->idcode);
1086                                 dap_syssec_filter_data[i].dap_init(dap);
1087                         }
1088                         tap = tap->next_tap;
1089                 }
1090         }
1091
1092         return ERROR_OK;
1093 }
1094
1095 /*--------------------------------------------------------------------------*/
1096
1097
1098 /* FIXME don't import ... just initialize as
1099  * part of DAP transport setup
1100 */
1101 extern const struct dap_ops jtag_dp_ops;
1102
1103 /*--------------------------------------------------------------------------*/
1104
1105 /**
1106  * Initialize a DAP.  This sets up the power domains, prepares the DP
1107  * for further use, and arranges to use AP #0 for all AP operations
1108  * until dap_ap-select() changes that policy.
1109  *
1110  * @param dap The DAP being initialized.
1111  *
1112  * @todo Rename this.  We also need an initialization scheme which account
1113  * for SWD transports not just JTAG; that will need to address differences
1114  * in layering.  (JTAG is useful without any debug target; but not SWD.)
1115  * And this may not even use an AHB-AP ... e.g. DAP-Lite uses an APB-AP.
1116  */
1117 int ahbap_debugport_init(struct adiv5_dap *dap)
1118 {
1119         uint32_t ctrlstat;
1120         int cnt = 0;
1121         int retval;
1122
1123         LOG_DEBUG(" ");
1124
1125         /* JTAG-DP or SWJ-DP, in JTAG mode
1126          * ... for SWD mode this is patched as part
1127          * of link switchover
1128          */
1129         if (!dap->ops)
1130                 dap->ops = &jtag_dp_ops;
1131
1132         /* Default MEM-AP setup.
1133          *
1134          * REVISIT AP #0 may be an inappropriate default for this.
1135          * Should we probe, or take a hint from the caller?
1136          * Presumably we can ignore the possibility of multiple APs.
1137          */
1138         dap->ap_current = !0;
1139         dap_ap_select(dap, 0);
1140
1141         /* DP initialization */
1142
1143         retval = dap_queue_dp_read(dap, DP_CTRL_STAT, NULL);
1144         if (retval != ERROR_OK)
1145                 return retval;
1146
1147         retval = dap_queue_dp_write(dap, DP_CTRL_STAT, SSTICKYERR);
1148         if (retval != ERROR_OK)
1149                 return retval;
1150
1151         retval = dap_queue_dp_read(dap, DP_CTRL_STAT, NULL);
1152         if (retval != ERROR_OK)
1153                 return retval;
1154
1155         dap->dp_ctrl_stat = CDBGPWRUPREQ | CSYSPWRUPREQ;
1156         retval = dap_queue_dp_write(dap, DP_CTRL_STAT, dap->dp_ctrl_stat);
1157         if (retval != ERROR_OK)
1158                 return retval;
1159
1160         retval = dap_queue_dp_read(dap, DP_CTRL_STAT, &ctrlstat);
1161         if (retval != ERROR_OK)
1162                 return retval;
1163         retval = dap_run(dap);
1164         if (retval != ERROR_OK)
1165                 return retval;
1166
1167         /* Check that we have debug power domains activated */
1168         while (!(ctrlstat & CDBGPWRUPACK) && (cnt++ < 10)) {
1169                 LOG_DEBUG("DAP: wait CDBGPWRUPACK");
1170                 retval = dap_queue_dp_read(dap, DP_CTRL_STAT, &ctrlstat);
1171                 if (retval != ERROR_OK)
1172                         return retval;
1173                 retval = dap_run(dap);
1174                 if (retval != ERROR_OK)
1175                         return retval;
1176                 alive_sleep(10);
1177         }
1178
1179         while (!(ctrlstat & CSYSPWRUPACK) && (cnt++ < 10)) {
1180                 LOG_DEBUG("DAP: wait CSYSPWRUPACK");
1181                 retval = dap_queue_dp_read(dap, DP_CTRL_STAT, &ctrlstat);
1182                 if (retval != ERROR_OK)
1183                         return retval;
1184                 retval = dap_run(dap);
1185                 if (retval != ERROR_OK)
1186                         return retval;
1187                 alive_sleep(10);
1188         }
1189
1190         retval = dap_queue_dp_read(dap, DP_CTRL_STAT, NULL);
1191         if (retval != ERROR_OK)
1192                 return retval;
1193         /* With debug power on we can activate OVERRUN checking */
1194         dap->dp_ctrl_stat = CDBGPWRUPREQ | CSYSPWRUPREQ | CORUNDETECT;
1195         retval = dap_queue_dp_write(dap, DP_CTRL_STAT, dap->dp_ctrl_stat);
1196         if (retval != ERROR_OK)
1197                 return retval;
1198         retval = dap_queue_dp_read(dap, DP_CTRL_STAT, NULL);
1199         if (retval != ERROR_OK)
1200                 return retval;
1201
1202         dap_syssec(dap);
1203
1204         return ERROR_OK;
1205 }
1206
1207 /* CID interpretation -- see ARM IHI 0029B section 3
1208  * and ARM IHI 0031A table 13-3.
1209  */
1210 static const char *class_description[16] = {
1211         "Reserved", "ROM table", "Reserved", "Reserved",
1212         "Reserved", "Reserved", "Reserved", "Reserved",
1213         "Reserved", "CoreSight component", "Reserved", "Peripheral Test Block",
1214         "Reserved", "OptimoDE DESS",
1215         "Generic IP component", "PrimeCell or System component"
1216 };
1217
1218 static bool is_dap_cid_ok(uint32_t cid3, uint32_t cid2, uint32_t cid1, uint32_t cid0)
1219 {
1220         return cid3 == 0xb1 && cid2 == 0x05
1221                         && ((cid1 & 0x0f) == 0) && cid0 == 0x0d;
1222 }
1223
1224 int dap_get_debugbase(struct adiv5_dap *dap, int ap,
1225                         uint32_t *out_dbgbase, uint32_t *out_apid)
1226 {
1227         uint32_t ap_old;
1228         int retval;
1229         uint32_t dbgbase, apid;
1230
1231         /* AP address is in bits 31:24 of DP_SELECT */
1232         if (ap >= 256)
1233                 return ERROR_COMMAND_SYNTAX_ERROR;
1234
1235         ap_old = dap->ap_current;
1236         dap_ap_select(dap, ap);
1237
1238         retval = dap_queue_ap_read(dap, AP_REG_BASE, &dbgbase);
1239         if (retval != ERROR_OK)
1240                 return retval;
1241         retval = dap_queue_ap_read(dap, AP_REG_IDR, &apid);
1242         if (retval != ERROR_OK)
1243                 return retval;
1244         retval = dap_run(dap);
1245         if (retval != ERROR_OK)
1246                 return retval;
1247
1248         /* Excavate the device ID code */
1249         struct jtag_tap *tap = dap->jtag_info->tap;
1250         while (tap != NULL) {
1251                 if (tap->hasidcode)
1252                         break;
1253                 tap = tap->next_tap;
1254         }
1255         if (tap == NULL || !tap->hasidcode)
1256                 return ERROR_OK;
1257
1258         dap_ap_select(dap, ap_old);
1259
1260         /* The asignment happens only here to prevent modification of these
1261          * values before they are certain. */
1262         *out_dbgbase = dbgbase;
1263         *out_apid = apid;
1264
1265         return ERROR_OK;
1266 }
1267
1268 int dap_lookup_cs_component(struct adiv5_dap *dap, int ap,
1269                         uint32_t dbgbase, uint8_t type, uint32_t *addr)
1270 {
1271         uint32_t ap_old;
1272         uint32_t romentry, entry_offset = 0, component_base, devtype;
1273         int retval = ERROR_FAIL;
1274
1275         if (ap >= 256)
1276                 return ERROR_COMMAND_SYNTAX_ERROR;
1277
1278         ap_old = dap->ap_current;
1279         dap_ap_select(dap, ap);
1280
1281         do {
1282                 retval = mem_ap_read_atomic_u32(dap, (dbgbase&0xFFFFF000) |
1283                                                 entry_offset, &romentry);
1284                 if (retval != ERROR_OK)
1285                         return retval;
1286
1287                 component_base = (dbgbase & 0xFFFFF000)
1288                         + (romentry & 0xFFFFF000);
1289
1290                 if (romentry & 0x1) {
1291                         retval = mem_ap_read_atomic_u32(dap,
1292                                         (component_base & 0xfffff000) | 0xfcc,
1293                                         &devtype);
1294                         if (retval != ERROR_OK)
1295                                 return retval;
1296                         if ((devtype & 0xff) == type) {
1297                                 *addr = component_base;
1298                                 retval = ERROR_OK;
1299                                 break;
1300                         }
1301                 }
1302                 entry_offset += 4;
1303         } while (romentry > 0);
1304
1305         dap_ap_select(dap, ap_old);
1306
1307         return retval;
1308 }
1309
1310 static int dap_info_command(struct command_context *cmd_ctx,
1311                 struct adiv5_dap *dap, int ap)
1312 {
1313         int retval;
1314         uint32_t dbgbase = 0, apid = 0; /* Silence gcc by initializing */
1315         int romtable_present = 0;
1316         uint8_t mem_ap;
1317         uint32_t ap_old;
1318
1319         retval = dap_get_debugbase(dap, ap, &dbgbase, &apid);
1320         if (retval != ERROR_OK)
1321                 return retval;
1322
1323         ap_old = dap->ap_current;
1324         dap_ap_select(dap, ap);
1325
1326         /* Now we read ROM table ID registers, ref. ARM IHI 0029B sec  */
1327         mem_ap = ((apid&0x10000) && ((apid&0x0F) != 0));
1328         command_print(cmd_ctx, "AP ID register 0x%8.8" PRIx32, apid);
1329         if (apid) {
1330                 switch (apid&0x0F) {
1331                         case 0:
1332                                 command_print(cmd_ctx, "\tType is JTAG-AP");
1333                                 break;
1334                         case 1:
1335                                 command_print(cmd_ctx, "\tType is MEM-AP AHB");
1336                                 break;
1337                         case 2:
1338                                 command_print(cmd_ctx, "\tType is MEM-AP APB");
1339                                 break;
1340                         default:
1341                                 command_print(cmd_ctx, "\tUnknown AP type");
1342                                 break;
1343                 }
1344
1345                 /* NOTE: a MEM-AP may have a single CoreSight component that's
1346                  * not a ROM table ... or have no such components at all.
1347                  */
1348                 if (mem_ap)
1349                         command_print(cmd_ctx, "AP BASE 0x%8.8" PRIx32, dbgbase);
1350         } else
1351                 command_print(cmd_ctx, "No AP found at this ap 0x%x", ap);
1352
1353         romtable_present = ((mem_ap) && (dbgbase != 0xFFFFFFFF));
1354         if (romtable_present) {
1355                 uint32_t cid0, cid1, cid2, cid3, memtype, romentry;
1356                 uint16_t entry_offset;
1357
1358                 /* bit 16 of apid indicates a memory access port */
1359                 if (dbgbase & 0x02)
1360                         command_print(cmd_ctx, "\tValid ROM table present");
1361                 else
1362                         command_print(cmd_ctx, "\tROM table in legacy format");
1363
1364                 /* Now we read ROM table ID registers, ref. ARM IHI 0029B sec  */
1365                 retval = mem_ap_read_u32(dap, (dbgbase&0xFFFFF000) | 0xFF0, &cid0);
1366                 if (retval != ERROR_OK)
1367                         return retval;
1368                 retval = mem_ap_read_u32(dap, (dbgbase&0xFFFFF000) | 0xFF4, &cid1);
1369                 if (retval != ERROR_OK)
1370                         return retval;
1371                 retval = mem_ap_read_u32(dap, (dbgbase&0xFFFFF000) | 0xFF8, &cid2);
1372                 if (retval != ERROR_OK)
1373                         return retval;
1374                 retval = mem_ap_read_u32(dap, (dbgbase&0xFFFFF000) | 0xFFC, &cid3);
1375                 if (retval != ERROR_OK)
1376                         return retval;
1377                 retval = mem_ap_read_u32(dap, (dbgbase&0xFFFFF000) | 0xFCC, &memtype);
1378                 if (retval != ERROR_OK)
1379                         return retval;
1380                 retval = dap_run(dap);
1381                 if (retval != ERROR_OK)
1382                         return retval;
1383
1384                 if (!is_dap_cid_ok(cid3, cid2, cid1, cid0))
1385                         command_print(cmd_ctx, "\tCID3 0x%2.2x"
1386                                         ", CID2 0x%2.2x"
1387                                         ", CID1 0x%2.2x"
1388                                         ", CID0 0x%2.2x",
1389                                         (unsigned) cid3, (unsigned)cid2,
1390                                         (unsigned) cid1, (unsigned) cid0);
1391                 if (memtype & 0x01)
1392                         command_print(cmd_ctx, "\tMEMTYPE system memory present on bus");
1393                 else
1394                         command_print(cmd_ctx, "\tMEMTYPE System memory not present. "
1395                                         "Dedicated debug bus.");
1396
1397                 /* Now we read ROM table entries from dbgbase&0xFFFFF000) | 0x000 until we get 0x00000000 */
1398                 entry_offset = 0;
1399                 do {
1400                         retval = mem_ap_read_atomic_u32(dap, (dbgbase&0xFFFFF000) | entry_offset, &romentry);
1401                         if (retval != ERROR_OK)
1402                                 return retval;
1403                         command_print(cmd_ctx, "\tROMTABLE[0x%x] = 0x%" PRIx32 "", entry_offset, romentry);
1404                         if (romentry & 0x01) {
1405                                 uint32_t c_cid0, c_cid1, c_cid2, c_cid3;
1406                                 uint32_t c_pid0, c_pid1, c_pid2, c_pid3, c_pid4;
1407                                 uint32_t component_base;
1408                                 unsigned part_num;
1409                                 char *type, *full;
1410
1411                                 component_base = (dbgbase & 0xFFFFF000) + (romentry & 0xFFFFF000);
1412
1413                                 /* IDs are in last 4K section */
1414                                 retval = mem_ap_read_atomic_u32(dap, component_base + 0xFE0, &c_pid0);
1415                                 if (retval != ERROR_OK)
1416                                         return retval;
1417                                 c_pid0 &= 0xff;
1418                                 retval = mem_ap_read_atomic_u32(dap, component_base + 0xFE4, &c_pid1);
1419                                 if (retval != ERROR_OK)
1420                                         return retval;
1421                                 c_pid1 &= 0xff;
1422                                 retval = mem_ap_read_atomic_u32(dap, component_base + 0xFE8, &c_pid2);
1423                                 if (retval != ERROR_OK)
1424                                         return retval;
1425                                 c_pid2 &= 0xff;
1426                                 retval = mem_ap_read_atomic_u32(dap, component_base + 0xFEC, &c_pid3);
1427                                 if (retval != ERROR_OK)
1428                                         return retval;
1429                                 c_pid3 &= 0xff;
1430                                 retval = mem_ap_read_atomic_u32(dap, component_base + 0xFD0, &c_pid4);
1431                                 if (retval != ERROR_OK)
1432                                         return retval;
1433                                 c_pid4 &= 0xff;
1434
1435                                 retval = mem_ap_read_atomic_u32(dap, component_base + 0xFF0, &c_cid0);
1436                                 if (retval != ERROR_OK)
1437                                         return retval;
1438                                 c_cid0 &= 0xff;
1439                                 retval = mem_ap_read_atomic_u32(dap, component_base + 0xFF4, &c_cid1);
1440                                 if (retval != ERROR_OK)
1441                                         return retval;
1442                                 c_cid1 &= 0xff;
1443                                 retval = mem_ap_read_atomic_u32(dap, component_base + 0xFF8, &c_cid2);
1444                                 if (retval != ERROR_OK)
1445                                         return retval;
1446                                 c_cid2 &= 0xff;
1447                                 retval = mem_ap_read_atomic_u32(dap, component_base + 0xFFC, &c_cid3);
1448                                 if (retval != ERROR_OK)
1449                                         return retval;
1450                                 c_cid3 &= 0xff;
1451
1452                                 command_print(cmd_ctx, "\t\tComponent base address 0x%" PRIx32 ","
1453                                                 "start address 0x%" PRIx32, component_base,
1454                                 /* component may take multiple 4K pages */
1455                                 component_base - 0x1000*(c_pid4 >> 4));
1456                                 command_print(cmd_ctx, "\t\tComponent class is 0x%x, %s",
1457                                                 (int) (c_cid1 >> 4) & 0xf,
1458                                                 /* See ARM IHI 0029B Table 3-3 */
1459                                                 class_description[(c_cid1 >> 4) & 0xf]);
1460
1461                                 /* CoreSight component? */
1462                                 if (((c_cid1 >> 4) & 0x0f) == 9) {
1463                                         uint32_t devtype;
1464                                         unsigned minor;
1465                                         char *major = "Reserved", *subtype = "Reserved";
1466
1467                                         retval = mem_ap_read_atomic_u32(dap,
1468                                                         (component_base & 0xfffff000) | 0xfcc,
1469                                                         &devtype);
1470                                         if (retval != ERROR_OK)
1471                                                 return retval;
1472                                         minor = (devtype >> 4) & 0x0f;
1473                                         switch (devtype & 0x0f) {
1474                                         case 0:
1475                                                 major = "Miscellaneous";
1476                                                 switch (minor) {
1477                                                 case 0:
1478                                                         subtype = "other";
1479                                                         break;
1480                                                 case 4:
1481                                                         subtype = "Validation component";
1482                                                         break;
1483                                                 }
1484                                                 break;
1485                                         case 1:
1486                                                 major = "Trace Sink";
1487                                                 switch (minor) {
1488                                                 case 0:
1489                                                         subtype = "other";
1490                                                         break;
1491                                                 case 1:
1492                                                         subtype = "Port";
1493                                                         break;
1494                                                 case 2:
1495                                                         subtype = "Buffer";
1496                                                         break;
1497                                                 }
1498                                                 break;
1499                                         case 2:
1500                                                 major = "Trace Link";
1501                                                 switch (minor) {
1502                                                 case 0:
1503                                                         subtype = "other";
1504                                                         break;
1505                                                 case 1:
1506                                                         subtype = "Funnel, router";
1507                                                         break;
1508                                                 case 2:
1509                                                         subtype = "Filter";
1510                                                         break;
1511                                                 case 3:
1512                                                         subtype = "FIFO, buffer";
1513                                                         break;
1514                                                 }
1515                                                 break;
1516                                         case 3:
1517                                                 major = "Trace Source";
1518                                                 switch (minor) {
1519                                                 case 0:
1520                                                         subtype = "other";
1521                                                         break;
1522                                                 case 1:
1523                                                         subtype = "Processor";
1524                                                         break;
1525                                                 case 2:
1526                                                         subtype = "DSP";
1527                                                         break;
1528                                                 case 3:
1529                                                         subtype = "Engine/Coprocessor";
1530                                                         break;
1531                                                 case 4:
1532                                                         subtype = "Bus";
1533                                                         break;
1534                                                 }
1535                                                 break;
1536                                         case 4:
1537                                                 major = "Debug Control";
1538                                                 switch (minor) {
1539                                                 case 0:
1540                                                         subtype = "other";
1541                                                         break;
1542                                                 case 1:
1543                                                         subtype = "Trigger Matrix";
1544                                                         break;
1545                                                 case 2:
1546                                                         subtype = "Debug Auth";
1547                                                         break;
1548                                                 }
1549                                                 break;
1550                                         case 5:
1551                                                 major = "Debug Logic";
1552                                                 switch (minor) {
1553                                                 case 0:
1554                                                         subtype = "other";
1555                                                         break;
1556                                                 case 1:
1557                                                         subtype = "Processor";
1558                                                         break;
1559                                                 case 2:
1560                                                         subtype = "DSP";
1561                                                         break;
1562                                                 case 3:
1563                                                         subtype = "Engine/Coprocessor";
1564                                                         break;
1565                                                 }
1566                                                 break;
1567                                         }
1568                                         command_print(cmd_ctx, "\t\tType is 0x%2.2x, %s, %s",
1569                                                         (unsigned) (devtype & 0xff),
1570                                                         major, subtype);
1571                                         /* REVISIT also show 0xfc8 DevId */
1572                                 }
1573
1574                                 if (!is_dap_cid_ok(cid3, cid2, cid1, cid0))
1575                                         command_print(cmd_ctx,
1576                                                         "\t\tCID3 0%2.2x"
1577                                                         ", CID2 0%2.2x"
1578                                                         ", CID1 0%2.2x"
1579                                                         ", CID0 0%2.2x",
1580                                                         (int) c_cid3,
1581                                                         (int) c_cid2,
1582                                                         (int)c_cid1,
1583                                                         (int)c_cid0);
1584                                 command_print(cmd_ctx,
1585                                 "\t\tPeripheral ID[4..0] = hex "
1586                                 "%2.2x %2.2x %2.2x %2.2x %2.2x",
1587                                 (int) c_pid4, (int) c_pid3, (int) c_pid2,
1588                                 (int) c_pid1, (int) c_pid0);
1589
1590                                 /* Part number interpretations are from Cortex
1591                                  * core specs, the CoreSight components TRM
1592                                  * (ARM DDI 0314H), CoreSight System Design
1593                                  * Guide (ARM DGI 0012D) and ETM specs; also
1594                                  * from chip observation (e.g. TI SDTI).
1595                                  */
1596                                 part_num = (c_pid0 & 0xff);
1597                                 part_num |= (c_pid1 & 0x0f) << 8;
1598                                 switch (part_num) {
1599                                 case 0x000:
1600                                         type = "Cortex-M3 NVIC";
1601                                         full = "(Interrupt Controller)";
1602                                         break;
1603                                 case 0x001:
1604                                         type = "Cortex-M3 ITM";
1605                                         full = "(Instrumentation Trace Module)";
1606                                         break;
1607                                 case 0x002:
1608                                         type = "Cortex-M3 DWT";
1609                                         full = "(Data Watchpoint and Trace)";
1610                                         break;
1611                                 case 0x003:
1612                                         type = "Cortex-M3 FBP";
1613                                         full = "(Flash Patch and Breakpoint)";
1614                                         break;
1615                                 case 0x00c:
1616                                         type = "Cortex-M4 SCS";
1617                                         full = "(System Control Space)";
1618                                         break;
1619                                 case 0x00d:
1620                                         type = "CoreSight ETM11";
1621                                         full = "(Embedded Trace)";
1622                                         break;
1623                                 /* case 0x113: what? */
1624                                 case 0x120:             /* from OMAP3 memmap */
1625                                         type = "TI SDTI";
1626                                         full = "(System Debug Trace Interface)";
1627                                         break;
1628                                 case 0x343:             /* from OMAP3 memmap */
1629                                         type = "TI DAPCTL";
1630                                         full = "";
1631                                         break;
1632                                 case 0x906:
1633                                         type = "Coresight CTI";
1634                                         full = "(Cross Trigger)";
1635                                         break;
1636                                 case 0x907:
1637                                         type = "Coresight ETB";
1638                                         full = "(Trace Buffer)";
1639                                         break;
1640                                 case 0x908:
1641                                         type = "Coresight CSTF";
1642                                         full = "(Trace Funnel)";
1643                                         break;
1644                                 case 0x910:
1645                                         type = "CoreSight ETM9";
1646                                         full = "(Embedded Trace)";
1647                                         break;
1648                                 case 0x912:
1649                                         type = "Coresight TPIU";
1650                                         full = "(Trace Port Interface Unit)";
1651                                         break;
1652                                 case 0x921:
1653                                         type = "Cortex-A8 ETM";
1654                                         full = "(Embedded Trace)";
1655                                         break;
1656                                 case 0x922:
1657                                         type = "Cortex-A8 CTI";
1658                                         full = "(Cross Trigger)";
1659                                         break;
1660                                 case 0x923:
1661                                         type = "Cortex-M3 TPIU";
1662                                         full = "(Trace Port Interface Unit)";
1663                                         break;
1664                                 case 0x924:
1665                                         type = "Cortex-M3 ETM";
1666                                         full = "(Embedded Trace)";
1667                                         break;
1668                                 case 0x925:
1669                                         type = "Cortex-M4 ETM";
1670                                         full = "(Embedded Trace)";
1671                                         break;
1672                                 case 0x930:
1673                                         type = "Cortex-R4 ETM";
1674                                         full = "(Embedded Trace)";
1675                                         break;
1676                                 case 0x9a1:
1677                                         type = "Cortex-M4 TPUI";
1678                                         full = "(Trace Port Interface Unit)";
1679                                         break;
1680                                 case 0xc08:
1681                                         type = "Cortex-A8 Debug";
1682                                         full = "(Debug Unit)";
1683                                         break;
1684                                 default:
1685                                         type = "-*- unrecognized -*-";
1686                                         full = "";
1687                                         break;
1688                                 }
1689                                 command_print(cmd_ctx, "\t\tPart is %s %s",
1690                                                 type, full);
1691                         } else {
1692                                 if (romentry)
1693                                         command_print(cmd_ctx, "\t\tComponent not present");
1694                                 else
1695                                         command_print(cmd_ctx, "\t\tEnd of ROM table");
1696                         }
1697                         entry_offset += 4;
1698                 } while (romentry > 0);
1699         } else
1700                 command_print(cmd_ctx, "\tNo ROM table present");
1701         dap_ap_select(dap, ap_old);
1702
1703         return ERROR_OK;
1704 }
1705
1706 COMMAND_HANDLER(handle_dap_info_command)
1707 {
1708         struct target *target = get_current_target(CMD_CTX);
1709         struct arm *arm = target_to_arm(target);
1710         struct adiv5_dap *dap = arm->dap;
1711         uint32_t apsel;
1712
1713         switch (CMD_ARGC) {
1714         case 0:
1715                 apsel = dap->apsel;
1716                 break;
1717         case 1:
1718                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], apsel);
1719                 break;
1720         default:
1721                 return ERROR_COMMAND_SYNTAX_ERROR;
1722         }
1723
1724         return dap_info_command(CMD_CTX, dap, apsel);
1725 }
1726
1727 COMMAND_HANDLER(dap_baseaddr_command)
1728 {
1729         struct target *target = get_current_target(CMD_CTX);
1730         struct arm *arm = target_to_arm(target);
1731         struct adiv5_dap *dap = arm->dap;
1732
1733         uint32_t apsel, baseaddr;
1734         int retval;
1735
1736         switch (CMD_ARGC) {
1737         case 0:
1738                 apsel = dap->apsel;
1739                 break;
1740         case 1:
1741                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], apsel);
1742                 /* AP address is in bits 31:24 of DP_SELECT */
1743                 if (apsel >= 256)
1744                         return ERROR_COMMAND_SYNTAX_ERROR;
1745                 break;
1746         default:
1747                 return ERROR_COMMAND_SYNTAX_ERROR;
1748         }
1749
1750         dap_ap_select(dap, apsel);
1751
1752         /* NOTE:  assumes we're talking to a MEM-AP, which
1753          * has a base address.  There are other kinds of AP,
1754          * though they're not common for now.  This should
1755          * use the ID register to verify it's a MEM-AP.
1756          */
1757         retval = dap_queue_ap_read(dap, AP_REG_BASE, &baseaddr);
1758         if (retval != ERROR_OK)
1759                 return retval;
1760         retval = dap_run(dap);
1761         if (retval != ERROR_OK)
1762                 return retval;
1763
1764         command_print(CMD_CTX, "0x%8.8" PRIx32, baseaddr);
1765
1766         return retval;
1767 }
1768
1769 COMMAND_HANDLER(dap_memaccess_command)
1770 {
1771         struct target *target = get_current_target(CMD_CTX);
1772         struct arm *arm = target_to_arm(target);
1773         struct adiv5_dap *dap = arm->dap;
1774
1775         uint32_t memaccess_tck;
1776
1777         switch (CMD_ARGC) {
1778         case 0:
1779                 memaccess_tck = dap->memaccess_tck;
1780                 break;
1781         case 1:
1782                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], memaccess_tck);
1783                 break;
1784         default:
1785                 return ERROR_COMMAND_SYNTAX_ERROR;
1786         }
1787         dap->memaccess_tck = memaccess_tck;
1788
1789         command_print(CMD_CTX, "memory bus access delay set to %" PRIi32 " tck",
1790                         dap->memaccess_tck);
1791
1792         return ERROR_OK;
1793 }
1794
1795 COMMAND_HANDLER(dap_apsel_command)
1796 {
1797         struct target *target = get_current_target(CMD_CTX);
1798         struct arm *arm = target_to_arm(target);
1799         struct adiv5_dap *dap = arm->dap;
1800
1801         uint32_t apsel, apid;
1802         int retval;
1803
1804         switch (CMD_ARGC) {
1805         case 0:
1806                 apsel = 0;
1807                 break;
1808         case 1:
1809                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], apsel);
1810                 /* AP address is in bits 31:24 of DP_SELECT */
1811                 if (apsel >= 256)
1812                         return ERROR_COMMAND_SYNTAX_ERROR;
1813                 break;
1814         default:
1815                 return ERROR_COMMAND_SYNTAX_ERROR;
1816         }
1817
1818         dap->apsel = apsel;
1819         dap_ap_select(dap, apsel);
1820
1821         retval = dap_queue_ap_read(dap, AP_REG_IDR, &apid);
1822         if (retval != ERROR_OK)
1823                 return retval;
1824         retval = dap_run(dap);
1825         if (retval != ERROR_OK)
1826                 return retval;
1827
1828         command_print(CMD_CTX, "ap %" PRIi32 " selected, identification register 0x%8.8" PRIx32,
1829                         apsel, apid);
1830
1831         return retval;
1832 }
1833
1834 COMMAND_HANDLER(dap_apid_command)
1835 {
1836         struct target *target = get_current_target(CMD_CTX);
1837         struct arm *arm = target_to_arm(target);
1838         struct adiv5_dap *dap = arm->dap;
1839
1840         uint32_t apsel, apid;
1841         int retval;
1842
1843         switch (CMD_ARGC) {
1844         case 0:
1845                 apsel = dap->apsel;
1846                 break;
1847         case 1:
1848                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], apsel);
1849                 /* AP address is in bits 31:24 of DP_SELECT */
1850                 if (apsel >= 256)
1851                         return ERROR_COMMAND_SYNTAX_ERROR;
1852                 break;
1853         default:
1854                 return ERROR_COMMAND_SYNTAX_ERROR;
1855         }
1856
1857         dap_ap_select(dap, apsel);
1858
1859         retval = dap_queue_ap_read(dap, AP_REG_IDR, &apid);
1860         if (retval != ERROR_OK)
1861                 return retval;
1862         retval = dap_run(dap);
1863         if (retval != ERROR_OK)
1864                 return retval;
1865
1866         command_print(CMD_CTX, "0x%8.8" PRIx32, apid);
1867
1868         return retval;
1869 }
1870
1871 static const struct command_registration dap_commands[] = {
1872         {
1873                 .name = "info",
1874                 .handler = handle_dap_info_command,
1875                 .mode = COMMAND_EXEC,
1876                 .help = "display ROM table for MEM-AP "
1877                         "(default currently selected AP)",
1878                 .usage = "[ap_num]",
1879         },
1880         {
1881                 .name = "apsel",
1882                 .handler = dap_apsel_command,
1883                 .mode = COMMAND_EXEC,
1884                 .help = "Set the currently selected AP (default 0) "
1885                         "and display the result",
1886                 .usage = "[ap_num]",
1887         },
1888         {
1889                 .name = "apid",
1890                 .handler = dap_apid_command,
1891                 .mode = COMMAND_EXEC,
1892                 .help = "return ID register from AP "
1893                         "(default currently selected AP)",
1894                 .usage = "[ap_num]",
1895         },
1896         {
1897                 .name = "baseaddr",
1898                 .handler = dap_baseaddr_command,
1899                 .mode = COMMAND_EXEC,
1900                 .help = "return debug base address from MEM-AP "
1901                         "(default currently selected AP)",
1902                 .usage = "[ap_num]",
1903         },
1904         {
1905                 .name = "memaccess",
1906                 .handler = dap_memaccess_command,
1907                 .mode = COMMAND_EXEC,
1908                 .help = "set/get number of extra tck for MEM-AP memory "
1909                         "bus access [0-255]",
1910                 .usage = "[cycles]",
1911         },
1912         COMMAND_REGISTRATION_DONE
1913 };
1914
1915 const struct command_registration dap_command_handlers[] = {
1916         {
1917                 .name = "dap",
1918                 .mode = COMMAND_EXEC,
1919                 .help = "DAP command group",
1920                 .usage = "",
1921                 .chain = dap_commands,
1922         },
1923         COMMAND_REGISTRATION_DONE
1924 };