######################################
AN00125: USB Mass Storage Device Class
######################################

This application note shows how to create a USB device compliant to the standard
USB mass storage device class on an `xmos xcore.ai` device.

The code associated with this application note provides an example of using the
`XMOS` Device Library and associated USB class descriptors to provide a framework for the
creation of a USB mass storage device.

The mass storage framework uses XMOS libraries to provide a bidirectional
mass storage device example over high speed USB.

Note: This application note provides a standard USB Mass Storage Device Class which
addresses Bulk-Only Transport (BOT) or Bulk/Bulk/Bulk (BBB) specification and as a
result does not require drivers to run on Windows, Linux or Mac.

The Peripheral Device Type (PDT) supported in this application note is SCSI (Small Computer
System Interface) Block Command (SBC) Direct-access device (e.g. flash-based storage).
This example application uses the on-board serial flash as its memory device.

|newpage|

This application note is designed to run on an `XMOS xcore-200` or `xcore.ai` series device.
The example code provided with the application has been implemented and tested
on the `XK-EVK-XU316` board but there is no dependency on this board and it can be modified to
run on any development board which uses an `xcore-200` or `xcore.ai` series device.

.. note::
  - This document assumes familiarity with the `XMOS xcore` architecture, the Universal Serial
    Bus 2.0 Specification (and related specifications), the `XMOS` tool chain and the xC language.
    Documentation related to these aspects which are not specific to this application note are linked to in the references appendix.

  - For the full API listing of the XMOS USB Device (XUD) Library please see the `XMOS USB Device (XUD) Library <https://www.xmos.com/file/lib_xud>`_.

********
Overview
********

The Universal Serial Bus (USB) is a communication architecture that gives a PC the ability to interconnect a variety of devices via a simple four-wire cable. One such device is the mass storage. Traditionally, mass storage device class provides adaptability for devices like

- USB flash drive
- memory card reader
- digital audio player
- digital camera
- external hard drive

The `USB specification <https://www.usb.org/sites/default/files/usbmassbulk_10.pdf>`_ provides as standard device class for the implementation of USB mass storage.

:ref:`mass_storage_block_diagaram` provides an overview of the system.

.. figure:: ../images/block_diagram.*
  :name: mass_storage_block_diagaram

  Block diagram of USB Mass storage application

Features
========

This section describes the features that are supported by the demo application. The application uses an on-board flash with a user memory partition of 3 MB. The application does the following

* Enumerates as Mass Storage device
* Displays as `` **XMOS DISK** ``

The device will have a FAT12 filesystem and 3 MBytes of memory available.

.. note::
  Read and write operations may be slow as this is just an example.

**********************************************
USB Mass Storage Device Class application note
**********************************************

The demo in this note uses the XMOS USB device library and shows a simple program that receives data from and sends data to the host.

For the USB Mass storage device class application example, the system comprises three tasks running
in separate logical cores of a `xcore` device.

The tasks perform the following operations.

* A task containing the USB library functionality to communicate over USB
* A task implementing Endpoint0 responding both standard and mass storage class USB requests
* A task implementing the application code for receiving and sending mass storage data into the device

These tasks communicate via the use of `xconnect` channels which allow data to be passed between application code running on separate logical cores.

:ref:`task_diagram` shows the task and communication structure for this application note.

.. figure:: ../images/task_diagram.*
   :align: center
   :name: task_diagram

   Task diagram of USB mass storage application

CMakeLists.txt additions for this application
=============================================

To start using the USB library, the user needs to add **lib_xud** to the `CMakeLists.txt`:

.. code-block:: cmake

    set (APP_DEPENDENT_MODULES "lib_xud")

After `CMakeLists.txt` has been modified, the USB APIs can be acessed via the **xud_device.h** header file:

.. code-block:: C

	#include <xud_device.h>

Declaring resource and setting up the USB components
====================================================

