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