]> sigrok.org Git - libsigrokdecode.git/blob - decoders/sdcard_spi/pd.py
3ffa1e5774d0528736450cde7919258ee6ed8bde
[libsigrokdecode.git] / decoders / sdcard_spi / pd.py
1 ##
2 ## This file is part of the libsigrokdecode project.
3 ##
4 ## Copyright (C) 2012 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 # SD card (SPI mode) low-level protocol decoder
22
23 import sigrokdecode as srd
24
25 cmd_name = {
26     # Normal commands (CMD)
27     0:  'GO_IDLE_STATE',
28     1:  'SEND_OP_COND',
29     6:  'SWITCH_FUNC',
30     8:  'SEND_IF_COND',
31     9:  'SEND_CSD',
32     10: 'SEND_CID',
33     12: 'STOP_TRANSMISSION',
34     13: 'SEND_STATUS',
35     16: 'SET_BLOCKLEN',
36     17: 'READ_SINGLE_BLOCK',
37     18: 'READ_MULTIPLE_BLOCK',
38     24: 'WRITE_BLOCK',
39     25: 'WRITE_MULTIPLE_BLOCK',
40     27: 'PROGRAM_CSD',
41     28: 'SET_WRITE_PROT',
42     29: 'CLR_WRITE_PROT',
43     30: 'SEND_WRITE_PROT',
44     32: 'ERASE_WR_BLK_START_ADDR',
45     33: 'ERASE_WR_BLK_END_ADDR',
46     38: 'ERASE',
47     42: 'LOCK_UNLOCK',
48     55: 'APP_CMD',
49     56: 'GEN_CMD',
50     58: 'READ_OCR',
51     59: 'CRC_ON_OFF',
52     # CMD60-63: Reserved for manufacturer
53
54     # Application-specific commands (ACMD)
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 = 1
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     probes = []
84     optional_probes = []
85     options = {}
86     annotations = [
87         ['Text', 'Human-readable text'],
88         ['Warnings', 'Human-readable warnings'],
89     ]
90
91     def __init__(self, **kwargs):
92         self.state = 'IDLE'
93         self.samplenum = 0
94         self.cmd_ss, self.cmd_es = 0, 0
95         self.cmd_token = []
96         self.is_acmd = False # Indicates CMD vs. ACMD
97         self.blocklen = 0
98         self.read_buf = []
99
100     def start(self):
101         # self.out_proto = self.register(srd.OUTPUT_PYTHON)
102         self.out_ann = self.register(srd.OUTPUT_ANN)
103
104     def putx(self, data):
105         self.put(self.cmd_ss, self.cmd_es, self.out_ann, data)
106
107     def handle_command_token(self, mosi, miso):
108         # Command tokens (6 bytes) are sent (MSB-first) by the host.
109         #
110         # Format:
111         #  - CMD[47:47]: Start bit (always 0)
112         #  - CMD[46:46]: Transmitter bit (1 == host)
113         #  - CMD[45:40]: Command index (BCD; valid: 0-63)
114         #  - CMD[39:08]: Argument
115         #  - CMD[07:01]: CRC7
116         #  - CMD[00:00]: End bit (always 1)
117
118         self.cmd_token.append(mosi)
119         # TODO: Record MISO too?
120
121         # All command tokens are 6 bytes long.
122         if len(self.cmd_token) < 6:
123             return
124
125         # Received all 6 bytes of the command token. Now decode it.
126
127         t = self.cmd_token
128
129         # CMD or ACMD?
130         s = 'ACMD' if self.is_acmd else 'CMD'
131         # TODO
132         self.put(0, 0, self.out_ann,
133                  [0, [s + ': %02x %02x %02x %02x %02x %02x' % tuple(t)]])
134
135         # Start bit
136         self.startbit = (t[0] & (1 << 7)) >> 7
137         self.put(0, 0, self.out_ann,
138                  [0, ['Start bit: %d' % self.startbit]])
139         if self.startbit != 0:
140             # TODO
141             self.put(0, 0, self.out_ann, [1, ['Warning: Start bit != 0']])
142
143         # Transmitter bit
144         self.transmitterbit = (t[0] & (1 << 6)) >> 6
145         self.put(0, 0, self.out_ann,
146                  [0, ['Transmitter bit: %d' % self.transmitterbit]])
147         if self.transmitterbit != 0:
148             # TODO
149             self.put(0, 0, self.out_ann, [1, ['Warning: Transmitter bit != 1']])
150
151         # Command index
152         cmd = self.cmd_index = t[0] & 0x3f
153         # TODO
154         self.put(0, 0, self.out_ann,
155                  [0, ['Command: %s%d (%s)' % (s, cmd, cmd_name[cmd])]])
156
157         # Argument
158         self.arg = (t[1] << 24) | (t[2] << 16) | (t[3] << 8) | t[4]
159         self.put(0, 0, self.out_ann, [0, ['Argument: 0x%04x' % self.arg]])
160         # TODO: Sanity check on argument? Must be per-cmd?
161
162         # CRC
163         # TODO: Check CRC.
164         self.crc = t[5] >> 1
165         self.put(0, 0, self.out_ann, [0, ['CRC: 0x%01x' % self.crc]])
166
167         # End bit
168         self.endbit = t[5] & (1 << 0)
169         self.put(0, 0, self.out_ann, [0, ['End bit: %d' % self.endbit]])
170         if self.endbit != 1:
171             # TODO
172             self.put(0, 0, self.out_ann, [1, ['Warning: End bit != 1']])
173
174         # Handle command.
175         if cmd in (0, 1, 9, 16, 17, 41, 49, 55, 59):
176             self.state = 'HANDLE CMD%d' % cmd
177
178         # ...
179         if self.is_acmd and cmd != 55:
180             self.is_acmd = False
181
182         self.cmd_token = []
183
184     def handle_cmd0(self, ):
185         # CMD0: GO_IDLE_STATE
186         # TODO
187         self.put(0, 0, self.out_ann, [0, ['CMD0: Card reset / idle state']])
188         self.state = 'GET RESPONSE R1'
189
190     def handle_cmd1(self):
191         # CMD1: SEND_OP_COND
192         # TODO
193         hcs = (self.arg & (1 << 30)) >> 30
194         self.put(0, 0, self.out_ann, [0, ['HCS bit = %d' % hcs]])
195         self.state = 'GET RESPONSE R1'
196
197     def handle_cmd9(self):
198         # CMD9: SEND_CSD (128 bits / 16 bytes)
199         self.read_buf.append(self.miso)
200         # FIXME
201         ### if len(self.read_buf) < 16:
202         if len(self.read_buf) < 16 + 4:
203             return
204         self.read_buf = self.read_buf[4:] ### TODO: Document or redo.
205         self.put(0, 0, self.out_ann, [0, ['CSD: %s' % self.read_buf]])
206         # TODO: Decode all bits.
207         self.read_buf = []
208         ### self.state = 'GET RESPONSE R1'
209         self.state = 'IDLE'
210
211     def handle_cmd10(self):
212         # CMD10: SEND_CID (128 bits / 16 bytes)
213         self.read_buf.append(self.miso)
214         if len(self.read_buf) < 16:
215             return
216         self.put(0, 0, self.out_ann, [0, ['CID: %s' % self.read_buf]])
217         # TODO: Decode all bits.
218         self.read_buf = []
219         self.state = 'GET RESPONSE R1'
220
221     def handle_cmd16(self):
222         # CMD16: SET_BLOCKLEN
223         self.blocklen = self.arg # TODO
224         # TODO: Sanity check on block length.
225         self.put(0, 0, self.out_ann, [0, ['Block length: %d' % self.blocklen]])
226         self.state = 'GET RESPONSE R1'
227
228     def handle_cmd17(self):
229         # CMD17: READ_SINGLE_BLOCK
230         self.read_buf.append(self.miso)
231         if len(self.read_buf) == 1:
232             self.put(0, 0, self.out_ann,
233                      [0, ['Read block at address: 0x%04x' % self.arg]])
234         if len(self.read_buf) < self.blocklen + 2: # FIXME
235             return
236         self.read_buf = self.read_buf[2:] # FIXME
237         self.put(0, 0, self.out_ann, [0, ['Block data: %s' % self.read_buf]])
238         self.read_buf = []
239         self.state = 'GET RESPONSE R1'
240
241     def handle_cmd41(self):
242         # ACMD41: SD_SEND_OP_COND
243         self.state = 'GET RESPONSE R1'
244
245     def handle_cmd49(self):
246         self.state = 'GET RESPONSE R1'
247
248     def handle_cmd55(self):
249         # CMD55: APP_CMD
250         self.is_acmd = True
251         self.state = 'GET RESPONSE R1'
252
253     def handle_cmd59(self):
254         # CMD59: CRC_ON_OFF
255         crc_on_off = self.arg & (1 << 0)
256         s = 'on' if crc_on_off == 1 else 'off'
257         self.put(0, 0, self.out_ann, [0, ['SD card CRC option: %s' % s]])
258         self.state = 'GET RESPONSE R1'
259
260     def handle_cid_register(self):
261         # Card Identification (CID) register, 128bits
262
263         cid = self.cid
264
265         # Manufacturer ID: CID[127:120] (8 bits)
266         mid = cid[15]
267
268         # OEM/Application ID: CID[119:104] (16 bits)
269         oid = (cid[14] << 8) | cid[13]
270
271         # Product name: CID[103:64] (40 bits)
272         pnm = 0
273         for i in range(12, 8 - 1, -1):
274             pnm <<= 8
275             pnm |= cid[i]
276
277         # Product revision: CID[63:56] (8 bits)
278         prv = cid[7]
279
280         # Product serial number: CID[55:24] (32 bits)
281         psn = 0
282         for i in range(6, 3 - 1, -1):
283             psn <<= 8
284             psn |= cid[i]
285
286         # RESERVED: CID[23:20] (4 bits)
287
288         # Manufacturing date: CID[19:8] (12 bits)
289         # TODO
290
291         # CRC7 checksum: CID[7:1] (7 bits)
292         # TODO
293
294         # Not used, always 1: CID[0:0] (1 bit)
295         # TODO
296
297     def handle_response_r1(self, res):
298         # The R1 response token format (1 byte).
299         # Sent by the card after every command except for SEND_STATUS.
300
301         self.put(0, 0, self.out_ann, [0, ['R1: 0x%02x' % res]])
302
303         # TODO: Configurable whether all bits are decoded.
304
305         # 'In idle state' bit
306         s = '' if (res & (1 << 0)) else 'not '
307         self.put(0, 0, self.out_ann, [0, ['Card is %sin idle state' % s]])
308
309         # 'Erase reset' bit
310         s = '' if (res & (1 << 1)) else 'not '
311         self.put(0, 0, self.out_ann, [0, ['Erase sequence %scleared' % s]])
312
313         # 'Illegal command' bit
314         s = 'I' if (res & (1 << 2)) else 'No i'
315         self.put(0, 0, self.out_ann, [0, ['%sllegal command detected' % s]])
316
317         # 'Communication CRC error' bit
318         s = 'failed' if (res & (1 << 3)) else 'was successful'
319         self.put(0, 0, self.out_ann,
320                  [0, ['CRC check of last command %s' % s]])
321
322         # 'Erase sequence error' bit
323         s = 'E' if (res & (1 << 4)) else 'No e'
324         self.put(0, 0, self.out_ann,
325                  [0, ['%srror in the sequence of erase commands' % s]])
326
327         # 'Address error' bit
328         s = 'M' if (res & (1 << 4)) else 'No m'
329         self.put(0, 0, self.out_ann,
330                  [0, ['%sisaligned address used in command' % s]])
331
332         # 'Parameter error' bit
333         s = '' if (res & (1 << 4)) else 'not '
334         self.put(0, 0, self.out_ann,
335                  [0, ['Command argument %soutside allowed range' % s]])
336
337         self.state = 'IDLE'
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 decode(self, ss, es, data):
360         ptype, mosi, miso = data
361
362         # For now, ignore non-data packets.
363         if ptype != 'DATA':
364             return
365
366         self.put(0, 0, self.out_ann, [0, ['0x%02x 0x%02x' % (mosi, miso)]])
367
368         # State machine.
369         if self.state == 'IDLE':
370             # Ignore stray 0xff bytes, some devices seem to send those!?
371             if mosi == 0xff: # TODO?
372                 return
373             self.state = 'GET COMMAND TOKEN'
374             self.handle_command_token(mosi, miso)
375         elif self.state == 'GET COMMAND TOKEN':
376             self.handle_command_token(mosi, miso)
377         elif self.state.startswith('HANDLE CMD'):
378             self.miso, self.mosi = miso, mosi
379             # Call the respective handler method for the command.
380             s = 'handle_cmd%s' % self.state[10:].lower()
381             handle_cmd = getattr(self, s)
382             handle_cmd()
383         elif self.state.startswith('GET RESPONSE'):
384             # Ignore stray 0xff bytes, some devices seem to send those!?
385             if miso == 0xff: # TODO?
386                 return
387
388             # Call the respective handler method for the response.
389             s = 'handle_response_%s' % self.state[13:].lower()
390             # self.put(0, 0, self.out_ann, [0, [s]]) # TODO
391             handle_response = getattr(self, s)
392             handle_response(miso)
393
394             self.state = 'IDLE'
395         else:
396             raise Exception('Invalid state: %s' % self.state)
397