**main.xc** contains the application implementation for a device based on the USB mass storage
device class.
There are some defines and arrays in it that are used to configure the XMOS USB device library.
These are displayed below.

.. literalinclude:: ../../app_an00125/src/main.xc
   :start-at: USB Endpoint Defines
   :end-at: epTypeTableIn
   :language: C

These describe the endpoint configuration for this device. This example has bi-directional communication with the host machine via the standard endpoint0, an endpoint for receiving the bulk data from the host into our device and an endpoint for sending the bulk data to host from our device.

The application main() function
===============================

Below is the source code for the main function of this application, which is taken from the source file **main.xc**

.. literalinclude:: ../../app_an00125/src/main.xc
   :start-at: int main
   :language: C

Looking at this in a more detail a few things can be noted:

- The `par` statement starts three separate tasks in parallel
- There is a task to configure and execute the USB library: `XUD_Main()`
- There is a task to startup and run the Endpoint0 code: `Endpoint0()`
- There is a task to deal with USB mass storage requests arriving from the host: `massStorageClass()`
- The define `USB_TILE` describes the tile on which the individual tasks will run
- In this example all tasks run on the same tile as the USB PHY
- The `xconnect` communication channels used by the application are set up at the beginning of main()
- The USB defines discussed earlier are passed into the function XUD_Main()

Configuring the USB Device ID
=============================

The USB ID values used for vendor id, product id and device version number are defined in the file **endpoint0.xc**. These are used by the host machine to determine the vendor of the device (in this case XMOS) and the product plus the firmware version.

.. literalinclude:: ../../app_an00125/src/endpoint0.xc
   :start-at: /* USB Device ID Defines */
   :end-before: /* USB Mass Storage
   :language: C

USB Mass storage Class specific defines
=======================================

The USB Mass storage Class is configured in the file **endpoint0.xc**. Below there are a set of standard defines which are used to configure the USB device descriptors to setup a USB mass storage device running on an `xcore` device.

.. literalinclude:: ../../app_an00125/src/endpoint0.xc
   :start-at: /* USB Mass Storage
   :end-before: /* USB Device Descriptor */
   :language: C

USB Device Descriptor
=====================

**endpoint0.xc** is where the standard USB device descriptor is declared for the mass storage device. Below is the structure which contains this descriptor. This will be requested by the host when the device is enumerated on the USB bus.

.. literalinclude:: ../../app_an00125/src/endpoint0.xc
   :start-at: devDesc
   :end-at: }
   :language: C

From this descriptor the user can see that product, vendor and device firmware revision are all coded into this structure. This will allow the host machine to recognise the mass storage device when it is connected to the USB bus.

USB Configuration Descriptor
============================

The USB configuration descriptor is used to configure the device in terms of the device class and the endpoint setup. For the USB mass storage device the configuration descriptor which is read by the host is as follows.

.. literalinclude:: ../../app_an00125/src/endpoint0.xc
   :start-at: cfgDesc
   :end-at: }
   :language: C

From this code the user can see that the USB mass storage class defines described earlier are encoded into the configuration descriptor along with the bulk USB endpoint description for receiving storage data into the application code. These endpoint allows us to process the storage data request from the host and to the host inside the main mass storage application task.

USB string descriptor
=====================

There is one more descriptor within this file relating to the configuration of the USB Mass storage Class. This section should also be modified to match the capabilities of the mass storage device.

.. literalinclude:: ../../app_an00125/src/endpoint0.xc
   :start-at: String table
   :end-at: }
   :language: C

USB Mass storage Class requests
===============================

Inside **endpoint0.xc** there is some code for handling the USB Mass storage device class specific requests. These are shown in the following code:

.. literalinclude:: ../../app_an00125/src/endpoint0.xc
   :start-at: Mass Storage Class Request
   :end-before: Endpoint 0
   :language: C

These mass storage specific request are implemented by the application as they do not form part of the standard requests which have to be accepted by all device classes via endpoint0.

