]> sigrok.org Git - libsigrokdecode.git/blob - decoders/sdcard_spi/pd.py
sdcard_spi: Add "Card is busy" annotations for CMD24.
[libsigrokdecode.git] / decoders / sdcard_spi / pd.py
1 ##
2 ## This file is part of the libsigrokdecode project.
3 ##
4 ## Copyright (C) 2012-2014 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 common.sdcard import (cmd_names, acmd_names)
22
23 class Decoder(srd.Decoder):
24     api_version = 3
25     id = 'sdcard_spi'
26     name = 'SD card (SPI mode)'
27     longname = 'Secure Digital card (SPI mode)'
28     desc = 'Secure Digital card (SPI mode) low-level protocol.'
29     license = 'gplv2+'
30     inputs = ['spi']
31     outputs = []
32     tags = ['Memory']
33     annotations = \
34         tuple(('cmd%d' % i, 'CMD%d' % i) for i in range(64)) + \
35         tuple(('acmd%d' % i, 'ACMD%d' % i) for i in range(64)) + ( \
36         ('r1', 'R1 reply'),
37         ('r1b', 'R1B reply'),
38         ('r2', 'R2 reply'),
39         ('r3', 'R3 reply'),
40         ('r7', 'R7 reply'),
41         ('bits', 'Bits'),
42         ('bit-warnings', 'Bit warnings'),
43     )
44     annotation_rows = (
45         ('bits', 'Bits', (133, 134)),
46         ('cmd-reply', 'Commands/replies', tuple(range(133))),
47     )
48
49     def __init__(self):
50         self.reset()
51
52     def reset(self):
53         self.state = 'IDLE'
54         self.ss, self.es = 0, 0
55         self.ss_bit, self.es_bit = 0, 0
56         self.ss_cmd, self.es_cmd = 0, 0
57         self.ss_busy, self.es_busy = 0, 0
58         self.cmd_token = []
59         self.cmd_token_bits = []
60         self.is_acmd = False # Indicates CMD vs. ACMD
61         self.blocklen = 0
62         self.read_buf = []
63         self.cmd_str = ''
64         self.is_cmd24 = False
65         self.cmd24_start_token_found = False
66         self.is_cmd17 = False
67         self.cmd17_start_token_found = False
68         self.busy_first_byte = False
69
70     def start(self):
71         self.out_ann = self.register(srd.OUTPUT_ANN)
72
73     def putx(self, data):
74         self.put(self.ss_cmd, self.es_cmd, self.out_ann, data)
75
76     def putc(self, cmd, desc):
77         self.putx([cmd, ['%s: %s' % (self.cmd_str, desc)]])
78
79     def putb(self, data):
80         self.put(self.ss_bit, self.es_bit, self.out_ann, data)
81
82     def cmd_name(self, cmd):
83         c = acmd_names if self.is_acmd else cmd_names
84         s = c.get(cmd, 'Unknown')
85         # SD mode names for CMD32/33: ERASE_WR_BLK_{START,END}.
86         # SPI mode names for CMD32/33: ERASE_WR_BLK_{START,END}_ADDR.
87         if cmd in (32, 33):
88             s += '_ADDR'
89         return s
90
91     def handle_command_token(self, mosi, miso):
92         # Command tokens (6 bytes) are sent (MSB-first) by the host.
93         #
94         # Format:
95         #  - CMD[47:47]: Start bit (always 0)
96         #  - CMD[46:46]: Transmitter bit (1 == host)
97         #  - CMD[45:40]: Command index (BCD; valid: 0-63)
98         #  - CMD[39:08]: Argument
99         #  - CMD[07:01]: CRC7
100         #  - CMD[00:00]: End bit (always 1)
101
102         if len(self.cmd_token) == 0:
103             self.ss_cmd = self.ss
104
105         self.cmd_token.append(mosi)
106         self.cmd_token_bits.append(self.mosi_bits)
107
108         # All command tokens are 6 bytes long.
109         if len(self.cmd_token) < 6:
110             return
111
112         self.es_cmd = self.es
113
114         t = self.cmd_token
115
116         # CMD or ACMD?
117         s = 'ACMD' if self.is_acmd else 'CMD'
118
119         def tb(byte, bit):
120             return self.cmd_token_bits[5 - byte][bit]
121
122         # Bits[47:47]: Start bit (always 0)
123         bit, self.ss_bit, self.es_bit = tb(5, 7)[0], tb(5, 7)[1], tb(5, 7)[2]
124         if bit == 0:
125             self.putb([134, ['Start bit: %d' % bit]])
126         else:
127             self.putb([135, ['Start bit: %s (Warning: Must be 0!)' % bit]])
128
129         # Bits[46:46]: Transmitter bit (1 == host)
130         bit, self.ss_bit, self.es_bit = tb(5, 6)[0], tb(5, 6)[1], tb(5, 6)[2]
131         if bit == 1:
132             self.putb([134, ['Transmitter bit: %d' % bit]])
133         else:
134             self.putb([135, ['Transmitter bit: %d (Warning: Must be 1!)' % bit]])
135
136         # Bits[45:40]: Command index (BCD; valid: 0-63)
137         cmd = self.cmd_index = t[0] & 0x3f
138         self.ss_bit, self.es_bit = tb(5, 5)[1], tb(5, 0)[2]
139         self.putb([134, ['Command: %s%d (%s)' % (s, cmd, self.cmd_name(cmd))]])
140
141         # Bits[39:8]: Argument
142         self.arg = (t[1] << 24) | (t[2] << 16) | (t[3] << 8) | t[4]
143         self.ss_bit, self.es_bit = tb(4, 7)[1], tb(1, 0)[2]
144         self.putb([134, ['Argument: 0x%04x' % self.arg]])
145
146         # Bits[7:1]: CRC7
147         # TODO: Check CRC7.
148         crc = t[5] >> 1
149         self.ss_bit, self.es_bit = tb(0, 7)[1], tb(0, 1)[2]
150         self.putb([134, ['CRC7: 0x%01x' % crc]])
151
152         # Bits[0:0]: End bit (always 1)
153         bit, self.ss_bit, self.es_bit = tb(0, 0)[0], tb(0, 0)[1], tb(0, 0)[2]
154         if bit == 1:
155             self.putb([134, ['End bit: %d' % bit]])
156         else:
157             self.putb([135, ['End bit: %d (Warning: Must be 1!)' % bit]])
158
159         # Handle command.
160         if cmd in (0, 1, 9, 16, 17, 24, 41, 49, 55, 59):
161             self.state = 'HANDLE CMD%d' % cmd
162             self.cmd_str = '%s%d (%s)' % (s, cmd, self.cmd_name(cmd))
163         else:
164             self.state = 'HANDLE CMD999'
165             a = '%s%d: %02x %02x %02x %02x %02x %02x' % ((s, cmd) + tuple(t))
166             self.putx([cmd, [a]])
167
168     def handle_cmd0(self):
169         # CMD0: GO_IDLE_STATE
170         self.putc(0, 'Reset the SD card')
171         self.state = 'GET RESPONSE R1'
172
173     def handle_cmd1(self):
174         # CMD1: SEND_OP_COND
175         self.putc(1, 'Send HCS info and activate the card init process')
176         hcs = (self.arg & (1 << 30)) >> 30
177         self.ss_bit = self.cmd_token_bits[5 - 4][6][1]
178         self.es_bit = self.cmd_token_bits[5 - 4][6][2]
179         self.putb([134, ['HCS: %d' % hcs]])
180         self.state = 'GET RESPONSE R1'
181
182     def handle_cmd9(self):
183         # CMD9: SEND_CSD (128 bits / 16 bytes)
184         self.putc(9, 'Ask card to send its card specific data (CSD)')
185         if len(self.read_buf) == 0:
186             self.ss_cmd = self.ss
187         self.read_buf.append(self.miso)
188         # FIXME
189         ### if len(self.read_buf) < 16:
190         if len(self.read_buf) < 16 + 4:
191             return
192         self.es_cmd = self.es
193         self.read_buf = self.read_buf[4:] # TODO: Document or redo.
194         self.putx([9, ['CSD: %s' % self.read_buf]])
195         # TODO: Decode all bits.
196         self.read_buf = []
197         ### self.state = 'GET RESPONSE R1'
198         self.state = 'IDLE'
199
200     def handle_cmd10(self):
201         # CMD10: SEND_CID (128 bits / 16 bytes)
202         self.putc(10, 'Ask card to send its card identification (CID)')
203         self.read_buf.append(self.miso)
204         if len(self.read_buf) < 16:
205             return
206         self.putx([10, ['CID: %s' % self.read_buf]])
207         # TODO: Decode all bits.
208         self.read_buf = []
209         self.state = 'GET RESPONSE R1'
210
211     def handle_cmd16(self):
212         # CMD16: SET_BLOCKLEN
213         self.blocklen = self.arg
214         # TODO: Sanity check on block length.
215         self.putc(16, 'Set the block length to %d bytes' % self.blocklen)
216         self.state = 'GET RESPONSE R1'
217
218     def handle_cmd17(self):
219         # CMD17: READ_SINGLE_BLOCK
220         self.putc(17, 'Read a block from address 0x%04x' % self.arg)
221         self.is_cmd17 = True
222         self.state = 'GET RESPONSE R1'
223
224     def handle_cmd24(self):
225         # CMD24: WRITE_BLOCK
226         self.putc(24, 'Write a block to address 0x%04x' % self.arg)
227         self.is_cmd24 = True
228         self.state = 'GET RESPONSE R1'
229
230     def handle_cmd49(self):
231         self.state = 'GET RESPONSE R1'
232
233     def handle_cmd55(self):
234         # CMD55: APP_CMD
235         self.putc(55, 'Next command is an application-specific command')
236         self.is_acmd = True
237         self.state = 'GET RESPONSE R1'
238
239     def handle_cmd59(self):
240         # CMD59: CRC_ON_OFF
241         crc_on_off = self.arg & (1 << 0)
242         s = 'on' if crc_on_off == 1 else 'off'
243         self.putc(59, 'Turn the SD card CRC option %s' % s)
244         self.state = 'GET RESPONSE R1'
245
246     def handle_acmd41(self):
247         # ACMD41: SD_SEND_OP_COND
248         self.putc(64 + 41, 'Send HCS info and activate the card init process')
249         self.state = 'GET RESPONSE R1'
250
251     def handle_cmd999(self):
252         self.state = 'GET RESPONSE R1'
253
254     def handle_cid_register(self):
255         # Card Identification (CID) register, 128bits
256
257         cid = self.cid
258
259         # Manufacturer ID: CID[127:120] (8 bits)
260         mid = cid[15]
261
262         # OEM/Application ID: CID[119:104] (16 bits)
263         oid = (cid[14] << 8) | cid[13]
264
265         # Product name: CID[103:64] (40 bits)
266         pnm = 0
267         for i in range(12, 8 - 1, -1):
268             pnm <<= 8
269             pnm |= cid[i]
270
271         # Product revision: CID[63:56] (8 bits)
272         prv = cid[7]
273
274         # Product serial number: CID[55:24] (32 bits)
275         psn = 0
276         for i in range(6, 3 - 1, -1):
277             psn <<= 8
278             psn |= cid[i]
279
280         # RESERVED: CID[23:20] (4 bits)
281
282         # Manufacturing date: CID[19:8] (12 bits)
283         # TODO
284
285         # CRC7 checksum: CID[7:1] (7 bits)
286         # TODO
287
288         # Not used, always 1: CID[0:0] (1 bit)
289         # TODO
290
291     def handle_response_r1(self, res):
292         # The R1 response token format (1 byte).
293         # Sent by the card after every command except for SEND_STATUS.
294
295         self.ss_cmd, self.es_cmd = self.miso_bits[7][1], self.miso_bits[0][2]
296         self.putx([65, ['R1: 0x%02x' % res]])
297
298         def putbit(bit, data):
299             b = self.miso_bits[bit]
300             self.ss_bit, self.es_bit = b[1], b[2]
301             self.putb([134, data])
302
303         # Bit 0: 'In idle state' bit
304         s = '' if (res & (1 << 0)) else 'not '
305         putbit(0, ['Card is %sin idle state' % s])
306
307         # Bit 1: 'Erase reset' bit
308         s = '' if (res & (1 << 1)) else 'not '
309         putbit(1, ['Erase sequence %scleared' % s])
310
311         # Bit 2: 'Illegal command' bit
312         s = 'I' if (res & (1 << 2)) else 'No i'
313         putbit(2, ['%sllegal command detected' % s])
314
315         # Bit 3: 'Communication CRC error' bit
316         s = 'failed' if (res & (1 << 3)) else 'was successful'
317         putbit(3, ['CRC check of last command %s' % s])
318
319         # Bit 4: 'Erase sequence error' bit
320         s = 'E' if (res & (1 << 4)) else 'No e'
321         putbit(4, ['%srror in the sequence of erase commands' % s])
322
323         # Bit 5: 'Address error' bit
324         s = 'M' if (res & (1 << 4)) else 'No m'
325         putbit(5, ['%sisaligned address used in command' % s])
326
327         # Bit 6: 'Parameter error' bit
328         s = '' if (res & (1 << 4)) else 'not '
329         putbit(6, ['Command argument %soutside allowed range' % s])
330
331         # Bit 7: Always set to 0
332         putbit(7, ['Bit 7 (always 0)'])
333
334         if self.is_cmd17:
335             self.state = 'HANDLE DATA BLOCK CMD17'
336         if self.is_cmd24:
337             self.state = 'HANDLE DATA BLOCK CMD24'
338
339     def handle_response_r1b(self, res):
340         # TODO
341         pass
342
343     def handle_response_r2(self, res):
344         # TODO
345         pass
346
347     def handle_response_r3(self, res):
348         # TODO
349         pass
350
351     # Note: Response token formats R4 and R5 are reserved for SDIO.
352
353     # TODO: R6?
354
355     def handle_response_r7(self, res):
356         # TODO
357         pass
358
359     def handle_data_cmd17(self, miso):
360         # CMD17 returns one byte R1, then some bytes 0xff, then a Start Block
361         # (single byte 0xfe), then self.blocklen bytes of data, then always
362         # 2 bytes of CRC.
363         if self.cmd17_start_token_found:
364             if len(self.read_buf) == 0:
365                 self.ss_data = self.ss
366                 if not self.blocklen:
367                     # Assume a fixed block size when inspection of the previous
368                     # traffic did not provide the respective parameter value.
369                     # TODO: Make the default block size a PD option?
370                     self.blocklen = 512
371             self.read_buf.append(miso)
372             # Wait until block transfer completed.
373             if len(self.read_buf) < self.blocklen:
374                 return
375             if len(self.read_buf) == self.blocklen:
376                 self.es_data = self.es
377                 self.put(self.ss_data, self.es_data, self.out_ann, [17, ['Block data: %s' % self.read_buf]])
378             elif len(self.read_buf) == (self.blocklen + 1):
379                 self.ss_crc = self.ss
380             elif len(self.read_buf) == (self.blocklen + 2):
381                 self.es_crc = self.es
382                 # TODO: Check CRC.
383                 self.put(self.ss_crc, self.es_crc, self.out_ann, [17, ['CRC']])
384                 self.state = 'IDLE'
385         elif miso == 0xfe:
386             self.put(self.ss, self.es, self.out_ann, [17, ['Start Block']])
387             self.cmd17_start_token_found = True
388
389     def handle_data_cmd24(self, mosi):
390         if self.cmd24_start_token_found:
391             if len(self.read_buf) == 0:
392                 self.ss_data = self.ss
393                 if not self.blocklen:
394                     # Assume a fixed block size when inspection of the
395                     # previous traffic did not provide the respective
396                     # parameter value.
397                     # TODO Make the default block size a user adjustable option?
398                     self.blocklen = 512
399             self.read_buf.append(mosi)
400             # Wait until block transfer completed.
401             if len(self.read_buf) < self.blocklen:
402                 return
403             self.es_data = self.es
404             self.put(self.ss_data, self.es_data, self.out_ann, [24, ['Block data: %s' % self.read_buf]])
405             self.read_buf = []
406             self.state = 'DATA RESPONSE'
407         elif mosi == 0xfe:
408             self.put(self.ss, self.es, self.out_ann, [24, ['Start Block']])
409             self.cmd24_start_token_found = True
410
411     def handle_data_response(self, miso):
412         # Data Response token (1 byte).
413         #
414         # Format:
415         #  - Bits[7:5]: Don't care.
416         #  - Bits[4:4]: Always 0.
417         #  - Bits[3:1]: Status.
418         #    - 010: Data accepted.
419         #    - 101: Data rejected due to a CRC error.
420         #    - 110: Data rejected due to a write error.
421         #  - Bits[0:0]: Always 1.
422         miso &= 0x1f
423         if miso & 0x11 != 0x01:
424             # This is not the byte we are waiting for.
425             # Should we return to IDLE here?
426             return
427         m = self.miso_bits
428         self.put(m[7][1], m[5][2], self.out_ann, [134, ['Don\'t care']])
429         self.put(m[4][1], m[4][2], self.out_ann, [134, ['Always 0']])
430         if miso == 0x05:
431             self.put(m[3][1], m[1][2], self.out_ann, [134, ['Data accepted']])
432         elif miso == 0x0b:
433             self.put(m[3][1], m[1][2], self.out_ann, [134, ['Data rejected (CRC error)']])
434         elif miso == 0x0d:
435             self.put(m[3][1], m[1][2], self.out_ann, [134, ['Data rejected (write error)']])
436         self.put(m[0][1], m[0][2], self.out_ann, [134, ['Always 1']])
437         ann_class = None
438         if self.is_cmd24:
439             ann_class = 24
440         if ann_class is not None:
441             self.put(self.ss, self.es, self.out_ann, [ann_class, ['Data Response']])
442         if self.is_cmd24:
443             # We just send a block of data to be written to the card,
444             # this takes some time.
445             self.state = 'WAIT WHILE CARD BUSY'
446             self.busy_first_byte = True
447         else:
448             self.state = 'IDLE'
449
450     def wait_while_busy(self, miso):
451         if miso != 0x00:
452             ann_class = None
453             if self.is_cmd24:
454                 ann_class = 24
455             if ann_class is not None:
456                 self.put(self.ss_busy, self.es_busy, self.out_ann, [24, ['Card is busy']])
457             self.state = 'IDLE'
458             return
459         else:
460             if self.busy_first_byte:
461                 self.ss_busy = self.ss
462                 self.busy_first_byte = False
463             else:
464                 self.es_busy = self.es
465
466     def decode(self, ss, es, data):
467         ptype, mosi, miso = data
468
469         # For now, only use DATA and BITS packets.
470         if ptype not in ('DATA', 'BITS'):
471             return
472
473         # Store the individual bit values and ss/es numbers. The next packet
474         # is guaranteed to be a 'DATA' packet belonging to this 'BITS' one.
475         if ptype == 'BITS':
476             self.miso_bits, self.mosi_bits = miso, mosi
477             return
478
479         self.ss, self.es = ss, es
480
481         # State machine.
482         if self.state == 'IDLE':
483             # Ignore stray 0xff bytes, some devices seem to send those!?
484             if mosi == 0xff: # TODO?
485                 return
486             self.state = 'GET COMMAND TOKEN'
487             self.handle_command_token(mosi, miso)
488         elif self.state == 'GET COMMAND TOKEN':
489             self.handle_command_token(mosi, miso)
490         elif self.state.startswith('HANDLE CMD'):
491             self.miso, self.mosi = miso, mosi
492             # Call the respective handler method for the command.
493             a, cmdstr = 'a' if self.is_acmd else '', self.state[10:].lower()
494             handle_cmd = getattr(self, 'handle_%scmd%s' % (a, cmdstr))
495             handle_cmd()
496             self.cmd_token = []
497             self.cmd_token_bits = []
498             # Leave ACMD mode again after the first command after CMD55.
499             if self.is_acmd and cmdstr != '55':
500                 self.is_acmd = False
501         elif self.state.startswith('GET RESPONSE'):
502             # Ignore stray 0xff bytes, some devices seem to send those!?
503             if miso == 0xff: # TODO?
504                 return
505             # Call the respective handler method for the response.
506             # Assume return to IDLE state, but allow response handlers
507             # to advance to some other state when applicable.
508             s = 'handle_response_%s' % self.state[13:].lower()
509             handle_response = getattr(self, s)
510             self.state = 'IDLE'
511             handle_response(miso)
512         elif self.state == 'HANDLE DATA BLOCK CMD17':
513             self.handle_data_cmd17(miso)
514         elif self.state == 'HANDLE DATA BLOCK CMD24':
515             self.handle_data_cmd24(mosi)
516         elif self.state == 'DATA RESPONSE':
517             self.handle_data_response(miso)
518         elif self.state == 'WAIT WHILE CARD BUSY':
519             self.wait_while_busy(miso)