.. _sec-flash-vector-table:

Flash Vector Table
==================

This table contains the reset value of the stack pointer, and the start 
addresses, also called exception vectors, for all exception handlers. 
The first 15 exception vectors are necessary system exceptions, followed
by a variable number of Interrupt Request (IRQ) vectors. The location of 
this table is fixed to address 0x00000000. At bootup time, the RTOS kernel 
will run a first function to initialize the :term:`Hwi` module.

.. ifconfig:: device == 'cc23xx'

    For more information about the vector table format, please refer to
    `Cortex-M0 Vector Table
    <https://developer.arm.com/documentation/dui0497/a/the-cortex-m0-processor/exception-model/vector-table>`__.


For more information on the kernel boot process and first functions, please see
:ref:`sec-freertos-overview`.

.. _ccfg:

Customer Configuration (CCFG) Table
===================================

The CCFG is placed at the end of the last flash page and lets the
customer configure various chip and system parameters in the Customer
Configuration (CCFG) table. 
Parameters can be determined in the SysConfig (\*.syscfg) file through
the *TI Devices* |rarr| *Device Configuration* options.
The last (sizeof(ccfg_t)) bytes of the CCFG sector are reserved by the system for the
CCFG table. By default, the linker allocates the unused flash of the last flash
page to the application image for code and data use.

See the |TRM| for details on CCFG fields and related configuration options,
including how to set the CCFG to disable access to internal flash memory
contents.

.. note::

  The CCFG cannot be relocated, and must reside at the end of the last page of
  flash. Consult the |TRM| for more information.

.. note::

  If SET_CCFG_ERASE_CONF_CHIP_ERASE_DIS_N is set to 0 it's not possible to do mass erase.

.. _sec_user_record:

User Record
===========

The user record is a 128-byte record in CCFG that can be written at the same time as CCFG is written or with
a separate command later. This allows the user record to be written as part of a commissioning step separate
from the application image that has been programmed. Consult the |TRM| for more information.

In this case the user record typically contains some kind of device unique ID, address or key.
For instance, it can be used to:

  * Store a custom ``Public Address`` inside the CCFG memory section which will not get erased by OAD procedures.
  * Store custom keys inside the CCFG memory.

Write into the User Record for Debugging or Developing purposes
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

It is possible to leverage the SysConfig interface for this purpose by following the next steps:

  1. Create a ``.h`` file and define the values that you want to write into the User Record. For example:
       
       .. code-block:: c
        :linenos:
        :caption: Example of definition.

        #define CCFG_USER_RECORD .val8={0x01, 0x02, 0x03, 0x04, 0x05, 0x06}

  2. Open SysConfig and go to ``Device Configuration`` inside the ``TI Devices`` section.

  3. Search for ``Hardware Initialization And User Data`` and modify the following:

     * Click on ``Enable User Record``.

     * Include the name of the defined variable inside the ``User Record Macro`` field. 
       In the previous example: ``CCFG_USER_RECORD``.

     * Include the path where the ``.h`` file can be found.

    .. figure:: /memory/resources/UserRecord_sysconfig.PNG
      :align: center

      Setting the User Record using SysConfig.

  4. Right click on the project and select ``Properties``.

  5. Go into the ``Debug`` option and disable the option ``Skip Programming of CCFG user record``
     inside the ``Flash Settings`` section.

    .. figure:: /memory/resources/UserRecord_skipCCFG.PNG
      :align: center

      Disable option to Skip Programming of CCFG user record.
  
  6. Build the project and flash it into the device.

    .. warning:: This is only applicable when programming the main flash along with the CCFG.

  7. To verify that the values have been properly flashed into the User Record section
     of the CCFG, you can use the ``Memory Browser`` while running in Debug mode. 
     The User Record section starts at the address: ``0x4e020750``.

    .. figure:: /memory/resources/UserRecord_checkmem.PNG
      :align: center

      Verify User Record value inside CCFG.

.. _sec-flash-user-record:

Write into the User Record while in Production
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

  .. warning:: UNIFLASH version 8.7 or higher must be used when flashing into the User Record to avoid unknown issues with the device.

  1. Select the ``.bin`` file with the values you want to flash into the User Record. You can also use the tool provided in
     :ref:`sec-crc-user-record`, which generates a ``.bin`` file from a ``.txt`` file. However please consider this tool also generates
     the CRC code at the last 4 bytes, reducing the available space that you can use inside the User Record to 124 bytes.

  .. warning::  All bytes in the CCFG user record must not have been previously modified (the values must be 0xFF) before attempting to program the CCFG user record.
                This can be avoided when programing into the main flash by using the ``Skip Programming of CCFG user record`` CCS option previously mentioned. If
                flashing the program from UNIFLASH, please find this option inside Settings & Utilities --> CCFG.
  
  2. Open UNIFLASH and select the ``.bin`` file along with the load address, which is the CCFG User Record address: ``0x4e020750``.

    .. figure:: /memory/resources/UserRecord_flashUNIFLASH.PNG
      :align: center

      Select program to load into User Record with UNIFLASH.
  
  3. Once the image has been successfully loaded, please power cycle the device and restart UNIFLASH again.

  4. Go to ``Memory`` and click on ``Read Target Device``. Search for the CCFG User Record address.

    .. figure:: /memory/resources/UserRecord_seeUNIFLASH.PNG
      :align: center

      Verify that the User Record has been correctly modified.

