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