USB Mass storage Class Endpoint0
================================

The function `Endpoint0()` contains the code for dealing with device requests made from the host to the standard endpoint0 which is present in all USB devices. In addition to requests required for all devices, the code handles the requests specific to the mass storage device class.

.. literalinclude:: ../../app_an00125/src/endpoint0.xc
   :start-at: result == XUD_RES_OKAY
   :end-before: If we
   :language: C

Receiving storage data from the host
====================================

The application endpoint for Command Transport, Data-In, Data-Out and Status Transport are implemented in the file **mass_storage.xc** as per the flow shown in below figure (:ref:`command_status_data_flow`). This is contained within the function `massStorageClass()` which is shown in next page.

.. figure:: ../images/command_data_status_flow.*
   :scale: 70%
   :align: center
   :name: command_status_data_flow

   Command/Data/Status Flow

.. literalinclude:: ../../app_an00125/src/mass_storage.xc
   :start-at: void massStorageClass
   :end-at: } // END of massStorageClass
   :language: C

The following points can be observed from the code above:

* Two buffers are declared, one to receive the Command transport CBW (Command Block Wrapper) data which is streamed into the application from the host and the other to send Status transport CSW (Command Status Wrapper) to the host.
* This task operates inside a while (1) loop which waits for data to arrive and then processes it.
* It checks for the CBW Signature and packet size that get received from the host.
* Based on the Operation code available on the CBWCB (CBW Command Block) field, SCSI commands corresponding to flash drive are executed.

  - Operation code received may correspond to SCSI commands like `Inquiry, Test Unit Ready, Request Sense, Read Capacity, Mode Sense, Read/Write,` etc.
* Once the execution (Command transport, Data-In or Data-Out) is completed, the device shall echo the contents of CBWTag field sent by the host back along with the CSWStatus and CSW Signature as Status transport.
  This ensures that the `Status` send to host is associated with the `Command` received from host.

|newpage|

SCSI Command Implementation
===========================

Some of the SCSI command definitions and the reponse from the device are mentioned below.

* **INQUIRY:** command requests that information regarding parameters of the Device be sent to the Host.

  - The response to this command provides standard INQUIRY data of (36 bytes) PDT, RMB (Removable Medium Bit), Vendor Identification, Product Identification and Product Revison Level, etc.
* **TEST UNIT READY:** command provides a means to check if the Device is ready. This command is useful in that it allows a Host to poll a Device until it is ready without the need to allocate space for returned data.

  - The response to this command returns GOOD, if the device accepts an appropriate medium access command or CHECK CONDITION status with a sense key of NOT READY.
* **REQUEST SENSE:** command requests the device to transfer sense data to the host whenever an error is reported. The sense data  describes what caused the error condition.

  - The response to this command is a sense key, Additional Sense Code (ASC) or ASC Qualifier (ASCQ) depending on which `error occured <http://www.t10.org/lists/asc-num.htm>`_.
* **READ CAPACITY:** command requests the device to transfer 8 bytes of parameter data describing the capacity of the installed medium of the device.

  - The response to this command returns Logical Block Address (LBA) and block length in bytes of the memory device.
* **MODE SENSE:** command requests the device to transfer parameter data describing the medium type, block descriptor length, read/write error recovery mode.

  - The response to this command returns PDT type as medium type, error recovery mode, descriptor length.
* **READ/WRITE:** command requests the device to read/write data onto the medium.

  - The response to `READ` transfers the most recent data value written in the addressed logical block of the medium to host.
  - The response to `WRITE` writes the data transferred by the host to the medium.

Serial Flash Functions
======================

For accessing the on-board serial flash, the user will need to add the flash library **lflash** in
`CMakeLists` as one of the `APP_COMPILER_FLAGS` and use **flashlib.h** to access the flash library
functions.

.. note:: No separate core is required to handle the SPI read/write.

