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