]> sigrok.org Git - libsigrokdecode.git/blob - decoders/swd/pd.py
9b318d281a5cc008b9aa41e550dc48e0a0bb8ac3
[libsigrokdecode.git] / decoders / swd / pd.py
1 ##
2 ## This file is part of the libsigrokdecode project.
3 ##
4 ## Copyright (C) 2014 Angus Gratton <gus@projectgus.com>
5 ##
6 ## This program is free software; you can redistribute it and/or modify
7 ## it under the terms of the GNU General Public License as published by
8 ## the Free Software Foundation; either version 2 of the License, or
9 ## (at your option) any later version.
10 ##
11 ## This program is distributed in the hope that it will be useful,
12 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 ## GNU General Public License for more details.
15 ##
16 ## You should have received a copy of the GNU General Public License
17 ## along with this program; if not, write to the Free Software
18 ## Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
19 ##
20
21 import sigrokdecode as srd
22 import re
23
24 '''
25 OUTPUT_PYTHON format:
26
27 Packet:
28 [<ptype>, <pdata>]
29
30 <ptype>:
31  - 'AP_READ' (AP read)
32  - 'DP_READ' (DP read)
33  - 'AP_WRITE' (AP write)
34  - 'DP_WRITE' (DP write)
35  - 'LINE_RESET' (line reset sequence)
36
37 <pdata>:
38   - tuple of address, ack state, data for the given sequence
39 '''
40
41 swd_states = [
42     'IDLE', # Idle/unknown
43     'REQUEST', # Request phase (first 8 bits)
44     'ACK', # Ack phase (next 3 bits)
45     'READ', # Reading phase (next 32 bits for reads)
46     'WRITE', # Writing phase (next 32 bits for write)
47     'DPARITY', # Data parity phase
48 ]
49
50 # Regexes for matching SWD data out of bitstring ('1' / '0' characters) format
51 RE_SWDSWITCH = re.compile(bin(0xE79E)[:1:-1] + '$')
52 RE_SWDREQ = re.compile(r'1(?P<apdp>.)(?P<rw>.)(?P<addr>..)(?P<parity>.)01$')
53 RE_IDLE = re.compile('0' * 50 + '$')
54
55 # Sample edges
56 RISING = 1
57 FALLING = 0
58
59 ADDR_DP_SELECT = 0x8
60 ADDR_DP_CTRLSTAT = 0x4
61
62 BIT_SELECT_CTRLSEL = 1
63 BIT_CTRLSTAT_ORUNDETECT = 1
64
65 ANNOTATIONS = ['reset', 'enable', 'read', 'write', 'ack', 'data', 'parity']
66
67 class Decoder(srd.Decoder):
68     api_version = 3
69     id = 'swd'
70     name = 'SWD'
71     longname = 'Serial Wire Debug'
72     desc = 'Two-wire protocol for debug access to ARM CPUs.'
73     license = 'gplv2+'
74     inputs = ['logic']
75     outputs = ['swd']
76     channels = (
77         {'id': 'swclk', 'name': 'SWCLK', 'desc': 'Master clock'},
78         {'id': 'swdio', 'name': 'SWDIO', 'desc': 'Data input/output'},
79     )
80     options = (
81         {'id': 'strict_start',
82          'desc': 'Wait for a line reset before starting to decode',
83          'default': 'no', 'values': ('yes', 'no')},
84     )
85     annotations = (
86         ('reset', 'RESET'),
87         ('enable', 'ENABLE'),
88         ('read', 'READ'),
89         ('write', 'WRITE'),
90         ('ack', 'ACK'),
91         ('data', 'DATA'),
92         ('parity', 'PARITY'),
93     )
94
95     def __init__(self):
96         # SWD data/clock state
97         self.state = 'UNKNOWN'
98         self.sample_edge = RISING
99         self.ack = None # Ack state of the current phase
100         self.ss_req = 0 # Start sample of current req
101         self.turnaround = 0 # Number of turnaround edges to ignore before continuing
102         self.bits = '' # Bits from SWDIO are accumulated here, matched against expected sequences
103         self.samplenums = [] # Sample numbers that correspond to the samples in self.bits
104         self.linereset_count = 0
105
106         # SWD debug port state
107         self.data = None
108         self.addr = None
109         self.rw = None # Are we inside an SWD read or a write?
110         self.ctrlsel = 0 # 'ctrlsel' is bit 0 in the SELECT register.
111         self.orundetect = 0 # 'orundetect' is bit 0 in the CTRLSTAT register.
112
113     def start(self):
114         self.out_ann = self.register(srd.OUTPUT_ANN)
115         self.out_python = self.register(srd.OUTPUT_PYTHON)
116         if self.options['strict_start'] == 'no':
117             self.state = 'REQ' # No need to wait for a LINE RESET.
118
119     def putx(self, ann, length, data):
120         '''Output annotated data.'''
121         ann = ANNOTATIONS.index(ann)
122         try:
123             ss = self.samplenums[-length]
124         except IndexError:
125             ss = self.samplenums[0]
126         if self.state == 'REQ':
127             self.ss_req = ss
128         es = self.samplenum
129         self.put(ss, es, self.out_ann, [ann, [data]])
130
131     def putp(self, ptype, pdata):
132         self.put(self.ss_req, self.samplenum, self.out_python, [ptype, pdata])
133
134     def put_python_data(self):
135         '''Emit Python data item based on current SWD packet contents.'''
136         ptype = {
137             ('AP', 'R'): 'AP_READ',
138             ('AP', 'W'): 'AP_WRITE',
139             ('DP', 'R'): 'DP_READ',
140             ('DP', 'W'): 'DP_WRITE',
141         }[(self.apdp, self.rw)]
142         self.putp(ptype, (self.addr, self.data, self.ack))
143
144     def decode(self):
145         while True:
146             # Wait for any clock edge.
147             clk, dio = self.wait({0: 'e'})
148
149             # Count rising edges with DIO held high,
150             # as a line reset (50+ high edges) can happen from any state.
151             if clk == RISING:
152                 if dio == 1:
153                     self.linereset_count += 1
154                 else:
155                     if self.linereset_count >= 50:
156                         self.putx('reset', self.linereset_count, 'LINERESET')
157                         self.putp('LINE_RESET', None)
158                         self.reset_state()
159                     self.linereset_count = 0
160
161             # Otherwise, we only care about either rising or falling edges
162             # (depending on sample_edge, set according to current state).
163             if clk != self.sample_edge:
164                 continue
165
166             # Turnaround bits get skipped.
167             if self.turnaround > 0:
168                 self.turnaround -= 1
169                 continue
170
171             self.bits += str(dio)
172             self.samplenums.append(self.samplenum)
173             {
174                 'UNKNOWN': self.handle_unknown_edge,
175                 'REQ': self.handle_req_edge,
176                 'ACK': self.handle_ack_edge,
177                 'DATA': self.handle_data_edge,
178                 'DPARITY': self.handle_dparity_edge,
179             }[self.state]()
180
181     def next_state(self):
182         '''Step to the next SWD state, reset internal counters accordingly.'''
183         self.bits = ''
184         self.samplenums = []
185         self.linereset_count = 0
186         if self.state == 'UNKNOWN':
187             self.state = 'REQ'
188             self.sample_edge = RISING
189             self.turnaround = 0
190         elif self.state == 'REQ':
191             self.state = 'ACK'
192             self.sample_edge = FALLING
193             self.turnaround = 1
194         elif self.state == 'ACK':
195             self.state = 'DATA'
196             self.sample_edge = RISING if self.rw == 'W' else FALLING
197             self.turnaround = 0 if self.rw == 'R' else 2
198         elif self.state == 'DATA':
199             self.state = 'DPARITY'
200         elif self.state == 'DPARITY':
201             self.put_python_data()
202             self.state = 'REQ'
203             self.sample_edge = RISING
204             self.turnaround = 1 if self.rw == 'R' else 0
205
206     def reset_state(self):
207         '''Line reset (or equivalent), wait for a new pending SWD request.'''
208         if self.state != 'REQ': # Emit a Python data item.
209             self.put_python_data()
210         # Clear state.
211         self.bits = ''
212         self.samplenums = []
213         self.linereset_count = 0
214         self.turnaround = 0
215         self.sample_edge = RISING
216         self.data = ''
217         self.ack = None
218         self.state = 'REQ'
219
220     def handle_unknown_edge(self):
221         '''
222         Clock edge in the UNKNOWN state.
223         In the unknown state, clock edges get ignored until we see a line
224         reset (which is detected in the decode method, not here.)
225         '''
226         pass
227
228     def handle_req_edge(self):
229         '''Clock edge in the REQ state (waiting for SWD r/w request).'''
230         # Check for a JTAG->SWD enable sequence.
231         m = re.search(RE_SWDSWITCH, self.bits)
232         if m is not None:
233             self.putx('enable', 16, 'JTAG->SWD')
234             self.reset_state()
235             return
236
237         # Or a valid SWD Request packet.
238         m = re.search(RE_SWDREQ, self.bits)
239         if m is not None:
240             calc_parity = sum([int(x) for x in m.group('rw') + m.group('apdp') + m.group('addr')]) % 2
241             parity = '' if str(calc_parity) == m.group('parity') else 'E'
242             self.rw = 'R' if m.group('rw') == '1' else 'W'
243             self.apdp = 'AP' if m.group('apdp') == '1' else 'DP'
244             self.addr = int(m.group('addr')[::-1], 2) << 2
245             self.putx('read' if self.rw == 'R' else 'write', 8, self.get_address_description())
246             self.next_state()
247             return
248
249     def handle_ack_edge(self):
250         '''Clock edge in the ACK state (waiting for complete ACK sequence).'''
251         if len(self.bits) < 3:
252             return
253         if self.bits == '100':
254             self.putx('ack', 3, 'OK')
255             self.ack = 'OK'
256             self.next_state()
257         elif self.bits == '001':
258             self.putx('ack', 3, 'FAULT')
259             self.ack = 'FAULT'
260             if self.orundetect == 1:
261                 self.next_state()
262             else:
263                 self.reset_state()
264             self.turnaround = 1
265         elif self.bits == '010':
266             self.putx('ack', 3, 'WAIT')
267             self.ack = 'WAIT'
268             if self.orundetect == 1:
269                 self.next_state()
270             else:
271                 self.reset_state()
272             self.turnaround = 1
273         elif self.bits == '111':
274             self.putx('ack', 3, 'NOREPLY')
275             self.ack = 'NOREPLY'
276             self.reset_state()
277         else:
278             self.putx('ack', 3, 'ERROR')
279             self.ack = 'ERROR'
280             self.reset_state()
281
282     def handle_data_edge(self):
283         '''Clock edge in the DATA state (waiting for 32 bits to clock past).'''
284         if len(self.bits) < 32:
285             return
286         self.data = 0
287         self.dparity = 0
288         for x in range(32):
289             if self.bits[x] == '1':
290                 self.data += (1 << x)
291                 self.dparity += 1
292         self.dparity = self.dparity % 2
293
294         self.putx('data', 32, '0x%08x' % self.data)
295         self.next_state()
296
297     def handle_dparity_edge(self):
298         '''Clock edge in the DPARITY state (clocking in parity bit).'''
299         if str(self.dparity) != self.bits:
300             self.putx('parity', 1, str(self.dparity) + self.bits) # PARITY ERROR
301         elif self.rw == 'W':
302             self.handle_completed_write()
303         self.next_state()
304
305     def handle_completed_write(self):
306         '''
307         Update internal state of the debug port based on a completed
308         write operation.
309         '''
310         if self.apdp != 'DP':
311             return
312         elif self.addr == ADDR_DP_SELECT:
313             self.ctrlsel = self.data & BIT_SELECT_CTRLSEL
314         elif self.addr == ADDR_DP_CTRLSTAT and self.ctrlsel == 0:
315             self.orundetect = self.data & BIT_CTRLSTAT_ORUNDETECT
316
317     def get_address_description(self):
318         '''
319         Return a human-readable description of the currently selected address,
320         for annotated results.
321         '''
322         if self.apdp == 'DP':
323             if self.rw == 'R':
324                 # Tables 2-4 & 2-5 in ADIv5.2 spec ARM document IHI 0031C
325                 return {
326                     0: 'IDCODE',
327                     0x4: 'R CTRL/STAT' if self.ctrlsel == 0 else 'R DLCR',
328                     0x8: 'RESEND',
329                     0xC: 'RDBUFF'
330                 }[self.addr]
331             elif self.rw == 'W':
332                 # Tables 2-4 & 2-5 in ADIv5.2 spec ARM document IHI 0031C
333                 return {
334                     0: 'W ABORT',
335                     0x4: 'W CTRL/STAT' if self.ctrlsel == 0 else 'W DLCR',
336                     0x8: 'W SELECT',
337                     0xC: 'W RESERVED'
338                 }[self.addr]
339         elif self.apdp == 'AP':
340             if self.rw == 'R':
341                 return 'R AP%x' % self.addr
342             elif self.rw == 'W':
343                 return 'W AP%x' % self.addr
344
345         # Any legitimate operations shouldn't fall through to here, probably
346         # a decoder bug.
347         return '? %s%s%x' % (self.rw, self.apdp, self.addr)