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