.. note:: In case you need to generate a User Record binary file with CRC, refer to :ref:`sec-crc-user-record`.

Read the User Record value from the application code
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Please consider the following example as reference.

  .. code-block:: c
      :caption: Example of how to read the CCFG User Recod.

          #include <ti/devices/DeviceFamily.h>
          #include DeviceFamily_constructPath(inc/hw_ccfg.h)
          #include <string.h>                                

          extern const ccfg_t ccfg;                           

          unsigned char buffer[6];
          void *user_record_source = (void*)ccfg.userRecord.val8;

          //Copy the User Record values into the buffer.
          memcpy(buffer, user_record_source, sizeof(buffer));

  .. note:: If you do not require the entire user record size, just define the amount of bytes to copy (reducing ``USER_RECORD_SIZE`` in our previous example).
            For instance, if you flashed a Bluetooth LE ``Public Address``, then you will need to read only the first 6 bytes.

CRC Tool
========

Please find the tool inside the SDK directory: ``<SDK>\tools\common\crc_tool``.

The CRC tool has two main features:

  1. **Adding CRC values to an ELF file**: Parse an Executable and Linkable Format (ELF) file. 
  Calculate CRC values over sections of memory as defined in the linker command file, and insert 
  these CRC values after the end address, as defined by these symbols. This can be used as a post 
  build step to add CRCs to the generated ELF file.

  2. **Generate a User Record binary file with CRC values**: Parse a text file, containing one or more hexadecimal values,
  merge this data and pad up to 124 bytes, calculate the CRC of this value and generate a binary file containing
  124 bytes of data and 4 bytes of CRC. This is intended to be given as input to a SACI Flash Programming command
  for programming the user record in the CCFG.

.. note:: The generated user record binary can be flashed in production line even with debug locked
          and without affecting the actual application.

.. _add_crc_to_elf_file_ccfg:

Adding CRC values to an ELF file
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

For ``crc_tool`` to know where to insert CRC values it needs to be able to find symbols in the ELF file
which matches the stated prefix. All symbols without a matching prefix are ignored. Symbols need to
come in pairs with matching names, except for ``_end``, and ``_begin`` suffixes. Symbols without a suffix,
or without a matching counterpart are ignored.

The following cases are examples of what the tool expects. These symbols must be introduced inside the linker command file
(``.cmd``, ``.icf``, ``.lds``) which can be found inside the project.

   .. code-block:: c
        :caption: Example of symbol definition. The addresses shown here are for illustrative purposes only.

        __my_prefix_name1_begin = 0x4E020000;
        __my_prefix_name1_end = 0x4E02000B;

        __my_prefix_name2_begin = 0x4E020010;
        __my_prefix_name2_end = 0x4E02074B;

.. warning:: If you have the ``_end`` values of two sections within the same 4 byte range, meaning that
            they would overwrite each other's CRCs, then an error is thrown. In addition, the value of the
            ``_end`` symbol must be greater or equal than the ``_begin`` value, otherwise an error is also thrown.

These symbols and their addresses are already generated by GenMap (See: :ref:`sysconfig-genMap`) and included inside
the linker command file with the prefix" ``ti_utils_build_GenMap_sym_CRC_CCFG``. To see these symbols and their respective
addresses please follow the next steps:

  1. Click on ``ti_utils_build_linker.cmd.genmap`` inside the ``Generated Files`` section.

  .. figure:: /memory/resources/CRC_genMap.PNG
    :align: center

    SysConfig - CCFG Symbols

  2. To see all of the symbols (including the Record User) enable the ``User Record CRC`` inside ``Device Configuration``.

  .. figure:: /memory/resources/CRC_genMap_symb.PNG
    :align: center

    SysConfig - CCFG Symbols from GenMap

The ``crc_tool`` tool will take an ELF file as input and output an ELF file with inserted CRC values. This can be automated
by using CCS post-build steps. To do this, please follow the next steps:

  1. Add the symbols to the ``.cmd`` file of the project.
  2. Right-click on the project file and search for ``Properties``.
  3. Inside ``Build`` look for ``Environment`` and click on ``Add..``. Add a new variable called ``CCS_CRC_TOOL_DIR`` with value
     equal to: ``C:\ti\simplelink_lowpower_f3_sdk_x_xx_xx_xx\tools\common\crc_tool``, where ``simplelink_lowpower_f3_sdk_x_xx_xx_xx``
     value must be updated to match the version of the used SDK.

    .. figure:: /memory/resources/CRC_tool_addEnrivornment.png
      :align: center

      Adding environment variable for CRC Tool.

  4. Inside ``Build`` look for ``Steps`` and include the following line inside the ``Post-build steps``. As you can see, we are using the
     prefix that is automatically generated by GenMap: ``ti_utils_build_GenMap_sym_CRC_CCFG``.

      * ``${CCS_CRC_TOOL_DIR}\crc_tool.exe patch-image --elf ${BuildArtifactFilePath} --symbol-prefix ti_utils_build_GenMap_sym_CRC_CCFG --output ${BuildArtifactFilePath}``

    .. figure:: /memory/resources/CRC_tool_postbuildsteps.png
      :align: center

      Adding Post Build Steps for CRC Tool.

  5. Build the project. You should be able to see the description of the actions being executed by the ``crc_tool``
     in the console when building.

    .. figure:: /memory/resources/CRC_tool_monitor.png
      :align: center

      Adding Post Build Steps for CRC Tool.

