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