Nios® V Processor Software Developer Handbook

ID 743810
Date 10/12/2024
Public
Document Table of Contents

7.8.3. Fine-Grained Flash Access

Three additional functions provide complete control for writing flash contents at the highest granularity:
  • alt_get_flash_info()
  • alt_erase_flash_block()
  • alt_write_flash_block()

By the nature of flash memory, you cannot erase a single address in a block. You must erase (that is, set to all ones) an entire block at a time. Writing to flash memory can only change bits from 1 to 0; to change any bit from 0 to 1, you must erase the entire block along with it.

Therefore, to alter a specific location in a block while leaving the surrounding contents unchanged, you must read out the entire contents of the block to a buffer, alter the value(s) in the buffer, erase the flash block, and finally write the whole block-sized buffer back to flash memory. The fine-grained flash access functions automate this process at the flash block level.

#include <stdio.h>
#include <string.h>
#include "sys/alt_flash.h"
#define BUF_SIZE 1024
int main ()
{
   alt_flash_fd* fd;
   int ret_code;
   char source[BUF_SIZE];
   char dest[BUF_SIZE];
   /* Initialize the source buffer to all 0xAA */
   memset(source, 0xAA, BUF_SIZE);
   fd = alt_flash_open_dev("/dev/ext_flash");
   if (fd!=NULL)
      {
         ret_code = alt_write_flash(fd, 0, source, BUF_SIZE);
         if (ret_code==0)
            {
               ret_code = alt_read_flash(fd, 0, dest, BUF_SIZE);
               if (ret_code==0)
                  {
                     /*
                      * Success.
                      * At this point, the flash is all 0xAA and we
                      * have read that all back to dest
                      */
                  }
            }
         alt_flash_close_dev(fd);
         }
         else
            {
               printf("Cannot open flash device\n");
            }
return 0;
}