]> sigrok.org Git - libsigrokdecode.git/blob - decoders/sdcard_sd/pd.py
sdcard_sd: Add basic support for CSD register fields.
[libsigrokdecode.git] / decoders / sdcard_sd / pd.py
1 ##
2 ## This file is part of the libsigrokdecode project.
3 ##
4 ## Copyright (C) 2015-2020 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, see <http://www.gnu.org/licenses/>.
18 ##
19
20 import sigrokdecode as srd
21 from common.srdhelper import SrdIntEnum, SrdStrEnum
22 from common.sdcard import (cmd_names, acmd_names, accepted_voltages, card_status, sd_status)
23
24 responses = '1 1b 2 3 6 7'.split()
25 reg_cid = 'MID OID PNM PRV PSN RSVD MDT CRC ONE'.split()
26 reg_csd = 'CSD_STRUCTURE RSVD TAAC NSAC TRAN_SPEED CCC READ_BL_LEN \
27     READ_BL_PARTIAL WRITE_BLK_MISALIGN READ_BLK_MISALIGN DSR_IMP C_SIZE \
28     VDD_R_CURR_MIN VDD_R_CURR_MAX VDD_W_CURR_MIN VDD_W_CURR_MAX C_SIZE_MULT \
29     ERASE_BLK_EN SECTOR_SIZE WP_GRP_SIZE WP_GRP_ENABLE R2W_FACTOR \
30     WRITE_BL_LEN WRITE_BL_PARTIAL FILE_FORMAT_GRP COPY PERM_WRITE_PROTECT \
31     TMP_WRITE_PROTECT FILE_FORMAT CRC ONE'.split()
32
33 Pin = SrdIntEnum.from_str('Pin', 'CMD CLK DAT0 DAT1 DAT2 DAT3')
34
35 a = ['CMD%d' % i for i in range(64)] + ['ACMD%d' % i for i in range(64)] + \
36     ['RESPONSE_R' + r.upper() for r in responses] + \
37     ['R_CID_' + r for r in reg_cid] + \
38     ['R_CSD_' + r for r in reg_csd] + \
39     ['F_' + f for f in 'START TRANSM CMD ARG CRC END'.split()] + \
40     ['BIT', 'DECODED_BIT', 'DECODED_F']
41 Ann = SrdIntEnum.from_list('Ann', a)
42
43 s = ['GET_COMMAND_TOKEN', 'HANDLE_CMD999'] + \
44     ['HANDLE_CMD%d' % i for i in range(64)] + \
45     ['HANDLE_ACMD%d' % i for i in range(64)] + \
46     ['GET_RESPONSE_R%s' % r.upper() for r in responses]
47 St = SrdStrEnum.from_list('St', s)
48
49 class Bit:
50     def __init__(self, s, e, b):
51         self.ss, self.es, self.bit = s, e ,b
52
53 class Decoder(srd.Decoder):
54     api_version = 3
55     id = 'sdcard_sd'
56     name = 'SD card (SD mode)'
57     longname = 'Secure Digital card (SD mode)'
58     desc = 'Secure Digital card (SD mode) low-level protocol.'
59     license = 'gplv2+'
60     inputs = ['logic']
61     outputs = []
62     tags = ['Memory']
63     channels = (
64         {'id': 'cmd',  'name': 'CMD',  'desc': 'Command'},
65         {'id': 'clk',  'name': 'CLK',  'desc': 'Clock'},
66     )
67     optional_channels = (
68         {'id': 'dat0', 'name': 'DAT0', 'desc': 'Data pin 0'},
69         {'id': 'dat1', 'name': 'DAT1', 'desc': 'Data pin 1'},
70         {'id': 'dat2', 'name': 'DAT2', 'desc': 'Data pin 2'},
71         {'id': 'dat3', 'name': 'DAT3', 'desc': 'Data pin 3'},
72     )
73     annotations = \
74         tuple(('cmd%d' % i, 'CMD%d' % i) for i in range(64)) + \
75         tuple(('acmd%d' % i, 'ACMD%d' % i) for i in range(64)) + \
76         tuple(('response_r%s' % r, 'R%s' % r) for r in responses) + \
77         tuple(('reg_cid_' + r.lower(), 'CID: ' + r) for r in reg_cid) + \
78         tuple(('reg_csd_' + r.lower(), 'CSD: ' + r) for r in reg_csd) + \
79     ( \
80         ('field-start', 'Start bit'),
81         ('field-transmission', 'Transmission bit'),
82         ('field-cmd', 'Command'),
83         ('field-arg', 'Argument'),
84         ('field-crc', 'CRC'),
85         ('field-end', 'End bit'),
86         ('bit', 'Bit'),
87         ('decoded-bit', 'Decoded bit'),
88         ('decoded-field', 'Decoded field'),
89     )
90     annotation_rows = (
91         ('raw-bits', 'Raw bits', (Ann.BIT,)),
92         ('decoded-bits', 'Decoded bits', (Ann.DECODED_BIT,) + Ann.prefixes('R_')),
93         ('decoded-fields', 'Decoded fields', (Ann.DECODED_F,)),
94         ('fields', 'Fields', Ann.prefixes('F_')),
95         ('commands', 'Commands', Ann.prefixes('CMD ACMD RESPONSE_')),
96     )
97
98     def __init__(self):
99         self.reset()
100
101     def reset(self):
102         self.state = St.GET_COMMAND_TOKEN
103         self.token = []
104         self.is_acmd = False # Indicates CMD vs. ACMD
105         self.cmd = None
106         self.last_cmd = None
107         self.arg = None
108
109     def start(self):
110         self.out_ann = self.register(srd.OUTPUT_ANN)
111
112     def putbit(self, b, data):
113         self.put(self.token[b].ss, self.token[b].es, self.out_ann,
114             [Ann.DECODED_BIT, data])
115
116     def putt(self, data):
117         self.put(self.token[0].ss, self.token[47].es, self.out_ann, data)
118
119     def putf(self, s, e, data):
120         self.put(self.token[s].ss, self.token[e].es, self.out_ann, data)
121
122     def puta(self, s, e, data):
123         self.put(self.token[47 - 8 - e].ss, self.token[47 - 8 - s].es,
124                  self.out_ann, data)
125
126     def putc(self, desc):
127         cmd = Ann.ACMD0 + self.cmd if self.is_acmd else self.cmd
128         self.last_cmd = cmd
129         self.putt([cmd, ['%s: %s' % (self.cmd_str, desc), self.cmd_str,
130                          self.cmd_str.split(' ')[0]]])
131
132     def putr(self, r):
133         self.putt([r, ['Response: %s' % r.name.split('_')[1]]])
134
135     def cmd_name(self, cmd):
136         c = acmd_names if self.is_acmd else cmd_names
137         return c.get(cmd, 'Unknown')
138
139     def get_token_bits(self, cmd_pin, n):
140         # Get a bit, return True if we already got 'n' bits, False otherwise.
141         self.token.append(Bit(self.samplenum, self.samplenum, cmd_pin))
142         if len(self.token) > 0:
143             self.token[len(self.token) - 2].es = self.samplenum
144         if len(self.token) < n:
145             return False
146         self.token[n - 1].es += self.token[n - 1].ss - self.token[n - 2].ss
147         return True
148
149     def handle_common_token_fields(self):
150         s = self.token
151
152         # Annotations for each individual bit.
153         for bit in range(len(self.token)):
154             self.putf(bit, bit, [Ann.BIT, ['%d' % s[bit].bit]])
155
156         # CMD[47:47]: Start bit (always 0)
157         self.putf(0, 0, [Ann.F_START, ['Start bit', 'Start', 'S']])
158
159         # CMD[46:46]: Transmission bit (1 == host)
160         t = 'host' if s[1].bit == 1 else 'card'
161         self.putf(1, 1, [Ann.F_TRANSM, ['Transmission: ' + t, 'T: ' + t, 'T']])
162
163         # CMD[45:40]: Command index (BCD; valid: 0-63)
164         self.cmd = int('0b' + ''.join([str(s[i].bit) for i in range(2, 8)]), 2)
165         c = '%s (%d)' % (self.cmd_name(self.cmd), self.cmd)
166         self.putf(2, 7, [Ann.F_CMD, ['Command: ' + c, 'Cmd: ' + c,
167                                'CMD%d' % self.cmd, 'Cmd', 'C']])
168
169         # CMD[39:08]: Argument
170         self.arg = int('0b' + ''.join([str(s[i].bit) for i in range(8, 40)]), 2)
171         self.putf(8, 39, [Ann.F_ARG, ['Argument: 0x%08x' % self.arg, 'Arg', 'A']])
172
173         # CMD[07:01]: CRC7
174         self.crc = int('0b' + ''.join([str(s[i].bit) for i in range(40, 47)]), 2)
175         self.putf(40, 46, [Ann.F_CRC, ['CRC: 0x%x' % self.crc, 'CRC', 'C']])
176
177         # CMD[00:00]: End bit (always 1)
178         self.putf(47, 47, [Ann.F_END, ['End bit', 'End', 'E']])
179
180     def get_command_token(self, cmd_pin):
181         # Command tokens (48 bits) are sent serially (MSB-first) by the host
182         # (over the CMD line), either to one SD card or to multiple ones.
183         #
184         # Format:
185         #  - Bits[47:47]: Start bit (always 0)
186         #  - Bits[46:46]: Transmission bit (1 == host)
187         #  - Bits[45:40]: Command index (BCD; valid: 0-63)
188         #  - Bits[39:08]: Argument
189         #  - Bits[07:01]: CRC7
190         #  - Bits[00:00]: End bit (always 1)
191
192         if not self.get_token_bits(cmd_pin, 48):
193             return
194
195         self.handle_common_token_fields()
196
197         # Handle command.
198         s = 'ACMD' if self.is_acmd else 'CMD'
199         self.cmd_str = '%s%d (%s)' % (s, self.cmd, self.cmd_name(self.cmd))
200         if hasattr(self, 'handle_%s%d' % (s.lower(), self.cmd)):
201             self.state = St['HANDLE_CMD%d' % self.cmd]
202         else:
203             self.state = St.HANDLE_CMD999
204             self.putc('%s%d' % (s, self.cmd))
205
206     def handle_cmd0(self):
207         # CMD0 (GO_IDLE_STATE) -> no response
208         self.puta(0, 31, [Ann.DECODED_F, ['Stuff bits', 'Stuff', 'SB', 'S']])
209         self.putc('Reset all SD cards')
210         self.token, self.state = [], St.GET_COMMAND_TOKEN
211
212     def handle_cmd2(self):
213         # CMD2 (ALL_SEND_CID) -> R2
214         self.puta(0, 31, [Ann.DECODED_F, ['Stuff bits', 'Stuff', 'SB', 'S']])
215         self.putc('Ask card for CID number')
216         self.token, self.state = [], St.GET_RESPONSE_R2
217
218     def handle_cmd3(self):
219         # CMD3 (SEND_RELATIVE_ADDR) -> R6
220         self.puta(0, 31, [Ann.DECODED_F, ['Stuff bits', 'Stuff', 'SB', 'S']])
221         self.putc('Ask card for new relative card address (RCA)')
222         self.token, self.state = [], St.GET_RESPONSE_R6
223
224     def handle_cmd6(self):
225         # CMD6 (SWITCH_FUNC) -> R1
226         self.putc('Switch/check card function')
227         self.token, self.state = [], St.GET_RESPONSE_R1
228
229     def handle_cmd7(self):
230         # CMD7 (SELECT/DESELECT_CARD) -> R1b
231         self.putc('Select / deselect card')
232         self.token, self.state = [], St.GET_RESPONSE_R6
233
234     def handle_cmd8(self):
235         # CMD8 (SEND_IF_COND) -> R7
236         self.puta(12, 31, [Ann.DECODED_F, ['Reserved', 'Res', 'R']])
237         self.puta(8, 11, [Ann.DECODED_F, ['Supply voltage', 'Voltage', 'VHS', 'V']])
238         self.puta(0, 7, [Ann.DECODED_F, ['Check pattern', 'Check pat', 'Check', 'C']])
239         self.putc('Send interface condition to card')
240         self.token, self.state = [], St.GET_RESPONSE_R7
241         # TODO: Handle case when card doesn't reply with R7 (no reply at all).
242
243     def handle_cmd9(self):
244         # CMD9 (SEND_CSD) -> R2
245         self.puta(16, 31, [Ann.DECODED_F, ['RCA', 'R']])
246         self.puta(0, 15, [Ann.DECODED_F, ['Stuff bits', 'Stuff', 'SB', 'S']])
247         self.putc('Send card-specific data (CSD)')
248         self.token, self.state = [], St.GET_RESPONSE_R2
249
250     def handle_cmd10(self):
251         # CMD10 (SEND_CID) -> R2
252         self.puta(16, 31, [Ann.DECODED_F, ['RCA', 'R']])
253         self.puta(0, 15, [Ann.DECODED_F, ['Stuff bits', 'Stuff', 'SB', 'S']])
254         self.putc('Send card identification data (CID)')
255         self.token, self.state = [], St.GET_RESPONSE_R2
256
257     def handle_cmd13(self):
258         # CMD13 (SEND_STATUS) -> R1
259         self.puta(16, 31, [Ann.DECODED_F, ['RCA', 'R']])
260         self.puta(0, 15, [Ann.DECODED_F, ['Stuff bits', 'Stuff', 'SB', 'S']])
261         self.putc('Send card status register')
262         self.token, self.state = [], St.GET_RESPONSE_R1
263
264     def handle_cmd16(self):
265         # CMD16 (SET_BLOCKLEN) -> R1
266         self.puta(0, 31, [Ann.DECODED_F, ['Block length', 'Blocklen', 'BL', 'B']])
267         self.putc('Set the block length to %d bytes' % self.arg)
268         self.token, self.state = [], St.GET_RESPONSE_R1
269
270     def handle_cmd55(self):
271         # CMD55 (APP_CMD) -> R1
272         self.puta(16, 31, [Ann.DECODED_F, ['RCA', 'R']])
273         self.puta(0, 15, [Ann.DECODED_F, ['Stuff bits', 'Stuff', 'SB', 'S']])
274         self.putc('Next command is an application-specific command')
275         self.is_acmd = True
276         self.token, self.state = [], St.GET_RESPONSE_R1
277
278     def handle_acmd6(self):
279         # ACMD6 (SET_BUS_WIDTH) -> R1
280         self.putc('Read SD config register (SCR)')
281         self.token, self.state = [], St.GET_RESPONSE_R1
282
283     def handle_acmd13(self):
284         # ACMD13 (SD_STATUS) -> R1
285         self.puta(0, 31, [Ann.DECODED_F, ['Stuff bits', 'Stuff', 'SB', 'S']])
286         self.putc('Set SD status')
287         self.token, self.state = [], St.GET_RESPONSE_R1
288
289     def handle_acmd41(self):
290         # ACMD41 (SD_SEND_OP_COND) -> R3
291         self.puta(0, 23, [Ann.DECODED_F,
292             ['VDD voltage window', 'VDD volt', 'VDD', 'V']])
293         self.puta(24, 24, [Ann.DECODED_F, ['S18R']])
294         self.puta(25, 27, [Ann.DECODED_F, ['Reserved', 'Res', 'R']])
295         self.puta(28, 28, [Ann.DECODED_F, ['XPC']])
296         self.puta(29, 29, [Ann.DECODED_F,
297             ['Reserved for eSD', 'Reserved', 'Res', 'R']])
298         self.puta(30, 30, [Ann.DECODED_F,
299             ['Host capacity support info', 'Host capacity', 'HCS', 'H']])
300         self.puta(31, 31, [Ann.DECODED_F, ['Reserved', 'Res', 'R']])
301         self.putc('Send HCS info and activate the card init process')
302         self.token, self.state = [], St.GET_RESPONSE_R3
303
304     def handle_acmd51(self):
305         # ACMD51 (SEND_SCR) -> R1
306         self.putc('Read SD config register (SCR)')
307         self.token, self.state = [], St.GET_RESPONSE_R1
308
309     def handle_cmd999(self):
310         self.token, self.state = [], St.GET_RESPONSE_R1
311
312     def handle_acmd999(self):
313         self.token, self.state = [], St.GET_RESPONSE_R1
314
315     def handle_reg_cid(self):
316         self.putf(8, 15, [Ann.R_CID_MID, ['Manufacturer ID', 'MID']])
317         self.putf(16, 31, [Ann.R_CID_OID, ['OEM/application ID', 'OID']])
318         self.putf(32, 71, [Ann.R_CID_PNM, ['Product name', 'PNM']])
319         self.putf(72, 79, [Ann.R_CID_PRV, ['Product revision', 'PRV']])
320         self.putf(80, 111, [Ann.R_CID_PSN, ['Product serial number', 'PSN']])
321         self.putf(112, 115, [Ann.R_CID_RSVD, ['Reserved', 'RSVD', 'R']])
322         self.putf(116, 127, [Ann.R_CID_MDT, ['Manufacturing date', 'MDT']])
323         self.putf(128, 134, [Ann.R_CID_CRC, ['CRC7 checksum', 'CRC']])
324         self.putf(135, 135, [Ann.R_CID_ONE, ['Always 1', '1']])
325
326     def handle_reg_csd(self):
327         self.putf(8, 9, [Ann.R_CSD_CSD_STRUCTURE, ['CSD structure', 'CSD_STRUCTURE']])
328         self.putf(10, 15, [Ann.R_CSD_RSVD, ['Reserved', 'RSVD', 'R']])
329         self.putf(16, 23, [Ann.R_CSD_TAAC, ['Data read access-time - 1', 'TAAC']])
330         self.putf(24, 31, [Ann.R_CSD_NSAC, ['Data read access-time - 2 in CLK cycles (NSAC * 100)', 'NSAC']])
331         self.putf(32, 39, [Ann.R_CSD_TRAN_SPEED, ['Max. data transfer rate', 'TRAN_SPEED']])
332         self.putf(40, 51, [Ann.R_CSD_CCC, ['Card command classes', 'CCC']])
333         self.putf(52, 55, [Ann.R_CSD_READ_BL_LEN, ['Max. read data block length', 'READ_BL_LEN']])
334         self.putf(56, 56, [Ann.R_CSD_READ_BL_PARTIAL, ['Partial blocks for read allowed', 'READ_BL_PARTIAL']])
335         self.putf(57, 57, [Ann.R_CSD_WRITE_BLK_MISALIGN, ['Write block misalignment', 'WRITE_BLK_MISALIGN']])
336         self.putf(58, 58, [Ann.R_CSD_READ_BLK_MISALIGN, ['Read block misalignment', 'READ_BLK_MISALIGN']])
337         self.putf(59, 59, [Ann.R_CSD_DSR_IMP, ['DSR implemented', 'DSR_IMP']])
338         self.putf(60, 61, [Ann.R_CSD_RSVD, ['Reserved', 'RSVD', 'R']])
339         self.putf(62, 73, [Ann.R_CSD_C_SIZE, ['Device size', 'C_SIZE']])
340         self.putf(74, 76, [Ann.R_CSD_VDD_R_CURR_MIN, ['Max. read current @VDD min', 'VDD_R_CURR_MIN']])
341         self.putf(77, 79, [Ann.R_CSD_VDD_R_CURR_MAX, ['Max. read current @VDD max', 'VDD_R_CURR_MAX']])
342         self.putf(80, 82, [Ann.R_CSD_VDD_W_CURR_MIN, ['Max. write current @VDD min', 'VDD_W_CURR_MIN']])
343         self.putf(83, 85, [Ann.R_CSD_VDD_W_CURR_MAX, ['Max. write current @VDD max', 'VDD_W_CURR_MAX']])
344         self.putf(86, 88, [Ann.R_CSD_C_SIZE_MULT, ['Device size multiplier', 'C_SIZE_MULT']])
345         self.putf(89, 89, [Ann.R_CSD_ERASE_BLK_EN, ['Erase single block enable', 'ERASE_BLK_EN']])
346         self.putf(90, 96, [Ann.R_CSD_SECTOR_SIZE, ['Erase sector size', 'SECTOR_SIZE']])
347         self.putf(97, 103, [Ann.R_CSD_WP_GRP_SIZE, ['Write protect group size', 'WP_GRP_SIZE']])
348         self.putf(104, 104, [Ann.R_CSD_WP_GRP_ENABLE, ['Write protect group enable', 'WP_GRP_ENABLE']])
349         self.putf(105, 106, [Ann.R_CSD_RSVD, ['Reserved', 'RSVD', 'R']])
350         self.putf(107, 109, [Ann.R_CSD_R2W_FACTOR, ['Write speed factor', 'R2W_FACTOR']])
351         self.putf(110, 113, [Ann.R_CSD_WRITE_BL_LEN, ['Max. write data block length', 'WRITE_BL_LEN']])
352         self.putf(114, 114, [Ann.R_CSD_WRITE_BL_PARTIAL, ['Partial blocks for write allowed', 'WRITE_BL_PARTIAL']])
353         self.putf(115, 119, [Ann.R_CSD_RSVD, ['Reserved', 'RSVD']])
354         self.putf(120, 120, [Ann.R_CSD_FILE_FORMAT_GRP, ['File format group', 'FILE_FORMAT_GRP']])
355         self.putf(121, 121, [Ann.R_CSD_COPY, ['Copy flag', 'COPY']])
356         self.putf(122, 122, [Ann.R_CSD_PERM_WRITE_PROTECT, ['Permanent write protection', 'PERM_WRITE_PROTECT']])
357         self.putf(123, 123, [Ann.R_CSD_TMP_WRITE_PROTECT, ['Temporary write protection', 'TMP_WRITE_PROTECT']])
358         self.putf(124, 125, [Ann.R_CSD_FILE_FORMAT, ['File format', 'FILE_FORMAT']])
359         self.putf(126, 127, [Ann.R_CSD_RSVD, ['Reserved', 'RSVD', 'R']])
360         self.putf(128, 134, [Ann.R_CSD_CRC, ['CRC', 'CRC', 'C']])
361         self.putf(135, 135, [Ann.R_CSD_ONE, ['Always 1', '1']])
362
363     # Response tokens can have one of four formats (depends on content).
364     # They can have a total length of 48 or 136 bits.
365     # They're sent serially (MSB-first) by the card that the host
366     # addressed previously, or (synchronously) by all connected cards.
367
368     def handle_response_r1(self, cmd_pin):
369         # R1: Normal response command
370         #  - Bits[47:47]: Start bit (always 0)
371         #  - Bits[46:46]: Transmission bit (0 == card)
372         #  - Bits[45:40]: Command index (BCD; valid: 0-63)
373         #  - Bits[39:08]: Card status
374         #  - Bits[07:01]: CRC7
375         #  - Bits[00:00]: End bit (always 1)
376         if not self.get_token_bits(cmd_pin, 48):
377             return
378         self.handle_common_token_fields()
379         self.putr(Ann.RESPONSE_R1)
380         self.puta(0, 31, [Ann.DECODED_F, ['Card status', 'Status', 'S']])
381         for i in range(32):
382             self.putbit(8 + i, [card_status[31 - i]])
383         self.token, self.state = [], St.GET_COMMAND_TOKEN
384
385     def handle_response_r1b(self, cmd_pin):
386         # R1b: Same as R1 with an optional busy signal (on the data line)
387         if not self.get_token_bits(cmd_pin, 48):
388             return
389         self.handle_common_token_fields()
390         self.puta(0, 31, [Ann.DECODED_F, ['Card status', 'Status', 'S']])
391         self.putr(Ann.RESPONSE_R1B)
392         self.token, self.state = [], St.GET_COMMAND_TOKEN
393
394     def handle_response_r2(self, cmd_pin):
395         # R2: CID/CSD register
396         #  - Bits[135:135]: Start bit (always 0)
397         #  - Bits[134:134]: Transmission bit (0 == card)
398         #  - Bits[133:128]: Reserved (always 0b111111)
399         #  - Bits[127:001]: CID or CSD register including internal CRC7
400         #  - Bits[000:000]: End bit (always 1)
401         if not self.get_token_bits(cmd_pin, 136):
402             return
403         # Annotations for each individual bit.
404         for bit in range(len(self.token)):
405             self.putf(bit, bit, [Ann.BIT, ['%d' % self.token[bit].bit]])
406         self.putf(0, 0, [Ann.F_START, ['Start bit', 'Start', 'S']])
407         t = 'host' if self.token[1].bit == 1 else 'card'
408         self.putf(1, 1, [Ann.F_TRANSM, ['Transmission: ' + t, 'T: ' + t, 'T']])
409         self.putf(2, 7, [Ann.F_CMD, ['Reserved', 'Res', 'R']])
410         self.putf(8, 134, [Ann.F_ARG, ['Argument', 'Arg', 'A']])
411         self.putf(135, 135, [Ann.F_END, ['End bit', 'End', 'E']])
412         self.putf(8, 134, [Ann.DECODED_F, ['CID/CSD register', 'CID/CSD', 'C']])
413         self.putf(0, 135, [Ann.RESPONSE_R2, ['Response: R2']])
414
415         if self.last_cmd in (Ann.CMD2, Ann.CMD10):
416             self.handle_reg_cid()
417
418         if self.last_cmd == Ann.CMD9:
419             self.handle_reg_csd()
420
421         self.token, self.state = [], St.GET_COMMAND_TOKEN
422
423     def handle_response_r3(self, cmd_pin):
424         # R3: OCR register
425         #  - Bits[47:47]: Start bit (always 0)
426         #  - Bits[46:46]: Transmission bit (0 == card)
427         #  - Bits[45:40]: Reserved (always 0b111111)
428         #  - Bits[39:08]: OCR register
429         #  - Bits[07:01]: Reserved (always 0b111111)
430         #  - Bits[00:00]: End bit (always 1)
431         if not self.get_token_bits(cmd_pin, 48):
432             return
433         self.putr(Ann.RESPONSE_R3)
434         # Annotations for each individual bit.
435         for bit in range(len(self.token)):
436             self.putf(bit, bit, [Ann.BIT, ['%d' % self.token[bit].bit]])
437         self.putf(0, 0, [Ann.F_START, ['Start bit', 'Start', 'S']])
438         t = 'host' if self.token[1].bit == 1 else 'card'
439         self.putf(1, 1, [Ann.F_TRANSM, ['Transmission: ' + t, 'T: ' + t, 'T']])
440         self.putf(2, 7, [Ann.F_CMD, ['Reserved', 'Res', 'R']])
441         self.putf(8, 39, [Ann.F_ARG, ['Argument', 'Arg', 'A']])
442         self.putf(40, 46, [Ann.F_CRC, ['Reserved', 'Res', 'R']])
443         self.putf(47, 47, [Ann.F_END, ['End bit', 'End', 'E']])
444         self.puta(0, 31, [Ann.DECODED_F, ['OCR register', 'OCR reg', 'OCR', 'O']])
445         self.token, self.state = [], St.GET_COMMAND_TOKEN
446
447     def handle_response_r6(self, cmd_pin):
448         # R6: Published RCA response
449         #  - Bits[47:47]: Start bit (always 0)
450         #  - Bits[46:46]: Transmission bit (0 == card)
451         #  - Bits[45:40]: Command index (always 0b000011)
452         #  - Bits[39:24]: Argument[31:16]: New published RCA of the card
453         #  - Bits[23:08]: Argument[15:0]: Card status bits
454         #  - Bits[07:01]: CRC7
455         #  - Bits[00:00]: End bit (always 1)
456         if not self.get_token_bits(cmd_pin, 48):
457             return
458         self.handle_common_token_fields()
459         self.puta(0, 15, [Ann.DECODED_F, ['Card status bits', 'Status', 'S']])
460         self.puta(16, 31, [Ann.DECODED_F, ['Relative card address', 'RCA', 'R']])
461         self.putr(Ann.RESPONSE_R6)
462         self.token, self.state = [], St.GET_COMMAND_TOKEN
463
464     def handle_response_r7(self, cmd_pin):
465         # R7: Card interface condition
466         #  - Bits[47:47]: Start bit (always 0)
467         #  - Bits[46:46]: Transmission bit (0 == card)
468         #  - Bits[45:40]: Command index (always 0b001000)
469         #  - Bits[39:20]: Reserved bits (all-zero)
470         #  - Bits[19:16]: Voltage accepted
471         #  - Bits[15:08]: Echo-back of check pattern
472         #  - Bits[07:01]: CRC7
473         #  - Bits[00:00]: End bit (always 1)
474         if not self.get_token_bits(cmd_pin, 48):
475             return
476         self.handle_common_token_fields()
477
478         self.putr(Ann.RESPONSE_R7)
479
480         # Arg[31:12]: Reserved bits (all-zero)
481         self.puta(12, 31, [Ann.DECODED_F, ['Reserved', 'Res', 'R']])
482
483         # Arg[11:08]: Voltage accepted
484         v = ''.join(str(i.bit) for i in self.token[28:32])
485         av = accepted_voltages.get(int('0b' + v, 2), 'Unknown')
486         self.puta(8, 11, [Ann.DECODED_F,
487             ['Voltage accepted: ' + av, 'Voltage', 'Volt', 'V']])
488
489         # Arg[07:00]: Echo-back of check pattern
490         self.puta(0, 7, [Ann.DECODED_F,
491             ['Echo-back of check pattern', 'Echo', 'E']])
492
493         self.token, self.state = [], St.GET_COMMAND_TOKEN
494
495     def decode(self):
496         while True:
497             # Wait for a rising CLK edge.
498             (cmd_pin, clk, dat0, dat1, dat2, dat3) = self.wait({Pin.CLK: 'r'})
499
500             # State machine.
501             if self.state == St.GET_COMMAND_TOKEN:
502                 if len(self.token) == 0:
503                     # Wait for start bit (CMD = 0).
504                     if cmd_pin != 0:
505                         continue
506                 self.get_command_token(cmd_pin)
507             elif self.state.value.startswith('HANDLE_CMD'):
508                 # Call the respective handler method for the command.
509                 a, cmdstr = 'a' if self.is_acmd else '', self.state.value[10:].lower()
510                 handle_cmd = getattr(self, 'handle_%scmd%s' % (a, cmdstr))
511                 handle_cmd()
512                 # Leave ACMD mode again after the first command after CMD55.
513                 if self.is_acmd and cmdstr not in ('55', '63'):
514                     self.is_acmd = False
515             elif self.state.value.startswith('GET_RESPONSE'):
516                 if len(self.token) == 0:
517                     # Wait for start bit (CMD = 0).
518                     if cmd_pin != 0:
519                         continue
520                 # Call the respective handler method for the response.
521                 s = 'handle_response_%s' % self.state.value[13:].lower()
522                 handle_response = getattr(self, s)
523                 handle_response(cmd_pin)