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