jtag: retire tap field
[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 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 "arm.h"
73 #include "arm_adi_v5.h"
74 #include <helper/time_support.h>
75
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  * DPACC and APACC scanchain access through JTAG-DP                        *
91  *                                                                         *
92 ***************************************************************************/
93
94 /**
95  * Scan DPACC or APACC using target ordered uint8_t buffers.  No endianness
96  * conversions are performed.  See section 4.4.3 of the ADIv5 spec, which
97  * discusses operations which access these registers.
98  *
99  * Note that only one scan is performed.  If RnW is set, a separate scan
100  * will be needed to collect the data which was read; the "invalue" collects
101  * the posted result of a preceding operation, not the current one.
102  *
103  * @param swjdp the DAP
104  * @param instr JTAG_DP_APACC (AP access) or JTAG_DP_DPACC (DP access)
105  * @param reg_addr two significant bits; A[3:2]; for APACC access, the
106  *      SELECT register has more addressing bits.
107  * @param RnW false iff outvalue will be written to the DP or AP
108  * @param outvalue points to a 32-bit (little-endian) integer
109  * @param invalue NULL, or points to a 32-bit (little-endian) integer
110  * @param ack points to where the three bit JTAG_ACK_* code will be stored
111  */
112 static int adi_jtag_dp_scan(struct adiv5_dap *swjdp,
113                 uint8_t instr, uint8_t reg_addr, uint8_t RnW,
114                 uint8_t *outvalue, uint8_t *invalue, uint8_t *ack)
115 {
116         struct arm_jtag *jtag_info = swjdp->jtag_info;
117         struct scan_field fields[2];
118         uint8_t out_addr_buf;
119
120         jtag_set_end_state(TAP_IDLE);
121         arm_jtag_set_instr(jtag_info, instr, NULL);
122
123         /* Scan out a read or write operation using some DP or AP register.
124          * For APACC access with any sticky error flag set, this is discarded.
125          */
126         fields[0].num_bits = 3;
127         buf_set_u32(&out_addr_buf, 0, 3, ((reg_addr >> 1) & 0x6) | (RnW & 0x1));
128         fields[0].out_value = &out_addr_buf;
129         fields[0].in_value = ack;
130
131         /* NOTE: if we receive JTAG_ACK_WAIT, the previous operation did not
132          * complete; data we write is discarded, data we read is unpredictable.
133          * When overrun detect is active, STICKYORUN is set.
134          */
135
136         fields[1].num_bits = 32;
137         fields[1].out_value = outvalue;
138         fields[1].in_value = invalue;
139
140         jtag_add_dr_scan(jtag_info->tap, 2, fields, jtag_get_end_state());
141
142         /* Add specified number of tck clocks after starting memory bus
143          * access, giving the hardware time to complete the access.
144          * They provide more time for the (MEM) AP to complete the read ...
145          * See "Minimum Response Time" for JTAG-DP, in the ADIv5 spec.
146          */
147         if ((instr == JTAG_DP_APACC)
148                         && ((reg_addr == AP_REG_DRW)
149                                 || ((reg_addr & 0xF0) == AP_REG_BD0))
150                         && (swjdp->memaccess_tck != 0))
151                 jtag_add_runtest(swjdp->memaccess_tck,
152                                 jtag_set_end_state(TAP_IDLE));
153
154         return jtag_get_error();
155 }
156
157 /**
158  * Scan DPACC or APACC out and in from host ordered uint32_t buffers.
159  * This is exactly like adi_jtag_dp_scan(), except that endianness
160  * conversions are performed (so the types of invalue and outvalue
161  * must be different).
162  */
163 static int adi_jtag_dp_scan_u32(struct adiv5_dap *swjdp,
164                 uint8_t instr, uint8_t reg_addr, uint8_t RnW,
165                 uint32_t outvalue, uint32_t *invalue, uint8_t *ack)
166 {
167         uint8_t out_value_buf[4];
168         int retval;
169
170         buf_set_u32(out_value_buf, 0, 32, outvalue);
171
172         retval = adi_jtag_dp_scan(swjdp, instr, reg_addr, RnW,
173                         out_value_buf, (uint8_t *)invalue, ack);
174         if (retval != ERROR_OK)
175                 return retval;
176
177         if (invalue)
178                 jtag_add_callback(arm_le_to_h_u32,
179                                 (jtag_callback_data_t) invalue);
180
181         return retval;
182 }
183
184 /**
185  * Utility to write AP registers.
186  */
187 static inline int adi_jtag_ap_write_check(struct adiv5_dap *dap,
188                 uint8_t reg_addr, uint8_t *outvalue)
189 {
190         return adi_jtag_dp_scan(dap, JTAG_DP_APACC, reg_addr, DPAP_WRITE,
191                         outvalue, NULL, NULL);
192 }
193
194 static int adi_jtag_scan_inout_check_u32(struct adiv5_dap *swjdp,
195                 uint8_t instr, uint8_t reg_addr, uint8_t RnW,
196                 uint32_t outvalue, uint32_t *invalue)
197 {
198         int retval;
199
200         /* Issue the read or write */
201         retval = adi_jtag_dp_scan_u32(swjdp, instr, reg_addr,
202                         RnW, outvalue, NULL, NULL);
203         if (retval != ERROR_OK)
204                 return retval;
205
206         /* For reads,  collect posted value; RDBUFF has no other effect.
207          * Assumes read gets acked with OK/FAULT, and CTRL_STAT says "OK".
208          */
209         if ((RnW == DPAP_READ) && (invalue != NULL))
210                 retval = adi_jtag_dp_scan_u32(swjdp, JTAG_DP_DPACC,
211                                 DP_RDBUFF, DPAP_READ, 0, invalue, &swjdp->ack);
212         return retval;
213 }
214
215 static int jtagdp_transaction_endcheck(struct adiv5_dap *swjdp)
216 {
217         int retval;
218         uint32_t ctrlstat;
219
220         /* too expensive to call keep_alive() here */
221
222 #if 0
223         /* Danger!!!! BROKEN!!!! */
224         adi_jtag_scan_inout_check_u32(swjdp, JTAG_DP_DPACC,
225                         DP_CTRL_STAT, DPAP_READ, 0, &ctrlstat);
226         /* Danger!!!! BROKEN!!!! Why will jtag_execute_queue() fail here????
227         R956 introduced the check on return value here and now Michael Schwingen reports
228         that this code no longer works....
229
230         https://lists.berlios.de/pipermail/openocd-development/2008-September/003107.html
231         */
232         if ((retval = jtag_execute_queue()) != ERROR_OK)
233         {
234                 LOG_ERROR("BUG: Why does this fail the first time????");
235         }
236         /* Why??? second time it works??? */
237 #endif
238
239         /* Post CTRL/STAT read; discard any previous posted read value
240          * but collect its ACK status.
241          */
242         adi_jtag_scan_inout_check_u32(swjdp, JTAG_DP_DPACC,
243                         DP_CTRL_STAT, DPAP_READ, 0, &ctrlstat);
244         if ((retval = jtag_execute_queue()) != ERROR_OK)
245                 return retval;
246
247         swjdp->ack = swjdp->ack & 0x7;
248
249         /* common code path avoids calling timeval_ms() */
250         if (swjdp->ack != JTAG_ACK_OK_FAULT)
251         {
252                 long long then = timeval_ms();
253
254                 while (swjdp->ack != JTAG_ACK_OK_FAULT)
255                 {
256                         if (swjdp->ack == JTAG_ACK_WAIT)
257                         {
258                                 if ((timeval_ms()-then) > 1000)
259                                 {
260                                         /* NOTE:  this would be a good spot
261                                          * to use JTAG_DP_ABORT.
262                                          */
263                                         LOG_WARNING("Timeout (1000ms) waiting "
264                                                 "for ACK=OK/FAULT "
265                                                 "in JTAG-DP transaction");
266                                         return ERROR_JTAG_DEVICE_ERROR;
267                                 }
268                         }
269                         else
270                         {
271                                 LOG_WARNING("Invalid ACK %#x "
272                                                 "in JTAG-DP transaction",
273                                                 swjdp->ack);
274                                 return ERROR_JTAG_DEVICE_ERROR;
275                         }
276
277                         adi_jtag_scan_inout_check_u32(swjdp, JTAG_DP_DPACC,
278                                         DP_CTRL_STAT, DPAP_READ, 0, &ctrlstat);
279                         if ((retval = dap_run(swjdp)) != ERROR_OK)
280                                 return retval;
281                         swjdp->ack = swjdp->ack & 0x7;
282                 }
283         }
284
285         /* REVISIT also STICKYCMP, for pushed comparisons (nyet used) */
286
287         /* Check for STICKYERR and STICKYORUN */
288         if (ctrlstat & (SSTICKYORUN | SSTICKYERR))
289         {
290                 LOG_DEBUG("jtag-dp: CTRL/STAT error, 0x%" PRIx32, ctrlstat);
291                 /* Check power to debug regions */
292                 if ((ctrlstat & 0xf0000000) != 0xf0000000)
293                          ahbap_debugport_init(swjdp);
294                 else
295                 {
296                         uint32_t mem_ap_csw, mem_ap_tar;
297
298                         /* Maybe print information about last intended
299                          * MEM-AP access; but not if autoincrementing.
300                          * *Real* CSW and TAR values are always shown.
301                          */
302                         if (swjdp->ap_tar_value != (uint32_t) -1)
303                                 LOG_DEBUG("MEM-AP Cached values: "
304                                         "ap_bank 0x%" PRIx32
305                                         ", ap_csw 0x%" PRIx32
306                                         ", ap_tar 0x%" PRIx32,
307                                         swjdp->ap_bank_value,
308                                         swjdp->ap_csw_value,
309                                         swjdp->ap_tar_value);
310
311                         if (ctrlstat & SSTICKYORUN)
312                                 LOG_ERROR("JTAG-DP OVERRUN - check clock, "
313                                         "memaccess, or reduce jtag speed");
314
315                         if (ctrlstat & SSTICKYERR)
316                                 LOG_ERROR("JTAG-DP STICKY ERROR");
317
318                         /* Clear Sticky Error Bits */
319                         adi_jtag_scan_inout_check_u32(swjdp, JTAG_DP_DPACC,
320                                         DP_CTRL_STAT, DPAP_WRITE,
321                                         swjdp->dp_ctrl_stat | SSTICKYORUN
322                                                 | SSTICKYERR, NULL);
323                         adi_jtag_scan_inout_check_u32(swjdp, JTAG_DP_DPACC,
324                                         DP_CTRL_STAT, DPAP_READ, 0, &ctrlstat);
325                         if ((retval = dap_run(swjdp)) != ERROR_OK)
326                                 return retval;
327
328                         LOG_DEBUG("jtag-dp: CTRL/STAT 0x%" PRIx32, ctrlstat);
329
330                         retval = dap_queue_ap_read(swjdp,
331                                         AP_REG_CSW, &mem_ap_csw);
332                         if (retval != ERROR_OK)
333                                 return retval;
334
335                         retval = dap_queue_ap_read(swjdp,
336                                         AP_REG_TAR, &mem_ap_tar);
337                         if (retval != ERROR_OK)
338                                 return retval;
339
340                         if ((retval = dap_run(swjdp)) != ERROR_OK)
341                                 return retval;
342                         LOG_ERROR("MEM_AP_CSW 0x%" PRIx32 ", MEM_AP_TAR 0x%"
343                                         PRIx32, mem_ap_csw, mem_ap_tar);
344
345                 }
346                 if ((retval = dap_run(swjdp)) != ERROR_OK)
347                         return retval;
348                 return ERROR_JTAG_DEVICE_ERROR;
349         }
350
351         return ERROR_OK;
352 }
353
354 /***************************************************************************
355  *                                                                         *
356  * DP and MEM-AP  register access  through APACC and DPACC                 *
357  *                                                                         *
358 ***************************************************************************/
359
360 /**
361  * Select one of the APs connected to the specified DAP.  The
362  * selection is implicitly used with future AP transactions.
363  * This is a NOP if the specified AP is already selected.
364  *
365  * @param swjdp The DAP
366  * @param apsel Number of the AP to (implicitly) use with further
367  *      transactions.  This normally identifies a MEM-AP.
368  */
369 void dap_ap_select(struct adiv5_dap *swjdp,uint8_t apsel)
370 {
371         uint32_t select = (apsel << 24) & 0xFF000000;
372
373         if (select != swjdp->apsel)
374         {
375                 swjdp->apsel = select;
376                 /* Switching AP invalidates cached values.
377                  * Values MUST BE UPDATED BEFORE AP ACCESS.
378                  */
379                 swjdp->ap_bank_value = -1;
380                 swjdp->ap_csw_value = -1;
381                 swjdp->ap_tar_value = -1;
382         }
383 }
384
385 /**
386  * Queue transactions setting up transfer parameters for the
387  * currently selected MEM-AP.
388  *
389  * Subsequent transfers using registers like AP_REG_DRW or AP_REG_BD2
390  * initiate data reads or writes using memory or peripheral addresses.
391  * If the CSW is configured for it, the TAR may be automatically
392  * incremented after each transfer.
393  *
394  * @todo Rename to reflect it being specifically a MEM-AP function.
395  *
396  * @param swjdp The DAP connected to the MEM-AP.
397  * @param csw MEM-AP Control/Status Word (CSW) register to assign.  If this
398  *      matches the cached value, the register is not changed.
399  * @param tar MEM-AP Transfer Address Register (TAR) to assign.  If this
400  *      matches the cached address, the register is not changed.
401  *
402  * @return ERROR_OK if the transaction was properly queued, else a fault code.
403  */
404 int dap_setup_accessport(struct adiv5_dap *swjdp, uint32_t csw, uint32_t tar)
405 {
406         int retval;
407
408         csw = csw | CSW_DBGSWENABLE | CSW_MASTER_DEBUG | CSW_HPROT;
409         if (csw != swjdp->ap_csw_value)
410         {
411                 /* LOG_DEBUG("DAP: Set CSW %x",csw); */
412                 retval = dap_queue_ap_write(swjdp, AP_REG_CSW, csw);
413                 if (retval != ERROR_OK)
414                         return retval;
415                 swjdp->ap_csw_value = csw;
416         }
417         if (tar != swjdp->ap_tar_value)
418         {
419                 /* LOG_DEBUG("DAP: Set TAR %x",tar); */
420                 retval = dap_queue_ap_write(swjdp, AP_REG_TAR, tar);
421                 if (retval != ERROR_OK)
422                         return retval;
423                 swjdp->ap_tar_value = tar;
424         }
425         /* Disable TAR cache when autoincrementing */
426         if (csw & CSW_ADDRINC_MASK)
427                 swjdp->ap_tar_value = -1;
428         return ERROR_OK;
429 }
430
431 /**
432  * Asynchronous (queued) read of a word from memory or a system register.
433  *
434  * @param swjdp The DAP connected to the MEM-AP performing the read.
435  * @param address Address of the 32-bit word to read; it must be
436  *      readable by the currently selected MEM-AP.
437  * @param value points to where the word will be stored when the
438  *      transaction queue is flushed (assuming no errors).
439  *
440  * @return ERROR_OK for success.  Otherwise a fault code.
441  */
442 int mem_ap_read_u32(struct adiv5_dap *swjdp, uint32_t address,
443                 uint32_t *value)
444 {
445         int retval;
446
447         /* Use banked addressing (REG_BDx) to avoid some link traffic
448          * (updating TAR) when reading several consecutive addresses.
449          */
450         retval = dap_setup_accessport(swjdp, CSW_32BIT | CSW_ADDRINC_OFF,
451                         address & 0xFFFFFFF0);
452         if (retval != ERROR_OK)
453                 return retval;
454
455         return dap_queue_ap_read(swjdp, AP_REG_BD0 | (address & 0xC), value);
456 }
457
458 /**
459  * Synchronous read of a word from memory or a system register.
460  * As a side effect, this flushes any queued transactions.
461  *
462  * @param swjdp The DAP connected to the MEM-AP performing the read.
463  * @param address Address of the 32-bit word to read; it must be
464  *      readable by the currently selected MEM-AP.
465  * @param value points to where the result will be stored.
466  *
467  * @return ERROR_OK for success; *value holds the result.
468  * Otherwise a fault code.
469  */
470 int mem_ap_read_atomic_u32(struct adiv5_dap *swjdp, uint32_t address,
471                 uint32_t *value)
472 {
473         int retval;
474
475         retval = mem_ap_read_u32(swjdp, address, value);
476         if (retval != ERROR_OK)
477                 return retval;
478
479         return dap_run(swjdp);
480 }
481
482 /**
483  * Asynchronous (queued) write of a word to memory or a system register.
484  *
485  * @param swjdp The DAP connected to the MEM-AP.
486  * @param address Address to be written; it must be writable by
487  *      the currently selected MEM-AP.
488  * @param value Word that will be written to the address when transaction
489  *      queue is flushed (assuming no errors).
490  *
491  * @return ERROR_OK for success.  Otherwise a fault code.
492  */
493 int mem_ap_write_u32(struct adiv5_dap *swjdp, uint32_t address,
494                 uint32_t value)
495 {
496         int retval;
497
498         /* Use banked addressing (REG_BDx) to avoid some link traffic
499          * (updating TAR) when writing several consecutive addresses.
500          */
501         retval = dap_setup_accessport(swjdp, CSW_32BIT | CSW_ADDRINC_OFF,
502                         address & 0xFFFFFFF0);
503         if (retval != ERROR_OK)
504                 return retval;
505
506         return dap_queue_ap_write(swjdp, AP_REG_BD0 | (address & 0xC),
507                         value);
508 }
509
510 /**
511  * Synchronous write of a word to memory or a system register.
512  * As a side effect, this flushes any queued transactions.
513  *
514  * @param swjdp The DAP connected to the MEM-AP.
515  * @param address Address to be written; it must be writable by
516  *      the currently selected MEM-AP.
517  * @param value Word that will be written.
518  *
519  * @return ERROR_OK for success; the data was written.  Otherwise a fault code.
520  */
521 int mem_ap_write_atomic_u32(struct adiv5_dap *swjdp, uint32_t address,
522                 uint32_t value)
523 {
524         int retval = mem_ap_write_u32(swjdp, address, value);
525
526         if (retval != ERROR_OK)
527                 return retval;
528
529         return dap_run(swjdp);
530 }
531
532 /*****************************************************************************
533 *                                                                            *
534 * mem_ap_write_buf(struct adiv5_dap *swjdp, uint8_t *buffer, int count, uint32_t address) *
535 *                                                                            *
536 * Write a buffer in target order (little endian)                             *
537 *                                                                            *
538 *****************************************************************************/
539 int mem_ap_write_buf_u32(struct adiv5_dap *swjdp, uint8_t *buffer, int count, uint32_t address)
540 {
541         int wcount, blocksize, writecount, errorcount = 0, retval = ERROR_OK;
542         uint32_t adr = address;
543         uint8_t* pBuffer = buffer;
544
545         count >>= 2;
546         wcount = count;
547
548         /* if we have an unaligned access - reorder data */
549         if (adr & 0x3u)
550         {
551                 for (writecount = 0; writecount < count; writecount++)
552                 {
553                         int i;
554                         uint32_t outvalue;
555                         memcpy(&outvalue, pBuffer, sizeof(uint32_t));
556
557                         for (i = 0; i < 4; i++)
558                         {
559                                 *((uint8_t*)pBuffer + (adr & 0x3)) = outvalue;
560                                 outvalue >>= 8;
561                                 adr++;
562                         }
563                         pBuffer += sizeof(uint32_t);
564                 }
565         }
566
567         while (wcount > 0)
568         {
569                 /* Adjust to write blocks within boundaries aligned to the TAR autoincremnent size*/
570                 blocksize = max_tar_block_size(swjdp->tar_autoincr_block, address);
571                 if (wcount < blocksize)
572                         blocksize = wcount;
573
574                 /* handle unaligned data at 4k boundary */
575                 if (blocksize == 0)
576                         blocksize = 1;
577
578                 dap_setup_accessport(swjdp, CSW_32BIT | CSW_ADDRINC_SINGLE, address);
579
580                 for (writecount = 0; writecount < blocksize; writecount++)
581                 {
582                         retval = dap_queue_ap_write(swjdp, AP_REG_DRW,
583                                 *(uint32_t *) (buffer + 4 * writecount));
584                         if (retval != ERROR_OK)
585                                 break;
586                 }
587
588                 if (dap_run(swjdp) == ERROR_OK)
589                 {
590                         wcount = wcount - blocksize;
591                         address = address + 4 * blocksize;
592                         buffer = buffer + 4 * blocksize;
593                 }
594                 else
595                 {
596                         errorcount++;
597                 }
598
599                 if (errorcount > 1)
600                 {
601                         LOG_WARNING("Block write error address 0x%" PRIx32 ", wcount 0x%x", address, wcount);
602                         /* REVISIT return the *actual* fault code */
603                         return ERROR_JTAG_DEVICE_ERROR;
604                 }
605         }
606
607         return retval;
608 }
609
610 static int mem_ap_write_buf_packed_u16(struct adiv5_dap *swjdp,
611                 uint8_t *buffer, int count, uint32_t address)
612 {
613         int retval = ERROR_OK;
614         int wcount, blocksize, writecount, i;
615
616         wcount = count >> 1;
617
618         while (wcount > 0)
619         {
620                 int nbytes;
621
622                 /* Adjust to write blocks within boundaries aligned to the TAR autoincremnent size*/
623                 blocksize = max_tar_block_size(swjdp->tar_autoincr_block, address);
624
625                 if (wcount < blocksize)
626                         blocksize = wcount;
627
628                 /* handle unaligned data at 4k boundary */
629                 if (blocksize == 0)
630                         blocksize = 1;
631
632                 dap_setup_accessport(swjdp, CSW_16BIT | CSW_ADDRINC_PACKED, address);
633                 writecount = blocksize;
634
635                 do
636                 {
637                         nbytes = MIN((writecount << 1), 4);
638
639                         if (nbytes < 4)
640                         {
641                                 if (mem_ap_write_buf_u16(swjdp, buffer,
642                                                 nbytes, address) != ERROR_OK)
643                                 {
644                                         LOG_WARNING("Block write error address "
645                                                 "0x%" PRIx32 ", count 0x%x",
646                                                 address, count);
647                                         return ERROR_JTAG_DEVICE_ERROR;
648                                 }
649
650                                 address += nbytes >> 1;
651                         }
652                         else
653                         {
654                                 uint32_t outvalue;
655                                 memcpy(&outvalue, buffer, sizeof(uint32_t));
656
657                                 for (i = 0; i < nbytes; i++)
658                                 {
659                                         *((uint8_t*)buffer + (address & 0x3)) = outvalue;
660                                         outvalue >>= 8;
661                                         address++;
662                                 }
663
664                                 memcpy(&outvalue, buffer, sizeof(uint32_t));
665                                 retval = dap_queue_ap_write(swjdp,
666                                                 AP_REG_DRW, outvalue);
667                                 if (retval != ERROR_OK)
668                                         break;
669
670                                 if (dap_run(swjdp) != ERROR_OK)
671                                 {
672                                         LOG_WARNING("Block write error address "
673                                                 "0x%" PRIx32 ", count 0x%x",
674                                                 address, count);
675                                         /* REVISIT return *actual* fault code */
676                                         return ERROR_JTAG_DEVICE_ERROR;
677                                 }
678                         }
679
680                         buffer += nbytes >> 1;
681                         writecount -= nbytes >> 1;
682
683                 } while (writecount);
684                 wcount -= blocksize;
685         }
686
687         return retval;
688 }
689
690 int mem_ap_write_buf_u16(struct adiv5_dap *swjdp, uint8_t *buffer, int count, uint32_t address)
691 {
692         int retval = ERROR_OK;
693
694         if (count >= 4)
695                 return mem_ap_write_buf_packed_u16(swjdp, buffer, count, address);
696
697         while (count > 0)
698         {
699                 dap_setup_accessport(swjdp, CSW_16BIT | CSW_ADDRINC_SINGLE, address);
700                 uint16_t svalue;
701                 memcpy(&svalue, buffer, sizeof(uint16_t));
702                 uint32_t outvalue = (uint32_t)svalue << 8 * (address & 0x3);
703                 retval = dap_queue_ap_write(swjdp, AP_REG_DRW, outvalue);
704                 if (retval != ERROR_OK)
705                         break;
706
707                 retval = dap_run(swjdp);
708                 if (retval != ERROR_OK)
709                         break;
710
711                 count -= 2;
712                 address += 2;
713                 buffer += 2;
714         }
715
716         return retval;
717 }
718
719 static int mem_ap_write_buf_packed_u8(struct adiv5_dap *swjdp,
720                 uint8_t *buffer, int count, uint32_t address)
721 {
722         int retval = ERROR_OK;
723         int wcount, blocksize, writecount, i;
724
725         wcount = count;
726
727         while (wcount > 0)
728         {
729                 int nbytes;
730
731                 /* Adjust to write blocks within boundaries aligned to the TAR autoincremnent size*/
732                 blocksize = max_tar_block_size(swjdp->tar_autoincr_block, address);
733
734                 if (wcount < blocksize)
735                         blocksize = wcount;
736
737                 dap_setup_accessport(swjdp, CSW_8BIT | CSW_ADDRINC_PACKED, address);
738                 writecount = blocksize;
739
740                 do
741                 {
742                         nbytes = MIN(writecount, 4);
743
744                         if (nbytes < 4)
745                         {
746                                 if (mem_ap_write_buf_u8(swjdp, buffer, nbytes, address) != ERROR_OK)
747                                 {
748                                         LOG_WARNING("Block write error address "
749                                                 "0x%" PRIx32 ", count 0x%x",
750                                                 address, count);
751                                         return ERROR_JTAG_DEVICE_ERROR;
752                                 }
753
754                                 address += nbytes;
755                         }
756                         else
757                         {
758                                 uint32_t outvalue;
759                                 memcpy(&outvalue, buffer, sizeof(uint32_t));
760
761                                 for (i = 0; i < nbytes; i++)
762                                 {
763                                         *((uint8_t*)buffer + (address & 0x3)) = outvalue;
764                                         outvalue >>= 8;
765                                         address++;
766                                 }
767
768                                 memcpy(&outvalue, buffer, sizeof(uint32_t));
769                                 retval = dap_queue_ap_write(swjdp,
770                                                 AP_REG_DRW, outvalue);
771                                 if (retval != ERROR_OK)
772                                         break;
773
774                                 if (dap_run(swjdp) != ERROR_OK)
775                                 {
776                                         LOG_WARNING("Block write error address "
777                                                 "0x%" PRIx32 ", count 0x%x",
778                                                 address, count);
779                                         /* REVISIT return *actual* fault code */
780                                         return ERROR_JTAG_DEVICE_ERROR;
781                                 }
782                         }
783
784                         buffer += nbytes;
785                         writecount -= nbytes;
786
787                 } while (writecount);
788                 wcount -= blocksize;
789         }
790
791         return retval;
792 }
793
794 int mem_ap_write_buf_u8(struct adiv5_dap *swjdp, uint8_t *buffer, int count, uint32_t address)
795 {
796         int retval = ERROR_OK;
797
798         if (count >= 4)
799                 return mem_ap_write_buf_packed_u8(swjdp, buffer, count, address);
800
801         while (count > 0)
802         {
803                 dap_setup_accessport(swjdp, CSW_8BIT | CSW_ADDRINC_SINGLE, address);
804                 uint32_t outvalue = (uint32_t)*buffer << 8 * (address & 0x3);
805                 retval = dap_queue_ap_write(swjdp, AP_REG_DRW, outvalue);
806                 if (retval != ERROR_OK)
807                         break;
808
809                 retval = dap_run(swjdp);
810                 if (retval != ERROR_OK)
811                         break;
812
813                 count--;
814                 address++;
815                 buffer++;
816         }
817
818         return retval;
819 }
820
821 /**
822  * Synchronously read a block of 32-bit words into a buffer
823  * @param swjdp The DAP connected to the MEM-AP.
824  * @param buffer where the words will be stored (in host byte order).
825  * @param count How many words to read.
826  * @param address Memory address from which to read words; all the
827  *      words must be readable by the currently selected MEM-AP.
828  */
829 int mem_ap_read_buf_u32(struct adiv5_dap *swjdp, uint8_t *buffer,
830                 int count, uint32_t address)
831 {
832         int wcount, blocksize, readcount, errorcount = 0, retval = ERROR_OK;
833         uint32_t adr = address;
834         uint8_t* pBuffer = buffer;
835
836         count >>= 2;
837         wcount = count;
838
839         while (wcount > 0)
840         {
841                 /* Adjust to read blocks within boundaries aligned to the
842                  * TAR autoincrement size (at least 2^10).  Autoincrement
843                  * mode avoids an extra per-word roundtrip to update TAR.
844                  */
845                 blocksize = max_tar_block_size(swjdp->tar_autoincr_block,
846                                 address);
847                 if (wcount < blocksize)
848                         blocksize = wcount;
849
850                 /* handle unaligned data at 4k boundary */
851                 if (blocksize == 0)
852                         blocksize = 1;
853
854                 dap_setup_accessport(swjdp, CSW_32BIT | CSW_ADDRINC_SINGLE,
855                                 address);
856
857                 /* FIXME remove these three calls to adi_jtag_dp_scan(),
858                  * so this routine becomes transport-neutral.  Be careful
859                  * not to cause performance problems with JTAG; would it
860                  * suffice to loop over dap_queue_ap_read(), or would that
861                  * be slower when JTAG is the chosen transport?
862                  */
863
864                 /* Scan out first read */
865                 adi_jtag_dp_scan(swjdp, JTAG_DP_APACC, AP_REG_DRW,
866                                 DPAP_READ, 0, NULL, NULL);
867                 for (readcount = 0; readcount < blocksize - 1; readcount++)
868                 {
869                         /* Scan out next read; scan in posted value for the
870                          * previous one.  Assumes read is acked "OK/FAULT",
871                          * and CTRL_STAT says that meant "OK".
872                          */
873                         adi_jtag_dp_scan(swjdp, JTAG_DP_APACC, AP_REG_DRW,
874                                         DPAP_READ, 0, buffer + 4 * readcount,
875                                         &swjdp->ack);
876                 }
877
878                 /* Scan in last posted value; RDBUFF has no other effect,
879                  * assuming ack is OK/FAULT and CTRL_STAT says "OK".
880                  */
881                 adi_jtag_dp_scan(swjdp, JTAG_DP_DPACC, DP_RDBUFF,
882                                 DPAP_READ, 0, buffer + 4 * readcount,
883                                 &swjdp->ack);
884                 if (dap_run(swjdp) == ERROR_OK)
885                 {
886                         wcount = wcount - blocksize;
887                         address += 4 * blocksize;
888                         buffer += 4 * blocksize;
889                 }
890                 else
891                 {
892                         errorcount++;
893                 }
894
895                 if (errorcount > 1)
896                 {
897                         LOG_WARNING("Block read error address 0x%" PRIx32
898                                 ", count 0x%x", address, count);
899                         /* REVISIT return the *actual* fault code */
900                         return ERROR_JTAG_DEVICE_ERROR;
901                 }
902         }
903
904         /* if we have an unaligned access - reorder data */
905         if (adr & 0x3u)
906         {
907                 for (readcount = 0; readcount < count; readcount++)
908                 {
909                         int i;
910                         uint32_t data;
911                         memcpy(&data, pBuffer, sizeof(uint32_t));
912
913                         for (i = 0; i < 4; i++)
914                         {
915                                 *((uint8_t*)pBuffer) =
916                                                 (data >> 8 * (adr & 0x3));
917                                 pBuffer++;
918                                 adr++;
919                         }
920                 }
921         }
922
923         return retval;
924 }
925
926 static int mem_ap_read_buf_packed_u16(struct adiv5_dap *swjdp,
927                 uint8_t *buffer, int count, uint32_t address)
928 {
929         uint32_t invalue;
930         int retval = ERROR_OK;
931         int wcount, blocksize, readcount, i;
932
933         wcount = count >> 1;
934
935         while (wcount > 0)
936         {
937                 int nbytes;
938
939                 /* Adjust to read blocks within boundaries aligned to the TAR autoincremnent size*/
940                 blocksize = max_tar_block_size(swjdp->tar_autoincr_block, address);
941                 if (wcount < blocksize)
942                         blocksize = wcount;
943
944                 dap_setup_accessport(swjdp, CSW_16BIT | CSW_ADDRINC_PACKED, address);
945
946                 /* handle unaligned data at 4k boundary */
947                 if (blocksize == 0)
948                         blocksize = 1;
949                 readcount = blocksize;
950
951                 do
952                 {
953                         retval = dap_queue_ap_read(swjdp, AP_REG_DRW, &invalue);
954                         if (dap_run(swjdp) != ERROR_OK)
955                         {
956                                 LOG_WARNING("Block read error address 0x%" PRIx32 ", count 0x%x", address, count);
957                                 /* REVISIT return the *actual* fault code */
958                                 return ERROR_JTAG_DEVICE_ERROR;
959                         }
960
961                         nbytes = MIN((readcount << 1), 4);
962
963                         for (i = 0; i < nbytes; i++)
964                         {
965                                 *((uint8_t*)buffer) = (invalue >> 8 * (address & 0x3));
966                                 buffer++;
967                                 address++;
968                         }
969
970                         readcount -= (nbytes >> 1);
971                 } while (readcount);
972                 wcount -= blocksize;
973         }
974
975         return retval;
976 }
977
978 /**
979  * Synchronously read a block of 16-bit halfwords into a buffer
980  * @param swjdp The DAP connected to the MEM-AP.
981  * @param buffer where the halfwords will be stored (in host byte order).
982  * @param count How many halfwords to read.
983  * @param address Memory address from which to read words; all the
984  *      words must be readable by the currently selected MEM-AP.
985  */
986 int mem_ap_read_buf_u16(struct adiv5_dap *swjdp, uint8_t *buffer,
987                 int count, uint32_t address)
988 {
989         uint32_t invalue, i;
990         int retval = ERROR_OK;
991
992         if (count >= 4)
993                 return mem_ap_read_buf_packed_u16(swjdp, buffer, count, address);
994
995         while (count > 0)
996         {
997                 dap_setup_accessport(swjdp, CSW_16BIT | CSW_ADDRINC_SINGLE, address);
998                 retval = dap_queue_ap_read(swjdp, AP_REG_DRW, &invalue);
999                 if (retval != ERROR_OK)
1000                         break;
1001
1002                 retval = dap_run(swjdp);
1003                 if (retval != ERROR_OK)
1004                         break;
1005
1006                 if (address & 0x1)
1007                 {
1008                         for (i = 0; i < 2; i++)
1009                         {
1010                                 *((uint8_t*)buffer) = (invalue >> 8 * (address & 0x3));
1011                                 buffer++;
1012                                 address++;
1013                         }
1014                 }
1015                 else
1016                 {
1017                         uint16_t svalue = (invalue >> 8 * (address & 0x3));
1018                         memcpy(buffer, &svalue, sizeof(uint16_t));
1019                         address += 2;
1020                         buffer += 2;
1021                 }
1022                 count -= 2;
1023         }
1024
1025         return retval;
1026 }
1027
1028 /* FIX!!! is this a potential performance bottleneck w.r.t. requiring too many
1029  * roundtrips when jtag_execute_queue() has a large overhead(e.g. for USB)s?
1030  *
1031  * The solution is to arrange for a large out/in scan in this loop and
1032  * and convert data afterwards.
1033  */
1034 static int mem_ap_read_buf_packed_u8(struct adiv5_dap *swjdp,
1035                 uint8_t *buffer, int count, uint32_t address)
1036 {
1037         uint32_t invalue;
1038         int retval = ERROR_OK;
1039         int wcount, blocksize, readcount, i;
1040
1041         wcount = count;
1042
1043         while (wcount > 0)
1044         {
1045                 int nbytes;
1046
1047                 /* Adjust to read blocks within boundaries aligned to the TAR autoincremnent size*/
1048                 blocksize = max_tar_block_size(swjdp->tar_autoincr_block, address);
1049
1050                 if (wcount < blocksize)
1051                         blocksize = wcount;
1052
1053                 dap_setup_accessport(swjdp, CSW_8BIT | CSW_ADDRINC_PACKED, address);
1054                 readcount = blocksize;
1055
1056                 do
1057                 {
1058                         retval = dap_queue_ap_read(swjdp, AP_REG_DRW, &invalue);
1059                         if (dap_run(swjdp) != ERROR_OK)
1060                         {
1061                                 LOG_WARNING("Block read error address 0x%" PRIx32 ", count 0x%x", address, count);
1062                                 /* REVISIT return the *actual* fault code */
1063                                 return ERROR_JTAG_DEVICE_ERROR;
1064                         }
1065
1066                         nbytes = MIN(readcount, 4);
1067
1068                         for (i = 0; i < nbytes; i++)
1069                         {
1070                                 *((uint8_t*)buffer) = (invalue >> 8 * (address & 0x3));
1071                                 buffer++;
1072                                 address++;
1073                         }
1074
1075                         readcount -= nbytes;
1076                 } while (readcount);
1077                 wcount -= blocksize;
1078         }
1079
1080         return retval;
1081 }
1082
1083 /**
1084  * Synchronously read a block of bytes into a buffer
1085  * @param swjdp The DAP connected to the MEM-AP.
1086  * @param buffer where the bytes will be stored.
1087  * @param count How many bytes to read.
1088  * @param address Memory address from which to read data; all the
1089  *      data must be readable by the currently selected MEM-AP.
1090  */
1091 int mem_ap_read_buf_u8(struct adiv5_dap *swjdp, uint8_t *buffer,
1092                 int count, uint32_t address)
1093 {
1094         uint32_t invalue;
1095         int retval = ERROR_OK;
1096
1097         if (count >= 4)
1098                 return mem_ap_read_buf_packed_u8(swjdp, buffer, count, address);
1099
1100         while (count > 0)
1101         {
1102                 dap_setup_accessport(swjdp, CSW_8BIT | CSW_ADDRINC_SINGLE, address);
1103                 retval = dap_queue_ap_read(swjdp, AP_REG_DRW, &invalue);
1104                 retval = dap_run(swjdp);
1105                 if (retval != ERROR_OK)
1106                         break;
1107
1108                 *((uint8_t*)buffer) = (invalue >> 8 * (address & 0x3));
1109                 count--;
1110                 address++;
1111                 buffer++;
1112         }
1113
1114         return retval;
1115 }
1116
1117 /*--------------------------------------------------------------------------*/
1118
1119 static int jtag_idcode_q_read(struct adiv5_dap *dap,
1120                 uint8_t *ack, uint32_t *data)
1121 {
1122         struct arm_jtag *jtag_info = dap->jtag_info;
1123         int retval;
1124         struct scan_field fields[1];
1125
1126         jtag_set_end_state(TAP_IDLE);
1127
1128         /* This is a standard JTAG operation -- no DAP tweakage */
1129         retval = arm_jtag_set_instr(jtag_info, JTAG_DP_IDCODE, NULL);
1130         if (retval != ERROR_OK)
1131                 return retval;
1132
1133         fields[0].num_bits = 32;
1134         fields[0].out_value = NULL;
1135         fields[0].in_value = (void *) data;
1136
1137         jtag_add_dr_scan(jtag_info->tap, 1, fields, jtag_get_end_state());
1138         retval = jtag_get_error();
1139         if (retval != ERROR_OK)
1140                 return retval;
1141
1142         jtag_add_callback(arm_le_to_h_u32,
1143                         (jtag_callback_data_t) data);
1144
1145         return retval;
1146 }
1147
1148 static int jtag_dp_q_read(struct adiv5_dap *dap, unsigned reg,
1149                 uint32_t *data)
1150 {
1151         return adi_jtag_scan_inout_check_u32(dap, JTAG_DP_DPACC,
1152                         reg, DPAP_READ, 0, data);
1153 }
1154
1155 static int jtag_dp_q_write(struct adiv5_dap *dap, unsigned reg,
1156                 uint32_t data)
1157 {
1158         return adi_jtag_scan_inout_check_u32(dap, JTAG_DP_DPACC,
1159                         reg, DPAP_WRITE, data, NULL);
1160 }
1161
1162 /** Select the AP register bank matching bits 7:4 of reg. */
1163 static int jtag_ap_q_bankselect(struct adiv5_dap *dap, unsigned reg)
1164 {
1165         uint32_t select = reg & 0x000000F0;
1166
1167         if (select == dap->ap_bank_value)
1168                 return ERROR_OK;
1169         dap->ap_bank_value = select;
1170
1171         select |= dap->apsel;
1172
1173         return jtag_dp_q_write(dap, DP_SELECT, select);
1174 }
1175
1176 static int jtag_ap_q_read(struct adiv5_dap *dap, unsigned reg,
1177                 uint32_t *data)
1178 {
1179         int retval = jtag_ap_q_bankselect(dap, reg);
1180
1181         if (retval != ERROR_OK)
1182                 return retval;
1183
1184         return adi_jtag_scan_inout_check_u32(dap, JTAG_DP_APACC, reg,
1185                         DPAP_READ, 0, data);
1186 }
1187
1188 static int jtag_ap_q_write(struct adiv5_dap *dap, unsigned reg,
1189                 uint32_t data)
1190 {
1191         uint8_t out_value_buf[4];
1192
1193         int retval = jtag_ap_q_bankselect(dap, reg);
1194         if (retval != ERROR_OK)
1195                 return retval;
1196
1197         buf_set_u32(out_value_buf, 0, 32, data);
1198
1199         return adi_jtag_ap_write_check(dap, reg, out_value_buf);
1200 }
1201
1202 static int jtag_ap_q_abort(struct adiv5_dap *dap, uint8_t *ack)
1203 {
1204         /* for JTAG, this is the only valid ABORT register operation */
1205         return adi_jtag_dp_scan_u32(dap, JTAG_DP_ABORT,
1206                         0, DPAP_WRITE, 1, NULL, ack);
1207 }
1208
1209 static int jtag_dp_run(struct adiv5_dap *dap)
1210 {
1211         return jtagdp_transaction_endcheck(dap);
1212 }
1213
1214 static const struct dap_ops jtag_dp_ops = {
1215         .queue_idcode_read =    jtag_idcode_q_read,
1216         .queue_dp_read =        jtag_dp_q_read,
1217         .queue_dp_write =       jtag_dp_q_write,
1218         .queue_ap_read =        jtag_ap_q_read,
1219         .queue_ap_write =       jtag_ap_q_write,
1220         .queue_ap_abort =       jtag_ap_q_abort,
1221         .run =                  jtag_dp_run,
1222 };
1223
1224 /*--------------------------------------------------------------------------*/
1225
1226 /**
1227  * Initialize a DAP.  This sets up the power domains, prepares the DP
1228  * for further use, and arranges to use AP #0 for all AP operations
1229  * until dap_ap-select() changes that policy.
1230  *
1231  * @param swjdp The DAP being initialized.
1232  *
1233  * @todo Rename this.  We also need an initialization scheme which account
1234  * for SWD transports not just JTAG; that will need to address differences
1235  * in layering.  (JTAG is useful without any debug target; but not SWD.)
1236  * And this may not even use an AHB-AP ... e.g. DAP-Lite uses an APB-AP.
1237  */
1238 int ahbap_debugport_init(struct adiv5_dap *swjdp)
1239 {
1240         uint32_t idreg, romaddr, dummy;
1241         uint32_t ctrlstat;
1242         int cnt = 0;
1243         int retval;
1244
1245         LOG_DEBUG(" ");
1246
1247         /* JTAG-DP or SWJ-DP, in JTAG mode */
1248         swjdp->ops = &jtag_dp_ops;
1249
1250         /* Default MEM-AP setup.
1251          *
1252          * REVISIT AP #0 may be an inappropriate default for this.
1253          * Should we probe, or take a hint from the caller?
1254          * Presumably we can ignore the possibility of multiple APs.
1255          */
1256         swjdp->apsel = !0;
1257         dap_ap_select(swjdp, 0);
1258
1259         /* DP initialization */
1260
1261         retval = dap_queue_dp_read(swjdp, DP_CTRL_STAT, &dummy);
1262         if (retval != ERROR_OK)
1263                 return retval;
1264
1265         retval = dap_queue_dp_write(swjdp, DP_CTRL_STAT, SSTICKYERR);
1266         if (retval != ERROR_OK)
1267                 return retval;
1268
1269         retval = dap_queue_dp_read(swjdp, DP_CTRL_STAT, &dummy);
1270         if (retval != ERROR_OK)
1271                 return retval;
1272
1273         swjdp->dp_ctrl_stat = CDBGPWRUPREQ | CSYSPWRUPREQ;
1274         retval = dap_queue_dp_write(swjdp, DP_CTRL_STAT, swjdp->dp_ctrl_stat);
1275         if (retval != ERROR_OK)
1276                 return retval;
1277
1278         retval = dap_queue_dp_read(swjdp, DP_CTRL_STAT, &ctrlstat);
1279         if (retval != ERROR_OK)
1280                 return retval;
1281         if ((retval = dap_run(swjdp)) != ERROR_OK)
1282                 return retval;
1283
1284         /* Check that we have debug power domains activated */
1285         while (!(ctrlstat & CDBGPWRUPACK) && (cnt++ < 10))
1286         {
1287                 LOG_DEBUG("DAP: wait CDBGPWRUPACK");
1288                 retval = dap_queue_dp_read(swjdp, DP_CTRL_STAT, &ctrlstat);
1289                 if (retval != ERROR_OK)
1290                         return retval;
1291                 if ((retval = dap_run(swjdp)) != ERROR_OK)
1292                         return retval;
1293                 alive_sleep(10);
1294         }
1295
1296         while (!(ctrlstat & CSYSPWRUPACK) && (cnt++ < 10))
1297         {
1298                 LOG_DEBUG("DAP: wait CSYSPWRUPACK");
1299                 retval = dap_queue_dp_read(swjdp, DP_CTRL_STAT, &ctrlstat);
1300                 if (retval != ERROR_OK)
1301                         return retval;
1302                 if ((retval = dap_run(swjdp)) != ERROR_OK)
1303                         return retval;
1304                 alive_sleep(10);
1305         }
1306
1307         retval = dap_queue_dp_read(swjdp, DP_CTRL_STAT, &dummy);
1308         if (retval != ERROR_OK)
1309                 return retval;
1310         /* With debug power on we can activate OVERRUN checking */
1311         swjdp->dp_ctrl_stat = CDBGPWRUPREQ | CSYSPWRUPREQ | CORUNDETECT;
1312         retval = dap_queue_dp_write(swjdp, DP_CTRL_STAT, swjdp->dp_ctrl_stat);
1313         if (retval != ERROR_OK)
1314                 return retval;
1315         retval = dap_queue_dp_read(swjdp, DP_CTRL_STAT, &dummy);
1316         if (retval != ERROR_OK)
1317                 return retval;
1318
1319         /*
1320          * REVISIT this isn't actually *initializing* anything in an AP,
1321          * and doesn't care if it's a MEM-AP at all (much less AHB-AP).
1322          * Should it?  If the ROM address is valid, is this the right
1323          * place to scan the table and do any topology detection?
1324          */
1325         retval = dap_queue_ap_read(swjdp, AP_REG_IDR, &idreg);
1326         retval = dap_queue_ap_read(swjdp, AP_REG_BASE, &romaddr);
1327
1328         LOG_DEBUG("MEM-AP #%d ID Register 0x%" PRIx32
1329                 ", Debug ROM Address 0x%" PRIx32,
1330                 swjdp->apsel, idreg, romaddr);
1331
1332         return ERROR_OK;
1333 }
1334
1335 /* CID interpretation -- see ARM IHI 0029B section 3
1336  * and ARM IHI 0031A table 13-3.
1337  */
1338 static const char *class_description[16] ={
1339         "Reserved", "ROM table", "Reserved", "Reserved",
1340         "Reserved", "Reserved", "Reserved", "Reserved",
1341         "Reserved", "CoreSight component", "Reserved", "Peripheral Test Block",
1342         "Reserved", "OptimoDE DESS",
1343                 "Generic IP component", "PrimeCell or System component"
1344 };
1345
1346 static bool
1347 is_dap_cid_ok(uint32_t cid3, uint32_t cid2, uint32_t cid1, uint32_t cid0)
1348 {
1349         return cid3 == 0xb1 && cid2 == 0x05
1350                         && ((cid1 & 0x0f) == 0) && cid0 == 0x0d;
1351 }
1352
1353 static int dap_info_command(struct command_context *cmd_ctx,
1354                 struct adiv5_dap *swjdp, int apsel)
1355 {
1356         int retval;
1357         uint32_t dbgbase, apid;
1358         int romtable_present = 0;
1359         uint8_t mem_ap;
1360         uint32_t apselold;
1361
1362         /* AP address is in bits 31:24 of DP_SELECT */
1363         if (apsel >= 256)
1364                 return ERROR_INVALID_ARGUMENTS;
1365
1366         apselold = swjdp->apsel;
1367         dap_ap_select(swjdp, apsel);
1368         retval = dap_queue_ap_read(swjdp, AP_REG_BASE, &dbgbase);
1369         retval = dap_queue_ap_read(swjdp, AP_REG_IDR, &apid);
1370         retval = dap_run(swjdp);
1371         if (retval != ERROR_OK)
1372                 return retval;
1373
1374         /* Now we read ROM table ID registers, ref. ARM IHI 0029B sec  */
1375         mem_ap = ((apid&0x10000) && ((apid&0x0F) != 0));
1376         command_print(cmd_ctx, "AP ID register 0x%8.8" PRIx32, apid);
1377         if (apid)
1378         {
1379                 switch (apid&0x0F)
1380                 {
1381                         case 0:
1382                                 command_print(cmd_ctx, "\tType is JTAG-AP");
1383                                 break;
1384                         case 1:
1385                                 command_print(cmd_ctx, "\tType is MEM-AP AHB");
1386                                 break;
1387                         case 2:
1388                                 command_print(cmd_ctx, "\tType is MEM-AP APB");
1389                                 break;
1390                         default:
1391                                 command_print(cmd_ctx, "\tUnknown AP type");
1392                                 break;
1393                 }
1394
1395                 /* NOTE: a MEM-AP may have a single CoreSight component that's
1396                  * not a ROM table ... or have no such components at all.
1397                  */
1398                 if (mem_ap)
1399                         command_print(cmd_ctx, "AP BASE 0x%8.8" PRIx32,
1400                                         dbgbase);
1401         }
1402         else
1403         {
1404                 command_print(cmd_ctx, "No AP found at this apsel 0x%x", apsel);
1405         }
1406
1407         romtable_present = ((mem_ap) && (dbgbase != 0xFFFFFFFF));
1408         if (romtable_present)
1409         {
1410                 uint32_t cid0,cid1,cid2,cid3,memtype,romentry;
1411                 uint16_t entry_offset;
1412
1413                 /* bit 16 of apid indicates a memory access port */
1414                 if (dbgbase & 0x02)
1415                         command_print(cmd_ctx, "\tValid ROM table present");
1416                 else
1417                         command_print(cmd_ctx, "\tROM table in legacy format");
1418
1419                 /* Now we read ROM table ID registers, ref. ARM IHI 0029B sec  */
1420                 mem_ap_read_u32(swjdp, (dbgbase&0xFFFFF000) | 0xFF0, &cid0);
1421                 mem_ap_read_u32(swjdp, (dbgbase&0xFFFFF000) | 0xFF4, &cid1);
1422                 mem_ap_read_u32(swjdp, (dbgbase&0xFFFFF000) | 0xFF8, &cid2);
1423                 mem_ap_read_u32(swjdp, (dbgbase&0xFFFFF000) | 0xFFC, &cid3);
1424                 mem_ap_read_u32(swjdp, (dbgbase&0xFFFFF000) | 0xFCC, &memtype);
1425                 retval = dap_run(swjdp);
1426                 if (retval != ERROR_OK)
1427                         return retval;
1428
1429                 if (!is_dap_cid_ok(cid3, cid2, cid1, cid0))
1430                         command_print(cmd_ctx, "\tCID3 0x%2.2" PRIx32
1431                                         ", CID2 0x%2.2" PRIx32
1432                                         ", CID1 0x%2.2" PRIx32
1433                                         ", CID0 0x%2.2" PRIx32,
1434                                         cid3, cid2, cid1, cid0);
1435                 if (memtype & 0x01)
1436                         command_print(cmd_ctx, "\tMEMTYPE system memory present on bus");
1437                 else
1438                         command_print(cmd_ctx, "\tMEMTYPE System memory not present. "
1439                                         "Dedicated debug bus.");
1440
1441                 /* Now we read ROM table entries from dbgbase&0xFFFFF000) | 0x000 until we get 0x00000000 */
1442                 entry_offset = 0;
1443                 do
1444                 {
1445                         mem_ap_read_atomic_u32(swjdp, (dbgbase&0xFFFFF000) | entry_offset, &romentry);
1446                         command_print(cmd_ctx, "\tROMTABLE[0x%x] = 0x%" PRIx32 "",entry_offset,romentry);
1447                         if (romentry&0x01)
1448                         {
1449                                 uint32_t c_cid0, c_cid1, c_cid2, c_cid3;
1450                                 uint32_t c_pid0, c_pid1, c_pid2, c_pid3, c_pid4;
1451                                 uint32_t component_start, component_base;
1452                                 unsigned part_num;
1453                                 char *type, *full;
1454
1455                                 component_base = (uint32_t)((dbgbase & 0xFFFFF000)
1456                                                 + (int)(romentry & 0xFFFFF000));
1457                                 mem_ap_read_atomic_u32(swjdp,
1458                                                 (component_base & 0xFFFFF000) | 0xFE0, &c_pid0);
1459                                 mem_ap_read_atomic_u32(swjdp,
1460                                                 (component_base & 0xFFFFF000) | 0xFE4, &c_pid1);
1461                                 mem_ap_read_atomic_u32(swjdp,
1462                                                 (component_base & 0xFFFFF000) | 0xFE8, &c_pid2);
1463                                 mem_ap_read_atomic_u32(swjdp,
1464                                                 (component_base & 0xFFFFF000) | 0xFEC, &c_pid3);
1465                                 mem_ap_read_atomic_u32(swjdp,
1466                                                 (component_base & 0xFFFFF000) | 0xFD0, &c_pid4);
1467                                 mem_ap_read_atomic_u32(swjdp,
1468                                                 (component_base & 0xFFFFF000) | 0xFF0, &c_cid0);
1469                                 mem_ap_read_atomic_u32(swjdp,
1470                                                 (component_base & 0xFFFFF000) | 0xFF4, &c_cid1);
1471                                 mem_ap_read_atomic_u32(swjdp,
1472                                                 (component_base & 0xFFFFF000) | 0xFF8, &c_cid2);
1473                                 mem_ap_read_atomic_u32(swjdp,
1474                                                 (component_base & 0xFFFFF000) | 0xFFC, &c_cid3);
1475                                 component_start = component_base - 0x1000*(c_pid4 >> 4);
1476
1477                                 command_print(cmd_ctx, "\t\tComponent base address 0x%" PRIx32
1478                                                 ", start address 0x%" PRIx32,
1479                                                 component_base, component_start);
1480                                 command_print(cmd_ctx, "\t\tComponent class is 0x%x, %s",
1481                                                 (int) (c_cid1 >> 4) & 0xf,
1482                                                 /* See ARM IHI 0029B Table 3-3 */
1483                                                 class_description[(c_cid1 >> 4) & 0xf]);
1484
1485                                 /* CoreSight component? */
1486                                 if (((c_cid1 >> 4) & 0x0f) == 9) {
1487                                         uint32_t devtype;
1488                                         unsigned minor;
1489                                         char *major = "Reserved", *subtype = "Reserved";
1490
1491                                         mem_ap_read_atomic_u32(swjdp,
1492                                                         (component_base & 0xfffff000) | 0xfcc,
1493                                                         &devtype);
1494                                         minor = (devtype >> 4) & 0x0f;
1495                                         switch (devtype & 0x0f) {
1496                                         case 0:
1497                                                 major = "Miscellaneous";
1498                                                 switch (minor) {
1499                                                 case 0:
1500                                                         subtype = "other";
1501                                                         break;
1502                                                 case 4:
1503                                                         subtype = "Validation component";
1504                                                         break;
1505                                                 }
1506                                                 break;
1507                                         case 1:
1508                                                 major = "Trace Sink";
1509                                                 switch (minor) {
1510                                                 case 0:
1511                                                         subtype = "other";
1512                                                         break;
1513                                                 case 1:
1514                                                         subtype = "Port";
1515                                                         break;
1516                                                 case 2:
1517                                                         subtype = "Buffer";
1518                                                         break;
1519                                                 }
1520                                                 break;
1521                                         case 2:
1522                                                 major = "Trace Link";
1523                                                 switch (minor) {
1524                                                 case 0:
1525                                                         subtype = "other";
1526                                                         break;
1527                                                 case 1:
1528                                                         subtype = "Funnel, router";
1529                                                         break;
1530                                                 case 2:
1531                                                         subtype = "Filter";
1532                                                         break;
1533                                                 case 3:
1534                                                         subtype = "FIFO, buffer";
1535                                                         break;
1536                                                 }
1537                                                 break;
1538                                         case 3:
1539                                                 major = "Trace Source";
1540                                                 switch (minor) {
1541                                                 case 0:
1542                                                         subtype = "other";
1543                                                         break;
1544                                                 case 1:
1545                                                         subtype = "Processor";
1546                                                         break;
1547                                                 case 2:
1548                                                         subtype = "DSP";
1549                                                         break;
1550                                                 case 3:
1551                                                         subtype = "Engine/Coprocessor";
1552                                                         break;
1553                                                 case 4:
1554                                                         subtype = "Bus";
1555                                                         break;
1556                                                 }
1557                                                 break;
1558                                         case 4:
1559                                                 major = "Debug Control";
1560                                                 switch (minor) {
1561                                                 case 0:
1562                                                         subtype = "other";
1563                                                         break;
1564                                                 case 1:
1565                                                         subtype = "Trigger Matrix";
1566                                                         break;
1567                                                 case 2:
1568                                                         subtype = "Debug Auth";
1569                                                         break;
1570                                                 }
1571                                                 break;
1572                                         case 5:
1573                                                 major = "Debug Logic";
1574                                                 switch (minor) {
1575                                                 case 0:
1576                                                         subtype = "other";
1577                                                         break;
1578                                                 case 1:
1579                                                         subtype = "Processor";
1580                                                         break;
1581                                                 case 2:
1582                                                         subtype = "DSP";
1583                                                         break;
1584                                                 case 3:
1585                                                         subtype = "Engine/Coprocessor";
1586                                                         break;
1587                                                 }
1588                                                 break;
1589                                         }
1590                                         command_print(cmd_ctx, "\t\tType is 0x%2.2x, %s, %s",
1591                                                         (unsigned) (devtype & 0xff),
1592                                                         major, subtype);
1593                                         /* REVISIT also show 0xfc8 DevId */
1594                                 }
1595
1596                                 if (!is_dap_cid_ok(cid3, cid2, cid1, cid0))
1597                                         command_print(cmd_ctx, "\t\tCID3 0x%2.2" PRIx32
1598                                                         ", CID2 0x%2.2" PRIx32
1599                                                         ", CID1 0x%2.2" PRIx32
1600                                                         ", CID0 0x%2.2" PRIx32,
1601                                                         c_cid3, c_cid2, c_cid1, c_cid0);
1602                                 command_print(cmd_ctx, "\t\tPeripheral ID[4..0] = hex "
1603                                                 "%2.2x %2.2x %2.2x %2.2x %2.2x",
1604                                                 (int) c_pid4,
1605                                                 (int) c_pid3, (int) c_pid2,
1606                                                 (int) c_pid1, (int) c_pid0);
1607
1608                                 /* Part number interpretations are from Cortex
1609                                  * core specs, the CoreSight components TRM
1610                                  * (ARM DDI 0314H), and ETM specs; also from
1611                                  * chip observation (e.g. TI SDTI).
1612                                  */
1613                                 part_num = c_pid0 & 0xff;
1614                                 part_num |= (c_pid1 & 0x0f) << 8;
1615                                 switch (part_num) {
1616                                 case 0x000:
1617                                         type = "Cortex-M3 NVIC";
1618                                         full = "(Interrupt Controller)";
1619                                         break;
1620                                 case 0x001:
1621                                         type = "Cortex-M3 ITM";
1622                                         full = "(Instrumentation Trace Module)";
1623                                         break;
1624                                 case 0x002:
1625                                         type = "Cortex-M3 DWT";
1626                                         full = "(Data Watchpoint and Trace)";
1627                                         break;
1628                                 case 0x003:
1629                                         type = "Cortex-M3 FBP";
1630                                         full = "(Flash Patch and Breakpoint)";
1631                                         break;
1632                                 case 0x00d:
1633                                         type = "CoreSight ETM11";
1634                                         full = "(Embedded Trace)";
1635                                         break;
1636                                 // case 0x113: what?
1637                                 case 0x120:             /* from OMAP3 memmap */
1638                                         type = "TI SDTI";
1639                                         full = "(System Debug Trace Interface)";
1640                                         break;
1641                                 case 0x343:             /* from OMAP3 memmap */
1642                                         type = "TI DAPCTL";
1643                                         full = "";
1644                                         break;
1645                                 case 0x906:
1646                                         type = "Coresight CTI";
1647                                         full = "(Cross Trigger)";
1648                                         break;
1649                                 case 0x907:
1650                                         type = "Coresight ETB";
1651                                         full = "(Trace Buffer)";
1652                                         break;
1653                                 case 0x908:
1654                                         type = "Coresight CSTF";
1655                                         full = "(Trace Funnel)";
1656                                         break;
1657                                 case 0x910:
1658                                         type = "CoreSight ETM9";
1659                                         full = "(Embedded Trace)";
1660                                         break;
1661                                 case 0x912:
1662                                         type = "Coresight TPIU";
1663                                         full = "(Trace Port Interface Unit)";
1664                                         break;
1665                                 case 0x921:
1666                                         type = "Cortex-A8 ETM";
1667                                         full = "(Embedded Trace)";
1668                                         break;
1669                                 case 0x922:
1670                                         type = "Cortex-A8 CTI";
1671                                         full = "(Cross Trigger)";
1672                                         break;
1673                                 case 0x923:
1674                                         type = "Cortex-M3 TPIU";
1675                                         full = "(Trace Port Interface Unit)";
1676                                         break;
1677                                 case 0x924:
1678                                         type = "Cortex-M3 ETM";
1679                                         full = "(Embedded Trace)";
1680                                         break;
1681                                 case 0xc08:
1682                                         type = "Cortex-A8 Debug";
1683                                         full = "(Debug Unit)";
1684                                         break;
1685                                 default:
1686                                         type = "-*- unrecognized -*-";
1687                                         full = "";
1688                                         break;
1689                                 }
1690                                 command_print(cmd_ctx, "\t\tPart is %s %s",
1691                                                 type, full);
1692                         }
1693                         else
1694                         {
1695                                 if (romentry)
1696                                         command_print(cmd_ctx, "\t\tComponent not present");
1697                                 else
1698                                         command_print(cmd_ctx, "\t\tEnd of ROM table");
1699                         }
1700                         entry_offset += 4;
1701                 } while (romentry > 0);
1702         }
1703         else
1704         {
1705                 command_print(cmd_ctx, "\tNo ROM table present");
1706         }
1707         dap_ap_select(swjdp, apselold);
1708
1709         return ERROR_OK;
1710 }
1711
1712 COMMAND_HANDLER(handle_dap_info_command)
1713 {
1714         struct target *target = get_current_target(CMD_CTX);
1715         struct arm *arm = target_to_arm(target);
1716         struct adiv5_dap *dap = arm->dap;
1717         uint32_t apsel;
1718
1719         switch (CMD_ARGC) {
1720         case 0:
1721                 apsel = dap->apsel;
1722                 break;
1723         case 1:
1724                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], apsel);
1725                 break;
1726         default:
1727                 return ERROR_COMMAND_SYNTAX_ERROR;
1728         }
1729
1730         return dap_info_command(CMD_CTX, dap, apsel);
1731 }
1732
1733 COMMAND_HANDLER(dap_baseaddr_command)
1734 {
1735         struct target *target = get_current_target(CMD_CTX);
1736         struct arm *arm = target_to_arm(target);
1737         struct adiv5_dap *dap = arm->dap;
1738
1739         uint32_t apsel, apselsave, baseaddr;
1740         int retval;
1741
1742         apselsave = dap->apsel;
1743         switch (CMD_ARGC) {
1744         case 0:
1745                 apsel = dap->apsel;
1746                 break;
1747         case 1:
1748                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], apsel);
1749                 /* AP address is in bits 31:24 of DP_SELECT */
1750                 if (apsel >= 256)
1751                         return ERROR_INVALID_ARGUMENTS;
1752                 break;
1753         default:
1754                 return ERROR_COMMAND_SYNTAX_ERROR;
1755         }
1756
1757         if (apselsave != apsel)
1758                 dap_ap_select(dap, apsel);
1759
1760         /* NOTE:  assumes we're talking to a MEM-AP, which
1761          * has a base address.  There are other kinds of AP,
1762          * though they're not common for now.  This should
1763          * use the ID register to verify it's a MEM-AP.
1764          */
1765         retval = dap_queue_ap_read(dap, AP_REG_BASE, &baseaddr);
1766         retval = dap_run(dap);
1767         if (retval != ERROR_OK)
1768                 return retval;
1769
1770         command_print(CMD_CTX, "0x%8.8" PRIx32, baseaddr);
1771
1772         if (apselsave != apsel)
1773                 dap_ap_select(dap, apselsave);
1774
1775         return retval;
1776 }
1777
1778 COMMAND_HANDLER(dap_memaccess_command)
1779 {
1780         struct target *target = get_current_target(CMD_CTX);
1781         struct arm *arm = target_to_arm(target);
1782         struct adiv5_dap *dap = arm->dap;
1783
1784         uint32_t memaccess_tck;
1785
1786         switch (CMD_ARGC) {
1787         case 0:
1788                 memaccess_tck = dap->memaccess_tck;
1789                 break;
1790         case 1:
1791                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], memaccess_tck);
1792                 break;
1793         default:
1794                 return ERROR_COMMAND_SYNTAX_ERROR;
1795         }
1796         dap->memaccess_tck = memaccess_tck;
1797
1798         command_print(CMD_CTX, "memory bus access delay set to %" PRIi32 " tck",
1799                         dap->memaccess_tck);
1800
1801         return ERROR_OK;
1802 }
1803
1804 COMMAND_HANDLER(dap_apsel_command)
1805 {
1806         struct target *target = get_current_target(CMD_CTX);
1807         struct arm *arm = target_to_arm(target);
1808         struct adiv5_dap *dap = arm->dap;
1809
1810         uint32_t apsel, apid;
1811         int retval;
1812
1813         switch (CMD_ARGC) {
1814         case 0:
1815                 apsel = 0;
1816                 break;
1817         case 1:
1818                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], apsel);
1819                 /* AP address is in bits 31:24 of DP_SELECT */
1820                 if (apsel >= 256)
1821                         return ERROR_INVALID_ARGUMENTS;
1822                 break;
1823         default:
1824                 return ERROR_COMMAND_SYNTAX_ERROR;
1825         }
1826
1827         dap_ap_select(dap, apsel);
1828         retval = dap_queue_ap_read(dap, AP_REG_IDR, &apid);
1829         retval = dap_run(dap);
1830         if (retval != ERROR_OK)
1831                 return retval;
1832
1833         command_print(CMD_CTX, "ap %" PRIi32 " selected, identification register 0x%8.8" PRIx32,
1834                         apsel, apid);
1835
1836         return retval;
1837 }
1838
1839 COMMAND_HANDLER(dap_apid_command)
1840 {
1841         struct target *target = get_current_target(CMD_CTX);
1842         struct arm *arm = target_to_arm(target);
1843         struct adiv5_dap *dap = arm->dap;
1844
1845         uint32_t apsel, apselsave, apid;
1846         int retval;
1847
1848         apselsave = dap->apsel;
1849         switch (CMD_ARGC) {
1850         case 0:
1851                 apsel = dap->apsel;
1852                 break;
1853         case 1:
1854                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], apsel);
1855                 /* AP address is in bits 31:24 of DP_SELECT */
1856                 if (apsel >= 256)
1857                         return ERROR_INVALID_ARGUMENTS;
1858                 break;
1859         default:
1860                 return ERROR_COMMAND_SYNTAX_ERROR;
1861         }
1862
1863         if (apselsave != apsel)
1864                 dap_ap_select(dap, apsel);
1865
1866         retval = dap_queue_ap_read(dap, AP_REG_IDR, &apid);
1867         retval = dap_run(dap);
1868         if (retval != ERROR_OK)
1869                 return retval;
1870
1871         command_print(CMD_CTX, "0x%8.8" PRIx32, apid);
1872         if (apselsave != apsel)
1873                 dap_ap_select(dap, apselsave);
1874
1875         return retval;
1876 }
1877
1878 static const struct command_registration dap_commands[] = {
1879         {
1880                 .name = "info",
1881                 .handler = handle_dap_info_command,
1882                 .mode = COMMAND_EXEC,
1883                 .help = "display ROM table for MEM-AP "
1884                         "(default currently selected AP)",
1885                 .usage = "[ap_num]",
1886         },
1887         {
1888                 .name = "apsel",
1889                 .handler = dap_apsel_command,
1890                 .mode = COMMAND_EXEC,
1891                 .help = "Set the currently selected AP (default 0) "
1892                         "and display the result",
1893                 .usage = "[ap_num]",
1894         },
1895         {
1896                 .name = "apid",
1897                 .handler = dap_apid_command,
1898                 .mode = COMMAND_EXEC,
1899                 .help = "return ID register from AP "
1900                         "(default currently selected AP)",
1901                 .usage = "[ap_num]",
1902         },
1903         {
1904                 .name = "baseaddr",
1905                 .handler = dap_baseaddr_command,
1906                 .mode = COMMAND_EXEC,
1907                 .help = "return debug base address from MEM-AP "
1908                         "(default currently selected AP)",
1909                 .usage = "[ap_num]",
1910         },
1911         {
1912                 .name = "memaccess",
1913                 .handler = dap_memaccess_command,
1914                 .mode = COMMAND_EXEC,
1915                 .help = "set/get number of extra tck for MEM-AP memory "
1916                         "bus access [0-255]",
1917                 .usage = "[cycles]",
1918         },
1919         COMMAND_REGISTRATION_DONE
1920 };
1921
1922 const struct command_registration dap_command_handlers[] = {
1923         {
1924                 .name = "dap",
1925                 .mode = COMMAND_EXEC,
1926                 .help = "DAP command group",
1927                 .chain = dap_commands,
1928         },
1929         COMMAND_REGISTRATION_DONE
1930 };
1931
1932
1933 /*
1934  * This represents the bits which must be sent out on TMS/SWDIO to
1935  * switch a DAP implemented using an SWJ-DP module into SWD mode.
1936  * These bits are stored (and transmitted) LSB-first.
1937  *
1938  * See the DAP-Lite specification, section 2.2.5 for information
1939  * about making the debug link select SWD or JTAG.  (Similar info
1940  * is in a few other ARM documents.)
1941  */
1942 static const uint8_t jtag2swd_bitseq[] = {
1943         /* More than 50 TCK/SWCLK cycles with TMS/SWDIO high,
1944          * putting both JTAG and SWD logic into reset state.
1945          */
1946         0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1947         /* Switching sequence enables SWD and disables JTAG
1948          * NOTE: bits in the DP's IDCODE may expose the need for
1949          * an old/deprecated sequence (0xb6 0xed).
1950          */
1951         0x9e, 0xe7,
1952         /* More than 50 TCK/SWCLK cycles with TMS/SWDIO high,
1953          * putting both JTAG and SWD logic into reset state.
1954          */
1955         0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1956 };
1957
1958 /**
1959  * Put the debug link into SWD mode, if the target supports it.
1960  * The link's initial mode may be either JTAG (for example,
1961  * with SWJ-DP after reset) or SWD.
1962  *
1963  * @param target Enters SWD mode (if possible).
1964  *
1965  * Note that targets using the JTAG-DP do not support SWD, and that
1966  * some targets which could otherwise support it may have have been
1967  * configured to disable SWD signaling
1968  *
1969  * @return ERROR_OK or else a fault code.
1970  */
1971 int dap_to_swd(struct target *target)
1972 {
1973         int retval;
1974
1975         LOG_DEBUG("Enter SWD mode");
1976
1977         /* REVISIT it's nasty to need to make calls to a "jtag"
1978          * subsystem if the link isn't in JTAG mode...
1979          */
1980
1981         retval =  jtag_add_tms_seq(8 * sizeof(jtag2swd_bitseq),
1982                         jtag2swd_bitseq, TAP_INVALID);
1983         if (retval == ERROR_OK)
1984                 retval = jtag_execute_queue();
1985
1986         /* REVISIT set up the DAP's ops vector for SWD mode. */
1987
1988         return retval;
1989 }
1990
1991 /**
1992  * This represents the bits which must be sent out on TMS/SWDIO to
1993  * switch a DAP implemented using an SWJ-DP module into JTAG mode.
1994  * These bits are stored (and transmitted) LSB-first.
1995  *
1996  * These bits are stored (and transmitted) LSB-first.
1997  */
1998 static const uint8_t swd2jtag_bitseq[] = {
1999         /* More than 50 TCK/SWCLK cycles with TMS/SWDIO high,
2000          * putting both JTAG and SWD logic into reset state.
2001          */
2002         0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
2003         /* Switching equence disables SWD and enables JTAG
2004          * NOTE: bits in the DP's IDCODE can expose the need for
2005          * the old/deprecated sequence (0xae 0xde).
2006          */
2007         0x3c, 0xe7,
2008         /* At least 50 TCK/SWCLK cycles with TMS/SWDIO high,
2009          * putting both JTAG and SWD logic into reset state.
2010          * NOTE:  some docs say "at least 5".
2011          */
2012         0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
2013 };
2014
2015 /** Put the debug link into JTAG mode, if the target supports it.
2016  * The link's initial mode may be either SWD or JTAG.
2017  *
2018  * @param target Enters JTAG mode (if possible).
2019  *
2020  * Note that targets implemented with SW-DP do not support JTAG, and
2021  * that some targets which could otherwise support it may have been
2022  * configured to disable JTAG signaling
2023  *
2024  * @return ERROR_OK or else a fault code.
2025  */
2026 int dap_to_jtag(struct target *target)
2027 {
2028         int retval;
2029
2030         LOG_DEBUG("Enter JTAG mode");
2031
2032         /* REVISIT it's nasty to need to make calls to a "jtag"
2033          * subsystem if the link isn't in JTAG mode...
2034          */
2035
2036         retval = jtag_add_tms_seq(8 * sizeof(swd2jtag_bitseq),
2037                         swd2jtag_bitseq, TAP_RESET);
2038         if (retval == ERROR_OK)
2039                 retval = jtag_execute_queue();
2040
2041         /* REVISIT set up the DAP's ops vector for JTAG mode. */
2042
2043         return retval;
2044 }