fssync.c 1.24 KB
#include <PR/bcp.h>
#include "os.h"
#include "os_bbcard.h"
#include "os_bbfs.h"
#include "bbint.h"

s32
__osBbFsSync(int force) {
    BbFat16* fat = __osBbFat;
    u32 target = __osBbFatBlock;
    u16 sum, *p, link = 0;
    int tries, k;
    if (!force && !__osBbFsAutoSync) return 0;
    /* recompute the checksum/version number and write out the
     * FAT blocks to the 'next' FAT block using a simple rotor
     */
    for(k = __osBbFsBlocks/BB_FAT16_ENTRIES; --k >= 0;) {
	fat[k].seq++;
	fat[k].link = link;
	sum = fat[k].cksum = 0;
	for(p = (u16*)(fat+k); p < (u16*)(fat+k)+BB_FL_BLOCK_SIZE/2; p++)
	    sum += *p;
	fat[k].cksum = BB_FAT16_CKSUM - sum;

	for(tries = 0; tries < BB_FAT16_BLOCKS; tries++) {
	    target++;
	    if (target >= BB_FAT16_BLOCKS) target = 0;
	    if (osBbCardEraseBlock(0, link = __osBbFsBlocks-target-1) == 0 &&
		osBbCardWriteBlock(0, __osBbFsBlocks-target-1, fat+k, NULL) == 0) {

		goto next;
	    }
	}
	return BBFS_ERR_FAIL;
next:;
    }
    __osBbFatBlock = target;
    return 0;
}

s32
osBbFAutoSync(u32 on) {
    __osBbFsAutoSync = on;
    return 0;
}

s32
osBbFSync(void) {
    s32 rv = BBFS_ERR_INVALID;
    if ((rv = __osBbFsGetAccess()) < 0) return rv;
    rv = __osBbFsSync(1);
    __osBbFsRelAccess();
    return rv;
}