Esempio n. 1
0
uint32_t isValidBufferStart(const void * buffer)
{
  if (memoryType == MEM_FLASH)
    return isFirmwareStart(buffer);
  else
    return isEepromStart(buffer);
}
int32_t fat12Write(const uint8_t *buffer, uint16_t sector, uint16_t count)
{
  enum FatWriteOperation {
    FATWRITE_NONE,
    FATWRITE_EEPROM,
    FATWRITE_FIRMWARE
  };

  static unsigned int operation = FATWRITE_NONE;

  TRACE("FAT12 Write(sector=%d, count=%d)", sector, count);

  if (sector < 3) {
    // reserved, read-only
  }
  else if (sector < 3 + (EESIZE/BLOCKSIZE)) {
    // eeprom
    while (count) {
      if (operation == FATWRITE_NONE && isEepromStart(buffer)) {
        TRACE("EEPROM start found in sector %d", sector);
        operation = FATWRITE_EEPROM;
      }
      if (operation == FATWRITE_EEPROM) {
        eeWriteBlockCmp((uint8_t *)buffer, (sector-3)*BLOCKSIZE, BLOCKSIZE);
      }
      buffer += BLOCKSIZE;
      sector++;
      count--;
      if (sector-3 >= (EESIZE/BLOCKSIZE)) {
        TRACE("EEPROM end written at sector %d", sector-1);
        operation = FATWRITE_NONE;
      }
    }
  }
  else if (sector < 3 + (EESIZE/BLOCKSIZE) + (FLASHSIZE/BLOCKSIZE)) {
    // firmware
    uint32_t address;
    address = sector - 3 - (EESIZE/BLOCKSIZE);
    address *= BLOCKSIZE;
    address += FIRMWARE_ADDRESS;
    while (count) {
      for (uint32_t i=0; i<BLOCKSIZE/FLASH_PAGESIZE; i++) {
        if (address >= FIRMWARE_ADDRESS+BOOTLOADER_SIZE/*protect bootloader*/ && address <= FIRMWARE_ADDRESS+FLASHSIZE-FLASH_PAGESIZE) {
          if (address == FIRMWARE_ADDRESS+BOOTLOADER_SIZE && isFirmwareStart(buffer)) {
            TRACE("FIRMWARE start found in sector %d", sector);
            operation = FATWRITE_FIRMWARE;
          }
          if (operation == FATWRITE_FIRMWARE) {
            writeFlash((uint32_t *)address, (uint32_t *)buffer);
          }
        }
        address += FLASH_PAGESIZE;
        buffer += FLASH_PAGESIZE;
      }
      sector++;
      count--;
      if (sector-3-(EESIZE/BLOCKSIZE) >= (FLASHSIZE/BLOCKSIZE)) {
        TRACE("FIRMWARE end written at sector %d", sector-1);
        operation = FATWRITE_NONE;
      }
    }
  }
  return 0 ;
}