Implementing a Gadget Driver

134
CHAPTER 1 INTRODUCTION 1

Transcript of Implementing a Gadget Driver

Page 1: Implementing a Gadget Driver

CHAPTER 1

INTRODUCTION

1

Page 2: Implementing a Gadget Driver

INTRODUCTION

The main goal of the Project is to write the Gadget Driver for the OMAP5912OSK and also

writing a USB device driver for host side. Using gadget driver we are exporting a functionality

of OMAP5912-OSK to the host side. Before writing a driver for the Device side there are certain

prerequisites which are to be full-filled.

First requirement is porting which includes installing the U-boot loader image which sets the

environment required for running Linux kernel and then the Linux Kernel image is brought into

the Flash of the OMAP-5912-OSK.

Porting the U-Boot loader and the Linux Kernel on the kit requires setting up the TFTP

Server at the machine side and client at the Kit side. Along with the TFTP server, setting up the

NFS Server is also very important; it hosts the root-file-system which provides the environment

for execution of the programs on the kit which are kept on the server.

The kernel version being used is Linux-2.6.27.

The U-BOOT version is U-BOOT-1.3.3.

Gadget Driver Development: This phase involves implementation of the Gadget driver which handled request right from introducing gadget and its capabilities to host to exporting a specific device functionality.

USB Device Driver Development: This phase involves development of the USB device driver(client driver) on the host side that adhered to request from user application.

2

Page 3: Implementing a Gadget Driver

CHAPTER 2

PORTING- AN

INTRODUCTION

3

Page 4: Implementing a Gadget Driver

PORTING –AN INTRODUCTION

2.1 Porting

Porting is a process wherein we try to customize an already available kernel so as to

make it compatible to run on a particular architecture of a particular hardware environment.

Different hardware has got different internal structure i.e. the internal implementation of the

basic blocks that make that hardware board. Two different development boards can have a totally

different type of memory layout, memory access methods, peripherals and other features. So the

kernel that may run on one of them will not work on other because of the basic difference in the

board architecture. This is the reason we need to customize the kernel. Customization of the

kernel would include changing some parameters in the kernel source, including or excluding

some kernel modules , libraries etc. Once the customization is completed the kernel is compiled

to generate an image that will be ready to be downloaded to the board.

This process will also invariably include the BOOTLOADER also. The bootloader may

or may not be required to customize, but yes , it can also be customized.

It should be noted that porting is not an atomic process. The process of porting will inturn

contain many other crucial modular steps. So when we are working on ‘porting’ we should work

in a modular method. Completing the process module by module.

2.2 Modules in Porting

The process of porting can be basically divided into following modules

Study

o Study of Bootloader

o Study of ‘kernel customization’

o Detailed study of the relevant h/w board

o Study of Support system required

4

Page 5: Implementing a Gadget Driver

Compiling and / installation of support system required

Bootloader

o Customizing bootloader (U-BOOT)

o Compiling and downloading U-BOOT(U-BOOT)

Kernel

o Customizing Kernel

o Compiling and downloading kernel

The study modules sound very trivial but these modules only will decide over the success

of failure of the complete process. Very good study materials on the porting and other relevant

topics are available on the internet. We have included most of those that we used in the CD with

this project report.

The second main module is compiling and installing the prerequisites. The porting

process will require a lot of other utilities, so before we start with the actual porting we should be

ready with all the prerequisites on our systems. All the required packages are also included in the

CD.

The third main part of the process of porting is the U-BOOT customization and

compilation. Normally the U-BOOT source is not needed to be customized barring one or two

very trivial changes. Once the U-BOOT image is ready we can download it into the intended

SOC. The detailed steps are explained in the further chapters.

The last part of the process of porting is customization and compilation of the kernel.

This is the most crucial part of the complete process. We need to be very sure of which features

of the kernel we need and which we don’t. The complete process of customizing and compiling

the kernel and then downloading it is explained in detail in further chapters.

5

Page 6: Implementing a Gadget Driver

2.3 Prerequisites of Porting

1) TFTP server

Get it from the Linux OS installation CD.

2) NFS server

Get it from the Linux OS installation CD.

3) Root File System mounted on NFS

4) Cross Development tool chain.

5) Minicom (or any other serial port communication utility)

Get it from the Linux OS installation CD.

6) U-BOOT loader source / image.

Get a U-Boot Loader from http://sourceforge.net/projects/uboot/

7) Linux Kernel Source + OMAP patch.

This is all we need as the procedure for porting. In the coming section all the details of the

steps are provided.

6

Page 7: Implementing a Gadget Driver

CHAPTER 3

TFTP Server

7

Page 8: Implementing a Gadget Driver

TFTP SERVER

Why do we need TFTP Server?

To answer the following questions:-

a) How to transfer the image of kernel to the board.

b) How to transfer the image of bootloader to the board.

The answer to above two questions is provided by TFTP (trivial file transfer protocol)

protocol.

3.1 Setting up TFTP Server

TFTP Server again uses certain kernel and user space Daemons.

The above shown is the snapshot of the first face of TPTP utility.

8

Page 9: Implementing a Gadget Driver

3.2 Some configuration settings:-

vi /etc/xinetd.d/tftp

# default: off

# description: tftp service is provided primarily for booting or when a \

# router need an upgrade. Most sites run this only on machines acting as

# "boot servers".

service tftp

{

socket_type = dgram

protocol = udp

wait = yes

user = root

server = /usr/sbin/in.tftpd

server_args = -s /tftpboot/

disable = no

}

3.3 Starting the Service by Command Parameters

# /sbin/service xinetd restart

Shutting down xinetd: done

Starting INET services. (xinetd) done

9

Page 10: Implementing a Gadget Driver

CHAPTER 4

NFS SERVER

10

Page 11: Implementing a Gadget Driver

NFS SERVER

4.1 Need of NFS Server:-

NFS is network file system which is used to make processes feel the 'PRINCIPLE OF

LOCALITY' .The scarcity of memory on the board to keep complete Linux system on the kit

is not possible, so to make it possible we have chosen the other way around.

The Network File System (NFS) is probably the most prominent network service using

RPC (remote procedure call). It allows you to access files on remote hosts in exactly the same

way you would access local files. A mixture of kernel support and user-space daemons on the

client side, along with an NFS server on the server side, makes this possible. This file access is

completely transparent to the client and works across a variety of server and host.

4.2 How to setup the NFS Server?

We have network utility available for setting up a NFS server in our project we are using the

latest version NFS V4.

11

Page 12: Implementing a Gadget Driver

The above shown is the snapshot of NFS server.

12

Page 13: Implementing a Gadget Driver

The above shown is the second snapshot where we can set the mount point /data/rootfs2.6

which we want to share with the NFS clients. Here * shows that all hosts can use NFS and the

respective permissions.

In case NFS don’t work it might also be because of firewall settings so we have to

explicitly disable firewall. To disable the firewall, use YAST administrator tool.

13

Page 14: Implementing a Gadget Driver

4.3 The NFS Daemons:-

If you want to provide NFS service to other hosts, you have to run the rpc.nfsd and rpc.mountd

daemons on your machine. As RPC-based programs, they are not managed by inetd, but are

started up at boot time and register themselves with the portmapper, therefore, you have to make

sure to start them only after rpc.portmap is running.

4.4 Few commands to start the NFS:-

linux-ozm3:~ # /sbin/service nfsserver restart

Shutting down kernel based NFS server: nfsd done

Starting kernel based NFS server: idmapd mountd statd nfsd sm-notify done

linux-ozm3:~ # /sbin/service nfsserver stop

Shutting down kernel based NFS server: nfsd statd mountd idmapd done

linux-ozm3:~ # rpcinfo –p

Shows all the network utilities running on the system.

4.5 NFS Configuration Files:-

vi /etc/exports {path to export or share the location}

vi /etc/hosts.allow {used to add the hosts which are allowed}

vi /etc/hosts.deny {used to add the hosts which should be denied access}

14

Page 15: Implementing a Gadget Driver

CHAPTER 5

ROOT FILE SYSTEM

15

Page 16: Implementing a Gadget Driver

ROOT FILE SYSTEM

5.1 What is file system?

A file system is the methods and data structures that an operating system uses to keep

track of files on a disk or partition; that is, the way the files are organized on the disk. The word

is also used to refer to a partition or disk that is used to store the files or the type of the file

system.

Before a partition or disk can be used as a file system, it needs to be initialized, and the

bookkeeping data structures need to be written to the disk. This process is called making a file

system.

One of the last operations conducted by the Linux kernel during system start up is

mounting the root file system. The Linux kernel itself doesn’t dictate any file system structure,

but user space applications do expect to find files with specific names in specific directory

structures. Therefore, it is useful to follow the de facto standards that have emerged in Linux

systems.

The root file system refers to the file system mounted at the base of the file system

hierarchy, designated simply as ‘/’. Even a small embedded system can mount a file system to

get the benefits of a services offered by operating system. Root file system is the first file system

mounted at the base of the hierarchy.

5.2 File system Layout

The complete list of root file system top-level directories and their content are shown

bellow.

1. bin : Binary executables i.e Essential user command binaries.

2. boot : Static files used by the bootloader.

3. dev : Device nodes i.e Devices and other special files.

4. etc : Local System configuration files, including startup files.

16

Page 17: Implementing a Gadget Driver

5. home : User home directories.

6. lib : Essential libraries, such as the C library, and kernel modules.

7. media : Mount points for removable media.

8. mnt : Mount points for temporarily mounted file systems.

9. opt : Add-on software packages.

10. proc : Virtual file system for kernel and process information.

11. root : Root user’s home directory.

12. sbin : Essential system administration binaries.

13. sys : Virtual file system for system information and control (buses, devices, and

drivers).

14. tmp : Temporary files.

15. usr : Secondary hierarchy containing most applications and documents useful to

most users, including the X server.

16. var : Variable data stored by daemons and utilities.

5.3 Installation of Root File System:-

We can customize the root file-system according to the requirements of our embedded

system environment for further details refer to the root file-system chapter of 'Building Linux

Systems'.

The installation steps for root file-system are as follows -

1. Download the pre-built ROOT file system.

2. Extract it with tar -xjvf /data/rootf.tar.bz.

3. File system is now available to use and resides it into folder where it is extracted.

4. This file system contains the essential data structure and well organized Busy Box.

5. The newly created file system is empty. Copy the library files (Loader) from GNU tool Chain

directory to Roofs lib directory. This library contains the soft links .hence copy this files using

following command.

6. cd [GNU toolchain folder]/arm-none-gnueabai/libc/lib.

7. Copy lib files #cp lib*.so /data/rootfs/lib.

8. Copy softlinks #cp -d lib*.so.* /data/rootfs/lib.

9. Copy softlinks of loader #cp -d ld*.so* /data/rootfs/lib.

17

Page 18: Implementing a Gadget Driver

CHAPTER 6

TOOL CHAIN

18

Page 19: Implementing a Gadget Driver

TOOLCHAIN

6.1 ARM Specific Development Tools:-

Development tools are required to develop a software or program. Suppose we want to

