-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
save.c
1053 lines (926 loc) · 31.6 KB
/
save.c
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
#include "global.h"
#include "agb_flash.h"
#include "gba/flash_internal.h"
#include "fieldmap.h"
#include "save.h"
#include "task.h"
#include "decompress.h"
#include "load_save.h"
#include "overworld.h"
#include "pokemon_storage_system.h"
#include "main.h"
#include "trainer_hill.h"
#include "link.h"
#include "constants/game_stat.h"
static u16 CalculateChecksum(void *, u16);
static bool8 ReadFlashSector(u8, struct SaveSector *);
static u8 GetSaveValidStatus(const struct SaveSectorLocation *);
static u8 CopySaveSlotData(u16, struct SaveSectorLocation *);
static u8 TryWriteSector(u8, u8 *);
static u8 HandleWriteSector(u16, const struct SaveSectorLocation *);
static u8 HandleReplaceSector(u16, const struct SaveSectorLocation *);
// Divide save blocks into individual chunks to be written to flash sectors
/*
* Sector Layout:
*
* Sectors 0 - 13: Save Slot 1
* Sectors 14 - 27: Save Slot 2
* Sectors 28 - 29: Hall of Fame
* Sector 30: Trainer Hill
* Sector 31: Recorded Battle
*
* There are two save slots for saving the player's game data. We alternate between
* them each time the game is saved, so that if the current save slot is corrupt,
* we can load the previous one. We also rotate the sectors in each save slot
* so that the same data is not always being written to the same sector. This
* might be done to reduce wear on the flash memory, but I'm not sure, since all
* 14 sectors get written anyway.
*
* See SECTOR_ID_* constants in save.h
*/
#define SAVEBLOCK_CHUNK(structure, chunkNum) \
{ \
chunkNum * SECTOR_DATA_SIZE, \
sizeof(structure) >= chunkNum * SECTOR_DATA_SIZE ? \
min(sizeof(structure) - chunkNum * SECTOR_DATA_SIZE, SECTOR_DATA_SIZE) : 0 \
}
struct
{
u16 offset;
u16 size;
} static const sSaveSlotLayout[NUM_SECTORS_PER_SLOT] =
{
SAVEBLOCK_CHUNK(struct SaveBlock2, 0), // SECTOR_ID_SAVEBLOCK2
SAVEBLOCK_CHUNK(struct SaveBlock1, 0), // SECTOR_ID_SAVEBLOCK1_START
SAVEBLOCK_CHUNK(struct SaveBlock1, 1),
SAVEBLOCK_CHUNK(struct SaveBlock1, 2),
SAVEBLOCK_CHUNK(struct SaveBlock1, 3), // SECTOR_ID_SAVEBLOCK1_END
SAVEBLOCK_CHUNK(struct PokemonStorage, 0), // SECTOR_ID_PKMN_STORAGE_START
SAVEBLOCK_CHUNK(struct PokemonStorage, 1),
SAVEBLOCK_CHUNK(struct PokemonStorage, 2),
SAVEBLOCK_CHUNK(struct PokemonStorage, 3),
SAVEBLOCK_CHUNK(struct PokemonStorage, 4),
SAVEBLOCK_CHUNK(struct PokemonStorage, 5),
SAVEBLOCK_CHUNK(struct PokemonStorage, 6),
SAVEBLOCK_CHUNK(struct PokemonStorage, 7),
SAVEBLOCK_CHUNK(struct PokemonStorage, 8), // SECTOR_ID_PKMN_STORAGE_END
};
// These will produce an error if a save struct is larger than the space
// alloted for it in the flash.
STATIC_ASSERT(sizeof(struct SaveBlock2) <= SECTOR_DATA_SIZE, SaveBlock2FreeSpace);
STATIC_ASSERT(sizeof(struct SaveBlock1) <= SECTOR_DATA_SIZE * (SECTOR_ID_SAVEBLOCK1_END - SECTOR_ID_SAVEBLOCK1_START + 1), SaveBlock1FreeSpace);
STATIC_ASSERT(sizeof(struct PokemonStorage) <= SECTOR_DATA_SIZE * (SECTOR_ID_PKMN_STORAGE_END - SECTOR_ID_PKMN_STORAGE_START + 1), PokemonStorageFreeSpace);
COMMON_DATA u16 gLastWrittenSector = 0;
COMMON_DATA u32 gLastSaveCounter = 0;
COMMON_DATA u16 gLastKnownGoodSector = 0;
COMMON_DATA u32 gDamagedSaveSectors = 0;
COMMON_DATA u32 gSaveCounter = 0;
COMMON_DATA struct SaveSector *gReadWriteSector = NULL; // Pointer to a buffer for reading/writing a sector
COMMON_DATA u16 gIncrementalSectorId = 0;
COMMON_DATA u16 gSaveUnusedVar = 0;
COMMON_DATA u16 gSaveFileStatus = 0;
COMMON_DATA void (*gGameContinueCallback)(void) = NULL;
COMMON_DATA struct SaveSectorLocation gRamSaveSectorLocations[NUM_SECTORS_PER_SLOT] = {0};
COMMON_DATA u16 gSaveUnusedVar2 = 0;
COMMON_DATA u16 gSaveAttemptStatus = 0;
EWRAM_DATA struct SaveSector gSaveDataBuffer = {0}; // Buffer used for reading/writing sectors
EWRAM_DATA static u8 sUnusedVar = 0;
void ClearSaveData(void)
{
u16 i;
// Clear the full save two sectors at a time
for (i = 0; i < SECTORS_COUNT / 2; i++)
{
EraseFlashSector(i);
EraseFlashSector(i + SECTORS_COUNT / 2);
}
}
void Save_ResetSaveCounters(void)
{
gSaveCounter = 0;
gLastWrittenSector = 0;
gDamagedSaveSectors = 0;
}
static bool32 SetDamagedSectorBits(u8 op, u8 sectorId)
{
bool32 retVal = FALSE;
switch (op)
{
case ENABLE:
gDamagedSaveSectors |= (1 << sectorId);
break;
case DISABLE:
gDamagedSaveSectors &= ~(1 << sectorId);
break;
case CHECK: // unused
if (gDamagedSaveSectors & (1 << sectorId))
retVal = TRUE;
break;
}
return retVal;
}
static u8 WriteSaveSectorOrSlot(u16 sectorId, const struct SaveSectorLocation *locations)
{
u32 status;
u16 i;
gReadWriteSector = &gSaveDataBuffer;
if (sectorId != FULL_SAVE_SLOT)
{
// A sector was specified, just write that sector.
// This is never reached, FULL_SAVE_SLOT is always used instead.
status = HandleWriteSector(sectorId, locations);
}
else
{
// No sector was specified, write full save slot.
gLastKnownGoodSector = gLastWrittenSector; // backup the current written sector before attempting to write.
gLastSaveCounter = gSaveCounter;
gLastWrittenSector++;
gLastWrittenSector = gLastWrittenSector % NUM_SECTORS_PER_SLOT;
gSaveCounter++;
status = SAVE_STATUS_OK;
for (i = 0; i < NUM_SECTORS_PER_SLOT; i++)
HandleWriteSector(i, locations);
if (gDamagedSaveSectors)
{
// At least one sector save failed
status = SAVE_STATUS_ERROR;
gLastWrittenSector = gLastKnownGoodSector;
gSaveCounter = gLastSaveCounter;
}
}
return status;
}
static u8 HandleWriteSector(u16 sectorId, const struct SaveSectorLocation *locations)
{
u16 i;
u16 sector;
u8 *data;
u16 size;
// Adjust sector id for current save slot
sector = sectorId + gLastWrittenSector;
sector %= NUM_SECTORS_PER_SLOT;
sector += NUM_SECTORS_PER_SLOT * (gSaveCounter % NUM_SAVE_SLOTS);
// Get current save data
data = locations[sectorId].data;
size = locations[sectorId].size;
// Clear temp save sector
for (i = 0; i < SECTOR_SIZE; i++)
((u8 *)gReadWriteSector)[i] = 0;
// Set footer data
gReadWriteSector->id = sectorId;
gReadWriteSector->signature = SECTOR_SIGNATURE;
gReadWriteSector->counter = gSaveCounter;
// Copy current data to temp buffer for writing
for (i = 0; i < size; i++)
gReadWriteSector->data[i] = data[i];
gReadWriteSector->checksum = CalculateChecksum(data, size);
return TryWriteSector(sector, gReadWriteSector->data);
}
static u8 HandleWriteSectorNBytes(u8 sectorId, u8 *data, u16 size)
{
u16 i;
struct SaveSector *sector = &gSaveDataBuffer;
// Clear temp save sector
for (i = 0; i < SECTOR_SIZE; i++)
((u8 *)sector)[i] = 0;
sector->signature = SECTOR_SIGNATURE;
// Copy data to temp buffer for writing
for (i = 0; i < size; i++)
sector->data[i] = data[i];
sector->id = CalculateChecksum(data, size); // though this appears to be incorrect, it might be some sector checksum instead of a whole save checksum and only appears to be relevent to HOF data, if used.
return TryWriteSector(sectorId, sector->data);
}
static u8 TryWriteSector(u8 sector, u8 *data)
{
if (ProgramFlashSectorAndVerify(sector, data)) // is damaged?
{
// Failed
SetDamagedSectorBits(ENABLE, sector);
return SAVE_STATUS_ERROR;
}
else
{
// Succeeded
SetDamagedSectorBits(DISABLE, sector);
return SAVE_STATUS_OK;
}
}
static u32 RestoreSaveBackupVarsAndIncrement(const struct SaveSectorLocation *locations)
{
gReadWriteSector = &gSaveDataBuffer;
gLastKnownGoodSector = gLastWrittenSector;
gLastSaveCounter = gSaveCounter;
gLastWrittenSector++;
gLastWrittenSector %= NUM_SECTORS_PER_SLOT;
gSaveCounter++;
gIncrementalSectorId = 0;
gDamagedSaveSectors = 0;
return 0;
}
static u32 RestoreSaveBackupVars(const struct SaveSectorLocation *locations)
{
gReadWriteSector = &gSaveDataBuffer;
gLastKnownGoodSector = gLastWrittenSector;
gLastSaveCounter = gSaveCounter;
gIncrementalSectorId = 0;
gDamagedSaveSectors = 0;
return 0;
}
static u8 HandleWriteIncrementalSector(u16 numSectors, const struct SaveSectorLocation *locations)
{
u8 status;
if (gIncrementalSectorId < numSectors - 1)
{
status = SAVE_STATUS_OK;
HandleWriteSector(gIncrementalSectorId, locations);
gIncrementalSectorId++;
if (gDamagedSaveSectors)
{
status = SAVE_STATUS_ERROR;
gLastWrittenSector = gLastKnownGoodSector;
gSaveCounter = gLastSaveCounter;
}
}
else
{
// Exceeded max sector, finished
status = SAVE_STATUS_ERROR;
}
return status;
}
static u8 HandleReplaceSectorAndVerify(u16 sectorId, const struct SaveSectorLocation *locations)
{
u8 status = SAVE_STATUS_OK;
HandleReplaceSector(sectorId - 1, locations);
if (gDamagedSaveSectors)
{
status = SAVE_STATUS_ERROR;
gLastWrittenSector = gLastKnownGoodSector;
gSaveCounter = gLastSaveCounter;
}
return status;
}
// Similar to HandleWriteSector, but fully erases the sector first, and skips writing the first signature byte
static u8 HandleReplaceSector(u16 sectorId, const struct SaveSectorLocation *locations)
{
u16 i;
u16 sector;
u8 *data;
u16 size;
u8 status;
// Adjust sector id for current save slot
sector = sectorId + gLastWrittenSector;
sector %= NUM_SECTORS_PER_SLOT;
sector += NUM_SECTORS_PER_SLOT * (gSaveCounter % NUM_SAVE_SLOTS);
// Get current save data
data = locations[sectorId].data;
size = locations[sectorId].size;
// Clear temp save sector.
for (i = 0; i < SECTOR_SIZE; i++)
((u8 *)gReadWriteSector)[i] = 0;
// Set footer data
gReadWriteSector->id = sectorId;
gReadWriteSector->signature = SECTOR_SIGNATURE;
gReadWriteSector->counter = gSaveCounter;
// Copy current data to temp buffer for writing
for (i = 0; i < size; i++)
gReadWriteSector->data[i] = data[i];
gReadWriteSector->checksum = CalculateChecksum(data, size);
// Erase old save data
EraseFlashSector(sector);
status = SAVE_STATUS_OK;
// Write new save data up to signature field
for (i = 0; i < SECTOR_SIGNATURE_OFFSET; i++)
{
if (ProgramFlashByte(sector, i, ((u8 *)gReadWriteSector)[i]))
{
status = SAVE_STATUS_ERROR;
break;
}
}
if (status == SAVE_STATUS_ERROR)
{
// Writing save data failed
SetDamagedSectorBits(ENABLE, sector);
return SAVE_STATUS_ERROR;
}
else
{
// Writing save data succeeded, write signature and counter
status = SAVE_STATUS_OK;
// Write signature (skipping the first byte) and counter fields.
// The byte of signature that is skipped is instead written by WriteSectorSignatureByte or WriteSectorSignatureByte_NoOffset
for (i = 0; i < SECTOR_SIZE - (SECTOR_SIGNATURE_OFFSET + 1); i++)
{
if (ProgramFlashByte(sector, SECTOR_SIGNATURE_OFFSET + 1 + i, ((u8 *)gReadWriteSector)[SECTOR_SIGNATURE_OFFSET + 1 + i]))
{
status = SAVE_STATUS_ERROR;
break;
}
}
if (status == SAVE_STATUS_ERROR)
{
// Writing signature/counter failed
SetDamagedSectorBits(ENABLE, sector);
return SAVE_STATUS_ERROR;
}
else
{
// Succeeded
SetDamagedSectorBits(DISABLE, sector);
return SAVE_STATUS_OK;
}
}
}
static u8 WriteSectorSignatureByte_NoOffset(u16 sectorId, const struct SaveSectorLocation *locations)
{
// Adjust sector id for current save slot
// This first line lacking -1 is the only difference from WriteSectorSignatureByte
u16 sector = sectorId + gLastWrittenSector;
sector %= NUM_SECTORS_PER_SLOT;
sector += NUM_SECTORS_PER_SLOT * (gSaveCounter % NUM_SAVE_SLOTS);
// Write just the first byte of the signature field, which was skipped by HandleReplaceSector
if (ProgramFlashByte(sector, SECTOR_SIGNATURE_OFFSET, SECTOR_SIGNATURE & 0xFF))
{
// Sector is damaged, so enable the bit in gDamagedSaveSectors and restore the last written sector and save counter.
SetDamagedSectorBits(ENABLE, sector);
gLastWrittenSector = gLastKnownGoodSector;
gSaveCounter = gLastSaveCounter;
return SAVE_STATUS_ERROR;
}
else
{
// Succeeded
SetDamagedSectorBits(DISABLE, sector);
return SAVE_STATUS_OK;
}
}
static u8 CopySectorSignatureByte(u16 sectorId, const struct SaveSectorLocation *locations)
{
// Adjust sector id for current save slot
u16 sector = sectorId + gLastWrittenSector - 1;
sector %= NUM_SECTORS_PER_SLOT;
sector += NUM_SECTORS_PER_SLOT * (gSaveCounter % NUM_SAVE_SLOTS);
// Copy just the first byte of the signature field from the read/write buffer
if (ProgramFlashByte(sector, SECTOR_SIGNATURE_OFFSET, ((u8 *)gReadWriteSector)[SECTOR_SIGNATURE_OFFSET]))
{
// Sector is damaged, so enable the bit in gDamagedSaveSectors and restore the last written sector and save counter.
SetDamagedSectorBits(ENABLE, sector);
gLastWrittenSector = gLastKnownGoodSector;
gSaveCounter = gLastSaveCounter;
return SAVE_STATUS_ERROR;
}
else
{
// Succeeded
SetDamagedSectorBits(DISABLE, sector);
return SAVE_STATUS_OK;
}
}
static u8 WriteSectorSignatureByte(u16 sectorId, const struct SaveSectorLocation *locations)
{
// Adjust sector id for current save slot
u16 sector = sectorId + gLastWrittenSector - 1;
sector %= NUM_SECTORS_PER_SLOT;
sector += NUM_SECTORS_PER_SLOT * (gSaveCounter % NUM_SAVE_SLOTS);
// Write just the first byte of the signature field, which was skipped by HandleReplaceSector
if (ProgramFlashByte(sector, SECTOR_SIGNATURE_OFFSET, SECTOR_SIGNATURE & 0xFF))
{
// Sector is damaged, so enable the bit in gDamagedSaveSectors and restore the last written sector and save counter.
SetDamagedSectorBits(ENABLE, sector);
gLastWrittenSector = gLastKnownGoodSector;
gSaveCounter = gLastSaveCounter;
return SAVE_STATUS_ERROR;
}
else
{
// Succeeded
SetDamagedSectorBits(DISABLE, sector);
return SAVE_STATUS_OK;
}
}
static u8 TryLoadSaveSlot(u16 sectorId, struct SaveSectorLocation *locations)
{
u8 status;
gReadWriteSector = &gSaveDataBuffer;
if (sectorId != FULL_SAVE_SLOT)
{
// This function may not be used with a specific sector id
status = SAVE_STATUS_ERROR;
}
else
{
status = GetSaveValidStatus(locations);
CopySaveSlotData(FULL_SAVE_SLOT, locations);
}
return status;
}
// sectorId arg is ignored, this always reads the full save slot
static u8 CopySaveSlotData(u16 sectorId, struct SaveSectorLocation *locations)
{
u16 i;
u16 checksum;
u16 slotOffset = NUM_SECTORS_PER_SLOT * (gSaveCounter % NUM_SAVE_SLOTS);
u16 id;
for (i = 0; i < NUM_SECTORS_PER_SLOT; i++)
{
ReadFlashSector(i + slotOffset, gReadWriteSector);
id = gReadWriteSector->id;
if (id == 0)
gLastWrittenSector = i;
checksum = CalculateChecksum(gReadWriteSector->data, locations[id].size);
// Only copy data for sectors whose signature and checksum fields are correct
if (gReadWriteSector->signature == SECTOR_SIGNATURE && gReadWriteSector->checksum == checksum)
{
u16 j;
for (j = 0; j < locations[id].size; j++)
((u8 *)locations[id].data)[j] = gReadWriteSector->data[j];
}
}
return SAVE_STATUS_OK;
}
static u8 GetSaveValidStatus(const struct SaveSectorLocation *locations)
{
u16 i;
u16 checksum;
u32 saveSlot1Counter = 0;
u32 saveSlot2Counter = 0;
u32 validSectorFlags = 0;
bool8 signatureValid = FALSE;
u8 saveSlot1Status;
u8 saveSlot2Status;
// Check save slot 1
for (i = 0; i < NUM_SECTORS_PER_SLOT; i++)
{
ReadFlashSector(i, gReadWriteSector);
if (gReadWriteSector->signature == SECTOR_SIGNATURE)
{
signatureValid = TRUE;
checksum = CalculateChecksum(gReadWriteSector->data, locations[gReadWriteSector->id].size);
if (gReadWriteSector->checksum == checksum)
{
saveSlot1Counter = gReadWriteSector->counter;
validSectorFlags |= 1 << gReadWriteSector->id;
}
}
}
if (signatureValid)
{
if (validSectorFlags == (1 << NUM_SECTORS_PER_SLOT) - 1)
saveSlot1Status = SAVE_STATUS_OK;
else
saveSlot1Status = SAVE_STATUS_ERROR;
}
else
{
// No sectors in slot 1 have the correct signature, treat it as empty
saveSlot1Status = SAVE_STATUS_EMPTY;
}
validSectorFlags = 0;
signatureValid = FALSE;
// Check save slot 2
for (i = 0; i < NUM_SECTORS_PER_SLOT; i++)
{
ReadFlashSector(i + NUM_SECTORS_PER_SLOT, gReadWriteSector);
if (gReadWriteSector->signature == SECTOR_SIGNATURE)
{
signatureValid = TRUE;
checksum = CalculateChecksum(gReadWriteSector->data, locations[gReadWriteSector->id].size);
if (gReadWriteSector->checksum == checksum)
{
saveSlot2Counter = gReadWriteSector->counter;
validSectorFlags |= 1 << gReadWriteSector->id;
}
}
}
if (signatureValid)
{
if (validSectorFlags == (1 << NUM_SECTORS_PER_SLOT) - 1)
saveSlot2Status = SAVE_STATUS_OK;
else
saveSlot2Status = SAVE_STATUS_ERROR;
}
else
{
// No sectors in slot 2 have the correct signature, treat it as empty.
saveSlot2Status = SAVE_STATUS_EMPTY;
}
if (saveSlot1Status == SAVE_STATUS_OK && saveSlot2Status == SAVE_STATUS_OK)
{
if ((saveSlot1Counter == -1 && saveSlot2Counter == 0)
|| (saveSlot1Counter == 0 && saveSlot2Counter == -1))
{
if ((unsigned)(saveSlot1Counter + 1) < (unsigned)(saveSlot2Counter + 1))
gSaveCounter = saveSlot2Counter;
else
gSaveCounter = saveSlot1Counter;
}
else
{
if (saveSlot1Counter < saveSlot2Counter)
gSaveCounter = saveSlot2Counter;
else
gSaveCounter = saveSlot1Counter;
}
return SAVE_STATUS_OK;
}
// One or both save slots are not OK
if (saveSlot1Status == SAVE_STATUS_OK)
{
gSaveCounter = saveSlot1Counter;
if (saveSlot2Status == SAVE_STATUS_ERROR)
return SAVE_STATUS_ERROR; // Slot 2 errored
return SAVE_STATUS_OK; // Slot 1 is OK, slot 2 is empty
}
if (saveSlot2Status == SAVE_STATUS_OK)
{
gSaveCounter = saveSlot2Counter;
if (saveSlot1Status == SAVE_STATUS_ERROR)
return SAVE_STATUS_ERROR; // Slot 1 errored
return SAVE_STATUS_OK; // Slot 2 is OK, slot 1 is empty
}
// Neither slot is OK, check if both are empty
if (saveSlot1Status == SAVE_STATUS_EMPTY
&& saveSlot2Status == SAVE_STATUS_EMPTY)
{
gSaveCounter = 0;
gLastWrittenSector = 0;
return SAVE_STATUS_EMPTY;
}
// Both slots errored
gSaveCounter = 0;
gLastWrittenSector = 0;
return SAVE_STATUS_CORRUPT;
}
static u8 TryLoadSaveSector(u8 sectorId, u8 *data, u16 size)
{
u16 i;
struct SaveSector *sector = &gSaveDataBuffer;
ReadFlashSector(sectorId, sector);
if (sector->signature == SECTOR_SIGNATURE)
{
u16 checksum = CalculateChecksum(sector->data, size);
if (sector->id == checksum)
{
// Signature and checksum are correct, copy data
for (i = 0; i < size; i++)
data[i] = sector->data[i];
return SAVE_STATUS_OK;
}
else
{
// Incorrect checksum
return SAVE_STATUS_CORRUPT;
}
}
else
{
// Incorrect signature value
return SAVE_STATUS_EMPTY;
}
}
// Return value always ignored
static bool8 ReadFlashSector(u8 sectorId, struct SaveSector *sector)
{
ReadFlash(sectorId, 0, sector->data, SECTOR_SIZE);
return TRUE;
}
static u16 CalculateChecksum(void *data, u16 size)
{
u16 i;
u32 checksum = 0;
for (i = 0; i < (size / 4); i++)
{
checksum += *((u32 *)data);
data += sizeof(u32);
}
return ((checksum >> 16) + checksum);
}
static void UpdateSaveAddresses(void)
{
int i = SECTOR_ID_SAVEBLOCK2;
gRamSaveSectorLocations[i].data = (void *)(gSaveBlock2Ptr) + sSaveSlotLayout[i].offset;
gRamSaveSectorLocations[i].size = sSaveSlotLayout[i].size;
for (i = SECTOR_ID_SAVEBLOCK1_START; i <= SECTOR_ID_SAVEBLOCK1_END; i++)
{
gRamSaveSectorLocations[i].data = (void *)(gSaveBlock1Ptr) + sSaveSlotLayout[i].offset;
gRamSaveSectorLocations[i].size = sSaveSlotLayout[i].size;
}
for (; i <= SECTOR_ID_PKMN_STORAGE_END; i++) //setting i to SECTOR_ID_PKMN_STORAGE_START does not match
{
gRamSaveSectorLocations[i].data = (void *)(gPokemonStoragePtr) + sSaveSlotLayout[i].offset;
gRamSaveSectorLocations[i].size = sSaveSlotLayout[i].size;
}
}
u8 HandleSavingData(u8 saveType)
{
u8 i;
u32 *backupVar = gTrainerHillVBlankCounter;
u8 *tempAddr;
gTrainerHillVBlankCounter = NULL;
UpdateSaveAddresses();
switch (saveType)
{
case SAVE_HALL_OF_FAME_ERASE_BEFORE:
// Unused. Erases the special save sectors (HOF, Trainer Hill, Recorded Battle)
// before overwriting HOF.
for (i = SECTOR_ID_HOF_1; i < SECTORS_COUNT; i++)
EraseFlashSector(i);
// fallthrough
case SAVE_HALL_OF_FAME:
if (GetGameStat(GAME_STAT_ENTERED_HOF) < 999)
IncrementGameStat(GAME_STAT_ENTERED_HOF);
// Write the full save slot first
CopyPartyAndObjectsToSave();
WriteSaveSectorOrSlot(FULL_SAVE_SLOT, gRamSaveSectorLocations);
// Save the Hall of Fame
tempAddr = gDecompressionBuffer;
HandleWriteSectorNBytes(SECTOR_ID_HOF_1, tempAddr, SECTOR_DATA_SIZE);
HandleWriteSectorNBytes(SECTOR_ID_HOF_2, tempAddr + SECTOR_DATA_SIZE, SECTOR_DATA_SIZE);
break;
case SAVE_NORMAL:
default:
CopyPartyAndObjectsToSave();
WriteSaveSectorOrSlot(FULL_SAVE_SLOT, gRamSaveSectorLocations);
break;
case SAVE_LINK:
case SAVE_EREADER: // Dummied, now duplicate of SAVE_LINK
// Used by link / Battle Frontier
// Write only SaveBlocks 1 and 2 (skips the PC)
CopyPartyAndObjectsToSave();
for(i = SECTOR_ID_SAVEBLOCK2; i <= SECTOR_ID_SAVEBLOCK1_END; i++)
HandleReplaceSector(i, gRamSaveSectorLocations);
for(i = SECTOR_ID_SAVEBLOCK2; i <= SECTOR_ID_SAVEBLOCK1_END; i++)
WriteSectorSignatureByte_NoOffset(i, gRamSaveSectorLocations);
break;
case SAVE_OVERWRITE_DIFFERENT_FILE:
// Erase Hall of Fame
for (i = SECTOR_ID_HOF_1; i < SECTORS_COUNT; i++)
EraseFlashSector(i);
// Overwrite save slot
CopyPartyAndObjectsToSave();
WriteSaveSectorOrSlot(FULL_SAVE_SLOT, gRamSaveSectorLocations);
break;
}
gTrainerHillVBlankCounter = backupVar;
return 0;
}
u8 TrySavingData(u8 saveType)
{
if (gFlashMemoryPresent != TRUE)
{
gSaveAttemptStatus = SAVE_STATUS_ERROR;
return SAVE_STATUS_ERROR;
}
HandleSavingData(saveType);
if (!gDamagedSaveSectors)
{
gSaveAttemptStatus = SAVE_STATUS_OK;
return SAVE_STATUS_OK;
}
else
{
DoSaveFailedScreen(saveType);
gSaveAttemptStatus = SAVE_STATUS_ERROR;
return SAVE_STATUS_ERROR;
}
}
bool8 LinkFullSave_Init(void)
{
if (gFlashMemoryPresent != TRUE)
return TRUE;
UpdateSaveAddresses();
CopyPartyAndObjectsToSave();
RestoreSaveBackupVarsAndIncrement(gRamSaveSectorLocations);
return FALSE;
}
bool8 LinkFullSave_WriteSector(void)
{
u8 status = HandleWriteIncrementalSector(NUM_SECTORS_PER_SLOT, gRamSaveSectorLocations);
if (gDamagedSaveSectors)
DoSaveFailedScreen(SAVE_NORMAL);
// In this case "error" either means that an actual error was encountered
// or that the given max sector has been reached (meaning it has finished successfully).
// If there was an actual error the save failed screen above will also be shown.
if (status == SAVE_STATUS_ERROR)
return TRUE;
else
return FALSE;
}
bool8 LinkFullSave_ReplaceLastSector(void)
{
HandleReplaceSectorAndVerify(NUM_SECTORS_PER_SLOT, gRamSaveSectorLocations);
if (gDamagedSaveSectors)
DoSaveFailedScreen(SAVE_NORMAL);
return FALSE;
}
bool8 LinkFullSave_SetLastSectorSignature(void)
{
CopySectorSignatureByte(NUM_SECTORS_PER_SLOT, gRamSaveSectorLocations);
if (gDamagedSaveSectors)
DoSaveFailedScreen(SAVE_NORMAL);
return FALSE;
}
u8 WriteSaveBlock2(void)
{
if (gFlashMemoryPresent != TRUE)
return TRUE;
UpdateSaveAddresses();
CopyPartyAndObjectsToSave();
RestoreSaveBackupVars(gRamSaveSectorLocations);
// Because RestoreSaveBackupVars is called immediately prior, gIncrementalSectorId will always be 0 below,
// so this function only saves the first sector (SECTOR_ID_SAVEBLOCK2)
HandleReplaceSectorAndVerify(gIncrementalSectorId + 1, gRamSaveSectorLocations);
return FALSE;
}
// Used in conjunction with WriteSaveBlock2 to write both for certain link saves.
// This will be called repeatedly in a task, writing each sector of SaveBlock1 incrementally.
// It returns TRUE when finished.
bool8 WriteSaveBlock1Sector(void)
{
u8 finished = FALSE;
u16 sectorId = ++gIncrementalSectorId; // Because WriteSaveBlock2 will have been called prior, this will be SECTOR_ID_SAVEBLOCK1_START
if (sectorId <= SECTOR_ID_SAVEBLOCK1_END)
{
// Write a single sector of SaveBlock1
HandleReplaceSectorAndVerify(gIncrementalSectorId + 1, gRamSaveSectorLocations);
WriteSectorSignatureByte(sectorId, gRamSaveSectorLocations);
}
else
{
// Beyond SaveBlock1, don't write the sector.
// Does write 1 byte of the next sector's signature field, but as these
// are the same for all valid sectors it doesn't matter.
WriteSectorSignatureByte(sectorId, gRamSaveSectorLocations);
finished = TRUE;
}
if (gDamagedSaveSectors)
DoSaveFailedScreen(SAVE_LINK);
return finished;
}
u8 LoadGameSave(u8 saveType)
{
u8 status;
if (gFlashMemoryPresent != TRUE)
{
gSaveFileStatus = SAVE_STATUS_NO_FLASH;
return SAVE_STATUS_ERROR;
}
UpdateSaveAddresses();
switch (saveType)
{
case SAVE_NORMAL:
default:
status = TryLoadSaveSlot(FULL_SAVE_SLOT, gRamSaveSectorLocations);
CopyPartyAndObjectsFromSave();
gSaveFileStatus = status;
gGameContinueCallback = 0;
break;
case SAVE_HALL_OF_FAME:
status = TryLoadSaveSector(SECTOR_ID_HOF_1, gDecompressionBuffer, SECTOR_DATA_SIZE);
if (status == SAVE_STATUS_OK)
status = TryLoadSaveSector(SECTOR_ID_HOF_2, &gDecompressionBuffer[SECTOR_DATA_SIZE], SECTOR_DATA_SIZE);
break;
}
return status;
}
u16 GetSaveBlocksPointersBaseOffset(void)
{
u16 i, slotOffset;
struct SaveSector* sector;
sector = gReadWriteSector = &gSaveDataBuffer;
if (gFlashMemoryPresent != TRUE)
return 0;
UpdateSaveAddresses();
GetSaveValidStatus(gRamSaveSectorLocations);
slotOffset = NUM_SECTORS_PER_SLOT * (gSaveCounter % NUM_SAVE_SLOTS);
for (i = 0; i < NUM_SECTORS_PER_SLOT; i++)
{
ReadFlashSector(i + slotOffset, gReadWriteSector);
// Base offset for SaveBlock2 is calculated using the trainer id
if (gReadWriteSector->id == SECTOR_ID_SAVEBLOCK2)
return sector->data[offsetof(struct SaveBlock2, playerTrainerId[0])] +
sector->data[offsetof(struct SaveBlock2, playerTrainerId[1])] +
sector->data[offsetof(struct SaveBlock2, playerTrainerId[2])] +
sector->data[offsetof(struct SaveBlock2, playerTrainerId[3])];
}
return 0;
}
u32 TryReadSpecialSaveSector(u8 sector, u8 *dst)
{
s32 i;
s32 size;
u8 *savData;
if (sector != SECTOR_ID_TRAINER_HILL && sector != SECTOR_ID_RECORDED_BATTLE)
return SAVE_STATUS_ERROR;
ReadFlash(sector, 0, (u8 *)&gSaveDataBuffer, SECTOR_SIZE);
if (*(u32 *)(&gSaveDataBuffer.data[0]) != SPECIAL_SECTOR_SENTINEL)
return SAVE_STATUS_ERROR;
// Copies whole save sector except u32 counter
i = 0;
size = SECTOR_COUNTER_OFFSET - 1;
savData = &gSaveDataBuffer.data[4]; // data[4] to skip past SPECIAL_SECTOR_SENTINEL
for (; i <= size; i++)
dst[i] = savData[i];
return SAVE_STATUS_OK;
}
u32 TryWriteSpecialSaveSector(u8 sector, u8 *src)
{
s32 i;
s32 size;
u8 *savData;
void *savDataBuffer;
if (sector != SECTOR_ID_TRAINER_HILL && sector != SECTOR_ID_RECORDED_BATTLE)
return SAVE_STATUS_ERROR;
savDataBuffer = &gSaveDataBuffer;
*(u32 *)(savDataBuffer) = SPECIAL_SECTOR_SENTINEL;
// Copies whole save sector except u32 counter
i = 0;
size = SECTOR_COUNTER_OFFSET - 1;
savData = &gSaveDataBuffer.data[4]; // data[4] to skip past SPECIAL_SECTOR_SENTINEL
for (; i <= size; i++)
savData[i] = src[i];
if (ProgramFlashSectorAndVerify(sector, savDataBuffer) != 0)
return SAVE_STATUS_ERROR;
return SAVE_STATUS_OK;
}
#define tState data[0]
#define tTimer data[1]
#define tInBattleTower data[2]
// Note that this is very different from TrySavingData(SAVE_LINK).
// Most notably it does save the PC data.
void Task_LinkFullSave(u8 taskId)
{
s16 *data = gTasks[taskId].data;
switch (tState)
{
case 0:
gSoftResetDisabled = TRUE;
tState = 1;
break;
case 1:
SetLinkStandbyCallback();
tState = 2;
break;
case 2:
if (IsLinkTaskFinished())
{
if (!tInBattleTower)
SaveMapView();
tState = 3;
}
break;