The below implementation does write/read operation onto the on-board serial flash.

.. literalinclude:: ../../app_an00125/src/mass_storage.xc
   :start-after: //Flash_Functions_start
   :end-before: //Flash_Functions_end
   :language: C

|newpage|

*******************
Demo Hardware Setup
*******************

To run the demo, connect the `XK-EVK-XU316` **DEBUG** and **USB** (:ref:`xk-evk-xu316`) recepticals to separate USB
connectors on the development PC.

.. figure:: ../images/xk-evk-xu316.*
  :name: xk-evk-xu316

  XMOS XK-EVK-XU316 Board

|newpage|

*******************
Example application
*******************

Building the example
====================

This section assumes that the `XMOS XTC Tools <https://www.xmos.com/software-tools/>`_ have been
downloaded and installed. The required version is specified in the accompanying ``README``.

Installation instructions can be found `here <https://xmos.com/xtc-install-guide>`_.

Special attention should be paid to the section on
`Installation of Required Third-Party Tools <https://www.xmos.com/documentation/XM-014363-PC/html/installation/install-configure/install-tools/install_prerequisites.html>`_.

The application is built using the `xcommon-cmake <https://www.xmos.com/file/xcommon-cmake-documentation/?version=latest>`_
build system, which is provided with the XTC tools and is based on `CMake <https://cmake.org/>`_.

The ``an0xxxx`` software ZIP package should be downloaded and extracted to a chosen working
directory.

To configure the build, the following commands should be run from an XTC command prompt::

    cd an00125
    cd app_an00125
    cmake -G "Unix Makefiles" -B build

All required dependencies are included in the software package. If any dependencies are missing,
they will be retrieved automatically during this step.

The application binaries should then be built using ``xmake``::

    xmake -j -C build

Binary artifacts (.xe files) will be generated under the appropriate subdirectories of the
``app_an0xxxx/bin`` directory — one for each supported build configuration.

For subsequent builds, the ``cmake`` step may be omitted.
If ``CMakeLists.txt`` or other build files are modified, ``cmake`` will be re-run automatically
by ``xmake`` as needed.

Running the example
===================

Once the application is built, the user will need to prepare the flash device by creating a data partition.
From a XTC command prompt run the following command from the `an00125/app_an00125` directory.

.. code-block:: console

  xflash --boot-partition-size=0x20000 --data disk.img --target=XK-EVK-XU316 ./bin/app_mass_storage.xe

The disk.img file is a 3MB FAT12-formatted disk image created for use as a virtual mass storage device.
It can be mounted and written to like a physical disk, allowing files such as hello.txt to be included for testing or emulation purposes.

After flashing the device, **XMOS DISK** device will appear on the host computer.

|newpage|

**********
References
**********

* `XMOS XTC Tools Installation Guide
  <https://xmos.com/xtc-install-guide>`_

* `XMOS XTC Tools User Guide
  <https://www.xmos.com/view/Tools-15-Documentation>`_

* `XMOS USB Device Library
  <https://www.xmos.com/file/lib_xud>`_

* `USB Mass Storage Class Bulk-Only Transport
  <https://www.usb.org/sites/default/files/usbmassbulk_10.pdf>`_

* `USB 2.0 Specification
  <https://www.usb.org/sites/default/files/usb_20_20240604.zip>`_

* `USB Mass Storage Specification For Bootability
  <https://www.usb.org/sites/default/files/usb_msc_boot_1.0.pdf>`_

* `SCSI Command
  <http://en.wikipedia.org/wiki/SCSI_command>`_

* `SCSI Commands Reference Manual (Seagate)
  <http://www.seagate.com/staticfiles/support/disc/manuals/Interface%20manuals/100293068c.pdf>`_

* `USB Mass Storage Device Specification Overview
  <https://usb.org/sites/default/files/Mass_Storage_Specification_Overview_v1.4_2-19-2010.pdf>`_