write programs on x86 based systems we need GCC compiler for compiling our codes, debugger

tool for debugging and creating binary executable files which can run on X86 processor.

Similarly we need tools specific to our processor that is ARM9 one such tool is tool

chain. It includes Linker, assembler, c-compiler, c-library & header. Additional components in

some tool chain include extra library and more supplementary tools such as Debugger, Profiler.

6.2 What is Tool-chain?

Tool chain can be defined as a complete collection of tools required for writing,

compiling, creating executable files and finally libraries used at run-time for running those

executables on the system.

6.3 Various Types of Tool chains:-

1. Native Tool chain:

Set of software tools running on one platform and generating binaries for same platform

are called as native tool chain. The usual development tools available on GNU/LINUX

workstation is NATIVE tool chain.

2. Cross development Tool chain:

In Embedded System development it is not practical to use native tool chain because of

following limitations.

1. The target is too restricted in terms of memory/storage.

2. The target is very slow as compared to workstation.

3. Not necessary to install all development tools on target.

19

Page 20: Implementing a Gadget Driver

Hence, embedded developer’s needs tools which are different than normal tool chain in

respect that they typically run on one platform while building application for another. This is

why these tools are called as “Cross development tools”.

These cross development tools are not installed in the target system but they remain on

the host and we can compile and create binaries for ARM on host machine itself.

Above shown is how the native and cross compiling toolchain works.

6.4 Components of Cross-Development Tool-chain:-

1. BINUTILS:-

o Binutils is a set of tools to generate and manipulate binaries for a given CPU

architecture.

o Various utilities in Binutils package are Loader, Linker, and Assembler.

2. GCC compiler:-

GNU C compiler free software compiler Can compile C, C++, Ada , Java Objective C++,

and generate code for a large number of CPU architectures, including ARM, AVR, CRIS, FRV,

M32, MIPS, v850, i386, x86_64, IA64,etc.

20

Page 21: Implementing a Gadget Driver

3. GLIBC or alternate C- library:-

o C library acts as an interface between the applications and the Kernel.

o It provides the well known standard C API to ease application development.

o Glibc is C library from the GNU project. Almost all user land applications will link to this

library.

o Only things like the kernel, bootloaders and other things that avoid using any C library

functions can be compiled without it.

o There are alternatives to glibc for small and embedded systems but this is the standard for

compiling the rest of gcc.

4. Kernel headers-

This is the first component required to build a tool chain. The C library and compiled programs

needs to interact with the kernel. Therefore compiling C library and many applications require

the kernel header.

21

Page 22: Implementing a Gadget Driver

6.5 Building a Tool chain:-

There are two methods of building a tool chain -

1. Build the tool chain from individual components.

2. By Using pre-compiled tool chain.

Many decisions must be made when building a tool chain which involves

1. Choosing the C library.

2. Choosing the version of the different components.

3. Choosing the configuration of the tool chain.

6.6 Installation steps for GNU Tool chain:-

1. cd /opt/

2. Untar the precompiled tool chain bz2 in the created folder

$ tar -jxvf /toolchain.bz2

22

Page 23: Implementing a Gadget Driver

CHAPTER 7

MINICOM

23

Page 24: Implementing a Gadget Driver

MINICOM - Interfacing with OSK

In order to communicate or operate the embedded OS we need serial interface utility like

a hyper terminal (in windows), or Minicom (in Linux).

7.1 Configuring Minicom

1. Install the package for MINICOM (from Linux CD/DVD).

2. Open terminal and type.

$ minicom –s

3. It will open the minicom window with option window (if option window does not

appear press Ctrl-A O)

4. In option window select ‘Modem and Dialing’ and ensure ‘Init String (A)’ is clear.

5. Now select ‘serial port setup’ and change ‘serial device’ to ‘/dev/ttyS0’ also change

‘Bps/par/bits’ to 115200 baud, 8Bps, no parity, 1 stop bit, and no flow control.

6. Save setup as def.

7. Exit.

NOTE: Once the settings have been saved, from next time there is no need for the '-s' option

simply type in

$ minicom

24

Page 25: Implementing a Gadget Driver

CHAPTER 8

BOOTLOADER

25

Page 26: Implementing a Gadget Driver

BOOTLOADER

ARM Linux cannot be started on a machine without a small amount of machine specific

code to initialize the system. ARM Linux requires the boot-loader code to do very little.

8.1 The minimal requirements from the bootloader are

Configure the system’s memory.

Load the kernel image at the correct memory address.

Optionally load an initial RAM disk at the correct memory address.

Initialize the boot parameters to pass to the kernel.

Obtain the ARM Linux machine type

Enter the kernel with the appropriate register values.

8.1.1 Configuring the System’s Memory:

The boot-loader is expected to find and initialize all RAM that the kernel will use for

volatile data storage in the system. It performs this in a machine dependent manner. It may use

internal algorithms to automatically locate and size all RAM, or it may use knowledge of the

RAM in the machine.

The kernel should have no knowledge of the setup or configuration of the RAM within a

system other than that provided by the boot-loader.

8.1.2 Loading the Kernel Image:

Kernel images generated by the kernel build process are either uncompressed "Image"

files or compressed zImage files. The uncompressed Image files are generally not used, as they

do not contain a readily identifiable magic number. The compressed zImage format is almost

universally used in preference.

The zImage has several benefits in addition to the magic number. Typically, the

decompression of the image is faster than reading from some external media. The integrity of the

image can be assured, as any errors will result in a failed decompress. The kernel has knowledge

of its internal structure and state, which allows for better results than a generic external

26

Page 27: Implementing a Gadget Driver

compression method. The zImage has a magic number and some useful information near its

beginning.

Offset into zImage Value Description

0x24 0x01F2818 Magic number used to identify

this is anARM Linux zImage

0x28 Start address The address the zImage start at

0x2C End address The address the zImage ends at

Table 8.1 - Useful fields in zImage head code

The start and end offsets can be used to determine the length of the compressed image

(size = end - start). This is used by several boot-loaders to determine if any data is appended to

the kernel image.

The zImage code is Position Independent Code (PIC) so may be loaded anywhere within

the available address space. The maximum kernel size after decompression is 4Megabytes. This

is a hard limit and would include the initrd if a boot-pImage target was used.

Despite the ability to place zImage anywhere within memory, convention has it that it is

loaded at the base of physical RAM plus an offset of 0x8000 (32K). This leaves space for the

parameter block usually placed at offset 0x100, zero page exception vectors and page tables.

8.1.3 Loading an Initial RAM disk:

An initial RAM disk is a common requirement on many systems. It provides a way to

have a root file-system available without access to other drivers or configurations.

There are two methods available on ARM Linux to obtain an initial RAM disk. The first

is a special build target bootpImage which takes an initial RAM disk at build time and appends it

to a zImage. This method has the benefit that it needs no bootloader intervention. The hard size

limit for the uncompressed kernel and initrd of 4Megabytes applies. Because of these limitations

this target is rarely used in practice.

27

Page 28: Implementing a Gadget Driver

The second and much more widely used method is for the bootloader to place a given

initial ramdisk image, obtained from whatever media, into memory at a set location. This

location is passed to the kernel using ATAG_INITRD2 and ATAG_RAMDISK.

Conventionally the initrd is placed 8Megabytes from the base of physical memory.

Wherever it is placed there must be sufficient memory after boot to decompress the initial

ramdisk into a real ramdisk i.e. enough memory for zImage + decompressed zImage + initrd +

uncompressed ramdisk. The compressed initial ramdisk memory will be freed after the

decompression has happened.

8.1.4 Kernel Parameters:

The bootloader must pass parameters to the kernel to describe the setup it has performed,

the size and shape of memory in the system and, optionally, numerous other values.

The tagged list should conform to the following constraints:

The list must be stored in RAM and placed in a region of memory where neither the

kernel decompression nor initrd manipulation will overwrite it. This is usually the start of

physical RAM plus 0x100 (which avoids zero page exception vectors).

The physical address of the tagged list must be placed in R2 on entry to the kernel,

however historically this has not been mandatory and the kernel has used the fixed value

of the start of physical RAM plus 0x100.

The list must not extend past the 0x4000 boundary where the kernel's initial translation

page table is created. The kernel performs no bounds checking and will overwrite the

parameter list if it does so.

The list must be aligned to a word (32 bit, 4byte) boundary (if not using the

recommended location).

The list must begin with an ATAG_CORE and end with ATAG_NONE.

28

Page 29: Implementing a Gadget Driver

The list must contain at least one ATAG_MEM.

Tag name Value Size Description

ATAG_NONE 0X00000000 2 Empty tag used to end list

ATAG_CORE 0X54410001 5(2 empty) First tag used to start list

ATAG_MEM 0x54410002 4 Describes a physical area os

memory

ATAG_VIDEOTEX

T

0x54410003 5 Describes a VGA text display

ATAG_RAMDISK 0x54410004 5 Describes how the ramdisk will be

used in kernel

ATAG_INITRD2 0x54410005 4 Describes where the compresses

ramdisk image

ATAG_SERIAL 0x54410006 4 64 bit board serial number

ATAG_REVISION 0x54410007 3 32 bit board revision number

ATAG_VIDEOLFB 0x54410008 8 Initial values for vesafb-type

framebuffers

ATAG_CMDLINE 0x54410009 2 Command line to pass kernel

Table 8.2 – List of Usable Tags

8.1.5 Obtaining the ARM Linux Machine Type:-

The only additional information the bootloader needs to provide is the machine type, this

is a simple number unique for each ARM system often referred to as a MACH_TYPE.

8.1.6 Starting the Kernel:

Once the bootloader has performed all the other steps it must start execution of the kernel

with the correct values in the CPU registers.

The entry requirements are:

The CPU must be in SVC (supervisor) mode with both IRQ and FIQ interrupts disabled.

The MMU must be off, i.e. code running from physical RAM with no translated

addressing.

Data cache must be off29

Page 30: Implementing a Gadget Driver

Instruction cache may be either on or off

CPU register 0 must be 0

CPU register 1 must be the ARM Linux machine type

CPU register 2 must be the physical address of the parameter list

The bootloader is expected to call the kernel image by jumping directly to the first instruction

of the kernel image.

8.2 Das U-Boot:-

We use Das U-boot as the bootloader for our board. Das U-Boot is the first thing we will

see when we start up our OSK. If we press a key when prompted, we will be able to use U-Boot,

rather than booting into Linux. From here, we can upgrade U-Boot or our kernel, or flash on a

new root filesystem; we can also change environment variables, such as the kernel’s boot

arguments.

8.2.1 Compiling U-Boot:-

Step 1: First move to the desired directory, where we want the bootloader to reside.

$ cd /usr/src/

Step 2: Unpack the tar with xjvf parameters. These parameters are used to untar the tar-file. And

change the current directory to the u-boot directory.

$ tar –xjvf /root/home/u-boot-1.3.3.tar.bz2

$ cd u-boot-1.3.3/

Step 3: Now set the path of toolchain. Toolchain is a set of tools to build computer software. It

includes – linker, assembler, archives, C compiler, C library and C header files. We need this to

