]> sigrok.org Git - libsigrokdecode.git/blame - decoders/usb_request/pd.py
decoders: Various cosmetic/consistency/typo fixes.
[libsigrokdecode.git] / decoders / usb_request / pd.py
CommitLineData
bd0e7d2e
SB
1##
2## This file is part of the libsigrokdecode project.
3##
4## Copyright (C) 2015 Stefan Brüns <stefan.bruens@rwth-aachen.de>
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
4539e9ca 17## along with this program; if not, see <http://www.gnu.org/licenses/>.
bd0e7d2e
SB
18##
19
20import sigrokdecode as srd
21import struct
22
23class SamplerateError(Exception):
24 pass
25
26class pcap_usb_pkt():
27 # Linux usbmon format, see Documentation/usb/usbmon.txt
28 h = b'\x00\x00\x00\x00' # ID part 1
29 h += b'\x00\x00\x00\x00' # ID part 2
30 h += b'C' # 'S'ubmit / 'C'omplete / 'E'rror
31 h += b'\x03' # ISO (0), Intr, Control, Bulk (3)
32 h += b'\x00' # Endpoint
33 h += b'\x00' # Device address
34 h += b'\x00\x00' # Bus number
35 h += b'-' # Setup tag - 0: Setup present, '-' otherwise
36 h += b'<' # Data tag - '<' no data, 0 otherwise
37 # Timestamp
38 h += b'\x00\x00\x00\x00' # TS seconds part 1
39 h += b'\x00\x00\x00\x00' # TS seconds part 2
40 h += b'\x00\x00\x00\x00' # TS useconds
41 #
42 h += b'\x00\x00\x00\x00' # Status 0: OK
43 h += b'\x00\x00\x00\x00' # URB length
44 h += b'\x00\x00\x00\x00' # Data length
45 # Setup packet data, valid if setup tag == 0
46 h += b'\x00' # bmRequestType
47 h += b'\x00' # bRequest
48 h += b'\x00\x00' # wValue
49 h += b'\x00\x00' # wIndex
50 h += b'\x00\x00' # wLength
51 #
52 h += b'\x00\x00\x00\x00' # ISO/interrupt interval
53 h += b'\x00\x00\x00\x00' # ISO start frame
54 h += b'\x00\x00\x00\x00' # URB flags
55 h += b'\x00\x00\x00\x00' # Number of ISO descriptors
56
57 def __init__(self, req, ts, is_submit):
58 self.header = bytearray(pcap_usb_pkt.h)
59 self.data = b''
60 self.set_urbid(req['id'])
61 self.set_urbtype('S' if is_submit else 'C')
62 self.set_timestamp(ts)
63 self.set_addr_ep(req['addr'], req['ep'])
64 if req['type'] in ('SETUP IN', 'SETUP OUT'):
65 self.set_transfertype(2) # Control
66 self.set_setup(req['setup_data'])
67 if req['type'] in ('BULK IN'):
68 self.set_addr_ep(req['addr'], 0x80 | req['ep'])
69 self.set_data(req['data'])
70
71 def set_urbid(self, urbid):
72 self.header[4:8] = struct.pack('>I', urbid)
73
74 def set_urbtype(self, urbtype):
75 self.header[8] = ord(urbtype)
76
77 def set_transfertype(self, transfertype):
78 self.header[9] = transfertype
79
80 def set_addr_ep(self, addr, ep):
81 self.header[11] = addr
82 self.header[10] = ep
83
84 def set_timestamp(self, ts):
85 self.timestamp = ts
86 self.header[20:24] = struct.pack('>I', ts[0]) # seconds
87 self.header[24:28] = struct.pack('>I', ts[1]) # microseconds
88
89 def set_data(self, data):
90 self.data = data
91 self.header[15] = 0
92 self.header[36:40] = struct.pack('>I', len(data))
93
94 def set_setup(self, data):
95 self.header[14] = 0
96 self.header[40:48] = data
97
98 def packet(self):
99 return bytes(self.header) + bytes(self.data)
100
101 def record_header(self):
102 # See https://wiki.wireshark.org/Development/LibpcapFileFormat.
103 (secs, usecs) = self.timestamp
104 h = struct.pack('>I', secs) # TS seconds
105 h += struct.pack('>I', usecs) # TS microseconds
106 # No truncation, so both lengths are the same.
107 h += struct.pack('>I', len(self)) # Captured len (usb hdr + data)
108 h += struct.pack('>I', len(self)) # Original len
109 return h
110
111 def __len__(self):
112 return 64 + len(self.data)
113
114class Decoder(srd.Decoder):
b197383c 115 api_version = 3
bd0e7d2e
SB
116 id = 'usb_request'
117 name = 'USB request'
118 longname = 'Universal Serial Bus (LS/FS) transaction/request'
2787cf2a 119 desc = 'USB (low-speed/full-speed) transaction/request protocol.'
bd0e7d2e
SB
120 license = 'gplv2+'
121 inputs = ['usb_packet']
122 outputs = ['usb_request']
d6d8a8a4 123 tags = ['PC']
bd0e7d2e
SB
124 annotations = (
125 ('request-setup-read', 'Setup: Device-to-host'),
126 ('request-setup-write', 'Setup: Host-to-device'),
127 ('request-bulk-read', 'Bulk: Device-to-host'),
128 ('request-bulk-write', 'Bulk: Host-to-device'),
129 ('errors', 'Unexpected packets'),
130 )
131 annotation_rows = (
132 ('request', 'USB requests', tuple(range(4))),
133 ('errors', 'Errors', (4,)),
134 )
135 binary = (
136 ('pcap', 'PCAP format'),
137 )
138
139 def __init__(self):
10aeb8ea
GS
140 self.reset()
141
142 def reset(self):
4045d684 143 self.samplerate = None
bd0e7d2e
SB
144 self.request = {}
145 self.request_id = 0
146 self.transaction_state = 'IDLE'
5b0b88ce
UH
147 self.ss_transaction = None
148 self.es_transaction = None
bd0e7d2e
SB
149 self.transaction_ep = None
150 self.transaction_addr = None
151 self.wrote_pcap_header = False
152
153 def putr(self, ss, es, data):
154 self.put(ss, es, self.out_ann, data)
155
156 def putb(self, ts, data):
2f370328 157 self.put(ts, ts, self.out_binary, data)
bd0e7d2e
SB
158
159 def pcap_global_header(self):
160 # See https://wiki.wireshark.org/Development/LibpcapFileFormat.
161 h = b'\xa1\xb2\xc3\xd4' # Magic, indicate microsecond ts resolution
162 h += b'\x00\x02' # Major version 2
163 h += b'\x00\x04' # Minor version 4
164 h += b'\x00\x00\x00\x00' # Correction vs. UTC, seconds
165 h += b'\x00\x00\x00\x00' # Timestamp accuracy
166 h += b'\xff\xff\xff\xff' # Max packet len
167 # LINKTYPE_USB_LINUX_MMAPPED 220
168 # Linux usbmon format, see Documentation/usb/usbmon.txt.
169 h += b'\x00\x00\x00\xdc' # Link layer
170 return h
171
172 def metadata(self, key, value):
173 if key == srd.SRD_CONF_SAMPLERATE:
174 self.samplerate = value
15a8a055
GS
175 if self.samplerate:
176 self.secs_per_sample = float(1) / float(self.samplerate)
bd0e7d2e
SB
177
178 def start(self):
2f370328 179 self.out_binary = self.register(srd.OUTPUT_BINARY)
bd0e7d2e
SB
180 self.out_ann = self.register(srd.OUTPUT_ANN)
181
182 def handle_transfer(self):
183 request_started = 0
72b2a50c 184 request_end = self.handshake in ('ACK', 'STALL', 'timeout')
bd0e7d2e
SB
185 ep = self.transaction_ep
186 addr = self.transaction_addr
fc9d619c
SB
187
188 # Handle protocol STALLs, condition lasts until next SETUP transfer (8.5.3.4)
189 if self.transaction_type == 'SETUP' and (addr, ep) in self.request:
190 request = self.request[(addr,ep)]
191 if request['type'] in ('SETUP IN', 'SETUP OUT'):
192 request['es'] = self.ss_transaction
193 self.handle_request(0, 1)
194
bd0e7d2e
SB
195 if not (addr, ep) in self.request:
196 self.request[(addr, ep)] = {'setup_data': [], 'data': [],
5b0b88ce 197 'type': None, 'ss': self.ss_transaction, 'es': None,
bd0e7d2e
SB
198 'id': self.request_id, 'addr': addr, 'ep': ep}
199 self.request_id += 1
200 request_started = 1
201 request = self.request[(addr,ep)]
202
fc9d619c 203 if request_end:
b677e536 204 request['es'] = self.es_transaction
fc9d619c
SB
205 request['handshake'] = self.handshake
206
bd0e7d2e
SB
207 # BULK or INTERRUPT transfer
208 if request['type'] in (None, 'BULK IN') and self.transaction_type == 'IN':
209 request['type'] = 'BULK IN'
210 request['data'] += self.transaction_data
bd0e7d2e
SB
211 self.handle_request(request_started, request_end)
212 elif request['type'] in (None, 'BULK OUT') and self.transaction_type == 'OUT':
213 request['type'] = 'BULK OUT'
214 request['data'] += self.transaction_data
bd0e7d2e
SB
215 self.handle_request(request_started, request_end)
216
217 # CONTROL, SETUP stage
8657abb6 218 elif request['type'] is None and self.transaction_type == 'SETUP':
bd0e7d2e
SB
219 request['setup_data'] = self.transaction_data
220 request['wLength'] = struct.unpack('<H',
221 bytes(self.transaction_data[6:8]))[0]
222 if self.transaction_data[0] & 0x80:
223 request['type'] = 'SETUP IN'
224 self.handle_request(1, 0)
225 else:
226 request['type'] = 'SETUP OUT'
227 self.handle_request(request['wLength'] == 0, 0)
228
229 # CONTROL, DATA stage
230 elif request['type'] == 'SETUP IN' and self.transaction_type == 'IN':
231 request['data'] += self.transaction_data
232
233 elif request['type'] == 'SETUP OUT' and self.transaction_type == 'OUT':
234 request['data'] += self.transaction_data
235 if request['wLength'] == len(request['data']):
236 self.handle_request(1, 0)
237
238 # CONTROL, STATUS stage
239 elif request['type'] == 'SETUP IN' and self.transaction_type == 'OUT':
bd0e7d2e
SB
240 self.handle_request(0, request_end)
241
242 elif request['type'] == 'SETUP OUT' and self.transaction_type == 'IN':
bd0e7d2e
SB
243 self.handle_request(0, request_end)
244
245 else:
246 return
247
248 return
249
250 def ts_from_samplenum(self, sample):
251 ts = float(sample) * self.secs_per_sample
252 return (int(ts), int((ts % 1.0) * 1e6))
253
254 def write_pcap_header(self):
255 if not self.wrote_pcap_header:
2f370328 256 self.put(0, 0, self.out_binary, [0, self.pcap_global_header()])
bd0e7d2e
SB
257 self.wrote_pcap_header = True
258
259 def request_summary(self, request):
260 s = '['
261 if request['type'] in ('SETUP IN', 'SETUP OUT'):
262 for b in request['setup_data']:
263 s += ' %02X' % b
264 s += ' ]['
265 for b in request['data']:
266 s += ' %02X' % b
fc9d619c 267 s += ' ] : %s' % request['handshake']
bd0e7d2e
SB
268 return s
269
270 def handle_request(self, request_start, request_end):
271 if request_start != 1 and request_end != 1:
272 return
273 self.write_pcap_header()
274 ep = self.transaction_ep
275 addr = self.transaction_addr
276 request = self.request[(addr, ep)]
277
278 ss, es = request['ss'], request['es']
279
280 if request_start == 1:
281 # Issue PCAP 'SUBMIT' packet.
282 ts = self.ts_from_samplenum(ss)
283 pkt = pcap_usb_pkt(request, ts, True)
502acfc2
UH
284 self.putb(ss, [0, pkt.record_header()])
285 self.putb(ss, [0, pkt.packet()])
bd0e7d2e
SB
286
287 if request_end == 1:
288 # Write annotation.
289 summary = self.request_summary(request)
290 if request['type'] == 'SETUP IN':
291 self.putr(ss, es, [0, ['SETUP in: %s' % summary]])
292 elif request['type'] == 'SETUP OUT':
293 self.putr(ss, es, [1, ['SETUP out: %s' % summary]])
294 elif request['type'] == 'BULK IN':
295 self.putr(ss, es, [2, ['BULK in: %s' % summary]])
296 elif request['type'] == 'BULK OUT':
297 self.putr(ss, es, [3, ['BULK out: %s' % summary]])
298
299 # Issue PCAP 'COMPLETE' packet.
300 ts = self.ts_from_samplenum(es)
301 pkt = pcap_usb_pkt(request, ts, False)
502acfc2
UH
302 self.putb(ss, [0, pkt.record_header()])
303 self.putb(ss, [0, pkt.packet()])
bd0e7d2e
SB
304 del self.request[(addr, ep)]
305
306 def decode(self, ss, es, data):
307 if not self.samplerate:
308 raise SamplerateError('Cannot decode without samplerate.')
309 ptype, pdata = data
310
311 # We only care about certain packet types for now.
312 if ptype not in ('PACKET'):
313 return
314
315 pcategory, pname, pinfo = pdata
316
317 if pcategory == 'TOKEN':
318 if pname == 'SOF':
319 return
72b2a50c 320 if self.transaction_state == 'TOKEN RECEIVED':
5b0b88ce 321 transaction_timeout = self.es_transaction
502acfc2
UH
322 # Token length is 35 bits, timeout is 16..18 bit times
323 # (USB 2.0 7.1.19.1).
5b0b88ce 324 transaction_timeout += int((self.es_transaction - self.ss_transaction) / 2)
502acfc2 325 if ss > transaction_timeout:
5b0b88ce 326 self.es_transaction = transaction_timeout
72b2a50c
SB
327 self.handshake = 'timeout'
328 self.handle_transfer()
329 self.transaction_state = 'IDLE'
330
bd0e7d2e
SB
331 if self.transaction_state != 'IDLE':
332 self.putr(ss, es, [4, ['ERR: received %s token in state %s' %
333 (pname, self.transaction_state)]])
334 return
335
336 sync, pid, addr, ep, crc5 = pinfo
337 self.transaction_data = []
5b0b88ce
UH
338 self.ss_transaction = ss
339 self.es_transaction = es
bd0e7d2e
SB
340 self.transaction_state = 'TOKEN RECEIVED'
341 self.transaction_ep = ep
342 self.transaction_addr = addr
343 self.transaction_type = pname # IN OUT SETUP
344
345 elif pcategory == 'DATA':
346 if self.transaction_state != 'TOKEN RECEIVED':
347 self.putr(ss, es, [4, ['ERR: received %s token in state %s' %
348 (pname, self.transaction_state)]])
349 return
350
351 self.transaction_data = pinfo[2]
352 self.transaction_state = 'DATA RECEIVED'
353
354 elif pcategory == 'HANDSHAKE':
355 if self.transaction_state not in ('TOKEN RECEIVED', 'DATA RECEIVED'):
356 self.putr(ss, es, [4, ['ERR: received %s token in state %s' %
357 (pname, self.transaction_state)]])
358 return
359
360 self.handshake = pname
361 self.transaction_state = 'IDLE'
5b0b88ce 362 self.es_transaction = es
bd0e7d2e
SB
363 self.handle_transfer()
364
be0f8fee
SB
365 elif pname == 'PRE':
366 return
367
bd0e7d2e
SB
368 else:
369 self.putr(ss, es, [4, ['ERR: received unhandled %s token in state %s' %
370 (pname, self.transaction_state)]])
371 return