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