compile our bootloader (C/C++ programs) intend to use on the OSK.

$ export PATH=/opt/arm-2009q3/bin:$PATH

Step 4: Now clean the previous configurations. To clean the previous configuration files we use

‘distclean’. This command simply run the ‘distclean’ rule defined in the Makefile. This rule

clears all previously saved configuration settings.

30

Page 31: Implementing a Gadget Driver

$ make distclean

Step 5: Apply default configuration for our OSK. Omap5912osk_defconfig is the configuration

file which comes with the bootloader for the omap5912 board. This file contains all the

necessary configuration settings of the bootloader to work properly on the board. This command

apply these configuration settings to .config file.

$ make omap5912osk_config

Step 6: Edit the Makefile for the following changes--

In Makefile find the following text

ifeq($(ARCH),arm)

CROSS_COMPILE = …

change the CROSS_COMPILE line to

CROSS_COMPILE = arm-none-linux-gnueabi-

This line tells the compiler that which cross-compiler we wants to use to compile the bootloader.

Step 7: Now compile the u-boot. U-boot is compiled with the make command. Make command

compile the u-boot source files according to the configuration which we have already applied

and create a binary image of the bootloader – u-boot.bin. This file will be available in the current

directory it can be used to boot our OSK.

$ make

This will be the final command for the compilation of the bootloader. After these

steps we have a compiled image of the U-Boot which we can send to our board to

boot the OMAP5912 board.

31

Page 32: Implementing a Gadget Driver

8.2.2 Upload U-Boot to the OSK:-

To upload the binary image of the bootloader we need to follow the following steps.

Step1: Connect the Ethernet cable and serial cable between computer and OMAP5912 kit. Our

computer and board communicate via these two interfaces.

Step2: Open the terminal on computer and start ‘minicom’. Minicom is the utility like

hyperterminal in windows, which is used to communicate with serial device.

Step3: Power up the OMAP5912 kit. When we power up the kit it start the previously loaded

bootloader which apply the initial setting to bootup the board and start the linux kernel.

Step4: Press any key to stop booting the kernel when prompted (stop booting the kernel).

Step5: Now setup environment variable. Environment variables are necessary parameters to

setup communication between our computer and board. To setup the environment variables

follow the following steps:

- First of all setup the Ethernet address of the board. This sets the MAC address of the OSK

(printed near the port).

$ setenv ethaddr <00:0E:99:XX:XX:XX>

- Now give an IP address to the board.

$ setenv ipaddr 192.168.72.33

- Also give the IP address of the computer.

$ setenv serverip 192.168.72.34

- Provide the NET MASK address of the LAN.

$ setenv netmask 255.255.255.0

- Set the GATE WAY IP of the LAN

$ setenv gatewayip 192.168.72.254

Step6: Save all the settings which we have just applied by the command

$ saveenv

32

Page 33: Implementing a Gadget Driver

Step7: Now our board is ready to receive the compiled image of the bootloader (u-boot.bin). To

upload the bootloader image, copy the image file to the ‘/tftpboot/’ directory.

$ cp –f /root/home/u-boot-1.3.3/u-boot.bin /tftpboot/

Step8: Send the bootloader image, u-bbot.bin, to the RAM in OSK

$ tftpboot 0x10000000 u-boot.bin

Step9: This command will upload the u-boot image to the board and also will show the size of

our file, note down this size. The size value will be used to move the binary image to the flash.

Step10: Now un-protect the memory area of the previously loaded bootloader, so that we can

remove that.

$ protect off 1:0

Here 1 is for the memory bank and 0 for the sector in that bank.

Step11: Erase the previous bootloader by the following command.

$ erase 1:0

Here 1 indicates the bank no 1 and 0 indicates sector no 0, i.e. the residing location of

bootloader.

Step12: Move the new bootloader image to flash.

$ cp.b 0x10000000 0x100000 <size of u-boot copied in RAM (in hex)>

e.g. $ cp.b 0X10000000 0X100000 34f2e

Now if we restart the OMAP5912 kit, it will boot the kit with our uploaded bootloader image.

Step13: Once the new bootloader starts we need to change the “boot arguments” of the new boot

loader in case they are not already properly set.

Though we have already set the new environment variables still we haven’t set the “boot

arguments”. Do it as follows

33

Page 34: Implementing a Gadget Driver

$ setenv bootargs=console=ttyS0,115200n8 noinitrd root=/dev/nfs rw

nfsroot=192.168.72.34:/data/rootfs2.6,nolock devfs=mount

ip=192.168.72.33:192.168.72.34:192.168.72.254:255.255.255.128:omap:eth0:off mem=30M

(this is a single line command !!!)

TRAP: copy and paste above string on the u-boot screen to avoid any errors, the only changes

that one need to do in this string are

nfsroot=<your IP>:<path of rootfs on your PC> and

ip=<your board IP>:<your PC IP>:<your gateway IP>:<your netmask>

8.3 Knowing U-BOOT interface

Start the Minicom application on the terminal by

$ minicom

NOTE: to know how to configure minicom refer section “configuring minicom”

When we power on the kit assuming that the U-Boot is already present or has been downloaded

on the board the following menu appears on the minicom screen.

U-Boot 1.1.1 (Jul 19 2004 – 09:17:40)

U-Boot code: 11080000 -> 11095D6C BSS: -> 1109A53C

DRAM Configuration:

Bank #0: 10000000 32 MB

Micron StrataFlash MT28F128J3 device initialized

Flash: 32MB

In: serial

Out: serial

Err: serial

Hit any key to stop autoboot: 10

34

Page 35: Implementing a Gadget Driver

After the counter which is right now at 10 becomes 0 the Kernel Image, if at all present

will start booting. Pressing any key before the counter runs out will stop the kernel from booting.

The above opening screen of U-BOOT shows us very crucial information about the system

so far.

The first line is showing the name and the date of compiling of the U-BOOT image.

The second line ie “U-Boot code: 11080000 -> 11095D6C” is showing the Address of the

RAM where the bootloader will relocate itself once it completes the execution from the

starting location of the RAM and brings in the kernel Image.

Here the U-BOOT will reside in RAM location 0X11080000 to 0X1109D6C.

RAM starts from 0X10000000,the first 8000 locations from here are reserved for kernel

parameters, Zero vector tables. So the first available RAM location is :

0x10000000 + 0X00008000 = 0X10008000.

0x10008000 is the first usable location of the RAM and hence in future the Kernel will

reside here. So we place the U-BOOT at a location where it will not collide with the kernel

Image specially when the kernel has decompressed and increased in size. This safe location is

0X11080000.

The last part of the second line is “ BSS: -> 1109A53C” . This lines tells the start address

of the zero initialized work area of the decompresser. i.e. this sector will be used by the

decompresser to decompress the kernel image. Further, the decompressed image will be stored at

the address given by a system macro “ZRELADDR” and will execute from here, most probably

this address will sum up to 0X10008000 , which is the starting address of the usable RAM.

If we have stopped the auto-booting of the kernel by hitting any key then we can start the

kernel from the U-BOOT prompt using a simple command

# bootm 100000

35

Page 36: Implementing a Gadget Driver

where 0X100000 is the flash address location where we have stored the kernel image.

We can check the environment variables from the U-BOOT prompt using

# printenv

One can also set the respective environment variables using

# setenv

# saveenv

usage of setenv and saveenv is explained in installing U-BOOT section.

To see all the possible commands type

# help

some common useful commands are

# imls : list all images found in flash memory

# flinfo : print flash meory information

# bdinfo : gives board information

# bootm : boots the image from the specified location

# go : simply jumps the execution to the specified addr.

Once the kernel image starts getting executed the following appears on the minicom screen

## Booting kernel from Legacy Image at 00100000 ...

Image Name: linux kernel image DSP enabled

Image Type: ARM Linux Kernel Image (gzip compressed)

Data Size: 1359130 Bytes = 1.3 MB

Load Address: 10c08000

Entry Point: 10c08000

Verifying Checksum ... OK

Uncompressing Kernel Image ... OK

Starting kernel ...

Uncompressing

36

Page 37: Implementing a Gadget Driver

Linux................................................................

