]> sigrok.org Git - libsigrokdecode.git/blob - decoders/sdcard_spi/pd.py
4f7c9f75b5fd9dc652a7eeebd82e4f87d688b0e1
[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, 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
23 cmd_name = {
24     # Normal commands (CMD)
25     0:  'GO_IDLE_STATE',
26     1:  'SEND_OP_COND',
27     6:  'SWITCH_FUNC',
28     8:  'SEND_IF_COND',
29     9:  'SEND_CSD',
30     10: 'SEND_CID',
31     12: 'STOP_TRANSMISSION',
32     13: 'SEND_STATUS',
33     16: 'SET_BLOCKLEN',
34     17: 'READ_SINGLE_BLOCK',
35     18: 'READ_MULTIPLE_BLOCK',
36     24: 'WRITE_BLOCK',
37     25: 'WRITE_MULTIPLE_BLOCK',
38     27: 'PROGRAM_CSD',
39     28: 'SET_WRITE_PROT',
40     29: 'CLR_WRITE_PROT',
41     30: 'SEND_WRITE_PROT',
42     32: 'ERASE_WR_BLK_START_ADDR',
43     33: 'ERASE_WR_BLK_END_ADDR',
44     38: 'ERASE',
45     42: 'LOCK_UNLOCK',
46     55: 'APP_CMD',
47     56: 'GEN_CMD',
48     58: 'READ_OCR',
49     59: 'CRC_ON_OFF',
50     # CMD60-63: Reserved for manufacturer
51
52     # Application-specific commands (ACMD)
53     13: 'SD_STATUS',
54     18: 'Reserved for SD security applications',
55     22: 'SEND_NUM_WR_BLOCKS',
56     23: 'SET_WR_BLK_ERASE_COUNT',
57     25: 'Reserved for SD security applications',
58     26: 'Reserved for SD security applications',
59     38: 'Reserved for SD security applications',
60     41: 'SD_SEND_OP_COND',
61     42: 'SET_CLR_CARD_DETECT',
62     43: 'Reserved for SD security applications',
63     44: 'Reserved for SD security applications',
64     45: 'Reserved for SD security applications',
65     46: 'Reserved for SD security applications',
66     47: 'Reserved for SD security applications',
67     48: 'Reserved for SD security applications',
68     49: 'Reserved for SD security applications',
69     51: 'SEND_SCR',
70 }
71
72 def cmd_list():
73     l = []
74     for i in range(63 + 1):
75         l.append(('cmd%d' % i, 'CMD%d' % i))
76
77     return tuple(l)
78
79 class Decoder(srd.Decoder):
80     api_version = 2
81     id = 'sdcard_spi'
82     name = 'SD card (SPI mode)'
83     longname = 'Secure Digital card (SPI mode)'
84     desc = 'Secure Digital card (SPI mode) low-level protocol.'
85     license = 'gplv2+'
86     inputs = ['spi']
87     outputs = ['sdcard_spi']
88     annotations = cmd_list() + (
89         ('cmd-desc', 'Command description'),
90         ('r1', 'R1 reply'),
91         ('r1b', 'R1B reply'),
92         ('r2', 'R2 reply'),
93         ('r3', 'R3 reply'),
94         ('r7', 'R7 reply'),
95         ('bits', 'Bits'),
96         ('bit-warnings', 'Bit warnings'),
97     )
98     annotation_rows = (
99         ('bits', 'Bits', (70, 71)),
100         ('cmd-reply', 'Commands/replies',
101             tuple(range(0, 63 + 1)) + tuple(range(65, 69 + 1))),
102         ('cmd-token', 'Command tokens', (64,)),
103     )
104
105     def __init__(self, **kwargs):
106         self.state = 'IDLE'
107         self.samplenum = 0
108         self.ss, self.es = 0, 0
109         self.bit_ss, self.bit_es = 0, 0
110         self.cmd_ss, self.cmd_es = 0, 0
111         self.cmd_token = []
112         self.cmd_token_bits = []
113         self.is_acmd = False # Indicates CMD vs. ACMD
114         self.blocklen = 0
115         self.read_buf = []
116         self.cmd_str = ''
117
118     def start(self):
119         self.out_ann = self.register(srd.OUTPUT_ANN)
120
121     def putx(self, data):
122         self.put(self.cmd_ss, self.cmd_es, self.out_ann, data)
123
124     def putc(self, cmd, desc):
125         self.putx([cmd, ['%s: %s' % (self.cmd_str, desc)]])
126
127     def putb(self, data):
128         self.put(self.bit_ss, self.bit_es, self.out_ann, data)
129
130     def handle_command_token(self, mosi, miso):
131         # Command tokens (6 bytes) are sent (MSB-first) by the host.
132         #
133         # Format:
134         #  - CMD[47:47]: Start bit (always 0)
135         #  - CMD[46:46]: Transmitter bit (1 == host)
136         #  - CMD[45:40]: Command index (BCD; valid: 0-63)
137         #  - CMD[39:08]: Argument
138         #  - CMD[07:01]: CRC7
139         #  - CMD[00:00]: End bit (always 1)
140
141         if len(self.cmd_token) == 0:
142             self.cmd_ss = self.ss
143
144         self.cmd_token.append(mosi)
145         self.cmd_token_bits.append(self.mosi_bits)
146
147         # All command tokens are 6 bytes long.
148         if len(self.cmd_token) < 6:
149             return
150
151         self.cmd_es = self.es
152
153         t = self.cmd_token
154
155         # CMD or ACMD?
156         s = 'ACMD' if self.is_acmd else 'CMD'
157
158         def tb(byte, bit):
159             return self.cmd_token_bits[5 - byte][bit]
160
161         # Bits[47:47]: Start bit (always 0)
162         bit, self.bit_ss, self.bit_es = tb(5, 7)[0], tb(5, 7)[1], tb(5, 7)[2]
163         if bit == 0:
164             self.putb([70, ['Start bit: %d' % bit]])
165         else:
166             self.putb([71, ['Start bit: %s (Warning: Must be 0!)' % bit]])
167
168         # Bits[46:46]: Transmitter bit (1 == host)
169         bit, self.bit_ss, self.bit_es = tb(5, 6)[0], tb(5, 6)[1], tb(5, 6)[2]
170         if bit == 1:
171             self.putb([70, ['Transmitter bit: %d' % bit]])
172         else:
173             self.putb([71, ['Transmitter bit: %d (Warning: Must be 1!)' % bit]])
174
175         # Bits[45:40]: Command index (BCD; valid: 0-63)
176         cmd = self.cmd_index = t[0] & 0x3f
177         self.bit_ss, self.bit_es = tb(5, 5)[1], tb(5, 0)[2]
178         self.putb([70, ['Command: %s%d (%s)' % (s, cmd, cmd_name[cmd])]])
179
180         # Bits[39:8]: Argument
181         self.arg = (t[1] << 24) | (t[2] << 16) | (t[3] << 8) | t[4]
182         self.bit_ss, self.bit_es = tb(4, 7)[1], tb(1, 0)[2]
183         self.putb([70, ['Argument: 0x%04x' % self.arg]])
184
185         # Bits[7:1]: CRC7
186         # TODO: Check CRC7.
187         crc = t[5] >> 1
188         self.bit_ss, self.bit_es = tb(0, 7)[1], tb(0, 1)[2]
189         self.putb([70, ['CRC7: 0x%01x' % crc]])
190
191         # Bits[0:0]: End bit (always 1)
192         bit, self.bit_ss, self.bit_es = tb(0, 0)[0], tb(0, 0)[1], tb(0, 0)[2]
193         self.putb([70, ['End bit: %d' % bit]])
194         if bit == 1:
195             self.putb([70, ['End bit: %d' % bit]])
196         else:
197             self.putb([71, ['End bit: %d (Warning: Must be 1!)' % bit]])
198
199         # Handle command.
200         if cmd in (0, 1, 9, 16, 17, 41, 49, 55, 59):
201             self.state = 'HANDLE CMD%d' % cmd
202             self.cmd_str = '%s%d (%s)' % (s, cmd, cmd_name[cmd])
203         else:
204             self.state = 'HANDLE CMD999'
205             a = '%s%d: %02x %02x %02x %02x %02x %02x' % ((s, cmd) + tuple(t))
206             self.putx([cmd, [a]])
207
208         # ...
209         if self.is_acmd and cmd != 55:
210             self.is_acmd = False
211
212     def handle_cmd0(self):
213         # CMD0: GO_IDLE_STATE
214         self.putc(0, 'Reset the SD card')
215         self.state = 'GET RESPONSE R1'
216
217     def handle_cmd1(self):
218         # CMD1: SEND_OP_COND
219         self.putc(1, 'Send HCS info and activate the card init process')
220         hcs = (self.arg & (1 << 30)) >> 30
221         self.bit_ss = self.cmd_token_bits[5 - 4][6][1]
222         self.bit_es = self.cmd_token_bits[5 - 4][6][2]
223         self.putb([70, ['HCS: %d' % hcs]])
224         self.state = 'GET RESPONSE R1'
225
226     def handle_cmd9(self):
227         # CMD9: SEND_CSD (128 bits / 16 bytes)
228         self.putc(9, 'Ask card to send its card specific data (CSD)')
229         if len(self.read_buf) == 0:
230             self.cmd_ss = self.ss
231         self.read_buf.append(self.miso)
232         # FIXME
233         ### if len(self.read_buf) < 16:
234         if len(self.read_buf) < 16 + 4:
235             return
236         self.cmd_es = self.es
237         self.read_buf = self.read_buf[4:] ### TODO: Document or redo.
238         self.putx([9, ['CSD: %s' % self.read_buf]])
239         # TODO: Decode all bits.
240         self.read_buf = []
241         ### self.state = 'GET RESPONSE R1'
242         self.state = 'IDLE'
243
244     def handle_cmd10(self):
245         # CMD10: SEND_CID (128 bits / 16 bytes)
246         self.putc(10, 'Ask card to send its card identification (CID)')
247         self.read_buf.append(self.miso)
248         if len(self.read_buf) < 16:
249             return
250         self.putx([10, ['CID: %s' % self.read_buf]])
251         # TODO: Decode all bits.
252         self.read_buf = []
253         self.state = 'GET RESPONSE R1'
254
255     def handle_cmd16(self):
256         # CMD16: SET_BLOCKLEN
257         self.blocklen = self.arg
258         # TODO: Sanity check on block length.
259         self.putc(16, 'Set the block length to %d bytes' % self.blocklen)
260         self.state = 'GET RESPONSE R1'
261
262     def handle_cmd17(self):
263         # CMD17: READ_SINGLE_BLOCK
264         self.putc(17, 'Read a block from address 0x%04x' % self.arg)
265         if len(self.read_buf) == 0:
266             self.cmd_ss = self.ss
267         self.read_buf.append(self.miso)
268         if len(self.read_buf) < self.blocklen + 2: # FIXME
269             return
270         self.cmd_es = self.es
271         self.read_buf = self.read_buf[2:] # FIXME
272         self.putx([17, ['Block data: %s' % self.read_buf]])
273         self.read_buf = []
274         self.state = 'GET RESPONSE R1'
275
276     def handle_cmd41(self):
277         # ACMD41: SD_SEND_OP_COND
278         self.putc(41, 'Send HCS info and activate the card init process')
279         self.state = 'GET RESPONSE R1'
280
281     def handle_cmd49(self):
282         self.state = 'GET RESPONSE R1'
283
284     def handle_cmd55(self):
285         # CMD55: APP_CMD
286         self.putc(55, 'Next command is an application-specific command')
287         self.is_acmd = True
288         self.state = 'GET RESPONSE R1'
289
290     def handle_cmd59(self):
291         # CMD59: CRC_ON_OFF
292         crc_on_off = self.arg & (1 << 0)
293         s = 'on' if crc_on_off == 1 else 'off'
294         self.putc(59, 'Turn the SD card CRC option %s' % s)
295         self.state = 'GET RESPONSE R1'
296
297     def handle_cmd999(self):
298         self.state = 'GET RESPONSE R1'
299
300     def handle_cid_register(self):
301         # Card Identification (CID) register, 128bits
302
303         cid = self.cid
304
305         # Manufacturer ID: CID[127:120] (8 bits)
306         mid = cid[15]
307
308         # OEM/Application ID: CID[119:104] (16 bits)
309         oid = (cid[14] << 8) | cid[13]
310
311         # Product name: CID[103:64] (40 bits)
312         pnm = 0
313         for i in range(12, 8 - 1, -1):
314             pnm <<= 8
315             pnm |= cid[i]
316
317         # Product revision: CID[63:56] (8 bits)
318         prv = cid[7]
319
320         # Product serial number: CID[55:24] (32 bits)
321         psn = 0
322         for i in range(6, 3 - 1, -1):
323             psn <<= 8
324             psn |= cid[i]
325
326         # RESERVED: CID[23:20] (4 bits)
327
328         # Manufacturing date: CID[19:8] (12 bits)
329         # TODO
330
331         # CRC7 checksum: CID[7:1] (7 bits)
332         # TODO
333
334         # Not used, always 1: CID[0:0] (1 bit)
335         # TODO
336
337     def handle_response_r1(self, res):
338         # The R1 response token format (1 byte).
339         # Sent by the card after every command except for SEND_STATUS.
340
341         self.cmd_ss, self.cmd_es = self.miso_bits[7][1], self.miso_bits[0][2]
342         self.putx([65, ['R1: 0x%02x' % res]])
343
344         def putbit(bit, data):
345             b = self.miso_bits[bit]
346             self.bit_ss, self.bit_es = b[1], b[2]
347             self.putb([70, data])
348
349         # Bit 0: 'In idle state' bit
350         s = '' if (res & (1 << 0)) else 'not '
351         putbit(0, ['Card is %sin idle state' % s])
352
353         # Bit 1: 'Erase reset' bit
354         s = '' if (res & (1 << 1)) else 'not '
355         putbit(1, ['Erase sequence %scleared' % s])
356
357         # Bit 2: 'Illegal command' bit
358         s = 'I' if (res & (1 << 2)) else 'No i'
359         putbit(2, ['%sllegal command detected' % s])
360
361         # Bit 3: 'Communication CRC error' bit
362         s = 'failed' if (res & (1 << 3)) else 'was successful'
363         putbit(3, ['CRC check of last command %s' % s])
364
365         # Bit 4: 'Erase sequence error' bit
366         s = 'E' if (res & (1 << 4)) else 'No e'
367         putbit(4, ['%srror in the sequence of erase commands' % s])
368
369         # Bit 5: 'Address error' bit
370         s = 'M' if (res & (1 << 4)) else 'No m'
371         putbit(5, ['%sisaligned address used in command' % s])
372
373         # Bit 6: 'Parameter error' bit
374         s = '' if (res & (1 << 4)) else 'not '
375         putbit(6, ['Command argument %soutside allowed range' % s])
376
377         # Bit 7: Always set to 0
378         putbit(7, ['Bit 7 (always 0)'])
379
380         self.state = 'IDLE'
381
382     def handle_response_r1b(self, res):
383         # TODO
384         pass
385
386     def handle_response_r2(self, res):
387         # TODO
388         pass
389
390     def handle_response_r3(self, res):
391         # TODO
392         pass
393
394     # Note: Response token formats R4 and R5 are reserved for SDIO.
395
396     # TODO: R6?
397
398     def handle_response_r7(self, res):
399         # TODO
400         pass
401
402     def decode(self, ss, es, data):
403         ptype, mosi, miso = data
404
405         # For now, only use DATA and BITS packets.
406         if ptype not in ('DATA', 'BITS'):
407             return
408
409         # Store the individual bit values and ss/es numbers. The next packet
410         # is guaranteed to be a 'DATA' packet belonging to this 'BITS' one.
411         if ptype == 'BITS':
412             self.miso_bits, self.mosi_bits = miso, mosi
413             return
414
415         self.ss, self.es = ss, es
416
417         # State machine.
418         if self.state == 'IDLE':
419             # Ignore stray 0xff bytes, some devices seem to send those!?
420             if mosi == 0xff: # TODO?
421                 return
422             self.state = 'GET COMMAND TOKEN'
423             self.handle_command_token(mosi, miso)
424         elif self.state == 'GET COMMAND TOKEN':
425             self.handle_command_token(mosi, miso)
426         elif self.state.startswith('HANDLE CMD'):
427             self.miso, self.mosi = miso, mosi
428             # Call the respective handler method for the command.
429             s = 'handle_cmd%s' % self.state[10:].lower()
430             handle_cmd = getattr(self, s)
431             handle_cmd()
432             self.cmd_token = []
433             self.cmd_token_bits = []
434         elif self.state.startswith('GET RESPONSE'):
435             # Ignore stray 0xff bytes, some devices seem to send those!?
436             if miso == 0xff: # TODO?
437                 return
438
439             # Call the respective handler method for the response.
440             s = 'handle_response_%s' % self.state[13:].lower()
441             handle_response = getattr(self, s)
442             handle_response(miso)
443
444             self.state = 'IDLE'
445         else:
446             raise Exception('Invalid state: %s' % self.state)
447