Xemu [doxygen]  hyppo 0a42be3a057156924bc1b626a687bd6e27349c45 @ Sat 19 Mar 02:15:11 CET 2022
sdext.c
Go to the documentation of this file.
1 /* Xep128: Minimalistic Enterprise-128 emulator with focus on "exotic" hardware
2  Copyright (C)2015,2016 LGB (Gábor Lénárt) <lgblgblgb@gmail.com>
3  http://xep128.lgb.hu/
4 
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
9 
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
14 
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
18 
19 /* General SD information:
20  http://elm-chan.org/docs/mmc/mmc_e.html
21  http://www.mikroe.com/downloads/get/1624/microsd_card_spec.pdf
22  http://users.ece.utexas.edu/~valvano/EE345M/SD_Physical_Layer_Spec.pdf
23  Flash IC used (AM29F400BT) on the cartridge:
24  http://www.mouser.com/ds/2/380/spansion%20inc_am29f400b_eol_21505e8-329620.pdf
25 */
26 
27 #include "xep128.h"
28 #include "sdext.h"
29 #include "cpu.h"
30 #include "configuration.h"
31 
32 #include <unistd.h>
33 
34 #ifndef CONFIG_SDEXT_SUPPORT
35 #warning "SDEXT support is disabled by configuration."
36 #else
37 //#define DEBUG_SDEXT
38 #define CONFIG_SDEXT_FLASH
39 
40 #ifdef DEBUG_SDEXT
41 # define SD_DEBUG DEBUG
42 #else
43 # define SD_DEBUG(...)
44 #endif
45 
46 
47 static const char *sdext_rom_signature = "SDEXT";
48 
49 int sdext_cart_enabler = SDEXT_CART_ENABLER_OFF;
50 char sdimg_path[PATH_MAX + 1];
51 static int rom_page_ofs;
52 static int is_hs_read;
53 static Uint8 _spi_last_w;
54 static int cs0, cs1;
55 static Uint8 status;
56 
57 static Uint8 sd_ram_ext[7 * 1024]; // 7K of accessible SRAM
58 /* The FIRST 64K of flash (sector 0) is structured this way:
59  * first 48K is accessed directly at segment 4,5,6, so it's part of the normal EP memory emulated
60  * the last 16K is CANNOT BE accessed at all from EP
61  It's part of the main memory array at the given offset, see flash[0][addr] below
62  The SECOND 64K of flash (sector 1) is stored in sd_rom_ext (see below), it's flash[1][addr] */
63 static Uint8 sd_rom_ext[0x10000];
64 static Uint8 *flash[2] = { memory + 0x10000, sd_rom_ext };
65 
66 static int flash_wr_protect = 0;
67 static int flash_bus_cycle = 0;
68 static int flash_command = 0;
69 
70 static Uint8 cmd[6], cmd_index, _read_b, _write_b, _write_specified;
71 static const Uint8 *ans_p;
72 static int ans_index, ans_size;
73 static int writing;
74 static int delay_answer;
75 static void (*ans_callback)(void);
76 
77 static FILE *sdf;
78 static int sdfd;
79 static Uint8 _buffer[1024];
80 off_t sd_card_size = 0;
81 
82 #define MAX_CARD_SIZE 2147483648UL
83 #define MIN_CARD_SIZE 8388608UL
84 
85 /* ID files:
86  * C0 71 00 00 │ 00 5D 01 32 │ 13 59 80 E3 │ 76 D9 CF FF │ 16 40 00 4F │ 01 50 41 53
87  * 30 31 36 42 │ 41 35 E4 39 │ 06 00 35 03 │ 80 FF 80 00 │ 00 00 00 00 │ 00 00 00 00
88  * 4 bytes: size in sectors: C0 71 00 00
89  * CSD register 00 5D 01 32 │ 13 59 80 E3 │ 76 D9 CF FF │ 16 40 00 4F
90  * CID register 01 50 41 53 | 30 31 36 42 │ 41 35 E4 39 │ 06 00 35 03
91  * OCR register 80 FF 80 00
92  */
93 
94 
95 static const Uint8 _stop_transmission_answer[] = {
96  0, 0, 0, 0, // "stuff byte" and some of it is the R1 answer anyway
97  0xFF // SD card is ready again
98 };
99 #define __CSD_OFS 2
100 #define CSD(a) _read_csd_answer[(__CSD_OFS) + (a)]
101 static Uint8 _read_csd_answer[] = {
102  0xFF, // waiting a bit
103  0xFE, // data token
104  // the CSD itself
105  0x00, 0x5D, 0x01, 0x32, 0x13, 0x59, 0x80, 0xE3, 0x76, 0xD9, 0xCF, 0xFF, 0x16, 0x40, 0x00, 0x4F,
106  0, 0 // CRC bytes
107 };
108 static const Uint8 _read_cid_answer[] = {
109  0xFF, // waiting a bit
110  0xFE, // data token
111  // the CID itself
112  0x01, 0x50, 0x41, 0x53, 0x30, 0x31, 0x36, 0x42, 0x41, 0x35, 0xE4, 0x39, 0x06, 0x00, 0x35, 0x03,
113  0, 0 // CRC bytes
114 };
115 static const Uint8 _read_ocr_answer[] = { // no data token, nor CRC! (technically this is the R3 answer minus the R1 part at the beginning ...)
116  // the OCR itself
117  0x80, 0xFF, 0x80, 0x00
118 };
119 
120 #define ADD_ANS(ans) { ans_p = (ans); ans_index = 0; ans_size = sizeof(ans); }
121 
122 #include "xemu/../rom/ep128/vhd_compressed.c"
123 
124 
125 
126 static int decompress_vhd ( const Uint8 *p, int fd )
127 {
128  int filelen = 0;
129  for (;;) {
130  Uint32 l = p[0] | (p[1] << 8) | (p[2] << 16) | ((p[3] & 0x7F) << 24);
131  if (!l)
132  break;
133  p += 4;
134  filelen += l;
135  if (p[-1] & 0x80) {
136  // printf("Zero seq len = %d\n", l);
137  if (lseek(fd, filelen, SEEK_SET) != filelen)
138  return 1;
139  } else {
140  // printf("Data len = %d\n", l);
141  while (l) {
142  int r = write(fd, p, l);
143  if (r <= 0)
144  return 1;
145  l -= r;
146  p += r;
147  }
148  }
149  }
150  return 0;
151 }
152 
153 
154 
155 void sdext_clear_ram(void)
156 {
157  memset(sd_ram_ext, 0xFF, 0x1C00);
158 }
159 
160 
161 
162 static int sdext_detect_rom ( void )
163 {
164  Uint8 *p = memory + 7 * 0x4000;
165  Uint8 *p2 = p + 0x2000 - strlen(sdext_rom_signature);
166  if (memcmp(p, "EXOS_ROM", 8))
167  return 1; // No EXOS_ROM header
168  for (; p < p2; p++ ) {
169  if (!memcmp(p, sdext_rom_signature, strlen(sdext_rom_signature)))
170  return 0; // found our extra ID
171  }
172  return 1; // our ID cannot be found
173 }
174 
175 
176 
177 #if 0
178 static inline off_t _assert_on_csd_size_mismatch ( off_t expected_size, int expected_mult, int expected_blocknr, int expected_blocklen )
179 {
180  int mult = 2 ** (i["C_SIZE_MULT"] + 2)
181  int blocknr = (i["C_SIZE"] + 1) * mult
182  int blocklen = 2 ** i["READ_BL_LEN"]
183  off_t size = (off_t)blocknr * (off_t)blocklen;
184  if (size != expected_size || mult != expected_mult || blocknr != excepted_blocknr || blocklen != expected_blocklen)
185  FATAL("Internal CSD size calculation failure!\nExpected=" PRINTF_LLD " Got=" PRINTF_LLD " (mult=%d blocknr=%d blocklen=%d)",
186  (long long)expected_size, (long long)size,
187  mult, blocknr, blocklen
188  );
189 }
190 #endif
191 
192 
193 
194 static int _size_calc ( off_t size )
195 {
196  int blen_i;
197  for (blen_i = 9; blen_i < 12; blen_i++) {
198  int mult_i;
199  int blen = 1 << blen_i;
200  for (mult_i = 0; mult_i < 8; mult_i++) {
201  int mult = 1 << (mult_i + 2);
202  int res = size / blen;
203  if (!(size % blen) && !(res % mult)) {
204  res = (res / mult) - 1;
205  if (res < 4096 && res > 0) {
206  //printf("MAY HIT with blen=%d[%d],mult=%d[%d],result=%d\n",
207  // blen, blen_i, mult, mult_i, res
208  //);
209  CSD( 5) = (CSD( 5) & 0xF0) | blen_i;
210  CSD( 6) = (CSD( 6) & 0xFC) | (res >> 10);
211  CSD( 7) = (res >> 2) & 0xFF;
212  CSD( 8) = (CSD( 8) & 0x3F) | ((res & 3) << 6);
213  CSD( 9) = (CSD( 9) & 0xFC) | (mult_i >> 1);
214  CSD(10) = (CSD(10) & 0x7F) | ((mult_i & 1) << 7);
215  // CHECKING the result follows now!
216  //_assert_on_csd_size_mismatch(size, mult, res, blen);
217  return 0;
218  }
219  }
220  }
221  }
222  return 1;
223 }
224 
225 
226 
227 static int sdext_check_and_set_size ( void )
228 {
229  off_t new_size;
230  int is_vhd;
231  if (sd_card_size < MIN_CARD_SIZE) {
232  ERROR_WINDOW(
233  "SD card image file \"%s\" is too small, minimal size is " PRINTF_LLD " Mbytes, but this one is " PRINTF_LLD " bytes long (about " PRINTF_LLD " Mbytes). SD access has been disabled!",
234  sdimg_path, (long long)(MIN_CARD_SIZE >> 20), (long long)sd_card_size, (long long)(sd_card_size >> 20)
235  );
236  return 1;
237  }
238  /* check for VHD footer (not the real part of the image, +512 bytes structure at the end) */
239  is_vhd = -1;
240  if (lseek(sdfd, sd_card_size - 512, SEEK_SET) == sd_card_size - 512) {
241  if (read(sdfd, _buffer, 512) == 512) {
242  Uint8 *p = NULL;
243  if (!memcmp(_buffer + 1, "conectix", 8)) {
244  sd_card_size++; // old, buggy Microsoft tool maybe, 511 bytes footer instead of 512. Treating size as the normalized one
245  p = _buffer + 1;
246  DEBUG("SDEXT: warning, old buggy Microsoft VHD file, activating workaround!" NL);
247  } else if (!memcmp(_buffer, "conectix", 8))
248  p = _buffer;
249  if (p) {
250  if (p[60] || p[61] || p[62] || p[63] != 2) {
251  ERROR_WINDOW("SD card image \"%s\" is an unsupported VHD file (not fixed, maybe dynamic?)", sdimg_path);
252  return 1;
253  }
254  is_vhd = 1;
255  } else
256  is_vhd = 0;
257  }
258  }
259  if (is_vhd < 0) {
260  ERROR_WINDOW("SD card image \"%s\" I/O error while detecting type: %s.\nSD access has been disabled!", sdimg_path, ERRSTR());
261  return 1;
262  }
263  if (is_vhd) {
264  DEBUG("SDEXT: VHD file detected as card image." NL);
265  sd_card_size -= 512;
266  } else
267  DEBUG("SDEXT: VHD file is not detected." NL);
268  if (sd_card_size > MAX_CARD_SIZE) { // do this check here, as VHD footer could overflow on 2G boundary at the beginning what we have support for in Xep128
269  ERROR_WINDOW(
270  "SD card image file \"%s\" is too large, maximal allowed size is " PRINTF_LLD " Mbytes, but this one is " PRINTF_LLD " bytes long (about " PRINTF_LLD " Mbytes). "
271  "SD access has been disabled!",
272  sdimg_path, (long long)(MAX_CARD_SIZE >> 20), (long long)sd_card_size, (long long)(sd_card_size >> 20)
273  );
274  return 1;
275  }
276  if ((sd_card_size & 511)) { // do this check here, as buggy MS tool can create 511 "tail" as footer
277  ERROR_WINDOW("SD card image file \"%s\" size is not multiple of 512 bytes! SD access has been disabled!", sdimg_path);
278  return 1;
279  }
280  /* probing size, optionally extending on request */
281  new_size = sd_card_size;
282  while (_size_calc(new_size))
283  new_size += 512;
284  if (new_size == sd_card_size)
285  return 0;
286  if (is_vhd)
287  WARNING_WINDOW("SD-card image \"%s\" is promoted for extension but it seems to be a VHD file.\nIf you allow extension it WON'T BE USED AS VHD ANY MORE BY OTHER SOFTWARE!", sdimg_path);
288  INFO_WINDOW("SD-card image file \"%s\" is about to be extended with %d bytes (the next valid SD-card size), new size is: " PRINTF_LLD, sdimg_path, (int)(new_size - sd_card_size), (long long)new_size);
289  if (!QUESTION_WINDOW("Not allowed|Allowed (DANGEROUS)", "Do you allow this extension? NOTE: it's a test feature, do not allow it, if you are unsure!")) {
290  INFO_WINDOW("You didn't allow the extension. You can continue, but some EP128 software may fail (ie: fdisk)!");
291  return 0;
292  }
293  if (lseek(sdfd, new_size - 1, SEEK_SET) != new_size - 1) {
294  ERROR_WINDOW("SD card image file \"%s\" cannot be extended (seek error: %s).\nYou can continue but some EP128 software may fail (ie: fdisk)!", sdimg_path, ERRSTR());
295  return 0;
296  }
297  if (write(sdfd, sd_rom_ext, 1) != 1) { // sd_rom_ext is just used to write some *RANDOM* byte, the content is not so important here :-P It will create a file "with hole" btw.
298  ERROR_WINDOW("SD card image file \"%s\" cannot be extended (write error: %s).\nYou can continue but some EP128 software may fail (ie: fdisk)!", sdimg_path, ERRSTR());
299  return 0;
300  }
301  sd_card_size = new_size;
302  INFO_WINDOW("Great, image file is successfully extended to valid SD-card size! :-)\nNext time you can enjoy the lack of these info message, as you have valid file size now :-)");
303  return 0;
304 }
305 
306 
307 
308 /* SDEXT emulation currently excepts the cartridge area (segments 4-7) to be filled
309  * with the FLASH ROM content. Even segment 7, which will be copied to the second 64K "hidden"
310  * and pagable flash area of the SD cartridge. Currently, there is no support for the full
311  * sized SDEXT flash image */
312 void sdext_init ( void )
313 {
314  /* try to detect SDEXT ROM extension and only turn on emulation if it exists */
315  if (sdext_detect_rom()) {
316  WARNING_WINDOW("No SD-card cartridge ROM code found in loaded ROM set. SD card hardware emulation has been disabled!");
317  *sdimg_path = 0;
318  sdf = NULL;
319  SD_DEBUG("SDEXT: init: REFUSE: no SD-card cartridge ROM code found in loaded ROM set." NL);
320  return;
321  }
322  SD_DEBUG("SDEXT: init: cool, SD-card cartridge ROM code seems to be found in loaded ROM set, enabling SD card hardware emulation ..." NL);
323  // try to open SD card image. If not found, and it's the DEFAULT config option we provide user to install an empty one (and later to download a populated one)
324 try_to_open_image:
325  sdf = open_emu_file(config_getopt_str("sdimg"), "rb", sdimg_path); // open in read-only mode, to get the path
326  if (sdf) {
327  fclose(sdf);
328  sdf = fopen(sdimg_path, "r+b");
329  if (sdf) {
330  DEBUGPRINT("SDEXT: SD image file is re-open in read/write mode, good (fd=%d)." NL, fileno(sdf));
331  } else {
332  sdf = fopen(sdimg_path, "rb");
333  DEBUGPRINT("SDEXT: SD image cannot be re-open in read-write mode, using read-only access (fd=%d)." NL, fileno(sdf));
334  }
335  }
336  // if we couldn't open image _AND_ it was the default ...
337  if (!sdf && !strcmp(config_getopt_str("sdimg"), SDCARD_IMG_FN)) {
338  int r = QUESTION_WINDOW("?Exit|!Continue without SD card|Create empty image", "Cannot open default SD card image file.");
339  if (r == 0)
340  XEMUEXIT(0);
341  else if (r == 2) { // create an empty image
342  char pathbuffer[PATH_MAX + 1];
343  snprintf(sdimg_path, PATH_MAX, "%s%s.tmp", app_pref_path, SDCARD_IMG_FN[0] == '@' ? SDCARD_IMG_FN + 1 : SDCARD_IMG_FN);
344  sdf = open_emu_file(sdimg_path, "wb", pathbuffer);
345  if (!sdf) {
346  ERROR_WINDOW("Cannot create empty image: %s", ERRSTR());
347  goto try_to_open_image;
348  }
349  r = decompress_vhd(empty_vhd_image, fileno(sdf));
350  if (r) {
351  ERROR_WINDOW("Error decompressing empty image: %s", ERRSTR());
352  fclose(sdf);
353  unlink(sdimg_path);
354  goto try_to_open_image;
355  }
356  fclose(sdf);
357  pathbuffer[strlen(pathbuffer) - 4] = 0;
358  if (rename(sdimg_path, pathbuffer))
359  ERROR_WINDOW("Rename of created temp file error: %s", ERRSTR());
360  else
361  INFO_WINDOW("Empty image file has been created: %s", pathbuffer);
362  goto try_to_open_image; // loop again, now with successfully created image we will have better chance :)
363  }
364  }
365  if (!sdf) {
366  WARNING_WINDOW("SD card image file \"%s\" cannot be open: %s. You can use Xep128 but SD card access won't work!", sdimg_path, ERRSTR());
367  *sdimg_path = 0;
368  } else {
369  sdfd = fileno(sdf);
370  sd_card_size = lseek(sdfd, 0, SEEK_END);
371  if (sdext_check_and_set_size()) {
372  fclose(sdf);
373  sdf = NULL;
374  *sdimg_path = 0;
375  } else
376  DEBUG("SDEXT: SD card size is: " PRINTF_LLD " bytes" NL, (long long)sd_card_size);
377  }
378  memset(sd_rom_ext, 0xFF, 0x10000);
379  /* Copy ROM image of 16K to the second 64K of the cartridge flash. Currently only 8K is used.
380  It's possible to use 64K the ROM set image used by Xep128 can only hold 16K this way, though. */
381  memcpy(sd_rom_ext, memory + 7 * 0x4000, 0x4000);
382  sdext_clear_ram();
383  sdext_cart_enabler = SDEXT_CART_ENABLER_ON; // turn emulation on
384  rom_page_ofs = 0;
385  is_hs_read = 0;
386  cmd_index = 0;
387  ans_size = 0;
388  delay_answer = 0;
389  ans_index = 0;
390  ans_callback = NULL;
391  status = 0;
392  _read_b = 0;
393  _write_b = 0xFF;
394  _spi_last_w = 0xFF;
395  writing = -2;
396  SD_DEBUG("SDEXT: init end" NL);
397 }
398 
399 
400 static int blocks;
401 
402 
403 // FIXME: error handling of read() !!!!
404 // FIXME: check excess of card size (during multiple block read) !!!!
405 static void _block_read ( void )
406 {
407  int ret;
408  z80ex_w_states(40); // TODO: fake some wait states here, actully this is the WRONG method, as not the Z80 should wait but the SD card's answer ...
409  blocks++;
410  _buffer[0] = 0xFF; // wait a bit
411  _buffer[1] = 0xFE; // data token
412  //ret = fread(_buffer + 2, 1, 512, sdf);
413  ret = read(sdfd, _buffer + 2, 512);
414  SD_DEBUG("SDEXT: REGIO: fread retval = %d" NL, ret);
415  (void)ret;
416  _buffer[512 + 2] = 0; // CRC
417  _buffer[512 + 3] = 0; // CRC
418  ans_p = _buffer;
419  ans_index = 0;
420  ans_size = 512 + 4;
421 }
422 
423 
424 
425 /* SPI is a read/write in once stuff. We have only a single function ...
426  * _write_b is the data value to put on MOSI
427  * _read_b is the data read from MISO without spending _ANY_ SPI time to do shifting!
428  * This is not a real thing, but easier to code this way.
429  * The implementation of the real behaviour is up to the caller of this function.
430  */
431 static void _spi_shifting_with_sd_card ()
432 {
433  if (!cs0) { // Currently, we only emulate one SD card, and it must be selected for any answer
434  _read_b = 0xFF;
435  return;
436  }
437  /* begin of write support */
438  if (delay_answer) {
439  delay_answer = 0;
440  return;
441  }
442  if (writing > -2) {
443  _read_b = 0xFF;
444  SD_DEBUG("SDEXT: write byte #%d as %02Xh for CMD %d" NL, writing, _write_b, cmd[0]);
445  if (writing == -1) {
446  if (_write_b == 0xFD) { // stop token
447  SD_DEBUG("SDEXT: Stop token got" NL);
448  _read_b = 0; // wait a tiny time ...
449  writing = -2; // ... but otherwise, end of write session
450  return;
451  }
452  if (_write_b != 0xFE && _write_b != 0xFC) {
453  SD_DEBUG("SDEXT: Waiting for token ..." NL);
454  return;
455  }
456  SD_DEBUG("SDEXT: token found %02Xh" NL, _write_b);
457  writing = 0;
458  return;
459  }
460  _buffer[writing++] = _write_b; // store written byte
461  if (writing == 512 + 2) { // if one block (+ 2byte CRC) is written by host ...
462  off_t ret, _offset = (cmd[1] << 24) | (cmd[2] << 16) | (cmd[3] << 8) | cmd[4];
463  _offset += 512UL * blocks;
464  blocks++;
465  if (_offset > sd_card_size - 512UL) {
466  ret = 13;
467  SD_DEBUG("SDEXT: access beyond the card size!" NL);
468  } else {
469  ret = (lseek(sdfd, _offset, SEEK_SET) == _offset) ? 5 : 13;
470  if (ret != 5)
471  SD_DEBUG("SDEXT: seek error: %s" NL, ERRSTR());
472  else {
473  ret = (write(sdfd, _buffer, 512) == 512) ? 5 : 13;
474  if (ret != 5)
475  SD_DEBUG("SDEXT: write error: %s" NL, ERRSTR());
476  }
477  }
478  // space for the actual block write ...
479  if (cmd[0] == 24 || ret != 5) {
480  SD_DEBUG("SDEXT: cmd-%d end blocks=%d" NL, cmd[0], blocks);
481  _read_b = ret; // data accepted?
482  writing = -2; // turn off write mode
483  delay_answer = 1;
484  } else {
485  SD_DEBUG("SDEXT: cmd-25 end blocks=%d" NL, blocks);
486  _read_b = ret; // data accepted?
487  writing = -1; // write mode back to the token waiting phase
488  delay_answer = 1;
489  }
490  }
491  return;
492  }
493  /* end of write support */
494  if (cmd_index == 0 && (_write_b & 0xC0) != 0x40) {
495  if (ans_index < ans_size) {
496  SD_DEBUG("SDEXT: REGIO: streaming answer byte %d of %d-1 value %02X" NL, ans_index, ans_size, ans_p[ans_index]);
497  _read_b = ans_p[ans_index++];
498  } else {
499  if (ans_callback)
500  ans_callback();
501  else {
502  //_read_b = 0xFF;
503  ans_index = 0;
504  ans_size = 0;
505  SD_DEBUG("SDEXT: REGIO: dummy answer 0xFF" NL);
506  }
507  _read_b = 0xFF;
508  }
509  return;
510  }
511  if (cmd_index < 6) {
512  cmd[cmd_index++] = _write_b;
513  _read_b = 0xFF;
514  return;
515  }
516  SD_DEBUG("SDEXT: REGIO: command (CMD%d) received: %02X %02X %02X %02X %02X %02X" NL, cmd[0] & 63, cmd[0], cmd[1], cmd[2], cmd[3], cmd[4], cmd[5]);
517  cmd[0] &= 63;
518  cmd_index = 0;
519  ans_callback = NULL;
520  switch (cmd[0]) {
521  case 0: // CMD 0
522  _read_b = 1; // IDLE state R1 answer
523  break;
524  case 1: // CMD 1 - init
525  _read_b = 0; // non-IDLE now (?) R1 answer
526  break;
527  case 16: // CMD16 - set blocklen (?!) : we only handles that as dummy command oh-oh ...
528  _read_b = 0; // R1 answer
529  break;
530  case 9: // CMD9: read CSD register
531  SD_DEBUG("SDEXT: REGIO: command is read CSD register" NL);
532  ADD_ANS(_read_csd_answer);
533  _read_b = 0; // R1
534  break;
535  case 10: // CMD10: read CID register
536  ADD_ANS(_read_cid_answer);
537  _read_b = 0; // R1
538  break;
539  case 58: // CMD58: read OCR
540  ADD_ANS(_read_ocr_answer);
541  _read_b = 0; // R1 (R3 is sent as data in the emulation without the data token)
542  break;
543  case 12: // CMD12: stop transmission (reading multiple)
544  ADD_ANS(_stop_transmission_answer);
545  _read_b = 0;
546  // actually we don't do too much, as on receiving a new command callback will be deleted before this switch-case block
547  SD_DEBUG("SDEXT: REGIO: block counter before CMD12: %d" NL, blocks);
548  blocks = 0;
549  break;
550  case 17: // CMD17: read a single block, babe
551  case 18: // CMD18: read multiple blocks
552  blocks = 0;
553  if (sdf == NULL)
554  _read_b = 32; // address error, if no SD card image ... [this is bad TODO, better error handling]
555  else {
556  off_t ret, _offset = (cmd[1] << 24) | (cmd[2] << 16) | (cmd[3] << 8) | cmd[4];
557  SD_DEBUG("SDEXT: REGIO: seek to %ld in the image file." NL, _offset);
558  z80ex_w_states(100); // TODO: fake some wait states here, actully this is the WRONG method, as not the Z80 should wait but the SD card's answer ...
559  if (_offset > sd_card_size - 512UL) {
560  _read_b = 32; // address error, TODO: what is the correct answer here?
561  SD_DEBUG("SDEXT: access beyond the card size!" NL);
562  } else {
563  //fseek(sdf, _offset, SEEK_SET);
564  ret = lseek(sdfd, _offset, SEEK_SET);
565  if (ret != _offset) {
566  _read_b = 32; // address error, TODO: what is the correct answer here?
567  SD_DEBUG("SDEXT: seek error to %ld (got: %ld)" NL, _offset, ret);
568  } else {
569  _block_read();
570  if (cmd[0] == 18)
571  ans_callback = _block_read; // in case of CMD18, continue multiple sectors, register callback for that!
572  _read_b = 0; // R1
573  }
574  }
575  }
576  break;
577  case 24: // CMD24: write block
578  case 25: // CMD25: write multiple blocks
579  blocks = 0;
580  writing = -1; // signal writing (-2 for not-write mode), also the write position into the buffer
581  _read_b = 0; // R1 answer, OK
582  break;
583  default: // unimplemented command, heh!
584  SD_DEBUG("SDEXT: REGIO: unimplemented command %d = %02Xh" NL, cmd[0], cmd[0]);
585  _read_b = 4; // illegal command :-/
586  break;
587  }
588 }
589 
590 
591 
592 static void flash_erase ( int sector ) // erase sectors 0 or 1, or both if -1 is given!
593 {
594  if (sector < 1) {
595  memset(flash[0], 0xFF, 0xC000); // erase sector 0, it's only 48K accessible on SD/EP so it does not matter, real flash would be 64K here too
596  SD_DEBUG("SDEXT: FLASH: erasing sector 0!" NL);
597  WARNING_WINDOW("Erasing flash sector 0! You can safely ignore this warning.");
598  }
599  if (abs(sector) == 1) {
600  memset(flash[1], 0xFF, 0x10000); // erase sector 1
601  SD_DEBUG("SDEXT: FLASH: erasing sector 1!" NL);
602  WARNING_WINDOW("Erasing flash sector 1! You can safely ignore this warning.");
603  }
604 }
605 
606 
607 
608 static Uint8 flash_rd_bus_op ( int sector, Uint16 addr )
609 {
610  Uint8 byte;
611  if (flash_command == 0x90)
612  switch (addr & 0xFF) {
613  case 0x00:
614  byte = 1; // manufacturer ID
615  SD_DEBUG("SDEXT: FLASH: cmd 0x90 get manufacturer ID, result = %02Xh" NL, byte);
616  break;
617  case 0x02:
618  byte = 0x23; // device ID, top boot block
619  SD_DEBUG("SDEXT: FLASH: cmd 0x90 get device ID, result = %02Xh" NL, byte);
620  break;
621  case 0x04:
622  byte = 0; // sector protect status, etc?
623  SD_DEBUG("SDEXT: FLASH: cmd 0x90 get sector protect status, result = %02Xh" NL, byte);
624  break;
625  default:
626  byte = flash[sector][addr]; // not sure what to do in case of non-valid query "code"
627  SD_DEBUG("SDEXT: FLASH: cmd 0x90 unknown info requested (%d), accesssing flash content instead." NL, addr & 0xFF);
628  break;
629  }
630  else
631  byte = flash[sector][addr];
632  flash_command = 0;
633  flash_bus_cycle = 0;
634  return byte;
635 }
636 
637 
638 static int flash_warn_programming = 1;
639 static void flash_wr_bus_op ( int sector, Uint16 addr, Uint8 data )
640 {
641  int idaddr = addr & 0x3FFF;
642  if (flash_command == 0x90)
643  flash_bus_cycle = 0; // autoselect mode does not have wr cycles more (only rd)
644  SD_DEBUG("SDEXT: FLASH: WR OP: sector %d addr %04Xh data %02Xh flash-bus-cycle %d flash-command %02Xh" NL, sector, addr, data, flash_bus_cycle, flash_command);
645  if (flash_wr_protect)
646  return; // write protection on flash, do not accept any write bus op
647  switch (flash_bus_cycle) {
648  case 0:
649  flash_command = 0; // invalidate command
650  if (data == 0xB0 || data == 0x30) {
651  //WARNING_WINDOW("SDEXT FLASH erase suspend/resume (cmd %02Xh) is not emulated yet :-(", data);
652  SD_DEBUG("SDEXT: FLASH: erase suspend/resume is not yet supported, ignoring ..." NL);
653  return; // well, erase suspend/resume is currently not supported :-(
654  }
655  if (data == 0xF0) {
656  SD_DEBUG("SDEXT: FLASH: reset command" NL);
657  return; // reset command
658  }
659  if (idaddr != 0xAAA || data != 0xAA) {
660  SD_DEBUG("SDEXT: FLASH: invalid command sequence at the beginning [bus_cycle=0]" NL);
661  return; // invalid cmd seq
662  }
663  flash_bus_cycle = 1;
664  return;
665  case 1:
666  if (idaddr != 0x555 || data != 0x55) { // invalid cmd seq
667  SD_DEBUG("SDEXT: FLASH: invalid command sequence [bus_cycle=1]" NL);
668  flash_bus_cycle = 0;
669  return;
670  }
671  flash_bus_cycle = 2;
672  return;
673  case 2:
674  if (idaddr != 0xAAA) {
675  SD_DEBUG("SDEXT: FLASH: invalid command sequence [bus_cycle=2]" NL);
676  flash_bus_cycle = 0; // invalid cmd seq
677  return;
678  }
679  if (data != 0x90 && data != 0x80 && data != 0xA0) {
680  SD_DEBUG("SDEXT: FLASH: unknown command [bus_cycle=2]" NL);
681  flash_bus_cycle = 0; // invalid cmd seq
682  return;
683  }
684  flash_command = data;
685  flash_bus_cycle = 3;
686  return;
687  case 3:
688  if (flash_command == 0xA0) { // program command!!!!
689  // flash programming allows only 1->0 on data bits, erase must be executed for 0->1
690  Uint8 oldbyte = flash[sector][addr];
691  Uint8 newbyte = oldbyte & data;
692  flash[sector][addr] = newbyte;
693  SD_DEBUG("SDEXT: FLASH: programming: sector %d address %04Xh data-req %02Xh, result %02Xh->%02Xh" NL, sector, addr, data, oldbyte, newbyte);
694  if (flash_warn_programming) {
695  WARNING_WINDOW("Flash programming detected! There will be no further warnings on more bytes.\nYou can safely ignore this warning.");
696  flash_warn_programming = 0;
697  }
698  flash_command = 0; // end of command
699  flash_bus_cycle = 0;
700  return;
701  }
702  // only flash command 0x80 can be left, 0x90 handled before "switch", 0xA0 just before ...
703  if (idaddr != 0xAAA || data != 0xAA) { // invalid cmd seq
704  SD_DEBUG("SDEXT: FLASH: invalid command sequence [bus_cycle=3]" NL);
705  flash_command = 0;
706  flash_bus_cycle = 0;
707  return;
708  }
709  flash_bus_cycle = 4;
710  return;
711  case 4: // only flash command 0x80 can get this far ...
712  if (idaddr != 0x555 || data != 0x55) { // invalid cmd seq
713  SD_DEBUG("SDEXT: FLASH: invalid command sequence [bus_cycle=4]" NL);
714  flash_command = 0;
715  flash_bus_cycle = 0;
716  return;
717  }
718  flash_bus_cycle = 5;
719  return;
720  case 5: // only flash command 0x80 can get this far ...
721  if (idaddr == 0xAAA && data == 0x10) { // CHIP ERASE!!!!
722  flash_erase(-1);
723  } else if (data == 0x30) {
724  flash_erase(sector);
725  }
726  flash_bus_cycle = 0; // end of erase command?
727  flash_command = 0;
728  return;
729  default:
730  FATAL("Invalid SDEXT FLASH bus cycle #%d on WR", flash_bus_cycle);
731  break;
732  }
733 }
734 
735 
736 
737 /* We expects all 4-7 seg reads/writes to be handled, as for re-flashing emu etc will need it!
738  Otherwise only segment 7 would be enough if flash is not emulated other than only "some kind of ROM". */
739 
740 Uint8 sdext_read_cart ( Uint16 addr )
741 {
742  SD_DEBUG("SDEXT: read cart @ %04X [CPU: seg=%02X, pc=%04X]" NL, addr, ports[0xB0 | (Z80_PC >> 14)], Z80_PC);
743  if (addr < 0xC000) {
744  Uint8 byte = flash_rd_bus_op(0, addr);
745  SD_DEBUG("SDEXT: reading base ROM, ROM offset = %04X, result = %02X" NL, addr, byte);
746  return byte;
747  }
748  if (addr < 0xE000) {
749  Uint8 byte;
750  addr = rom_page_ofs + (addr & 0x1FFF);
751  byte = flash_rd_bus_op(1, addr);
752  SD_DEBUG("SDEXT: reading paged ROM, ROM offset = %04X, result = %02X" NL, addr, byte);
753  return byte;
754  }
755  if (addr < 0xFC00) {
756  addr -= 0xE000;
757  SD_DEBUG("SDEXT: reading RAM at offset %04X, result = %02X" NL, addr, sd_ram_ext[addr]);
758  return sd_ram_ext[addr];
759  }
760  if (is_hs_read) {
761  // in HS-read (high speed read) mode, all the 0x3C00-0x3FFF acts as data _read_ register (but not for _write_!!!)
762  // also, there is a fundamental difference compared to "normal" read: each reads triggers SPI shifting in HS mode, but not in regular mode, there only write does that!
763  Uint8 old = _read_b; // HS-read initiates an SPI shift, but the result (AFAIK) is the previous state, as shifting needs time!
764  _spi_shifting_with_sd_card();
765  SD_DEBUG("SDEXT: REGIO: R: DATA: SPI data register HIGH SPEED read %02X [future byte %02X] [shited out was: %02X]" NL, old, _read_b, _write_b);
766  return old;
767  } else
768  switch (addr & 3) {
769  case 0:
770  // regular read (not HS) only gives the last shifted-in data, that's all!
771  SD_DEBUG("SDEXT: REGIO: R: DATA: SPI data register regular read %02X" NL, _read_b);
772  return _read_b;
773  case 1: // status reg: bit7=wp1, bit6=insert, bit5=changed (insert/changed=1: some of the cards not inserted or changed)
774  SD_DEBUG("SDEXT: REGIO: R: status" NL);
775  return status;
776  //return 0xFF - 32 + changed;
777  //return changed | 64;
778  case 2: // ROM pager [hmm not readble?!]
779  SD_DEBUG("SDEXT: REGIO: R: rom pager" NL);
780  return 0xFF;
781  return rom_page_ofs >> 8;
782  case 3: // HS read config is not readable?!]
783  SD_DEBUG("SDEXT: REGIO: R: HS config" NL);
784  return 0xFF;
785  return is_hs_read;
786  default:
787  FATAL("SDEXT: FATAL, unhandled (RD) case");
788  break;
789  }
790  FATAL("SDEXT: FATAL, control should not get here");
791  return 0; // make GCC happy :)
792 }
793 
794 
795 void sdext_write_cart ( Uint16 addr, Uint8 data )
796 {
797  SD_DEBUG("SDEXT: write cart @ %04X with %02X [CPU: seg=%02X, pc=%04X]" NL, addr, data, ports[0xB0 | (Z80_PC >> 14)], Z80_PC);
798  if (addr < 0xC000) { // segments 4-6, call flash WR emulation (sector 0, last 16K cannot be accessed by the EP ever!)
799  flash_wr_bus_op(0, addr, data);
800  return;
801  }
802  if (addr < 0xE000) { // pageable ROM (8K), call flash WR emulation with the right flash sector (1) and address offset in flash within the sector
803  flash_wr_bus_op(1, (addr & 0x1FFF) + rom_page_ofs, data);
804  return;
805  }
806  if (addr < 0xFC00) { // SDEXT's RAM (7K), writable
807  addr -= 0xE000;
808  SD_DEBUG("SDEXT: writing RAM at offset %04X" NL, addr);
809  sd_ram_ext[addr] = data;
810  return;
811  }
812  // rest 1K is the (memory mapped) I/O area
813  switch (addr & 3) {
814  case 0: // data register
815  SD_DEBUG("SDEXT: REGIO: W: DATA: SPI data register to %02X" NL, data);
816  if (!is_hs_read) _write_b = data;
817  _write_specified = data;
818  _spi_shifting_with_sd_card();
819  break;
820  case 1: // control register (bit7=CS0, bit6=CS1, bit5=clear change card signal
821  if (data & 32) // clear change signal
822  status &= 255 - 32;
823  cs0 = data & 128;
824  cs1 = data & 64;
825  SD_DEBUG("SDEXT: REGIO: W: control register to %02X CS0=%d CS1=%d" NL, data, cs0, cs1);
826  break;
827  case 2: // ROM pager register
828  rom_page_ofs = (data & 0xE0) << 8; // only high 3 bits count
829  SD_DEBUG("SDEXT: REGIO: W: paging ROM to %02X" NL, data);
830  break;
831  case 3: // HS (high speed) read mode to set: bit7=1
832  is_hs_read = data & 128;
833  _write_b = is_hs_read ? 0xFF : _write_specified;
834  SD_DEBUG("SDEXT: REGIO: W: HS read mode is %s" NL, is_hs_read ? "set" : "reset");
835  break;
836  default:
837  FATAL("SDEXT: FATAL, unhandled (WR) case");
838  break;
839  }
840 }
841 
842 #endif
z80ex_w_states
void z80ex_w_states(unsigned w_states)
Definition: z80ex.c:307
WARNING_WINDOW
#define WARNING_WINDOW(...)
Definition: xep128.h:115
INFO_WINDOW
#define INFO_WINDOW(...)
Definition: xep128.h:114
addr
int addr
Definition: dma65.c:81
app_pref_path
char * app_pref_path
Definition: configuration.c:84
m65-memcontent-generator.data
data
Definition: m65-memcontent-generator.py:119
Uint32
uint32_t Uint32
Definition: fat32.c:49
sdext.h
Uint8
uint8_t Uint8
Definition: fat32.c:51
open_emu_file
FILE * open_emu_file(const char *name, const char *mode, char *pathbuffer)
Definition: configuration.c:109
cpu.h
DEBUGPRINT
#define DEBUGPRINT(...)
Definition: emutools_basicdefs.h:171
ERROR_WINDOW
#define ERROR_WINDOW(...)
Definition: xep128.h:116
NL
#define NL
Definition: fat32.c:37
compress_sd_image.r
def r
Definition: compress_sd_image.py:76
memory
Uint8 memory[0x100000]
Definition: commodore_65.c:43
PRINTF_LLD
#define PRINTF_LLD
Definition: emutools_basicdefs.h:145
XEMUEXIT
#define XEMUEXIT(n)
Definition: emutools_basicdefs.h:246
blocks
Uint32 blocks
Definition: fat32.c:73
xep128.h
size
int size
Definition: inject.c:37
Z80_PC
#define Z80_PC
Definition: z80ex.h:121
status
enum @26::@29 status
configuration.h
Uint16
uint16_t Uint16
Definition: fat32.c:50
ERRSTR
#define ERRSTR()
Definition: enterprise128.h:56
QUESTION_WINDOW
#define QUESTION_WINDOW(items, msg)
Definition: xep128.h:124
DEBUG
#define DEBUG(...)
Definition: emutools_basicdefs.h:167
FATAL
#define FATAL(...)
Definition: xep128.h:117
sdimg_path
char sdimg_path[PATH_MAX+1]
SDCARD_IMG_FN
#define SDCARD_IMG_FN
Definition: enterprise128.h:29