Linux version 2.6.25-omap1 (root@linux-ozm3) (gcc version 4.2.1

(CodeSourcery S0CPU: ARM926EJ-S [41069263] revision 3 (ARMv5TEJ),

cr=00053177

Machine: TI-OSK

Memory policy: ECC disabled, Data cache writeback

OMAP162123 revision 2 handled as 16xx id: 330594085995081b

SRAM: Mapped pa 0x20000000 to va 0xd7000000 size: 0x100000

CPU0: D VIVT write-back cache

CPU0: I cache: 16384 bytes, associativity 4, 32 byte lines, 128 sets

.

IP-Config: Gateway not on directly connected network.

Looking up port of RPC 100003/2 on 192.168.72.16

Looking up port of RPC 100005/1 on 192.168.72.16

VFS: Mounted root (nfs filesystem).

Freeing init memory: 120K

init started: BusyBox v1.00-pre8 (2004.03.05-22:18+0000) multi-call

binary

******************************************

Starting System Init for OMAP5912OSK

******************************************

Please press Enter to activate this console.

BusyBox v1.00-pre8 (2004.03.05-22:18+0000) Built-in shell (ash)

Enter 'help' for a list of built-in commands.

-sh: can't access tty; job control turned off

#

#

The kernel has decompressed and started. This is the kernel prompt or the root prompt of

the rootfs.

37

Page 38: Implementing a Gadget Driver

Now we can use the simple UNIX utilities like ls, ps, cp, insmod, cd etc to operate the

system.

TRAPS: It can so happen that the U-BOOT runs but the kernel image never gets called.

i.e there is no activity after the following screen

U-Boot 1.1.1 (Jul 19 2004 – 09:17:40)

U-Boot code: 11080000 -> 11095D6C BSS: -> 1109A53C

DRAM Configuration:

Bank #0: 10000000 32 MB

Micron StrataFlash MT28F128J3 device initialized

Flash: 32MB

In: serial

Out: serial

Err: serial

The reasons for these are 2 environment variables which are probably not yet set.

bootcmd

bootdelay

Set them as follows

# setenv bootcmd bootm 100000

# setenv bootdelay 10

# saveenv

Bootcmd is an environment variable that stores the string or the command that is to be executed

once the bootdelay timer runs out. So here we are setting the command to bootm 100000 which

will lead to booting of the image present at 0X100000 (our kernel image) once the bootdelay

counter is over.

38

Page 39: Implementing a Gadget Driver

Bootdelay is the count in seconds for which the U-BOOT will wait before executing the

command stored in another variable called bootcmd.

8.4 BOOTING SEQUENCE:-

Flash is of 32MB (16MB X 2) divided into 258 sectors of 125K each. When JP3 is in

position 1-2 position. Flash is positiond at address 0x0. When powered on CPU fetches the first

instruction from address 0x0.

Therefore U-Boot bootloader is burned at address 0x00000000 (sector 0). U-Boot is

configured to fetch the LINUX kernel from address 0x00100000. Therefore LINUX kernel is

burned at address 0x00100000.

U-Boot bootloader remaps itself at address 0x11080000 in RAM and operates from there.

In RAM,

0x10000000 contains Zero page exception vectors.

0x10000100 contains Parameter block. (kernel parameters from Uboot)

0x10004000 contains page tables.

0x10008000 contains zImage. (kernel image)

0x10800000 contains initrd. (initial file system)

0X11080000 contains U-BOOT image (remapped)

0x11096144 contains BSS area(used by kernel decompression)

1109 6144 BSS area(used by kernel decompression)

1108 0000 U-BOOT image (remapped)

1080 0000 inittrd.(initial file system)

1000 8000 zImage.(kernel image)

1000 4000 page tables.

1000 0100 Parameter block.(kernel parameter from Uboot)

1000 0000 Zero page exception vector

0010 0000 LINUX kernel

0000 0000 U-BOOT bootloader

39

Page 40: Implementing a Gadget Driver

CHAPTER 9

FLASH UTILITY

40

Page 41: Implementing a Gadget Driver

FLASH UTILITY

When you have a board without any bootloader or in worst cases it can so happen that the

bootloader that you loaded gets corrupted. In such cases the board will not boot-up at all, i.e.

there will be no U-boot prompt and hence in such cases we cannot use the U-Boot commands to

load or unload new bootloader.

In such a case the only solution is a “Flash Recovery Utility”.

9.1 How to Use the Flash Utility?

Step 1: Firstly install a usb library like libusb-1.0.6. (because flash utility uses USB)

# tar -jxvf libusb-1.0.6.tar.bz2

# cd libusb-1.0.6

# ./configure

# make

# make install

Step 2: Untar the tarball for the flash utility and compile the utility using simple commands

# tar zxvf omapfl-1.0.tar.gz

# make clean

# make all

After these commands a runnable file by name “omaplf” will be created in the un-tared folder.

Step 3: To use it, connect the board with your computer using USB ( board has a type A

connector, as your computer, and you need to do a A-A direct cable) Power the board, set JP3 to

pins 1-2, connect USB cable and executes the program passing it two arguments.

41

Page 42: Implementing a Gadget Driver

First argument is the second stage loader (the included 2nd.bin file) and second one is the

program you want to load at flash (example: u-boot-1.1.1). If it doesn't work, press the reset

button of the board.

The flash loading (recovery) is done by following simple commands

# ./omaplf 2nd.bin <your uboot file.bin> e.g.

# ./omaplf 2nd.bin u-boot.bin

After this step the Flash has been rescued and the new U-Boot is ready to run . Reset the

board !!

The file "2nd.bin" is the second stage boot loader. The main program (omaplf) sends it

to the OMAP processor, where it is executed by the internal bootloader. Then it send the second

binary to be flashed.

"2nd.bin" is already provided in the utility folder , if you need to recompile the second

boot loader, you will need a cross compiler, "2nd/Makefile". If your local gcc compiler is not

called "gcc", change "Makefile", also if your include files for libusb isn't located at /usr/include

(add -L/.... to INCLUDES= line at Makefile).

42

Page 43: Implementing a Gadget Driver

CHAPTER 10

LINUX KERNEL FOR

OMAP5912 OSK

43

Page 44: Implementing a Gadget Driver

Linux Kernel for OMAP5912 OSK

Building the Linux kernel for OMAP5912 processor is little different than building it for

general purpose computers. We need to configure the Kernel according to our need. This

depends on what features we require and which modules we need to include in our Linux Kernel.

Following are the steps to build the bootable Kernel which can be used by the OMAP5912

processor.

The latest kernel can be obtained from http://www.kernel.org/ and the necessary patch to

use this kernel on an OMAP system can be found at http://www.-muru.com/linux/omap/

10.1 Compilation of Linux Kernel:-

Once these files are obtained, we can compile the Linux kernel following the steps

below:

Step1: Change the current directory to the directory where we want the source of the kernel.

# cd /usr/src/

Step2: Un-pack the source of the kernel here.

# tar -xjvf /root/home/linux-2.6.27.tar.bz2

Step3: Copy the patch for the OMAP5912 in current directory.

# cp /root/home/patch-2.6.27-omap1.bz2 .

Step4: Un-zip the patch file by following command

# bunzip2 patch-2.6.27-omap1.bz2

Step5: Now change directory to the kernel source directory

44

Page 45: Implementing a Gadget Driver

# cd linux-2.6.27/

Step6: Apply the OMAP5912 patch to the kernel.

# cat ../patch-2.6.27-omap1 | patch -p1

Step7: Here we have the kernel source tree which is patched for the OMAP5912 OSK. Now we

need to compile the kernel for our OMAP5912 processor. To have the cross compiler generate an

ARM Linux image, the path to the cross compiler tools is added to the host machine's PATH

variable by:

#export PATH=/opt/arm-2009q3/bin:$PATH

Step8: Edit the Makefile for the following changes, to tell the compiler that which compilation

library to be used to cross compile the Kernel.

In Makefile change the find the line –

“CROSS_COMPILE ?=

change this line to -

“CROSS_COMPILE ?= arm-none-linux-gnueabi-

Step9: Now clean the previously save configuration if any by passing ‘clean’ parameter to the

make command. This is the rule defined in the Makefile of the kernel which deletes all the

previous configuration files available in current Kernel.

# make clean (or # make mrproper)

Step10: Apply default configuration on the kernel for OMAP5912 which has been obtained with

the kernel source in file ‘omap_osk_5912_config’.

# make ARCH=arm omap_osk_5912_config

In this command ‘ARCH=arm’ defines the architecture of the hardware for which we want to

compile the Kernel and ‘omap_osk_5912_config’ is a file that contains the default configurations

for the OMAP5912. This command will create a ‘.config’ file which will contain all the default

45

Page 46: Implementing a Gadget Driver

configurations necessary for the OMAP5912 board. Default configuration files are located in

KSRC/arch/arm/configs/ .

Step11: Now we can change the default configuration according to our needs by

# make menuconfig

This command will open a configuration window, through which we can change the Kernel

configuration according to our needs.

In this window we need to change following settings

Kernel Features -> Use the arm EABI… (Enable)

Device Driver -> I2C support (Disable)

Device Driver -> OMAP DSP driver -> (DSP GATEWAY) (Enable)

System Type -> TI OMAP implementation -> MMU Framework Support (Enable)

Step12: Now we have configured the Kernel according to our need and we can now compile it.

To compile the Kernel use the make command with ‘ARCH=arm’ parameter. Here we again

explicitly tells the compiler that we want the compiled Kernel for ARM architecture by

specifying it as ‘ARCH=arm’. This is optional we can also compile without using this argument.

# make ARCH=arm

After make operation we will have vmlinux in our Kernel source tree. File vmlinux is

stand alone, monolithic Kernel image but it is not in a suitable format for U-Boot to upload. To

convert the file, the mkimage utility must be used which comes with UBoot.

Step13: To make the kernel image suitable for U-Boot, first of all create a new binary from

vmlinux which we will use to change into the suitable format for u-boot. For all this we need to

apply the following operations

#arm-linux-objcopy -O binary -R .note -R .comment –S

rch/arm/boot/compressed/vmlinux linux.bin

46

Page 47: Implementing a Gadget Driver

Step14: This linux.bin is needs to be compressed before sending to the board. To compress this

image use gzip utility

# gzip -9 linux.bin

Step15: Now we have compressed image of Linux kernel which is ready to be changed into

required format which u-boot can use to boot the kernel. The format of kernel image can be

changed by the following operation

# <U-Boot Directory>/tools/mkimage -A arm -O Linux -T kernel –C gzip -a 0x10c08000 -e

0x10c08000 -n ‘Linux Kernel Image’ -d linux.bin.gz uImage-2.6.27.cc

Note that above command is a single line command.

After this we will have a file ‘uImage-2.6.27.cc’ which can be upload to the

OMAP5912 board.

10.2 Upload Linux Kernel to the OSK:-

To upload the binary image of the Linux kernel we need to follow the following steps.

Step1: Power up the OMAP5912 kit. When we power up the kit it start the bootloader which

apply the initial setting to boot-up the board.

Step2: Press any key to stop booting the kernel when prompted.

Step 3: Now copy the kernel image in ‘tftpboot’ directory to upload it

$cp <U-Boot Directory> uImage-2.627.cc /tftpboot/

Step 4: Send the Linux kernel image, uImage-2.6.27.cc, to the RAM in OSK

$tftpboot 0x10000000 uImage-2.6.27.cc

Step 5: This command will upload the kernel image to the board and also will show the size of

our kernel image file, note down this size. The size value will be used to move the binary image

to the flash.

47

Page 48: Implementing a Gadget Driver

Step 6: Now un-protect the memory area of the previously loaded kernel, so that we can remove

that.

$protect off 1:8-22

Here 1 is for the memory bank and 8-22 for the sectors from 8 to 22 in that bank.

Step 7: Erase the kernel by the following command.

$erase 1:8-22

Step 8: Move our new Linux kernel image to flash.

$cp.b 0x10000000 0x100000 <size of kernel image(in hex)>

Now if we restart the OMAP5912 kit, it will boot the kit with our Linux kernel!!!

48

Page 49: Implementing a Gadget Driver

CHAPTER 11

HARDWARE DETAILS

49

Page 50: Implementing a Gadget Driver

HARDWARE DETAILS

11.1 ARM926EJ-S PROCESSOR:-

The ARM926EJ-S processor is a member of ARM9 family of micro processors from the

house of ARM. It is basically used for muti-tasking applications.

11.1.1 Features of ARM926EJ-S:-

1. It supports 32 bit ARM and 16 bit THUMB instructions.

2. It supports efficient execution of java byte codes(JAZELLE).

3. It has Harvard Architecture i.e. separate data and instruction caches and separate

AMBA AHB

4. Bus interfaces buses for each.

5. Separate instruction and data TCM interfaces.

6. Provides support for external co-processors enabling floating point.

7. Protection Unit (15), Jazelle enabled hardware accelerator, MMU etc.

8. It supports ARM v5TEJ instruction architecture.

9. It is a synthesizable macrocell i.e. you can optimize the memory to suit to your

requirements and Optimize the macro cell for your target code.

10. It supports five stage pipeline which are Fetch, Decode, Execute, Memory and

WriteBack

11. It also support six stage pipeline in case of jazelle state, Fetch, Jazelle/decode,

Execute.

12. It is a RISC based architecture i.e. the instruction set and related decode mechanism is

much simple compared to CISC.

50

Page 51: Implementing a Gadget Driver

11.1.2 Block Diagram of ARM926EJ-S:

Fig 11.4 Block Diagram of ARM926EJ-S

51

Page 52: Implementing a Gadget Driver

11.2 Programming Prerequisites:-

The ARM926EJ-S processor implements ARM architecture v5TE with Jazelle

extensions. This includes the 32-bit ARM instruction set, 16-bit Thumb instruction set, and the

8-bit Jazelle instruction set. For details of both the ARM and Thumb instruction sets, see the

ARM Architecture Reference Manual.

11.2.1 Processor operating states:-

The ARM926EJ-S core has three operating states:

1. ARM state : 32-bit, word-aligned ARM instructions are executed in this state.

2. Thumb state : 16-bit, halfword-aligned Thumb instructions.

3. Jazelle state : Variable length, byte-aligned Jazelle instructions.

In Thumb state, the Program Counter (PC) uses bit 1 to select between alternate

halfwords. In Jazelle state, all instruction Fetches are in words.

NOTE: Transition between ARM, Thumb, and Jazelle states does not affect the processor mode

or the register contents.

11.2.2 Switching state:-

You can switch the operating state of the ARM926EJ-S core between:

1. ARM state and Thumb state using the BX and BLX instructions,and loads to the PC.

Switching state is described in the ARM Architecture Reference Manual.

2. ARM state and Jazelle state using the BXJ instruction.

All exceptions are entered, handled, and exited in ARM state. If an exception occurs in

Thumb state or Jazelle state, the processor reverts to ARM state. The transition back to Thumb or

Jazelle states occurs automatically on return from the exception handler.

11.2.3 Memory formats:-

The ARM926EJ-S core views memory as a linear collection of bytes numbered in

ascending order from zero. Bytes 0 to 3 hold the first stored word, and bytes 4 to 7 hold the

second stored word, for example.

52

Page 53: Implementing a Gadget Driver

The ARM926EJ-S core can treat words in memory as being stored in either:

• Big-endian format

• Little-endian format.

Big-endian format:-

In big-endian format, the ARM926EJ-S core stores the most significant byte of a

word at the lowest-numbered byte, and the least significant byte at the highest-numbered byte.

Little-endian format:-

In little-endian format, the lowest-numbered byte in a word is the least significant

byte of the word and the highest numbered byte is the most significant.

11.2.4 Instruction length:-

Instructions are either:

• 32 bits long (in ARM state)

• 16 bits long (in Thumb state)

• Variable length, multiples of 8 bits (in Jazelle state).

11.2.5 Data types:-

The ARM926EJ-S core supports the following data types:

Word (32-bit)

Halfword (16-bit)

Byte (8-bit).

You must align these as follows:

Word quantities must be aligned to four-byte boundaries

Halfword quantities must be aligned to two-byte boundaries

Byte quantities can be placed on any byte boundary.

11.2.6 Operating modes:

In all states there are seven modes of operation:

User mode is the usual ARM program execution state, and is used for executing most

application programs.

Fast interrupt (FIQ) mode is used for handling fast interrupts.53

Page 54: Implementing a Gadget Driver

Interrupt (IRQ) mode is used for general-purpose interrupt handling.

Supervisor mode is a protected mode for the operating system.

Abort mode is entered after a data or instruction Prefetch Abort.

System mode is a privileged user mode for the operating system.

Undefined mode is entered when an undefined instruction exception occurs.

Modes other than User mode are collectively known as privileged modes. Privileged modes

are used to service interrupts or exceptions, or to access protected resources.

11.3 Hardware description of OMAP5912 OSK

MEMORY MAP OF OMAP5912 OSK

SDRAM Memory Map

54

Page 55: Implementing a Gadget Driver

Flash Bus Memory MAP of OMAP5912_OSK

The flash memory is physically connected to CS3. When JP3 is in the 2-3 position

(default),the OMAP5912 boots in fast boot mode where CS3 is swapped with CS0 so the Flash

starts at address 0. When the processor starts running, it will execute the code in flash (U-Boot is

stored in flash at factory).

55

Page 56: Implementing a Gadget Driver

If JP3 is in the 1-2 position, the OMAP5912 comes up in full boot mode with the internal

ROM at address 0. The internal bootloader supports additional boot modes such as booting from

the serial port. At any time, the state of the CS0-CS3 mapping can be changed by modifying the

BM(bit 1) of the EMIFS_CONFIG register(address 0xFFFECC00).

11.4 OMAP5912 Application Processor:-

OMAP5912 Features

1. Low-Power, High-Performance CMOS Technology

a. 192-MHz Maximum Frequency

b. 1.6 + 5% V Core Voltage

2. ARM926EJ-Sc (MPU) Core

a. Support for 32-Bit and 16-Bit (Thumb Mode) Instruction Sets

b. 16K-Byte Instruction Cache

c. 8K-Byte Data Cache

d. Data and Program Memory Management Unit (MMU)

e. 17-Word Write Buffer

f. Two 64-Entry Translation Look-Aside Buffers (TLBs) for MMUs

3. TMS320C55x (C55x) DSP Core

a. One/Two Instructions Executed per Cycle

b. Dual Multipliers (Two Multiply-Accumulates per Cycle)

c. Two Arithmetic/Logic Units

d. Five Internal Data/Operand Buses (3 Read Buses and 2 Write Buses)

e. 32K x 16-Bit On-Chip Dual-Access RAM (DARAM) (64K Bytes)

f. 48K x 16-Bit On-Chip Single-Access RAM (SARAM) (96K Bytes)

g. Instruction Cache (24K Bytes) 250K Bytes of Shared Internal SRAM

4. Memory Traffic Controller (TC)

a. 16-Bit EMIFS Supports up to 256M Bytes of External Memory (i.e., Async.

ROM/RAM, NOR/NAND Flash, and Sync. Burst Flash)

b. 16-Bit EMIFF to Access up to 64M Bytes of SDRAM, Mobile SDRAM, or

Mobile DDR.

56

Page 57: Implementing a Gadget Driver

5. DSP Memory Management Unit.

6. DSP Peripherals.

a. Three 32-Bit Timers and Watchdog Timer.

b. Six-Channel DMA Controller.

c. Two Multichannel Buffered Serial Ports.

d. Two Multichannel Serial Interfaces.

7. MPU Peripherals.

a. Three 32-Bit Timers and Watchdog Timer.

b. USB 1.1 Host and Client Controllers.

c. USB On-the-Go (OTG) Controller.

d. 3 USB Ports, One With an Integrated Transceiver.

e. Camera Interface for Parallel CMOS Sensors.

f. Real-Time Clock (RTC).

g. Pulse-Width Tone (PWT) Interface.

h. Pulse-Width Light (PWL) Interface.

i. Keyboard Matrix Interface (6 x 5 or 8 x 8).

j. HDQ/1-Wirec Interface.

k. Multimedia Card (MMC) and Secure Digital (SD) Interface.

l. Up to 16 MPU General-Purpose I/Os.

m. 32-kHz Operating System (OS) Timer.

8. Shared Peripherals

a. 8 General-Purpose Timers.

b. Serial Port Interface (SPI).

c. Three Universal Asynchronous Receiver/Transmitters (UARTs) (Two

Supporting SIR mode for IrDA).

d. Inter-Integrated Circuit (I2C) Master and Slave Interface.

e. Multimedia Card (MMC) and Secure Digital (SD) Interface.

f. Multichannel Buffered Serial Port.

g. Up to 64 Shared General-Purpose I/Os.

h. 32-kHz Synchronous Counter.

9. Hardware Accelerators for Cryptographic Functions.

57

Page 58: Implementing a Gadget Driver

a. Random Number Generation.

b. DES and 3DES.

c. SHA-1 and MD5.

10. Individual Power-Saving Modes for MPU/DSP/TC.

11. On-Chip Scan-Based Emulation Logic.

12. IEEE Std 1149.1† (JTAG) Boundary Scan Logic.

13. Three 289-Ball BGA (Ball Grid Array).

14. Packages (ZDY and ZZG − Lead-Free; GDY − With Lead).

11.5 Detailed Description of Board:-

OMAP5912 is a highly integrated hardware and software platform, designed to meet the

application processing needs of next-generation embedded devices.

The OMAP platform enables OEMs and ODMs to quickly bring to market devices

featuring rich user interfaces, high processing performance, and long battery life through the

maximum flexibility of a fully integrated mixed processor solution.

The dual-core architecture provides benefits of both DSP and reduced instruction set

computer (RISC) technologies, incorporating a TMS320C55x DSP core and a high performance

ARM926EJ-S ARM core.

The OMAP5912 is available in three 289-ball ball grid array (BGA) packages (ZDY and

ZZG − lead-free; GDY − with lead).We are using the ZDY package.

58

Page 59: Implementing a Gadget Driver

11.6 Functional Block Diagram of OMAP 5912

Fig 11.5 Block Diagram of OMAP5912

11.7 OMAP5912 Interconnections:-

OMAP5912 consists of two processors on chip

MPU (Microprocessor Unit).

DSP (Digital Signal Processor).

OMAP5912 includes several peripherals. These peripherals are broadly divided into 3 main

categories

Shared Peripherals : shared by DSP and MPU.

Public Peripherals : DSP peripherals but accessible to MPU also.

Private Peripherals : Explicitly DSP/MPU peripherals.

59

Page 60: Implementing a Gadget Driver

The SOC also provides 4 peripheral busses

16-bit data bus (DSP private).

16-bit data bus (DSP shared).

32-bit data bus (MPU private).

32-bit data bus (MPU shared).

At the highest level OMAP supports only one BUS protocol, “TIPB” i.e. Texas Instrument

Peripheral Bus Protocol. But different peripherals connected to the OMAP may or may not

follow TIPB protocol. So in order to communicate with all peripherals OMAP implements

various Bridges and Switches interconnecting them to MPU or DSP.

11.8 Layer 4 interface/interconnect (L4 interconnect):-

L4 interface groups a set of wrappers i.e. protocol converters, dynamic switches and

static switches. They enable interface with all the peripherals, regardless of their interface

protocol with the MPU and DSP peripheral buses.

Protocols used by peripherals are

TI Peripheral Bus (TIPB protocol).

Versatile Interconnection Architecture (VIA protocol).

Open Core Protocol (OCP).

Before accessing any peripheral that is shared by MPU and DSP like ‘SPI’ we need to tell the

system which bus to use to access that peripheral, This is done by setting the particular switch

register. When set the switch can switch from DSP to MPU access. Such static switch registers

are named as follows

XXX_SSW_MPU_CONF

XXX_SSW_DSP_CONF

i.e. static switch DSP/MPU configuration register.

Each shared peripheral will have one such pair of registers. E.g. for the ‘SPI’ we have

SPI_SSW_MPU_CONF

SPI_SSW_DSP_CONF

60

Page 61: Implementing a Gadget Driver

When we want to do an MPU access the MPU_SWITCH bit in the XXX_SSW_MPU_CONF

register should be set to 1. Due to this all the MPU TIPB bus signals are connected either to the

TIPB bus peripheral signal (for TIPB peripherals) or to the dedicated wrapper TIPB bus interface

(for OCP peripherals).

To perform a DSP access to the shared peripheral, first set MPU_SWITCH in

SSW_MPU_CONF bit to 0 and then set the DSP_SWITCH in SSW_DSP_CONF to 1. So in our

case the very first step for initializing the SPI is to set the register

SPI_SSW_MPU_CONF = 0X01.

11.9 Pin out and multiplexed functions:-

The OMAP5912 has got a highly multiplexed pin out structure.

Each ball of the package can have up-to 6 functions. The function of a ball(pin) can be selected

by setting the respective FUNC_MUX_CTRL_X register.

e.g. Ball no N17 has got 5 functions

GPIO0

SPIRDY

USB.VBUS

SPIF.DOUT

MMC2.CLKIN

In order to select the SPIF.DOUT function of ball N17 we need to set the corresponding

FUNC_MUX_CTRL_X register.

.i.e. FUNC_MUX_CTRL_7 = 0X00000600

More on the registers and values to be set can be found in the

OMAP5912 Application Processor - Data Manual

61

Page 62: Implementing a Gadget Driver

CHAPTER 12

USB BASICS

62

Page 63: Implementing a Gadget Driver

USB BASICS

12.1 KEY FEATURES OF USB:-

FEATURES DESCRIPTION

Low Cost The USB provides a low-cost solution for attaching peripheral devices to PCs.

Hot Pluggable Device attachment is automatically detected by the USB and software

automatically configures the device for immediate use, without user intervention

Single Connector Type The USB defines a single connector used to attach any USB device. Additional

connectors can be added with USB hubs.

Low Speed, Full Speed,

and High Speed Devices

The USB 2.0 supports three device speeds: 1.5Mb/s, 12Mb/s, and 480Mb/s.

System Resource Requirement

Eliminated

USB devices, unlike their ISA, EISA, and PCI cousins,require no memory or I/O address space and need no IRQ lines.

Power Conservation USB devices automatically enter a suspend state after 3ms of no bus activity. During suspend devices can consume no

more than 500μa of current.

Support for Four Types of

Transfers

The USB defines four different transfer types to support different transfer

characteristics required by devices. Transfer types include: bulk, isochronous,

interrupt, and control transfers.

63

Page 64: Implementing a Gadget Driver

12.2 Overview of USB Host Software the Players

All USB transactions are initiated by USB software. These accesses are typically originated by a

USB device driver that wants to communicate with its device. The USB driver provides the

interface between USB device driver and the USB host controller. This software is responsible

for translating client requests into transactions that send information either to or from a target

USB device.

The primary hardware and software elements associated with a USB solution includes:

64

Page 65: Implementing a Gadget Driver

65

Page 66: Implementing a Gadget Driver

Figure: Host Side Key Modules

66

Page 67: Implementing a Gadget Driver

USB Hardware

• USB Host Controller/Root Hub

• USB Hubs

• USB Devices

USB Software

• USB Device Drivers

• USB Driver

• Host Controller Driver

12.3 USB Client Drivers:-

USB device drivers (or client drivers) issue requests to the USB bus driver via I/O

Request Packets (IRPs). These IRPs initiate a given transfer to or from a target USB device. For

example, a USB keyboard driver must initiate an interrupt transfer by establishing an IRP and

supplying a memory buffer into which data will be returned from the USB keyboard. Note that

the client driver has no knowledge of the USB serial transfer mechanisms.

12.4 USB Bus Driver:-

The USB bus driver knows the characteristics of the USB target device and how to

communicate with the device via USB. The USB characteristics are detected by the USB driver

when it parses the device descriptors during device configuration.

For example, some devices require a specific amount of throughput during each frame,

while others may only require periodic access every nth frame.

When an IRP is received from a USB client driver, the USB driver organizes the request

into individual transactions that will be executed during a series of bus intervals called frames (to

low- and full-speed devices) and microframes (for high-speed devices). The USB driver sets up

the transactions based on its knowledge of the USB device requirements, the needs of the client

driver, and the limitations/capabilities of the USB.

Depending on the operating environment, the USB driver may be shipped with the

operating system or added as an extension via a loadable device driver.67

Page 68: Implementing a Gadget Driver

12.5 USB Host Controller Driver:-

The USB host controller driver (HCD) schedules transactions to be broadcast over the

USB. Transactions are scheduled by software (host controller driver) via a series of transaction

lists. Each list consists of pending transactions targeted for one or more of the USB devices

attached to the bus and defines the sequence of transactions to be performed during each frame

or microframe. The USB host controller fetches and executes a new list every 1ms, or 125µs.

Note that a single block transfer requested by a USB client may be performed as a series of

transactions that are scheduled and executed during consecutive µframes. The actual scheduling

depends on a variety of factors including device speed, type of transaction, transfer requirements

specified by the device, and the transaction traffic on the USB bus.

The USB host controller initiates transactions via its root hub or hubs. Each frame begins

with a start of frame (SOF) packet and is followed by the serial broadcast of all transactions

contained within the current list. For example, if one of the requested transactions is a request to

transfer data to a USB printer, the host controller would obtain the data to be sent from a

memory buffer supplied by the client software and transmit the data over the USB. The hub

portion of the controller converts the requested transactions into the low-level protocols

required by the USB.

12.6 USB Host Controller/Root Hub:-

All communication on USB originates at the host under software control. The host

hardware consists the USB host controller, which initiates transactions over the USB system, and

the root hub, which provides attachment points (or ports) for USB devices. Three USB host

controller designs have been developed:

• Universal Host Controller Interface (UHCI) -- 1.x

• Open Host Controller Interface (OHCI) -- 1.x

• Enhanced Host Controller (EHCI) -- 2.0

Each of these controllers perform the same basic job although in slightly different ways.

Appendix C and D discuss the operation of the 1.x host controllers. The EHCI specification was

under non-disclosure during the writing of this book. Check MindShare’s web site at

68

Page 69: Implementing a Gadget Driver

www.mindshare.com for a white paper on the EHCI implementation that will be developed once

the specification is released.

12.7 The Host Controller

The host controller is responsible for generating the transactions that have been scheduled

by the host software. The host controller software driver builds a linked list of data structures in

memory that defines the transactions that are scheduled to be performed during a given frame.

These data structures, called transfer descriptors, contain all of the information the host

controller needs to generate the transactions. This information includes:

• USB Device Address

• Type of Transfer

• Direction of Transfer

• Address of Device Driver’s Memory Buffer

The host controller performs writes to a target device by reading data from a memory buffer

(supplied by the USB device driver) that is to be delivered to the target device. The host

controller performs a parallel to serial conversion on the data, creates the USB transaction, and

forwards it to the root hub to send over the bus.

If a read transfer is required, the host controller builds the read transaction and sends it to

the root hub. The hub transmits the read transaction over the USB. The target device recognizes

that it is being addressed and that data is being requested. The device then transmits data back to

the root hub, which forwards the data on to the host controller. The host controller performs the

serial to parallel conversion on the data and transfers the data to the device driver’s memory

buffer.

Note that the USB root hub and target devices perform error checks during a transaction.

Errors detected are recognized by the root hub, forwarded to the host controller to be logged and

reported to the host software.

69

Page 70: Implementing a Gadget Driver

12.8 The Root Hub:-

Transactions generated by the host controller are forwarded to the root hub to be

transmitted to the USB. Consequently, every USB transaction originates at the root hub. The root

hub provides the connection points for USB devices and performs the following key operations:

• controls power to its USB ports

• enables and disables ports

• recognizes devices attached to each port

• sets and reports status events associated with each port (when polled by host software).

12.9 Device Framework (how devices present themselves to software):-

USB has been designed to promote class device driver implementations. A set of devices

that have similar attributes and services are defined as belonging to a given class of device.

These common groupings of devices have a common class driver that can accommodate all

devices within the class.

12.10 Device Descriptors:-

A device describes itself to host software via a number of standard descriptors. These

descriptors include:

• Device Descriptor — Each device has a single device descriptor containing information

about the default communications pipe that is used to configure the device, along with

general information about the device. The device descriptor also identifies the number of

possible configurations (one or more) that a device supports.

• Configuration Descriptor — A device has a configuration descriptor for each

configuration that it supports. For example, a high-power device may also support a low

power mode, resulting in a configuration descriptor for each power mode. The

configuration descriptor includes general information about the configuration and defines

the number of interfaces for the device when used in this configuration.

• Interface Descriptor — A given configuration may have one or more interfaces that it

supports. An example of a multiple interface device could be a CD-ROM, in which case

70

Page 71: Implementing a Gadget Driver

three device drivers may be used to access the different functional devices: one device

driver for the device’s mass storage interface (for storing files), one for the audio device

(for playing music CDs), and one for the video image driver (for displaying images).

Interface descriptors provide general information about this interface. They also indicate

the class of device supported by this particular interface and specify the number of

endpoint descriptors used when communicating with this interface.

• Endpoint Descriptors — A device interface contains one or more endpoint descriptors,

each of which defines a point of communication (e.g., a data register). The endpoint

descriptor contains information, such as the transfer type supported by the endpoint (i.e.,

isochronous, bulk, interrupt, or control), and the maximum transfer rate supported.

• String Descriptors — String descriptors can be defined for the overall device, for a

given configuration, and/or for each interface definition. These string descriptors describe

the configuration and interfaces in Unicode that can be displayed and read by the user.

• Class-Specific Descriptors — Some device classes require descriptors beyond the

standard descriptors defined by the USB specification. These descriptors are defined by

the relevant device class specification (not shown).

71

Page 72: Implementing a Gadget Driver

Figure: Standard Descriptors

12.11 USB Communication Flow:-

The USB provides a communication service between software on the host and its USB

function. Functions can have different communication flow requirements for different client-to-

function interactions. The USB provides better overall bus utilization by allowing the separation

of the different communication flows to a USB function. Each communication flow makes use of

some bus access to accomplish communication between client and function. Each

communication flow is terminated at an endpoint on a device. Device endpoints are used to

identify aspects of each communication flow.

72

Page 73: Implementing a Gadget Driver

A USB logical device appears to the USB system as a collection of endpoints. Endpoints

are grouped into endpoint sets that implement an interface. Interfaces are views to the function.

The USB System Software manages the device using the Default Control Pipe. Client software

manages an interface using pipe bundles (associated with an endpoint set). Client software

requests that data be moved across the USB between a buffer on the host and an endpoint on the

USB device. The Host Controller (or USB device, depending on transfer direction) packetizes

73

Page 74: Implementing a Gadget Driver

the data to move it over the USB. The Host Controller also coordinates when bus access is used

to move the packet of data over the USB.

Software on the host communicates with a logical device via a set of communication flows. The

set of communication flows are selected by the device software/hardware designer(s) to

efficiently match the communication requirements of the device to the transfer characteristics

provided by the USB.

12.12 Device Endpoints:-

An endpoint is a uniquely identifiable portion of a USB device that is the terminus of a

communication flow between the host and device. Each USB logical device is composed of a

collection of independent endpoints. Each logical device has a unique address assigned by the

system at device attachment time. Each endpoint on a device is given at design time a unique

device-determined identifier called the endpoint number. Each endpoint has a device-determined

direction of data flow. The combination of the device address, endpoint number, and direction

allows each endpoint to be uniquely referenced. Each endpoint is a simplex connection that

supports data flow in one direction: either input (from device to host) or output (from host to

74

Page 75: Implementing a Gadget Driver

device). An endpoint has characteristics that determine the type of transfer service required

between the endpoint and the client software. An endpoint describes itself by:

• Bus access frequency/latency requirement.

• Bandwidth requirement.

• Endpoint number.

• Error handling behavior requirements.

• Maximum packet size that the endpoint is capable of sending or receiving.

• The transfer type for the endpoint.

• The direction in which data is transferred between the endpoint and the host.

Endpoints other than those with endpoint number zero are in an unknown state before being

configured and may not be accessed by the host before being configured.

12.13 Endpoint Zero Requirements:-

All USB devices are required to implement a default control method that uses both the

input and output endpoints with endpoint number zero. The USB System Software uses this

default control method to initialize and generically manipulate the logical device (e.g., to

configure the logical device) as the Default Control Pipe . The Default Control Pipe provides

access to the device’s configuration information and allows generic USB status and control

access.. The endpoints with endpoint number zero are always accessible once a device is

attached, powered, and has received a bus reset.

A USB device that is capable of operating at high-speed must have a minimum level of

support for operating at full-speed. When the device is attached to a hub operating in full-speed,

the device must:

• Be able to reset successfully at full-speed.

• Respond successfully to standard requests: set_address, set_configuration,

get_descriptor for device and configuration descriptors, and return appropriate information.

The high-speed device may or may not be able to support its intended functionality when

operating at full speed.

75

Page 76: Implementing a Gadget Driver

12.14 Non-endpoint Zero Requirements:-

Functions can have additional endpoints as required for their implementation. Low-speed

functions are limited to two optional endpoints beyond the two required to implement the Default

Control Pipe. Full speed devices can have additional endpoints only limited by the protocol

definition (i.e., a maximum of 15 additional input endpoints and 15 additional output endpoints).

Endpoints other than those for the Default Control Pipe cannot be used until the device is

configured as a normal part of the device configuration process .

Pipes:-

A USB pipe is an association between an endpoint on a device and software on the host.

Pipes represent the ability to move data between software on the host via a memory buffer and

an endpoint on a device. There are two mutually exclusive pipe communication modes:

• Stream: Data moving through a pipe has no USB-defined structure.

• Message: Data moving through a pipe has some USB-defined structure.

The USB does not interpret the content of data it delivers through a pipe. Even though a message

pipe requires that data be structured according to USB definitions, the content of the data is not

interpreted by the USB.

Additionally, pipes have the following associated with them:

• A claim on USB bus access and bandwidth usage.

• A transfer type.

• The associated endpoint’s characteristics, such as directionality and maximum data payload

sizes. The data payload is the data that is carried in the data field of a data packet within a bus

transaction

The pipe that consists of the two endpoints with endpoint number zero is called the

Default Control Pipe. This pipe is always available once a device is powered and has received a

bus reset. Other pipes come into existence when a USB device is configured. The Default

Control Pipe is used by the USB System Software to determine device identification and

76

Page 77: Implementing a Gadget Driver

configuration requirements and to configure the device. The Default Control Pipe can also be

used by device-specific software after the device is configured. The USB System Universal

Serial Bus Specification Revision 2.0 Software retains “ownership” of the Default Control Pipe

and mediates use of the pipe by other client software.

A software client normally requests data transfers via I/O Request Packets (IRPs) to a

pipe and then either waits or is notified when they are completed. Details about IRPs are defined

in an operating system specific manner. This specification uses the term to simply refer to an

identifiable request by a software client to move data between itself (on the host) and an endpoint

of a device in an appropriate direction. A software client can cause a pipe to return all

outstanding IRPs if it desires. The software client is notified that an IRP has completed when the

bus transactions associated with it have completed either successfully or due to errors.

If there are no IRPs pending or in progress for a pipe, the pipe is idle and the Host

Controller will take no action with regard to the pipe; i.e., the endpoint for such a pipe will not

see any bus transactions directed to it. The only time bus activity is present for a pipe is when

IRPs are pending for that pipe.

If a non-isochronous pipe encounters a condition that causes it to send a STALL to the

host (refer to Chapter 8) or three bus errors are encountered on any packet of an IRP, the IRP is

aborted/retired, all outstanding IRPs are also retired, and no further IRPs are accepted until the

software client recovers from the condition (in an implementation-dependent way) and

acknowledges the halt or error condition via a USBD call. An appropriate status informs the

software client of the specific IRP result for error versus halt .

An IRP may require multiple data payloads to move the client data over the bus. The data

payloads for such a multiple data payload IRP are expected to be of the maximum packet size

until the last data payload that contains the remainder of the overall IRP. See the description of

each transfer type for more details. For such an IRP, short packets (i.e., less than maximum-sized

data payloads) on input that do not completely fill an IRP data buffer can have one of two

possible meanings, depending upon the expectations of a client:

77

Page 78: Implementing a Gadget Driver

• A client can expect a variable-sized amount of data in an IRP. In this case, a short

packet that does not fill an IRP data buffer can be used simply as an in-band delimiter to indicate

“end of unit of data.” The IRP should be retired without error and the Host Controller should

advance to the next IRP.

• A client can expect a specific-sized amount of data. In this case, a short packet that does

not fill an IRP data buffer is an indication of an error. The IRP should be retired, the pipe should

be stalled, and any pending IRPs associated with the pipe should also be retired.

Because the Host Controller must behave differently in the two cases and cannot know on

its own which way to behave for a given IRP; it is possible to indicate per IRP which behavior

the client desires. An endpoint can inform the host that it is busy by responding with NAK.

NAKs are not used as a retire condition for returning an IRP to a software client. Any number of

NAKs can be encountered during the processing of a given IRP. A NAK response to a

transaction does not constitute an error and is not counted as one of the three errors described

above.

Stream Pipes

Stream pipes deliver data in the data packet portion of bus transactions with no USB-

required structure on the data content. Data flows in at one end of a stream pipe and out the other

end in the same order. Stream pipes are always uni-directional in their communication flow.

Data flowing through a stream pipe is expected to interact with what the USB believes is

a single client. The USB System Software is not required to provide synchronization between

multiple clients that may be using the same stream pipe. Data presented to a stream pipe is

moved through the pipe in sequential order: first-in, first-out.

A stream pipe to a device is bound to a single device endpoint number in the appropriate

direction (i.e. corresponding to an IN or OUT token as defined by the protocol layer). The device

endpoint number for the opposite direction can be used for some other stream pipe to the device.

Universal Serial Bus Specification Revision 2.0 Stream pipes support bulk, isochronous, and

interrupt transfer types, which are explained in later sections.

78

Page 79: Implementing a Gadget Driver

Message Pipes

Message pipes interact with the endpoint in a different manner than stream pipes. First, a

request is sent to the USB device from the host. This request is followed by data transfer(s) in the

appropriate direction. Finally, a Status stage follows at some later time. In order to accommodate

the request/data/status paradigm, message pipes impose a structure on the communication flow

that allows commands to be reliably identified and communicated. Message pipes allow

communication flow in both directions, although the communication flow may be predominately

one way. The Default Control Pipe is always a message pipe.

The USB System Software ensures that multiple requests are not sent to a message pipe

concurrently. A device is required to service only a single message request at a time per message

pipe. Multiple software clients on the host can make requests via the Default Control Pipe, but

they are sent to the device in a firstin, first-out order. A device can control the flow of

information during the Data and Status stages based on its ability to respond to the host

transactions (refer to Chapter 8 for more details).

A message pipe will not normally be sent the next message from the host until the current

message’s processing at the device has been completed. However, there are error conditions

whereby a message transfer can be aborted by the host and the message pipe can be sent a new

message transfer prematurely (from the device’s perspective). From the perspective of the

software manipulating a message pipe, an error on some part of an IRP retires the current IRP

and all queued IRPs. The software client that requested the IRP is notified of the IRP completion

with an appropriate error indication.

A message pipe to a device requires a single device endpoint number in both directions

(IN and OUT tokens). The USB does not allow a message pipe to be associated with different

endpoint numbers for each direction.

Frames and Microframes:-

USB establishes a 1 millisecond time base called a frame on a full-/low-speed bus and a

125 μs time base called a microframe on a high-speed bus. A (micro)frame can contain several

79

Page 80: Implementing a Gadget Driver

transactions. Each transfer type defines what transactions are allowed within a (micro)frame for

an endpoint. Isochronous and interrupt endpoints are given opportunities to the bus every N

(micro)frames.

Transfer Types:-

The USB transports data through a pipe between a memory buffer associated with a

software client on the host and an endpoint on the USB device. Data transported by message

pipes is carried in a USB-defined structure, but the USB allows device-specific structured data to

be transported within the USB-defined message data payload. The USB also defines that data

moved over the bus is packetized for any pipe(stream or message), but ultimately the formatting

and interpretation of the data transported in the data payload of a bus transaction is the

responsibility of the client software and function using the pipe. However, the USB provides

different transfer types that are optimized to more closely match the service requirements of the

client software and function using the pipe. An IRP uses one or more bus transactions to move

information between a software client and its function.

Each transfer type determines various characteristics of the communication flow

including the following:

• Data format imposed by the USB.

• Direction of communication flow.

• Packet size constraints.

• Required data sequences.

• Error handling.

•Bus access constraints.

• Latency constraints

The designers of a USB device choose the capabilities for the device’s endpoints. When a

pipe is established for an endpoint, most of the pipe’s transfer characteristics are determined and

remain fixed for the lifetime of the pipe. Transfer characteristics that can be modified are

described for each transfer type.

80

Page 81: Implementing a Gadget Driver

The USB defines four transfer types:

• Control Transfers: Bursty, non-periodic, host software-initiated request/response

communication, typically used for command/status operations.

• Isochronous Transfers: Periodic, continuous communication between host and device, typically

used for time-relevant information. This transfer type also preserves the concept of time

encapsulated in the data. This does not imply, however, that the delivery needs of such data is

always time-critical.

• Interrupt Transfers: Low-frequency, bounded-latency communication.

• Bulk Transfers: Non-periodic, large-packet bursty communication, typically used for data that

can use any available bandwidth and can also be delayed until bandwidth is available.

81

Page 82: Implementing a Gadget Driver

CHAPTER 13

DEVICE ENUMERATION

82

Page 83: Implementing a Gadget Driver

DEVICE ENUMERATION

13.1Configuration Management:-

Host software must support automatic configuration of USB devices. The actual software

elements involved in configuration and the sequence of steps taken to perform the configuration

vary. Configuration begins with the root hub and proceeds one port at a time until all devices

have been detected and configured.

Configuration activities rely on access to the default control endpoint within each device.

The USBD initializes the default control pipe before configuration begins. This pipe is used

repeatedly during the configuration process. The actual software components involved in

configuration vary depending on the implementation; however, conceptually the components

involved can be thought of as the:

• hub client driver

• configuration software

• USBD

13.2 Summary of Configuration Process:-

Prior to configuring a device, the hub to which the device is attached must have already

been configured and power must be applied to the port. Next, the hub and configuration software

must detect the connected device:

• The hub recognizes that a device has been attached by monitoring the D and D+ port signals.

• The hub sets status information for the port indicating device connect and speed.

• Configuration software reads port status and recognizes that a full-speed device is connected.

• Software then enables the port so that the hub will pass bus traffic to the device.

• Configuration software then issues a Reset Port request, forcing the device into its default state.

In the default state the device is un configured and responds only to accesses targeted for device

zero and endpoint zero. Configuration software can now begin the device configuration process.

This process is similar to that used when configuring a hub.

83

Page 84: Implementing a Gadget Driver

• Host queries device’s control endpoint (zero) at address zero to determine maximum payload

supported by the default pipe.

• Host assigns unique address to USB device.

• Host reads and evaluates configuration information from descriptors.

• Host verifies that the USB resources needed by the device are available.

• Host issues a configuration value to USB device specifying how it’s to be used. When the

configuration value is received, the device assumes its described characteristics. Device is now

ready to be accessed by client software and can draw the amount of Vbus power described in the

configuration.

13.3 USB Elements Requiring Configuration:-

USB configuration involves configuring three distinct elements:

• Device Configuration — Device configuration involves accessing the device’s descriptors,

determining the USB resources required by the device (i.e., power and bus bandwidth),

allocating these resources by establishing communications pipes for each endpoint, and assigning

the configuration value for the selected configuration.

• USB Configuration — The communications pipes established during device configuration

cannot be used until the pipes are initialized by the device driver using the pipes. During

initialization, the device driver must set the policy for the pipe. Setting the policy means defining

how the pipe is to be used by the device driver. For example, the service interval must be

established, as well as the maximum data transfer used by the client, etc. Once the policy for a

pipe is set, it is ready to be used.

• Function Configuration — The device driver for a given USB device may have additional

configuration to complete that the USB software is completely unaware of. This configuration is

typically related to a particular device class or might be part of a vendor-specific device and

driver. Once a configuration has been established, the USBD permits modification of the

configuration by adjusting settings associated with a given interface, or by selecting an entirely

different configuration.

84

Page 85: Implementing a Gadget Driver

13.4 Allocating USB Resources:-

Host software must be able to determine if a device just attached to the USB can operate

based on the available USB resources. Host software tracks two USB resources:

• Power

• Bus Bandwidth

It is the responsibility of software to ensure that the device has the necessary

resources prior to configuring it for operation.

13.5 Verifying Power

Some devices may require more USB bus power than is available at a given port. This can occur

when a high powered device is attached to a bus powered hub port. By reading a hub’s standard

descriptors, configuration software can determine the amount of power that is available at a

given USB port (minimum current allowed is 100ma). Software can also determine the amount

of current required by a device that is attached to a port by reading its descriptors. Note that

descriptors can be read because a device cannot draw more than the 100ma of current (the

guaranteed amount of current available). If the device requires more current than the port can

supply, then software must not configure the device and should report power shortage to the

user.

85

Page 86: Implementing a Gadget Driver

Standard Device Requests

Table: Format of Data Payload during Setup Transactions

86

Page 87: Implementing a Gadget Driver

87

Page 88: Implementing a Gadget Driver

CHAPTER 14

GADGET DRIVER

88

Page 89: Implementing a Gadget Driver

GADGET DRIVER

14.1 Structure of Gadget Drivers:-

A system running inside a USB peripheral normally has at least three layers inside the

kernel to handle USB protocol processing, and may have additional layers in user space code.

The "gadget" API is used by the middle layer to interact with the lowest level (which directly

handles hardware).

In Linux, from the bottom up, these layers are:

14.1.1 USB Controller Driver:-

This is the lowest software level. It is the only layer that talks to hardware, through

registers, fifos,dma, irqs, and the like. The <linux/usb/gadget.h> API abstracts the peripheral

controller endpoint hardware. That hardware is exposed through endpoint objects, which accept

streams of IN/OUT buffers, and through callbacks that interact with gadget drivers. Since normal

USB devices only have one upstream port, they only have one of these drivers. The controller

driver can support any number of different gadget drivers, but only one of them can be used at a

time.

14.1.2 Gadget Driver:-

The lower boundary of this driver implements hardware-neutral USB functions, using

calls to the controller driver. Because such hardware varies widely in capabilities and

restrictions, and is used in embedded environments where space is at a premium, the gadget

driver is often configured at compile time to work with endpoint supported by one particular

controller. Gadget drivers may be portable to several different controllers, using conditional

compilation. (Recent kernels substantially simplify the work involved in supporting new

hardware, by autoconfiguring endpoints automatically for many bulk oriented drivers.)

89

Page 90: Implementing a Gadget Driver

Gadget driver responsibilities include:-

1 .Handling setup requests (ep0 protocol responses) possibly including class-specific

functionality

2. Returning configuration and string descriptors

3. (re)setting configurations and interface altsettings, including enabling and configuring

endpoints

4. Handling life cycle events, such as managing bindings to hardware, USB

suspend/resume, remote wakeup, and disconnection from the USB host.

5. Managing IN and OUT transfers on all currently enabled endpoints

14.1.3 Upper Level:-

Most gadget drivers have an upper boundary that connects to some Linux driver or

framework in Linux. Through that boundary flows the data which the gadget driver produces

and/or consumes through protocol transfers over USB. Examples include:

1. User mode code, using generic (gadgetfs) or application specific files in /dev

2. Networking subsystem (for network gadgets, like the CDC Ethernet Model gadget

driver)

3. Data capture drivers, perhaps video4Linux or a scanner driver; or test and

measurement hardware.

4. Input subsystem (for HID gadgets)

5. Sound subsystem (for audio gadgets)

6. File system (for PTP gadgets)

7. Block i/o subsystem (for usb-storage gadgets)

8. ... and more

90

Page 91: Implementing a Gadget Driver

14.2 Driver Life Cycle:-

Gadget drivers make endpoint I/O requests to hardware without needing to know many

details of the hardware, but driver setup/configuration code needs to handle some differences.

Use the API like this:

1. Register a driver for the particular device side usb controller hardware, such as the

net2280 on PCI (USB 2.0), sa11x0 or pxa25x as found in Linux PDAs, and so on. At this

point the device is logically in the USB ch9 initial state ("attached"), drawing no power

and not usable (since it does not yet support enumeration). Any host should not see the

device, since it's not activated the data line pullup used by the host to detect a device,

even if VBUS power is available.

2. Register a gadget driver that implements some higher level device function. That will

then bind() to a usb_gadget, which activates the data line pullup sometime after detecting

VBUS.

3. The hardware driver can now start enumerating. The steps it handles are to accept USB

power and set_address requests. Other steps are handled by the gadget driver. If the

gadget driver module is unloaded before the host starts to enumerate, steps before step 7

are skipped.

4. The gadget driver's setup() call returns usb descriptors, based both on what the bus

interface hardware provides and on the functionality being implemented. That can

involve alternate settings or configurations, unless the hardware prevents such operation

5. The gadget driver handles the last step of enumeration, when the USB host issues a

set_configuration call. It enables all endpoints used in that configuration, with all

interfaces in their default settings. That involves using a list of the hardware's endpoints,

enabling each endpoint according to its descriptor. It may also involve using

usb_gadget_vbus_draw to let more power be drawn from VBUS, as allowed by that

configuration. For OTG devices, setting a configuration may also involve reporting HNP

capabilities through a user interface.

6. . Do real work and perform data transfers, possibly involving changes to interface

settings or switching to new configurations, until the device is disconnect()ed from the

host. Queue any number of transfer requests to each endpoint. It may be suspended and

91

Page 92: Implementing a Gadget Driver

resumed several times before being disconnected. On disconnect, the drivers go back to

step 3 (above).

7. When the gadget driver module is being unloaded, the driver unbind() callback is issued.

That lets the controller driver be unloaded. Drivers will normally be arranged so that just

loading the gadget driver module (or statically linking it into a Linux kernel) allows the

peripheral device to be enumerated, but some drivers will defer enumeration until some

higher level component (like a user mode daemon) enables it. Note that at this lowest

level there are no policies about how ep0 configuration logic is implemented, except that

it should obey USB specifications.

Such issues are in the domain of gadget drivers, including knowing about implementation

constraints imposed by some USB controllers or understanding that composite devices might

happen to be built by integrating reusable components.

92

Page 93: Implementing a Gadget Driver

14.3 Design Description (Refer to Figure)

1. The User Application issues a read call to get the RTC reading.

(2-3-4-5). This Call made by the User Application travels all the way through System Call

Interface Layer and Virtual File System and finally reaches our USB Device Driver (Client

Driver) .This results in a call back to the read function defined in our driver.

6. In the read function we then create a URB that will act as a box to carry our message (control

request) to the target device (OMAP 5912). In the control request we set bRequest to 0xAB

(type vendor specific).

7. We then submit the URB created in step 6 to the USB core to complete it. Note that once the

USB core and lower layers successfully complete the URB there will be a callback made to

URB complete routine.

(8-9-10-11-12-13). The URB travels through the lower layer and finally reaches the gadget side.

At this point it is identified as a control request and a call back to the setup function of our

gadget driver is made.

14. In the setup function we get the reading from the previously initialized and running RTC and

place it a buffer in memory. We the use a USB_Request (Similar to URB but used on gadget

side) to send that data back to the host.

15. We queue our request to the endpoint 0 to be processed…here once again we have complete

function that is called back once the URB_request is processed.

(16-17-18-19-20-21). Once the URB is complete then callback is made to the URB complete

function that returns the data to the user application….

93

Page 94: Implementing a Gadget Driver

94

Page 95: Implementing a Gadget Driver

CHAPTER 15

CONCLUSION

CONCLUSION

95

Page 96: Implementing a Gadget Driver

The project covers whole life cycle of the Universal Serial BUS (USB) and gives us host

and device side perspective of the technology.

Milestones of the project:-

1. Porting: Gadget Driver was constructed on Embedded Linux platform which involved

porting to the target hardware(OMAP 5912 OSK)using GNU tool chain.

2. Gadget Driver Development: This phase involved implementing the Gadget driver

which handled request right from introducing gadget and its capabilities to host to exporting a

specific device functionality.

3. USB Device Driver Development: This phase involved development of the USB

device driver(client driver) on the host side that adhered to request from user application.

Experience:

It was a team work that led to the successful completion of the project. We got hands on

experience in interacting with USB subsystem on host side, Gadget APIs on the device side and

porting the OS.

96

Page 97: Implementing a Gadget Driver

CHAPTER 16

REFERNCES

97

Page 98: Implementing a Gadget Driver

REFRENCES

Linux Device Drivers : Jonathan Corbet, Alessandro Rubini, & Greg Kroah-Hartman

Linux Kernel Development : Robert Love

Building Embedded Linux System 2nd edition - Karim Yaghmour

Embedded Linux Primer -Christopher Hallinan

Kernel Source Documentation

OSK 5912 Newbie Guide - Matthew Percival

http://www.denx.de for U-BOOT

http://www.tldp.org for Linux Documentation

http://www.-muru.com/linux/omap/

http://sourceforge.net/projects/uboot/

http://freeelectrons.com/docs/

http://linux.omap.com for OMAP related Documentation

USB System Architecture (USB 2.0): Don Anderson

USB complete: Jan Axelson

http://tali.admingilde.org/linux-docbook/gadget/index.html

98