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