]> sigrok.org Git - libsigrokdecode.git/blob - decoders/usb_request/pd.py
license: remove FSF postal address from boiler plate license text
[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, see <http://www.gnu.org/licenses/>.
18 ##
19
20 import sigrokdecode as srd
21 import struct
22
23 class SamplerateError(Exception):
24     pass
25
26 class 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
114 class Decoder(srd.Decoder):
115     api_version = 2
116     id = 'usb_request'
117     name = 'USB request'
118     longname = 'Universal Serial Bus (LS/FS) transaction/request'
119     desc = 'USB (low-speed and full-speed) transaction/request protocol.'
120     license = 'gplv2+'
121     inputs = ['usb_packet']
122     outputs = ['usb_request']
123     annotations = (
124         ('request-setup-read', 'Setup: Device-to-host'),
125         ('request-setup-write', 'Setup: Host-to-device'),
126         ('request-bulk-read', 'Bulk: Device-to-host'),
127         ('request-bulk-write', 'Bulk: Host-to-device'),
128         ('errors', 'Unexpected packets'),
129     )
130     annotation_rows = (
131         ('request', 'USB requests', tuple(range(4))),
132         ('errors', 'Errors', (4,)),
133     )
134     binary = (
135         ('pcap', 'PCAP format'),
136     )
137
138     def __init__(self):
139         self.samplerate = None
140         self.request = {}
141         self.request_id = 0
142         self.transaction_state = 'IDLE'
143         self.ss_transaction = None
144         self.es_transaction = None
145         self.transaction_ep = None
146         self.transaction_addr = None
147         self.wrote_pcap_header = False
148
149     def putr(self, ss, es, data):
150         self.put(ss, es, self.out_ann, data)
151
152     def putb(self, ts, data):
153         self.put(ts, ts, self.out_binary, data)
154
155     def pcap_global_header(self):
156         # See https://wiki.wireshark.org/Development/LibpcapFileFormat.
157         h  = b'\xa1\xb2\xc3\xd4' # Magic, indicate microsecond ts resolution
158         h += b'\x00\x02'         # Major version 2
159         h += b'\x00\x04'         # Minor version 4
160         h += b'\x00\x00\x00\x00' # Correction vs. UTC, seconds
161         h += b'\x00\x00\x00\x00' # Timestamp accuracy
162         h += b'\xff\xff\xff\xff' # Max packet len
163         # LINKTYPE_USB_LINUX_MMAPPED 220
164         # Linux usbmon format, see Documentation/usb/usbmon.txt.
165         h += b'\x00\x00\x00\xdc' # Link layer
166         return h
167
168     def metadata(self, key, value):
169         if key == srd.SRD_CONF_SAMPLERATE:
170             self.samplerate = value
171             self.secs_per_sample = float(1) / float(self.samplerate)
172
173     def start(self):
174         self.out_binary = self.register(srd.OUTPUT_BINARY)
175         self.out_ann = self.register(srd.OUTPUT_ANN)
176
177     def handle_transfer(self):
178         request_started = 0
179         request_end = self.handshake in ('ACK', 'STALL', 'timeout')
180         ep = self.transaction_ep
181         addr = self.transaction_addr
182         if not (addr, ep) in self.request:
183             self.request[(addr, ep)] = {'setup_data': [], 'data': [],
184                 'type': None, 'ss': self.ss_transaction, 'es': None,
185                 'id': self.request_id, 'addr': addr, 'ep': ep}
186             self.request_id += 1
187             request_started = 1
188         request = self.request[(addr,ep)]
189
190         # BULK or INTERRUPT transfer
191         if request['type'] in (None, 'BULK IN') and self.transaction_type == 'IN':
192             request['type'] = 'BULK IN'
193             request['data'] += self.transaction_data
194             request['es'] = self.es_transaction
195             self.handle_request(request_started, request_end)
196         elif request['type'] in (None, 'BULK OUT') and self.transaction_type == 'OUT':
197             request['type'] = 'BULK OUT'
198             request['data'] += self.transaction_data
199             request['es'] = self.es_transaction
200             self.handle_request(request_started, request_end)
201
202         # CONTROL, SETUP stage
203         elif request['type'] is None and self.transaction_type == 'SETUP':
204             request['setup_data'] = self.transaction_data
205             request['wLength'] = struct.unpack('<H',
206                 bytes(self.transaction_data[6:8]))[0]
207             if self.transaction_data[0] & 0x80:
208                 request['type'] = 'SETUP IN'
209                 self.handle_request(1, 0)
210             else:
211                 request['type'] = 'SETUP OUT'
212                 self.handle_request(request['wLength'] == 0, 0)
213
214         # CONTROL, DATA stage
215         elif request['type'] == 'SETUP IN' and self.transaction_type == 'IN':
216             request['data'] += self.transaction_data
217
218         elif request['type'] == 'SETUP OUT' and self.transaction_type == 'OUT':
219             request['data'] += self.transaction_data
220             if request['wLength'] == len(request['data']):
221                 self.handle_request(1, 0)
222
223         # CONTROL, STATUS stage
224         elif request['type'] == 'SETUP IN' and self.transaction_type == 'OUT':
225             request['es'] = self.es_transaction
226             self.handle_request(0, request_end)
227
228         elif request['type'] == 'SETUP OUT' and self.transaction_type == 'IN':
229             request['es'] = self.es_transaction
230             self.handle_request(0, request_end)
231
232         else:
233             return
234
235         return
236
237     def ts_from_samplenum(self, sample):
238         ts = float(sample) * self.secs_per_sample
239         return (int(ts), int((ts % 1.0) * 1e6))
240
241     def write_pcap_header(self):
242         if not self.wrote_pcap_header:
243             self.put(0, 0, self.out_binary, [0, self.pcap_global_header()])
244             self.wrote_pcap_header = True
245
246     def request_summary(self, request):
247         s = '['
248         if request['type'] in ('SETUP IN', 'SETUP OUT'):
249             for b in request['setup_data']:
250                 s += ' %02X' % b
251             s += ' ]['
252         for b in request['data']:
253             s += ' %02X' % b
254         s += ' ] : %s' % self.handshake
255         return s
256
257     def handle_request(self, request_start, request_end):
258         if request_start != 1 and request_end != 1:
259             return
260         self.write_pcap_header()
261         ep = self.transaction_ep
262         addr = self.transaction_addr
263         request = self.request[(addr, ep)]
264
265         ss, es = request['ss'], request['es']
266
267         if request_start == 1:
268             # Issue PCAP 'SUBMIT' packet.
269             ts = self.ts_from_samplenum(ss)
270             pkt = pcap_usb_pkt(request, ts, True)
271             self.putb(ss, [0, pkt.record_header()])
272             self.putb(ss, [0, pkt.packet()])
273
274         if request_end == 1:
275             # Write annotation.
276             summary = self.request_summary(request)
277             if request['type'] == 'SETUP IN':
278                 self.putr(ss, es, [0, ['SETUP in: %s' % summary]])
279             elif request['type'] == 'SETUP OUT':
280                 self.putr(ss, es, [1, ['SETUP out: %s' % summary]])
281             elif request['type'] == 'BULK IN':
282                 self.putr(ss, es, [2, ['BULK in: %s' % summary]])
283             elif request['type'] == 'BULK OUT':
284                 self.putr(ss, es, [3, ['BULK out: %s' % summary]])
285
286             # Issue PCAP 'COMPLETE' packet.
287             ts = self.ts_from_samplenum(es)
288             pkt = pcap_usb_pkt(request, ts, False)
289             self.putb(ss, [0, pkt.record_header()])
290             self.putb(ss, [0, pkt.packet()])
291             del self.request[(addr, ep)]
292
293     def decode(self, ss, es, data):
294         if not self.samplerate:
295             raise SamplerateError('Cannot decode without samplerate.')
296         ptype, pdata = data
297
298         # We only care about certain packet types for now.
299         if ptype not in ('PACKET'):
300             return
301
302         pcategory, pname, pinfo = pdata
303
304         if pcategory == 'TOKEN':
305             if pname == 'SOF':
306                 return
307             if self.transaction_state == 'TOKEN RECEIVED':
308                 transaction_timeout = self.es_transaction
309                 # Token length is 35 bits, timeout is 16..18 bit times
310                 # (USB 2.0 7.1.19.1).
311                 transaction_timeout += int((self.es_transaction - self.ss_transaction) / 2)
312                 if ss > transaction_timeout:
313                     self.es_transaction = transaction_timeout
314                     self.handshake = 'timeout'
315                     self.handle_transfer()
316                     self.transaction_state = 'IDLE'
317
318             if self.transaction_state != 'IDLE':
319                 self.putr(ss, es, [4, ['ERR: received %s token in state %s' %
320                     (pname, self.transaction_state)]])
321                 return
322
323             sync, pid, addr, ep, crc5 = pinfo
324             self.transaction_data = []
325             self.ss_transaction = ss
326             self.es_transaction = es
327             self.transaction_state = 'TOKEN RECEIVED'
328             self.transaction_ep = ep
329             self.transaction_addr = addr
330             self.transaction_type = pname # IN OUT SETUP
331
332         elif pcategory == 'DATA':
333             if self.transaction_state != 'TOKEN RECEIVED':
334                 self.putr(ss, es, [4, ['ERR: received %s token in state %s' %
335                     (pname, self.transaction_state)]])
336                 return
337
338             self.transaction_data = pinfo[2]
339             self.transaction_state = 'DATA RECEIVED'
340
341         elif pcategory == 'HANDSHAKE':
342             if self.transaction_state not in ('TOKEN RECEIVED', 'DATA RECEIVED'):
343                 self.putr(ss, es, [4, ['ERR: received %s token in state %s' %
344                     (pname, self.transaction_state)]])
345                 return
346
347             self.handshake = pname
348             self.transaction_state = 'IDLE'
349             self.es_transaction = es
350             self.handle_transfer()
351
352         elif pname == 'PRE':
353             return
354
355         else:
356             self.putr(ss, es, [4, ['ERR: received unhandled %s token in state %s' %
357                 (pname, self.transaction_state)]])
358             return