]> sigrok.org Git - libsigrokdecode.git/blob - decoders/spiflash/pd.py
spiflash: Major refactoring and annotation improvements.
[libsigrokdecode.git] / decoders / spiflash / pd.py
1 ##
2 ## This file is part of the libsigrokdecode project.
3 ##
4 ## Copyright (C) 2011-2016 Uwe Hermann <uwe@hermann-uwe.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 from .lists import *
23
24 L = len(cmds)
25
26 # Don't forget to keep this in sync with 'cmds' is lists.py.
27 class Ann:
28     WRSR, PP, READ, WRDI, RDSR, WREN, FAST_READ, SE, RDSCUR, WRSCUR, \
29     RDSR2, CE, ESRY, DSRY, REMS, RDID, RDP_RES, CP, ENSO, DP, READ2X, \
30     EXSO, CE2, BE, REMS2, \
31     BIT, FIELD, WARN = range(L + 3)
32
33 def cmd_annotation_classes():
34     return tuple([tuple([cmd[0].lower(), cmd[1]]) for cmd in cmds.values()])
35
36 def decode_dual_bytes(sio0, sio1):
37     # Given a byte in SIO0 (MOSI) of even bits and a byte in
38     # SIO1 (MISO) of odd bits, return a tuple of two bytes.
39     def combine_byte(even, odd):
40         result = 0
41         for bit in range(4):
42             if even & (1 << bit):
43                 result |= 1 << (bit*2)
44             if odd & (1 << bit):
45                 result |= 1 << ((bit*2) + 1)
46         return result
47     return (combine_byte(sio0 >> 4, sio1 >> 4), combine_byte(sio0, sio1))
48
49 def decode_status_reg(data):
50     # TODO: Additional per-bit(s) self.put() calls with correct start/end.
51
52     # Bits[0:0]: WIP (write in progress)
53     s = 'W' if (data & (1 << 0)) else 'No w'
54     ret = '%srite operation in progress.\n' % s
55
56     # Bits[1:1]: WEL (write enable latch)
57     s = '' if (data & (1 << 1)) else 'not '
58     ret += 'Internal write enable latch is %sset.\n' % s
59
60     # Bits[5:2]: Block protect bits
61     # TODO: More detailed decoding (chip-dependent).
62     ret += 'Block protection bits (BP3-BP0): 0x%x.\n' % ((data & 0x3c) >> 2)
63
64     # Bits[6:6]: Continuously program mode (CP mode)
65     s = '' if (data & (1 << 6)) else 'not '
66     ret += 'Device is %sin continuously program mode (CP mode).\n' % s
67
68     # Bits[7:7]: SRWD (status register write disable)
69     s = 'not ' if (data & (1 << 7)) else ''
70     ret += 'Status register writes are %sallowed.\n' % s
71
72     return ret
73
74 class Decoder(srd.Decoder):
75     api_version = 2
76     id = 'spiflash'
77     name = 'SPI flash'
78     longname = 'SPI flash chips'
79     desc = 'xx25 series SPI (NOR) flash chip protocol.'
80     license = 'gplv2+'
81     inputs = ['spi']
82     outputs = ['spiflash']
83     annotations = cmd_annotation_classes() + (
84         ('bit', 'Bit'),
85         ('field', 'Field'),
86         ('warning', 'Warning'),
87     )
88     annotation_rows = (
89         ('bits', 'Bits', (L + 0,)),
90         ('fields', 'Fields', (L + 1,)),
91         ('commands', 'Commands', tuple(range(len(cmds)))),
92         ('warnings', 'Warnings', (L + 2,)),
93     )
94     options = (
95         {'id': 'chip', 'desc': 'Chip', 'default': tuple(chips.keys())[0],
96             'values': tuple(chips.keys())},
97         {'id': 'format', 'desc': 'Data format', 'default': 'hex',
98             'values': ('hex', 'ascii')},
99     )
100
101     def __init__(self):
102         self.device_id = -1
103         self.on_end_transaction = None
104         self.end_current_transaction()
105
106         # Build dict mapping command keys to handler functions. Each
107         # command in 'cmds' (defined in lists.py) has a matching
108         # handler self.handle_<shortname>.
109         def get_handler(cmd):
110             s = 'handle_%s' % cmds[cmd][0].lower().replace('/', '_')
111             return getattr(self, s)
112         self.cmd_handlers = dict((cmd, get_handler(cmd)) for cmd in cmds.keys())
113
114     def end_current_transaction(self):
115         if self.on_end_transaction is not None: # Callback for CS# transition.
116             self.on_end_transaction()
117             self.on_end_transaction = None
118         self.state = None
119         self.cmdstate = 1
120         self.addr = 0
121         self.data = []
122
123     def start(self):
124         self.out_ann = self.register(srd.OUTPUT_ANN)
125         self.chip = chips[self.options['chip']]
126         self.vendor = self.options['chip'].split('_')[0]
127
128     def putx(self, data):
129         # Simplification, most annotations span exactly one SPI byte/packet.
130         self.put(self.ss, self.es, self.out_ann, data)
131
132     def putf(self, data):
133         self.put(self.ss_field, self.es_field, self.out_ann, data)
134
135     def putc(self, data):
136         self.put(self.ss_cmd, self.es_cmd, self.out_ann, data)
137
138     def device(self):
139         return device_name[self.vendor].get(self.device_id, 'Unknown')
140
141     def vendor_device(self):
142         return '%s %s' % (self.chip['vendor'], self.device())
143
144     def cmd_ann_list(self):
145         x, s = cmds[self.state][0], cmds[self.state][1]
146         return ['Command: %s (%s)' % (s, x), 'Command: %s' % s,
147                 'Cmd: %s' % s, 'Cmd: %s' % x, x]
148
149     def cmd_vendor_dev_list(self):
150         c, d = cmds[self.state], 'Device = %s' % self.vendor_device()
151         return ['%s (%s): %s' % (c[1], c[0], d), '%s: %s' % (c[1], d),
152                 '%s: %s' % (c[0], d), d, self.vendor_device()]
153
154     def emit_cmd_byte(self):
155         self.ss_cmd = self.ss
156         self.putx([Ann.FIELD, self.cmd_ann_list()])
157         self.addr = 0
158
159     def emit_addr_bytes(self, mosi):
160         self.addr |= (mosi << ((4 - self.cmdstate) * 8))
161         b = ((3 - (self.cmdstate - 2)) * 8) - 1
162         self.putx([Ann.BIT,
163             ['Address bits %d..%d: 0x%02x' % (b, b - 7, mosi),
164              'Addr bits %d..%d: 0x%02x' % (b, b - 7, mosi),
165              'Addr bits %d..%d' % (b, b - 7), 'A%d..A%d' % (b, b - 7)]])
166         if self.cmdstate == 2:
167             self.ss_field = self.ss
168         if self.cmdstate == 4:
169             self.es_field = self.es
170             self.putf([Ann.FIELD, ['Address: 0x%06x' % self.addr,
171                 'Addr: 0x%06x' % self.addr, '0x%06x' % self.addr]])
172
173     def handle_wren(self, mosi, miso):
174         self.putx([Ann.WREN, self.cmd_ann_list()])
175         self.state = None
176
177     def handle_wrdi(self, mosi, miso):
178         pass # TODO
179
180     def handle_rdid(self, mosi, miso):
181         if self.cmdstate == 1:
182             # Byte 1: Master sends command ID.
183             self.emit_cmd_byte()
184         elif self.cmdstate == 2:
185             # Byte 2: Slave sends the JEDEC manufacturer ID.
186             self.putx([Ann.FIELD, ['Manufacturer ID: 0x%02x' % miso]])
187         elif self.cmdstate == 3:
188             # Byte 3: Slave sends the memory type.
189             self.putx([Ann.FIELD, ['Memory type: 0x%02x' % miso]])
190         elif self.cmdstate == 4:
191             # Byte 4: Slave sends the device ID.
192             self.device_id = miso
193             self.putx([Ann.FIELD, ['Device ID: 0x%02x' % miso]])
194
195         if self.cmdstate == 4:
196             self.es_cmd = self.es
197             self.putc([Ann.RDID, self.cmd_vendor_dev_list()])
198             self.state = None
199         else:
200             self.cmdstate += 1
201
202     def handle_rdsr(self, mosi, miso):
203         # Read status register: Master asserts CS#, sends RDSR command,
204         # reads status register byte. If CS# is kept asserted, the status
205         # register can be read continuously / multiple times in a row.
206         # When done, the master de-asserts CS# again.
207         if self.cmdstate == 1:
208             # Byte 1: Master sends command ID.
209             self.emit_cmd_byte()
210         elif self.cmdstate >= 2:
211             # Bytes 2-x: Slave sends status register as long as master clocks.
212             self.es_cmd = self.es
213             self.putx([Ann.BIT, [decode_status_reg(miso)]])
214             self.putx([Ann.FIELD, ['Status register']])
215             self.putc([Ann.RDSR, self.cmd_ann_list()])
216         self.cmdstate += 1
217
218     def handle_rdsr2(self, mosi, miso):
219         # Read status register 2: Master asserts CS#, sends RDSR2 command,
220         # reads status register 2 byte. If CS# is kept asserted, the status
221         # register 2 can be read continuously / multiple times in a row.
222         # When done, the master de-asserts CS# again.
223         if self.cmdstate == 1:
224             # Byte 1: Master sends command ID.
225             self.emit_cmd_byte()
226         elif self.cmdstate >= 2:
227             # Bytes 2-x: Slave sends status register 2 as long as master clocks.
228             self.es_cmd = self.es
229             # TODO: Decode status register 2 correctly.
230             self.putx([Ann.BIT, [decode_status_reg(miso)]])
231             self.putx([Ann.FIELD, ['Status register 2']])
232             self.putc([Ann.RDSR2, self.cmd_ann_list()])
233         self.cmdstate += 1
234
235     def handle_wrsr(self, mosi, miso):
236         # Write status register: Master asserts CS#, sends WRSR command,
237         # writes 1 or 2 status register byte(s).
238         # When done, the master de-asserts CS# again. If this doesn't happen
239         # the WRSR command will not be executed.
240         if self.cmdstate == 1:
241             # Byte 1: Master sends command ID.
242             self.emit_cmd_byte()
243         elif self.cmdstate == 2:
244             # Byte 2: Master sends status register 1.
245             self.putx([Ann.BIT, [decode_status_reg(miso)]])
246             self.putx([Ann.FIELD, ['Status register 1']])
247         elif self.cmdstate == 3:
248             # Byte 3: Master sends status register 2.
249             # TODO: Decode status register 2 correctly.
250             self.putx([Ann.BIT, [decode_status_reg(miso)]])
251             self.putx([Ann.FIELD, ['Status register 2']])
252             self.es_cmd = self.es
253             self.putc([Ann.WRSR, self.cmd_ann_list()])
254         self.cmdstate += 1
255
256     def handle_read(self, mosi, miso):
257         # Read data bytes: Master asserts CS#, sends READ command, sends
258         # 3-byte address, reads >= 1 data bytes, de-asserts CS#.
259         if self.cmdstate == 1:
260             # Byte 1: Master sends command ID.
261             self.emit_cmd_byte()
262         elif self.cmdstate in (2, 3, 4):
263             # Bytes 2/3/4: Master sends read address (24bits, MSB-first).
264             self.emit_addr_bytes(mosi)
265         elif self.cmdstate >= 5:
266             # Bytes 5-x: Master reads data bytes (until CS# de-asserted).
267             self.es_field = self.es # Will be overwritten for each byte.
268             if self.cmdstate == 5:
269                 self.ss_field = self.ss
270                 self.on_end_transaction = lambda: self.output_data_block('Data', Ann.READ)
271             self.data.append(miso)
272         self.cmdstate += 1
273
274     def handle_fast_read(self, mosi, miso):
275         # Fast read: Master asserts CS#, sends FAST READ command, sends
276         # 3-byte address + 1 dummy byte, reads >= 1 data bytes, de-asserts CS#.
277         if self.cmdstate == 1:
278             # Byte 1: Master sends command ID.
279             self.emit_cmd_byte()
280         elif self.cmdstate in (2, 3, 4):
281             # Bytes 2/3/4: Master sends read address (24bits, MSB-first).
282             self.emit_addr_bytes(mosi)
283         elif self.cmdstate == 5:
284             self.putx([Ann.BIT, ['Dummy byte: 0x%02x' % mosi]])
285         elif self.cmdstate >= 6:
286             # Bytes 6-x: Master reads data bytes (until CS# de-asserted).
287             self.es_field = self.es # Will be overwritten for each byte.
288             if self.cmdstate == 6:
289                 self.ss_field = self.ss
290                 self.on_end_transaction = lambda: self.output_data_block('Data', Ann.FAST_READ)
291             self.data.append(miso)
292         self.cmdstate += 1
293
294     def handle_2read(self, mosi, miso):
295         # 2x I/O read (fast read dual I/O): Master asserts CS#, sends 2READ
296         # command, sends 3-byte address + 1 dummy byte, reads >= 1 data bytes,
297         # de-asserts CS#. All data after the command is sent via two I/O pins.
298         # MOSI = SIO0 = even bits, MISO = SIO1 = odd bits.
299         if self.cmdstate != 1:
300             b1, b2 = decode_dual_bytes(mosi, miso)
301         if self.cmdstate == 1:
302             # Byte 1: Master sends command ID.
303             self.emit_cmd_byte()
304         elif self.cmdstate == 2:
305             # Bytes 2/3(/4): Master sends read address (24bits, MSB-first).
306             # Handle bytes 2 and 3 here.
307             self.emit_addr_bytes(b1)
308             self.cmdstate = 3
309             self.emit_addr_bytes(b2)
310         elif self.cmdstate == 4:
311             # Byte 5: Dummy byte. Also handle byte 4 (address LSB) here.
312             self.emit_addr_bytes(b1)
313             self.cmdstate = 5
314             self.putx([Ann.BIT, ['Dummy byte: 0x%02x' % b2]])
315         elif self.cmdstate >= 6:
316             # Bytes 6-x: Master reads data bytes (until CS# de-asserted).
317             self.es_field = self.es # Will be overwritten for each byte.
318             if self.cmdstate == 6:
319                 self.ss_field = self.ss
320                 self.on_end_transaction = lambda: self.output_data_block('Data', Ann.READ2X)
321             self.data.append(b1)
322             self.data.append(b2)
323         self.cmdstate += 1
324
325     # TODO: Warn/abort if we don't see the necessary amount of bytes.
326     # TODO: Warn if WREN was not seen before.
327     def handle_se(self, mosi, miso):
328         if self.cmdstate == 1:
329             # Byte 1: Master sends command ID.
330             self.emit_cmd_byte()
331         elif self.cmdstate in (2, 3, 4):
332             # Bytes 2/3/4: Master sends sector address (24bits, MSB-first).
333             self.emit_addr_bytes(mosi)
334
335         if self.cmdstate == 4:
336             self.es_cmd = self.es
337             d = 'Erase sector %d (0x%06x)' % (self.addr, self.addr)
338             self.putc([Ann.SE, [d]])
339             # TODO: Max. size depends on chip, check that too if possible.
340             if self.addr % 4096 != 0:
341                 # Sector addresses must be 4K-aligned (same for all 3 chips).
342                 self.putc([Ann.WARN, ['Warning: Invalid sector address!']])
343             self.state = None
344         else:
345             self.cmdstate += 1
346
347     def handle_be(self, mosi, miso):
348         pass # TODO
349
350     def handle_ce(self, mosi, miso):
351         pass # TODO
352
353     def handle_ce2(self, mosi, miso):
354         pass # TODO
355
356     def handle_pp(self, mosi, miso):
357         # Page program: Master asserts CS#, sends PP command, sends 3-byte
358         # page address, sends >= 1 data bytes, de-asserts CS#.
359         if self.cmdstate == 1:
360             # Byte 1: Master sends command ID.
361             self.emit_cmd_byte()
362         elif self.cmdstate in (2, 3, 4):
363             # Bytes 2/3/4: Master sends page address (24bits, MSB-first).
364             self.emit_addr_bytes(mosi)
365         elif self.cmdstate >= 5:
366             # Bytes 5-x: Master sends data bytes (until CS# de-asserted).
367             self.es_field = self.es # Will be overwritten for each byte.
368             if self.cmdstate == 5:
369                 self.ss_field = self.ss
370                 self.on_end_transaction = lambda: self.output_data_block('Data', Ann.PP)
371             self.data.append(mosi)
372         self.cmdstate += 1
373
374     def handle_cp(self, mosi, miso):
375         pass # TODO
376
377     def handle_dp(self, mosi, miso):
378         pass # TODO
379
380     def handle_rdp_res(self, mosi, miso):
381         if self.cmdstate == 1:
382             # Byte 1: Master sends command ID.
383             self.emit_cmd_byte()
384         elif self.cmdstate in (2, 3, 4):
385             # Bytes 2/3/4: Master sends three dummy bytes.
386             self.putx([Ann.FIELD, ['Dummy byte: %02x' % mosi]])
387         elif self.cmdstate == 5:
388             # Byte 5: Slave sends device ID.
389             self.es_cmd = self.es
390             self.device_id = miso
391             self.putx([Ann.FIELD, ['Device ID: %s' % self.device()]])
392             d = 'Device = %s' % self.vendor_device()
393             self.putc([Ann.RDP_RES, self.cmd_vendor_dev_list()])
394             self.state = None
395         self.cmdstate += 1
396
397     def handle_rems(self, mosi, miso):
398         if self.cmdstate == 1:
399             # Byte 1: Master sends command ID.
400             self.emit_cmd_byte()
401         elif self.cmdstate in (2, 3):
402             # Bytes 2/3: Master sends two dummy bytes.
403             self.putx([Ann.FIELD, ['Dummy byte: 0x%02x' % mosi]])
404         elif self.cmdstate == 4:
405             # Byte 4: Master sends 0x00 or 0x01.
406             # 0x00: Master wants manufacturer ID as first reply byte.
407             # 0x01: Master wants device ID as first reply byte.
408             self.manufacturer_id_first = True if (mosi == 0x00) else False
409             d = 'manufacturer' if (mosi == 0x00) else 'device'
410             self.putx([Ann.FIELD, ['Master wants %s ID first' % d]])
411         elif self.cmdstate == 5:
412             # Byte 5: Slave sends manufacturer ID (or device ID).
413             self.ids = [miso]
414             d = 'Manufacturer' if self.manufacturer_id_first else 'Device'
415             self.putx([Ann.FIELD, ['%s ID: 0x%02x' % (d, miso)]])
416         elif self.cmdstate == 6:
417             # Byte 6: Slave sends device ID (or manufacturer ID).
418             self.ids.append(miso)
419             d = 'Device' if self.manufacturer_id_first else 'Manufacturer'
420             self.putx([Ann.FIELD, ['%s ID: 0x%02x' % (d, miso)]])
421
422         if self.cmdstate == 6:
423             id = self.ids[1] if self.manufacturer_id_first else self.ids[0]
424             self.device_id = id
425             self.es_cmd = self.es
426             self.putc([Ann.REMS, self.cmd_vendor_dev_list()])
427             self.state = None
428         else:
429             self.cmdstate += 1
430
431     def handle_rems2(self, mosi, miso):
432         pass # TODO
433
434     def handle_enso(self, mosi, miso):
435         pass # TODO
436
437     def handle_exso(self, mosi, miso):
438         pass # TODO
439
440     def handle_rdscur(self, mosi, miso):
441         pass # TODO
442
443     def handle_wrscur(self, mosi, miso):
444         pass # TODO
445
446     def handle_esry(self, mosi, miso):
447         pass # TODO
448
449     def handle_dsry(self, mosi, miso):
450         pass # TODO
451
452     def output_data_block(self, label, idx):
453         # Print accumulated block of data
454         # (called on CS# de-assert via self.on_end_transaction callback).
455         self.es_cmd = self.es # End on the CS# de-assert sample.
456         if self.options['format'] == 'hex':
457             s = ' '.join([('%02x' % b) for b in self.data])
458         else:
459             s = ''.join(map(chr, self.data))
460         self.putf([Ann.FIELD, ['%s (%d bytes)' % (label, len(self.data))]])
461         self.putc([idx, ['%s (addr 0x%06x, %d bytes): %s' % \
462                    (cmds[self.state][1], self.addr, len(self.data), s)]])
463
464     def decode(self, ss, es, data):
465         ptype, mosi, miso = data
466
467         self.ss, self.es = ss, es
468
469         if ptype == 'CS-CHANGE':
470             self.end_current_transaction()
471
472         if ptype != 'DATA':
473             return
474
475         # If we encountered a known chip command, enter the resp. state.
476         if self.state is None:
477             self.state = mosi
478             self.cmdstate = 1
479
480         # Handle commands.
481         try:
482             self.cmd_handlers[self.state](mosi, miso)
483         except KeyError:
484             self.putx([Ann.BIT, ['Unknown command: 0x%02x' % mosi]])
485             self.state = None