forked from MEGA65/m65dbg
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmega65_ftp.c
More file actions
2336 lines (1981 loc) · 71 KB
/
Copy pathmega65_ftp.c
File metadata and controls
2336 lines (1981 loc) · 71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* vim: set expandtab shiftwidth=2 tabstop=2: */
/*
Upload one or more files to SD card on MEGA65
Copyright (C) 2018 Paul Gardner-Stephen
Portions Copyright (C) 2013 Serval Project Inc.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <sys/time.h>
#include <time.h>
#include <strings.h>
#include <string.h>
#include <ctype.h>
#include <sys/time.h>
#include <errno.h>
#include <getopt.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#if !defined(__CYGWIN__) && !defined(__APPLE__)
#include <dirent.h>
#else
#define NAME_MAX 260
#define DT_DIR 0
#define DT_REG 2
#define DT_UNKNOWN 0xffff
struct dirent
{
uint32_t __d_version; /* Used internally */
ino_t d_ino;
unsigned char d_type;
unsigned char __d_unused1[3];
__uint32_t d_off; // needed to add this
__uint32_t d_reclen; // needed to add this
__uint32_t __d_internal1;
char d_name[NAME_MAX + 1];
};
#endif
#include <stdio.h>
#include <readline/readline.h>
#include <readline/history.h>
#define DT_FREESLOT 0xff
#ifdef __APPLE__
static const int B1000000 = 1000000;
static const int B1500000 = 1500000;
static const int B2000000 = 2000000;
static const int B4000000 = 4000000;
#else
#ifndef __CYGWIN__
#include <sys/ioctl.h>
#include <linux/serial.h>
#endif
#endif
#ifdef __CYGWIN__
#define USLEEP_LCMD 300
#else
#define USLEEP_LCMD 4
#endif
#include "m65.h"
static time_t start_time=0;
long long start_usec=0;
extern int fd;
int open_file_system(void);
int download_slot(int sllot,char *dest_name);
int download_file(char *dest_name,char *local_name,int showClusters);
void show_clustermap(void);
void show_cluster(void);
void dump_sectors(void);
void restore_sectors(void);
void show_secinfo(void);
void show_mbrinfo(void);
void show_vbrinfo(void);
void poke_sector(void);
int show_directory(char *path);
int rename_file(char *name,char *dest_name);
int upload_file(char *name,char *dest_name);
int sdhc_check(void);
int read_sector(const unsigned int sector_number,unsigned char *buffer, int noCacheP);
int load_helper(void);
int stuff_keybuffer(char *s);
int get_pc(void);
unsigned char mega65_peek(unsigned int addr);
int fetch_ram(unsigned long address,unsigned int count,unsigned char *buffer);
int slow_write_ftp(int fd,char *d,int l,int preWait);
// Helper routine for faster sector writing
extern unsigned int helperroutine_len;
extern unsigned char helperroutine[];
int job_done;
int sectors_written;
int job_status_fresh=0;
static int osk_enable=0;
static int not_already_loaded=1;
static int halt=0;
// 0 = old hard coded monitor, 1= Kenneth's 65C02 based fancy monitor
static int new_monitor=0;
extern int saw_c64_mode;
extern int saw_c65_mode;
extern unsigned char viciv_regs[0x100];
static int mode_report=0;
extern int serial_speed;
extern char devSerial[];
extern char *bitstream;
unsigned char *sd_read_buffer=NULL;
int sd_read_offset=0;
int file_system_found=0;
unsigned int partition_start=0;
unsigned int partition_size=0;
unsigned char sectors_per_cluster=0;
unsigned int sectors_per_fat=0;
unsigned int data_sectors=0;
unsigned int first_cluster=0;
unsigned int fsinfo_sector=0;
unsigned int reserved_sectors=0;
unsigned int fat1_sector=0,fat2_sector=0,first_cluster_sector;
unsigned int syspart_start=0;
unsigned int syspart_size=0;
unsigned int syspart_freeze_area=0;
unsigned int syspart_freeze_program_size=0;
unsigned int syspart_slot_size=0;
unsigned int syspart_slot_count=0;
unsigned int syspart_slotdir_sectors=0;
unsigned int syspart_service_area=0;
unsigned int syspart_service_area_size=0;
unsigned int syspart_service_slot_size=0;
unsigned int syspart_service_slot_count=0;
unsigned int syspart_service_slotdir_sectors=0;
unsigned char mbr[512];
unsigned char fat_mbr[512];
unsigned char syspart_sector0[512];
unsigned char syspart_configsector[512];
int dirent_raw = 0;
int clustermap_start = 0;
int clustermap_count = 0;
int cluster_num = 0;
char secdump_file[256] = { 0 };
int secdump_start = 0;
int secdump_count = 0;
char secrestore_file[256] = { 0 };
int secrestore_start = 0;
int poke_secnum = 0;
int poke_offset = 0;
int poke_value = 0;
#ifdef WINDOWS
#include <windows.h>
#undef SLOW_FACTOR
#define SLOW_FACTOR 1
#define SLOW_FACTOR2 1
// #define do_usleep usleep
void do_usleep(__int64 usec)
{
HANDLE timer;
LARGE_INTEGER ft;
ft.QuadPart = -(10*usec); // Convert to 100 nanosecond interval, negative value indicates relative time
timer = CreateWaitableTimer(NULL, TRUE, NULL);
SetWaitableTimer(timer, &ft, 0, NULL, NULL, 0);
WaitForSingleObject(timer, INFINITE);
CloseHandle(timer);
}
#else
#include <termios.h>
#define do_usleep usleep
#endif
int sd_status_fresh=0;
unsigned char sd_status[16];
int process_char(unsigned char c,int live);
void usage_ftp(void)
{
fprintf(stderr,"MEGA65 cross-development tool for remote access to MEGA65 SD card via serial monitor interface\n");
fprintf(stderr,"usage: mega65_ftp [-l <serial port>] [-s <230400|2000000|4000000>] [-b bitstream] [[-c command] ...]\n");
fprintf(stderr," -l - Name of serial port to use, e.g., /dev/ttyUSB1\n");
fprintf(stderr," -s - Speed of serial port in bits per second. This must match what your bitstream uses.\n");
fprintf(stderr," (Older bitstream use 230400, and newer ones 2000000 or 4000000).\n");
fprintf(stderr," -b - Name of bitstream file to load.\n");
fprintf(stderr,"\n");
exit(-3);
}
int slow_write_ftp(int fd,char *d,int l,int preWait)
{
//printf("slow_write_ftp(%s)...\n", d);
// UART is at 2Mbps, but we need to allow enough time for a whole line of
// writing. 100 chars x 0.5usec = 500usec. So 1ms between chars should be ok.
// printf("Writing [%s]\n",d);
int i;
usleep(preWait);
for(i=0;i<l;i++)
{
int w=write(fd,&d[i],1);
while (w<1) {
usleep(1000);
w=write(fd,&d[i],1);
}
// Only control characters can cause us whole line delays,
if (d[i]<' ') { usleep(2000); } else usleep(0);
}
tcdrain(fd);
//printf("slow_write_ftp finished\n");
return 0;
}
#define READ_SECTOR_BUFFER_ADDRESS 0xFFD6e00
#define WRITE_SECTOR_BUFFER_ADDRESS 0xFFD6e00
int process_line(char *line,int live)
{
// printf("[%s]\n",line);
if (!live) return 0;
if (strstr(line,"ws h RECA8LHC")) {
if (!new_monitor) printf("Detected new-style UART monitor.\n");
new_monitor=1;
}
{
int addr;
int b[16];
int gotIt=0;
unsigned int v[4];
if (line[0]=='?') fprintf(stderr,"%s\n",line);
if (sscanf(line,":%x:%08x%08x%08x%08x",
&addr,&v[0],&v[1],&v[2],&v[3])==5) {
for(int i=0;i<16;i++) b[i]=(v[i/4]>>( (3-(i&3))*8)) &0xff;
gotIt=1;
}
if (sscanf(line," :%x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
&addr,
&b[0],&b[1],&b[2],&b[3],
&b[4],&b[5],&b[6],&b[7],
&b[8],&b[9],&b[10],&b[11],
&b[12],&b[13],&b[14],&b[15])==17) gotIt=1;
if (gotIt) {
// printf("Read memory @ $%04x\n",addr);
if (addr==0xf05) {
job_done=b[0];
sectors_written=b[1];
job_status_fresh=1;
}
if (addr==0xffd3680) {
// SD card status registers
for(int i=0;i<16;i++) sd_status[i]=b[i];
// dump_bytes(0,"SDcard status",sd_status,16);
sd_status_fresh=1;
}
else if(addr >= READ_SECTOR_BUFFER_ADDRESS && (addr <= (READ_SECTOR_BUFFER_ADDRESS + 0x200))) {
// Reading sector card buffer
int sector_offset=addr-READ_SECTOR_BUFFER_ADDRESS;
// printf("Read sector buffer 0x%03x - 0x%03x\n",sector_offset,sector_offset+15);
if (sector_offset<512) {
if (sd_read_buffer) {
for(int i=0;i<16;i++) sd_read_buffer[sector_offset+i]=b[i];
}
sd_read_offset=sector_offset+16;
}
}
}
}
return 0;
}
static char line[1024];
static int line_len=0;
int process_char(unsigned char c, int live)
{
//printf("char $%02x\n",c);
if (c=='\r'||c=='\n') {
line[line_len]=0;
if (line_len>0) process_line(line,live);
line_len=0;
} else {
if (line_len<1023) line[line_len++]=c;
}
return 0;
}
int process_waiting(int fd)
{
unsigned char read_buff[1024];
int b=read(fd,read_buff,1024);
while (b>0) {
int i;
for(i=0;i<b;i++) {
process_char(read_buff[i],1);
}
b=read(fd,read_buff,1024);
}
return 0;
}
void set_speed(int fd,int serial_speed)
{
struct termios t;
if (serial_speed==230400) {
if (cfsetospeed(&t, B230400)) perror("Failed to set output baud rate");
if (cfsetispeed(&t, B230400)) perror("Failed to set input baud rate");
} else if (serial_speed==2000000) {
if (cfsetospeed(&t, B2000000)) perror("Failed to set output baud rate");
if (cfsetispeed(&t, B2000000)) perror("Failed to set input baud rate");
} else if (serial_speed==1000000) {
if (cfsetospeed(&t, B1000000)) perror("Failed to set output baud rate");
if (cfsetispeed(&t, B1000000)) perror("Failed to set input baud rate");
} else if (serial_speed==1500000) {
if (cfsetospeed(&t, B1500000)) perror("Failed to set output baud rate");
if (cfsetispeed(&t, B1500000)) perror("Failed to set input baud rate");
}
#ifndef __CYGWIN__
else {
if (cfsetospeed(&t, B4000000)) perror("Failed to set output baud rate");
if (cfsetispeed(&t, B4000000)) perror("Failed to set input baud rate");
}
#endif
t.c_cflag &= ~PARENB;
t.c_cflag &= ~CSTOPB;
t.c_cflag &= ~CSIZE;
t.c_cflag &= ~CRTSCTS;
t.c_cflag |= CS8 | CLOCAL;
t.c_lflag &= ~(ICANON | ISIG | IEXTEN | ECHO | ECHOE);
t.c_iflag &= ~(BRKINT | ICRNL | IGNBRK | IGNCR | INLCR |
INPCK | ISTRIP | IXON | IXOFF | IXANY | PARMRK);
t.c_oflag &= ~OPOST;
if (tcsetattr(fd, TCSANOW, &t)) perror("Failed to set terminal parameters");
}
int queued_command_count=0;
#define MAX_QUEUED_COMMANDS 64
char *queued_commands[MAX_QUEUED_COMMANDS];
int queue_command(char *c)
{
if (queued_command_count<MAX_QUEUED_COMMANDS)
queued_commands[queued_command_count++]=c;
else {
fprintf(stderr,"ERROR: Too many commands queued via -c\n");
}
return 0;
}
unsigned char show_buf[512];
int show_sector(unsigned int sector_num)
{
if (read_sector(sector_num,show_buf,0)) {
printf("ERROR: Could not read sector %d ($%x)\n",sector_num,sector_num);
return -1;
}
dump_bytes(0,"Sector contents",show_buf,512);
return 0;
}
int execute_command(char *cmd)
{
unsigned int sector_num;
if (strlen(cmd)>1000) {
fprintf(stderr,"ERROR: Command too long\n");
return -1;
}
int slot=0;
char src[1024];
char dst[1024];
if ((!strcmp(cmd,"exit"))||(!strcmp(cmd,"quit"))) {
printf("Reseting MEGA65 and exiting.\n");
restart_hyppo();
return -1;
}
if (sscanf(cmd,"getslot %d %s",&slot,dst)==2) {
download_slot(slot,dst);
} else if (sscanf(cmd,"get %s %s",src,dst)==2) {
download_file(src,dst,0);
}
else if (sscanf(cmd,"put %s %s",src,dst)==2) {
upload_file(src,dst);
}
else if (sscanf(cmd,"rename %s %s",src,dst)==2) {
rename_file(src,dst);
}
else if (sscanf(cmd,"sector %d",§or_num)==1) {
show_sector(sector_num);
}
else if (sscanf(cmd,"sector $%x",§or_num)==1) {
show_sector(sector_num);
} else if (sscanf(cmd,"dirent_raw %d", &dirent_raw) == 1) {
printf("dirent_raw = %d\n", dirent_raw);
}
else if (sscanf(cmd,"dir %s",src)==1) {
show_directory(src);
}
else if (!strcmp(cmd,"dir")) {
show_directory("/");
}
else if (sscanf(cmd,"put %s",src)==1) {
char *dest=src;
// Set destination name to last element of source name, if no destination name provided
for(int i=0;src[i];i++) if (src[i]=='/') dest=&src[i+1];
upload_file(src,dest);
}
else if (sscanf(cmd,"get %s",src)==1) {
download_file(src,src,0);
} else if (sscanf(cmd, "clustermap %d %d", &clustermap_start, &clustermap_count)==2) {
show_clustermap();
} else if (sscanf(cmd, "clustermap %d", &clustermap_start)==1) {
clustermap_count = 1;
show_clustermap();
} else if (sscanf(cmd,"clusters %s",src)==1) {
download_file(src,src,1);
} else if (sscanf(cmd,"cluster %d", &cluster_num)==1) {
show_cluster();
} else if (sscanf(cmd,"secdump %s %d %d", secdump_file, &secdump_start, &secdump_count)==3) {
dump_sectors();
} else if (sscanf(cmd, "secrestore %s %d", secrestore_file, &secrestore_start)==2) {
restore_sectors();
} else if (!strcmp(cmd, "secinfo")) {
show_secinfo();
} else if (!strcmp(cmd, "mbrinfo")) {
show_mbrinfo();
} else if (!strcmp(cmd, "vbrinfo")) {
show_vbrinfo();
} else if (sscanf(cmd, "poke %d %d %d", &poke_secnum, &poke_offset, &poke_value)==3) {
poke_sector();
} else if (!strcasecmp(cmd,"help")) {
printf("MEGA65 File Transfer Program Command Reference:\n");
printf("\n");
printf("dir [directory] - show contents of current or specified directory.\n");
printf("put <file> [destination name] - upload file to SD card, and optionally rename it destination file.\n");
printf("get <file> [destination name] - download file from SD card, and optionally rename it destination file.\n");
printf("sector <num> - shows a hexdump of the 512-bytes within the specified sector.\n");
printf("clusters <decimal>|<$hex> - show cluster chain of specified file.\n");
printf("getslot <slot> <destination name> - download a freeze slot.\n");
printf("dirent_raw 0|1 - flag to hide/show 32-byte dump of directory entries.\n");
printf("clustermap <startidx> [<count>] - show cluster-map entries for specified range.\n");
printf("cluster <num> - dump the entire contents of this cluster.\n");
printf("secdump <filename> <startsec> <count> - dump the specified sector range to a file.\n");
printf("secrestore <filename> <startsec> - restore a dumped file back into the specified sector area.\n");
printf("secinfo - lists the locations of various useful sectors, for easy reference.\n");
printf("mbrinfo - lists the partitions specified in the MBR (sector 0)\n");
printf("vbrinfo - lists the VBR details of the main Mega65 partition\n");
printf("poke <sector> <offset> <val> - poke a value into a sector, at the desired offset.\n");
printf("exit - leave this programme.\n");
printf("quit - leave this programme.\n");
} else {
fprintf(stderr,"ERROR: Unknown command or invalid syntax. Type help for help.\n");
}
return 0;
}
int do_ftp(char* bitstream)
{
start_time=time(0);
start_usec=gettime_us();
#ifndef __APPLE__
#ifndef __CYGWIN__
// And also another way
struct serial_struct serial;
ioctl(fd, TIOCGSERIAL, &serial);
serial.flags |= ASYNC_LOW_LATENCY;
ioctl(fd, TIOCSSERIAL, &serial);
{
char latency_timer[1024];
int offset=strlen(devSerial);
while(offset&&devSerial[offset-1]!='/') offset--;
snprintf(latency_timer,1024,"/sys/bus/usb-serial/devices/%s/latency_timer",
&devSerial[offset]);
int new_latency=999;
FILE *f=fopen(latency_timer,"r");
if (f) { fscanf(f,"%d",&new_latency); fclose(f); }
if (new_latency==1) printf("Successfully set USB serial port to low-latency\n");
else printf("WARNING: Could not set USB serial port to low latency. Transfers will be (even) slower.\n");
}
#endif
#endif
// Load bitstream if file provided
#ifndef __CYGWIN__
if (bitstream && strlen(bitstream)) {
char cmd[1024];
snprintf(cmd,1024,"fpgajtag -a %s",bitstream);
fprintf(stderr,"%s\n",cmd);
system(cmd);
fprintf(stderr,"[T+%lldsec] Bitstream loaded\n",(long long)time(0)-start_time);
}
#endif
// Set higher speed on serial interface to improve throughput, and make sure
// we have reset.
set_speed(fd,2000000);
// slow_write_ftp(fd,"\r!\r",3,0); usleep(100000);
#ifndef __CYGWIN__
slow_write_ftp(fd,"\r+9\r",4,5000);
set_speed(fd,4000000);
#endif
// slow_write_ftp(fd,"\r!\r",3,0); usleep(100000);
// set_speed(fd,2000000);
// slow_write_ftp(fd,"\r+9\r",4,5000);
// set_speed(fd,4000000);
//stop_cpu();
load_helper();
sdhc_check();
if (!file_system_found) open_file_system();
char *cmd=NULL;
using_history();
while((cmd=readline("MEGA65 SD-card> "))!=NULL) {
int ret = execute_command(cmd);
if (ret == -1) // user quit ftp?
break;
add_history(cmd);
free(cmd);
}
slow_write_ftp(fd,"\r!\r",3,0); usleep(100000);
set_speed(fd,2000000);
#if !defined(__CYGWIN__) && !defined(__APPLE__)
serial.flags -= ASYNC_LOW_LATENCY;
ioctl(fd, TIOCSSERIAL, &serial);
#endif
printf("\n");
unsigned char read_buff[8192];
// flush out any serial data that occurred after the restart.
serialport_read(fd,read_buff,8192);
return 0;
}
void wait_for_sdready(void)
{
do {
// long long start=gettime_us();
// Ask for SD card status
sd_status[0]=0xff;
while(sd_status[0]&3) {
sd_status_fresh=0;
slow_write_ftp(fd,"mffd3680\r",strlen("mffd3680\r"),0);
while(!sd_status_fresh) process_waiting(fd);
if (sd_status[0]&3) {
// Send reset sequence
printf("SD card not yet ready, so reset it.\n");
slow_write_ftp(fd,"sffd3680 0\rsffd3680 1\r",strlen("sffd3680 0\rsffd3680 1\r"),2000);
sleep(1);
}
}
// printf("SD Card looks ready.\n");
// printf("wait_for_sdready() took %lld usec\n",gettime_us()-start);
} while(0);
return;
}
int wait_for_sdready_passive(void)
{
int retVal=0;
do {
// long long start=gettime_us();
int tries=16;
int sleep_time=1;
// Ask for SD card status
sd_status[0]=0xff;
process_waiting(fd);
while(sd_status[0]&3) {
sd_status_fresh=0;
slow_write_ftp(fd,"mffd3680\r",strlen("mffd3680\r"),0);
while(!sd_status_fresh) process_waiting(fd);
if ((sd_status[0]&3)==0x03)
{ // printf("SD card error 0x3 - failing\n");
tries--; if (tries) usleep(sleep_time); else {
retVal=-1; break; }
sleep_time*=2;
}
}
// printf("SD Card looks ready.\n");
// printf("wait_for_sdready_passive() took %lld usec\n",gettime_us()-start);
} while(0);
return retVal;
}
int sdhc=-1;
int onceOnly=1;
int sdhc_check(void)
{
unsigned char buffer[512];
sleep(1);
unsigned char read_buff[8192];
// flush out any serial data that occurred after the restart.
serialport_read(fd,read_buff,8192);
sdhc=-1;
//printf("sdhc_check()...\n");
int r0=read_sector(0,buffer,1);
//printf("r0=%d\n",r0);
int r1=read_sector(1,buffer,1);
//printf("r1=%d\n",r1);
int r200=read_sector(0x200,buffer,1);
//printf("r200=%d\n",r200);
// printf("%d %d %d\n",r0,r1,r200);
if (r0||r200) {
fprintf(stderr,"Could not detect SD/SDHC card\n");
exit(-3);
}
if (r1) sdhc=0; else sdhc=1;
if (sdhc) fprintf(stderr,"SD card is SDHC\n");
return sdhc;
}
extern unsigned char ram_cache[512*1024+255];
extern unsigned char ram_cache_valids[512*1024+255];
extern int ram_cache_initialised;
int load_helper(void)
{
int retVal=0;
do {
// Install helper routine
char cmd[1024];
detect_mode();
if ((!saw_c64_mode)) {
printf("Trying to switch to C64 mode...\n");
monitor_sync();
stuff_keybuffer("GO64\rY\r");
saw_c65_mode=0;
do_usleep(100000);
detect_mode();
while (!saw_c64_mode) {
fprintf(stderr,"WARNING: Failed to switch to C64 mode.\n");
monitor_sync();
stuff_keybuffer("GO64\rY\r");
do_usleep(100000);
detect_mode();
}
}
snprintf(cmd,1024,"t1\r");
slow_write_ftp(fd,cmd,strlen(cmd),500);
snprintf(cmd,1024,"l0801 %x\r",0x801+helperroutine_len-2);
slow_write_ftp(fd,cmd,strlen(cmd),500);
usleep(10000); // give uart monitor time to get ready for the data
process_waiting(fd);
int offset=2;
while(offset<helperroutine_len) {
int written=write(fd,&helperroutine[offset],helperroutine_len-offset);
if (written!=helperroutine_len) {
usleep(10000);
}
offset+=written;
}
slow_write_ftp(fd,"\r",1,500);
process_waiting(fd);
// Launch helper programme
sleep(1);
snprintf(cmd,1024,"g080d\r");
slow_write_ftp(fd,cmd,strlen(cmd),500);
snprintf(cmd,1024,"t0\r");
slow_write_ftp(fd,cmd,strlen(cmd),500);
printf("\nNOTE: Fast SD card access routine installed.\n");
} while(0);
return retVal;
}
int data_byte_count=0;
uint8_t queue_jobs=0;
uint16_t queue_addr=0xc001;
uint8_t queue_read_data[1024*1024];
uint32_t queue_read_len=0;
uint8_t queue_cmds[0x0fff];
uint8_t q_rle_count=0,q_raw_count=0;
void queue_data_decode(uint8_t v)
{
if (0) fprintf(stderr,"Decoding $%02x, rle_count=%d, raw_count=%d, data_byte_count=$%04x\n",
v,q_rle_count,q_raw_count,data_byte_count);
if (q_rle_count) {
// fprintf(stderr,"$%02x x byte $%02x\n",q_rle_count,v);
data_byte_count-=q_rle_count;
for(int i=0;i<q_rle_count;i++) {
if (queue_read_len<1024*1024) queue_read_data[queue_read_len++]=v;
}
q_rle_count=0;
} else if (q_raw_count) {
// fprintf(stderr,"Raw byte $%02x\n",v);
if (queue_read_len<1024*1024) queue_read_data[queue_read_len++]=v;
if (data_byte_count) data_byte_count--;
q_raw_count--;
} else {
// fprintf(stderr,"Data code $%02x\n",v);
if (v&0x80) {
q_rle_count=v&0x7f;
// fprintf(stderr,"RLE of $%02x bytes\n",q_rle_count);
} else {
q_raw_count=v&0x7f;
// fprintf(stderr,"$%02x raw bytes\n",q_raw_count);
}
}
}
void queue_add_job(uint8_t *j,int len)
{
int b;
uint8_t read_buff[8192];
b=1;
while(b>0) {
b=serialport_read(fd,read_buff,8192);
// if (b>0) dump_bytes(2,"Purged input",read_buff,b);
}
bcopy(j,&queue_cmds[queue_addr-0xc001],len);
queue_jobs++;
queue_addr+=len;
// printf("remote job queued.\n");
b=1;
while(b>0) {
b=serialport_read(fd,read_buff,8192);
// if (b>0) dump_bytes(2,"Purged input",read_buff,b);
}
}
void job_process_results(void)
{
printf("job_process_results()...\n");
long long now =gettime_us();
queue_read_len=0;
uint8_t buff[8192];
uint8_t recent[32];
data_byte_count=0;
int debug_rx=0;
while (1) {
int b=read(fd,buff,8192);
if (b<1) usleep(0);
if (b>0) if (debug_rx) dump_bytes(0,"jobresponse",buff,b);
for(int i=0;i<b;i++) {
// Keep rolling window of most recent chars for interpretting job
// results
if (data_byte_count)
{
queue_data_decode(buff[i]);
} else {
bcopy(&recent[1],&recent[0],30);
recent[30]=buff[i];
recent[31]=0;
if (!strncmp((char*)&recent[30-10],"FTBATCHDONE",11)) {
long long endtime =gettime_us();
if (debug_rx) printf("%lld: Saw end of batch job after %lld usec\n",endtime-start_usec,endtime-now);
// dump_bytes(0,"read data",queue_read_data,queue_read_len);
return;
}
if (!strncmp((char*)recent,"FTJOBDONE:",10)) {
int jn=atoi((char *)&recent[10]);
if (debug_rx) printf("Saw job #%d completion.\n",jn);
}
int j_addr,n;
uint32_t transfer_size;
int fn=sscanf((char*)recent,"FTJOBDATA:%x:%x:%n",&j_addr,&transfer_size,&n);
if (fn==2) {
if (debug_rx)
printf("Spotted job data: Reading $%x bytes of data, offset %d,"
" %02x %02x\n",transfer_size,n,
recent[n],recent[n+1]
);
q_rle_count=0; q_raw_count=0;
data_byte_count=transfer_size;
// Don't forget to process the bytes we have already injested
for(int k=n;k<=30;k++) {
if (data_byte_count) {
queue_data_decode(recent[k]);
}
}
}
}
}
}
}
void queue_execute(void)
{
char cmd[1024];
long long start = gettime_us();
// Push queued jobs in on go
sprintf(cmd,"l%x %x\r",0xc001,queue_addr);
slow_write_ftp(fd,cmd,strlen(cmd),0);
// give serial uart time to get ready
// (and make sure we end up in a different USB packet to the command)
usleep(1000);
serialport_write(fd,queue_cmds,queue_addr-0xc001);
// changing this from 3 to 6 seemed to help cygwin...
usleep(USLEEP_LCMD*(queue_addr-0xc001));
sprintf(cmd,"sc000 %x\r",queue_jobs);
slow_write_ftp(fd,cmd,strlen(cmd),0);
long long end = gettime_us();
printf("%lld Executing queued jobs (took %lld us to dispatch)\n",end-start_usec,end-start);
job_process_results();
queue_addr=0xc001;
queue_jobs=0;
}
uint32_t write_buffer_offset=0;
uint8_t write_data_buffer[65536];
uint32_t write_sector_numbers[65536/512];
uint8_t write_sector_count=0;
void queue_physical_write_sector(uint32_t sector_number,uint32_t mega65_address)
{
uint8_t job[9];
job[0]=0x02;
job[5]=sector_number>>0;
job[6]=sector_number>>8;
job[7]=sector_number>>16;
job[8]=sector_number>>24;
job[1]=mega65_address>>0;
job[2]=mega65_address>>8;
job[3]=mega65_address>>16;
job[4]=mega65_address>>24;
queue_add_job(job,9);
}
int execute_write_queue(void)
{
int retVal=0;
do {
char cmd[1024];
printf("Executing write queue with %d sectors in the queue (write_buffer_offset=$%08x)\n",
write_sector_count,write_buffer_offset);
snprintf(cmd,1024,"l%x %x\r",0x50000,(0x50000+write_buffer_offset)&0xffff);
// printf("CMD: '%s'\n",cmd);
slow_write_ftp(fd,cmd,strlen(cmd),1000);
usleep(5000);
int offset=0;
while (offset<write_buffer_offset)
{
int written=write(fd,&write_data_buffer[offset],write_buffer_offset-offset);
if (written>0) offset+=written;
else usleep(0);
}
usleep(USLEEP_LCMD*write_buffer_offset);
// XXX - Sort sector number order and merge consecutive writes into
// multi-sector writes would be a good idea here.
for(int i=0;i<write_sector_count;i++)
{
queue_physical_write_sector(write_sector_numbers[i],0x50000+(i<<9));
}
queue_execute();
// Reset write queue
write_buffer_offset=0;
write_sector_count=0;
} while (0);
return retVal;
}
void queue_write_sector(uint32_t sector_number, uint8_t *buffer)
{
// Merge writes to same sector
for (int i=0;i<write_sector_count;i++) {
if (sector_number==write_sector_numbers[i]) {
printf("Updating sector $%08x while in the write queue.\n",sector_number);
bcopy(buffer,&write_data_buffer[i<<9],512);
return;
}
}
// Purge pending jobs when they are banked up
// (only 32KB at a time, as the l command for fast pushing data
// can't do 64KB
if (write_buffer_offset>=32768) execute_write_queue();
bcopy(buffer,&write_data_buffer[write_buffer_offset],512);
write_buffer_offset+=512;
write_sector_numbers[write_sector_count]=sector_number;
write_sector_count++;
}
void queue_read_sector(uint32_t sector_number,uint32_t mega65_address)
{
uint8_t job[9];
job[0]=0x01;
job[5]=sector_number>>0;
job[6]=sector_number>>8;
job[7]=sector_number>>16;
job[8]=sector_number>>24;
job[1]=mega65_address>>0;
job[2]=mega65_address>>8;
job[3]=mega65_address>>16;
job[4]=mega65_address>>24;
queue_add_job(job,9);
}
void queue_read_mem(uint32_t mega65_address,uint32_t len)
{
uint8_t job[9];
job[0]=0x11;
job[1]=mega65_address>>0;
job[2]=mega65_address>>8;
job[3]=mega65_address>>16;
job[4]=mega65_address>>24;
job[5]=len>>0;
job[6]=len>>8;
job[7]=len>>16;
job[8]=len>>24;
queue_add_job(job,9);
}