If there is no need to use CCS and the intention is to only add CRC values to an ELF file, the following steps can be used:

  1. Add the symbols to the ``.cmd`` file.
  2. Go to the CRC tool directory (``<SDK>\tools\common\crc_tool``) and open the command prompt.
  3. In order to calculate the CRC values for the ELF file named ``output.out`` run the following command:

    * ``.\crc_tool.exe patch-image --elf output.out --symbol-prefix ti_utils_build_GenMap_sym_CRC_CCFG --output output.out``

  .. note:: Please make sure that you are using the same prefix inside the ELF file as the one
            declared below (in our example due to GenMap: ``ti_utils_build_GenMap_sym_CRC_CCFG``) with the ``--symbol-prefix``.

  .. table:: The following command line options are available for ``patch-image``:

    +---------------------------+----------------------------------------------------+
    | **Name**                  | **Usage**                                          |
    +---------------------------+----------------------------------------------------+
    |  '--elf {file location}'  | Specify location of input file                     | 
    +---------------------------+----------------------------------------------------+
    |  '--symbol-prefix'        | Specify prefix of begin / end symbols in ELF file  |
    +---------------------------+----------------------------------------------------+
    | '--output {file_name}'    | Specify name of output file                        |
    +---------------------------+----------------------------------------------------+

.. _sec-crc-user-record:

Generate a User Record binary file with CRC
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The User Record can be used to program unique ID specific to each device in their own defined format. 
A total of ``124 + 4(CRC)`` bytes are available for the user record. In addition,
the generated user record binary can be flashed on the production line even with debug locked and without
affecting the actual application.

Please consider the following for the input text (``.txt``) file: 

  1. The input text file must contain one or more valid hex values (``0x`` prefix is optional).
  2. Separate integers are separated by whitespace or newlines.
  3. Each value must consist of two hexadecimal characters. For instance, ``1`` is invalid, ``01`` is valid.
  4. The total length of all values can be at most 124 bytes.
  5. Comments can be added with ``#``, and blank lines are ignored.

.. warning:: Currently only text files (``.txt``) are supported.

Please consider the following for the output binary (``.bin``) file:

  1. The output file will be a 128 byte binary file, containing integers in the same order as
     the input data, with the first integer at the lowest address.
  2. The output data will be right-padded with zeros to a total of 124 bytes. After the 124
     bytes of content there will be four CRC bytes.
  3. Each integer will be written to the file using little endian.

In order to generate a binary file named ``output.bin`` with input data and CRC from a text
file named ``input.txt``, the following command line invocation can be used after opening a
command prompt inside the CRC Tool directory (``\tools\common\crc_tool``):

  * ``.\crc_tool.exe generate-user-record --user-record-file input.txt --output output.bin``
  
  .. code-block:: c
        :caption: Example of input text file.
        :emphasize-lines: 2, 5

        # integer #1       #2   #3   #4    #5
        0x0123456789ABCDEF EF  0123 0000 0x0ABCDE
        # Newline can also be used as divider
        # Integer #6
        0xBCDE

  .. table:: The following command line options are available for ``generate-user-record``:

    +---------------------------+----------------------------------------------------+
    | **Name**                  | **Usage**                                          |
    +---------------------------+----------------------------------------------------+
    |  '--user-record-file'     | Specify location of input file                     | 
    +---------------------------+----------------------------------------------------+
    | '--output {file_name}'    | Specify name of output file                        |
    +---------------------------+----------------------------------------------------+

  .. code-block:: c
        :caption: Example of output ``.bin`` file which you can see has been padded to 124 bytes, plus 4 bytes CRC.
        :emphasize-lines: 2, 3, 6 

        # ------------------- hexdump -C <output_file> -------------#
        # 00000000  ef cd ab 89 67 45 23 01  ef 23 01 00 00 de bc 0a
        # 00000010  de bc 00 00 00 00 00 00  00 00 00 00 00 00 00 00
        # 00000020  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00
        # ...
        # 00000070  00 00 00 00 00 00 00 00  00 00 00 00 52 14 8f e6
        # 00000080

Once you have the binary file, it is possible to flash it into the User Record using UNIFLASH following the
same steps described in :ref:`sec-flash-user-record`.